问:
VBA error caused by iterating past expected stopping point
Background:
I am attempting to convert an old style of managing departments, facilities, and job titles at work to a new more convenient lookup table style format. Right now each set of data for new departments, facilities, and job titles are stored on separate sheets (a couple per week) and the sheet name is a date.

The issue:
The program runs fine for the majority of the workbook; however, I eventually get a

1004 - Application-defined or objected-defined error

When debugging, I find that my row value has to 1,048,577 and therefore caused the error. I am unsure how the iterating value is escaping my handling of it.

The code:

```<code>Sub cleanUp()

Dim wks As Worksheet
Dim wksNum As Long
Dim destWks As Worksheet
Dim rng As Range
Dim row As Long
Dim col As Long
Dim destRow As Long
Dim lastRow As Long
Dim itemType As String

Set destWks = ActiveWorkbook.Sheets("new")
destRow = 2

For wksNum = 1 To ActiveWorkbook.Sheets.Count
NextWks:
    Set wks = ActiveWorkbook.Worksheets(wksNum)

    If wks.Name = "new" Then
        wksNum = wksNum + 1
        GoTo NextWks
    End If

    lastRow = wks.Cells(wks.Rows.Count, 1).End(xlUp).row

    For row = 1 To lastRow
NextRow:
            Select Case wks.Cells(row, 1).Value
                Case "New Hospitals"
                    itemType = "Hospital"
                    row = row + 1
                    GoTo NextRow
                Case "New Departments"
                    itemType = "Department"
                    row = row + 1
                    GoTo NextRow
                Case "New Job Titles"
                    itemType = "Job Title"
                    row = row + 1
                    GoTo NextRow
                Case "none"
                    row = row + 1
                    GoTo NextRow
                Case ""
                    row = row + 1
                    GoTo NextRow
            End Select
            destWks.Cells(destRow, 1).Value = wks.Name
            destWks.Cells(destRow, 2).Value = itemType
            wks.Range("A" & row & ":C" & row).Copy destWks.Range("C" & destRow)
            destRow = destRow + 1
    Next row

Next wksNum

End Sub
</code>```

Example Sheet:

```<code>New Hospitals
None

New Departments
10 146 7205-DeptA
10 193 9178-DeptB

New Job Titles
004315  JobTitleA
</code>```

A side question:
Is there a more elegant way of skipping to the next iteration of a for loop without using a GoTo statement. My thoughts are that these are causing my issue.

Thank you for any and all help.

答:
The problem is if your data on any sheet ends with either of the group headings or none then it will start an eternal loop adding 1 to row until it reaches a row number that is not supported by the worksheet.

You have taken the loop outside the For Loop and so it does not stop.

It is better to test for the opposite and do the code instead of using the archaic Goto.

Use this:

```<code>Sub cleanUp()

Dim wks As Worksheet
Dim wksNum As Long
Dim destWks As Worksheet
Dim rng As Range
Dim row As Long
Dim col As Long
Dim destRow As Long
Dim lastRow As Long
Dim itemType As String

Set destWks = ActiveWorkbook.Sheets("new")
destRow = 2

For wksNum = 1 To ActiveWorkbook.Sheets.Count
    Set wks = ActiveWorkbook.Worksheets(wksNum)

    If wks.Name <> "new" Then
        lastRow = wks.Cells(wks.Rows.Count, 1).End(xlUp).row

        For row = 1 To lastRow
            Select Case wks.Cells(row, 1).Value
                Case "New Hospitals", "New Departments", "New Job Titles"
                    itemType = Replace(wks.Cells(row, 1).Value, "New ", "")
                Case "None", ""
                Case Else
                    destWks.Cells(destRow, 1).Value = wks.Name
                    destWks.Cells(destRow, 2).Value = itemType
                    wks.Range("A" & row & ":C" & row).Copy destWks.Range("C" & destRow)
                    destRow = destRow + 1
            End Select

        Next row
    End If
Next wksNum

End Sub
</code>```

Edited to simplify Select Case based on Scott Holtzman's now deleted answer

Output with provided data:

Body:
Background:
I am attempting to convert an old style of managing departments, facilities, and job titles at work to a new more convenient lookup table style format. Right now each set of data for new departments, facilities, and job titles are stored on separate sheets (a couple per week) and the sheet name is a date.

The issue:
The program runs fine for the majority of the workbook; however, I eventually get a

1004 - Application-defined or objected-defined error

When debugging, I find that my row value has to 1,048,577 and therefore caused the error. I am unsure how the iterating value is escaping my handling of it.

The code:

Sub cleanUp()

Dim wks As Worksheet
Dim wksNum As Long
Dim destWks As Worksheet
Dim rng As Range
Dim row As Long
Dim col As Long
Dim destRow As Long
Dim lastRow As Long
Dim itemType As String

Set destWks = ActiveWorkbook.Sheets("new")
destRow = 2

For wksNum = 1 To ActiveWorkbook.Sheets.Count
NextWks:
    Set wks = ActiveWorkbook.Worksheets(wksNum)

    If wks.Name = "new" Then
        wksNum = wksNum + 1
        GoTo NextWks
    End If

    lastRow = wks.Cells(wks.Rows.Count, 1).End(xlUp).row

    For row = 1 To lastRow
NextRow:
            Select Case wks.Cells(row, 1).Value
                Case "New Hospitals"
                    itemType = "Hospital"
                    row = row + 1
                    GoTo NextRow
                Case "New Departments"
                    itemType = "Department"
                    row = row + 1
                    GoTo NextRow
                Case "New Job Titles"
                    itemType = "Job Title"
                    row = row + 1
                    GoTo NextRow
                Case "none"
                    row = row + 1
                    GoTo NextRow
                Case ""
                    row = row + 1
                    GoTo NextRow
            End Select
            destWks.Cells(destRow, 1).Value = wks.Name
            destWks.Cells(destRow, 2).Value = itemType
            wks.Range("A" & row & ":C" & row).Copy destWks.Range("C" & destRow)
            destRow = destRow + 1
    Next row

Next wksNum

End Sub

Example Sheet:

New Hospitals
None

New Departments
10 146 7205-DeptA
10 193 9178-DeptB

New Job Titles
004315  JobTitleA

A side question:
Is there a more elegant way of skipping to the next iteration of a for loop without using a GoTo statement. My thoughts are that these are causing my issue.

Thank you for any and all help.

Body:
The problem is if your data on any sheet ends with either of the group headings or none then it will start an eternal loop adding 1 to row until it reaches a row number that is not supported by the worksheet.

You have taken the loop outside the For Loop and so it does not stop.

It is better to test for the opposite and do the code instead of using the archaic Goto.

Use this:

Sub cleanUp()

Dim wks As Worksheet
Dim wksNum As Long
Dim destWks As Worksheet
Dim rng As Range
Dim row As Long
Dim col As Long
Dim destRow As Long
Dim lastRow As Long
Dim itemType As String

Set destWks = ActiveWorkbook.Sheets("new")
destRow = 2

For wksNum = 1 To ActiveWorkbook.Sheets.Count
    Set wks = ActiveWorkbook.Worksheets(wksNum)

    If wks.Name <> "new" Then
        lastRow = wks.Cells(wks.Rows.Count, 1).End(xlUp).row

        For row = 1 To lastRow
            Select Case wks.Cells(row, 1).Value
                Case "New Hospitals", "New Departments", "New Job Titles"
                    itemType = Replace(wks.Cells(row, 1).Value, "New ", "")
                Case "None", ""
                Case Else
                    destWks.Cells(destRow, 1).Value = wks.Name
                    destWks.Cells(destRow, 2).Value = itemType
                    wks.Range("A" & row & ":C" & row).Copy destWks.Range("C" & destRow)
                    destRow = destRow + 1
            End Select

        Next row
    End If
Next wksNum

End Sub

Edited to simplify Select Case based on Scott Holtzman's now deleted answer

Output with provided data:


来源: stackexchange

问:
If clause optimization
I need to write an IF clause (we're using Java 8). The relevant variables are group, privilege, role, level and class. There is an action that needs to be performed in certain case. I've written the alghoritm in the following way:

```<code>if (group == G1) {
  if (privilege == P1) {
    // Perform the action if a user has this particular privilege
    perform_action_and_exit();
  } else {
    if (role == R1) {
      if ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3))) {
        perform_action_and_exit();
      }
      // Ignore other combinations of level and class
    }
    // Ignore other roles
  }
} else {
  // Perform the action for any group other than G1
  perform_action_and_exit();
}
</code>```

Is there a cleaner way to write this condition?

Thanks.

答:
the code seems messy, you've repeated the perform_action_and_exit(); three times. think of single responsibility.

```<code>//all the code should be replaced by this:
if(should_perform_action_and_exit()){
   perform_action_and_exit();
}
....
</code>```

then create methods/class (whatever fits the purpose better) for each action

```<code>boolean should_perform_action_and_exit(){

   return groupCheck() || privilageCheck() || roleCheck();

}
</code>```

now the last three methods:

```<code>boolean groupCheck(){
   return group != G1;
}

boolean privilageCheck(){
   return privilege == P1;
}

boolean roleCheck(){
   return (role == R1)  &&  ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3)));
}
</code>```

the above might look like more code, but the readability is improved for later.

ContentLicense: CC BY-SA 3.0

Title: If clause optimization

Body:
I need to write an IF clause (we're using Java 8). The relevant variables are group, privilege, role, level and class. There is an action that needs to be performed in certain case. I've written the alghoritm in the following way:

if (group == G1) {
  if (privilege == P1) {
    // Perform the action if a user has this particular privilege
    perform_action_and_exit();
  } else {
    if (role == R1) {
      if ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3))) {
        perform_action_and_exit();
      }
      // Ignore other combinations of level and class
    }
    // Ignore other roles
  }
} else {
  // Perform the action for any group other than G1
  perform_action_and_exit();
}

