问:
SQL Select on priority of not exist
I'm quite confused as to how I'd structure a query I need:

```<code>select distinct NodeID from GroupsTable
                    where GroupID in
                    (
                        select GroupID from UserGroupsTable
                        where UserID = @UserID
                    )
</code>```

I need to select NodeID from GroupsTable where the User belongs to multiple groups, UNLESS any group that the user belongs to does not have that NodeID.

The above code only selects a NodeID from GroupsTable where it apears in any one of the users groups.

So:

Group|Node

1|A

  1|B

  2|A

I need only B to be selected for example.

Any Ideas?

答:
You can use a having clause to ensure that the count of groups per node is less than the count of all groups the user is in:

```<code>select  g.NodeID
from    GroupsTable g
join    UserGroupsTable ug
on      g.GroupID = ug.GroupID
where   ug.UserID = 1
group by
        ug.UserID
,       g.NodeID
having  COUNT(distinct g.GroupID) <
        (
        select  COUNT(distinct GroupID)
        from    UserGroupsTable ug2
        where   ug2.UserID = ug.UserID
        )
</code>```

Title: SQL Select on priority of not exist

Body:
I'm quite confused as to how I'd structure a query I need:

select distinct NodeID from GroupsTable
                    where GroupID in
                    (
                        select GroupID from UserGroupsTable
                        where UserID = @UserID
                    )

I need to select NodeID from GroupsTable where the User belongs to multiple groups, UNLESS any group that the user belongs to does not have that NodeID.

The above code only selects a NodeID from GroupsTable where it apears in any one of the users groups.

So:

Group|Node

1|A

  1|B

  2|A

I need only B to be selected for example.

Any Ideas?

Body:
You can use a having clause to ensure that the count of groups per node is less than the count of all groups the user is in:

select  g.NodeID
from    GroupsTable g
join    UserGroupsTable ug
on      g.GroupID = ug.GroupID
where   ug.UserID = 1
group by
        ug.UserID
,       g.NodeID
having  COUNT(distinct g.GroupID) <
        (
        select  COUNT(distinct GroupID)
        from    UserGroupsTable ug2
        where   ug2.UserID = ug.UserID
        )


来源: stackexchange

问:
Soapenv parsing Error
I am not able to fetch values from the XML shown below, in SQL Server 2012. Please help</p>

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.abc.org/soap/envelope/" xmlns:wsap="http://schemas.abc.com/abcd">
  <soapenv:Header xmlns:wsap="http://schemas.abc.com/abcd" xmlns:soapenv="http://schemas.example.org/soap/envelope/">
    <header xmlns:wsap="http://schemas.abc.com/abcd" xmlns:soapenv="http://schemas.example.org/soap/envelope/" xmlns="http://schemas.abc.com/General/1.0/">
      <msg-id>0673c07b-2b67-11e7-f959-0b3aae0b96ad</msg-id>
    </header>
  </soapenv:Header>
  <soapenv:Body>
    <GetInvoice_DataResponse xmlns:soapenv="http://schemas.example.org/soap/abcd/" xmlns="http://schemas.abc.com/abcd" preserveSpace="no" qAccess="0">
      <tuple xmlns="http://schemas.abc.com/abcd">
        <old>
          <S_ORDER xmlns="http://schemas.abc.com/abcd">
            <BILLING_TYPE>Paid</BILLING_TYPE>
            <CREATED>2017-11-13T10:40:28.0</CREATED>
            <CREATED_BY>1-455454asdas</CREATED_BY>
            <LAST_UPD>2017-11-13T10:40:29.0</LAST_UPD>
            <LAST_UPD_BY>1-dsafasc</LAST_UPD_BY>
            <INVC_DT>2017-11-13T00:00:00.0</INVC_DT>
            <INVC_NUM>dasda123</INVC_NUM>
            <STATUS_CD>New</STATUS_CD>
            <X_CANCELLATION_REASON xmlns:xsi="http://www.example.org/2001/exap-example" null="true" xsi:nil="true" />
            <GROSS_AMT>1768</GROSS_AMT>
            <ITEM_DTL_AMT>1381.25</ITEM_DTL_AMT>
            <ACCNT_ID>1-sad</ACCNT_ID>
            <ORDER_ID>1-fasdf</ORDER_ID>
            <GROSS_AMT>1768</GROSS_AMT>
            <DIV_ID>1-fas</DIV_ID>
            <ORDER_NUM>Osasaasf</ORDER_NUM>
            <PART>264731200101</PART>
            <ORDER_DT>20171113</ORDER_DT>
            <INVOICE_DT>20171113</INVOICE_DT>
            <ORDER_TYPE>ads fd</ORDER_TYPE>
            <QTY>1</QTY>
            <LINE_NUM>1</LINE_NUM>
            <INVC_STATUS>New</INVC_STATUS>
            <LINE_ITEM_STATUS>Invoiced</LINE_ITEM_STATUS>
            <BU>CVBU</BU>
          </S_ORDER>
        </old>
      </tuple>
      <tuple xmlns="http://schemas.abc.com/abcd">
        <old>
          <S_ORDER xmlns="http://schemas.abc.com/abcd">
            <BILLING_TYPE>Paid</BILLING_TYPE>
            <CREATED>2017-11-13T10:40:28.0</CREATED>
            <CREATED_BY>1-das</CREATED_BY>
            <LAST_UPD>2017-11-13T10:40:29.0</LAST_UPD>
            <LAST_UPD_BY>1-safdfa</LAST_UPD_BY>
            <INVC_DT>2017-11-13T00:00:00.0</INVC_DT>
            <INVC_NUM>afsfas415415</INVC_NUM>
            <STATUS_CD>New</STATUS_CD>
            <X_CANCELLATION_REASON xmlns:xsi="http://www.example.org/2001/exap-example" null="true" xsi:nil="true" />
            <GROSS_AMT>1768</GROSS_AMT>
            <ITEM_DTL_AMT>0</ITEM_DTL_AMT>
            <ACCNT_ID>1-fasf</ACCNT_ID>
            <ORDER_ID>1-saf</ORDER_ID>
            <GROSS_AMT>1768</GROSS_AMT>
            <DIV_ID>1-1IJGRE5</DIV_ID>
            <ORDER_NUM>fasf-sf-s-fd-gd</ORDER_NUM>
            <PART>0000079641</PART>
            <ORDER_DT>20171113</ORDER_DT>
            <INVOICE_DT>20171113</INVOICE_DT>
            <ORDER_TYPE>fasdf d</ORDER_TYPE>
            <QTY>1</QTY>
            <LINE_NUM>2</LINE_NUM>
            <INVC_STATUS>New</INVC_STATUS>
            <LINE_ITEM_STATUS>Invoiced</LINE_ITEM_STATUS>
            <BU>CVBU</BU>
          </S_ORDER>
        </old>
      </tuple>
    </GetInvoice_DataResponse>
  </soapenv:Body>
</soapenv:Envelope>
</code>```

答:
If you have your XML in a @Input variable of type XML, you can try this:

```<code>-- define your XML namespaces used in the XML document
;WITH XMLNAMESPACES ('http://schemas.abc.org/soap/envelope/' AS soapenv,
                     'http://schemas.abc.com/abcd' AS inv)
SELECT
    -- "reach into" the XML fragment representing the "<S_ORDER>" element
    -- and get the individual subelements from it - using the *default*
    -- XML namespace for those subelements
    BillingType = xc.value('(inv:BILLING_TYPE)[1]', 'varchar(50)'),
    Created = xc.value('(inv:CREATED)[1]', 'varchar(50)')
FROM
    -- define the path down to the "<S_ORDER>" elements, and fetch
    -- an "in-memory" table of each of those elements as a XML fragment
    @input.nodes('/soapenv:Envelope/soapenv:Body/inv:GetInvoice_DataResponse/inv:tuple/inv:old/inv:S_ORDER') AS XT(XC)
