问:
Sort table not sorting input
How can I sort the following table I used var rows = $('#mytable tbody tr').get(); should I also include the div and the span and input inorder for it to work? The sort is not working

HTML

```<code><table id="mytable" class="table">
            <thead>
                <tr>
                    <th id="employee" class="col-xs-2">Employee</th>
                    <th id="basic_pay" style="color:#337ab7;">basic pay</th>
                    <th id="tax" style="color:#337ab7;">tax</th>
                    <th id="loans" style="color:#337ab7;">loans</th>
                </tr>
            </thead>
            <tbody>
                <% @pay_list.each do |a| %>
                    <tr>
                        <td><%= a.user.profile.full_name %></td>
                        <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="12000.0" class="form-control
                                 currency" id="display_basic_pay_4">
                            </div>
                            <input type="hidden" id="child_num_<%= a.id %>" value="<%= a.user.profile.num_of_children%>" />
                        </td>
                            <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="12000.0" class="form-control
                                 currency" id="display_basic_pay_4">
                            </div></td>
                        <% end %>
                    </tr>
                <% end %>
            </tbody>
        </table>
</code>```

Javascript

```<code><script>
function sortTable(f,n){
    var rows = $('#mytable tbody tr').get();
    rows.sort(function(a, b) {
        var A = getVal(a);
        var B = getVal(b);
        if(A < B) {
            return -1*f;
        }
        if(A > B) {
            return 1*f;
        }
        return 0;
    });
    function getVal(elm){
        var v = $(elm).children('td').eq(n).text().toUpperCase();
        if($.isNumeric(v)){
            v = parseInt(v,10);
        }
        return v;
    }
    $.each(rows, function(index, row) {
        $('#mytable').children('tbody').append(row);
    });
}

var f_basic_pay = 1;
var f_tax = 1;
$("#basic_pay").click(function(){
    f_basic_pay *= -1;
    var n = $(this).prevAll().length;
    sortTable(f_basic_pay,n);
});
$("#tax").click(function(){
    f_tax *= -1;
    var n = $(this).prevAll().length;
    sortTable(f_tax,n);
});
</code>```

Used rails for the <% values %>

答:
I added a css class to the input fields in your cells and updated your getVal() method to retrieve this value for comparison. Check below snippet:

function sortTable(f,n){
    var rows = $('#mytable tbody tr').get();

    rows.sort(function(a, b) {
        var A = getVal(a);
        var B = getVal(b);

        if(A  B) {
            return 1*f;
        }
        return 0;
    });
    function getVal(elm){
        var element = $(elm).children('td').get(n);

        var v = $(".sort_val",element).val()
        if($.isNumeric(v)){
            v = parseInt(v,10);
        }

        return v;
    }
    $.each(rows, function(index, row) {
        $('#mytable').children('tbody').append(row);
    });
}