Is there a cleaner way to write this condition?

Thanks.

Body:
the code seems messy, you've repeated the perform_action_and_exit(); three times. think of single responsibility.

//all the code should be replaced by this:
if(should_perform_action_and_exit()){
   perform_action_and_exit();
}
....

then create methods/class (whatever fits the purpose better) for each action

boolean should_perform_action_and_exit(){

   return groupCheck() || privilageCheck() || roleCheck();

}

now the last three methods:

boolean groupCheck(){
   return group != G1;
}

boolean privilageCheck(){
   return privilege == P1;
}

boolean roleCheck(){
   return (role == R1)  &&  ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3)));
}

the above might look like more code, but the readability is improved for later.


问:
Extract not sending WHERE conditions to SQL Server in DI Studio
I have a Job where I want to bring rows over from a SQL Server data source to a SAS data set.

In my Extract task, I have a condition applied as follows:

datepart(LastUpdated) eq '14Nov2017'd;

This connects to a SQL Server view which we'll call vw.Sales.

When I check what is running on the SQL instance, it looks like it is selecting the WHOLE of the view, which is 650+ million rows.  Obviously I don't want that all brought into work and then  filtered down.

Unless I am missing something and that what I can see as the running query is the subselect, can anyone identify how I can ensure my WHERE condition is passed through to SQL correctly?

答:
It is very likely that SAS is indeed doing a 'SELECT *' on the table and processing your query on the SAS server rather than having your SQL server executing the query.

The reason is that SAS does not know how to translate your query to SQL server language likely because of the datepart function.

Your options are either to rewrite that query to something that SAS will be able to translate or to do your extract with explicit pass-through in a 'custom code' node.

As far as rewriting goes, you could maybe try something like:

```<code>where '14NOV2017:00:00:00'dt le lastupdated lt '15NOV2017:00:00:00'dt
</code>```

Body:
It is very likely that SAS is indeed doing a 'SELECT *' on the table and processing your query on the SAS server rather than having your SQL server executing the query.

The reason is that SAS does not know how to translate your query to SQL server language likely because of the datepart function.

Your options are either to rewrite that query to something that SAS will be able to translate or to do your extract with explicit pass-through in a 'custom code' node.

As far as rewriting goes, you could maybe try something like:

where '14NOV2017:00:00:00'dt le lastupdated lt '15NOV2017:00:00:00'dt


问:
getting the name of the form tag from an HTML element within a directive
I'm getting the ngModel name, but I also want to get the name of the form to which the element with the "validacion" directive belongs.

I strictly need to get the name of the form to which the HTML element belongs. I can have several forms so I need a dynamic solution. thank you very much

```<code>.directive('validacion', function ($timeout,$rootScope,validacionCampos,$compile) {

      return {
          restrict: 'AE',
          require: 'ngModel',

          link: function (scope, element, attrs, ngModel) {
                  if (!ngModel){
                          console.log("no hay modal")
                  return;
          }
</code>```

答:
The following code should fetch you the value of name attribute of the form to which the validacion element belongs:

```<code>link: function (scope, element, attrs, ngModel) {
    console.log(element.closest('form').attr('name'));
  }
</code>```

EDIT If jQuery is not there in the project, use the parent() function instead, provided that the directive element is the direct child of the <form> tag:

```<code>link: function (scope, element, attrs, ngModel) {
    console.log(element.parent().attr('name'));
  }
</code>```

Body:
I'm getting the ngModel name, but I also want to get the name of the form to which the element with the "validacion" directive belongs.

I strictly need to get the name of the form to which the HTML element belongs. I can have several forms so I need a dynamic solution. thank you very much

