问:
How to implement the getElementByClassName()
I've got an application which contains a list and looks like this:

When I click on each tick, the name of the Book is added to a textbox below and I want the tick to be replaced with a cross where the user can remove it.

As it stands, when I click any of the ticks, only the first list items box changes to a cross like this:

However, I want whatever tick is alongside the book to change to a cross not the first one at the top of the list.

I know this issue has something to do with the items needing to be a class element rather than ID as using an ID tag will always select the first item with that ID. However, i'm unsure how to implement it into my code as i've tried wrapping the tick and cross boxes in divs with a class name and still the same thing happens.

The JS code looks like this:

function saveToList(event) {
    if (event.which == 13 || event.keyCode == 13) {

function saveToFB(bookName) {

var user = firebase.auth().currentUser;
var bookList = firebase.database().ref('users/' + uid + '/');
var uid = user.uid;

// This will save data to Firebase
bookList.push({
    book: bookName
    });
};

// This is JS which creates the list from firebase data. Split into 3 lists holding 10 books each
function refreshUI(list) {
var lis = '';
var lis2 = '';
var lis3 = '';

for (var i = 0; i < 10 && i < list.length; i++) {

// Creates the list item by adding the firebase object + genLinks which contains the select, remove and delete icons.
lis += '
' + list[i].book + genLinks(list[i].key, list[i].book) +'
';
      };

for (var i = 10; i < 20 && i < list.length; i++) {

lis2 += '
' + list[i].book + genLinks(list[i].key, list[i].book) +'
';
      };

for (var i = 20; i < 30 && i < list.length; i++) {

 lis3 += '
' + list[i].book + genLinks(list[i].key, list[i].book) +'
';
      };

      // Populates the HTML lists with the JS list items
        document.getElementById('bookList').innerHTML = lis;
        document.getElementById('bookList2').innerHTML = lis2;
        document.getElementById('bookList3').innerHTML = lis3;
    };

// This is the area of the JS concerned with generating the icons found alongside each book name and where I need help

// The google icons wrapped in divs with class names
function genLinks(key, bkName) {
var links = '';
links += '
delete
 ';
links += '
clear
 ';
links += '
check
';
return links;
};

// onClick event from the selectBook icon which hides the tick and replaces with a cross
function showRemove() {
  document.getElementById('removeBook').style.display = 'block';
  document.getElementById('selectBook').style.display = 'none';
}

// onClick event from the removeBook icon which hides the cross and replaces with a tick
function showAdd() {
  document.getElementById('selectBook').style.display = 'block';
  document.getElementById('removeBook').style.display = 'none';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bookListContainer">
    <ol id="bookList"> </ol>

    <ol id="bookList2"> </ol>

    <ol id="bookList3"> </ol>
</div></code>```

I was told by somebody to use getElementsByClassName() but they gave no explanation on how to do so. If anybody has any advice or could offer some help I would really appreciate it.

Thanks in advance,

G

答:
You can use CSS to control the icon that is displayed. Also using checkboxes makes it easy to know what is selected. Than it is a simple query and loop to get the checked items.

function buildList() {
   /* Get the checked checkboxes */
   var checkboxes = document.querySelectorAll('[name="books"]:checked');
   /* Build up list of the values by looping over the elements */
   var out = [];
   for (var i=0; i<checkboxes.length; i++) {
       out.push(checkboxes[i].value);
   }
   /* Join list together and display it */
   document.getElementById("output").innerHTML = out.join(", ")
}
document.getElementById("booklist").addEventListener("change", buildList);
buildList();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[name="books"] {  /* Hide checkbox */
  display: none
}

[name="books"]+i+i { /* Hide the x when not checked */
  display: none
}

[name="books"]:checked+i {  /* Hide the check when checked */
  display: none
}

[name="books"]:checked+i+i { /* show the x when checked */
  display: inline
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

      Book 1
      <input type="checkbox" value="book1" name="books" />

      Book 2
      <input type="checkbox" value="book2" name="books" checked/>

      Book 3
      <input type="checkbox" value="book3" name="books" />

      Book 4
      <input type="checkbox" value="book4" name="books" />

```
</div>
</div>
</p>

<p>And we can alter it slightly to handle multiple lists. This time we can use a data attribute to say where to output the item. And we use a loop to add the event listeners to the parents.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(function() {
  function buildList(listId) {
    /* Get the checked checkboxes */
    var checkboxes = document.querySelectorAll('#' + listId + ' [name="books"]:checked');
    /* Build up list of the values by looping over the elements */
    var out = [];
    for (var i = 0; i < checkboxes.length; i++) {
      out.push(checkboxes[i].value);
    }
    var outputId = document.getElementById(listId).dataset.output;
    /* Join list together and display it */
    document.getElementById(outputId).innerHTML = out.join(", ")
  }

  var lists = document.querySelectorAll(".book-list");
  for (var i = 0; i < lists.length; i++) {
    (function(list) {
      list.addEventListener("change", function() {
        buildList(list.id)
      });
      buildList(list.id);
    }(lists[i]))
  }
}());</code>```

[name="books"] {
  /* Hide checkbox */
  display: none
}

[name="books"]+i+i {
  /* Hide the x when not checked */
  display: none
}

[name="books"]:checked+i {
  /* Hide the check when checked */
  display: none
}

[name="books"]:checked+i+i {
  /* show the x when checked */
  display: inline
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<ul id="booklist1" class="book-list" data-output="output1">
  <li>
    <label>
      <span>Book 1</span>
      <input type="checkbox" value="book1" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 2</span>
      <input type="checkbox" value="book2" name="books" checked/>
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 3</span>
      <input type="checkbox" value="book3" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 4</span>
      <input type="checkbox" value="book4" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
</ul>

<div id="output1"></div>

<ul id="booklist2" class="book-list" data-output="output2">
  <li>
    <label>
      <span>Book 5</span>
      <input type="checkbox" value="book5" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 6</span>
      <input type="checkbox" value="book6" name="books"/>
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 7</span>
      <input type="checkbox" value="book7" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 8</span>
      <input type="checkbox" value="book8" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
</ul>

<div id="output2"></div></code>```

Body:
I've got an application which contains a list and looks like this:

When I click on each tick, the name of the Book is added to a textbox below and I want the tick to be replaced with a cross where the user can remove it.

As it stands, when I click any of the ticks, only the first list items box changes to a cross like this:

However, I want whatever tick is alongside the book to change to a cross not the first one at the top of the list.

I know this issue has something to do with the items needing to be a class element rather than ID as using an ID tag will always select the first item with that ID. However, i'm unsure how to implement it into my code as i've tried wrapping the tick and cross boxes in divs with a class name and still the same thing happens.

The JS code looks like this:

function saveToList(event) {
    if (event.which == 13 || event.keyCode == 13) {

function saveToFB(bookName) {

var user = firebase.auth().currentUser;
var bookList = firebase.database().ref('users/' + uid + '/');
var uid = user.uid;

// This will save data to Firebase
bookList.push({
    book: bookName
    });
};

// This is JS which creates the list from firebase data. Split into 3 lists holding 10 books each
function refreshUI(list) {
var lis = '';
var lis2 = '';
var lis3 = '';

for (var i = 0; i < 10 && i < list.length; i++) {

// Creates the list item by adding the firebase object + genLinks which contains the select, remove and delete icons.
lis += '
' + list[i].book + genLinks(list[i].key, list[i].book) +'
';
      };

for (var i = 10; i < 20 && i < list.length; i++) {

lis2 += '
' + list[i].book + genLinks(list[i].key, list[i].book) +'
';
      };

for (var i = 20; i < 30 && i < list.length; i++) {

 lis3 += '
' + list[i].book + genLinks(list[i].key, list[i].book) +'
';
      };

      // Populates the HTML lists with the JS list items
        document.getElementById('bookList').innerHTML = lis;
        document.getElementById('bookList2').innerHTML = lis2;
        document.getElementById('bookList3').innerHTML = lis3;
    };

// This is the area of the JS concerned with generating the icons found alongside each book name and where I need help

// The google icons wrapped in divs with class names
function genLinks(key, bkName) {
var links = '';
links += '
delete
 ';
links += '
clear
 ';
links += '
check
';
return links;
};

// onClick event from the selectBook icon which hides the tick and replaces with a cross
function showRemove() {
  document.getElementById('removeBook').style.display = 'block';
  document.getElementById('selectBook').style.display = 'none';
}

// onClick event from the removeBook icon which hides the cross and replaces with a tick
function showAdd() {
  document.getElementById('selectBook').style.display = 'block';
  document.getElementById('removeBook').style.display = 'none';
}

I was told by somebody to use getElementsByClassName() but they gave no explanation on how to do so. If anybody has any advice or could offer some help I would really appreciate it.

Thanks in advance,

G

Body:
You can use CSS to control the icon that is displayed. Also using checkboxes makes it easy to know what is selected. Than it is a simple query and loop to get the checked items.

function buildList() {
   /* Get the checked checkboxes */
   var checkboxes = document.querySelectorAll('[name="books"]:checked');
   /* Build up list of the values by looping over the elements */
   var out = [];
   for (var i=0; i<checkboxes.length; i++) {
       out.push(checkboxes[i].value);
   }
   /* Join list together and display it */
   document.getElementById("output").innerHTML = out.join(", ")
}
document.getElementById("booklist").addEventListener("change", buildList);
buildList();

[name="books"] {  /* Hide checkbox */
  display: none
}

[name="books"]+i+i { /* Hide the x when not checked */
  display: none
}

[name="books"]:checked+i {  /* Hide the check when checked */
  display: none
}

[name="books"]:checked+i+i { /* show the x when checked */
  display: inline
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<ul id="booklist">
  <li>
    <label>
      <span>Book 1</span>
      <input type="checkbox" value="book1" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 2</span>
      <input type="checkbox" value="book2" name="books" checked/>
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 3</span>
      <input type="checkbox" value="book3" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 4</span>
      <input type="checkbox" value="book4" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
</ul>

<div id="output"></div>

And we can alter it slightly to handle multiple lists. This time we can use a data attribute to say where to output the item. And we use a loop to add the event listeners to the parents.

(function() {
  function buildList(listId) {
    /* Get the checked checkboxes */
    var checkboxes = document.querySelectorAll('#' + listId + ' [name="books"]:checked');
    /* Build up list of the values by looping over the elements */
    var out = [];
    for (var i = 0; i < checkboxes.length; i++) {
      out.push(checkboxes[i].value);
    }
    var outputId = document.getElementById(listId).dataset.output;
    /* Join list together and display it */
    document.getElementById(outputId).innerHTML = out.join(", ")
  }

  var lists = document.querySelectorAll(".book-list");
  for (var i = 0; i < lists.length; i++) {
    (function(list) {
      list.addEventListener("change", function() {
        buildList(list.id)
      });
      buildList(list.id);
    }(lists[i]))
  }
}());

[name="books"] {
  /* Hide checkbox */
  display: none
}

[name="books"]+i+i {
  /* Hide the x when not checked */
  display: none
}

[name="books"]:checked+i {
  /* Hide the check when checked */
  display: none
}

[name="books"]:checked+i+i {
  /* show the x when checked */
  display: inline
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<ul id="booklist1" class="book-list" data-output="output1">
  <li>
    <label>
      <span>Book 1</span>
      <input type="checkbox" value="book1" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 2</span>
      <input type="checkbox" value="book2" name="books" checked/>
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 3</span>
      <input type="checkbox" value="book3" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 4</span>
      <input type="checkbox" value="book4" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
</ul>

<div id="output1"></div>

<ul id="booklist2" class="book-list" data-output="output2">
  <li>
    <label>
      <span>Book 5</span>
      <input type="checkbox" value="book5" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 6</span>
      <input type="checkbox" value="book6" name="books"/>
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 7</span>
      <input type="checkbox" value="book7" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
  <li>
    <label>
      <span>Book 8</span>
      <input type="checkbox" value="book8" name="books" />
      <i class="fa fa-check-square-o" aria-hidden="true"></i>
      <i class="fa fa-times" aria-hidden="true"></i>
    </label>
  </li>
</ul>

<div id="output2"></div>


来源: stackexchange

问:
Merging mulit-valued dictionaries
Lets say I have two dictionaries with multiple values per key:

```<code>Dict1 = { key1 : [value1,value2] }
Dict2 = { key1 : [value3,value4], key2 : [value5,value6]}
</code>```

I want to merge them into one dictionary like this:

```<code>mergedDict = { key 1 : [value1,value2,value3,value4], key 2 : [0,0,value5,value6] }
</code>```

答:
This should do it, and covers possibity of Dict1 having keys that Dict2 doesn't:

```<code>Dict1 = {'key1': ['value1', 'value2'], 'key3': ['value7', 'value8']}
Dict2 = { 'key1' : ['value3','value4'], 'key2' : ['value5', 'value6']}

mergedDict = {k: [0, 0] + v  if k not in Dict1 else Dict1[k] + v for k, v in Dict2.items()}
mergedDict.update({i: j + [0, 0] for i, j in Dict1.items() if i not in Dict2})
#{'key3': ['value7', 'value8', 0, 0], 'key2': [0, 0, 'value5', 'value6'], 'key1': ['value1', 'value2', 'value3', 'value4']}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Merging mulit-valued dictionaries

Body:
Lets say I have two dictionaries with multiple values per key:

Dict1 = { key1 : [value1,value2] }
Dict2 = { key1 : [value3,value4], key2 : [value5,value6]}

I want to merge them into one dictionary like this:

mergedDict = { key 1 : [value1,value2,value3,value4], key 2 : [0,0,value5,value6] }

Body:
This should do it, and covers possibity of Dict1 having keys that Dict2 doesn't:

Dict1 = {'key1': ['value1', 'value2'], 'key3': ['value7', 'value8']}
Dict2 = { 'key1' : ['value3','value4'], 'key2' : ['value5', 'value6']}

mergedDict = {k: [0, 0] + v  if k not in Dict1 else Dict1[k] + v for k, v in Dict2.items()}
mergedDict.update({i: j + [0, 0] for i, j in Dict1.items() if i not in Dict2})
#{'key3': ['value7', 'value8', 0, 0], 'key2': [0, 0, 'value5', 'value6'], 'key1': ['value1', 'value2', 'value3', 'value4']}


问:
VBA Excel Change Content of another Cell based on content of one cell
Can you help me with this. The Excel looks something like this:

I hope to automate 2 tasks:

When cells in Column C contains word "processed" => clear content in corresponding cell in column A

When cells in Column C contains word "blue" => change corresponding cell in column B to 0

I have tried Offset, Looping and other various method but can't seem to get it right. Please help.

答:
```<code>Sub removeprocessed()
Dim Nlines As Long
Dim i As Long
Nlines = Columns(1).Find("*", , , , xlByColumns, xlPrevious).Row
For i = 2 To Nlines
    If 0 <> InStr(1, Cells(i, 3).Value, "processed") Then
        Cells(i, 1).Value = ""
    End If
    If 0 <> InStr(1, Cells(i, 3).Value, "blue") Then
        Cells(i, 2).Value = 0
    End If
Next
End Sub
</code>```

Using InStr as proposed by @UGP

Body:
Sub removeprocessed()
Dim Nlines As Long
Dim i As Long
Nlines = Columns(1).Find("*", , , , xlByColumns, xlPrevious).Row
For i = 2 To Nlines
    If 0 <> InStr(1, Cells(i, 3).Value, "processed") Then
        Cells(i, 1).Value = ""
    End If
    If 0 <> InStr(1, Cells(i, 3).Value, "blue") Then
        Cells(i, 2).Value = 0
    End If
Next
End Sub

Using InStr as proposed by @UGP


问:
CKeditor and Razor syntax
Does anyone knows how to implement razor syntax to be rendered when using CKediotr. I want to enter c# code in CKEditor but Im not able to do that because it renders all content as a text.

Sample:

I want to enter e.g. @DateTime.Now.Year inside ckeditor.

and other more complex types.

Thanks,

答:
TinyMCE, (F)CKEditor, et al are HTML editors, and are not designed for C# (or PHP, ASP, CFM...) functions. While you could possible right something for evaluating the text and figuring out what you need to do, it becomes a royally complex PIA. There are two ways that I have seen that work with decent results.

The first method would be to have the output from your (CK) Editor saved as a partial view, and then calling that inside of a parent view. The problem with this method is that if someone who does not know Razor makes an error it will kill the page. Same thing occurs for other programming errors.

The second method would be to create placeholders for common items, and then doing an evaluation method for replacements.

```<code>string BodyContent = GetPageContent(PageID); // whatever to grab CKEditor content
BodyContent = BodyContent.Replace("##Year##", DateTime.Now.ToString("yyyy"));
// other replacements here
</code>```

And then on the view you would just call that variable accordingly. It is limited as to what you can do, but that isn't always a bad thing.

Title: CKeditor and Razor syntax

Body:
TinyMCE, (F)CKEditor, et al are HTML editors, and are not designed for C# (or PHP, ASP, CFM...) functions. While you could possible right something for evaluating the text and figuring out what you need to do, it becomes a royally complex PIA. There are two ways that I have seen that work with decent results.

The first method would be to have the output from your (CK) Editor saved as a partial view, and then calling that inside of a parent view. The problem with this method is that if someone who does not know Razor makes an error it will kill the page. Same thing occurs for other programming errors.

The second method would be to create placeholders for common items, and then doing an evaluation method for replacements.

string BodyContent = GetPageContent(PageID); // whatever to grab CKEditor content
BodyContent = BodyContent.Replace("##Year##", DateTime.Now.ToString("yyyy"));
// other replacements here

And then on the view you would just call that variable accordingly. It is limited as to what you can do, but that isn't always a bad thing.


答: The functions showremove and showadd can only change one id, aka one box. If it's supposed to work with more than one box you should change selectbook and removebook to a class and add an index to access an individual one.</p>

Title: How to implement the getElementByClassName()


问:
reversing an array using pointer c
I am trying to write a code that receives the number of input numbers and integers, then reverses those order and prints them out. When I run this code it freezes from the for loop in input_integer function. What am I doing wrong?</p>

```<code># include <stdio.h>
# include <stdlib.h>

void input_integer (int *arr, int *arrSize);
void inverse_reorder (int *arr, int *arrSize);

int main (void){
    int* arrSize;
    int* arr;
    int i;

    input_integer(arr, arrSize);
    printf("inputted data : ");
    for ( i = 0; i < *arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }
    inverse_reorder(arr, arrSize);
    printf("reversed data : ");
    for ( i = 0; i < *arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }

    return 0;
}

void input_integer (int* arr, int *arrSize){
    printf("Array size = ? ");
    scanf("%d", arrSize);
    int i;
    for( i = 0; i < *arrSize ; i++ ){
        scanf("%d", *(arr + i));
    }
}

void inverse_reorder (int * arr, int *arrSize){
    int i;
    int temp = 0;
    for ( i = 0; i < *arrSize ; i++ ){
        temp = *(arr+i);
        *(arr+i) = *(arr + *arrSize - i);
        *(arr + *arrSize - i) = temp;
    }
}
</code>```

答:
You declare arrSize as an int *, but you never assign a value to that pointer, so it's value is indeterminate.  When you later pass the value of that pointer to scanf, it reads that garbage value and attempts to write to that invalid address.  This invokes undefined behavior.  You also never allocate space for arr.  Also, when you read in each array element, you're passing in an array value instead of the address of an array element.

You should declare arrSize as an int in your main function, then pass its address to input_integer to populate it.  Then in input_integer, you need use malloc to allocate space for the array.  You'll also need to pass in the address of arr to write to it.

```<code>int main (void){
    int arrSize;
    int *arr;
    int i;

    input_integer(&arr, &arrSize);
    printf("inputted data : ");
    for ( i = 0; i < arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }
    inverse_reorder(arr, arrSize);
    printf("reversed data : ");
    for ( i = 0; i < arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }

    return 0;
}

void input_integer (int **arr, int *arrSize){
    printf("Array size = ? ");
    scanf("%d", arrSize);
    *arr = malloc(*arrSize * sizeof(int));
    if (*arr == NULL) {
        perror("malloc failed");
        exit(1);
    }
    int i;
    for( i = 0; i < *arrSize ; i++ ){
        scanf("%d", *arr + i);
    }
}

void inverse_reorder (int *arr, int arrSize){
    int i;
    int temp = 0;
    for ( i = 0; i < arrSize ; i++ ){
        temp = *(arr+i);
        *(arr+i) = *(arr + arrSize - i);
        *(arr + arrSize - i) = temp;
    }
}
</code>```

Title: reversing an array using pointer c

Body:
I am trying to write a code that receives the number of input numbers and integers, then reverses those order and prints them out. When I run this code it freezes from the for loop in input_integer function. What am I doing wrong?

# include <stdio.h>
# include <stdlib.h>

void input_integer (int *arr, int *arrSize);
void inverse_reorder (int *arr, int *arrSize);

int main (void){
    int* arrSize;
    int* arr;
    int i;

    input_integer(arr, arrSize);
    printf("inputted data : ");
    for ( i = 0; i < *arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }
    inverse_reorder(arr, arrSize);
    printf("reversed data : ");
    for ( i = 0; i < *arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }

    return 0;
}

void input_integer (int* arr, int *arrSize){
    printf("Array size = ? ");
    scanf("%d", arrSize);
    int i;
    for( i = 0; i < *arrSize ; i++ ){
        scanf("%d", *(arr + i));
    }
}

void inverse_reorder (int * arr, int *arrSize){
    int i;
    int temp = 0;
    for ( i = 0; i < *arrSize ; i++ ){
        temp = *(arr+i);
        *(arr+i) = *(arr + *arrSize - i);
        *(arr + *arrSize - i) = temp;
    }
}

Body:
You declare arrSize as an int *, but you never assign a value to that pointer, so it's value is indeterminate.  When you later pass the value of that pointer to scanf, it reads that garbage value and attempts to write to that invalid address.  This invokes undefined behavior.  You also never allocate space for arr.  Also, when you read in each array element, you're passing in an array value instead of the address of an array element.

You should declare arrSize as an int in your main function, then pass its address to input_integer to populate it.  Then in input_integer, you need use malloc to allocate space for the array.  You'll also need to pass in the address of arr to write to it.

int main (void){
    int arrSize;
    int *arr;
    int i;

    input_integer(&arr, &arrSize);
    printf("inputted data : ");
    for ( i = 0; i < arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }
    inverse_reorder(arr, arrSize);
    printf("reversed data : ");
    for ( i = 0; i < arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }

    return 0;
}

void input_integer (int **arr, int *arrSize){
    printf("Array size = ? ");
    scanf("%d", arrSize);
    *arr = malloc(*arrSize * sizeof(int));
    if (*arr == NULL) {
        perror("malloc failed");
        exit(1);
    }
    int i;
    for( i = 0; i < *arrSize ; i++ ){
        scanf("%d", *arr + i);
    }
}

void inverse_reorder (int *arr, int arrSize){
    int i;
    int temp = 0;
    for ( i = 0; i < arrSize ; i++ ){
        temp = *(arr+i);
        *(arr+i) = *(arr + arrSize - i);
        *(arr + arrSize - i) = temp;
    }
}


问:
How do I make a different icon name for the home screen and the App Store?
How do I make a different icon name for the home screen and the App Store in iPhone?</p>

答:
Apple requires that all of the icons, including the large 512x512 pixel icon for iTunes, be effectively identical. In my experience the large one can be more detailed (graphic textures, etc.), as long as anyone who saw both icons would be able to clearly tell they were for the same app.

The same rule is true for the name of the app in iTunes and the name that shows below the icon on the device: an average user should be able to easily tell that the names match in some way. I've had success with the name on the device being a shortened version of the full name, dropping things like articles ("the," "a," "an") and short prepositions ("for," "by," "on," etc.). I've also had to shorten the app name to its initials ("Fighting Chicks Unlimited" became "FCU"), and it passed without problem.

I have a couple of developer friends who have had their app rejected for the icons looking too dissimilar and for the name in the App Store and the one on the device being too different, so I know Apple definitely has a line you don't want to cross.

I advise that unless there's a very compelling reason for the icons or names to be drastically different, don't bother trying; rejection and resubmission can take weeks.

ContentLicense: CC BY-SA 2.5


问:
Jump to method signature from code inside the method, or find out in which method the cursor is currently
I am doing reverse engineering of code that someone else wrote. When I search for all references of a variable or method and click on one of the results it beams my cursor right away on the line of code where it is used (which is a brilliant feature). Visual Studio shows me the class where this variable or method is used but not the method. The problem is that sometimes I end up in a huge method deep within, and the only thing I really need is the name of this cursed method.

Question: Is there a simple way to jump to the signature of the method in which the cursor is situated? Or any other way to find it out? (Besides scrolling dozens of pages of code upwards and likely missing it)

答:
In Visual Studio 2015 on the top right of the code editing window there's a drop-down list that contains all the method in the current file:

When you move from one method to another inside a file, the selected item in this drop-down list is updated accordingly.

Therefore if you put the cursor in the middle of a method the drop-down list should automatically change the selected item matching the method you're in.

Now if you open the drop-down list and select the current method it should take you to the method's signature.


问:
Reflect Laser off collider
I'm trying to accurately reflect a LaserBeam off a wall/collider.  The Laser Beam is fired from a LaserGun and is small, measuring around 2.

So I have currently set my LaserBeam as a 3D Capsule and coloured it red.  Its pretty ugly, but I'm not too concerned just now.

Whenever the LaserBeam collides with an Object/Wall it doesn't rebound as I would like.  I suppose it would have to be completely absorbed by the wall/collider so that the direction would be pointing the correct way.

The image in the website below should explain what I'm trying to achieve.
http://answers.unity3d.com/questions/631311/making-an-object-bounce-off-a-wall-the-same-way-li.html
(If the LaserBeam was an Arrow.  And the arrow is the InDirection and once the Arrow has collided with the wall, it would be in the direction of the Result).

I have set both the Drag and AngularDrag to 0.
In my Capsule material.  Dynamic and Static Friction is set to 0.  Bounciness is 1.  FrictionCombine is Min and BounceCombine is Max.

I'm wondering if I have to change the 3D Capsule to a LineRenderer?

Any help would be greatly appreciated.

答:
Have you tried using a TrailRenderer component?

This way you would have your "Laser" set up as a small sphere (which size will be your lasers width): on this object, you'll have the following componennts:

Transform (kinda obvious)

SphereCollider (you can set its size and give it a bouncy physic material)

RigidBody (set both drags to zero, use gravity to false and freeze all rotations)

TrailRenderer (here you can adjust the visual of your laser: width, material, length (using the Time property), ...)

To "fire" a laser you simply have to set this object as a prefab and instantiate it at a given position, afterward simply set the RigidBody velocity according to the desired speed/direction :)

One benefit of this method is you can easily register to OnCollision[...] events and use them to your needs.

Hope this helps,

Title: Reflect Laser off collider


问:
firebaseAuth.getCurrentUser() return null DisplayName
When I signIn with my google account and get the name with the getDisplayName(), my name appear correctly, but in the AuthStateListener doesn't.

here part of my code:

```<code>private void handleSignInResult(GoogleSignInResult result) {

    Alert.dismissProgress();

    if (result.isSuccess()) {
        GoogleSignInAccount acct = result.getSignInAccount();

        if(acct != null) {
            Log.i("NAME", acct.getDisplayName()); <-- RETURN MY NAME CORRECTLY
            credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
            fuser.linkWithCredential(credential).addOnCompleteListener(authResult);
        } else {
            //ERROR
        }

    } else {
        //ERROR
    }
}
</code>```

But in my AuthStateListener

```<code>@Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser nuser = firebaseAuth.getCurrentUser();

        if (nuser != null) {

            Log.i("NAME", nuser.getDisplayName()); <--- RETURN NULL
        }
    }
</code>```

Somebody know why this can happen?

答:
This issue is resolved in the  latest verison of firebase ui
compile 'com.firebaseui:firebase-ui:1.2.0'</p>

Body:
When I signIn with my google account and get the name with the getDisplayName(), my name appear correctly, but in the AuthStateListener doesn't.

here part of my code:

private void handleSignInResult(GoogleSignInResult result) {

    Alert.dismissProgress();

    if (result.isSuccess()) {
        GoogleSignInAccount acct = result.getSignInAccount();

        if(acct != null) {
            Log.i("NAME", acct.getDisplayName()); <-- RETURN MY NAME CORRECTLY
            credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
            fuser.linkWithCredential(credential).addOnCompleteListener(authResult);
        } else {
            //ERROR
        }

    } else {
        //ERROR
    }
}

But in my AuthStateListener

@Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser nuser = firebaseAuth.getCurrentUser();

        if (nuser != null) {

            Log.i("NAME", nuser.getDisplayName()); <--- RETURN NULL
        }
    }

Somebody know why this can happen?


问:
python multithreading wait till all threads finished
This may have been asked in a similar context but I was unable to find an answer after about 20 minutes of searching, so I will ask.

I have written a Python script (lets say: scriptA.py) and a script (lets say scriptB.py)

In scriptB I want to call scriptA multiple times with different arguments, each time takes about an hour to run, (its a huge script, does lots of stuff.. don't worry about it) and I want to be able to run the scriptA with all the different arguments simultaneously, but I need to wait till ALL of them are done before continuing; my code:

```<code>import subprocess

#setup
do_setup()

#run scriptA
subprocess.call(scriptA + argumentsA)
subprocess.call(scriptA + argumentsB)
subprocess.call(scriptA + argumentsC)

#finish
do_finish()
</code>```

I want to do run all the subprocess.call() at the same time, and then wait till they are all done, how should I do this?

I tried to use threading like the example here:

```<code>from threading import Thread
import subprocess

def call_script(args)
    subprocess.call(args)

#run scriptA
t1 = Thread(target=call_script, args=(scriptA + argumentsA))
t2 = Thread(target=call_script, args=(scriptA + argumentsB))
t3 = Thread(target=call_script, args=(scriptA + argumentsC))
t1.start()
t2.start()
t3.start()
</code>```

But I do not think this is right.

How do I know they have all finished running before going to my do_finish()?

答:
Maybe, something like</p>

```<code>for t in threading.enumerate():
    if t.daemon:
        t.join()
</code>```

Body:
This may have been asked in a similar context but I was unable to find an answer after about 20 minutes of searching, so I will ask.

I have written a Python script (lets say: scriptA.py) and a script (lets say scriptB.py)

In scriptB I want to call scriptA multiple times with different arguments, each time takes about an hour to run, (its a huge script, does lots of stuff.. don't worry about it) and I want to be able to run the scriptA with all the different arguments simultaneously, but I need to wait till ALL of them are done before continuing; my code:

import subprocess

#setup
do_setup()

#run scriptA
subprocess.call(scriptA + argumentsA)
subprocess.call(scriptA + argumentsB)
subprocess.call(scriptA + argumentsC)

#finish
do_finish()

I want to do run all the subprocess.call() at the same time, and then wait till they are all done, how should I do this?

I tried to use threading like the example here:

from threading import Thread
import subprocess

def call_script(args)
    subprocess.call(args)

#run scriptA
t1 = Thread(target=call_script, args=(scriptA + argumentsA))
t2 = Thread(target=call_script, args=(scriptA + argumentsB))
t3 = Thread(target=call_script, args=(scriptA + argumentsC))
t1.start()
t2.start()
t3.start()

But I do not think this is right.

How do I know they have all finished running before going to my do_finish()?

Body:
Maybe, something like

for t in threading.enumerate():
    if t.daemon:
        t.join()


问:
Java: getMinutes and getHours
How do you get Hours and Minutes since Date.getHours and Date.getMinutes got deprecated? The examples that I found on Google search used the deprecated methods.

答:
```<code>public static LocalTime time() {
    LocalTime ldt = java.time.LocalTime.now();

    ldt = ldt.truncatedTo(ChronoUnit.MINUTES);
    System.out.println(ldt);
    return ldt;
}
</code>```

This works for me

OwnerDisplayName: Alex

Title: Java: getMinutes and getHours

Body:
public static LocalTime time() {
    LocalTime ldt = java.time.LocalTime.now();

    ldt = ldt.truncatedTo(ChronoUnit.MINUTES);
    System.out.println(ldt);
    return ldt;
}

This works for me


问:
Allowing single digit in UITextField in iOS
I have a Verification ViewController, I get 4 digit verification code by SMS and I need to enter those code to login, I have created the ViewController like this

As you can see four UITextFields, I need to allow only single digit for each UITextField,

What I tried: I was trying to use shouldChangeCharactersInRange:method: , but its not getting called, I don't know what's wrong, I think because UITextFields are in UITableView so it is not working.

答:
try this : - For swift 3.0

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // On inputing value to textfield
    if ((textField.text?.characters.count)! < 1  && string.characters.count > 0){
        let nextTag = textField.tag + 1;

        // get next responder
        let nextResponder = textField.superview?.viewWithTag(nextTag);
        textField.text = string;

        if (nextResponder == nil){
            textField.resignFirstResponder()
        }
        nextResponder?.becomeFirstResponder();
        return false;
    }
    else if ((textField.text?.characters.count)! >= 1  && string.characters.count == 0){
        // on deleting value from Textfield
        let previousTag = textField.tag - 1;

        // get next responder
        var previousResponder = textField.superview?.viewWithTag(previousTag);

        if (previousResponder == nil){
            previousResponder = textField.superview?.viewWithTag(1);
        }
        textField.text = "";
        previousResponder?.becomeFirstResponder();
        return false;
    }
    return true;
}
</code>```

converted Anurag Soni answer in swift 3.0

You just have to implement this method only.

Body:
try this : - For swift 3.0

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // On inputing value to textfield
    if ((textField.text?.characters.count)! < 1  && string.characters.count > 0){
        let nextTag = textField.tag + 1;

        // get next responder
        let nextResponder = textField.superview?.viewWithTag(nextTag);
        textField.text = string;

        if (nextResponder == nil){
            textField.resignFirstResponder()
        }
        nextResponder?.becomeFirstResponder();
        return false;
    }
    else if ((textField.text?.characters.count)! >= 1  && string.characters.count == 0){
        // on deleting value from Textfield
        let previousTag = textField.tag - 1;

        // get next responder
        var previousResponder = textField.superview?.viewWithTag(previousTag);

        if (previousResponder == nil){
            previousResponder = textField.superview?.viewWithTag(1);
        }
        textField.text = "";
        previousResponder?.becomeFirstResponder();
        return false;
    }
    return true;
}

converted Anurag Soni answer in swift 3.0

You just have to implement this method only.


问:
System.ComponentModel.Win32Exception: The system cannot find the file specified
I been working on a website and when i finished everything was working properly then when i published it on somee.com i had an error when i tried to log in

PS.. log in credentials are not from a database, so i don't get why I'm receiving a database related error, and when i go back to visula studio and run the site it works without any errors

```<code>        if (TextBoxUserName.Text == "administrator" && TextBoxPassword.Text == "aphamia")
        {
            Session["user_ID"] = TextBoxUserName.Text;
            Response.Redirect("EmpLogin.aspx");
        }
        else
            LabelLogin.Text = "Icorrect Username or Password";

        if (Session["user_ID"] != null)
            PanelLogIn.Visible = false;
</code>```

答: Most probably your connection string is wrong.</p>

Body:
I been working on a website and when i finished everything was working properly then when i published it on somee.com i had an error when i tried to log in

PS.. log in credentials are not from a database, so i don't get why I'm receiving a database related error, and when i go back to visula studio and run the site it works without any errors

        if (TextBoxUserName.Text == "administrator" && TextBoxPassword.Text == "aphamia")
        {
            Session["user_ID"] = TextBoxUserName.Text;
            Response.Redirect("EmpLogin.aspx");
        }
        else
            LabelLogin.Text = "Icorrect Username or Password";

        if (Session["user_ID"] != null)
            PanelLogIn.Visible = false;


问:
How can I group similar results from mySQL database in foreach loop?
```<code>$pdo = $db->prepare('SELECT * FROM animals WHERE id = :id ');
$pdo->execute(array('id' => $id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
     $name = $row["name"];
     echo $name."<br>";
}
</code>```

The result of my loop is right now-

```<code>cat
cat
cat
cat
dog
bird
</code>```

I want to group results if they are similar, so I get as a result like this-

```<code>cat
dog
bird
</code>```

答:
You can use GROUP BY

Example

```<code> $pdo = $db->prepare('SELECT * FROM animals WHERE id = :id  GROUP BY name');
</code>```

OR you can use DISTINCT

Example-

```<code>$pdo = $db->prepare('SELECT DISTINCT name FROM animals WHERE id = :id');
</code>```

Body:
$pdo = $db->prepare('SELECT * FROM animals WHERE id = :id ');
$pdo->execute(array('id' => $id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
     $name = $row["name"];
     echo $name."
";
}

The result of my loop is right now-

cat
cat
cat
cat
dog
bird

I want to group results if they are similar, so I get as a result like this-

cat
dog
bird

Body:
You can use GROUP BY

Example

 $pdo = $db->prepare('SELECT * FROM animals WHERE id = :id  GROUP BY name');

OR you can use DISTINCT

Example-

$pdo = $db->prepare('SELECT DISTINCT name FROM animals WHERE id = :id');


问:
Storyboard show viewcontrollers in reversed Preview (Xcode 8.3.2)
Xcode 8.3.2 shows the viewControllers in a reversed preview like a mirror (screenshot attached). I don't know whether it's an Xcode bug or a hidden feature. I'm facing a problem due to this. Is there any way to recover the viewControllers in the original preview and to resolve this issue?

答:
Reinstall the Xcode.Because the same problem was faced by me.
I think it happens when me having many viewController in storyBoard and we keep changing the file at that time this occur.</p>

ContentLicense: CC BY-SA 4.0


问:
How to reffer in CSS to an input which has class attached to?
I have the following problem: I have an form with a few inputs. At the end of the form I have a submit and a reset button, which are inputs. I have a style in my CSS file for inputs (white background), but I want to write another style for inputs which are buttons (type=submit and type=reset).

I have tried to make a style named .button, and adding it to the input ( <input class=button) but the properties from the input style are used, not the properties from the .button style.

Any help would be appreciated.

答:
Just take a look on attribute selectors from CSS2.1 specification:

[attribute-name=value] - this selector will match every element with attribute-name set on value value. So all you need is input[type=submit], input[type=reset] selector.


问:
Validating the type of django queryset related objects parameters
Does django provide a way to validate the model type in django queryset when for example filtering by related objects? Let's say we have the following models:

```<code>class Person(models.Model):
    name = models.CharField(max_length=5)

class Author(models.Model):
    name = models.CharField(max_length=25)

class Book(models.Model):
    name = models.CharField(max_length=5)
    author = models.ForeignKey(Author)
</code>```

And

```<code>p = Person.objects.all().first()
query = Book.objects.filter(author=p)
</code>```

filters all books which auhtor_id is equal to given person_id (p_id), although Book refers to Author, not to Person.

Of course this is the responsibility of a programmer to avoid such errors but it's sitll possible.

This happens in django 1.7

答:
If author_id is same as person_id you can filter using the id directly:

```<code>query = Book.objects.filter(author_id=p.id)
</code>```

Body:
Does django provide a way to validate the model type in django queryset when for example filtering by related objects? Let's say we have the following models:

class Person(models.Model):
    name = models.CharField(max_length=5)

class Author(models.Model):
    name = models.CharField(max_length=25)

class Book(models.Model):
    name = models.CharField(max_length=5)
    author = models.ForeignKey(Author)

And

p = Person.objects.all().first()
query = Book.objects.filter(author=p)

filters all books which auhtor_id is equal to given person_id (p_id), although Book refers to Author, not to Person.

Of course this is the responsibility of a programmer to avoid such errors but it's sitll possible.

This happens in django 1.7

Body:
If author_id is same as person_id you can filter using the id directly:

query = Book.objects.filter(author_id=p.id)


问:
Android ask for multi permissions
I have an app which need to ask first for two permission , to read contacts and write file in extrernal storage. The problem is that when the app open at first time crash and ask for the permissions, when I reopen it all is good the app is run smoothly.
MainActivity.java

```<code>public class MainActivity extends AppCompatActivity implements
        LoaderManager.LoaderCallbacks<Cursor>,
        AdapterView.OnItemClickListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener
        {

    /**
     * Global variables
     */
    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    private ListView mContactsList; //the listview to display contacts
    private LinearLayout contactLayout; //the listview item layout for each contact
    private SimpleCursorAdapter mCursorAdapter; // An adapter that binds the result Cursor to the ListView
    private boolean bigmode = false; //flag indicating whether we are currently using the normal or big contact layout
    public GoogleApiClient mApiClient; //client to the google play services activity detection
    private int activityDetectionInterval = 3000; //how often to request an activity detection in milliseconds

    /*
     * Defines an array that contains column names to move from
     * the Cursor to the ListView (we really just want the name).
     */

    private final static String[] FROM_COLUMNS = {
            ContactsContract.Contacts.DISPLAY_NAME
    };

    /*
     * Defines an array that contains column names to retrieve from the
     * contacts DB when we query it (we really just want the name).
     */

    private static final String[] PROJECTION =
            {
                    ContactsContract.Contacts._ID,
                    ContactsContract.Contacts.DISPLAY_NAME
            };

    /*
     * Defines an array that contains resource ids for the listview item layout views
     * that get the Cursor column contents.
     */

    private final static int[] TO_IDS = {
            R.id.label
    };

    /**
     * Methods
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        askpermissions();

       /* showContacts(); // Ask permission to read contacts
        showlogs(); // Ask permission to create file where we write the logs*/

        setContentView(R.layout.activity_main);

        // set up the action toolbar

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // set up the listview by retrieving contacts

        mContactsList = (ListView) findViewById(R.id.listView);
        //setup an adapter to populate the listview
        mCursorAdapter = new SimpleCursorAdapter(
                this,
                R.layout.contacts_list_item,
                null,
                FROM_COLUMNS, TO_IDS,
                0);

            // Sets the adapter for the ListView
        mContactsList.setAdapter(mCursorAdapter);
        // set up the listener for the listview - it will be handled by code in this activity
        mContactsList.setOnItemClickListener(this);
        //call the cursor loader
        getLoaderManager().initLoader(0, null, this);
        // set up the "zoom" button

        final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        // set up the click action - toggle between big and normal layouts
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                toggleDisplaySize();
            }
        });

        // set up the client for google play services so we can request activity detection later
        Log.i("START", "Start");
        writefile("START");
        mApiClient = new GoogleApiClient.Builder(this)
                .addApi(ActivityRecognition.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        mApiClient.connect();

                mContactsList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                Log.i("Scroll", "Scroll list"); // When user scrolled the list
                writefile("SCROLL");
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * when the application is ready to be brought to the front, we must assess whether to use
     * the big or normal layouts
     */
    @Override
    public void onResume() {
        super.onResume();

        //check the shared preference value set by the activity detection service

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        if (sp.getBoolean("isWalking", false)) {
            bigmode = false;
        } else {
            bigmode = true;
        }
        //set the appropriate layout for the listview
        toggleDisplaySize();

    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        // Starts the query and returns the result cursor

        // we only want the "name" column and also we want it sorted alphabetically
        return new CursorLoader(
                this,
                ContactsContract.Contacts.CONTENT_URI,
                PROJECTION,
                null,
                null,
                "DISPLAY_NAME ASC"
        );
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        // Put the result Cursor in the adapter for the ListView
        //Log.i("CursorLoaderFinished", "retrieved "+ cursor.getCount()+" contacts");
        mCursorAdapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // Delete the reference to the existing Cursor
        mCursorAdapter.swapCursor(null);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        // show a toast with the contact name
        Log.i("onItemClick", "Click");
        writefile("CLICK "+String.valueOf(((TextView) view.findViewById(R.id.label)).getText()));
        Log.i("Name", String.valueOf(((TextView) view.findViewById(R.id.label)).getText()));
        //writefile(String.valueOf(((TextView) view.findViewById(R.id.label)).getText()));
        Toast.makeText(this, ((TextView) view.findViewById(R.id.label)).getText(), Toast.LENGTH_SHORT).show();
    }

    /**
     * the google play services client is ready, now we can start requesting activity
     * detection updates from it
     */
    @Override
    public void onConnected(@Nullable Bundle bundle) {
        //create an intent pointing to the background service which will update our current activity
        Intent intent = new Intent(this, ActivityRecognizedService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        //request updates
        ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mApiClient, activityDetectionInterval, pendingIntent);

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    /**
     * this method selects and sets the appropriate listview layout according to whether we should
     * be in big or normal mode (either from a zoom button click, or because the service has detected
     * that we are currently walking
     */
    public void toggleDisplaySize() {

        int layoutid;
        if (!bigmode) {
            Log.i("ZOOM", "1");//ZOOM IN
            writefile("ZOOM_1");
            layoutid = R.layout.contacts_list_item_big;
            bigmode = true;
        } else {
            Log.i("ZOOM", "0");//ZOOM OUT
            writefile("ZOOM_0");
            layoutid = R.layout.contacts_list_item;
            bigmode = false;
        }

        mCursorAdapter = new SimpleCursorAdapter(
                getApplicationContext(),
                layoutid,
                null,
                FROM_COLUMNS, TO_IDS,
                0);
        mContactsList.setAdapter(mCursorAdapter);
        getLoaderManager().initLoader(0, null, MainActivity.this);

    }

/*
    private void showContacts() {
        // Check the SDK version and whether the permission is already granted or not. To get te contacts
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }

    private void showlogs() {
        //Check the SDK version and whether the permission is already granted or not. To be able to create and write in file
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }

    }*/
public void askpermissions(){
    int PERMISSION_ALL = 1;
    String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    if(!hasPermissions(this, PERMISSIONS)){
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
    }

}

public static boolean hasPermissions(Context context, String... permissions) {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

    public void writefile(String te){
        //Write in file the logs
        te =gettime()+' '+te+'\n';
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "Logs");
        if (! file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file,true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileWriter.write(te);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

public String gettime(){
    String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
    return timeStamp;

}

}
</code>```

I ask for permission with  askpermissions(); function... There is any idea what can be wrong to my code???

答:
Edit your code like this</p>

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

   /* showContacts(); // Ask permission to read contacts
    showlogs(); // Ask permission to create file where we write the logs*/

    setContentView(R.layout.activity_main);

    // set up the action toolbar

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // set up the listview by retrieving contacts

    mContactsList = (ListView) findViewById(R.id.listView);
    //setup an adapter to populate the listview
    mCursorAdapter = new SimpleCursorAdapter(
            this,
            R.layout.contacts_list_item,
            null,
            FROM_COLUMNS, TO_IDS,
            0);

        // Sets the adapter for the ListView
    mContactsList.setAdapter(mCursorAdapter);
    // set up the listener for the listview - it will be handled by code in this activity
    mContactsList.setOnItemClickListener(this);
    //call the cursor loader
    getLoaderManager().initLoader(0, null, this);
    // set up the "zoom" button

    final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    // set up the click action - toggle between big and normal layouts
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            toggleDisplaySize();
        }
    });

    // set up the client for google play services so we can request activity detection later

askpermissions();
    }

void permissionGranted()
{ Log.i("START", "Start");
    writefile("START");
    mApiClient = new GoogleApiClient.Builder(this)
            .addApi(ActivityRecognition.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    mApiClient.connect();

            mContactsList.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState)
    {
                Log.i("Scroll", "Scroll list"); // When user scrolled the list
                writefile("SCROLL");
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        }
    });}