var f_basic_pay = 1;
var f_tax = 1;
$("#basic_pay").click(function(){
    f_basic_pay *= -1;
    var n = $(this).prevAll().length;

    sortTable(f_basic_pay,n);
});
$("#tax").click(function(){
    f_tax *= -1;
    var n = $(this).prevAll().length;
    sortTable(f_tax,n);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable" class="table">
            <thead>
                <tr>
                    <th id="employee" class="col-xs-2">Employee</th>
                    <th id="basic_pay" style="color:#337ab7;">basic pay</th>
                    <th id="tax" style="color:#337ab7;">tax</th>
                    <th id="sss" style="color:#337ab7;">sss</th>
                    <th id="hdmf" style="color:#337ab7;">hdmf</th>
                    <th id="phil_health" style="color:#337ab7;">phil_health</th>
                </tr>
            </thead>
            <tbody>

                    <tr>
                        <td>  User 1 </td>
                        <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="14000.0" class="form-control
                                 currency sort_val" id="display_basic_pay_14">
                            </div>
                            <input type="hidden" id="child_num_14" value="14" />
                        </td>
                            <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="14000.0" class="form-control
                                 currency sort_val" id="display_basic_pay_4">
                            </div></td>

                    </tr>
                     <tr>
                        <td>  User 2 </td>
                        <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="12000.0" class="form-control
                                 currency sort_val" id="display_basic_pay_4">
                            </div>
                            <input type="hidden" id="child_num_12" value="12" />
                        </td>
                            <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="12000.0" class="form-control
                                 currency sort_val" id="display_basic_pay_4">
                            </div></td>

                    </tr>
                     <tr>
                        <td>  User 3 </td>
                        <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="15000.0" class="form-control
                                 currency sort_val" id="display_basic_pay_4">
                            </div>
                            <input type="hidden" id="child_num_15" value="15" />
                        </td>
                            <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="15000.0" class="form-control
                                 currency sort_val" id="display_basic_pay_4">
                            </div></td>

                    </tr>

            </tbody>
        </table></code>```

Title: Sort table not sorting input

Body:
How can I sort the following table I used var rows = $('#mytable tbody tr').get(); should I also include the div and the span and input inorder for it to work? The sort is not working

HTML

                    Employee
                    basic pay
                    tax
                    loans

                <% @pay_list.each do |a| %>

                        <%= a.user.profile.full_name %>

                                ₱
                                <input value="12000.0" class="form-control
                                 currency" id="display_basic_pay_4">

                            <input type="hidden" id="child_num_<%= a.id %>" value="<%= a.user.profile.num_of_children%>" />

                                ₱
                                <input value="12000.0" class="form-control
                                 currency" id="display_basic_pay_4">

                        <% end %>

                <% end %>

Javascript

Body:
I added a css class to the input fields in your cells and updated your getVal() method to retrieve this value for comparison. Check below snippet:

function sortTable(f,n){
    var rows = $('#mytable tbody tr').get();

    rows.sort(function(a, b) {
        var A = getVal(a);
        var B = getVal(b);

        if(A < B) {
            return -1*f;
        }
        if(A > B) {
            return 1*f;
        }
        return 0;
    });
    function getVal(elm){
        var element = $(elm).children('td').get(n);

        var v = $(".sort_val",element).val()
        if($.isNumeric(v)){
            v = parseInt(v,10);
        }

        return v;
    }
    $.each(rows, function(index, row) {
        $('#mytable').children('tbody').append(row);
    });
}

var f_basic_pay = 1;
var f_tax = 1;
$("#basic_pay").click(function(){
    f_basic_pay *= -1;
    var n = $(this).prevAll().length;

    sortTable(f_basic_pay,n);
});
$("#tax").click(function(){
    f_tax *= -1;
    var n = $(this).prevAll().length;
    sortTable(f_tax,n);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable" class="table">
            <thead>
                <tr>
                    <th id="employee" class="col-xs-2">Employee</th>
                    <th id="basic_pay" style="color:#337ab7;">basic pay</th>
                    <th id="tax" style="color:#337ab7;">tax</th>
                    <th id="sss" style="color:#337ab7;">sss</th>
                    <th id="hdmf" style="color:#337ab7;">hdmf</th>
                    <th id="phil_health" style="color:#337ab7;">phil_health</th>
                </tr>
            </thead>
            <tbody>

                    <tr>
                        <td>  User 1 </td>
                        <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="14000.0" class="form-control
                                 currency sort_val" id="display_basic_pay_14">
                            </div>
                            <input type="hidden" id="child_num_14" value="14" />
                        </td>
                            <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="14000.0" class="form-control
                                 currency sort_val" id="display_basic_pay_4">
                            </div></td>

                    </tr>
                     <tr>
                        <td>  User 2 </td>
                        <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="12000.0" class="form-control
                                 currency sort_val" id="display_basic_pay_4">
                            </div>
                            <input type="hidden" id="child_num_12" value="12" />
                        </td>
                            <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="12000.0" class="form-control
                                 currency sort_val" id="display_basic_pay_4">
                            </div></td>

                    </tr>
                     <tr>
                        <td>  User 3 </td>
                        <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="15000.0" class="form-control
                                 currency sort_val" id="display_basic_pay_4">
                            </div>
                            <input type="hidden" id="child_num_15" value="15" />
                        </td>
                            <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="15000.0" class="form-control
                                 currency sort_val" id="display_basic_pay_4">
                            </div></td>

                    </tr>

            </tbody>
        </table>


来源: stackexchange

问:
number of substring which are whose anagrams are palindrome
Given a string of digits, count the number of subwords (consistent subsequences) that are anagrams of any palindrome.

My attempt in Python:

```<code>def ispalin(s):
    if len(s)%2==0:
        for i in s:
            if s.count(i)%2!=0:
                return False
    else:
        sum =0
        for i in set(s):
            if s.count(i)%2==1:
                sum = sum+1
        if sum == 1:
            return True
        else:
            return False

    return True

def solution(S):
    # write your code in Python 3.6
    count=len(S)
    for i in range(len(S)):
        for j in range(i+1,len(S)):
            if ispalin(S[i:j+1]):
                count=count+1

    return count
</code>```

i/o format

```<code>For example, given:

    S = "02002"
the function should return 11.
these are 11 substrings whose anagrams are palindrome
"0", "2", "0", "0", "2", "00", "020", "200", "002", "2002", "02002"
</code>```

It is giving time limit exceeded for big strings. How can I optimize the above code?

 i bet there exists a better solution than this here is the proof
[image][1]

https://i.stack.imgur.com/7x3Jq.png

答:
You can get quadratic complexity using O(n) of memory.

Make array[0..9] of digit counters (or use another data structure convenient for Python)

Walk through the string, increment counter for current digit and add modified array to the list. After that list will contain "cumulative sums" - counts for every digit upto every index (for example, five 2's before 40-th string entry)

Now to get count for digit between i-th and j-th entries, just subtract C[j][digit] - C[i][digit]

Interesting question - does better complexity solution exist?

ContentLicense: CC BY-SA 3.0

Body:
Given a string of digits, count the number of subwords (consistent subsequences) that are anagrams of any palindrome.

My attempt in Python:

def ispalin(s):
    if len(s)%2==0:
        for i in s:
            if s.count(i)%2!=0:
                return False
    else:
        sum =0
        for i in set(s):
            if s.count(i)%2==1:
                sum = sum+1
        if sum == 1:
            return True
        else:
            return False

    return True

def solution(S):
    # write your code in Python 3.6
    count=len(S)
    for i in range(len(S)):
        for j in range(i+1,len(S)):
            if ispalin(S[i:j+1]):
                count=count+1

    return count

i/o format

For example, given:

    S = "02002"
the function should return 11.
these are 11 substrings whose anagrams are palindrome
"0", "2", "0", "0", "2", "00", "020", "200", "002", "2002", "02002"

It is giving time limit exceeded for big strings. How can I optimize the above code?

 i bet there exists a better solution than this here is the proof
[image][1]

https://i.stack.imgur.com/7x3Jq.png


问:
How to make NSButton in macOS app has a highlighted border?
I want to give NSButton a highlighted border to guide user to click it. I expect it to be similar to the effect of using becomeFirstResponder() on NSTextField as below.

I tried to use becomeFirstResponder() on NSButton, but there is no UI change.

I also tried to use button.highlight(true), but it highlights the whole button, which is kind of confusing as it is being clicked.

What should I do? Thank you.

答:
As commentators have pointed out doing what you propose is unwise as it would conflict with full keyboard access, which some of your users could have enabled.

There is already a macOS convention to highlight the "default" button in some way – this formerly added a ring around the button, currently it draws the button in a different colour. The default button will be triggered when the user presses the return key (whereas in full keyboard access the space key is the trigger).

You can dynamically set and change the default button using NSWindow's defaultButtonCell property. Note this takes an NSButtonCell, not an NSButton, you get the former from the latter using the cell property. So your code to set the default would look something like:

```<code>myWindow.defaultButtonCell = oneOfMyButtons.cell;
</code>```

Following the standard macOS GUI here both indicates to the user the most common button to press and allows them to trigger it from the keyboard using the return key.

HTH

Body:
As commentators have pointed out doing what you propose is unwise as it would conflict with full keyboard access, which some of your users could have enabled.

There is already a macOS convention to highlight the "default" button in some way – this formerly added a ring around the button, currently it draws the button in a different colour. The default button will be triggered when the user presses the return key (whereas in full keyboard access the space key is the trigger).

You can dynamically set and change the default button using NSWindow's defaultButtonCell property. Note this takes an NSButtonCell, not an NSButton, you get the former from the latter using the cell property. So your code to set the default would look something like:

myWindow.defaultButtonCell = oneOfMyButtons.cell;

Following the standard macOS GUI here both indicates to the user the most common button to press and allows them to trigger it from the keyboard using the return key.

HTH


问:
Last child not removing border bottom
HTML:

```<code><div class="offer-section">
    <div class="divider"></div>
</div>
<div class="offer-section">
    <div class="divider"></div>
</div>
<div class="offer-section">
    <div class="divider"></div>
</div>
<div class="offer-section">
    <div class="divider"></div>
</div>
</code>```

CSS:

```<code>.offer-section{
   .divider { border: solid 1px #bdbdc3; height: 2px; margin-top: 5%; }
}
.offer-section:last-child {
   .divider { }
}
</code>```

Trying to add a divider to the bottom of every offer-section div except the last one. However the code above does not seem to be able to do the job. Would appreciate any help :)

答:
```<code>.offer-section .divider {
    border: solid 1px #bdbdc3; height: 20px; margin-top: 5%;
}
.offer-section:nth-child(4) .divider{
    border-bottom: none;
}
</code>```

Title: Last child not removing border bottom

Body:
HTML:

CSS:

.offer-section{
   .divider { border: solid 1px #bdbdc3; height: 2px; margin-top: 5%; }
}
.offer-section:last-child {
   .divider { }
}

Trying to add a divider to the bottom of every offer-section div except the last one. However the code above does not seem to be able to do the job. Would appreciate any help :)


问:
Hex addition in C++
I want to add an array in Hex. I have done this but I am facing problems in the addition function; it is not adding but showing some pictures.

```<code>void addition(char hexDecOne[10], char hexDecTwo[10], char (&hexDecSum)[10]) {
    for (int i = 0; i < 10; i++) {
        // convert to decimal and add both array values
        hexDecSum[i] = convert(hexDecOne[i]) + convert(hexDecTwo[i]);
        // add values and if they are greater than F add 1 to next value
        hexDecSum[i + 1] += hexDecSum[i] / 16;
        hexDecSum[i] %= 16;
    }
}

int convert(char item) {
    switch (item) {
        case 'A':
            return 10;
            break;
        case 'B':
            return 11;
            break;
        case 'C':
            return 12;
            break;
        case 'D':
            return 13;
            break;
        case 'E':
            return 14;
            break;
        case 'F':
            return 15;
            break;
    }
}
</code>```

Any help will be appreciated.

答:
For large hex number, here is an example:

```<code>#include <iostream>
#include <string>

using namespace std;

string plus_hex(string hex1, string hex2)
{
    if (hex1.length() < hex2.length())
        hex1.swap(hex2);

    //for convenience, make sure that hex1 is longer.

    /*Strat algorithm*/

    int length1, length2;
    length1 = hex1.length();
    length2 = hex2.length();
    int flag = 0; // carry
    int get1, get2;
    int sum;

    while (length1>0)
    {
        //get first number
        if (hex1[length1 - 1] >= 'A')
            get1 = hex1[length1 - 1] - 55;
        else
            get1 = hex1[length1 - 1] - '0';

        //get second number

        if (length2 > 0)
        {
            if (hex2[length2 - 1] >= 'A')
                get2 = hex2[length2 - 1] - 55;
            else
                get2 = hex2[length2 - 1] - '0';
        }
        else
            get2 = 0;

        //get the sum
        sum = get1 + get2 + flag;

        if (sum >= 16)
        {
            int left = sum % 16;
            if (left >= 10)
                hex1[length1 - 1] = 'A' + left % 10;
            else
                hex1[length1 - 1] = '0' + left;
            flag = 1;
        }
        else
        {
            if (sum >= 10)
                hex1[length1 - 1] = 'A' + sum % 10;
            else
                hex1[length1 - 1] = '0' + sum;
            flag = 0;
        }

        length1--;
        length2--;
    }

    if (flag == 1)
        return "1" + hex1;
    else
        return hex1;

    /*End of algorithm*/
}
int main(void)
{
    string hex1, hex2;

    while (cin >> hex1 >> hex2)
        cout << plus_hex(hex1, hex2);

    return 0;
}
</code>```

Example:

```<code>For example:

FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
1
</code>```

Result:

```<code>10000000000000000000000000000000000
</code>```

Title: Hex addition in C++

Body:
I want to add an array in Hex. I have done this but I am facing problems in the addition function; it is not adding but showing some pictures.

void addition(char hexDecOne[10], char hexDecTwo[10], char (&hexDecSum)[10]) {
    for (int i = 0; i < 10; i++) {
        // convert to decimal and add both array values
        hexDecSum[i] = convert(hexDecOne[i]) + convert(hexDecTwo[i]);
        // add values and if they are greater than F add 1 to next value
        hexDecSum[i + 1] += hexDecSum[i] / 16;
        hexDecSum[i] %= 16;
    }
}

int convert(char item) {
    switch (item) {
        case 'A':
            return 10;
            break;
        case 'B':
            return 11;
            break;
        case 'C':
            return 12;
            break;
        case 'D':
            return 13;
            break;
        case 'E':
            return 14;
            break;
        case 'F':
            return 15;
            break;
    }
}

Any help will be appreciated.

Body:
For large hex number, here is an example:

#include <iostream>
#include <string>

using namespace std;

string plus_hex(string hex1, string hex2)
{
    if (hex1.length() < hex2.length())
        hex1.swap(hex2);

    //for convenience, make sure that hex1 is longer.

    /*Strat algorithm*/

    int length1, length2;
    length1 = hex1.length();
    length2 = hex2.length();
    int flag = 0; // carry
    int get1, get2;
    int sum;

    while (length1>0)
    {
        //get first number
        if (hex1[length1 - 1] >= 'A')
            get1 = hex1[length1 - 1] - 55;
        else
            get1 = hex1[length1 - 1] - '0';

        //get second number

        if (length2 > 0)
        {
            if (hex2[length2 - 1] >= 'A')
                get2 = hex2[length2 - 1] - 55;
            else
                get2 = hex2[length2 - 1] - '0';
        }
        else
            get2 = 0;

        //get the sum
        sum = get1 + get2 + flag;

        if (sum >= 16)
        {
            int left = sum % 16;
            if (left >= 10)
                hex1[length1 - 1] = 'A' + left % 10;
            else
                hex1[length1 - 1] = '0' + left;
            flag = 1;
        }
        else
        {
            if (sum >= 10)
                hex1[length1 - 1] = 'A' + sum % 10;
            else
                hex1[length1 - 1] = '0' + sum;
            flag = 0;
        }

        length1--;
        length2--;
    }

    if (flag == 1)
        return "1" + hex1;
    else
        return hex1;

    /*End of algorithm*/
}
int main(void)
{
    string hex1, hex2;

    while (cin >> hex1 >> hex2)
        cout << plus_hex(hex1, hex2);

    return 0;
}

Example:

For example:

FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
1

Result:

10000000000000000000000000000000000


问:
How to check null condition for the boolean variable
I have a class as shown

```<code>package com;

public class Person {
boolean registered;

public boolean isRegistered() {
    return registered;
}

public void setRegistered(boolean registered) {
    this.registered = registered;
}
}
</code>```

The Data to Person Object will be set based on the Data present in DB .
The problem is that for older records the registered filed is not present .

so i how can i test if the filed is present or not ??

package com;

```<code>public class Test {

    public static void main(String args[]) {
        Person per = new Person();

        if (per.isRegistered()) {

        }
    }

}
</code>```

How can i check if the per.isRegistered() field is present or not for that Person Object  ??

答:
You should use Optional</p>

```<code>if (Optional.ofNullable(per.isRegistered()).orElse(false)) {
  // ...
}
</code>```

Body:
I have a class as shown

package com;

public class Person {
boolean registered;

public boolean isRegistered() {
    return registered;
}

public void setRegistered(boolean registered) {
    this.registered = registered;
}
}

The Data to Person Object will be set based on the Data present in DB .
The problem is that for older records the registered filed is not present .

so i how can i test if the filed is present or not ??

package com;

public class Test {

    public static void main(String args[]) {
        Person per = new Person();

        if (per.isRegistered()) {

        }
    }

}

How can i check if the per.isRegistered() field is present or not for that Person Object  ??

Body:
You should use Optional

if (Optional.ofNullable(per.isRegistered()).orElse(false)) {
  // ...
}


问:
Deleting rows in excel table with office-js
I have an ajax call in my add in which it should create or update the table in excel. If table is already exists, it should remove the rows and add the new results.
When deleting the rows in loop, it is deleting some rows and then I am getting following error:

Debug info: {"code":"InvalidArgument","message":"The argument is invalid or missing or has an incorrect format.","errorLocation":"TableRowCollection.getItemAt"}

My ajax call in my excel web add-in looks like this:

```<code>$.ajax({
        //....
    }).done(function (data) {
        Excel.run(function (ctx) {
            var odataTable = ctx.workbook.tables.getItemOrNullObject("odataTable");
            //rows items are not available at this point, that is why we need to load them and sync the context
            odataTable.rows.load();

            return ctx.sync().then(function () {
                if (odataTable.rows.items == null) {
                    odataTable.delete();
                    odataTable = ctx.workbook.tables.add('B2:G2', true);
                    odataTable.name = "odataTable";
                } else {
                    console.log("Rows items:" + odataTable.rows.items.length);
                    odataTable.rows.items.forEach(function (item) {
                        console.log("Removing row item: " + item.values);
                        item.delete();
                    });
                    console.log("rows cleaned");
                }
            }).then(function () {
                //add rows to the table
                });
            }).then(ctx.sync);

        }).catch(errorHandler);

    }).fail(function (status) {
        showNotification('Error', 'Could not communicate with the server. ' + JSON.stringify(status));
    }).always(function () {
        $('#refresh-button').prop('disabled', false);
    });
</code>```

答:
The idea of the iterable collections is that they consist of different items. Once you remove something from these items in a not appropriate way, the collection stops being a collection. This is because they are implemented as a linked list, in which every unit knows only the next unit. https://en.wikipedia.org/wiki/Linked_list

In your case, you are deleting wtih a for-each loop. After the first deletion, the collection is broken. Thus, you need another approach.

Another approach:

Start looping with a normal for loop. Reversed.
E.g.:

```<code>for i = TotalRows to 1 i--
  if row(i) something then delete
</code>```

Body:
I have an ajax call in my add in which it should create or update the table in excel. If table is already exists, it should remove the rows and add the new results.
When deleting the rows in loop, it is deleting some rows and then I am getting following error:

Debug info: {"code":"InvalidArgument","message":"The argument is invalid or missing or has an incorrect format.","errorLocation":"TableRowCollection.getItemAt"}

My ajax call in my excel web add-in looks like this:

$.ajax({
        //....
    }).done(function (data) {
        Excel.run(function (ctx) {
            var odataTable = ctx.workbook.tables.getItemOrNullObject("odataTable");
            //rows items are not available at this point, that is why we need to load them and sync the context
            odataTable.rows.load();

            return ctx.sync().then(function () {
                if (odataTable.rows.items == null) {
                    odataTable.delete();
                    odataTable = ctx.workbook.tables.add('B2:G2', true);
                    odataTable.name = "odataTable";
                } else {
                    console.log("Rows items:" + odataTable.rows.items.length);
                    odataTable.rows.items.forEach(function (item) {
                        console.log("Removing row item: " + item.values);
                        item.delete();
                    });
                    console.log("rows cleaned");
                }
            }).then(function () {
                //add rows to the table
                });
            }).then(ctx.sync);

        }).catch(errorHandler);

    }).fail(function (status) {
        showNotification('Error', 'Could not communicate with the server. ' + JSON.stringify(status));
    }).always(function () {
        $('#refresh-button').prop('disabled', false);
    });

Body:
The idea of the iterable collections is that they consist of different items. Once you remove something from these items in a not appropriate way, the collection stops being a collection. This is because they are implemented as a linked list, in which every unit knows only the next unit. https://en.wikipedia.org/wiki/Linked_list

In your case, you are deleting wtih a for-each loop. After the first deletion, the collection is broken. Thus, you need another approach.

Another approach:

Start looping with a normal for loop. Reversed.
E.g.:

for i = TotalRows to 1 i--
  if row(i) something then delete


问:
How to sniff all packets on python when scapy and pypcap have serious loss?
I tried to sniff packets on Win10 using python. However, i find a lot of packets are actually dropped by scapy.

For example, I download a file of 2 MB from ftp, the wiresharks captures nearly 2000 packets and the scapy only captures 500.

I have tried pypcap and the result is almost the same, more than half of the packets are dropped, especially on downloading.

Is there a solution to avoid such loss and make scapy perform the same as wireshark, or there is no library on python capable of buffering a lot of packets in short time?

答:
You can have Scapy use tcpdump (or windump under Windows) to sniff the packets for you, using for example:</p>

```<code>sniff(opened_socket=L2ListenTcpdump())
</code>```

Body:
You can have Scapy use tcpdump (or windump under Windows) to sniff the packets for you, using for example:

sniff(opened_socket=L2ListenTcpdump())


问:
How to access the parent class inside a resource
I'm trying to create a complex tooltip, where one of the TextBlocks would be bound to a property of the UserControl in which this tooltip is defined as a resource. The simplified version of the XAML code looks like this:

```<code><UserControl x:Class="WpfApplication3.TestPage"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         xmlns:pixellab="clr-namespace:PixelLab.Wpf;assembly=UIControls"
         xmlns:my="clr-namespace:WpfApplication3"
         d:DesignHeight="499" d:DesignWidth="409"
         x:Name="PageInstance" >
<UserControl.Resources>
    <Grid x:Key="Tooltip">
        <TextBlock Text="{Binding ElementName=PageInstance, Path=PageTest}"/>
    </Grid>
</UserControl.Resources>
<Border Background="Red" ToolTip="{StaticResource Tooltip}" />
</code>```

UserControl is named PageInstance. The border displayed inside has a tooltip defined as a resource. If I try to bind Text with

```<code><TextBlock Text="{Binding ElementName=PageInstance, Path=PageTest}"/>
</code>```

I get a binding error when I run the app:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=PageInstance'. BindingExpression:Path=PageTest; DataItem=null; target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

What do I have to do to successfuly bind the text to the PageTest property in PageInstance usercontrol?

Thanks for any help. I still haven't completely figured out how Bindings work.
Gregor

答:
Use RelativeSource in your binding, something like this:

```<code><TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=PageTest}"/>
</code>```

Body:
I'm trying to create a complex tooltip, where one of the TextBlocks would be bound to a property of the UserControl in which this tooltip is defined as a resource. The simplified version of the XAML code looks like this:

<UserControl x:Class="WpfApplication3.TestPage"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         xmlns:pixellab="clr-namespace:PixelLab.Wpf;assembly=UIControls"
         xmlns:my="clr-namespace:WpfApplication3"
         d:DesignHeight="499" d:DesignWidth="409"
         x:Name="PageInstance" >
<UserControl.Resources>
    <Grid x:Key="Tooltip">
        <TextBlock Text="{Binding ElementName=PageInstance, Path=PageTest}"/>
    </Grid>
</UserControl.Resources>
<Border Background="Red" ToolTip="{StaticResource Tooltip}" />

UserControl is named PageInstance. The border displayed inside has a tooltip defined as a resource. If I try to bind Text with

<TextBlock Text="{Binding ElementName=PageInstance, Path=PageTest}"/>

I get a binding error when I run the app:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=PageInstance'. BindingExpression:Path=PageTest; DataItem=null; target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

What do I have to do to successfuly bind the text to the PageTest property in PageInstance usercontrol?

Thanks for any help. I still haven't completely figured out how Bindings work.
Gregor

Body:
Use RelativeSource in your binding, something like this:

<TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=PageTest}"/>


问:
Unable to populate dropdowns in correct sequence using angular js

I have 3 dropdowns, lets say A,B,C.

When I select item from dropdown A, then dropdown B is filled, and accordingly c is also filled. (not like cascading read my question fully)

Based on the dropdown C item selection, more dropdowns will be populated. For ex. if i select option 1 from dropdown c, then 3 dropdowns will be populated, if I select option 2, then 2 dropdowns will be populated.

So, till point 2 I have achieved, but while implementing point 3, I am not able to populate dropdowns. When I select any option from  dropdown c, then entire dropdowns are getting generated.

var option1Options = ["Men", "women", "kids"];
var option2Options = [
  ["m-top", "m-bottom", "m-f0otwear"],
  ["w-top", "w-bottom", "w-footwear"],
  ["k-top", "k-bottom", "k-footwear"]
];
var option3Options = [
  ["m-Shirt", "m-t-shirt"],
  ["m-jeans", "m-trousers"],
  ["m-chapals", "m-formal shoes"],
  ["w-Shirt", "w-t-shirt"],
  ["w-jeans", "w-trousers"],
  ["w-chapals", "w-formal shoes"]

];

function myCtrl($scope) {
  $scope.opt1 = ["opt1", "opt2", "opt3"];
  $scope.opt2 = ["opt1", "opt2"];
  $scope.opt3 = ["opt1", "opt2"];
  $scope.opt4 = ["opt1", "opt2"];
  $scope.opt5 = ["opt1", "opt2"];
  $scope.opt6 = ["opt1", "opt2"];
  $scope.opt7 = ["opt1", "opt2"];
  $scope.opt8 = ["opt1", "opt2"];
  $scope.opt9 = ["opt1", "opt2"];
  $scope.opt10 = [];

  $scope.onOption3Change = function() {
    $scope.obj = {};

    $scope.selectC = $scope.options3.indexOf($scope.option3)

  }
  $scope.showDropDownOptions = [];
  $scope.showDropDownOptions[0] = [2, 3, 6];
  $scope.showDropDownOptions[1] = [1, 4];
  $scope.showDropDownOptions[2] = [5, 9, 10, 7];
  $scope.showDropDownOptions[3] = [8, 10];

  //$scope.second[0] = [1];
  $scope.obj = {};

  $scope.options1 = option1Options;
  $scope.options2 = []; // we'll get these later
  $scope.options3 = [];
  $scope.getOptions2 = function() {

    $scope.options2 = option2Options[option1Options.indexOf($scope.option1)];
    $scope.getOptions3();
  };

  $scope.getOptions3 = function() {
    var mergedOptions2 = [].concat.apply([], option2Options)
    $scope.options3 = option3Options[mergedOptions2.indexOf($scope.option2)];
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app data-ng-controller="myCtrl">
  <select data-ng-model="option1" data-ng-options="option for option in options1 " data-ng-change="getOptions2($index)">
  </select>
  <select data-ng-model="option2" data-ng-options="option for option in options2" data-ng-show='options2.length' data-ng-change="getOptions3()">
  </select>{{option2}}
  <select data-ng-model="option3" data-ng-options="option for option in options3" data-ng-show='options3.length' ng-change="onOption3Change()">
  </select>
  <hr>
  <select ng-if="showDropDownOptions[selectC].indexOf(1) != '-1' && selectC && opt1.length>0" ng-model="obj.selectedName245" ng-options="x for x in opt1">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(2) != '-1' && selectC && opt2.length>0" ng-model="obj.selectedName64" ng-options="x for x in opt2">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(3) != '-1' && selectC && opt3.length>0" ng-model="obj.selectedName321" ng-options="x for x in opt3">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(4) != '-1' && selectC && opt4.length>0" ng-model="obj.selectedName34" ng-options="x for x in opt4">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(5) != '-1' && selectC && opt5.length>0" ng-model="obj.selectedName21" ng-options="x for x in opt5">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(6) != '-1' && selectC && opt6.length>0" ng-model="obj.selectedName12" ng-options="x for x in opt6">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(7) != '-1' && selectC && opt7.length>0" ng-model="obj.selectedName222" ng-options="x for x in opt7">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(8) != '-1' && selectC && opt8.length>0" ng-model="obj.selectedName22" ng-options="x for x in opt8">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(9) != '-1' && selectC && opt9.length>0" ng-model="obj.selectedName2" ng-options="x for x in opt9">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(10) != '-1' && selectC && opt10.length>0" ng-model="obj.selectedNamelast" ng-options="x for x in opt10">
    <option>opt10</option>
  </select>

  Test Model: {{obj}}
</div></code>```