.directive('validacion', function ($timeout,$rootScope,validacionCampos,$compile) {

      return {
          restrict: 'AE',
          require: 'ngModel',

          link: function (scope, element, attrs, ngModel) {
                  if (!ngModel){
                          console.log("no hay modal")
                  return;
          }

Body:
The following code should fetch you the value of name attribute of the form to which the validacion element belongs:

link: function (scope, element, attrs, ngModel) {
    console.log(element.closest('form').attr('name'));
  }

EDIT If jQuery is not there in the project, use the parent() function instead, provided that the directive element is the direct child of the <form> tag:

link: function (scope, element, attrs, ngModel) {
    console.log(element.parent().attr('name'));
  }


问:
Finding the count of  Jquery
I have the following HTML structure and I wanted to find out the length of immediate s. here is the code that I am using:-

```<code><table class="PrintTable">
    <tr>
      **<td>**
        <table>
            <thead>
                <tr><th>Type Of Transaction</th></tr>
            </thead>
            <tbody>
                <tr>
                    <td>Name</td>
                </tr>
                <tr>
                    <td>Age</td>
                </tr>
            </tbody>
        </table>
      </td>
      **<td>**
        <table>
            <thead>
                <tr><th>2006</th></tr>
            </thead>
            <tbody>
                <tr>
                    <td>Andi</td>
                </tr>
                <tr>
                    <td>25</td>
                </tr>
            </tbody>
        </table>
      </td>

    </tr>
</table>
</code>```

The function that I am using to find out the length of td is

```<code>function getBody(element)
{
    var divider=2;
    var originalTable=element.clone();
    var tds = $(originalTable).children('tr').children('td').length;
    alert(tds);

}
</code>```

The result I am seeing is 0. No clue at all. I am expecting 2. Any help will be appreciated.

答:
This should work:

```<code>var itemsCount = $(".PrintTable > tr > td").length;
</code>```

Update:

I just realized that at least Chrome inserts
 if it isn't already present, so to get cross browser support:

```<code>var itemsCount = $(".PrintTable > tbody > tr > td, .PrintTable > tr > td").length;
</code>```

Example: http://jsfiddle.net/H2JWS/

ContentLicense: CC BY-SA 2.5

Title: Finding the count of <td> Jquery

Body:
I have the following HTML structure and I wanted to find out the length of immediate s. here is the code that I am using:-

      ****

Type Of Transaction

                    Name

                    Age

      ****

2006

                    Andi

                    25

The function that I am using to find out the length of td is

function getBody(element)
{
    var divider=2;
    var originalTable=element.clone();
    var tds = $(originalTable).children('tr').children('td').length;
    alert(tds);

}

The result I am seeing is 0. No clue at all. I am expecting 2. Any help will be appreciated.

Body:
This should work:

var itemsCount = $(".PrintTable > tr > td").length;

Update:

I just realized that at least Chrome inserts <tbody> if it isn't already present, so to get cross browser support:

var itemsCount = $(".PrintTable > tbody > tr > td, .PrintTable > tr > td").length;

Example: http://jsfiddle.net/H2JWS/


问:
EditText constantly returns Empty - Android
I'm attempting to null check an EditText (which should be simple enough) however each time I enter text into my two ET's - they always return as empty: "" and they should not (if they have text in them).

I've looked over several other SO articles related to this and none of the fixes seem to resolve the issue.

Can anyone spot what I might be doing wrong in this instance?

Source Snippet:

Java class:

...

```<code>public void doneClicked(View v) throws JSONException {

    LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v1 = li.inflate(R.layout.profile_notification_settings_list_edit, null);

    final EditText label = (EditText) v1.findViewById(R.id.emaillabel);
    final EditText value = (EditText) v1.findViewById(R.id.emailvalue);

    String sValue = value.getText().toString();
    if (sValue.matches("")) {
        Toast.makeText(this, "You did not enter a value", Toast.LENGTH_SHORT).show();
        return;
    }

    String sLabel = label.getText().toString();
    if (sLabel.matches("")) {
        Toast.makeText(this, "You did not enter a label", Toast.LENGTH_SHORT).show();
        return;
    }
</code>```

...

Adapter:

```<code>@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
    view = inflater.inflate(R.layout.profile_notification_settings_list_edit, null);
    EditText value = (EditText) view.findViewById(R.id.emailvalue);
    value.setHint("Value");
    value.setText(valueList[i]);

    EditText label = (EditText) view.findViewById(R.id.emaillabel);
    if (labelList != null)
        label.setHint("Label");
    label.setText(labelList[i]);
</code>```

Full source:

Java Class:

https://pastebin.com/y1e9J1yE

Adapter:

https://pastebin.com/Zqh3eCAk

答:
Because everytime you click you are creating a new view which has nothing to do with the views currently being displayed on the screen

```<code>public void doneClicked(View v) throws JSONException {

    // don't inflate new views
    LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v1 = li.inflate(R.layout.profile_notification_settings_list_edit, null);

    final EditText label = (EditText) v1.findViewById(R.id.emaillabel);
    final EditText value = (EditText) v1.findViewById(R.id.emailvalue);

    // ... code
</code>```

Note : you cannot directly fetch the data from rowItemVies from ListView , so you need to add method in your adapter class to get the selected position through which you can fetch the rowView using yourListView.getChildAt(position) and further fetch data from children in rowView

Body:
I'm attempting to null check an EditText (which should be simple enough) however each time I enter text into my two ET's - they always return as empty: "" and they should not (if they have text in them).

I've looked over several other SO articles related to this and none of the fixes seem to resolve the issue.

Can anyone spot what I might be doing wrong in this instance?

Source Snippet:

Java class:

...

public void doneClicked(View v) throws JSONException {

    LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v1 = li.inflate(R.layout.profile_notification_settings_list_edit, null);

    final EditText label = (EditText) v1.findViewById(R.id.emaillabel);
    final EditText value = (EditText) v1.findViewById(R.id.emailvalue);

    String sValue = value.getText().toString();
    if (sValue.matches("")) {
        Toast.makeText(this, "You did not enter a value", Toast.LENGTH_SHORT).show();
        return;
    }

    String sLabel = label.getText().toString();
    if (sLabel.matches("")) {
        Toast.makeText(this, "You did not enter a label", Toast.LENGTH_SHORT).show();
        return;
    }

...

Adapter:

@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
    view = inflater.inflate(R.layout.profile_notification_settings_list_edit, null);
    EditText value = (EditText) view.findViewById(R.id.emailvalue);
    value.setHint("Value");
    value.setText(valueList[i]);

    EditText label = (EditText) view.findViewById(R.id.emaillabel);
    if (labelList != null)
        label.setHint("Label");
    label.setText(labelList[i]);

Full source:

Java Class:

https://pastebin.com/y1e9J1yE

Adapter:

https://pastebin.com/Zqh3eCAk

Body:
Because everytime you click you are creating a new view which has nothing to do with the views currently being displayed on the screen

public void doneClicked(View v) throws JSONException {

    // don't inflate new views
    LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v1 = li.inflate(R.layout.profile_notification_settings_list_edit, null);

    final EditText label = (EditText) v1.findViewById(R.id.emaillabel);
    final EditText value = (EditText) v1.findViewById(R.id.emailvalue);

    // ... code

Note : you cannot directly fetch the data from rowItemVies from ListView , so you need to add method in your adapter class to get the selected position through which you can fetch the rowView using yourListView.getChildAt(position) and further fetch data from children in rowView


问:
Checkbox value set with jquery not showing in POST
I've been looking for over an hour on the net, nothing showed up. I got some simple checkboxes, with a litle trick to style them, the classic hidden attribute and the label with the style. Nothing fancy.
All I want is to send those checkboxes values/checked status through POST for proccesing.
The problem is that whenever I change those values with jQuery, onClick, the inspector showes the changes, but in POST the input is not there anymore.
I've tried setting the "checked" attribute with $.prop(). It worked for the inspector, but didn't worked on POST.
Then I've changed to using values, setting all checkboxes as "checked" and changing the values with jQuery from 1 to 0 and back.
The inspector showes the values changing, but the POST shows nothing.

Here the HTML form :

```<code><form action="./ajax/process.php" enctype="multipart/form-data" method="post" id="admEmailParameteres1">
                    <input type="hidden" name="procesare" value="adm-process-parameters">

                    <input type="checkbox" id="sendConfEmailToClient" name="sendConfEmailToClient" value="<?= ($options['email_conf'] == 1 ? 1:0) ?>" class="hidden" checked>
                    <label for="sendConfEmailToClient" class="as-link tip label" onClick="toggleCheckSimple(this)" title="Trimite email de confirmare catre client la plasarea comenzii."><i class="fa fa-check label-check <?= ($options['email_conf'] == 1 ? 'active':'') ?>"></i> Client - email de confirmare la plasarea comenzii</label><br>

                    <input type="checkbox" id="sendAdvConfEmailToClient" name="sendAdvConfEmailToClient" value="<?= ($options['email_conf_sumar'] == 1 ? 1:0) ?>" class="hidden" checked>
                    <label for="sendAdvConfEmailToClient" class="as-link tip label" onClick="toggleCheckSimple(this)" title="Adauga si sumarul comenzii la email-ul de confirmare, trimis catre client la plasarea comenzii."><i class="fa fa-check label-check <?= ($options['email_conf_sumar'] == 1 ? 'active':'') ?>"></i> Client - adauga sumarul la email, la plasarea comenzii</label><br>

                    <input type="submit" class="btn btn-sm btn-success mb-5 " value="Salveaza modificarile" data-form="admEmailParameteres">
                </form>
</code>```

Here's the JS code:

```<code>function toggleCheckSimple(el){
$(el).find('.label-check').toggleClass('active');
var trg = $(el).attr('for');
if($('#'+trg).val() == 1){
    $('input[name="'+trg+'"]').val(0);
}else{
    $('input[name="'+trg+'"]').val(1);
}
</code>```

}

And in the PHP side, if I call:

```<code>echo '```';
        print_r($_POST);
        echo '```';
</code>```

The checkboxes are not there if they were changed with jQuery. If you don't touch them, they are there. Extremely strange adn upseting for me, as I am not a beginer. Can't figure this out.

答:
```<code><label for="myId"></label>
<input type="checkbox" id="myId">
</code>```

When you give a label the id of another element as it's for attribute, then if the user clicks on that label, it will act as if the user clicked on the other element.  In this way you can make clicking a label toggle checkboxes, select radio buttons, or give focus to an associated text field.  Making this logic a part of a javascript method is unnecessary.

Ref. https://html.spec.whatwg.org/multipage/forms.html#the-label-element

Body:
I've been looking for over an hour on the net, nothing showed up. I got some simple checkboxes, with a litle trick to style them, the classic hidden attribute and the label with the style. Nothing fancy.
All I want is to send those checkboxes values/checked status through POST for proccesing.
The problem is that whenever I change those values with jQuery, onClick, the inspector showes the changes, but in POST the input is not there anymore.
I've tried setting the "checked" attribute with $.prop(). It worked for the inspector, but didn't worked on POST.
Then I've changed to using values, setting all checkboxes as "checked" and changing the values with jQuery from 1 to 0 and back.
The inspector showes the values changing, but the POST shows nothing.

Here the HTML form :

<form action="./ajax/process.php" enctype="multipart/form-data" method="post" id="admEmailParameteres1">
                    <input type="hidden" name="procesare" value="adm-process-parameters">

                    <input type="checkbox" id="sendConfEmailToClient" name="sendConfEmailToClient" value="<?= ($options['email_conf'] == 1 ? 1:0) ?>" class="hidden" checked>
                    <i class="fa fa-check label-check <?= ($options['email_conf'] == 1 ? 'active':'') ?>"> Client - email de confirmare la plasarea comenzii

                    <input type="checkbox" id="sendAdvConfEmailToClient" name="sendAdvConfEmailToClient" value="<?= ($options['email_conf_sumar'] == 1 ? 1:0) ?>" class="hidden" checked>
                    <i class="fa fa-check label-check <?= ($options['email_conf_sumar'] == 1 ? 'active':'') ?>"> Client - adauga sumarul la email, la plasarea comenzii

                    <input type="submit" class="btn btn-sm btn-success mb-5 " value="Salveaza modificarile" data-form="admEmailParameteres">
                </form>

Here's the JS code:

function toggleCheckSimple(el){
$(el).find('.label-check').toggleClass('active');
var trg = $(el).attr('for');
if($('#'+trg).val() == 1){
    $('input[name="'+trg+'"]').val(0);
}else{
    $('input[name="'+trg+'"]').val(1);
}

}

And in the PHP side, if I call:

echo '
';
        print_r($_POST);
        echo '
';

The checkboxes are not there if they were changed with jQuery. If you don't touch them, they are there. Extremely strange adn upseting for me, as I am not a beginer. Can't figure this out.

Body:
<label for="myId"></label>
<input type="checkbox" id="myId">

When you give a label the id of another element as it's for attribute, then if the user clicks on that label, it will act as if the user clicked on the other element.  In this way you can make clicking a label toggle checkboxes, select radio buttons, or give focus to an associated text field.  Making this logic a part of a javascript method is unnecessary.

Ref. https://html.spec.whatwg.org/multipage/forms.html#the-label-element


问:
Try - Catch Laravel on Index function
Hi everyone

I've a question, and it's about Try - Catch, I've a function where I've 3 variables, from two differents models. The problem is, when the model don't have any records in DB, I try redirect the user from the home page, but dind't work, !important, one function had a request for an ajax function inside the view; here my code:

This one is with Try and Catch

```<code>try
      {
        $events = Event::all();
        $competitions = Competition::orderBy('id', 'DESC')->get();
        $ultimos = Event::orderBy('id', 'DESC')->paginate(5);

        if ($request->ajax()) {
            return Response::json(\View::make('events.partials.last', array('ultimos' => $ultimos))->render());
        }

        return View('events.index', compact('events', 'ultimos', 'competitions'));
      } catch (\Exception $e) {
          return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
      }
</code>```

I used also and IF and ELSE, like this one:

```<code>public function show_events(Request $request)
    {
      $events = Event::all();
      if($events) {
        $competitions = Competition::orderBy('id', 'DESC')->get();
        $ultimos = Event::orderBy('id', 'DESC')->paginate(5);

        if ($request->ajax()) {
            return Response::json(\View::make('events.partials.last', array('ultimos' => $ultimos))->render());
        }

        return View('events.index', compact('events', 'ultimos', 'competitions'));

      } else {
        return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
      }
    }
</code>```

But didn't work to, if someone can help me, I'll be really gratefull!

答:
You can use the count method of the collections like this :

```<code>public function show_events(Request $request)
    {
      $events = Event::all();
      if($events->count() > 0) {
        $competitions = Competition::orderBy('id', 'DESC')->get();
        $ultimos = Event::orderBy('id', 'DESC')->paginate(5);

        if ($request->ajax()) {
            return Response::json(\View::make('events.partials.last', array('ultimos' => $ultimos))->render());
        }

        return View('events.index', compact('events', 'ultimos', 'competitions'));

      } else {
        return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
      }
    }
</code>```

For the try catch it will not work because there no exception to catch here except if you throw one using the count method one more time like this

```<code>try {
    $events = Event::all();
    if($events->count() > 0) {
        throw new Exception("Ha ocurrido un errror, lo sentimos");
    }
    $competitions = Competition::orderBy('id', 'DESC')->get();
    $ultimos = Event::orderBy('id', 'DESC')->paginate(5);

    if ($request->ajax()) {
        return Response::json(\View::make('events.partials.last', array('ultimos' => $ultimos))->render());
    }

    return View('events.index', compact('events', 'ultimos', 'competitions'));
} catch (\Exception $e) {
    return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
}
</code>```

Title: Try - Catch Laravel on Index function

Body:
Hi everyone

I've a question, and it's about Try - Catch, I've a function where I've 3 variables, from two differents models. The problem is, when the model don't have any records in DB, I try redirect the user from the home page, but dind't work, !important, one function had a request for an ajax function inside the view; here my code:

This one is with Try and Catch

try
      {
        $events = Event::all();
        $competitions = Competition::orderBy('id', 'DESC')->get();
        $ultimos = Event::orderBy('id', 'DESC')->paginate(5);

        if ($request->ajax()) {
            return Response::json(\View::make('events.partials.last', array('ultimos' => $ultimos))->render());
        }

        return View('events.index', compact('events', 'ultimos', 'competitions'));
      } catch (\Exception $e) {
          return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
      }

I used also and IF and ELSE, like this one:

public function show_events(Request $request)
    {
      $events = Event::all();
      if($events) {
        $competitions = Competition::orderBy('id', 'DESC')->get();
        $ultimos = Event::orderBy('id', 'DESC')->paginate(5);

        if ($request->ajax()) {
            return Response::json(\View::make('events.partials.last', array('ultimos' => $ultimos))->render());
        }

        return View('events.index', compact('events', 'ultimos', 'competitions'));

      } else {
        return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
      }
    }

But didn't work to, if someone can help me, I'll be really gratefull!

Body:
You can use the count method of the collections like this :

public function show_events(Request $request)
    {
      $events = Event::all();
      if($events->count() > 0) {
        $competitions = Competition::orderBy('id', 'DESC')->get();
        $ultimos = Event::orderBy('id', 'DESC')->paginate(5);

        if ($request->ajax()) {
            return Response::json(\View::make('events.partials.last', array('ultimos' => $ultimos))->render());
        }

        return View('events.index', compact('events', 'ultimos', 'competitions'));

      } else {
        return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
      }
    }

For the try catch it will not work because there no exception to catch here except if you throw one using the count method one more time like this

try {
    $events = Event::all();
    if($events->count() > 0) {
        throw new Exception("Ha ocurrido un errror, lo sentimos");
    }
    $competitions = Competition::orderBy('id', 'DESC')->get();
    $ultimos = Event::orderBy('id', 'DESC')->paginate(5);

    if ($request->ajax()) {
        return Response::json(\View::make('events.partials.last', array('ultimos' => $ultimos))->render());
    }

    return View('events.index', compact('events', 'ultimos', 'competitions'));
} catch (\Exception $e) {
    return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
}


问:
Javascript Replace All words
I need to replace all the words in a DOM (web page in memory) using jquery and javascript.
I need to transform this:

```<code><html>
<head>
    Hi to all
</head>
<body>
    Hi to all
</body>
</html>
</code>```

Into this:

```<code><html>
    <head>
        Bye to all
    </head>
    <body>
        Bye to all
    </body>
</html>
</code>```

But without modifying the tags (ONLY THE VALUES IN THERE)

One try is:

```<code>jQuery.fn.replaceEachOne = function (objective, rep) {
    return this.each( function(){
                $(this).html( $(this).html().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
            }
        );
}
</code>```

But it continue replacing the tag values and breaks the page if I put it.

Help!!!

答:
Im guessing that there are going to be other elements in the header rather then just replacing everything with the new text. Try out something like this</p>

```<code>$(function(){
  var element = $('body, head').find('*:contains("Hi to all")');
  element.html('Bye to all');
});
</code>```

Title: Javascript Replace All words

Body:
I need to replace all the words in a DOM (web page in memory) using jquery and javascript.
I need to transform this:

    Hi to all

    Hi to all

Into this:

        Bye to all

        Bye to all

But without modifying the tags (ONLY THE VALUES IN THERE)

One try is:

jQuery.fn.replaceEachOne = function (objective, rep) {
    return this.each( function(){
                $(this).html( $(this).html().replace( new RegExp('(\\s'+objective+'\\s(?![[\\w\\s?&.\\/;#~%"=-]*>]))', "ig"), rep) );
            }
        );
}

But it continue replacing the tag values and breaks the page if I put it.

Help!!!

Body:
Im guessing that there are going to be other elements in the header rather then just replacing everything with the new text. Try out something like this

$(function(){
  var element = $('body, head').find('*:contains("Hi to all")');
  element.html('Bye to all');
});


问:
Select data in single row for multi records of an ID from table
I have the following table in PostgreSQL database

I want a query that can produce following results.

Thank you

答:
Try this - </p>

```<code>SELECT record_id
      ,MAX(CASE WHEN Node = 'A' THEN state) END AS A
      ,MAX(CASE WHEN Node = 'B' THEN state) END AS B
      ,MAX(CASE WHEN Node = 'C' THEN state) END AS C
FROM YOUR_TABLE
GROUP BY record_id
</code>```

Body:
Try this -

SELECT record_id
      ,MAX(CASE WHEN Node = 'A' THEN state) END AS A
      ,MAX(CASE WHEN Node = 'B' THEN state) END AS B
      ,MAX(CASE WHEN Node = 'C' THEN state) END AS C
FROM YOUR_TABLE
GROUP BY record_id


问:
Regex to get text BETWEEN two characters
PLEASE READ CAREFULLY:  This is a bit unusual and you will be tempted to say things like "that isn't how to use a regex" or "dude, just use String.SubString()," Etc...

I have a need to write a regex (to use a pre-existing method) that will match text BETWEEN curly braces, BUT NOT the curly braces themselves.

For Example: "{MatchThisText}" AND "La la la {MatchThisText} la la la..."

Should Both Match: "MatchThisText"

Someone asked this exact question a year ago, and he got a bunch of solutions for regexes that WILL match the curly braces in addition to "MatchThisText," resulting in a match of "{MatchThisText}" which is not what he (or I) needed.

If someone can write a Regex that actually matches only the characters BETWEEN the curly braces, I'd really appreciate it.  It should allow any ASCII values, and should stop the match at the FIRST closing bracket.

For Example: "{retailCategoryUrl}/{filters}"

Should Match: retailCategoryUrl and filters

But NOT Match: "retailCategoryUrl}/{filters" (Everything but the outer braces)

Hey, this is a really tricky one for me, so please forgive the question if this is trivial for some of you.

THANKS!

答:
In Javascript you get an array with all matches. Here is an example that machtes text between css` and ` for machting template strings:</p>

```<code>yourstring.match(/css`([^}]+).`/gmi)
</code>```

Body:
In Javascript you get an array with all matches. Here is an example that machtes text between css` and ` for machting template strings:

yourstring.match(/css`([^}]+).`/gmi)


问:
Indices of n largest values in lower triangular region of a NumPy array
I have a numpy cosine similarity matrix. I want to find the indices of the n largest values, but exclude the 1.0's on the diagonals and only for the lower triangular region in it.

```<code>similarities = [[ 1.          0.18898224  0.16903085]
 [ 0.18898224  1.          0.67082039]
 [ 0.16903085  0.67082039  1.        ]]
</code>```

In this case, if I want the two highest values, I would want it to return [1, 0] and [2, 1].

I have tried using argpartition but this does not return what I'm looking for

```<code>n_select = 1
most_similar = (-similarities).argpartition(n_select, axis=None)[:n_select]
</code>```

How can I get the n highest values excluding the diagonal 1's and also exclude the upper triangular elements?

答:
Approach #1

One approach with np.tril_indices -

```<code>def n_largest_indices_tril(a, n=2):
    m = a.shape[0]
    r,c = np.tril_indices(m,-1)
    idx = a[r,c].argpartition(-n)[-n:]
    return zip(r[idx], c[idx])
</code>```

Sample run -

```<code>In [39]: a
Out[39]:
array([[ 1.  ,  0.4 ,  0.59,  0.15,  0.29],
       [ 0.4 ,  1.  ,  0.03,  0.57,  0.57],
       [ 0.59,  0.03,  1.  ,  0.9 ,  0.52],
       [ 0.15,  0.57,  0.9 ,  1.  ,  0.37],
       [ 0.29,  0.57,  0.52,  0.37,  1.  ]])

In [40]: n_largest_indices_tril(a, n=2)
Out[40]: [(2, 0), (3, 2)]

In [41]: n_largest_indices_tril(a, n=3)
Out[41]: [(4, 1), (2, 0), (3, 2)]
</code>```

Approach #2

For performance, we might want to avoid generating all lower triangular indices and instead work with a mask, giving us a second method to solve our case, like so -

```<code>def n_largest_indices_tril_v2(a, n=2):
    m = a.shape[0]
    r = np.arange(m)
    mask = r[:,None] > r
    idx = a[mask].argpartition(-n)[-n:]

    clens = np.arange(m).cumsum()
    grp_start = clens[:-1]
    grp_stop = clens[1:]-1

    rows = np.searchsorted(grp_stop, idx)+1
    cols  = idx - grp_start[rows-1]
    return zip(rows, cols)
</code>```

Runtime test

```<code>In [143]: # Setup symmetric array
     ...: N = 1000
     ...: a = np.random.rand(N,N)*0.9
     ...: np.fill_diagonal(a,1)
     ...: m = a.shape[0]
     ...: r,c = np.tril_indices(m,-1)
     ...: a[r,c] = a[c,r]

In [144]: %timeit n_largest_indices_tril(a, n=2)
100 loops, best of 3: 12.5 ms per loop

In [145]: %timeit n_largest_indices_tril_v2(a, n=2)
100 loops, best of 3: 7.85 ms per loop
</code>```

For n smallest indices

For getting n smallest ones, simply use ndarray.argpartition(n)[:n] instead for both of the approaches.

Body:
I have a numpy cosine similarity matrix. I want to find the indices of the n largest values, but exclude the 1.0's on the diagonals and only for the lower triangular region in it.

similarities = [[ 1.          0.18898224  0.16903085]
 [ 0.18898224  1.          0.67082039]
 [ 0.16903085  0.67082039  1.        ]]

In this case, if I want the two highest values, I would want it to return [1, 0] and [2, 1].

I have tried using argpartition but this does not return what I'm looking for

n_select = 1
most_similar = (-similarities).argpartition(n_select, axis=None)[:n_select]

How can I get the n highest values excluding the diagonal 1's and also exclude the upper triangular elements?

Body:
Approach #1

One approach with np.tril_indices -

def n_largest_indices_tril(a, n=2):
    m = a.shape[0]
    r,c = np.tril_indices(m,-1)
    idx = a[r,c].argpartition(-n)[-n:]
    return zip(r[idx], c[idx])

Sample run -

In [39]: a
Out[39]:
array([[ 1.  ,  0.4 ,  0.59,  0.15,  0.29],
       [ 0.4 ,  1.  ,  0.03,  0.57,  0.57],
       [ 0.59,  0.03,  1.  ,  0.9 ,  0.52],
       [ 0.15,  0.57,  0.9 ,  1.  ,  0.37],
       [ 0.29,  0.57,  0.52,  0.37,  1.  ]])

In [40]: n_largest_indices_tril(a, n=2)
Out[40]: [(2, 0), (3, 2)]

In [41]: n_largest_indices_tril(a, n=3)
Out[41]: [(4, 1), (2, 0), (3, 2)]

Approach #2

For performance, we might want to avoid generating all lower triangular indices and instead work with a mask, giving us a second method to solve our case, like so -

def n_largest_indices_tril_v2(a, n=2):
    m = a.shape[0]
    r = np.arange(m)
    mask = r[:,None] > r
    idx = a[mask].argpartition(-n)[-n:]

    clens = np.arange(m).cumsum()
    grp_start = clens[:-1]
    grp_stop = clens[1:]-1

    rows = np.searchsorted(grp_stop, idx)+1
    cols  = idx - grp_start[rows-1]
    return zip(rows, cols)

Runtime test

In [143]: # Setup symmetric array
     ...: N = 1000
     ...: a = np.random.rand(N,N)*0.9
     ...: np.fill_diagonal(a,1)
     ...: m = a.shape[0]
     ...: r,c = np.tril_indices(m,-1)
     ...: a[r,c] = a[c,r]

In [144]: %timeit n_largest_indices_tril(a, n=2)
100 loops, best of 3: 12.5 ms per loop

In [145]: %timeit n_largest_indices_tril_v2(a, n=2)
100 loops, best of 3: 7.85 ms per loop

For n smallest indices

For getting n smallest ones, simply use ndarray.argpartition(n)[:n] instead for both of the approaches.


问:
Can we run a particular Redis Query using Jmeter?
I want to retrieve particular key values from Redis, using jmeter. I am fairly new to both jmeter and redis. For your instance

I want to connect to the host,
then retrieve value for "get batchid_dasd8adasda8asda0"and
then use the result in my beanshell preprocessor.

Thanks in advance.

答:
Here is a JMeter file and bean shell script to fetch a set of keys from redis and put them into variables used by a looping HTTP GET request.

https://bitbucket.org/barryknapp/shared/src/d62f8ebb57ede1d15a3bd7683adfdd02cd039369/jmeter/?at=master


问:
JQuery iterate through string occurrences
I've an HTML like this

blalblala bla  blalba  bla and so on...

Now I would to get the left position of all items of kind myID.
I've tried with this code

```<code>var x = "";
$('.myID').each(function(index) {
    x += " " + $(this).position().left+",";
});
return x;
</code>```

But it's wrong because it does not return anything.
What's wrong?
Thanks

答:
You should not use id on more than one element.  The appropriate attribute to use is class.

```<code><span class="myClass" >bla < /span>
<span class="myClass"> bla< /span>
</code>```

And then your code should work if you update the selector to be:

```<code>$('.myClass')
</code>```

Body:
I've an HTML like this

blalblala bla  blalba  bla and so on...

Now I would to get the left position of all items of kind myID.
I've tried with this code

var x = "";
$('.myID').each(function(index) {
    x += " " + $(this).position().left+",";
});
return x;

But it's wrong because it does not return anything.
What's wrong?
Thanks

Body:
You should not use id on more than one element.  The appropriate attribute to use is class.

<span class="myClass" >bla < /span>
<span class="myClass"> bla< /span>

And then your code should work if you update the selector to be:

$('.myClass')


问:
HAProxy + pgbouncer server closed the connection unexpectedly
I have an architecture of haproxy on web server which is routing to slave servers, where I have pgbouncer over postgre.
HAPoxy config:

```<code>global
    log 127.0.0.1 local1 debug
    user haproxy
    group haproxy

defaults
    log global
    retries 3
    timeout connect 1s
    timeout server 20m
    timeout client 20m

listen pgsql-cluster
    bind 127.0.0.1:5433
    mode tcp
    balance leastconn
    #option pgsql-check user postgres -
    default-server inter 1s downinter 1s rise 2 fall 1
    server pgsql-1 10.5.8.14:6432 check
    server pgsql-2 10.5.8.21:6432 check
</code>```

Pgbouncer config is default.
First problem, pgsql-check is not working.
pgboucer.log:

```<code>2016-11-23 12:47:37.805 17068 WARNING C-0x23bb760: (nodb)/(nouser)@10.5.8.13:48898 Pooler Error: No such database: postgres
2016-11-23 12:47:37.805 17068 LOG C-0x23bb760: (nodb)/(nouser)@10.5.8.13:48898 login failed: db=postgres user=postgres
</code>```

But the biggest problem, is that after some period of time i've got many errors in my site (Yii2). Log:

```<code>2016-11-22 16:37:42 [10.5.33.135][-][-][error][application] SQLSTATE[08006] [7] server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request. in file /var/www/copy-search/vendor/yiisoft/yii2/db/Connection.php on line 547
</code>```

I've got the feeling, that haproxy just breaks the session.

答:
To answer the first problem make sure that a user named postgres is defined in your PG Bouncer configs. I currently have HA Proxy setup to distribute load between two PG Bouncer processes and have a postgres user and a postgres database defined in my configs and the health checks work. As for the second problem I am currently getting the same error.

Update:

I increased the timeouts on HA Proxy and this resolved my issue.

```<code>listen pgsql-cluster
   bind 127.0.0.1:5433
   mode tcp
   balance leastconn
   timeout client 30h
   timeout server 30h
   #option pgsql-check user postgres -
   default-server inter 1s downinter 1s rise 2 fall 1
   server pgsql-1 10.5.8.14:6432 check
   server pgsql-2 10.5.8.21:6432 check
</code>```

Body:
I have an architecture of haproxy on web server which is routing to slave servers, where I have pgbouncer over postgre.
HAPoxy config:

global
    log 127.0.0.1 local1 debug
    user haproxy
    group haproxy

defaults
    log global
    retries 3
    timeout connect 1s
    timeout server 20m
    timeout client 20m

listen pgsql-cluster
    bind 127.0.0.1:5433
    mode tcp
    balance leastconn
    #option pgsql-check user postgres -
    default-server inter 1s downinter 1s rise 2 fall 1
    server pgsql-1 10.5.8.14:6432 check
    server pgsql-2 10.5.8.21:6432 check

Pgbouncer config is default.
First problem, pgsql-check is not working.
pgboucer.log:

2016-11-23 12:47:37.805 17068 WARNING C-0x23bb760: (nodb)/(nouser)@10.5.8.13:48898 Pooler Error: No such database: postgres
2016-11-23 12:47:37.805 17068 LOG C-0x23bb760: (nodb)/(nouser)@10.5.8.13:48898 login failed: db=postgres user=postgres

But the biggest problem, is that after some period of time i've got many errors in my site (Yii2). Log:

2016-11-22 16:37:42 [10.5.33.135][-][-][error][application] SQLSTATE[08006] [7] server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request. in file /var/www/copy-search/vendor/yiisoft/yii2/db/Connection.php on line 547

I've got the feeling, that haproxy just breaks the session.

Body:
To answer the first problem make sure that a user named postgres is defined in your PG Bouncer configs. I currently have HA Proxy setup to distribute load between two PG Bouncer processes and have a postgres user and a postgres database defined in my configs and the health checks work. As for the second problem I am currently getting the same error.

Update:

I increased the timeouts on HA Proxy and this resolved my issue.

listen pgsql-cluster
   bind 127.0.0.1:5433
   mode tcp
   balance leastconn
   timeout client 30h
   timeout server 30h
   #option pgsql-check user postgres -
   default-server inter 1s downinter 1s rise 2 fall 1
   server pgsql-1 10.5.8.14:6432 check
   server pgsql-2 10.5.8.21:6432 check


问:
Unable to upload a picture on firebase storage
I am trying to upload a picture on firebase storage. On pressing capture button for capturing picture my app crashes and i get this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference

on this line Uri photoURI = FileProvider.getUriForFile(this,
                        "com.faum.faum_expert.fileprovider",
                        photoFile);

That is my code:

```<code>private ImageView ivKitchen1,ivKitchen2,ivKitchen3;
private Button btnCapture1,btnCapture2,btnCapture3;
private TextView tvKitchenSnaps;

private StorageReference snapsStorage;

private static final int CAMERA_REQUEST_CODE = 1;

private ProgressDialog mProgress;

private Uri filepath;

String mCurrentPhotoPath;

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
        }
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.faum.faum_expert.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
        }
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.kitchen_snaps);

    snapsStorage = FirebaseStorage.getInstance().getReference();

    ivKitchen1 = (ImageView)findViewById(R.id.ivKitchen1);

    btnCapture1 = (Button)findViewById(R.id.btnCapture1);

    mProgress = new ProgressDialog(this);

    btnCapture1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivityForResult(intent, CAMERA_REQUEST_CODE);*/

            dispatchTakePictureIntent();
        }
    });
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
        mProgress.setMessage("Uploading...");
        mProgress.show();
        Uri uri = data.getData();

        StorageReference filepath = snapsStorage.child("Photos").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(Kitchen_Snaps.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
                mProgress.dismiss();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(Kitchen_Snaps.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
</code>```

Manifesto File

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!--
-
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.faum.faum_expert.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths"></meta-data>
</provider>
-->
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Social_Connect" />
    <activity android:name=".User_sign" />

    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/facebook_app_id" />

    <activity android:name=".Personal_Information" />
    <activity android:name=".Contact_Infrormation" />
    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/.
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps" />
    <activity android:name=".Kitchen_Snaps" />
    <activity
        android:name=".Navigation_Drawer"
        android:label="@string/title_activity_navigation__drawer"
        android:theme="@style/AppTheme" />
    <activity android:name=".New_Deal" />
    <activity android:name=".New_Deal_Time" />
    <activity android:name=".New_Deal_List" />
    <activity android:name=".New_Deal_Confirmation"></activity>
</application>
</code>```

答:
I think, you have to check permission at first
I hope it helps
Here are full source code</p>

```<code>public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.kitchen_snaps);

    snapsStorage = FirebaseStorage.getInstance().getReference();

    ivKitchen1 = (ImageView)findViewById(R.id.ivKitchen1);

    btnCapture1 = (Button)findViewById(R.id.btnCapture1);

    mProgress = new ProgressDialog(this);

    btnCapture1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //startActivityForResult(intent, CAMERA_REQUEST_CODE);*/

            //dispatchTakePictureIntent();
            if (checkPermission(YourActivity.class))
                cameraIntent();
        }
    });
}

 @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                cameraIntent();
            }

            break;
    }
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
    int currentAPIVersion = Build.VERSION.SDK_INT;
    if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
    {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                alertBuilder.setCancelable(true);
                alertBuilder.setTitle("Permission necessary");
                alertBuilder.setMessage("External storage permission is necessary");
                alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                    }
                });
                AlertDialog alert = alertBuilder.create();
                alert.show();

            } else {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
            }
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}

private void cameraIntent() {
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (cameraIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile(SetupProfileActivity.this);
        } catch (IOException ex) {
            Log.i(TAG, "IOException");
        }

        //For Android SDk 24+, 7.0
        if (photoFile != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mPhotoUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", photoFile);

                List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    grantUriPermission(packageName, mPhotoUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            } else {
                mPhotoUri = Uri.fromFile(photoFile);
            }

            //mPhotoUri = Uri.fromFile(photoFile);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
            startActivityForResult(cameraIntent, REQUEST_CAMERA);
        }
    }
}
</code>```

Body:
I am trying to upload a picture on firebase storage. On pressing capture button for capturing picture my app crashes and i get this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference

on this line Uri photoURI = FileProvider.getUriForFile(this,
                        "com.faum.faum_expert.fileprovider",
                        photoFile);

That is my code:

private ImageView ivKitchen1,ivKitchen2,ivKitchen3;
private Button btnCapture1,btnCapture2,btnCapture3;
private TextView tvKitchenSnaps;

private StorageReference snapsStorage;

private static final int CAMERA_REQUEST_CODE = 1;

private ProgressDialog mProgress;

private Uri filepath;

String mCurrentPhotoPath;

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
        }
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.faum.faum_expert.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
        }
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.kitchen_snaps);

    snapsStorage = FirebaseStorage.getInstance().getReference();

    ivKitchen1 = (ImageView)findViewById(R.id.ivKitchen1);

    btnCapture1 = (Button)findViewById(R.id.btnCapture1);

    mProgress = new ProgressDialog(this);

    btnCapture1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivityForResult(intent, CAMERA_REQUEST_CODE);*/

            dispatchTakePictureIntent();
        }
    });
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
        mProgress.setMessage("Uploading...");
        mProgress.show();
        Uri uri = data.getData();

        StorageReference filepath = snapsStorage.child("Photos").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(Kitchen_Snaps.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
                mProgress.dismiss();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(Kitchen_Snaps.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Manifesto File

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Social_Connect" />
    <activity android:name=".User_sign" />

    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/facebook_app_id" />

    <activity android:name=".Personal_Information" />
    <activity android:name=".Contact_Infrormation" />

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps" />
    <activity android:name=".Kitchen_Snaps" />
    <activity
        android:name=".Navigation_Drawer"
        android:label="@string/title_activity_navigation__drawer"
        android:theme="@style/AppTheme" />
    <activity android:name=".New_Deal" />
    <activity android:name=".New_Deal_Time" />
    <activity android:name=".New_Deal_List" />
    <activity android:name=".New_Deal_Confirmation"></activity>
</application>

Body:
I think, you have to check permission at first
I hope it helps
Here are full source code

public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.kitchen_snaps);

    snapsStorage = FirebaseStorage.getInstance().getReference();

    ivKitchen1 = (ImageView)findViewById(R.id.ivKitchen1);

    btnCapture1 = (Button)findViewById(R.id.btnCapture1);

    mProgress = new ProgressDialog(this);

    btnCapture1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //startActivityForResult(intent, CAMERA_REQUEST_CODE);*/

            //dispatchTakePictureIntent();
            if (checkPermission(YourActivity.class))
                cameraIntent();
        }
    });
}

 @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                cameraIntent();
            }

            break;
    }
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
    int currentAPIVersion = Build.VERSION.SDK_INT;
    if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
    {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                alertBuilder.setCancelable(true);
                alertBuilder.setTitle("Permission necessary");
                alertBuilder.setMessage("External storage permission is necessary");
                alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                    }
                });
                AlertDialog alert = alertBuilder.create();
                alert.show();

            } else {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
            }
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}