public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
    for (String permission : permissions) {
        if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
            return false;
        }else{
permissionGranted();}
    }
}
return true;
}

public void askpermissions(){
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE};

if(!hasPermissions(this, PERMISSIONS)){
    ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else
permissionGranted();
}
</code>```

Title: Android ask for multi permissions

Body:
I have an app which need to ask first for two permission , to read contacts and write file in extrernal storage. The problem is that when the app open at first time crash and ask for the permissions, when I reopen it all is good the app is run smoothly.
MainActivity.java

public class MainActivity extends AppCompatActivity implements
        LoaderManager.LoaderCallbacks<Cursor>,
        AdapterView.OnItemClickListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener
        {

    /**
     * Global variables
     */
    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    private ListView mContactsList; //the listview to display contacts
    private LinearLayout contactLayout; //the listview item layout for each contact
    private SimpleCursorAdapter mCursorAdapter; // An adapter that binds the result Cursor to the ListView
    private boolean bigmode = false; //flag indicating whether we are currently using the normal or big contact layout
    public GoogleApiClient mApiClient; //client to the google play services activity detection
    private int activityDetectionInterval = 3000; //how often to request an activity detection in milliseconds

    /*
     * Defines an array that contains column names to move from
     * the Cursor to the ListView (we really just want the name).
     */

    private final static String[] FROM_COLUMNS = {
            ContactsContract.Contacts.DISPLAY_NAME
    };

    /*
     * Defines an array that contains column names to retrieve from the
     * contacts DB when we query it (we really just want the name).
     */

    private static final String[] PROJECTION =
            {
                    ContactsContract.Contacts._ID,
                    ContactsContract.Contacts.DISPLAY_NAME
            };

    /*
     * Defines an array that contains resource ids for the listview item layout views
     * that get the Cursor column contents.
     */

    private final static int[] TO_IDS = {
            R.id.label
    };

    /**
     * Methods
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        askpermissions();

       /* showContacts(); // Ask permission to read contacts
        showlogs(); // Ask permission to create file where we write the logs*/

        setContentView(R.layout.activity_main);

        // set up the action toolbar

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // set up the listview by retrieving contacts

        mContactsList = (ListView) findViewById(R.id.listView);
        //setup an adapter to populate the listview
        mCursorAdapter = new SimpleCursorAdapter(
                this,
                R.layout.contacts_list_item,
                null,
                FROM_COLUMNS, TO_IDS,
                0);

            // Sets the adapter for the ListView
        mContactsList.setAdapter(mCursorAdapter);
        // set up the listener for the listview - it will be handled by code in this activity
        mContactsList.setOnItemClickListener(this);
        //call the cursor loader
        getLoaderManager().initLoader(0, null, this);
        // set up the "zoom" button

        final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        // set up the click action - toggle between big and normal layouts
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                toggleDisplaySize();
            }
        });

        // set up the client for google play services so we can request activity detection later
        Log.i("START", "Start");
        writefile("START");
        mApiClient = new GoogleApiClient.Builder(this)
                .addApi(ActivityRecognition.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        mApiClient.connect();

                mContactsList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                Log.i("Scroll", "Scroll list"); // When user scrolled the list
                writefile("SCROLL");
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * when the application is ready to be brought to the front, we must assess whether to use
     * the big or normal layouts
     */
    @Override
    public void onResume() {
        super.onResume();

        //check the shared preference value set by the activity detection service

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        if (sp.getBoolean("isWalking", false)) {
            bigmode = false;
        } else {
            bigmode = true;
        }
        //set the appropriate layout for the listview
        toggleDisplaySize();

    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        // Starts the query and returns the result cursor

        // we only want the "name" column and also we want it sorted alphabetically
        return new CursorLoader(
                this,
                ContactsContract.Contacts.CONTENT_URI,
                PROJECTION,
                null,
                null,
                "DISPLAY_NAME ASC"
        );
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        // Put the result Cursor in the adapter for the ListView
        //Log.i("CursorLoaderFinished", "retrieved "+ cursor.getCount()+" contacts");
        mCursorAdapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // Delete the reference to the existing Cursor
        mCursorAdapter.swapCursor(null);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        // show a toast with the contact name
        Log.i("onItemClick", "Click");
        writefile("CLICK "+String.valueOf(((TextView) view.findViewById(R.id.label)).getText()));
        Log.i("Name", String.valueOf(((TextView) view.findViewById(R.id.label)).getText()));
        //writefile(String.valueOf(((TextView) view.findViewById(R.id.label)).getText()));
        Toast.makeText(this, ((TextView) view.findViewById(R.id.label)).getText(), Toast.LENGTH_SHORT).show();
    }

    /**
     * the google play services client is ready, now we can start requesting activity
     * detection updates from it
     */
    @Override
    public void onConnected(@Nullable Bundle bundle) {
        //create an intent pointing to the background service which will update our current activity
        Intent intent = new Intent(this, ActivityRecognizedService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        //request updates
        ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mApiClient, activityDetectionInterval, pendingIntent);

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    /**
     * this method selects and sets the appropriate listview layout according to whether we should
     * be in big or normal mode (either from a zoom button click, or because the service has detected
     * that we are currently walking
     */
    public void toggleDisplaySize() {

        int layoutid;
        if (!bigmode) {
            Log.i("ZOOM", "1");//ZOOM IN
            writefile("ZOOM_1");
            layoutid = R.layout.contacts_list_item_big;
            bigmode = true;
        } else {
            Log.i("ZOOM", "0");//ZOOM OUT
            writefile("ZOOM_0");
            layoutid = R.layout.contacts_list_item;
            bigmode = false;
        }

        mCursorAdapter = new SimpleCursorAdapter(
                getApplicationContext(),
                layoutid,
                null,
                FROM_COLUMNS, TO_IDS,
                0);
        mContactsList.setAdapter(mCursorAdapter);
        getLoaderManager().initLoader(0, null, MainActivity.this);

    }

/*
    private void showContacts() {
        // Check the SDK version and whether the permission is already granted or not. To get te contacts
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }

    private void showlogs() {
        //Check the SDK version and whether the permission is already granted or not. To be able to create and write in file
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }

    }*/
public void askpermissions(){
    int PERMISSION_ALL = 1;
    String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    if(!hasPermissions(this, PERMISSIONS)){
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
    }

}

public static boolean hasPermissions(Context context, String... permissions) {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

    public void writefile(String te){
        //Write in file the logs
        te =gettime()+' '+te+'\n';
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "Logs");
        if (! file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file,true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileWriter.write(te);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

public String gettime(){
    String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
    return timeStamp;

}

}

I ask for permission with  askpermissions(); function... There is any idea what can be wrong to my code???

Body:
Edit your code like this

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

   /* showContacts(); // Ask permission to read contacts
    showlogs(); // Ask permission to create file where we write the logs*/

    setContentView(R.layout.activity_main);

    // set up the action toolbar

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // set up the listview by retrieving contacts

    mContactsList = (ListView) findViewById(R.id.listView);
    //setup an adapter to populate the listview
    mCursorAdapter = new SimpleCursorAdapter(
            this,
            R.layout.contacts_list_item,
            null,
            FROM_COLUMNS, TO_IDS,
            0);

        // Sets the adapter for the ListView
    mContactsList.setAdapter(mCursorAdapter);
    // set up the listener for the listview - it will be handled by code in this activity
    mContactsList.setOnItemClickListener(this);
    //call the cursor loader
    getLoaderManager().initLoader(0, null, this);
    // set up the "zoom" button

    final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    // set up the click action - toggle between big and normal layouts
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            toggleDisplaySize();
        }
    });

    // set up the client for google play services so we can request activity detection later

askpermissions();
    }

void permissionGranted()
{ Log.i("START", "Start");
    writefile("START");
    mApiClient = new GoogleApiClient.Builder(this)
            .addApi(ActivityRecognition.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    mApiClient.connect();

            mContactsList.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState)
    {
                Log.i("Scroll", "Scroll list"); // When user scrolled the list
                writefile("SCROLL");
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        }
    });}

public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
    for (String permission : permissions) {
        if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
            return false;
        }else{
permissionGranted();}
    }
}
return true;
}

public void askpermissions(){
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE};

if(!hasPermissions(this, PERMISSIONS)){
    ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}else
permissionGranted();
}


问:
hot to iterate through checkboxes placed in groupbox in proper order i.e from first to last c# windows form application
```<code>     cs.Open();
        SqlCommand cmd = new SqlCommand("SELECT * FROM SEATING", cs);
        SqlDataReader reader = cmd.ExecuteReader();
        foreach (Control c in groupBox1.Controls)
        {

                reader.Read();
                CheckBox temp = (CheckBox)c;
                int seat = reader.GetInt32(0);
                int status = reader.GetInt32(2);

                if (status == 1 && seat == Convert.ToInt32(temp.AccessibleName))
                {
                    temp.Checked = true;
                    temp.Enabled = false;
                }

        }