See Fiddle here

答:
Your problem is with these lines

```<code><select ng-if="showDropDownOptions[selectC].indexOf(10) != '-1' && selectC && opt10.length>0" ng-model="obj.selectedNamelast" ng-options="x for x in opt10">
</code>```

On the third dropdown, when you select the first option selectC will be set to 0 which is a falsey value meaning the && selectC will make it so that the select will not be shown

you can change this to be selectC != null and change the function to be

```<code>$scope.getOptions3 = function() {
    $scope.selectC = null;
    var mergedOptions2 = [].concat.apply([], option2Options)
    $scope.options3 = option3Options[mergedOptions2.indexOf($scope.option2)];
}
</code>```

var option1Options = ["Men", "women", "kids"];
var option2Options = [
  ["m-top", "m-bottom", "m-f0otwear"],
  ["w-top", "w-bottom", "w-footwear"],
  ["k-top", "k-bottom", "k-footwear"]
];
var option3Options = [
  ["m-Shirt", "m-t-shirt"],
  ["m-jeans", "m-trousers"],
  ["m-chapals", "m-formal shoes"],
  ["w-Shirt", "w-t-shirt"],
  ["w-jeans", "w-trousers"],
  ["w-chapals", "w-formal shoes"]

];

function myCtrl($scope) {
  $scope.opt1 = ["opt1", "opt2", "opt3"];
  $scope.opt2 = ["opt1", "opt2"];
  $scope.opt3 = ["opt1", "opt2"];
  $scope.opt4 = ["opt1", "opt2"];
  $scope.opt5 = ["opt1", "opt2"];
  $scope.opt6 = ["opt1", "opt2"];
  $scope.opt7 = ["opt1", "opt2"];
  $scope.opt8 = ["opt1", "opt2"];
  $scope.opt9 = ["opt1", "opt2"];
  $scope.opt10 = [];

  $scope.onOption3Change = function() {
    $scope.obj = {};

    $scope.selectC = $scope.options3.indexOf($scope.option3)

  }
  $scope.showDropDownOptions = [];
  $scope.showDropDownOptions[0] = [2, 3, 6];
  $scope.showDropDownOptions[1] = [1, 4];
  $scope.showDropDownOptions[2] = [5, 9, 10, 7];
  $scope.showDropDownOptions[3] = [8, 10];

  //$scope.second[0] = [1];
  $scope.obj = {};

  $scope.options1 = option1Options;
  $scope.options2 = []; // we'll get these later
  $scope.options3 = [];
  $scope.getOptions2 = function() {

    $scope.options2 = option2Options[option1Options.indexOf($scope.option1)];
    $scope.getOptions3();
  };

  $scope.getOptions3 = function() {
    $scope.selectC = null;
    var mergedOptions2 = [].concat.apply([], option2Options)
    $scope.options3 = option3Options[mergedOptions2.indexOf($scope.option2)];
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app data-ng-controller="myCtrl">
  <select data-ng-model="option1" data-ng-options="option for option in options1 " data-ng-change="getOptions2($index)">
  </select>
  <select data-ng-model="option2" data-ng-options="option for option in options2" data-ng-show='options2.length' data-ng-change="getOptions3()">
  </select>{{option2}}
  <select data-ng-model="option3" data-ng-options="option for option in options3" data-ng-show='options3.length' ng-change="onOption3Change()">
  </select>
  <hr>
  <select ng-if="showDropDownOptions[selectC].indexOf(1) != '-1' && selectC != null && opt1.length>0 " ng-model="obj.selectedName245" ng-options="x for x in opt1">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(2) != '-1' && selectC != null && opt2.length>0" ng-model="obj.selectedName64" ng-options="x for x in opt2">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(3) != '-1'&& selectC != null && opt3.length>0" ng-model="obj.selectedName321" ng-options="x for x in opt3">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(4) != '-1' && selectC != null && opt4.length>0" ng-model="obj.selectedName34" ng-options="x for x in opt4">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(5) != '-1' && selectC != null && opt5.length>0" ng-model="obj.selectedName21" ng-options="x for x in opt5">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(6) != '-1' && selectC != null && opt6.length>0" ng-model="obj.selectedName12" ng-options="x for x in opt6">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(7) != '-1' && selectC != null && opt7.length>0" ng-model="obj.selectedName222" ng-options="x for x in opt7">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(8) != '-1' && selectC != null && opt8.length>0" ng-model="obj.selectedName22" ng-options="x for x in opt8">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(9) != '-1' && selectC != null && opt9.length>0" ng-model="obj.selectedName2" ng-options="x for x in opt9">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(10) != '-1' && selectC != null && opt10.length>0" ng-model="obj.selectedNamelast" ng-options="x for x in opt10">
    <option>opt10</option>
  </select> Test Model: {{obj}}
</div></code>```

JSFiddle

Body:
I have 3 dropdowns, lets say A,B,C.

When I select item from dropdown A, then dropdown B is filled, and accordingly c is also filled. (not like cascading read my question fully)

Based on the dropdown C item selection, more dropdowns will be populated. For ex. if i select option 1 from dropdown c, then 3 dropdowns will be populated, if I select option 2, then 2 dropdowns will be populated.

So, till point 2 I have achieved, but while implementing point 3, I am not able to populate dropdowns. When I select any option from  dropdown c, then entire dropdowns are getting generated.

var option1Options = ["Men", "women", "kids"];
var option2Options = [
  ["m-top", "m-bottom", "m-f0otwear"],
  ["w-top", "w-bottom", "w-footwear"],
  ["k-top", "k-bottom", "k-footwear"]
];
var option3Options = [
  ["m-Shirt", "m-t-shirt"],
  ["m-jeans", "m-trousers"],
  ["m-chapals", "m-formal shoes"],
  ["w-Shirt", "w-t-shirt"],
  ["w-jeans", "w-trousers"],
  ["w-chapals", "w-formal shoes"]

];

function myCtrl($scope) {
  $scope.opt1 = ["opt1", "opt2", "opt3"];
  $scope.opt2 = ["opt1", "opt2"];
  $scope.opt3 = ["opt1", "opt2"];
  $scope.opt4 = ["opt1", "opt2"];
  $scope.opt5 = ["opt1", "opt2"];
  $scope.opt6 = ["opt1", "opt2"];
  $scope.opt7 = ["opt1", "opt2"];
  $scope.opt8 = ["opt1", "opt2"];
  $scope.opt9 = ["opt1", "opt2"];
  $scope.opt10 = [];

  $scope.onOption3Change = function() {
    $scope.obj = {};

    $scope.selectC = $scope.options3.indexOf($scope.option3)

  }
  $scope.showDropDownOptions = [];
  $scope.showDropDownOptions[0] = [2, 3, 6];
  $scope.showDropDownOptions[1] = [1, 4];
  $scope.showDropDownOptions[2] = [5, 9, 10, 7];
  $scope.showDropDownOptions[3] = [8, 10];

  //$scope.second[0] = [1];
  $scope.obj = {};

  $scope.options1 = option1Options;
  $scope.options2 = []; // we'll get these later
  $scope.options3 = [];
  $scope.getOptions2 = function() {

    $scope.options2 = option2Options[option1Options.indexOf($scope.option1)];
    $scope.getOptions3();
  };

  $scope.getOptions3 = function() {
    var mergedOptions2 = [].concat.apply([], option2Options)
    $scope.options3 = option3Options[mergedOptions2.indexOf($scope.option2)];
  }
}

  <select data-ng-model="option1" data-ng-options="option for option in options1 " data-ng-change="getOptions2($index)">
  </select>
  <select data-ng-model="option2" data-ng-options="option for option in options2" data-ng-show='options2.length' data-ng-change="getOptions3()">
  </select>{{option2}}
  <select data-ng-model="option3" data-ng-options="option for option in options3" data-ng-show='options3.length' ng-change="onOption3Change()">
  </select>

  <select ng-if="showDropDownOptions[selectC].indexOf(1) != '-1' && selectC && opt1.length>0" ng-model="obj.selectedName245" ng-options="x for x in opt1">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(2) != '-1' && selectC && opt2.length>0" ng-model="obj.selectedName64" ng-options="x for x in opt2">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(3) != '-1' && selectC && opt3.length>0" ng-model="obj.selectedName321" ng-options="x for x in opt3">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(4) != '-1' && selectC && opt4.length>0" ng-model="obj.selectedName34" ng-options="x for x in opt4">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(5) != '-1' && selectC && opt5.length>0" ng-model="obj.selectedName21" ng-options="x for x in opt5">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(6) != '-1' && selectC && opt6.length>0" ng-model="obj.selectedName12" ng-options="x for x in opt6">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(7) != '-1' && selectC && opt7.length>0" ng-model="obj.selectedName222" ng-options="x for x in opt7">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(8) != '-1' && selectC && opt8.length>0" ng-model="obj.selectedName22" ng-options="x for x in opt8">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(9) != '-1' && selectC && opt9.length>0" ng-model="obj.selectedName2" ng-options="x for x in opt9">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(10) != '-1' && selectC && opt10.length>0" ng-model="obj.selectedNamelast" ng-options="x for x in opt10">
    <option>opt10</option>
  </select>

  Test Model: {{obj}}

See Fiddle here

Body:
Your problem is with these lines

<select ng-if="showDropDownOptions[selectC].indexOf(10) != '-1' && selectC && opt10.length>0" ng-model="obj.selectedNamelast" ng-options="x for x in opt10">

On the third dropdown, when you select the first option selectC will be set to 0 which is a falsey value meaning the && selectC will make it so that the select will not be shown

you can change this to be selectC != null and change the function to be

$scope.getOptions3 = function() {
    $scope.selectC = null;
    var mergedOptions2 = [].concat.apply([], option2Options)
    $scope.options3 = option3Options[mergedOptions2.indexOf($scope.option2)];
}

var option1Options = ["Men", "women", "kids"];
var option2Options = [
  ["m-top", "m-bottom", "m-f0otwear"],
  ["w-top", "w-bottom", "w-footwear"],
  ["k-top", "k-bottom", "k-footwear"]
];
var option3Options = [
  ["m-Shirt", "m-t-shirt"],
  ["m-jeans", "m-trousers"],
  ["m-chapals", "m-formal shoes"],
  ["w-Shirt", "w-t-shirt"],
  ["w-jeans", "w-trousers"],
  ["w-chapals", "w-formal shoes"]

];

function myCtrl($scope) {
  $scope.opt1 = ["opt1", "opt2", "opt3"];
  $scope.opt2 = ["opt1", "opt2"];
  $scope.opt3 = ["opt1", "opt2"];
  $scope.opt4 = ["opt1", "opt2"];
  $scope.opt5 = ["opt1", "opt2"];
  $scope.opt6 = ["opt1", "opt2"];
  $scope.opt7 = ["opt1", "opt2"];
  $scope.opt8 = ["opt1", "opt2"];
  $scope.opt9 = ["opt1", "opt2"];
  $scope.opt10 = [];

  $scope.onOption3Change = function() {
    $scope.obj = {};

    $scope.selectC = $scope.options3.indexOf($scope.option3)

  }
  $scope.showDropDownOptions = [];
  $scope.showDropDownOptions[0] = [2, 3, 6];
  $scope.showDropDownOptions[1] = [1, 4];
  $scope.showDropDownOptions[2] = [5, 9, 10, 7];
  $scope.showDropDownOptions[3] = [8, 10];

  //$scope.second[0] = [1];
  $scope.obj = {};

  $scope.options1 = option1Options;
  $scope.options2 = []; // we'll get these later
  $scope.options3 = [];
  $scope.getOptions2 = function() {

    $scope.options2 = option2Options[option1Options.indexOf($scope.option1)];
    $scope.getOptions3();
  };

  $scope.getOptions3 = function() {
    $scope.selectC = null;
    var mergedOptions2 = [].concat.apply([], option2Options)
    $scope.options3 = option3Options[mergedOptions2.indexOf($scope.option2)];
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app data-ng-controller="myCtrl">
  <select data-ng-model="option1" data-ng-options="option for option in options1 " data-ng-change="getOptions2($index)">
  </select>
  <select data-ng-model="option2" data-ng-options="option for option in options2" data-ng-show='options2.length' data-ng-change="getOptions3()">
  </select>{{option2}}
  <select data-ng-model="option3" data-ng-options="option for option in options3" data-ng-show='options3.length' ng-change="onOption3Change()">
  </select>
  <hr>
  <select ng-if="showDropDownOptions[selectC].indexOf(1) != '-1' && selectC != null && opt1.length>0 " ng-model="obj.selectedName245" ng-options="x for x in opt1">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(2) != '-1' && selectC != null && opt2.length>0" ng-model="obj.selectedName64" ng-options="x for x in opt2">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(3) != '-1'&& selectC != null && opt3.length>0" ng-model="obj.selectedName321" ng-options="x for x in opt3">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(4) != '-1' && selectC != null && opt4.length>0" ng-model="obj.selectedName34" ng-options="x for x in opt4">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(5) != '-1' && selectC != null && opt5.length>0" ng-model="obj.selectedName21" ng-options="x for x in opt5">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(6) != '-1' && selectC != null && opt6.length>0" ng-model="obj.selectedName12" ng-options="x for x in opt6">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(7) != '-1' && selectC != null && opt7.length>0" ng-model="obj.selectedName222" ng-options="x for x in opt7">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(8) != '-1' && selectC != null && opt8.length>0" ng-model="obj.selectedName22" ng-options="x for x in opt8">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(9) != '-1' && selectC != null && opt9.length>0" ng-model="obj.selectedName2" ng-options="x for x in opt9">
  </select>
  <select ng-if="showDropDownOptions[selectC].indexOf(10) != '-1' && selectC != null && opt10.length>0" ng-model="obj.selectedNamelast" ng-options="x for x in opt10">
    <option>opt10</option>
  </select> Test Model: {{obj}}
</div>

JSFiddle


问:
Trouble parsing JSON generated from Node.js and MySQL

Hello everyone,

I am currently having trouble trying to parse a JSON from a server response. Im the Client/App side programmer, and we have a Server programmer responsible for creating the JSON. So I don't really know that much about JSON and how they generate them.

I am parsing the JSON in Unity(Game Engine), using the built-in JSON Utility. I've been googling around and there might be some different variations of JSON, so I am not sure If I need a 3rd party library that can parse the specific JSON that I have.

Are you familiar with this type of JSON below?

```<code>[
  {
    "id": 221,
    "builder_count": 1,
    "units": "[{\"count\": 1, \"level\": 1, \"type_id\": 1, \"unit_id\": \"2359-1\", \"research_time\": 0, \"research_complete\": 1}],[{\"count\": 5, \"level\": 1, \"type_id\": 11, \"unit_id\": \"2359-11\", \"research_time\": 0, \"research_complete\": 1}],[{\"count\": 5, \"level\": 1, \"type_id\": 2, \"unit_id\": \"2359-2\", \"research_time\": 0, \"research_complete\": 1}]"
  }
]
</code>```

The Units key seems a bit off, they are being treated as a string even though they are really an object.

I have access to the server code, and this is how the Key:Units is being generated. (The whole code block is pretty big, so I just selected this part as an example, please let me know If I need to post the whole function that generated the entire JSON)

```<code>    '    (SELECT CAST(GROUP_CONCAT ( ' +
    '       JSON_ARRAY( ' +
    '           JSON_OBJECT( ' +
    '               "unit_id", tu.unique_id, ' +
    '               "type_id", tu.unit_type_id, ' +
    '               "level", tu.level, ' +
    '               "research_time", tu.research_time, ' +
    '               "research_complete", tu.research_complete, ' +
    '               "count", tu.tally ' +
    '               )' +
    '           )' +
    '       ) AS CHAR)' +
    '     FROM api_TurfUnits tu WHERE tu.turf_id = t.id) AS units, '
</code>```

Our server technology that we use is Node.js and AWS Aurora (MySQL).

Basically I'm looking for a library that might be able to parse the type of JSON properly (the Key: Units)

I have used the website https://jsonformatter.curiousconcept.com/ and tried all the different JSON standard, but none of them can't seem to parse it.

答:
JSON.parse will take care of most of your needs.

If you're using the request library there is an option to pre-parse it into json.

Body:
Hello everyone,

I am currently having trouble trying to parse a JSON from a server response. Im the Client/App side programmer, and we have a Server programmer responsible for creating the JSON. So I don't really know that much about JSON and how they generate them.

I am parsing the JSON in Unity(Game Engine), using the built-in JSON Utility. I've been googling around and there might be some different variations of JSON, so I am not sure If I need a 3rd party library that can parse the specific JSON that I have.

Are you familiar with this type of JSON below?

[
  {
    "id": 221,
    "builder_count": 1,
    "units": "[{\"count\": 1, \"level\": 1, \"type_id\": 1, \"unit_id\": \"2359-1\", \"research_time\": 0, \"research_complete\": 1}],[{\"count\": 5, \"level\": 1, \"type_id\": 11, \"unit_id\": \"2359-11\", \"research_time\": 0, \"research_complete\": 1}],[{\"count\": 5, \"level\": 1, \"type_id\": 2, \"unit_id\": \"2359-2\", \"research_time\": 0, \"research_complete\": 1}]"
  }
]

The Units key seems a bit off, they are being treated as a string even though they are really an object.

I have access to the server code, and this is how the Key:Units is being generated. (The whole code block is pretty big, so I just selected this part as an example, please let me know If I need to post the whole function that generated the entire JSON)

    '    (SELECT CAST(GROUP_CONCAT ( ' +
    '       JSON_ARRAY( ' +
    '           JSON_OBJECT( ' +
    '               "unit_id", tu.unique_id, ' +
    '               "type_id", tu.unit_type_id, ' +
    '               "level", tu.level, ' +
    '               "research_time", tu.research_time, ' +
    '               "research_complete", tu.research_complete, ' +
    '               "count", tu.tally ' +
    '               )' +
    '           )' +
    '       ) AS CHAR)' +
    '     FROM api_TurfUnits tu WHERE tu.turf_id = t.id) AS units, '

Our server technology that we use is Node.js and AWS Aurora (MySQL).

Basically I'm looking for a library that might be able to parse the type of JSON properly (the Key: Units)

I have used the website https://jsonformatter.curiousconcept.com/ and tried all the different JSON standard, but none of them can't seem to parse it.


问:
How to use an array element value if the array name is extracted later (in Python)?
eg:

CASE 1:

```<code>arr1 = [1, 2, 3, 4, 5]

print('arr1[0]')
</code>```

Output is:

1

CASE 2: (in the same program, after finding out name of array)

```<code>new = 'arr1'

print('new[0]')
</code>```

Output is :

a

In case 1, we are accessing list elements but in case 2, we are accessing string elements.
The problem is that I want that the computer should understand that this is the same arr1 defined in Case 1.

答:
You could use eval:

```<code>arr1 = [1, 2, 3, 4, 5]

print(eval('arr1[0]'))

new = 'arr1'

print(eval('new[0]'))
</code>```

The second case will, however, not give you the answer you wanted. You need to use eval twice:

```<code>arr1 = [1, 2, 3, 4, 5]

print(eval('arr1[0]'))

new = eval('arr1')

print(eval('new[0]'))
</code>```

Body:
eg:

CASE 1:

arr1 = [1, 2, 3, 4, 5]

print('arr1[0]')

Output is:

1

CASE 2: (in the same program, after finding out name of array)

new = 'arr1'

print('new[0]')

Output is :

a

In case 1, we are accessing list elements but in case 2, we are accessing string elements.
The problem is that I want that the computer should understand that this is the same arr1 defined in Case 1.

Body:
You could use eval:

arr1 = [1, 2, 3, 4, 5]

print(eval('arr1[0]'))

new = 'arr1'

print(eval('new[0]'))

The second case will, however, not give you the answer you wanted. You need to use eval twice:

arr1 = [1, 2, 3, 4, 5]

print(eval('arr1[0]'))

new = eval('arr1')

print(eval('new[0]'))


问:
Python - Only the first inner funciton was excuted
I am writing a program that could greet users on at fixed times. And if the user didn't reply anything within a period of time, the program will send another message.

Currently I use a outer function including two inner functions as I wanted to import the outer one into another main file in the future. But when I call the outer function test(), only the first inner function weekends() was executed.

This is my code.

```<code>import schedule
import time
from threading import Thread

def test():

    def weekends():
        weekends_ans = None
        def weekends_check():
            time.sleep(20)
            if weekends_ans!=None:
                return
            print('\nWhat about watching a movie?')
        Thread(target=weekends_check).start()
        weekends_ans=input('Whats your plan for weekends?')

    def monday():
        monday_ans = None
        def monday_check():
            time.sleep(20)
            if monday_ans!=None:
                return
            print('\nHave fun next week!')
        Thread(target=monday_check).start()
        monday_ans=input('Monday again.')

    schedule.every().friday.at('17:00').do(weekends)
    schedule.every().sunday.at('17:00').do(monday)
    while True:
        schedule.run_pending()
        time.sleep(1)

test()
</code>```

Anyone could help?

答:
Does it enter this part

if weekends_ans!=None:
    return

If it does the code will return and will not contine to the next part.
( It will do a return and then continue from below test() )

Side note: Check out async programming. Using sleep is almost always bad practise, example link to async:
https://hackernoon.com/asynchronous-python-45df84b82434

Body:
I am writing a program that could greet users on at fixed times. And if the user didn't reply anything within a period of time, the program will send another message.

Currently I use a outer function including two inner functions as I wanted to import the outer one into another main file in the future. But when I call the outer function test(), only the first inner function weekends() was executed.

This is my code.

import schedule
import time
from threading import Thread

def test():

    def weekends():
        weekends_ans = None
        def weekends_check():
            time.sleep(20)
            if weekends_ans!=None:
                return
            print('\nWhat about watching a movie?')
        Thread(target=weekends_check).start()
        weekends_ans=input('Whats your plan for weekends?')

    def monday():
        monday_ans = None
        def monday_check():
            time.sleep(20)
            if monday_ans!=None:
                return
            print('\nHave fun next week!')
        Thread(target=monday_check).start()
        monday_ans=input('Monday again.')

    schedule.every().friday.at('17:00').do(weekends)
    schedule.every().sunday.at('17:00').do(monday)
    while True:
        schedule.run_pending()
        time.sleep(1)

test()

Anyone could help?


问:
iPhone Dev: Tab View controller. Buttons on first view don't show actions in File's Owner
Hey all, I'm really new to iphone development and am getting really frustrated. I know ASP and Javascript and i'm trying to do this objective-c. I took a course on lynda and now i'm trying to hook up a tab view.

I placed buttons on the first view of the tab view controller. I then went into the header file and created the - (IBAction) for the 4 buttons on there and added the function in the implementation file. The problem is when i go back to Interface builder and try to connect the actions to the buttons, they don't show up. I have no actions listed in the File's owner so i can't do anything. Can anyone out there please help! thanks.

damien

答: In tab view controller app make sure that class of view is your ViewController class and also in MainWindow.xib make sure all tabs are referencing respective ViewController </p>

ContentLicense: CC BY-SA 2.5


问:
SQL Server command line backup statement
Does any one know if there is a way to script out SQL Server backup in to a batch file, so that it could be executed from a command line?</p>

答: You can use sqlcmd to run a backup, or any other T-SQL script. You can find the detailed instructions and examples on various useful sqlcmd switches in this article: Working with the SQL Server command line (sqlcmd)</p>


问:
PHP: INSERT DATA BY SELECTION TAG HTML WITH PHP
I use this code to insert the data selection from select tag in html but i doesn't work perfectly when i put a value number in text input i would like someone helps me with that. otherwise, when i click in add_btn without value the insertion of data is added in MySQL databases.

HTML->

```<code>  <form id="myForm" action="userInfo.php" method="post">
                    <select name="type" class="add__type" >
                        <option value="inc" selected>+</option>
                        <option value="exp">-</option>
                    </select>
                 <select  name="description" class="add__description" title="h" >
                   <option  value="Food">Food</option>
                   <option  value="Salary">Salary</option>
                   <option  value="Home">Home</option>
                   <option  value="Car">Car</option>
                   <option  value="Education">Education</option>
                   <option  value="Gift">Gift</option>
                   <option  value="Travle"> Travle </option>
                   <option  value="Fun">Fun</option>
                        </select>
                <input name="value" type="number" class="add__value">
           <button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
            </form>
     <script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
    <script src="script/my_script.js" type="text/javascript"></script>
</code>```

PHP-> userinfo.php

```<code>  <?php
        include_once('db.php');

        $type = $_POST['type'];
        $description = $_POST['description'];
        $value = $_POST['value'];

        if(mysql_query("INSERT INTO budget VALUES('$type', '$description' , '$value')"))
          echo "Successfully Inserted";
        else
          echo "Insertion Failed";
?>
</code>```

PHP -> db.php

```<code><?php
      $conn = mysql_connect ('localhost', 'root', '');
      $db   = mysql_select_db ('test');
?>
</code>```

答:
You're using an outdated method to do this. Have a look here : http://php.net/manual/it/book.mysqli.php

I suggest you also to check datas before insert them into your database. you are not checking anything to protect you to SqlInjection (you can start with a simple mysql_real_escape_string).

Correct the line 5 from this

$value = $_POST['value'];

to this

$value = $_POST['description'];

The fact that the data may not get inserted successfully can be due to an issue with your database. Be sure that your columns have the property to accept varchar instead of the text because if you try to insert number to a filed that only want letters your query will not work.

Body:
I use this code to insert the data selection from select tag in html but i doesn't work perfectly when i put a value number in text input i would like someone helps me with that. otherwise, when i click in add_btn without value the insertion of data is added in MySQL databases.

HTML->

  <form id="myForm" action="userInfo.php" method="post">
                    <select name="type" class="add__type" >
                        <option value="inc" selected>+</option>
                        <option value="exp">-</option>
                    </select>
                 <select  name="description" class="add__description" title="h" >
                   <option  value="Food">Food</option>
                   <option  value="Salary">Salary</option>
                   <option  value="Home">Home</option>
                   <option  value="Car">Car</option>
                   <option  value="Education">Education</option>
                   <option  value="Gift">Gift</option>
                   <option  value="Travle"> Travle </option>
                   <option  value="Fun">Fun</option>
                        </select>
                <input name="value" type="number" class="add__value">
           <button class="add__btn"></button>
            </form>

PHP-> userinfo.php

  <?php
        include_once('db.php');

        $type = $_POST['type'];
        $description = $_POST['description'];
        $value = $_POST['value'];

        if(mysql_query("INSERT INTO budget VALUES('$type', '$description' , '$value')"))
          echo "Successfully Inserted";
        else
          echo "Insertion Failed";
?>

PHP -> db.php

<?php
      $conn = mysql_connect ('localhost', 'root', '');
      $db   = mysql_select_db ('test');
?>


问:
Xml written twice while appending
When trying to append an existing xml file using xml.etree.ElementTree. The sub elements are written twice. Is there any way we can overcome this.

This is my current code:

```<code>with open('filename.aiml',"a+") as f:
                        tree=ET.parse(f)
                        root=tree.getroot()
                        rootTag=root.find('.')
                        category=ET.SubElement(rootTag,'category')
                        pattern=ET.SubElement(category,'pattern')
                        pattern.text=input_text.upper()
                        template=ET.SubElement(category,'template')
                        template.text=response
                        root.append(category)
                        tree.write(open("filename.aiml","w+"),encoding='ISO-8859-1')
</code>```

XML before written:

```<code><?xml version='1.0' encoding='ISO-8859-1'?>
<aiml version="1.0">
<category>
<pattern>WHAT IS DEEP LEARNING</pattern>
<template>Deep learning (also known as deep structured learning or hierarchical learning) is part of a broader family of machine learning methods based on learning data representations, as opposed to task-specific algorithms.</template>
</category>
</code>```

XML after written:

```<code>  <?xml version='1.0' encoding='ISO-8859-1'?>
    <aiml version="1.0">
    <category>
    <pattern>WHAT IS DEEP LEARNING</pattern>
    <template>Deep learning (also known as deep structured learning or hierarchical learning) is part of a broader family of machine learning methods based on learning data representations, as opposed to task-specific algorithms.</template>
    </category>
 <category>
<pattern>WHAT IS PROOF OF CONCEPT</pattern>
<template>Proof of Concept (PoC) is a realization of a certain method or idea in order to demonstrate its feasibility.</template>
</category>
<category><pattern>TELL ME ABOUT POC</pattern>
<template>Proof of Concept (PoC) is a realization of a certain method or idea in order to demonstrate its feasibility</template>
</category>
<category><pattern>WHAT IS PROOF OF CONCEPT</pattern>
<template>Proof of Concept (PoC) is a realization of a certain method or idea in order to demonstrate its feasibility</template>
</category>
<category><pattern>TELL ME ABOUT POC</pattern>
<template>Proof of Concept (PoC) is a realization of a certain method or idea in order to demonstrate its feasibility.</template></category>
</code>```

答:
you xml is throwing errors on parsing , so i would go with an example here.

Parse your data

```<code>root= ET.XML(filename)
</code>```

do your modifications whatever you want (adding nodes,values)
e.g. from the python document

```<code>for rank in root.iter('rank'):
...     new_rank = int(rank.text) + 1
...     rank.text = str(new_rank)
...     rank.set('updated', 'yes')
</code>```

all the changes are saved to root element.

Write it to a xml file

you need to pass root to ET.ElementTree(), that will save all your previous changes and would write to xml

```<code>with open('d:\output.xml', 'wb') as file:
    ET.ElementTree(root).write(file, encoding='utf-8', xml_declaration=True)
</code>```

Title: Xml written twice while appending

Body:
When trying to append an existing xml file using xml.etree.ElementTree. The sub elements are written twice. Is there any way we can overcome this.

This is my current code:

with open('filename.aiml',"a+") as f:
                        tree=ET.parse(f)
                        root=tree.getroot()
                        rootTag=root.find('.')
                        category=ET.SubElement(rootTag,'category')
                        pattern=ET.SubElement(category,'pattern')
                        pattern.text=input_text.upper()
                        template=ET.SubElement(category,'template')
                        template.text=response
                        root.append(category)
                        tree.write(open("filename.aiml","w+"),encoding='ISO-8859-1')

XML before written:

<?xml version='1.0' encoding='ISO-8859-1'?>
<aiml version="1.0">
<category>
<pattern>WHAT IS DEEP LEARNING</pattern>
<template>Deep learning (also known as deep structured learning or hierarchical learning) is part of a broader family of machine learning methods based on learning data representations, as opposed to task-specific algorithms.</template>
</category>

XML after written:

  <?xml version='1.0' encoding='ISO-8859-1'?>
    <aiml version="1.0">
    <category>
    <pattern>WHAT IS DEEP LEARNING</pattern>
    <template>Deep learning (also known as deep structured learning or hierarchical learning) is part of a broader family of machine learning methods based on learning data representations, as opposed to task-specific algorithms.</template>
    </category>
 <category>
<pattern>WHAT IS PROOF OF CONCEPT</pattern>
<template>Proof of Concept (PoC) is a realization of a certain method or idea in order to demonstrate its feasibility.</template>
</category>
<category><pattern>TELL ME ABOUT POC</pattern>
<template>Proof of Concept (PoC) is a realization of a certain method or idea in order to demonstrate its feasibility</template>
</category>
<category><pattern>WHAT IS PROOF OF CONCEPT</pattern>
<template>Proof of Concept (PoC) is a realization of a certain method or idea in order to demonstrate its feasibility</template>
</category>
<category><pattern>TELL ME ABOUT POC</pattern>
<template>Proof of Concept (PoC) is a realization of a certain method or idea in order to demonstrate its feasibility.</template></category>

Body:
you xml is throwing errors on parsing , so i would go with an example here.

Parse your data

root= ET.XML(filename)

do your modifications whatever you want (adding nodes,values)
e.g. from the python document

for rank in root.iter('rank'):
...     new_rank = int(rank.text) + 1
...     rank.text = str(new_rank)
...     rank.set('updated', 'yes')

all the changes are saved to root element.

Write it to a xml file

you need to pass root to ET.ElementTree(), that will save all your previous changes and would write to xml

with open('d:\output.xml', 'wb') as file:
    ET.ElementTree(root).write(file, encoding='utf-8', xml_declaration=True)


问:
How can I change the permissions on a service with Delphi?
I have written a Windows service that I would like to keep Administrators from casually tampering with by removing their right to start/stop it.

Granted, an Administrator can elevate to SYSTEM and do anything they want, or even an admin can still suspend the service's threads or delete the service, but this is meant to prevent casual tampering.

I can do this using Process Explorer quite easily (see below) but I am not sure where to begin with Delphi. I've browsed the SetAcl C++ source code (and I may use their OCX file), but I'd prefer to use a native Delphi solution if one already exists. If not, I'll work on cloning SetAcl functionality.

Does anyone have experience with this that they could share?

NOTE: I had advocated a screen capture tool written in Delphi in this post and I am removing it b/c it is unrelated. I'm leaving this note here so the comments will still make sense! Regards.

答:
Administrators have rights on their computers, to do whatever they want.  Are you asking for a way to change how Administrator rights work on a computer?

Any software that prevents administrators from "tampering" with something under their control sounds suspiciously like either a rootkit, or some other malevolent software.  If the administrator wants your service off, you should provide your own quick tools to get it off, and you shouldn't (and probably can't) block them from doing it, either from Windows GUI or from SC.EXE or NET STOP on the command line.

That being said, if it's a Windows API you want a Delphi wrapper for, I would find the name of the API and search the JEDI API library for it. It looks like JWSCL would work.


问:
Watir: get sometimes a Net::ReadTimeout error by launching chrome browser
I just use a watir script to download sequential status infos from a server. In most cases it works fine, but sometimes I get an Net::ReadTimeout error. I don't know why?

Code:

```<code>require "rubygems"
require "watir"
Watir.default_timeout = 180     # seconds – default is 60
prefs = { :download => { :prompt_for_download => false, :default_directory => path } }
browser = Watir::Browser.new :chrome, :switches => %w[--no-sandbox], :prefs => prefs
browser.goto 'https://www...'
...
</code>```

Error Message:

```<code>/usr/lib/ruby/2.3.0/net/protocol.rb:158:in `rbuf_fill': Net::ReadTimeout (Net::ReadTimeout)
    from /usr/lib/ruby/2.3.0/net/protocol.rb:136:in `readuntil'
    from /usr/lib/ruby/2.3.0/net/protocol.rb:146:in `readline'
    from /usr/lib/ruby/2.3.0/net/http/response.rb:40:in `read_status_line'
    from /usr/lib/ruby/2.3.0/net/http/response.rb:29:in `read_new'
    from /usr/lib/ruby/2.3.0/net/http.rb:1437:in `block in transport_request'
    from /usr/lib/ruby/2.3.0/net/http.rb:1434:in `catch'
    from /usr/lib/ruby/2.3.0/net/http.rb:1434:in `transport_request'from /usr/lib/ruby/2.3.0/net/http.rb:1407:in `request'
    from /usr/lib/ruby/2.3.0/net/http.rb:1400:in `block in request'
    from /usr/lib/ruby/2.3.0/net/http.rb:853:in `start'
    from /usr/lib/ruby/2.3.0/net/http.rb:1398:in `request'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/remote/http/default.rb:103:in `response_for'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/remote/http/default.rb:57:in `request'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/remote/http/common.rb:59:in `call'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/remote/bridge.rb:653:in `raw_execute'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/remote/bridge.rb:124:in `create_session'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/remote/bridge.rb:88:in `initialize'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/chrome/bridge.rb:41:in `initialize'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/common/driver.rb:61:in `new'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/common/driver.rb:61:in `for'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver.rb:82:in `for'
    from /var/lib/gems/2.3.0/gems/watir-6.0.2/lib/watir/browser.rb:46:in `initialize'
    from /var/www/jobs/ubuntu.rb:110:in `new'from /var/www/jobs/ubuntu.rb:5:in `<main>'
</code>```

I just looking for a reason on this?

Is it possible the customize the settings on firefox? What is wrong?

Watir Version: 6.0.2

Selenium Version: 3.0.1

Browser Chrome Version: 57.0.2987.110

Chrome Driver Version: 2.29.461571

OS Version: Ubuntu 16.04.3 LTS

答:
Finally i tested also the solution with firefox and get the described error:

```<code>/var/lib/gems/2.1.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/remote/response.rb:69:in 'assert_ok':
TypeError: Given platformVersion [object String] "any", but current platform version is [object String] "3.16.0-4-amd64"
(Selenium::WebDriver::Error::SessionNotCreatedError)
</code>```

It seems to be a problem with a specific firefox and geckodriver version. I tested many combinations. This versions work without the TypeError:

Firefox 51.0.1

geckodriver 0.11.1

Thanks to dan.brown

Body:
I just use a watir script to download sequential status infos from a server. In most cases it works fine, but sometimes I get an Net::ReadTimeout error. I don't know why?

Code:

require "rubygems"
require "watir"
Watir.default_timeout = 180     # seconds – default is 60
prefs = { :download => { :prompt_for_download => false, :default_directory => path } }
browser = Watir::Browser.new :chrome, :switches => %w[--no-sandbox], :prefs => prefs
browser.goto 'https://www...'
...

Error Message:

/usr/lib/ruby/2.3.0/net/protocol.rb:158:in `rbuf_fill': Net::ReadTimeout (Net::ReadTimeout)
    from /usr/lib/ruby/2.3.0/net/protocol.rb:136:in `readuntil'
    from /usr/lib/ruby/2.3.0/net/protocol.rb:146:in `readline'
    from /usr/lib/ruby/2.3.0/net/http/response.rb:40:in `read_status_line'
    from /usr/lib/ruby/2.3.0/net/http/response.rb:29:in `read_new'
    from /usr/lib/ruby/2.3.0/net/http.rb:1437:in `block in transport_request'
    from /usr/lib/ruby/2.3.0/net/http.rb:1434:in `catch'
    from /usr/lib/ruby/2.3.0/net/http.rb:1434:in `transport_request'from /usr/lib/ruby/2.3.0/net/http.rb:1407:in `request'
    from /usr/lib/ruby/2.3.0/net/http.rb:1400:in `block in request'
    from /usr/lib/ruby/2.3.0/net/http.rb:853:in `start'
    from /usr/lib/ruby/2.3.0/net/http.rb:1398:in `request'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/remote/http/default.rb:103:in `response_for'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/remote/http/default.rb:57:in `request'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/remote/http/common.rb:59:in `call'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/remote/bridge.rb:653:in `raw_execute'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/remote/bridge.rb:124:in `create_session'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/remote/bridge.rb:88:in `initialize'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/chrome/bridge.rb:41:in `initialize'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/common/driver.rb:61:in `new'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/common/driver.rb:61:in `for'
    from /var/lib/gems/2.3.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver.rb:82:in `for'
    from /var/lib/gems/2.3.0/gems/watir-6.0.2/lib/watir/browser.rb:46:in `initialize'
    from /var/www/jobs/ubuntu.rb:110:in `new'from /var/www/jobs/ubuntu.rb:5:in `'

I just looking for a reason on this?

Is it possible the customize the settings on firefox? What is wrong?

Watir Version: 6.0.2

Selenium Version: 3.0.1

Browser Chrome Version: 57.0.2987.110

Chrome Driver Version: 2.29.461571

OS Version: Ubuntu 16.04.3 LTS

Body:
Finally i tested also the solution with firefox and get the described error:

/var/lib/gems/2.1.0/gems/selenium-webdriver-3.0.1/lib/selenium/webdriver/remote/response.rb:69:in 'assert_ok':
TypeError: Given platformVersion [object String] "any", but current platform version is [object String] "3.16.0-4-amd64"
(Selenium::WebDriver::Error::SessionNotCreatedError)

It seems to be a problem with a specific firefox and geckodriver version. I tested many combinations. This versions work without the TypeError:

Firefox 51.0.1

geckodriver 0.11.1

Thanks to dan.brown


问:
IntelliJ's emmet + react-css-modules
I'm moving to react-css-modules which requires the class layout to be:

```<code><div styleName="local-class-here">
</code>```

instead of the traditional:

```<code><div className="global-class-here">
</code>```

How do I customize emmet in IntelliJ so that I when I expand

```<code>.my-class
</code>```

it will return this instead?:

```<code><div styleName="my-class">
</code>```

答: There is no way to do this; if you miss this feature, please follow WEB-28691 for updates</p>

Title: IntelliJ's emmet + react-css-modules

Body:
I'm moving to react-css-modules which requires the class layout to be:

instead of the traditional:

How do I customize emmet in IntelliJ so that I when I expand

.my-class

it will return this instead?:


问:
How to make all nodes in a line when using netchart of zoomcharts
In the pic that all node not in a line.

I want all the nodes in a line within the netcharts,not incline as showed in pic.
Which property of zoomcharts is used for disable incline?
Thanks for help.

答:
Make all nodes in a line

I found that using direction to make all nodes in a line.Just make direction consistent with from ... to...

```<code>"links":[
            {"from":"a", "to":"b","style":{"toDecoration":"arrow","direction":"R"}},
            {"from":"b", "to":"c", "style":{"toDecoration":"arrow", "direction":"R"}},
            {"from":"a", "to":"a_child1","style":{"toDecoration":"arrow","direction":"L"}},
            {"from":"c", "to":"c_child1","style":{"toDecoration":"arrow","direction":"R"}}
        ]
</code>```

a_child1 <- a -> b -> c -> c_child1

Body:
Make all nodes in a line

I found that using direction to make all nodes in a line.Just make direction consistent with from ... to...

"links":[
            {"from":"a", "to":"b","style":{"toDecoration":"arrow","direction":"R"}},
            {"from":"b", "to":"c", "style":{"toDecoration":"arrow", "direction":"R"}},
            {"from":"a", "to":"a_child1","style":{"toDecoration":"arrow","direction":"L"}},
            {"from":"c", "to":"c_child1","style":{"toDecoration":"arrow","direction":"R"}}
        ]

a_child1 <- a -> b -> c -> c_child1


问:
How to pass result from Model to Controller in CodeIgniter?
I want to get data from the database and display it on a webpage using CodeIgniter. I coded my controller, model and view as follows.

Controller;

```<code>//HomeController

<?php

class HomeController extends CI_Controller
{
    public function index()
    {
        $this->load->model('HomeModel');
        $data['records'] = $this->HomeModel->getData();
        $this->load->view('HomeView',$data);

    }
}
?>
</code>```

Model;

```<code>//HomeModel
<?php

class HomeModel extends CI_Model
{
    public function getData()
    {

          $query = $this->db->query('SELECT * FROM data');
          return $query->unbuffered_row('object');

    }
}
?>
</code>```

View;

```<code>//HomeView
<?php

echo "Recoeds from database<br>";

while($records)
{
    echo $records->name." ".$records->age."</br>";
}

?>
</code>```

But this code doesn't print anything on the screen.(echo "Records from database
"; )

So I tried the following code given in the CodeIgniter documentation and echoed the result in the model itself rather than return it to the controller and then to the views.It worked fine.

```<code>//HomeModel
<?php
        class HomeModel extends CI_Model
        {
            public function getData()
            {
                $query = $this->db->query('SELECT * FROM data');
                while ($row = $query->unbuffered_row())
                {
                     echo $row->name;
                     echo $row->age;
                }
             }
        }
?>
</code>```

My question is how do we return the result of the unbuffered_row() method into the controller and then to the view as per MVC architecture? We can get the output by echoing result at the model itself but it is against the purpose of the MVC architecture.

答:
Try This One

controller

```<code><?php

class HomeController extends CI_Controller
{
    public function index()
    {
        $this->load->model('HomeModel');
        $data['records'] = $this->HomeModel->getData();
        $this->load->view('HomeView',$data);

    }
}
?>
</code>```

Model

```<code><?php

class HomeModel extends CI_Model
{
    public function getData()
    {

          $data = $this->db->query('SELECT * FROM data');
          return array('count'=>$data->num_rows(), 'data'=>$data->result(),'first'=>$data->row());

    }
}
?>
</code>```

View

```<code><?php

echo "Recoeds from database<br>";

foreach($record['data'] as $row)
{
    echo $row->name." ".$row->age;
}

?>
</code>```

Body:
I want to get data from the database and display it on a webpage using CodeIgniter. I coded my controller, model and view as follows.

Controller;

//HomeController

<?php

class HomeController extends CI_Controller
{
    public function index()
    {
        $this->load->model('HomeModel');
        $data['records'] = $this->HomeModel->getData();
        $this->load->view('HomeView',$data);

    }
}
?>

Model;

//HomeModel
<?php

class HomeModel extends CI_Model
{
    public function getData()
    {

          $query = $this->db->query('SELECT * FROM data');
          return $query->unbuffered_row('object');

    }
}
?>

View;

//HomeView
<?php

echo "Recoeds from database
";

while($records)
{
    echo $records->name." ".$records->age."
";
}

?>

But this code doesn't print anything on the screen.(echo "Records from database
"; )

So I tried the following code given in the CodeIgniter documentation and echoed the result in the model itself rather than return it to the controller and then to the views.It worked fine.

//HomeModel
<?php
        class HomeModel extends CI_Model
        {
            public function getData()
            {
                $query = $this->db->query('SELECT * FROM data');
                while ($row = $query->unbuffered_row())
                {
                     echo $row->name;
                     echo $row->age;
                }
             }
        }
?>

My question is how do we return the result of the unbuffered_row() method into the controller and then to the view as per MVC architecture? We can get the output by echoing result at the model itself but it is against the purpose of the MVC architecture.

Body:
Try This One

controller

<?php

class HomeController extends CI_Controller
{
    public function index()
    {
        $this->load->model('HomeModel');
        $data['records'] = $this->HomeModel->getData();
        $this->load->view('HomeView',$data);

    }
}
?>

Model

<?php

class HomeModel extends CI_Model
{
    public function getData()
    {

          $data = $this->db->query('SELECT * FROM data');
          return array('count'=>$data->num_rows(), 'data'=>$data->result(),'first'=>$data->row());

    }
}
?>

View

<?php

echo "Recoeds from database<br>";

foreach($record['data'] as $row)
{
    echo $row->name." ".$row->age;
}

?>


问:
Dead connection message and delivery receipt received delay in stream management - MongooseIM server 2.0.0
I have enable stream management in both side client or server. I have two users A and B. Both users are online.Then user A suddenly lose his connection. but A user still appear online on user B and as well as on server. During that time user B sending message on user A. Those message are not lost but when user A is appear online again it will receive those message after 2-3 minute.and i will get message stanza on Offline storage and delivery receipt i will got on SM storage.This issue same occur on one to one chat and mucLight. have i need to customized any mongooseIM modules. Please guide me why users received delay message when their are lost his connection. is it possible to changed SM storage to offline storage(MAM). here's link for same issue i have found same issue on this link (https://www.ejabberd.im/faq/tcp) but have not lost my messages but just received it delay.

I am use smack-4.2 lib on my Android app.and following code used to enabled stream management in XMPPTCPConnection.

```<code>  static{
        XMPPTCPConnection.setUseStreamManagementDefault(true);
        XMPPTCPConnection.setUseStreamManagementResumptionDefault(true);
   }
</code>```

Here's my ejabbered.cfg file for mod_stream_management module

```<code>      {mod_stream_management, [
                       % default 100
                       % size of a buffer of unacked messages
                       % {buffer_max, 100}

                       % default 1 - server sends the ack request after each stanza
                       % {ack_freq, 1}

                       % default: 600 seconds
                       % {resume_timeout, 600}
                      ]},
</code>```

I have also enable following module on my config file

```<code>   %% Only archives for c2c messages, good performance.
  {mod_mam_odbc_user, [pm]},
  {mod_mam_cache_user, [pm]},
% {mod_mam_mnesia_dirty_prefs, [pm]},
% {mod_mam_odbc_arch, [pm, no_writer]},
  {mod_mam_odbc_async_pool_writer, [pm]},
  {mod_mam, []}
</code>```

I found little solution here smack connect to xmpp server with previous stream id but its not work on mongooseIM-2.0 server.

Thank you in advanced.

答:
I'm assuming below that user A, when they reconnect, is not using Stream Resumption (as defined by XEP-0198: Stream Management) and merely starting a new session.
This means that on the server side there's still a dangling process waiting for Stream Resumption to happen. When user A is already reconnected to the server, the dangling process times out (which takes resume_timeout seconds) and sends the messages it had stored for delivery in the outgoing message buffer.

If you don't like this behaviour, you can do one of these:

a) (not advised) disable Stream Management and send a Message Archive Management query (that is use mod_mam) to have the most up to date conversation state each time you establish a new connection to the server

b) leave Stream Management enabled, but use Stream Resumption if only possible; that is, you always try to resume the previous session, unless you don't have the previous session ID or the server rejects the resumption request; ideally you would also use Message Archive Management