</code>```

The main point is: you need to respect and include the XML namespaces in your XQuery!

ContentLicense: CC BY-SA 3.0

Title: Soapenv parsing Error

Body:
I am not able to fetch values from the XML shown below, in SQL Server 2012. Please help

<soapenv:Envelope xmlns:soapenv="http://schemas.abc.org/soap/envelope/" xmlns:wsap="http://schemas.abc.com/abcd">
  <soapenv:Header xmlns:wsap="http://schemas.abc.com/abcd" xmlns:soapenv="http://schemas.example.org/soap/envelope/">

      <msg-id>0673c07b-2b67-11e7-f959-0b3aae0b96ad</msg-id>

  </soapenv:Header>
  <soapenv:Body>
    <GetInvoice_DataResponse xmlns:soapenv="http://schemas.example.org/soap/abcd/" xmlns="http://schemas.abc.com/abcd" preserveSpace="no" qAccess="0">
      <tuple xmlns="http://schemas.abc.com/abcd">
        <old>
          <S_ORDER xmlns="http://schemas.abc.com/abcd">
            <BILLING_TYPE>Paid</BILLING_TYPE>
            <CREATED>2017-11-13T10:40:28.0</CREATED>
            <CREATED_BY>1-455454asdas</CREATED_BY>
            <LAST_UPD>2017-11-13T10:40:29.0</LAST_UPD>
            <LAST_UPD_BY>1-dsafasc</LAST_UPD_BY>
            <INVC_DT>2017-11-13T00:00:00.0</INVC_DT>
            <INVC_NUM>dasda123</INVC_NUM>
            <STATUS_CD>New</STATUS_CD>
            <X_CANCELLATION_REASON xmlns:xsi="http://www.example.org/2001/exap-example" null="true" xsi:nil="true" />
            <GROSS_AMT>1768</GROSS_AMT>
            <ITEM_DTL_AMT>1381.25</ITEM_DTL_AMT>
            <ACCNT_ID>1-sad</ACCNT_ID>
            <ORDER_ID>1-fasdf</ORDER_ID>
            <GROSS_AMT>1768</GROSS_AMT>
            <DIV_ID>1-fas</DIV_ID>
            <ORDER_NUM>Osasaasf</ORDER_NUM>
            <PART>264731200101</PART>
            <ORDER_DT>20171113</ORDER_DT>
            <INVOICE_DT>20171113</INVOICE_DT>
            <ORDER_TYPE>ads fd</ORDER_TYPE>
            <QTY>1</QTY>
            <LINE_NUM>1</LINE_NUM>
            <INVC_STATUS>New</INVC_STATUS>
            <LINE_ITEM_STATUS>Invoiced</LINE_ITEM_STATUS>
            <BU>CVBU</BU>
          </S_ORDER>
        </old>
      </tuple>
      <tuple xmlns="http://schemas.abc.com/abcd">
        <old>
          <S_ORDER xmlns="http://schemas.abc.com/abcd">
            <BILLING_TYPE>Paid</BILLING_TYPE>
            <CREATED>2017-11-13T10:40:28.0</CREATED>
            <CREATED_BY>1-das</CREATED_BY>
            <LAST_UPD>2017-11-13T10:40:29.0</LAST_UPD>
            <LAST_UPD_BY>1-safdfa</LAST_UPD_BY>
            <INVC_DT>2017-11-13T00:00:00.0</INVC_DT>
            <INVC_NUM>afsfas415415</INVC_NUM>
            <STATUS_CD>New</STATUS_CD>
            <X_CANCELLATION_REASON xmlns:xsi="http://www.example.org/2001/exap-example" null="true" xsi:nil="true" />
            <GROSS_AMT>1768</GROSS_AMT>
            <ITEM_DTL_AMT>0</ITEM_DTL_AMT>
            <ACCNT_ID>1-fasf</ACCNT_ID>
            <ORDER_ID>1-saf</ORDER_ID>
            <GROSS_AMT>1768</GROSS_AMT>
            <DIV_ID>1-1IJGRE5</DIV_ID>
            <ORDER_NUM>fasf-sf-s-fd-gd</ORDER_NUM>
            <PART>0000079641</PART>
            <ORDER_DT>20171113</ORDER_DT>
            <INVOICE_DT>20171113</INVOICE_DT>
            <ORDER_TYPE>fasdf d</ORDER_TYPE>
            <QTY>1</QTY>
            <LINE_NUM>2</LINE_NUM>
            <INVC_STATUS>New</INVC_STATUS>
            <LINE_ITEM_STATUS>Invoiced</LINE_ITEM_STATUS>
            <BU>CVBU</BU>
          </S_ORDER>
        </old>
      </tuple>
    </GetInvoice_DataResponse>
  </soapenv:Body>
</soapenv:Envelope>

Body:
If you have your XML in a @Input variable of type XML, you can try this:

-- define your XML namespaces used in the XML document
;WITH XMLNAMESPACES ('http://schemas.abc.org/soap/envelope/' AS soapenv,
                     'http://schemas.abc.com/abcd' AS inv)
SELECT
    -- "reach into" the XML fragment representing the "<S_ORDER>" element
    -- and get the individual subelements from it - using the *default*
    -- XML namespace for those subelements
    BillingType = xc.value('(inv:BILLING_TYPE)[1]', 'varchar(50)'),
    Created = xc.value('(inv:CREATED)[1]', 'varchar(50)')
FROM
    -- define the path down to the "<S_ORDER>" elements, and fetch
    -- an "in-memory" table of each of those elements as a XML fragment
    @input.nodes('/soapenv:Envelope/soapenv:Body/inv:GetInvoice_DataResponse/inv:tuple/inv:old/inv:S_ORDER') AS XT(XC)

The main point is: you need to respect and include the XML namespaces in your XQuery!


问:
Time-Efficient Sorting of structure in c++
I have a structure

```<code> struct abc
       {
        int p;
        int q;
       }
</code>```

and a file which gives the value of p and q and the operation that is to be done( insert,delete or modify) and then accordingly the values needs to be maintained in a sorted manner(sort acc to p).

The sequence is

```<code>1.Read the line from file
2.If insert, insert in a sorted manner<br>
  If modify,delete; first remove the element and then sort<br>
3.Repeat step 1<br><br>
</code>```

I already implemented this with a linked list but is there any other more time-efficient method than this?

I thought of an array(with memcpy-ing to ease the operations),set and vector but implementation wise it seems to be a bit difficult as all the operations has to done.

Would be helpful if i could get an algorithm or snapshot of the code

答:
You shouldn't need to implement many operations.

Define your ordering relation:

```<code>bool operator<(const abc& lhs, const abc& rhs) { return lhs.p < rhs.p; }
</code>```

Read the data:

```<code>std::vector<abc> data;
abc x;
while (whatever >> x.p >> x.q)
{
    data.push_back(x);
}
</code>```

Sort the data:

```<code>std::sort(data.begin(), data.end());
</code>```

Insert while maintaining the order

```<code>abc y = whatever;
data.insert(std::lower_bound(data.begin(), data.end(), y), y);
</code>```

Body:
I have a structure

 struct abc
       {
        int p;
        int q;
       }

and a file which gives the value of p and q and the operation that is to be done( insert,delete or modify) and then accordingly the values needs to be maintained in a sorted manner(sort acc to p).

The sequence is

1.Read the line from file
2.If insert, insert in a sorted manner

  If modify,delete; first remove the element and then sort

3.Repeat step 1

I already implemented this with a linked list but is there any other more time-efficient method than this?

I thought of an array(with memcpy-ing to ease the operations),set and vector but implementation wise it seems to be a bit difficult as all the operations has to done.

Would be helpful if i could get an algorithm or snapshot of the code

Body:
You shouldn't need to implement many operations.

Define your ordering relation:

bool operator<(const abc& lhs, const abc& rhs) { return lhs.p < rhs.p; }

Read the data:

std::vector<abc> data;
abc x;
while (whatever >> x.p >> x.q)
{
    data.push_back(x);
}

Sort the data:

std::sort(data.begin(), data.end());

Insert while maintaining the order

abc y = whatever;
data.insert(std::lower_bound(data.begin(), data.end(), y), y);


问:
HTML & JS infinite background loop
since i'm relatively new to Js & html I would like too loop a background image, where one of it just flashes up really quickly. The problem which i currently am facing is to bring the whole process into a infinite loop....

```<code>setTimeout(function ()
{
    document.body.style.backgroundImage = 'url(\'source/css/IMAGES/introInvertImage.jpg\')';
    setTimeout(function ()
    {
        document.body.style.backgroundImage = 'url(\'source/css/IMAGES/introImage.jpg\')';
    }, 300);
}, 3000);
</code>```

if i put this snippet into an infinite loop via for or while it breaks the whole page..

答:
Use of two functions which are going to call each other in an infinite way.

```<code>function firstPicture() {
  document.body.style.backgroundImage = '...';

  setTimeout(function() {
    secondPicture();
  }, 3000);
}

function secondPicture() {
  document.body.style.backgroundImage = '...';

  setTimeout(function() {
    firstPicture();
  }, 300);
}

firstPicture();
</code>```

Or in one function

```<code>var pictureState = false;

function pictureChanging() {
  var timeout;

  if (pictureState) {
    document.body.style.backgroundImage = '...';

    timeout = 3000;
  } else {
    document.body.style.backgroundImage = '...';

    timeout = 300;
  }

  pictureState = !pictureState;

  setTimeout(function() {
    pictureChanging();
  }, timeout);
}

pictureChanging();
</code>```

Title: HTML & JS infinite background loop

Body:
since i'm relatively new to Js & html I would like too loop a background image, where one of it just flashes up really quickly. The problem which i currently am facing is to bring the whole process into a infinite loop....

setTimeout(function ()
{
    document.body.style.backgroundImage = 'url(\'source/css/IMAGES/introInvertImage.jpg\')';
    setTimeout(function ()
    {
        document.body.style.backgroundImage = 'url(\'source/css/IMAGES/introImage.jpg\')';
    }, 300);
}, 3000);

if i put this snippet into an infinite loop via for or while it breaks the whole page..

Body:
Use of two functions which are going to call each other in an infinite way.

function firstPicture() {
  document.body.style.backgroundImage = '...';

  setTimeout(function() {
    secondPicture();
  }, 3000);
}

function secondPicture() {
  document.body.style.backgroundImage = '...';

  setTimeout(function() {
    firstPicture();
  }, 300);
}

firstPicture();

Or in one function

var pictureState = false;

function pictureChanging() {
  var timeout;

  if (pictureState) {
    document.body.style.backgroundImage = '...';

    timeout = 3000;
  } else {
    document.body.style.backgroundImage = '...';

    timeout = 300;
  }

  pictureState = !pictureState;

  setTimeout(function() {
    pictureChanging();
  }, timeout);
}

pictureChanging();


问:
PHP how to find the duplicates
I am using php and I want to display list of records from database.
Say for example, the following is the table structure

```<code>sno val1 val2 val3  amt
1    2c   3e   I    500
2    2b   i7   I    1500
3    2w   u9   I    0
4    18   e3   I    50
5    2c   3e   S    70
</code>```

Now I want to display records like below,

```<code>sno val1  val2  value
1    2c    3e    1
2    2b    i7    1
3    2w    u9    1
4    18    e3    1
5    2c    3e    0 //because already listed
</code>```

I'm using normal while loop to show this structure, but I don't know weather the value is already listed or not..

Can anyone help

答:
One solution:

```<code>$listed = array();
while() // your loop
{
    if(in_array($uniq_id_of_your_item, $listed)) {
         continue;
    }
    $listed[] = $uniq_id_of_your_item;

    // rest of your code
}
</code>```

Second solution (better): you can limit that in SQL query

Title: PHP how to find the duplicates

Body:
I am using php and I want to display list of records from database.
Say for example, the following is the table structure

sno val1 val2 val3  amt
1    2c   3e   I    500
2    2b   i7   I    1500
3    2w   u9   I    0
4    18   e3   I    50
5    2c   3e   S    70

Now I want to display records like below,

sno val1  val2  value
1    2c    3e    1
2    2b    i7    1
3    2w    u9    1
4    18    e3    1
5    2c    3e    0 //because already listed

I'm using normal while loop to show this structure, but I don't know weather the value is already listed or not..

Can anyone help

Body:
One solution:

$listed = array();
while() // your loop
{
    if(in_array($uniq_id_of_your_item, $listed)) {
         continue;
    }
    $listed[] = $uniq_id_of_your_item;

    // rest of your code
}

Second solution (better): you can limit that in SQL query


问:
Angular 4 form validation on multiple fields
EDIT:
What I want to achieve is a validation on one single formControl and not the whole form. The validator should check all atom fields like house number, street etc. and then invalidate the google maps input control.

I am programming a form with Google Maps Autocomplete.
The user should enter a address into a input field that triggers the Google Maps autocomplete logic. When an address is selected the callback function selects the street, house number etc. and uses the API result to fill in the required address data fields.
The other form elements are displayed but readonly so we always get valid data and can perform validation on the inputs.

The problem is that my validator doesn't trigger the input field. The main input field is always valid and doesn't get the ng-invalid class.

```<code>@Component({
  selector: 'my-app',

  styles: [`
    .ng-valid {
      border:#0ff;
    }

    .ng-invalid {
      border:#f00;
    }
  `],
  template: `

  <form [formGroup]="testForm">
                <input type="text" formControlName="address">
                <input type="text" formControlName="tel">
                <input type="text" formControlName="mail">
            </form>
  `
})
export class AppComponent {
  testForm:FormGroup;