</code>```

this is my code for iterating through checkbox placed in groupbox,
but it iterates in reverse order from last to first
can anyone help to make it iterats from first to last

答:
Try something like this (not sure it works, I didn't test it):</p>

```<code>    cs.Open();
    SqlCommand cmd = new SqlCommand("SELECT * FROM SEATING", cs);
    SqlDataReader reader = cmd.ExecuteReader();
    foreach (Control c in groupBox1.Controls.Cast<Control>()
                                     .OrderBy(a=> a.TabIndex))
    {

            reader.Read();
            CheckBox temp = (CheckBox)c;
            int seat = reader.GetInt32(0);
            int status = reader.GetInt32(2);

            if (status == 1 && seat == Convert.ToInt32(temp.AccessibleName))
            {
                temp.Checked = true;
                temp.Enabled = false;
            }

    }
</code>```

Body:
     cs.Open();
        SqlCommand cmd = new SqlCommand("SELECT * FROM SEATING", cs);
        SqlDataReader reader = cmd.ExecuteReader();
        foreach (Control c in groupBox1.Controls)
        {

                reader.Read();
                CheckBox temp = (CheckBox)c;
                int seat = reader.GetInt32(0);
                int status = reader.GetInt32(2);

                if (status == 1 && seat == Convert.ToInt32(temp.AccessibleName))
                {
                    temp.Checked = true;
                    temp.Enabled = false;
                }

        }

this is my code for iterating through checkbox placed in groupbox,
but it iterates in reverse order from last to first
can anyone help to make it iterats from first to last

Body:
Try something like this (not sure it works, I didn't test it):

    cs.Open();
    SqlCommand cmd = new SqlCommand("SELECT * FROM SEATING", cs);
    SqlDataReader reader = cmd.ExecuteReader();
    foreach (Control c in groupBox1.Controls.Cast<Control>()
                                     .OrderBy(a=> a.TabIndex))
    {

            reader.Read();
            CheckBox temp = (CheckBox)c;
            int seat = reader.GetInt32(0);
            int status = reader.GetInt32(2);

            if (status == 1 && seat == Convert.ToInt32(temp.AccessibleName))
            {
                temp.Checked = true;
                temp.Enabled = false;
            }

    }


问:
How to keep animation working on UICollectionView
Basically I just add a simple rotate animation on an imageView which is a subview of UICollectionViewCell, the animation works fine, but when I scroll the collection view and scroll back, the animation just stoped. How to solve this problem?
This is what I added to the imageView.</p>

```<code>let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = Double.pi
rotationAnimation.duration = 2.0
rotationAnimation.repeatCount = .infinity
view.layer.add(rotationAnimation, forKey: nil)
</code>```

答:
Because you have not added key for animation, which you used when initialising rotationAnimation
change line

```<code>view.layer.add(rotationAnimation, forKey: nil)
</code>```

to

```<code>view.layer.add(rotationAnimation, forKey: "transform.rotation")
</code>```

Hope it helps

Body:
Basically I just add a simple rotate animation on an imageView which is a subview of UICollectionViewCell, the animation works fine, but when I scroll the collection view and scroll back, the animation just stoped. How to solve this problem?
This is what I added to the imageView.

let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = Double.pi
rotationAnimation.duration = 2.0
rotationAnimation.repeatCount = .infinity
view.layer.add(rotationAnimation, forKey: nil)

Body:
Because you have not added key for animation, which you used when initialising rotationAnimation
change line

view.layer.add(rotationAnimation, forKey: nil)

to

view.layer.add(rotationAnimation, forKey: "transform.rotation")

Hope it helps


问:
Get all HTML data EXCEPT mailto: and tel: in BS4 Python decompose()
I need to take out phone numbers and Emails from HTML.

I can get the data.

```<code>description_source = soup.select('a[href^="mailto:"]'),
                     soup.select('a[href^="tel:"]')