private void cameraIntent() {
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (cameraIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile(SetupProfileActivity.this);
        } catch (IOException ex) {
            Log.i(TAG, "IOException");
        }

        //For Android SDk 24+, 7.0
        if (photoFile != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mPhotoUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", photoFile);

                List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    grantUriPermission(packageName, mPhotoUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            } else {
                mPhotoUri = Uri.fromFile(photoFile);
            }

            //mPhotoUri = Uri.fromFile(photoFile);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
            startActivityForResult(cameraIntent, REQUEST_CAMERA);
        }
    }
}


问:
ApplicationModalAdorner GetLayoutClip() InvalidOperationException
I have my own ApplicationModalAdorner. Sometimes I get an InvalidOperationException from GetLayoutClip() which I override. The call to TransformToAncestor causes the exception. I am unable to reproduce the exception (I see the exception in the logging quite a lot). Maybe the Window isn't completly rendered? I'm looking for a reproduction (maybe in a simple app) and a cause/solution for this exception. I get the exception a couple of times in the same minute. I prefer a solution without a Dispatcher.

Relevant callstack part:

```<code>Wrapped Exception: System.InvalidOperationException: An exception occured while handling another exception;
   bij System.Windows.Media.Visual.TrySimpleTransformToAncestor(Visual ancestor, Boolean inverse, GeneralTransform& generalTransform, Matrix& simpleTransform)
   bij System.Windows.Media.Visual.TransformToAncestor(Visual ancestor)
   bij x.x.x.ApplicationModalAdorner.WindowRect()
   bij x.x.x.ApplicationModalAdorner.GetLayoutClip(Size layoutSlotSize)
   bij System.Windows.UIElement.ensureClip(Size layoutSlotSize)
   bij System.Windows.UIElement.Arrange(Rect finalRect)
   bij System.Windows.Documents.AdornerLayer.ArrangeOverride(Size finalSize)
   bij System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
   bij System.Windows.UIElement.Arrange(Rect finalRect)
   bij System.Windows.Documents.AdornerDecorator.ArrangeOverride(Size finalSize)
   bij System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
   bij System.Windows.UIElement.Arrange(Rect finalRect)
   bij System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds)
   bij System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
   bij System.Windows.UIElement.Arrange(Rect finalRect)
   bij MS.Internal.Helper.ArrangeElementWithSingleChild(UIElement element, Size arrangeSize)
   bij System.Windows.Controls.ContentPresenter.ArrangeOverride(Size arrangeSize)
   bij System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
   bij System.Windows.UIElement.Arrange(Rect finalRect)
   bij System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize)
   bij System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
   bij System.Windows.UIElement.Arrange(Rect finalRect)
</code>```