  constructor(private fb: FormBuilder) {
    this.testForm = this.fb.group({
            address:['', myValidator],
            tel:[''],
            mail:['']
        }, {
            validator: myValidator("tel", "mail")
        });
  }
}

export const myValidator = (field1, field2): ValidatorFn => (control: AbstractControl) => {
        if(control.get(field1).value=="test" && control.get(field2).value=="test2") {
            return null;
        }
        return { myValidator: { valid: false } };
    }
</code>```

I have made a punker of it so you can see it in action:
https://plnkr.co/edit/2kncVT6thQTU1HMCmyTy?p=preview

答:
I think your validation is correct you just have to show the message for the validation like this

```<code><form [formGroup]="testForm">
    <input type="text" formControlName="address">
    <input type="text" formControlName="tel">
    <input type="text" formControlName="mail">
</form>
<span *ngIf="!testForm.errors.myValidator">Incorrect<span>
</code>```

and in your validation use this

```<code>if(control.get(field1).value=="test" && control.get(field2).value=="test2") {
        return { myValidator: true  }
    }
    return  { myValidator: false  };
</code>```

Body:
EDIT:
What I want to achieve is a validation on one single formControl and not the whole form. The validator should check all atom fields like house number, street etc. and then invalidate the google maps input control.

I am programming a form with Google Maps Autocomplete.
The user should enter a address into a input field that triggers the Google Maps autocomplete logic. When an address is selected the callback function selects the street, house number etc. and uses the API result to fill in the required address data fields.
The other form elements are displayed but readonly so we always get valid data and can perform validation on the inputs.

The problem is that my validator doesn't trigger the input field. The main input field is always valid and doesn't get the ng-invalid class.

@Component({
  selector: 'my-app',

  styles: [`
    .ng-valid {
      border:#0ff;
    }

    .ng-invalid {
      border:#f00;
    }
  `],
  template: `

  <form [formGroup]="testForm">
                <input type="text" formControlName="address">
                <input type="text" formControlName="tel">
                <input type="text" formControlName="mail">
            </form>
  `
})
export class AppComponent {
  testForm:FormGroup;

  constructor(private fb: FormBuilder) {
    this.testForm = this.fb.group({
            address:['', myValidator],
            tel:[''],
            mail:['']
        }, {
            validator: myValidator("tel", "mail")
        });
  }
}

export const myValidator = (field1, field2): ValidatorFn => (control: AbstractControl) => {
        if(control.get(field1).value=="test" && control.get(field2).value=="test2") {
            return null;
        }
        return { myValidator: { valid: false } };
    }

I have made a punker of it so you can see it in action:
https://plnkr.co/edit/2kncVT6thQTU1HMCmyTy?p=preview

Body:
I think your validation is correct you just have to show the message for the validation like this

<form [formGroup]="testForm">
    <input type="text" formControlName="address">
    <input type="text" formControlName="tel">
    <input type="text" formControlName="mail">
</form>
<span *ngIf="!testForm.errors.myValidator">Incorrect<span>

and in your validation use this

if(control.get(field1).value=="test" && control.get(field2).value=="test2") {
        return { myValidator: true  }
    }
    return  { myValidator: false  };


问:
JQgrid show message before update and multiple update
I am working on JQgrid and trying to achieve some specific functionality. These functionalists are
1)inline update with message shown before update.
2)Multiple update

I tried to read jqgrid and got this code https://jsfiddle.net/OlegKi/byygepy3/11/ . Which is quite approximate to my requirement but it doesn't contain multiple update and message shown before update.

I tried to overwrite these code but maximum i reached is this https://jsfiddle.net/byygepy3/72/  but failed because multiple update only updating half of record and it doesn't show any message before updating either single row or multiple row.

code is inserting just allow me to ask question.

```<code>$(function () {
    var myData = [
            { id: 10, ParameterName: "Test", ParameterValue: "" },
            { id: 20, ParameterName: "Test 1", ParameterValue: "" },
            { id: 30, ParameterName: "Test 2", ParameterValue: "" },
            { id: 40, ParameterName: "Test 2", ParameterValue: "" },
            { id: 50, ParameterName: "Test 2", ParameterValue: "" },
            { id: 60, ParameterName: "Test 2", ParameterValue: "" }
        ],
        $grid = $("#list");

    // change the text displayed on editrules: {required: true }
    $.extend(true, $.jgrid.locales["en-US"].edit.msg, {
        required: "No value was entered for this parameter!!!"
    });

    $grid.jqGrid({
        datatype: "local",
        data: myData,
        colNames: ["", "Parameter Name", "Parameter Value"],
        colModel: [
            { name: "act", template: "actions" }, // optional feature
            { name: "ParameterName" },
            { name: "ParameterValue", editable: true,
                editoptions: { maxlength: 100 }, editrules: {required: true } }
        ],
        cmTemplate: { autoResizable: true },
        autoResizing: { compact: true },
        pager: true,
        pgbuttons: false,     // disable page control like next, back button
        pgtext: null,         // disable pager text like 'Page 0 of 10'
        viewrecords: true,    // disable current view record text like 'View 1-10 of 100'
        sortname: "Name",
        iconSet: "fontAwesome",
        caption: 'Parameters',
        autowidth: true,
        hidegrid: false,
        inlineEditing: {
            keys: true
        },
        singleSelectClickMode: "selectonly", // prevent unselect once selected rows
        beforeSelectRow: function (rowid) {
             // allow selection if saving successful
        },
        onSelectRow: function (rowid) {
            $(this).jqGrid("editRow", rowid);
        },
        afterSetRow: function (options) {
            var item = $(this).jqGrid("getLocalRow", options.rowid);
            if (item != null) {
                item.dirty = true;
            }
        },
        navOptions: {
            edit: false,
            add: false,
            search: false,
            deltext: "Delete",
            refreshtext: "Refresh"
        },
        inlineNavOptions: {
            save: false,
            savetext: "Save",
            cancel: false,
            restoreAfterSelect: false
        },
        formDeleting: {
            // delete options
            url: window.g_baseUrl + 'MfgTransactions_MVC/COA/Delete?',
            beforeSubmit: function () {
                // get value
                var selRowId = $(this).jqGrid('getGridParam', 'selrow');
                var parametricValue = $(this).jqGrid('getCell', selRowId, 'ParameterValue');

                // check if empty
                if (parametricValue === "") {
                    return [false, "Cannot delete: No value exists for this parameter"];
                }

                return [true, "Successfully deleted"];
            },
            delData: {
                batchId: function () {
                    return $("#BatchId").val();
                }
            },
            closeOnEscape: true,
            closeAfterDelete: true,
            width: 400,
            msg: "Are you sure you want to delete the Parameter?",
            afterComplete: function (response) {
                if (response.responseText) {
                    alert("response.responseText");
                }

                //loadBatchListIntoGrid();
            }
        }
    }).jqGrid('navGrid')
    .jqGrid('inlineNav')
    .jqGrid('navButtonAdd', {
        caption: "Save Changed",
        buttonicon: "fa-floppy-o",
        onClickButton: function () {
            var $self = $(this), i,
                // savedRows array is not empty if some row is in inline editing mode
                savedRows = $self.jqGrid("getGridParam", "savedRow");
            for (i = 0; i < savedRows.length; i++) {
                    $self.jqGrid("saveRow", savedRows[i].id);
            }

            var localData = $(this).jqGrid("getGridParam", "data"),
                dirtyData = $.grep(localData, function (item) {
                    return item.dirty;
                });
            alert(dirtyData.length > 0 ? JSON.stringify(dirtyData) : "no dirty data");
        }
    });

    // make more place for navigator buttons be rwducing the width of the right part
    var pagerIdSelector = $grid.jqGrid("getGridParam", "pager");
    $(pagerIdSelector + "_right").width(100);

    // make the grid responsive
    $(window).bind("resize", function () {
        $grid.jqGrid("setGridWidth", $grid.closest(".container-fluid").width());
    }).triggerHandler("resize");
});
</code>```

答:
Free jqGrid supports a lot of callbacks, which will be used during saving the rows. You can use for example beforeSaveRow callback of inline editing, custom validation via editrules.custom callback function, beforeSelectRow and other. Additionally, your code seems to distinguish the initial empty value "" of ParameterValue column from any other values. The final code you should made yourself. I posted an example

beforeSelectRow: function (rowid) {
    // allow selection if saving successful
    var $self = $(this), i,
        savedRows = $self.jqGrid("getGridParam", "savedRow");

    for (i = 0; i < savedRows.length; i++) {
        if (rowid !== savedRows[i].id) {
            if (allowSaving.call(this, savedRows[i].id)) {
                $self.jqGrid("saveRow", savedRows[i].id);
            } else {
                $self.jqGrid("restoreRow", savedRows[i].id);
            }
        }
    }
    return true;
},
```