</code>```

But I do not want it.

I am trying to use

decompose

```<code>description_source = soup.decompose('a[href^="mailto:"]')
</code>```

I get this error

TypeError: decompose() takes 1 positional argument but 2 were given

I have thought about using

SoupStrainer

But it looks like i would have to include everything but the mailto and tel to get the correct information...

full current code for this bit is this

```<code>import requests
from bs4 import BeautifulSoup as bs4

item_number = '122124438749'

ebay_url = "http://vi.vipr.ebaydesc.com/ws/eBayISAPI.dll?ViewItemDescV4&item=" + item_number
r = requests.get(ebay_url)
html_bytes = r.text
soup = bs4(html_bytes, 'html.parser')

description_source = soup.decompose('a[href^="mailto:"]')
#description_source.

print(description_source)
</code>```

答:
Try using find_all(). Find all the links in that page and then check which ones contain phone and email. Then remove them using extract().

Use lxml parser for faster processing. It's also recommended to use in the official documentation.

```<code>import requests
from bs4 import BeautifulSoup

item_number = '122124438749'

ebay_url = "http://vi.vipr.ebaydesc.com/ws/eBayISAPI.dll?ViewItemDescV4&item=" + item_number
r = requests.get(ebay_url)
html_bytes = r.text
soup = BeautifulSoup(html_bytes, 'lxml')