Code

```<code>public class ApplicationModalAdorner : Adorner
{
    private SolidColorBrush _brush;

    private XamDialogWindow Window
    {
        get
        {
            return (XamDialogWindow)AdornedElement;
        }
    }

    private Window MainWindow
    {
        get
        {
            if (Application.Current != null)
            {
                return Application.Current.MainWindow;
            }
            return null;
        }
    }

    public ApplicationModalAdorner(UIElement adornedElement)
        : base(adornedElement)
    {
        _brush = (SolidColorBrush)FindResource("ModalBackgroundBrush");

        Window.Moved += WindowMoved;
        Window.WindowStateChanged += WindowStateChanged;
        MainWindow.SizeChanged += MainWindowSizeChanged;
    }

    // There is no WindowClosed event. Infragistics states that when a window is closed,
    // the WindowStateChanged event gets triggerd and the value will be Hidden. Because
    // the ApplicationModal windows cannot be hidden, this is a nice way to clean events.
    private void WindowStateChanged(object sender, WindowStateChangedEventArgs e)
    {
        if (e.NewWindowState == Infragistics.Controls.Interactions.WindowState.Hidden)
        {
            Window.Moved -= WindowMoved;
            Window.WindowStateChanged -= WindowStateChanged;
            if (MainWindow != null)
            {
                MainWindow.SizeChanged -= MainWindowSizeChanged;
            }
        }
    }

    private void WindowMoved(object sender, MovedEventArgs e)
    {
        InvalidateVisual();
    }

    private void MainWindowSizeChanged(object sender, SizeChangedEventArgs e)
    {
        InvalidateVisual();
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        drawingContext.DrawRectangle(_brush, null, WindowRect());
        base.OnRender(drawingContext);
    }

    protected override Geometry GetLayoutClip(Size layoutSlotSize)
    {
        var xamDialogWindowRect = new Rect(new Point(Window.Left, Window.Top), layoutSlotSize);
        var geometryGroup = new GeometryGroup();
        geometryGroup.Children.Add(new RectangleGeometry(WindowRect()));
        geometryGroup.Children.Add(new RectangleGeometry(xamDialogWindowRect));
        return geometryGroup;
    }

    private Rect WindowRect()
    {
        var transformToAncestor = Window.TransformToAncestor(MainWindow);
        var topLeft = transformToAncestor.Inverse.Transform(new Point(0, 0));
        var bottomRight = transformToAncestor.Inverse.Transform(new Point(MainWindow.ActualWidth, MainWindow.ActualHeight));
        return new Rect(topLeft, bottomRight);
    }

    public override GeneralTransform GetDesiredTransform(GeneralTransform transform)
    {
        InvalidateVisual();
        return base.GetDesiredTransform(transform);
    }
  }
}
</code>```