<p>with <code>allowSaving</code> function defined as</p>

```var allowSaving = function (rowid) {
        var item = $(this).jqGrid("getRowData", rowid);
        if (item.ParameterValue !== "") {
            return confirm("Do you want to save \"" +
                        item.ParameterValue  + "\" value in \"" +
                        item.ParameterName + "\"?");
        } else {
            return false;
        }
    };
```

It allows to ask the user to confirm the changes of ParameterName. Additionally the code of "Save Changed" button should be adjusted too.

See https://jsfiddle.net/OlegKi/byygepy3/74/

Body:
I am working on JQgrid and trying to achieve some specific functionality. These functionalists are
1)inline update with message shown before update.
2)Multiple update

I tried to read jqgrid and got this code https://jsfiddle.net/OlegKi/byygepy3/11/ . Which is quite approximate to my requirement but it doesn't contain multiple update and message shown before update.

I tried to overwrite these code but maximum i reached is this https://jsfiddle.net/byygepy3/72/  but failed because multiple update only updating half of record and it doesn't show any message before updating either single row or multiple row.

code is inserting just allow me to ask question.

$(function () {
    var myData = [
            { id: 10, ParameterName: "Test", ParameterValue: "" },
            { id: 20, ParameterName: "Test 1", ParameterValue: "" },
            { id: 30, ParameterName: "Test 2", ParameterValue: "" },
            { id: 40, ParameterName: "Test 2", ParameterValue: "" },
            { id: 50, ParameterName: "Test 2", ParameterValue: "" },
            { id: 60, ParameterName: "Test 2", ParameterValue: "" }
        ],
        $grid = $("#list");

    // change the text displayed on editrules: {required: true }
    $.extend(true, $.jgrid.locales["en-US"].edit.msg, {
        required: "No value was entered for this parameter!!!"
    });

    $grid.jqGrid({
        datatype: "local",
        data: myData,
        colNames: ["", "Parameter Name", "Parameter Value"],
        colModel: [
            { name: "act", template: "actions" }, // optional feature
            { name: "ParameterName" },
            { name: "ParameterValue", editable: true,
                editoptions: { maxlength: 100 }, editrules: {required: true } }
        ],
        cmTemplate: { autoResizable: true },
        autoResizing: { compact: true },
        pager: true,
        pgbuttons: false,     // disable page control like next, back button
        pgtext: null,         // disable pager text like 'Page 0 of 10'
        viewrecords: true,    // disable current view record text like 'View 1-10 of 100'
        sortname: "Name",
        iconSet: "fontAwesome",
        caption: 'Parameters',
        autowidth: true,
        hidegrid: false,
        inlineEditing: {
            keys: true
        },
        singleSelectClickMode: "selectonly", // prevent unselect once selected rows
        beforeSelectRow: function (rowid) {
             // allow selection if saving successful
        },
        onSelectRow: function (rowid) {
            $(this).jqGrid("editRow", rowid);
        },
        afterSetRow: function (options) {
            var item = $(this).jqGrid("getLocalRow", options.rowid);
            if (item != null) {
                item.dirty = true;
            }
        },
        navOptions: {
            edit: false,
            add: false,
            search: false,
            deltext: "Delete",
            refreshtext: "Refresh"
        },
        inlineNavOptions: {
            save: false,
            savetext: "Save",
            cancel: false,
            restoreAfterSelect: false
        },
        formDeleting: {
            // delete options
            url: window.g_baseUrl + 'MfgTransactions_MVC/COA/Delete?',
            beforeSubmit: function () {
                // get value
                var selRowId = $(this).jqGrid('getGridParam', 'selrow');
                var parametricValue = $(this).jqGrid('getCell', selRowId, 'ParameterValue');

                // check if empty
                if (parametricValue === "") {
                    return [false, "Cannot delete: No value exists for this parameter"];
                }

                return [true, "Successfully deleted"];
            },
            delData: {
                batchId: function () {
                    return $("#BatchId").val();
                }
            },
            closeOnEscape: true,
            closeAfterDelete: true,
            width: 400,
            msg: "Are you sure you want to delete the Parameter?",
            afterComplete: function (response) {
                if (response.responseText) {
                    alert("response.responseText");
                }

                //loadBatchListIntoGrid();
            }
        }
    }).jqGrid('navGrid')
    .jqGrid('inlineNav')
    .jqGrid('navButtonAdd', {
        caption: "Save Changed",
        buttonicon: "fa-floppy-o",
        onClickButton: function () {
            var $self = $(this), i,
                // savedRows array is not empty if some row is in inline editing mode
                savedRows = $self.jqGrid("getGridParam", "savedRow");
            for (i = 0; i < savedRows.length; i++) {
                    $self.jqGrid("saveRow", savedRows[i].id);
            }

            var localData = $(this).jqGrid("getGridParam", "data"),
                dirtyData = $.grep(localData, function (item) {
                    return item.dirty;
                });
            alert(dirtyData.length > 0 ? JSON.stringify(dirtyData) : "no dirty data");
        }
    });

    // make more place for navigator buttons be rwducing the width of the right part
    var pagerIdSelector = $grid.jqGrid("getGridParam", "pager");
    $(pagerIdSelector + "_right").width(100);

    // make the grid responsive
    $(window).bind("resize", function () {
        $grid.jqGrid("setGridWidth", $grid.closest(".container-fluid").width());
    }).triggerHandler("resize");
});

Body:
Free jqGrid supports a lot of callbacks, which will be used during saving the rows. You can use for example beforeSaveRow callback of inline editing, custom validation via editrules.custom callback function, beforeSelectRow and other. Additionally, your code seems to distinguish the initial empty value "" of ParameterValue column from any other values. The final code you should made yourself. I posted an example

beforeSelectRow: function (rowid) {
    // allow selection if saving successful
    var $self = $(this), i,
        savedRows = $self.jqGrid("getGridParam", "savedRow");

    for (i = 0; i < savedRows.length; i++) {
        if (rowid !== savedRows[i].id) {
            if (allowSaving.call(this, savedRows[i].id)) {
                $self.jqGrid("saveRow", savedRows[i].id);
            } else {
                $self.jqGrid("restoreRow", savedRows[i].id);
            }
        }
    }
    return true;
},

with allowSaving function defined as

var allowSaving = function (rowid) {
        var item = $(this).jqGrid("getRowData", rowid);
        if (item.ParameterValue !== "") {
            return confirm("Do you want to save \"" +
                        item.ParameterValue  + "\" value in \"" +
                        item.ParameterName + "\"?");
        } else {
            return false;
        }
    };

It allows to ask the user to confirm the changes of ParameterName. Additionally the code of "Save Changed" button should be adjusted too.

See https://jsfiddle.net/OlegKi/byygepy3/74/


问:
Ruby string mutability
This may be a bit of a nooby question, I have been trying to get better at ruby recently, and started reading the fantastic The Ruby Programming Language. Something that was mentioned is that string literals are considered mutable, so in a loop it is better to use a variable then a literal, as a new string will get instantiated at every iteration.

My question is why? At first I thought it was because of interpolation, but symbols are immutable and they support interpolation. Coming from a static background, it doesn't really make much sense to me.

EDIT:

After reading thenduks answer, I think I may have it. AFAIK, languages like Java or C# don't have destructive string methods (they use upcase, but not upcase!). Because of things like upcase! or <<, the literal cannot be immutable.

Not 100% sure on that, the other possibility is that it is a compile-time interning that happens, which is something that just doesn't happen in a scripting language.

答:
Not really sure what exactly your question is, but consider the following code:

```<code>10.times { puts "abc".object_id }
</code>```

This prints out 10 different id's. Why? Just because you know this string wont change doesn't mean Ruby does. If you think that "abc" should only be created once then what happens if you do:

```<code>10.times { puts "abc".upcase! }
</code>```

The upcase! method mutates the string to be upper case, on the next iteration the string created in the first iteration isn't the same anymore.

Perhaps post a code example that is confusing to you?

OwnerDisplayName: Matt Briggs

ContentLicense: CC BY-SA 2.5

Title: Ruby string mutability

LastEditorDisplayName: Matt Briggs

Body:
Not really sure what exactly your question is, but consider the following code:

10.times { puts "abc".object_id }

This prints out 10 different id's. Why? Just because you know this string wont change doesn't mean Ruby does. If you think that "abc" should only be created once then what happens if you do:

10.times { puts "abc".upcase! }

The upcase! method mutates the string to be upper case, on the next iteration the string created in the first iteration isn't the same anymore.

Perhaps post a code example that is confusing to you?

OwnerDisplayName: thenduks


问:
How to split a sentence into multiple parts in Ruby
I want to split a main string and create multiples strings with the words obtained in Ruby.

```<code>str = "one two three four five"
</code>```

I want to create all these possibilities in an array of strings:

```<code>"one"
"one two"
"one two three"
"one two three four"
"one two three four five"
</code>```

but also:

```<code>"two three four five"
"three four five"
"four five"
"five"
</code>```

Ideally I would also obtain the strings inside too, but not required:

```<code>"two three four"
"two three"
"three four"
</code>```

I tried many things but difficult to have a best way to do that.

For example, I tried to work with each_slice:

```<code>words = string.split(" ")
        number_of_words = words.length
        max_number_of_slices = number_of_words
        array_of_strings_to_match = []
        number_of_slices = 1
        while (number_of_slices <= max_number_of_slices)
          array = words.each_slice(number_of_slices).map do |a| a.join ' ' end
          array.each do |w| array_of_strings_to_match << w end
          number_of_slices = number_of_slices + 1
        end
</code>```

But it's not the good way.

Any idea is welcome. :-)