links = soup.find_all('a')
email = ''
phone = ''

for link in links:
    if(link.get('href').find('tel:') > -1):
        link.extract()

    elif(link.get('href').find('mailto:') > -1):
        link.extract()

print(soup.prettify())
</code>```

You can use decompose() also instead of extract().

Body:
I need to take out phone numbers and Emails from HTML.

I can get the data.

description_source = soup.select('a[href^="mailto:"]'),
                     soup.select('a[href^="tel:"]')

But I do not want it.

I am trying to use

decompose

description_source = soup.decompose('a[href^="mailto:"]')

I get this error

TypeError: decompose() takes 1 positional argument but 2 were given

I have thought about using

SoupStrainer

But it looks like i would have to include everything but the mailto and tel to get the correct information...

full current code for this bit is this

import requests
from bs4 import BeautifulSoup as bs4

item_number = '122124438749'

ebay_url = "http://vi.vipr.ebaydesc.com/ws/eBayISAPI.dll?ViewItemDescV4&item=" + item_number
r = requests.get(ebay_url)
html_bytes = r.text
soup = bs4(html_bytes, 'html.parser')

description_source = soup.decompose('a[href^="mailto:"]')
#description_source.

print(description_source)

Body:
Try using find_all(). Find all the links in that page and then check which ones contain phone and email. Then remove them using extract().

Use lxml parser for faster processing. It's also recommended to use in the official documentation.

import requests
from bs4 import BeautifulSoup

item_number = '122124438749'

ebay_url = "http://vi.vipr.ebaydesc.com/ws/eBayISAPI.dll?ViewItemDescV4&item=" + item_number
r = requests.get(ebay_url)
html_bytes = r.text
soup = BeautifulSoup(html_bytes, 'lxml')

links = soup.find_all('a')
email = ''
phone = ''

for link in links:
    if(link.get('href').find('tel:') > -1):
        link.extract()

    elif(link.get('href').find('mailto:') > -1):
        link.extract()

print(soup.prettify())

You can use decompose() also instead of extract().


答:
```<code>p = Person.objects.all().first()
query = Book.objects.filter(author=p)
</code>```

Did you actually try this? According to me it should raise a ValueError Something along the lines of 'Must be a Author instance"

Now if you want to avoid this error, you need to use an id, and Moses as usual has a good answer showing how it's done.

Title: Validating the type of django queryset related objects parameters

Body:
p = Person.objects.all().first()
query = Book.objects.filter(author=p)

Did you actually try this? According to me it should raise a ValueError Something along the lines of 'Must be a Author instance"

Now if you want to avoid this error, you need to use an id, and Moses as usual has a good answer showing how it's done.


问:
Send file in memory to API from Node Express
I've an API in Node and Express which is receiving a file from a the client (Postman in development) and I use multer to get the file in memory like this:

```<code>router.post('/api/v1/upload', contrl.upload, contrl.uploadFile);
</code>```

and then in my controller:

```<code>exports upload = multer({ storage: multer.memoryStorage() }).single('file');
</code>```

Now I can access the file with req.file.buffer, but then I want to send this same file to another API.
I'm using request-promise-native so this would be something like this:

```<code>const rp = require('request-promise-native')