答:
Your window is not present in the Visual Tree. You have two options:

Listen for the Loaded event. Then, when loaded, start listening for the other events (Moved, WindowStateChanged, SizeChanged).

Use dispatcher where necessary and then hope for the best.

As for your request for a sample app I can assure you that the issue you are seeing is unbelievably hard to reproduce.

Body:
I have my own ApplicationModalAdorner. Sometimes I get an InvalidOperationException from GetLayoutClip() which I override. The call to TransformToAncestor causes the exception. I am unable to reproduce the exception (I see the exception in the logging quite a lot). Maybe the Window isn't completly rendered? I'm looking for a reproduction (maybe in a simple app) and a cause/solution for this exception. I get the exception a couple of times in the same minute. I prefer a solution without a Dispatcher.

Relevant callstack part:

Wrapped Exception: System.InvalidOperationException: An exception occured while handling another exception;
   bij System.Windows.Media.Visual.TrySimpleTransformToAncestor(Visual ancestor, Boolean inverse, GeneralTransform& generalTransform, Matrix& simpleTransform)
   bij System.Windows.Media.Visual.TransformToAncestor(Visual ancestor)
   bij x.x.x.ApplicationModalAdorner.WindowRect()
   bij x.x.x.ApplicationModalAdorner.GetLayoutClip(Size layoutSlotSize)
   bij System.Windows.UIElement.ensureClip(Size layoutSlotSize)
   bij System.Windows.UIElement.Arrange(Rect finalRect)
   bij System.Windows.Documents.AdornerLayer.ArrangeOverride(Size finalSize)
   bij System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
   bij System.Windows.UIElement.Arrange(Rect finalRect)
   bij System.Windows.Documents.AdornerDecorator.ArrangeOverride(Size finalSize)
   bij System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
   bij System.Windows.UIElement.Arrange(Rect finalRect)
   bij System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds)
   bij System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
   bij System.Windows.UIElement.Arrange(Rect finalRect)
   bij MS.Internal.Helper.ArrangeElementWithSingleChild(UIElement element, Size arrangeSize)
   bij System.Windows.Controls.ContentPresenter.ArrangeOverride(Size arrangeSize)
   bij System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
   bij System.Windows.UIElement.Arrange(Rect finalRect)
   bij System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize)
   bij System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
   bij System.Windows.UIElement.Arrange(Rect finalRect)