This question is a little different from this one because I need to split a sentence of words, not a string by letters (even if it's quite the same).

答:
Based on a modified version of this answer:

```<code>def split_words(string)
  words = string.split
  (0..words.length).inject([]) do |ai,i|
    (1..words.length - i).inject(ai) { |aj,j| aj << words[i,j] }
  end.map { |words| words.join(' ') }.uniq
end
</code>```

Usage

```<code>str = "one two three four five"

split_words(str)
#=> ["one",
#    "one two",
#    "one two three",
#    "one two three four",
#    "one two three four five",
#    "two",
#    "two three",
#    "two three four",
#    "two three four five",
#    "three",
#    "three four",
#    "three four five",
#    "four",
#    "four five",
#    "five"]
</code>```

Body:
I want to split a main string and create multiples strings with the words obtained in Ruby.

str = "one two three four five"

I want to create all these possibilities in an array of strings:

"one"
"one two"
"one two three"
"one two three four"
"one two three four five"

but also:

"two three four five"
"three four five"
"four five"
"five"

Ideally I would also obtain the strings inside too, but not required:

"two three four"
"two three"
"three four"

I tried many things but difficult to have a best way to do that.

For example, I tried to work with each_slice:

words = string.split(" ")
        number_of_words = words.length
        max_number_of_slices = number_of_words
        array_of_strings_to_match = []
        number_of_slices = 1
        while (number_of_slices <= max_number_of_slices)
          array = words.each_slice(number_of_slices).map do |a| a.join ' ' end
          array.each do |w| array_of_strings_to_match << w end
          number_of_slices = number_of_slices + 1
        end

But it's not the good way.

Any idea is welcome. :-)

This question is a little different from this one because I need to split a sentence of words, not a string by letters (even if it's quite the same).

Body:
Based on a modified version of this answer:

def split_words(string)
  words = string.split
  (0..words.length).inject([]) do |ai,i|
    (1..words.length - i).inject(ai) { |aj,j| aj << words[i,j] }
  end.map { |words| words.join(' ') }.uniq
end

Usage

str = "one two three four five"

split_words(str)
#=> ["one",
#    "one two",
#    "one two three",
#    "one two three four",
#    "one two three four five",
#    "two",
#    "two three",
#    "two three four",
#    "two three four five",
#    "three",
#    "three four",
#    "three four five",
#    "four",
#    "four five",
#    "five"]


问:
unexpected response code 401 for URL
```<code>package com.example.murarilal.volley;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    RequestQueue queue;
    ListView listView;
    List<Hero> heroList;

    private String url="API_KEY";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         queue= Volley.newRequestQueue(this);
        home();

        listView = (ListView) findViewById(R.id.listView);
        heroList = new ArrayList<>();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
                intent.putExtra("description",url);
                startActivity(intent);
            }
        });
    }

    public void home()
    {
        JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONObject obj = new JSONObject(String.valueOf(response));

                    JSONArray array = obj.getJSONArray("articles");

                    for (int i = 0; i < array.length(); i++) {
                        Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
                        heroList.add(hero);
                    }

                    ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
                    listView.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);
    }
}

package com.example.murarilal.volley;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ArticleActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);
        String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";

        WebView webView=(WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());

        Intent intent=getIntent();
        webView.loadDataWithBaseURL(url,null,intent.getStringExtra("description"),"text/html","UTF-8");
        webView.loadUrl(url);
    }
}
</code>```

https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=d6eaad863cc640a7a6864d18196bea9e

I'm trying to fetch data from the above url but it returns an unexpected 401 response code. I checked the url and it's perfectly valid but the my code gives this error. when the emulator starts it shows blank activity

this the log error

11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
  W/System.err: com.android.volley.AuthFailureError 11-17 16:20:20.804
  14350-14350/com.example.murarilal.volley W/System.err:     at
  com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:141)
  11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
  W/System.err:     at
  com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)

答:
Try to use URLConnection instead of volley.
401 indicates of have Unauthorized access to the given URL

Title: unexpected response code 401 for URL

Body:
package com.example.murarilal.volley;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    RequestQueue queue;
    ListView listView;
    List<Hero> heroList;

    private String url="API_KEY";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         queue= Volley.newRequestQueue(this);
        home();

        listView = (ListView) findViewById(R.id.listView);
        heroList = new ArrayList<>();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
                intent.putExtra("description",url);
                startActivity(intent);
            }
        });
    }

    public void home()
    {
        JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONObject obj = new JSONObject(String.valueOf(response));

                    JSONArray array = obj.getJSONArray("articles");

                    for (int i = 0; i < array.length(); i++) {
                        Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
                        heroList.add(hero);
                    }

                    ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
                    listView.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);
    }
}

package com.example.murarilal.volley;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ArticleActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);
        String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";

        WebView webView=(WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());

        Intent intent=getIntent();
        webView.loadDataWithBaseURL(url,null,intent.getStringExtra("description"),"text/html","UTF-8");
        webView.loadUrl(url);
    }
}

https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=d6eaad863cc640a7a6864d18196bea9e

I'm trying to fetch data from the above url but it returns an unexpected 401 response code. I checked the url and it's perfectly valid but the my code gives this error. when the emulator starts it shows blank activity

this the log error

11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
  W/System.err: com.android.volley.AuthFailureError 11-17 16:20:20.804
  14350-14350/com.example.murarilal.volley W/System.err:     at
  com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:141)
  11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
  W/System.err:     at
  com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)


问:
Angular 1.5 - Insert custom element after last element with certain property
Let's assume I'm having following code:

```<code><li ng-repeat="task in todoList">
    {{task.name}}
</li>
</code>```

And let's assume this is my dataset ( Assuming it's ordered by when, from now to future ) :

```<code>var todoList = [ { name : 'Work hard', when : 'Today'}, { name : 'Play hard', when : 'Today'}, { name : 'Relax hard', when : 'This week'}, ]
</code>```

How can I detect in the ng-repeat when the current repeated item is the last item with the property when set to Today ?

So I'll end up something with something like this

```<code><li ng-repeat="task in todoList">
    {{task.name}}
</li>
<!-- If last of current period, then show this -->
<li>
    <h3>Next period</h3>
</li>
</code>```

答:
You can try grouping the data by when, and repeating on the result set:

```<code><ul ng-repeat="(when, tasks) in todoList | groupBy: 'when'">
  When: {{ when }}
  <li ng-repeat="task in tasks track by $index">
    <span ng-hide="$last">{{task.name}}</span>
    <h3 ng-show="$last">Next period</h3>
  </li>
</ul>
</code>```

Edit 1:

If you just want to show the data of Today, you can just filter out the todoList, and then render it:

```<code><li ng-repeat="task in todoList | filter:{ when: 'Today' }">
  <span ng-hide="$last">{{task.name}}</span>
  <h3 ng-show="$last">Next period</h3>
</li>
</code>```

Body:
Let's assume I'm having following code:

    {{task.name}}

And let's assume this is my dataset ( Assuming it's ordered by when, from now to future ) :

var todoList = [ { name : 'Work hard', when : 'Today'}, { name : 'Play hard', when : 'Today'}, { name : 'Relax hard', when : 'This week'}, ]

How can I detect in the ng-repeat when the current repeated item is the last item with the property when set to Today ?

So I'll end up something with something like this

    {{task.name}}

Next period

Body:
You can try grouping the data by when, and repeating on the result set:

<ul ng-repeat="(when, tasks) in todoList | groupBy: 'when'">
  When: {{ when }}
  <li ng-repeat="task in tasks track by $index">
    <span ng-hide="$last">{{task.name}}</span>
    <h3 ng-show="$last">Next period</h3>
  </li>
</ul>

Edit 1:

If you just want to show the data of Today, you can just filter out the todoList, and then render it:

<li ng-repeat="task in todoList | filter:{ when: 'Today' }">
  <span ng-hide="$last">{{task.name}}</span>
  <h3 ng-show="$last">Next period</h3>
</li>


问:
Is there any easy way to round a float with one digit number in objective c?
Yes. You are right. Of Course this is a duplicate question. Before flag my question, please continue reading below.

I want to round a float value, which is

```<code>56.6748939 to 56.7
56.45678 to 56.5
56.234589 to 56.2
</code>```

Actually it can be any number of decimal precisions. But I want to round it to nearest value. (If it is greater than or equal to 5, then round up and if not, then round down).

I can do that with the below code.

```<code>float value = 56.68899
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
[numberFormatter setMaximumFractionDigits:1];
[numberFormatter setRoundingMode:NSNumberFormatterRoundUp];

NSString *roundedString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:value]];
NSNumber *roundedNumber = [NSNumber numberFromString:roundedString];
float roundedValue = [roundedNumber floatValue];
</code>```

Above code looks like a long process. I have several numbers to round off. So this process is hard to convert a float value into NSNumber and to NSString and to NSNumber and to float.

Is there any other easy way to achieve what I asked ?

I still have a doubt in the above code. It says roundUp. So when it comes to roundDown, will it work?

答:
You can use </p>

```<code>[dictionaryTemp setObject:[NSString stringWithFormat:@"%.1f",averageRatingOfAllOrders] forKey:@"AvgRating"];
</code>```

<p>%.1f will give us value 2.1 only one digit after decimal point. </p>

Body:
Yes. You are right. Of Course this is a duplicate question. Before flag my question, please continue reading below.

I want to round a float value, which is

56.6748939 to 56.7
56.45678 to 56.5
56.234589 to 56.2

Actually it can be any number of decimal precisions. But I want to round it to nearest value. (If it is greater than or equal to 5, then round up and if not, then round down).

I can do that with the below code.

float value = 56.68899
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
[numberFormatter setMaximumFractionDigits:1];
[numberFormatter setRoundingMode:NSNumberFormatterRoundUp];

NSString *roundedString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:value]];
NSNumber *roundedNumber = [NSNumber numberFromString:roundedString];
float roundedValue = [roundedNumber floatValue];

Above code looks like a long process. I have several numbers to round off. So this process is hard to convert a float value into NSNumber and to NSString and to NSNumber and to float.

Is there any other easy way to achieve what I asked ?

I still have a doubt in the above code. It says roundUp. So when it comes to roundDown, will it work?

Body:
You can use

[dictionaryTemp setObject:[NSString stringWithFormat:@"%.1f",averageRatingOfAllOrders] forKey:@"AvgRating"];

%.1f will give us value 2.1 only one digit after decimal point.


问:
stanford core nlp -- "last year" not recognized as a date
I am running Stanford Core NLP locally and comparing the results with the web interface at http://http://corenlp.run/. For the test sentence, "The economy grew by 2% last year", the web interface identifies "last year" as a date entity.
NER