exports.uploadFile = (req, res) => {

  const options = {
    method: 'POST',
    uri: `${uri}`,
    form: {
      file: req.file.buffer
    }
  }

  rp(options)
    .then(parsedBody => {
      return res.status(201).send(parsedBody);
    })
    .catch(err => res.status(400).send(err));
}
</code>```

I removed some other params for simplicity, but this is not working, probably because Node doesn´t know how to handle the info inside req.file.buffer.

EDIT. Ok after some tests I tried to make this work with a real file instead of using multer memoryStorage. So I got this:

```<code>exports upload = multer({ dest: 'uploads/' }).single('file');
</code>```

to save the file to disk, and then

```<code>const request = require('request')

exports.uploadFile = (req, res) => {

  const formData = {
    file: fs.createReadStream('uploads/' + req.file.filename)
  }
  const options = {
    url: `${uri}`
    formData
  }

  request.post(options, (err, response, body) => {
    if (err) return res.status(400).send(err);
    return res.status(201).send(response);
  });
}
</code>```

And it works! But then when I change to memoryStorage in multer and I use file: req.file.buffer instead, it does not work.

EDIT2: I also tried to send the file as a stream when in memory, so I tried this

```<code>const bufferStream = new stream.PassThrough();
bufferStream.end(req.file.buffer);
</code>```

and then passing it in the formData with file: bufferStream but also not working.

How can I achieve this?
Thanks

答:
This should solve your problem</p>

```<code>const http = require('http');
exports.uploadFile = (req, res) => {
    // create new request to reupload file
    const request = http.request({
        port : 80,
        hostname : '127.0.0.1',
        method : 'POST',
        path : '/'
    });
    let result = '';
    // grab response from new request
    request.on('data', (chunk) => {
        result += chunk;
    });
    // resend response from new request
    request.on('end', () => {
        res.status(201).end(result);
    });
    // resend error from new request
    request.on('error', (err) => {
        res.status(400).end(err);
    });
    // pipe your file to new request
    req.file.stream.pipe(request);
};
</code>```

Body:
I've an API in Node and Express which is receiving a file from a the client (Postman in development) and I use multer to get the file in memory like this:

router.post('/api/v1/upload', contrl.upload, contrl.uploadFile);

and then in my controller:

exports upload = multer({ storage: multer.memoryStorage() }).single('file');

Now I can access the file with req.file.buffer, but then I want to send this same file to another API.
I'm using request-promise-native so this would be something like this:

const rp = require('request-promise-native')

exports.uploadFile = (req, res) => {

  const options = {
    method: 'POST',
    uri: `${uri}`,
    form: {
      file: req.file.buffer
    }
  }

  rp(options)
    .then(parsedBody => {
      return res.status(201).send(parsedBody);
    })
    .catch(err => res.status(400).send(err));
}

I removed some other params for simplicity, but this is not working, probably because Node doesn´t know how to handle the info inside req.file.buffer.

EDIT. Ok after some tests I tried to make this work with a real file instead of using multer memoryStorage. So I got this:

exports upload = multer({ dest: 'uploads/' }).single('file');

to save the file to disk, and then

const request = require('request')

exports.uploadFile = (req, res) => {

  const formData = {
    file: fs.createReadStream('uploads/' + req.file.filename)
  }
  const options = {
    url: `${uri}`
    formData
  }

  request.post(options, (err, response, body) => {
    if (err) return res.status(400).send(err);
    return res.status(201).send(response);
  });
}

And it works! But then when I change to memoryStorage in multer and I use file: req.file.buffer instead, it does not work.

EDIT2: I also tried to send the file as a stream when in memory, so I tried this

const bufferStream = new stream.PassThrough();
bufferStream.end(req.file.buffer);

and then passing it in the formData with file: bufferStream but also not working.

How can I achieve this?
Thanks

Body:
This should solve your problem

const http = require('http');
exports.uploadFile = (req, res) => {
    // create new request to reupload file
    const request = http.request({
        port : 80,
        hostname : '127.0.0.1',
        method : 'POST',
        path : '/'
    });
    let result = '';
    // grab response from new request
    request.on('data', (chunk) => {
        result += chunk;
    });
    // resend response from new request
    request.on('end', () => {
        res.status(201).end(result);
    });
    // resend error from new request
    request.on('error', (err) => {
        res.status(400).end(err);
    });
    // pipe your file to new request
    req.file.stream.pipe(request);
};


问:
POSTMAN : parsing a JSON response, how deep can I go into the response?
I'm currently trying to parse precisely a JSON response (using POSTMAN).

The JSON response has the following structure (I use ... to skip irrelevant info):

*

```<code>{
  "href": ...,
  "offset": ...,
  "limit": ...,
  "first": ...,
  "last": ...,
  "entries": [
    {
      "href": ...,
      "id": ...,
      "name": "MY_FIRST_ITEM_NAME",
      "tags": [
        ...,
        ...
      ],
      "objectClass": [
        ...
      ],
      "attributes": {
        ...,
        ...,
        ...,
        "device.type": "MY_ITEM_TYPE,
        ...
      },
      ...
    },
    {
      "href": ...,
      "id": ...,
      "name": "MY_SECOND_ITEM_NAME",
      "tags": [
        ...,
        ...
      ],
      "objectClass": [
        ...
      ],
      "attributes": {
        ...,
        ...,
        ...,
        "device.type": "MY_ITEM_TYPE,
        ...
      },
      ...
    },
    ...
    ]
}*
</code>```

I want to test several known values:
tests["test first item"] = responseBody.has("MY_FIRST_ITEM_NAME")
this works, but I also want to check the associated device type
if I use responseBody.has("MY_ITEM_TYPE") I can't figure out to which item it is related to, so I try to make a more precise checking:
*

```<code>tests["test entries 0"] = body.entries[0].name === "MY_FIRST_ITEM_NAME"*;
this works but when it comes to test the device type:
tests["test entries 0"] = body.entries[0].attributes.device.type
</code>```

it ends up with an error "TypeError: Cannot read property 'type' of undefined"

With the console I can see the attributes (doing console.log(body.entries[0].attributes);) but it is not possible to go one step deeper. Is it a postman limitation ? is there another way to reach precisely this device.type information ?

Thank you for help

Alexandre

答:
Oups ! sorry for the edit, I'm quite new to this. Here is the answer for this problem,
The device.type attribute can be reached this way:
body.entries[0].attributes['device.type']

There are some limitations though:
- I can't use .attributes[2], 2 being the index of the element if 'attributes' could be seen as a table.
- The syntax is particular, it doesn't work if we use double-quotes instead of single-quotes
- I still don't know why it happens at this stage ... if someone knows, I'll be happy to read from him

Cheers

Alexandre

Body:
I'm currently trying to parse precisely a JSON response (using POSTMAN).

The JSON response has the following structure (I use ... to skip irrelevant info):

*

{
  "href": ...,
  "offset": ...,
  "limit": ...,
  "first": ...,
  "last": ...,
  "entries": [
    {
      "href": ...,
      "id": ...,
      "name": "MY_FIRST_ITEM_NAME",
      "tags": [
        ...,
        ...
      ],
      "objectClass": [
        ...
      ],
      "attributes": {
        ...,
        ...,
        ...,
        "device.type": "MY_ITEM_TYPE,
        ...
      },
      ...
    },
    {
      "href": ...,
      "id": ...,
      "name": "MY_SECOND_ITEM_NAME",
      "tags": [
        ...,
        ...
      ],
      "objectClass": [
        ...
      ],
      "attributes": {
        ...,
        ...,
        ...,
        "device.type": "MY_ITEM_TYPE,
        ...
      },
      ...
    },
    ...
    ]
}*

I want to test several known values:
tests["test first item"] = responseBody.has("MY_FIRST_ITEM_NAME")
this works, but I also want to check the associated device type
if I use responseBody.has("MY_ITEM_TYPE") I can't figure out to which item it is related to, so I try to make a more precise checking:
*

tests["test entries 0"] = body.entries[0].name === "MY_FIRST_ITEM_NAME"*;
this works but when it comes to test the device type:
tests["test entries 0"] = body.entries[0].attributes.device.type

it ends up with an error "TypeError: Cannot read property 'type' of undefined"

With the console I can see the attributes (doing console.log(body.entries[0].attributes);) but it is not possible to go one step deeper. Is it a postman limitation ? is there another way to reach precisely this device.type information ?

Thank you for help

Alexandre