c) use Delayed Delivery aka mod_offline, but risk that in some rare cases, if you use multiple devices, the messages might be sent to a wrong device; for example, if you have a phone and a laptop, it might happen that your messages will reach the laptop, but never reach the phone

Body:
I have enable stream management in both side client or server. I have two users A and B. Both users are online.Then user A suddenly lose his connection. but A user still appear online on user B and as well as on server. During that time user B sending message on user A. Those message are not lost but when user A is appear online again it will receive those message after 2-3 minute.and i will get message stanza on Offline storage and delivery receipt i will got on SM storage.This issue same occur on one to one chat and mucLight. have i need to customized any mongooseIM modules. Please guide me why users received delay message when their are lost his connection. is it possible to changed SM storage to offline storage(MAM). here's link for same issue i have found same issue on this link (https://www.ejabberd.im/faq/tcp) but have not lost my messages but just received it delay.

I am use smack-4.2 lib on my Android app.and following code used to enabled stream management in XMPPTCPConnection.

  static{
        XMPPTCPConnection.setUseStreamManagementDefault(true);
        XMPPTCPConnection.setUseStreamManagementResumptionDefault(true);
   }

Here's my ejabbered.cfg file for mod_stream_management module

      {mod_stream_management, [
                       % default 100
                       % size of a buffer of unacked messages
                       % {buffer_max, 100}

                       % default 1 - server sends the ack request after each stanza
                       % {ack_freq, 1}

                       % default: 600 seconds
                       % {resume_timeout, 600}
                      ]},