But my local instance fails to recognize "last year" as a date:

```<code>{'after': ' ',
  'before': ' ',
  'characterOffsetBegin': 23,
  'characterOffsetEnd': 27,
  'index': 7,
  'lemma': 'last',
  'ner': **'O'**,
  'originalText': 'Last',
  'pos': 'JJ',
  'word': 'Last'},
 {'after': '',
  'before': ' ',
  'characterOffsetBegin': 28,
  'characterOffsetEnd': 32,
  'index': 8,
  'lemma': 'year',
  'ner': **'O'**,
  'originalText': 'Year',
  'pos': 'NN',
  'word': 'Year'}
</code>```

Strangely, if I change "last year" to "last month", "last month" does get recognized by my local instance as a date.

```<code>{'after': ' ',
  'before': ' ',
  'characterOffsetBegin': 23,
  'characterOffsetEnd': 27,
  'index': 7,
  'lemma': 'last',
  'ner': **'DATE'**,
  'normalizedNER': 'Last Month ',
  'originalText': 'Last',
  'pos': 'JJ',
  'word': 'Last'},
 {'after': '',
  'before': ' ',
  'characterOffsetBegin': 28,
  'characterOffsetEnd': 33,
  'index': 8,
  'lemma': 'Month',
  'ner': **'DATE'**,
  'normalizedNER': 'Last Month ',
  'originalText': 'Month',
  'pos': 'NNP',
  'word': 'Month'}
</code>```

Help with understanding and resolving this will be appreciated!!

答:
If I use the latest code from GitHub with the latest models, and run this command:

```<code>java -Xmx8g edu.stanford.nlp.pipeline.StanfordCoreNLP -annotators tokenize,ssplit,pos,lemma,ner -file example-1.txt -outputFormat text
</code>```

On your example, I find "last year" marked as date.  I would presume this is true for 3.8.0 as well.

Body:
I am running Stanford Core NLP locally and comparing the results with the web interface at http://http://corenlp.run/. For the test sentence, "The economy grew by 2% last year", the web interface identifies "last year" as a date entity.
NER

But my local instance fails to recognize "last year" as a date:

{'after': ' ',
  'before': ' ',
  'characterOffsetBegin': 23,
  'characterOffsetEnd': 27,
  'index': 7,
  'lemma': 'last',
  'ner': **'O'**,
  'originalText': 'Last',
  'pos': 'JJ',
  'word': 'Last'},
 {'after': '',
  'before': ' ',
  'characterOffsetBegin': 28,
  'characterOffsetEnd': 32,
  'index': 8,
  'lemma': 'year',
  'ner': **'O'**,
  'originalText': 'Year',
  'pos': 'NN',
  'word': 'Year'}

Strangely, if I change "last year" to "last month", "last month" does get recognized by my local instance as a date.

{'after': ' ',
  'before': ' ',
  'characterOffsetBegin': 23,
  'characterOffsetEnd': 27,
  'index': 7,
  'lemma': 'last',
  'ner': **'DATE'**,
  'normalizedNER': 'Last Month ',
  'originalText': 'Last',
  'pos': 'JJ',
  'word': 'Last'},
 {'after': '',
  'before': ' ',
  'characterOffsetBegin': 28,
  'characterOffsetEnd': 33,
  'index': 8,
  'lemma': 'Month',
  'ner': **'DATE'**,
  'normalizedNER': 'Last Month ',
  'originalText': 'Month',
  'pos': 'NNP',
  'word': 'Month'}

Help with understanding and resolving this will be appreciated!!

Body:
If I use the latest code from GitHub with the latest models, and run this command:

java -Xmx8g edu.stanford.nlp.pipeline.StanfordCoreNLP -annotators tokenize,ssplit,pos,lemma,ner -file example-1.txt -outputFormat text

On your example, I find "last year" marked as date.  I would presume this is true for 3.8.0 as well.


问:
Remove all
 If does not contain "test" in text
I am making a chrome extension for the first time and need a little help with my Javascript.

In my popup menu I want a few buttons. Once someone presses this button lets say button "test". I want it to remove every single
 whom does not contain the word "test".

I am making this because the filter functionality on this website I use a lot is very slow. This way I can filter faster myself by removing the rows instead of the program searching through all of them.

This is what I have so far:

var searchString = 'TEST';
$("#tbody tr td:contains('" + searchString + "')").each(function Tester() {
  if ($(this).text() != searchString) {
    $(this).parent().remove();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Remove all rows which don't contain:</p>
<button onclick="Tester()">TEST</button></code>```

答:
Firstly don't use inline JS. It's bad practice. Attach event handlers using unobtrusive JS instead.

To fix your actual issue, use the :contains selector along remove(), something like this:

$('button').click(function() {
  var searchString = $(this).text();
  $("#tbody tr td:contains('" + searchString + "')").closest('tr').remove();
});```
<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>
<p>Remove all rows which don't contain:</p>
<button>TEST</button>

<table>
  <tbody id="tbody">
    <tr>
      <td>TEST</td>
    </tr>
    <tr>
      <td>Foo</td>
    </tr>
    <tr>
      <td>TEST</td>
    </tr>
    <tr>
      <td>Bar</td>
    </tr>
  </tbody>
</table></code>```

Title: Remove all <tr> If does not contain "test" in text

Body:
I am making a chrome extension for the first time and need a little help with my Javascript.

In my popup menu I want a few buttons. Once someone presses this button lets say button "test". I want it to remove every single
 whom does not contain the word "test".

I am making this because the filter functionality on this website I use a lot is very slow. This way I can filter faster myself by removing the rows instead of the program searching through all of them.

This is what I have so far:

var searchString = 'TEST';
$("#tbody tr td:contains('" + searchString + "')").each(function Tester() {
  if ($(this).text() != searchString) {
    $(this).parent().remove();
  }
});

Remove all rows which don't contain:

<button onclick="Tester()">TEST</button>

Body:
Firstly don't use inline JS. It's bad practice. Attach event handlers using unobtrusive JS instead.

To fix your actual issue, use the :contains selector along remove(), something like this:

$('button').click(function() {
  var searchString = $(this).text();
  $("#tbody tr td:contains('" + searchString + "')").closest('tr').remove();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Remove all rows which don't contain:</p>
<button>TEST</button>

<table>
  <tbody id="tbody">
    <tr>
      <td>TEST</td>
    </tr>
    <tr>
      <td>Foo</td>
    </tr>
    <tr>
      <td>TEST</td>
    </tr>
    <tr>
      <td>Bar</td>
    </tr>
  </tbody>
</table>


问:
React-Native: Getting exception: invokeGuardedCallbackAndCatchFirstError

In my application there is common action defined to call a specific API.

This action/API can get called from different tabs / internal screens of tabs.

I am getting the exception, when I called action from one tab and tried accessing same action from another tab for same API.

As per the input params, this same API response with two different outputs.

There is an exception occurring while making second call from another tab. In error, it seems that the second call trying to access the output parameters which are actually expected for first call.

Question: Is there any issue while using same same Actions across multiple places simultaneously? Do I need to create/duplicate Actions for each tabs/calls?

React Info:
    "axios": "^0.16.2",
    "react": "16.0.0-alpha.12",
    "react-native": "0.47.1",

PFA image to see the exception messages

答:
Thanks Eduard , but we just got the solution. The issue was arising due to wrong references used at UI components.

e.g.

```<code>render()
{
  onTapped = this.props.onTapped
  return (
  <View>
    <GridView
     ...
     renderItem={this.renderItem}
     .../>
  </View>
  );
 }
</code>```

AND
the 'this.renderItem' functions was:

```<code>renderItem(item)
{
 onPress={() => onTapped(item)}
}
</code>```

We just replaced, onTapped(item) with "this.props.onTapped(item)" AND used ES6 syntax to define method "renderItem = (item) => {}"

Closing the thread, as this issue is resolved now.

Body:
Thanks Eduard , but we just got the solution. The issue was arising due to wrong references used at UI components.

e.g.

render()
{
  onTapped = this.props.onTapped
  return (
  <View>
    <GridView
     ...
     renderItem={this.renderItem}
     .../>
  </View>
  );
 }

AND
the 'this.renderItem' functions was:

renderItem(item)
{
 onPress={() => onTapped(item)}
}

We just replaced, onTapped(item) with "this.props.onTapped(item)" AND used ES6 syntax to define method "renderItem = (item) => {}"

Closing the thread, as this issue is resolved now.


问:
Custom Content Element with IRRE via Typoscript -> empty array
i have a little problem getting a custom content element via typoscript on all pages.
i´ve created a custom element without any extensions (like mask or dce) so im only using
TYPO3 core functions. This Element is a simple thingy that just uses irre for creating
different boxes to be displayed in the frontend.

```<code>tt_content.box = COA
tt_content.box {
    10 = FLUIDTEMPLATE
    10 {
        file = EXT:xxx_elements/Resources/Private/Templates/Box.html
        partialRootPath = EXT:xxx_setup/Resources/Private/Content/Partials
        layoutRootPath = EXT:xxx_setup/Resources/Private/Content/Layouts
        dataProcessing {
            10 = TYPO3\CMS\Frontend\DataProcessing\DatabaseQueryProcessor
            10 {
                table = tx_xxxelements_box
                orderBy = sorting
                where {
                    data = field:uid
                    intval = 1
                    wrap = tt_content=|
                }
                as = boxitems
            }
        }
    }
}
</code>```

rendered with normal fluid like

```<code><f:for each="{boxitems}" as="boxitem">
  <boxitem.header>...
</f:for>
</code>```

so everything works fine as long as i use it as a regular content element that is placed
on a page. now i put one element into a storagefolder and try to reuse this element on all pages via typoscript
where 10 is the ID of the content element

```<code>lib.SubFooter = COA
lib.SubFooter {
    10 = RECORDS
    10 {
        tables = tt_content
        source = 10
    }
}
</code>```

the lib is rendered correct, but the "boxitems" array is empty on all pages :-(

now the funny part:
if i place the element with ID 10 on a page the boxitems array is filled for both element and lib...

Here is an image with the variable dump for different situations:
element, lib, element+lib

答:
maybe you're missing the pid ;-)

```<code>    dataProcessing {
        10 = TYPO3\CMS\Frontend\DataProcessing\DatabaseQueryProcessor
        10 {
            ....
            pidInList.field = pid
</code>```

and you can simplify in my opinion in this case the where clause:

```<code>            where.dataWrap = tt_content={field:uid}
</code>```

because you're not matching against vars from outside...

Body:
i have a little problem getting a custom content element via typoscript on all pages.
i´ve created a custom element without any extensions (like mask or dce) so im only using
TYPO3 core functions. This Element is a simple thingy that just uses irre for creating
different boxes to be displayed in the frontend.

tt_content.box = COA
tt_content.box {
    10 = FLUIDTEMPLATE
    10 {
        file = EXT:xxx_elements/Resources/Private/Templates/Box.html
        partialRootPath = EXT:xxx_setup/Resources/Private/Content/Partials
        layoutRootPath = EXT:xxx_setup/Resources/Private/Content/Layouts
        dataProcessing {
            10 = TYPO3\CMS\Frontend\DataProcessing\DatabaseQueryProcessor
            10 {
                table = tx_xxxelements_box
                orderBy = sorting
                where {
                    data = field:uid
                    intval = 1
                    wrap = tt_content=|
                }
                as = boxitems
            }
        }
    }
}

rendered with normal fluid like

<f:for each="{boxitems}" as="boxitem">
  <boxitem.header>...
</f:for>

so everything works fine as long as i use it as a regular content element that is placed
on a page. now i put one element into a storagefolder and try to reuse this element on all pages via typoscript
where 10 is the ID of the content element

lib.SubFooter = COA
lib.SubFooter {
    10 = RECORDS
    10 {
        tables = tt_content
        source = 10
    }
}

the lib is rendered correct, but the "boxitems" array is empty on all pages :-(

now the funny part:
if i place the element with ID 10 on a page the boxitems array is filled for both element and lib...

Here is an image with the variable dump for different situations:
element, lib, element+lib

Body:
maybe you're missing the pid ;-)

    dataProcessing {
        10 = TYPO3\CMS\Frontend\DataProcessing\DatabaseQueryProcessor
        10 {
            ....
            pidInList.field = pid

and you can simplify in my opinion in this case the where clause:

            where.dataWrap = tt_content={field:uid}

because you're not matching against vars from outside...


问:
how prevent the parent click event on change a checkbox
I have a checkbox inside a parent container which has a click event, whenever I try to click the checkbox parent click works first and following by the change event, I am using e.stopPropagation(); on both the parent and child events, but still, it's not working

```<code>// make the .parent react
 function grandParent(){
    alert('Grand Parent: You hit me, my child or my grand child, now deal with me!');
}

// make the .parent react
$('.parent').on('click', function(e){
    e.stopPropagation()
    alert('Parent : Don\'t you dare hitting me or my child, again!');
});

// make the child cry, when we hit him.
$('.child').on('click', function(e){
e.stopPropagation();
 alert('Child : waaaaaa waaaa waa huh huh waaa waaaa!');
});

$('.hello').on('change', function(e){
e.stopPropagation();
 alert('checkbox clicked');
});
</code>```

Fiddle example

答:
Sequence of the event matters , where the click event occurs first and Change event the next ,So in your case you need to change the type of event handling to Click click here to see the sequence / priority of events happening after clicking on check box

```<code>$('.hello').on('click change', function(e){
e.stopPropagation();
 alert('checkbox '+e.type);
});
</code>```

Body:
I have a checkbox inside a parent container which has a click event, whenever I try to click the checkbox parent click works first and following by the change event, I am using e.stopPropagation(); on both the parent and child events, but still, it's not working

// make the .parent react
 function grandParent(){
    alert('Grand Parent: You hit me, my child or my grand child, now deal with me!');
}

// make the .parent react
$('.parent').on('click', function(e){
    e.stopPropagation()
    alert('Parent : Don\'t you dare hitting me or my child, again!');
});

// make the child cry, when we hit him.
$('.child').on('click', function(e){
e.stopPropagation();
 alert('Child : waaaaaa waaaa waa huh huh waaa waaaa!');
});

$('.hello').on('change', function(e){
e.stopPropagation();
 alert('checkbox clicked');
});

Fiddle example

Body:
Sequence of the event matters , where the click event occurs first and Change event the next ,So in your case you need to change the type of event handling to Click click here to see the sequence / priority of events happening after clicking on check box

$('.hello').on('click change', function(e){
e.stopPropagation();
 alert('checkbox '+e.type);
});


问:
Google Cloud and Go creating instances
thanks for looking at my post. i need to create an Linux instance with go lang and display the created public IP on the webpage.</p>

答:
You should look at http://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/making-requests.html and then calling DescribeInstances (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html), should give you the public IP address.

Some pointers which may help here (haven't used these): https://gist.github.com/stephen-mw/9f289d724c4cfd3c88f2 and http://www.heystephenwood.com/search/label/aws

Hope this helps.

Title: Google Cloud and Go creating instances


问:
How to create a rectangle with two rounded corners?
I need to create a rectangle view with two rounded corners using canvas.I used drawRoundRect but i am getting rectangle with four rounded corners.Please anyone suggest me a way that can be helpful in solving my problem.</p>

```<code> rect = new RectF(left, top, right, bottom);

 canvas.drawRoundRect(rect, 20, 20, facePaint);
</code>```

答:
Use this :-</p>

```<code>// Initialize a new Bitmap
                Bitmap bitmap = Bitmap.createBitmap(
                        600, // Width
                        300, // Height
                        Bitmap.Config.ARGB_8888 // Config
                );

                // Initialize a new Canvas instance
                Canvas canvas = new Canvas(bitmap);

                // Draw a solid color on the canvas as background
                canvas.drawColor(Color.WHITE);

                // Initialize a new Paint instance to draw the rounded rectangle
                Paint paint = new Paint();
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(Color.RED);
                paint.setAntiAlias(true);

                // Set an offset value in pixels to draw rounded rectangle on canvas
                int offset = 50;

                /*
                    public RectF (float left, float top, float right, float bottom)
                        Create a new rectangle with the specified coordinates. Note: no range
                        checking is performed, so the caller must ensure that
                        left <= right and top <= bottom.

                    Parameters
                        left  The X coordinate of the left side of the rectangle
                        top  The Y coordinate of the top of the rectangle
                        right  The X coordinate of the right side of the rectangle
                        bottom  The Y coordinate of the bottom of the rectangle
                */
                // Initialize a new RectF instance
                RectF rectF = new RectF(
                        offset, // left
                        offset, // top
                        canvas.getWidth() - offset, // right
                        canvas.getHeight() - offset // bottom
                );

                /*
                    public void drawRoundRect (RectF rect, float rx, float ry, Paint paint)
                        Draw the specified round-rect using the specified paint. The roundrect
                        will be filled or framed based on the Style in the paint.

                    Parameters
                        rect : The rectangular bounds of the roundRect to be drawn
                        rx : The x-radius of the oval used to round the corners
                        ry : The y-radius of the oval used to round the corners
                        paint : The paint used to draw the roundRect
                */

                // Define the corners radius of rounded rectangle
                int cornersRadius = 25;

                // Finally, draw the rounded corners rectangle object on the canvas
                canvas.drawRoundRect(
                        rectF, // rect
                        cornersRadius, // rx
                        cornersRadius, // ry
                        paint // Paint
                );

                // Display the newly created bitmap on app interface
                mImageView.setImageBitmap(bitmap);
</code>```

Body:
I need to create a rectangle view with two rounded corners using canvas.I used drawRoundRect but i am getting rectangle with four rounded corners.Please anyone suggest me a way that can be helpful in solving my problem.

 rect = new RectF(left, top, right, bottom);

 canvas.drawRoundRect(rect, 20, 20, facePaint);

Body:
Use this :-

// Initialize a new Bitmap
                Bitmap bitmap = Bitmap.createBitmap(
                        600, // Width
                        300, // Height
                        Bitmap.Config.ARGB_8888 // Config
                );

                // Initialize a new Canvas instance
                Canvas canvas = new Canvas(bitmap);

                // Draw a solid color on the canvas as background
                canvas.drawColor(Color.WHITE);

                // Initialize a new Paint instance to draw the rounded rectangle
                Paint paint = new Paint();
                paint.setStyle(Paint.Style.FILL);
                paint.setColor(Color.RED);
                paint.setAntiAlias(true);

                // Set an offset value in pixels to draw rounded rectangle on canvas
                int offset = 50;

                /*
                    public RectF (float left, float top, float right, float bottom)
                        Create a new rectangle with the specified coordinates. Note: no range
                        checking is performed, so the caller must ensure that
                        left <= right and top <= bottom.

                    Parameters
                        left  The X coordinate of the left side of the rectangle
                        top  The Y coordinate of the top of the rectangle
                        right  The X coordinate of the right side of the rectangle
                        bottom  The Y coordinate of the bottom of the rectangle
                */
                // Initialize a new RectF instance
                RectF rectF = new RectF(
                        offset, // left
                        offset, // top
                        canvas.getWidth() - offset, // right
                        canvas.getHeight() - offset // bottom
                );

                /*
                    public void drawRoundRect (RectF rect, float rx, float ry, Paint paint)
                        Draw the specified round-rect using the specified paint. The roundrect
                        will be filled or framed based on the Style in the paint.

                    Parameters
                        rect : The rectangular bounds of the roundRect to be drawn
                        rx : The x-radius of the oval used to round the corners
                        ry : The y-radius of the oval used to round the corners
                        paint : The paint used to draw the roundRect
                */

                // Define the corners radius of rounded rectangle
                int cornersRadius = 25;

                // Finally, draw the rounded corners rectangle object on the canvas
                canvas.drawRoundRect(
                        rectF, // rect
                        cornersRadius, // rx
                        cornersRadius, // ry
                        paint // Paint
                );

                // Display the newly created bitmap on app interface
                mImageView.setImageBitmap(bitmap);


问:
Is there a central SPARQL endpoint for the semantic web
We are going to have the semantic web. Now we have LOD cloud.

Every data set has its own SPARQL endpoint.

I can query the dataset triples.

How can I query the whole semantic web or LOD?

答:
There exists a W3C-owned and (un-?)maintained wiki page with ~60 SPARQL endpoints. Many "last accessed/checked" entries are from 2010. On that page is a link to http://sparqles.ai.wu.ac.at/availability which lists more endpoints and is much more recent and up-to-date.

Read the 2nd paragraphs titled "SPARQL Endpoints" of the blogpost Querying DBpedia with GraphQL for a skeptical view of the state of SPARQL today. Cannot say it any better myself.

Also note that SPARQL permits every endpoint to offer any number of "named GRAPH" constructs that can be queried at that endpoint. So that is another  feature more to consider.


问:
Android Studio - Implement Methods and parameter names
Java compiler does not preserve parameter names for any interface, unless newer compiler option -parameter is used (I am not sure how to use it with android studio) - refer example below.

Since java compiler does not preserve parameters names,  Android Studio "code -> implement methods" is not able to generate code with original parameter names.

The question is, how to implement a library module so that Android Studio Menu, Code->Implement Methods correctly generates code with all the original parameter names.

For example, following is a simple class and an interface. This class is in a separate aar module. When application uses this AAR, implements TablaListener and asks AndroidStudio to generate interface methods stubs, the parameter names are not preserved.

Please note that proguard is NOT used.

Any ideas?

```<code>public class TablaCore {

    public interface TablaListener {
        /**
         * @param params
         * @param data
         * @return
         */
        boolean TablaCore_onAction(String params, byte[] data);
    }

    private static TablaListener mListener = null;
    public static void setListener(TablaListener myListener) {
        mListener = myListener;
    }

    public TablaListener getListener() {
        return mListener;
    }

}
</code>```

It is easy to demonstrate by compiling and decompiling above class. This is decompiled version

```<code>public class TablaCore
{
  private static TablaListener mListener = null;

  public static void setListener(TablaListener myListener)
  {
    mListener = myListener;
  }

  public TablaListener getListener()
  {
    return mListener;
  }

  public static abstract interface TablaListener
  {
    public abstract boolean TablaCore_onAction(String paramMessageParams, byte[] paramArrayOfByte);

  }
}
</code>```

答:
You have to include Android SDK source code.

Go to: File > Settings... > Apperance & Behavior > System Settings > Android SDK

On the tab SDK Platforms select Show Package Details and find and select appropriate Sources for Android XX. Unfortunately, currently for Android API 27, there is no sources, but there is for Sources for Android 26. Apply changes - the download window should appear automatically.

After downloading and restarting implementing methods should use proper names for method parameters.

Body:
Java compiler does not preserve parameter names for any interface, unless newer compiler option -parameter is used (I am not sure how to use it with android studio) - refer example below.

Since java compiler does not preserve parameters names,  Android Studio "code -> implement methods" is not able to generate code with original parameter names.

The question is, how to implement a library module so that Android Studio Menu, Code->Implement Methods correctly generates code with all the original parameter names.

For example, following is a simple class and an interface. This class is in a separate aar module. When application uses this AAR, implements TablaListener and asks AndroidStudio to generate interface methods stubs, the parameter names are not preserved.

Please note that proguard is NOT used.

Any ideas?

public class TablaCore {

    public interface TablaListener {
        /**
         * @param params
         * @param data
         * @return
         */
        boolean TablaCore_onAction(String params, byte[] data);
    }

    private static TablaListener mListener = null;
    public static void setListener(TablaListener myListener) {
        mListener = myListener;
    }

    public TablaListener getListener() {
        return mListener;
    }

}

It is easy to demonstrate by compiling and decompiling above class. This is decompiled version

public class TablaCore
{
  private static TablaListener mListener = null;

  public static void setListener(TablaListener myListener)
  {
    mListener = myListener;
  }

  public TablaListener getListener()
  {
    return mListener;
  }

  public static abstract interface TablaListener
  {
    public abstract boolean TablaCore_onAction(String paramMessageParams, byte[] paramArrayOfByte);

  }
}


问:
Selenium Webdriver error: An item with the same key has already been added
Can someone advice me how to prevent this error: "An item with the same key has already been added."?

I have two tests that runs fine when run individually, but when I "run all" in visual studio, I get that error.

```<code>[Binding]
public sealed class Steps
{
    private Squish squish = new Squish();
    private Tools tools = new Tools();

    [Given(@"I navigated to the Squish homepage")]
    public void GivenINavigatedToTheSquishHomepage()
    {
        squish.NavigateToURL("Squish.com");
        ScenarioContext.Current["siteTitle"] = squish.GetPageTitle();
    }
</code>```

Is there any alternatives to FeatureContext.Current.Add(key, value)? So I don't have to be directly be storing anything?

答:
I guess you should read specflow documentation about parallel test runs http://specflow.org/documentation/Parallel-Execution/
It's said:

You may not be using the static context properties
  ScenarioContext.Current, FeatureContext.Current or
  ScenarioStepContext.Current.

Actually your error is self-descriptive - you've created item in dictionary with key "siteTitle"

Body:
Can someone advice me how to prevent this error: "An item with the same key has already been added."?

I have two tests that runs fine when run individually, but when I "run all" in visual studio, I get that error.

[Binding]
public sealed class Steps
{
    private Squish squish = new Squish();
    private Tools tools = new Tools();

    [Given(@"I navigated to the Squish homepage")]
    public void GivenINavigatedToTheSquishHomepage()
    {
        squish.NavigateToURL("Squish.com");
        ScenarioContext.Current["siteTitle"] = squish.GetPageTitle();
    }

Is there any alternatives to FeatureContext.Current.Add(key, value)? So I don't have to be directly be storing anything?


问:
When i ionic app build at that time build is successful but when i emulate with android at that time give following error
When i ionic app build at that time build is successful but when i emulate with android at that time give following error

```<code>D:/Demo-Projects/tabsapp/platforms/android/build/outputs/apk/android-debug.apk:
1 file pushed. 1.2 MB/s (4213012 bytes in 3.437s)

        pkg: /data/local/tmp/android-debug.apk enter code here

Failure [INSTALL_FAILED_OLDER_SDK]

rm failed for -f, Read-only file system

**[ERROR] An error occurred while running cordova emulate android (exit code 1).**
</code>```

advance thanks a lot please help me i am stuck here.

答:
The error INSTALL_FAILED_OLDER_SDK means that your app is built with a minimum version of android that is higher than the version of android of your emulator.

The error happens when the app is deployed to the device/emulator, after the apk is built.

To solve the issue, either use an emulator running a newer version of android or change the minimum sdk version of the app.

You can configure the minimum sdk version in config.xml:

```<code>...
<platform name="android">
    <preference name="android-minSdkVersion" value="16" />
</platform>
...
</code>```

Here we set the minSDK to 16, you have to adjust depending on the minimum version you want to cover.

If you already have a platform name="android" section in your config.xml just add the preference line, if not, add the section.

Body:
When i ionic app build at that time build is successful but when i emulate with android at that time give following error

D:/Demo-Projects/tabsapp/platforms/android/build/outputs/apk/android-debug.apk:
1 file pushed. 1.2 MB/s (4213012 bytes in 3.437s)

        pkg: /data/local/tmp/android-debug.apk enter code here

Failure [INSTALL_FAILED_OLDER_SDK]

rm failed for -f, Read-only file system

**[ERROR] An error occurred while running cordova emulate android (exit code 1).**

advance thanks a lot please help me i am stuck here.

Body:
The error INSTALL_FAILED_OLDER_SDK means that your app is built with a minimum version of android that is higher than the version of android of your emulator.

The error happens when the app is deployed to the device/emulator, after the apk is built.

To solve the issue, either use an emulator running a newer version of android or change the minimum sdk version of the app.

You can configure the minimum sdk version in config.xml:

...
<platform name="android">
    <preference name="android-minSdkVersion" value="16" />
</platform>
...

Here we set the minSDK to 16, you have to adjust depending on the minimum version you want to cover.

If you already have a platform name="android" section in your config.xml just add the preference line, if not, add the section.


问:
Open graph protocol not working in whatsapp
I Follow the below open graph meta tags to show thumbnail on sharing.
It works perfectly in facebook but not in whatsapp</p>

```<code>  <meta property="og:site_name" content="Hahaa haa">
  <meta property="og:title" content="Haaha haa - Music Player" />
  <meta property="og:url" content="http://13.126.57.106/aiyoapp/public/" />
  <meta property="og:description" content="Haaha haa Music Player is used to share">
  <meta property="og:image" itemprop="image"  content="http://13.126.57.106/aiyoapp/public/images/ha_thumb.png">
  <meta property="og:type" content="website" />
</code>```

答:
I have had the same problem, everything worked fine in any opengraph testing tool and in the social sites themself's: facebook, twitter, ok, vk but in whatsapp & telegram not.

So after a lot of research, the problem was in our virtual site firewall that protects from site crawling by many logics, a couple of them is IP and User-Agent. The whatsapp & telegram are pinging sites to fetch og data are not throw their servers like social sites, but through your mobile operator's dynamic IP, but the user-agent is of the messenger itself, and it was in our automatically generated blacklist.

Check if you don't ban access to your site by theirs user-agents string that contains: WhatsApp/2.17.395 A or TelegramBot (like TwitterBot)

Wish it helped.

Body:
I Follow the below open graph meta tags to show thumbnail on sharing.
It works perfectly in facebook but not in whatsapp

  <meta property="og:site_name" content="Hahaa haa">
  <meta property="og:title" content="Haaha haa - Music Player" />
  <meta property="og:url" content="http://13.126.57.106/aiyoapp/public/" />
  <meta property="og:description" content="Haaha haa Music Player is used to share">
  <meta property="og:image" itemprop="image"  content="http://13.126.57.106/aiyoapp/public/images/ha_thumb.png">
  <meta property="og:type" content="website" />