Code

public class ApplicationModalAdorner : Adorner
{
    private SolidColorBrush _brush;

    private XamDialogWindow Window
    {
        get
        {
            return (XamDialogWindow)AdornedElement;
        }
    }

    private Window MainWindow
    {
        get
        {
            if (Application.Current != null)
            {
                return Application.Current.MainWindow;
            }
            return null;
        }
    }

    public ApplicationModalAdorner(UIElement adornedElement)
        : base(adornedElement)
    {
        _brush = (SolidColorBrush)FindResource("ModalBackgroundBrush");

        Window.Moved += WindowMoved;
        Window.WindowStateChanged += WindowStateChanged;
        MainWindow.SizeChanged += MainWindowSizeChanged;
    }

    // There is no WindowClosed event. Infragistics states that when a window is closed,
    // the WindowStateChanged event gets triggerd and the value will be Hidden. Because
    // the ApplicationModal windows cannot be hidden, this is a nice way to clean events.
    private void WindowStateChanged(object sender, WindowStateChangedEventArgs e)
    {
        if (e.NewWindowState == Infragistics.Controls.Interactions.WindowState.Hidden)
        {
            Window.Moved -= WindowMoved;
            Window.WindowStateChanged -= WindowStateChanged;
            if (MainWindow != null)
            {
                MainWindow.SizeChanged -= MainWindowSizeChanged;
            }
        }
    }

    private void WindowMoved(object sender, MovedEventArgs e)
    {
        InvalidateVisual();
    }

    private void MainWindowSizeChanged(object sender, SizeChangedEventArgs e)
    {
        InvalidateVisual();
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        drawingContext.DrawRectangle(_brush, null, WindowRect());
        base.OnRender(drawingContext);
    }

    protected override Geometry GetLayoutClip(Size layoutSlotSize)
    {
        var xamDialogWindowRect = new Rect(new Point(Window.Left, Window.Top), layoutSlotSize);
        var geometryGroup = new GeometryGroup();
        geometryGroup.Children.Add(new RectangleGeometry(WindowRect()));
        geometryGroup.Children.Add(new RectangleGeometry(xamDialogWindowRect));
        return geometryGroup;
    }

    private Rect WindowRect()
    {
        var transformToAncestor = Window.TransformToAncestor(MainWindow);
        var topLeft = transformToAncestor.Inverse.Transform(new Point(0, 0));
        var bottomRight = transformToAncestor.Inverse.Transform(new Point(MainWindow.ActualWidth, MainWindow.ActualHeight));
        return new Rect(topLeft, bottomRight);
    }

    public override GeneralTransform GetDesiredTransform(GeneralTransform transform)
    {
        InvalidateVisual();
        return base.GetDesiredTransform(transform);
    }
  }
}


问:
Are C constant character strings always null terminated?
Are C constant character strings always null terminated without exception?

For example, will the following C code always print "true":

```<code>const char* s = "abc";
if( *(s + 3) == 0 ){
   printf( "true" );
} else {
   printf( "false" );
}
</code>```

答:
The notion of a string is determinate as a sequence of characters terminated by zero character. It is not important whether the sequence is modifiable or not that is whether a corresponding declaration has the qualifier const or not.

For example string literals in C have types of non-constant character arrays. So you may write for example

```<code>char *s = "Hello world";
</code>```

In this declaration the identifier s points to the first character of the string.

You can initialize a character array yourself by a string using a string literal. For example

```<code>char s[] = "Hello world";
</code>```

This declaration is equivalent to

```<code>char s[] = { 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\0' };
</code>```

However in C you may exclude the terminating zero from an initialization of a character array.

For example

```<code>char s[11] = "Hello world";
</code>```

Though the string literal used as the initializer contains the terminating zero it is excluded from the initialization. As result the character array s does not contain a string.

Body:
Are C constant character strings always null terminated without exception?

For example, will the following C code always print "true":

const char* s = "abc";
if( *(s + 3) == 0 ){
   printf( "true" );
} else {
   printf( "false" );
}

Body:
The notion of a string is determinate as a sequence of characters terminated by zero character. It is not important whether the sequence is modifiable or not that is whether a corresponding declaration has the qualifier const or not.

For example string literals in C have types of non-constant character arrays. So you may write for example

char *s = "Hello world";

In this declaration the identifier s points to the first character of the string.

You can initialize a character array yourself by a string using a string literal. For example

char s[] = "Hello world";

This declaration is equivalent to