I have also enable following module on my config file

   %% Only archives for c2c messages, good performance.
  {mod_mam_odbc_user, [pm]},
  {mod_mam_cache_user, [pm]},
% {mod_mam_mnesia_dirty_prefs, [pm]},
% {mod_mam_odbc_arch, [pm, no_writer]},
  {mod_mam_odbc_async_pool_writer, [pm]},
  {mod_mam, []}

I found little solution here smack connect to xmpp server with previous stream id but its not work on mongooseIM-2.0 server.

Thank you in advanced.


问:
How to check element duplicate in Map java
I have a function, which allow input key and value into Map.

here my code

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

public class MapDemo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Map<String, Integer> map = new HashMap<>();
        System.out.println("Elemment number: ");
        String sNum = input.nextLine();
        int iNum = Integer.parseInt(sNum);
        for (int i = 0; i < iNum; i++) {
            System.out.println("Key: ");
            String sKey = input.nextLine();
            System.out.println("Value: ");
            String sValue = input.nextLine();
            int iValue = Integer.parseInt(sValue);
            map.put(sKey, iValue);
        }
    }
}
</code>```

I don't know how to check element next, which I will input. it the same with element before, and if it same I will input again.

答: There is a Collection.contains() method available in every data structure that implements Collection interface !!!!</p>

Body:
I have a function, which allow input key and value into Map.

here my code

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class MapDemo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Map<String, Integer> map = new HashMap<>();
        System.out.println("Elemment number: ");
        String sNum = input.nextLine();
        int iNum = Integer.parseInt(sNum);
        for (int i = 0; i < iNum; i++) {
            System.out.println("Key: ");
            String sKey = input.nextLine();
            System.out.println("Value: ");
            String sValue = input.nextLine();
            int iValue = Integer.parseInt(sValue);
            map.put(sKey, iValue);
        }
    }
}

I don't know how to check element next, which I will input. it the same with element before, and if it same I will input again.