char s[] = { 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\0' };

However in C you may exclude the terminating zero from an initialization of a character array.

For example

char s[11] = "Hello world";

Though the string literal used as the initializer contains the terminating zero it is excluded from the initialization. As result the character array s does not contain a string.


答:
use
sValue.trim().equals("") instead of sValue.matches("")</p>

Title: EditText constantly returns Empty - Android

Body:
I'm attempting to null check an EditText (which should be simple enough) however each time I enter text into my two ET's - they always return as empty: "" and they should not (if they have text in them).

I've looked over several other SO articles related to this and none of the fixes seem to resolve the issue.

Can anyone spot what I might be doing wrong in this instance?

Source Snippet:

Java class:

...

public void doneClicked(View v) throws JSONException {

    LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v1 = li.inflate(R.layout.profile_notification_settings_list_edit, null);

    final EditText label = (EditText) v1.findViewById(R.id.emaillabel);
    final EditText value = (EditText) v1.findViewById(R.id.emailvalue);

    String sValue = value.getText().toString();
    if (sValue.matches("")) {
        Toast.makeText(this, "You did not enter a value", Toast.LENGTH_SHORT).show();
        return;
    }

    String sLabel = label.getText().toString();
    if (sLabel.matches("")) {
        Toast.makeText(this, "You did not enter a label", Toast.LENGTH_SHORT).show();
        return;
    }

...

Adapter:

@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
    view = inflater.inflate(R.layout.profile_notification_settings_list_edit, null);
    EditText value = (EditText) view.findViewById(R.id.emailvalue);
    value.setHint("Value");
    value.setText(valueList[i]);

    EditText label = (EditText) view.findViewById(R.id.emaillabel);
    if (labelList != null)
        label.setHint("Label");
    label.setText(labelList[i]);

Full source:

Java Class:

https://pastebin.com/y1e9J1yE

Adapter:

https://pastebin.com/Zqh3eCAk


问:
Highlight text differences between two RichTextBoxes
I am trying to compare two XML files, each put into a different RichTextBox, in VB.NET. The first RichTextBox will have the original XML file, while the second RichTextBox will have an updated XML file. I want to highlight the differences between the two files in the second RichTextBox.

Currently, I simply put each row of text from the original XML file into a List(Of String). I then loop through all the lines of the second RichTextBox and if the List(Of String) does not contain that line, then I know the line was either added (a new line) or was edited, so it has to be highlighted in the second RichTextBox.

This is the code:

```<code>Dim sRichTextBox1Lines() As String = RichTextBox1.Lines
Dim sRichTextBox2Lines() As String = RichTextBox2.Lines
Dim sLines As List(Of String) = New List(Of String)
Dim sRichTextBox2Line As String = ""
Dim nIndexStartOfCurrLine As Integer = 0

For i As Integer = 0 To (sRichTextBox1Lines.Length - 1)
    sLines.Add(sRichTextBox1Lines(i))
Next

For i As Integer = 0 To (sRichTextBox2Lines.Length)
    sRichTextBox2Line = sRichTextBox2Lines(i).ToString
    nIndexStartOfCurrLine = RichTextBox2.GetFirstCharIndexFromLine(i)
        If (Not sLines.Contains(sRichTextBox2Line)) Then
            RichTextBox2.Select(nIndexStartOfCurrLine, sRichTextBox2Lines(i).Length)
            RichTextBox2.SelectionColor = Color.White
            RichTextBox2.SelectionBackColor = Color.Red
        End If
    Next
</code>```

This does the job. However, I was thinking about only highlighting the actual differences, such as a space added, rather than simply highlighting the whole line.

Now this is where I am having issues. I was thinking of going line-by-line and comparing each line to highlight only the difference between the two lines, but there are issues with this approach (e.g. a line was removed, a line was commented out and modified on the next line, a blank line was added, etc.) and the code becomes very convoluted and hard to follow. For example, suppose this is in the first XML file (RichTextBox1):

```<code><add key="Test123A" value="123A"/>
<add key="Test123B" value="123B"/>
<add key="Test123C" value="123C"/>
<add key="Test123D" value="123D"/>
</code>```

And suppose this is in the second XML file (RichTextBox2):

```<code><add key="Test123A" value="123A"/>
<!--<add key="Test123B" value="123B"/>-->
<add key="Test123B" value="456B" />
<add key="Test123C" value="123C" />
<add key="Test123D" value="123D" />
</code>```

A line-by-line comparison would be messed up since lines 2 and 3 do not match anything in the original XML file. Also, note that there is now a space after the last quotation marks in the new XML file, which isn't a huge difference (literally a 1-char difference). I was thinking about taking SubStrings but some other parts of the XML file could have the same text, making things complicated.

Perhaps I'm overthinking this but I'm just struggling to find a nice method to highlight only the differences rather than the whole line.

答:
Presumably, the key attribute is a unique value and you only want to compare if the value is different. If that is the case, then load your two XML files into an XDocument object, set the Text property of your RichTextBox controls to their respective XDocument. Then iterate through each <add> of XDocument A to get the <add> of XDocument B that share the same key so that you can compare if the value is different. If so, then find the XElement in the RichTextBox to highlight it.

Here is a quick (free-typed untested) example:

```<code>'Declare and load the documents
Dim documentA, documentB As New XDocument
documentA.Load("FileA.xml")
documentB.Load("FileB.xml")

'Display the files in the RTB
RichTextBox1.Text = documentA.ToString()
RichTextBox2.Text = documentB.ToString()

'Placeholder variables
Dim addB As XElement

'Iterate through each <add> element
For Each addA As XElement In documentA.Descendants("add")
  'Check to make sure that the <add> has a key and value attribute
  If addA.HasAttribute("key") AndAlso addB.HasAttribute("value") Then
    addB = documentB.Descendants("add").FirstOrDefault(Function(e) e.HasAttribute("key") AndAlso e.Attribute("key") = addA.Attribute("key"))

    'Check to make sure that it found an element with the same key and that it also has a value and that the values does not match <addA>'s value
    If addB IsNot Nothing AndAlso addB.HasAttribute("value") AndAlso addB.Attribute("value") <> addA.attribute("value") Then
      'Get the index of <addB>
      Dim index As Integer = RichTextBox2.Find(addB.ToString())

      With RichTextBox2
        .Select(index, addB.ToString().Length()) 'Select the tag
        .SelectionColor = Color.White 'Change the font color
        .SelectionBackColor = Color.Read 'Change the background color
      End With
    End If
  End If
Next
</code>```

Body:
I am trying to compare two XML files, each put into a different RichTextBox, in VB.NET. The first RichTextBox will have the original XML file, while the second RichTextBox will have an updated XML file. I want to highlight the differences between the two files in the second RichTextBox.

Currently, I simply put each row of text from the original XML file into a List(Of String). I then loop through all the lines of the second RichTextBox and if the List(Of String) does not contain that line, then I know the line was either added (a new line) or was edited, so it has to be highlighted in the second RichTextBox.

This is the code:

Dim sRichTextBox1Lines() As String = RichTextBox1.Lines
Dim sRichTextBox2Lines() As String = RichTextBox2.Lines
Dim sLines As List(Of String) = New List(Of String)
Dim sRichTextBox2Line As String = ""
Dim nIndexStartOfCurrLine As Integer = 0

For i As Integer = 0 To (sRichTextBox1Lines.Length - 1)
    sLines.Add(sRichTextBox1Lines(i))
Next

For i As Integer = 0 To (sRichTextBox2Lines.Length)
    sRichTextBox2Line = sRichTextBox2Lines(i).ToString
    nIndexStartOfCurrLine = RichTextBox2.GetFirstCharIndexFromLine(i)
        If (Not sLines.Contains(sRichTextBox2Line)) Then
            RichTextBox2.Select(nIndexStartOfCurrLine, sRichTextBox2Lines(i).Length)
            RichTextBox2.SelectionColor = Color.White
            RichTextBox2.SelectionBackColor = Color.Red
        End If
    Next

This does the job. However, I was thinking about only highlighting the actual differences, such as a space added, rather than simply highlighting the whole line.

Now this is where I am having issues. I was thinking of going line-by-line and comparing each line to highlight only the difference between the two lines, but there are issues with this approach (e.g. a line was removed, a line was commented out and modified on the next line, a blank line was added, etc.) and the code becomes very convoluted and hard to follow. For example, suppose this is in the first XML file (RichTextBox1):

<add key="Test123A" value="123A"/>
<add key="Test123B" value="123B"/>
<add key="Test123C" value="123C"/>
<add key="Test123D" value="123D"/>

And suppose this is in the second XML file (RichTextBox2):

<add key="Test123A" value="123A"/>

<add key="Test123B" value="456B" />
<add key="Test123C" value="123C" />
<add key="Test123D" value="123D" />

A line-by-line comparison would be messed up since lines 2 and 3 do not match anything in the original XML file. Also, note that there is now a space after the last quotation marks in the new XML file, which isn't a huge difference (literally a 1-char difference). I was thinking about taking SubStrings but some other parts of the XML file could have the same text, making things complicated.

Perhaps I'm overthinking this but I'm just struggling to find a nice method to highlight only the differences rather than the whole line.

Body:
Presumably, the key attribute is a unique value and you only want to compare if the value is different. If that is the case, then load your two XML files into an XDocument object, set the Text property of your RichTextBox controls to their respective XDocument. Then iterate through each <add> of XDocument A to get the <add> of XDocument B that share the same key so that you can compare if the value is different. If so, then find the XElement in the RichTextBox to highlight it.

Here is a quick (free-typed untested) example:

'Declare and load the documents
Dim documentA, documentB As New XDocument
documentA.Load("FileA.xml")
documentB.Load("FileB.xml")

'Display the files in the RTB
RichTextBox1.Text = documentA.ToString()
RichTextBox2.Text = documentB.ToString()

'Placeholder variables
Dim addB As XElement

'Iterate through each <add> element
For Each addA As XElement In documentA.Descendants("add")
  'Check to make sure that the <add> has a key and value attribute
  If addA.HasAttribute("key") AndAlso addB.HasAttribute("value") Then
    addB = documentB.Descendants("add").FirstOrDefault(Function(e) e.HasAttribute("key") AndAlso e.Attribute("key") = addA.Attribute("key"))

    'Check to make sure that it found an element with the same key and that it also has a value and that the values does not match <addA>'s value
    If addB IsNot Nothing AndAlso addB.HasAttribute("value") AndAlso addB.Attribute("value") <> addA.attribute("value") Then
      'Get the index of <addB>
      Dim index As Integer = RichTextBox2.Find(addB.ToString())

      With RichTextBox2
        .Select(index, addB.ToString().Length()) 'Select the tag
        .SelectionColor = Color.White 'Change the font color
        .SelectionBackColor = Color.Read 'Change the background color
      End With
    End If
  End If
Next