问:
Making a more efficient function - Word counter
I'm going through some C programming questions and I want to make sure I got the fundamentals down. Currently I'm on a word counter question:

Q: Write a function which will determine how many words are in a given string. You can assume that one or more
consecutive white spaces is a delimiter between words, and that the string you pass to your function is null terminated.

I got the thing working, but efficiency is important. I'm wondering how it can be improved. Have to use pointers and no other library besides #include(stdio.h) Thanks!

```<code>#include <stdio.h>
int word_counter(char string[])
{
  //We start with first word unless we have a empty string then we have no words
  int count;
  if(*string!='\0'){
    count=1;
}
  else{
    count=0;
    return 0;
  }
  //while we dont reach the end of the string
  while(*string!='\0'){
    //if we detect a whitespace
    if(*string==' '){
      //get previous character
      string--;
      // If previous character is not a space we increase the count
      // Otherwise we dont since we already counted a word
      if(*string!=' '){
        count++;
      }
      //return pointer to current character
      string++;
    }
    // set pointer to next character
    string++;
  }
  return count;
}

//just to test if it works
int main(void)
{
    char str[] = "Hello World!";
    printf("How many words? = %i\n", word_counter(str));
    return 0;
}
</code>```

答:
Looking at your code, I see there's a special case for the initial condition of an empty string. Sometimes getting the initial condition out of the way early simplifies the rest of the algorithm, sometimes you can eliminate it by changing how you look at the problem. This time it's the second one.

If you think about this as counting the boundaries between words, the algorithm becomes simpler. There's two ways to define a word boundary, from the front, and from the back.

```<code>"  Prestidigitation  \n"
   ^               ^
   front           back
</code>```

Are we looking for a non-whitespace character after a whitespace character? Or are we looking for a whitespace character after a non-whitespace character?

You also have code that looks backwards in the string (string--), that's often not safe because what if the string starts with whitespace? Then you've walked backwards off the string, so moving backwards should be avoided.

Finally, there's the problem of whether or not there's any whitespace at the end of the string. We'd have to special case the end of the string.

So looking at the first word boundary is the way to go: a non-whitespace character after a whitespace character. Instead of looking backwards, we'll track the state of the previous character (last_was_space below).

That's a non-whitespace character after a whitespace character. What if the string doesn't start with whitespace?

```<code>"Basset hounds got long ears."
 ^
 What about this?
</code>```

Since we have last_was_space, we can initialize it to true and pretend the start of the string starts with whitespace. This also handles leading whitespace like "   this is four words".

Finally, there's more types of space than just space like tab and newline and other exotic stuff. Instead of writing if( *space == ' ' || *space == '\n' == ... ) we can use switch to make things tidy and efficient. This is one of those rare cases where you want to take advantage of its "fall through" mechanic to do the same thing for multiple cases.

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

// Note that it's `const` since we don't touch the string memory.
int word_counter(const char string[]) {
    // Start with no words.
    int count = 0;

    // Pretend every word starts with space.
    short last_was_space = 1;

    // Using a for loop to make the movement of the pointer more apparent
    for( ; *string!='\0'; string++ ) {
        // A switch can be faster than an if/else if.
        switch( *string ) {
            // There's more than one type of whitespace.
            // These are from isspace().
            // It takes advantage of switch's fall through.
            case ' ':
            case '\t':
            case '\n':
            case '\r':
            case '\v':
            case '\f':
                // Remember we saw a space.
                last_was_space = 1;
                break;
            default:
                if( last_was_space ) {
                    // Non-whitespace after space, count it
                    count++;

                    // Remember we didn't see a space.
                    last_was_space = 0;
                }
                break;
        }
    }

    return count;
}
</code>```

Normally I'd use bool from stdbool.h and isspace from ctype.h, but your exercise can only use stdio.h.

Body:
I'm going through some C programming questions and I want to make sure I got the fundamentals down. Currently I'm on a word counter question:

Q: Write a function which will determine how many words are in a given string. You can assume that one or more
consecutive white spaces is a delimiter between words, and that the string you pass to your function is null terminated.

I got the thing working, but efficiency is important. I'm wondering how it can be improved. Have to use pointers and no other library besides #include(stdio.h) Thanks!

#include <stdio.h>
int word_counter(char string[])
{
  //We start with first word unless we have a empty string then we have no words
  int count;
  if(*string!='\0'){
    count=1;
}
  else{
    count=0;
    return 0;
  }
  //while we dont reach the end of the string
  while(*string!='\0'){
    //if we detect a whitespace
    if(*string==' '){
      //get previous character
      string--;
      // If previous character is not a space we increase the count
      // Otherwise we dont since we already counted a word
      if(*string!=' '){
        count++;
      }
      //return pointer to current character
      string++;
    }
    // set pointer to next character
    string++;
  }
  return count;
}

//just to test if it works
int main(void)
{
    char str[] = "Hello World!";
    printf("How many words? = %i\n", word_counter(str));
    return 0;
}

Body:
Looking at your code, I see there's a special case for the initial condition of an empty string. Sometimes getting the initial condition out of the way early simplifies the rest of the algorithm, sometimes you can eliminate it by changing how you look at the problem. This time it's the second one.

If you think about this as counting the boundaries between words, the algorithm becomes simpler. There's two ways to define a word boundary, from the front, and from the back.

"  Prestidigitation  \n"
   ^               ^
   front           back

Are we looking for a non-whitespace character after a whitespace character? Or are we looking for a whitespace character after a non-whitespace character?

You also have code that looks backwards in the string (string--), that's often not safe because what if the string starts with whitespace? Then you've walked backwards off the string, so moving backwards should be avoided.

Finally, there's the problem of whether or not there's any whitespace at the end of the string. We'd have to special case the end of the string.

So looking at the first word boundary is the way to go: a non-whitespace character after a whitespace character. Instead of looking backwards, we'll track the state of the previous character (last_was_space below).

That's a non-whitespace character after a whitespace character. What if the string doesn't start with whitespace?

"Basset hounds got long ears."
 ^
 What about this?

Since we have last_was_space, we can initialize it to true and pretend the start of the string starts with whitespace. This also handles leading whitespace like "   this is four words".

Finally, there's more types of space than just space like tab and newline and other exotic stuff. Instead of writing if( *space == ' ' || *space == '\n' == ... ) we can use switch to make things tidy and efficient. This is one of those rare cases where you want to take advantage of its "fall through" mechanic to do the same thing for multiple cases.

#include <stdio.h>

// Note that it's `const` since we don't touch the string memory.
int word_counter(const char string[]) {
    // Start with no words.
    int count = 0;

    // Pretend every word starts with space.
    short last_was_space = 1;

    // Using a for loop to make the movement of the pointer more apparent
    for( ; *string!='\0'; string++ ) {
        // A switch can be faster than an if/else if.
        switch( *string ) {
            // There's more than one type of whitespace.
            // These are from isspace().
            // It takes advantage of switch's fall through.
            case ' ':
            case '\t':
            case '\n':
            case '\r':
            case '\v':
            case '\f':
                // Remember we saw a space.
                last_was_space = 1;
                break;
            default:
                if( last_was_space ) {
                    // Non-whitespace after space, count it
                    count++;

                    // Remember we didn't see a space.
                    last_was_space = 0;
                }
                break;
        }
    }

    return count;
}

Normally I'd use bool from stdbool.h and isspace from ctype.h, but your exercise can only use stdio.h.


来源: stackexchange

问:
mb_strtolower not working
I have the following string:

```<code>$var = "RUA TANGARA"
</code>```

And I'm doing:

```<code>echo mb_strtolower(preg_replace('/[^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $var)), 'UTF-8');
</code>```

But this still returning "RUA TANGARA".

I use the preg_replace() because $var can be "RÜÁ TÃNAGARA".

Can someone help me?

答:
Try </p>

```<code>$newStr = strtolower($var);

echo $newStr;
</code>```

ContentLicense: CC BY-SA 3.0

Title: mb_strtolower not working

Body:
I have the following string:

$var = "RUA TANGARA"

And I'm doing:

echo mb_strtolower(preg_replace('/[^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $var)), 'UTF-8');

But this still returning "RUA TANGARA".

I use the preg_replace() because $var can be "RÜÁ TÃNAGARA".

Can someone help me?

Body:
Try

$newStr = strtolower($var);

echo $newStr;


问:
Getting the bits of a string in C++
I need to get bits of a character. I haven't used C++ bitwise operators before, and I can't figure out what I'm doing wrong.</p>

```<code>int main()
{
    bool bits[8];
    char c = static_cast<char>(0b11101101);
    for(int i = 0; i < 8; i++) {
        bits[i] = (c >> i) & 1;
    }
    for(int i = 0; i < 8; i++) {
        std::cout << bits[i];
    }
}
//output: 10110111
</code>```

答:
Just change your first loop to:</p>

```<code>for(int i = 0; i < 8; i++) {
    bits[7-i] = (c >> i ) & 1;
}
</code>```

Title: Getting the bits of a string in C++

Body:
I need to get bits of a character. I haven't used C++ bitwise operators before, and I can't figure out what I'm doing wrong.

int main()
{
    bool bits[8];
    char c = static_cast<char>(0b11101101);
    for(int i = 0; i < 8; i++) {
        bits[i] = (c >> i) & 1;
    }
    for(int i = 0; i < 8; i++) {
        std::cout << bits[i];
    }
}
//output: 10110111

Body:
Just change your first loop to:

for(int i = 0; i < 8; i++) {
    bits[7-i] = (c >> i ) & 1;
}


问:
Regex_match for particular character of given string c++
I am trying to find the match the characters of a string(s) to a specific set of characters ("aeiou").

Once matched, I intend to reverse the order of the vowels.

I get an error for matching function for regex_match(). Not sure if I can pass a character as an argument for a regex_match?

EDIT:
    ERROR: no matching function for call to 'regex_match(__gnu_cxx::__alloc_traits >::value_type&, std::__cxx11::regex&)'

This is what my code looks like:

```<code>string reverseVowels(string s) {

    vector<int> v;
    std::regex r("[aeiou]");

    for (int i=0;i<s.length();j++)       //find all vowels and push back to vector
    {
        if (std::regex_match(s[i],r)))
        {
            v.push_back(i);
        }
    }

    for (int j=0;j<v.size()/2;j++)      //swap first and last element
    {
        char temp=s[v[j]];
        s[v[i]]=s[v[v.size()-1]];
        s[v[v.size()-1-j]]=temp;
    }
    return s;
}
</code>```

答:
As were stated in the comments, regex_match does not work on char. Also match is intended if you are interested if a string matches your regex. You seem to be interested in finding all occurrences, which can be achieved with regex iterators. Something like that:

```<code>for (auto i = std::sregex_iterator(s.begin(), s.end(), r); i != std::sregex_iterator(); ++i) {
    v.push_back(i->position());
}
</code>```

Body:
I am trying to find the match the characters of a string(s) to a specific set of characters ("aeiou").

Once matched, I intend to reverse the order of the vowels.

I get an error for matching function for regex_match(). Not sure if I can pass a character as an argument for a regex_match?

EDIT:
    ERROR: no matching function for call to 'regex_match(__gnu_cxx::__alloc_traits >::value_type&, std::__cxx11::regex&)'

This is what my code looks like:

string reverseVowels(string s) {

    vector<int> v;
    std::regex r("[aeiou]");

    for (int i=0;i<s.length();j++)       //find all vowels and push back to vector
    {
        if (std::regex_match(s[i],r)))
        {
            v.push_back(i);
        }
    }

    for (int j=0;j<v.size()/2;j++)      //swap first and last element
    {
        char temp=s[v[j]];
        s[v[i]]=s[v[v.size()-1]];
        s[v[v.size()-1-j]]=temp;
    }
    return s;
}

Body:
As were stated in the comments, regex_match does not work on char. Also match is intended if you are interested if a string matches your regex. You seem to be interested in finding all occurrences, which can be achieved with regex iterators. Something like that:

for (auto i = std::sregex_iterator(s.begin(), s.end(), r); i != std::sregex_iterator(); ++i) {
    v.push_back(i->position());
}


问:
Edit VBA code that Consolidates Workbooks
I have a macro here that consolidates all files into a master file. Currently this copies the entire worksheet from each file and stacks it into the master file. This ideal code will go into source file and find the header row and copy below. The header row is not static. Sometimes its on Row 5, sometimes row 15. There is data above the header and its usually long text strings.

How do I edit the below code to do that?

 Thanks In Advance!

Here is the Code:

```<code> Sub Consolidate_BST()

 Dim SummarySheet As Worksheet
 Dim FolderPath As String
 Dim NRow As Long
 Dim FileName As String
 Dim WorkBk As Workbook
 Dim sourceRange As Range
 Dim destrange As Range

 Worksheets("Consolidate BSts").Range("A1:J50000").ClearContents
 Application.AskToUpdateLinks = False
 Application.DisplayAlerts = False
 ' Create a new workbook and set a variable to the first sheet.
 Set SummarySheet = ThisWorkbook.Sheets("Consolidate BSts")

 ' Modify this folder path to point to the files you want to use. 'M
 FolderPath = "C:\Users\413315\Documents\\March Bluesheets"

 ' NRow keeps track of where to insert new rows in the destination workbook.
 NRow = 1

 ' Call Dir the first time, pointing it to all Excel files in the folder path.
 FileName = Dir(FolderPath & "*.xl*")

 ' Loop until Dir returns an empty string.
 Do While FileName <> ""
 ' Open a workbook in the folder
 Set WorkBk = Workbooks.Open(FolderPath & FileName)

 ' Set the cell in column A to be the file name.
 SummarySheet.Range("A" & NRow).Value = FileName

 ' Modify this range for your workbooks.
 ' It can span multiple rows.
 Set sourceRange = WorkBk.Worksheets("Regional Estimates").Range("B3:J1000")

 ' Set the destination range to start at column B and
 ' be the same size as the source range.
 Set destrange = SummarySheet.Range("B" & NRow)
 Set destrange = destrange.Resize(sourceRange.Rows.Count, _
 sourceRange.Columns.Count)

 ' Copy over the values from the source to the destination.
 destrange.Value = sourceRange.Value

 ' Increase NRow so that we know where to copy data next.
 NRow = NRow + destrange.Rows.Count

 ' Close the source workbook without saving changes.
 WorkBk.Close savechanges:=False

 ' Use Dir to get the next file name.
 FileName = Dir()
 Loop

 SummarySheet.Columns.AutoFit
 Worksheets("Consolidate BSts").Range("D2:D50000").ClearContents

 End Sub
</code>```

答:
Assuming that the header is always in the same column, you could add something like the following to the top of your code:

```<code>Dim cond As Boolean
Dim headerRow As Integer, i As Integer
cond = False

While cond <> True

    i = i + 1
    If sourceRange.Cells(i, 1) = "Name of Header" Then     'For a header in column A
        i = headerRow
        cond = True
    End If
Wend
</code>```

Then with you should be able to modify the range of data that it intakes based on what row the headers are in.

Also you could change the if statement to something more general, but it's hard to know what it should be without knowing what your headers and data look like.

Body:
I have a macro here that consolidates all files into a master file. Currently this copies the entire worksheet from each file and stacks it into the master file. This ideal code will go into source file and find the header row and copy below. The header row is not static. Sometimes its on Row 5, sometimes row 15. There is data above the header and its usually long text strings.

How do I edit the below code to do that?

 Thanks In Advance!

Here is the Code:

 Sub Consolidate_BST()

 Dim SummarySheet As Worksheet
 Dim FolderPath As String
 Dim NRow As Long
 Dim FileName As String
 Dim WorkBk As Workbook
 Dim sourceRange As Range
 Dim destrange As Range

 Worksheets("Consolidate BSts").Range("A1:J50000").ClearContents
 Application.AskToUpdateLinks = False
 Application.DisplayAlerts = False
 ' Create a new workbook and set a variable to the first sheet.
 Set SummarySheet = ThisWorkbook.Sheets("Consolidate BSts")

 ' Modify this folder path to point to the files you want to use. 'M
 FolderPath = "C:\Users\413315\Documents\\March Bluesheets"

 ' NRow keeps track of where to insert new rows in the destination workbook.
 NRow = 1

 ' Call Dir the first time, pointing it to all Excel files in the folder path.
 FileName = Dir(FolderPath & "*.xl*")

 ' Loop until Dir returns an empty string.
 Do While FileName <> ""
 ' Open a workbook in the folder
 Set WorkBk = Workbooks.Open(FolderPath & FileName)

 ' Set the cell in column A to be the file name.
 SummarySheet.Range("A" & NRow).Value = FileName

 ' Modify this range for your workbooks.
 ' It can span multiple rows.
 Set sourceRange = WorkBk.Worksheets("Regional Estimates").Range("B3:J1000")

 ' Set the destination range to start at column B and
 ' be the same size as the source range.
 Set destrange = SummarySheet.Range("B" & NRow)
 Set destrange = destrange.Resize(sourceRange.Rows.Count, _
 sourceRange.Columns.Count)

 ' Copy over the values from the source to the destination.
 destrange.Value = sourceRange.Value

 ' Increase NRow so that we know where to copy data next.
 NRow = NRow + destrange.Rows.Count

 ' Close the source workbook without saving changes.
 WorkBk.Close savechanges:=False

 ' Use Dir to get the next file name.
 FileName = Dir()
 Loop

 SummarySheet.Columns.AutoFit
 Worksheets("Consolidate BSts").Range("D2:D50000").ClearContents

 End Sub

Body:
Assuming that the header is always in the same column, you could add something like the following to the top of your code:

Dim cond As Boolean
Dim headerRow As Integer, i As Integer
cond = False

While cond <> True

    i = i + 1
    If sourceRange.Cells(i, 1) = "Name of Header" Then     'For a header in column A
        i = headerRow
        cond = True
    End If
Wend

Then with you should be able to modify the range of data that it intakes based on what row the headers are in.

Also you could change the if statement to something more general, but it's hard to know what it should be without knowing what your headers and data look like.


问:
What a "Comparable interface" specifically
Is "Comparable" a Single Abstract Method interface or an Abstarct interface in java ?(I am using it in a TreeSet and my class contains "compareTo" method)</p>

答:
Java Comparable interface is used to order the objects of user-defined
  class.This interface is found in java.lang package and contains only
  one method named compareTo(Object). It provide single sorting sequence
  only i.e. you can sort the elements on based on single data member
  only. For example it may be rollno, name, age or anything else.

public int compareTo(Object obj): is used to compare the current object with the specified object

Example is as below

```<code>class Student implements Comparable<Student>{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}

public int compareTo(Student st){
if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}
</code>```

And this compareTo method is used for sorting like below

```<code>public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));

Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
</code>```

This will print the result like this

```<code>105 Jai 21
101 Vijay 23
106 Ajay 27
</code>```

for more detail you can refer this link

Body:
Java Comparable interface is used to order the objects of user-defined
  class.This interface is found in java.lang package and contains only
  one method named compareTo(Object). It provide single sorting sequence
  only i.e. you can sort the elements on based on single data member
  only. For example it may be rollno, name, age or anything else.

public int compareTo(Object obj): is used to compare the current object with the specified object

Example is as below

class Student implements Comparable<Student>{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}

public int compareTo(Student st){
if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}

And this compareTo method is used for sorting like below

public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));

Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}

This will print the result like this

105 Jai 21
101 Vijay 23
106 Ajay 27

for more detail you can refer this link


问:
Why is the size 127 (prime) better than 128 for a hash-table?
Supposing simple uniform hashing, that being, any given value is equally like to hash into any of the slots of the hash. Why is it better to use a table of size 127 and not 128? I really don't understand what's the problem with the power of 2 numbers. Or how it actually makes any difference at all.

When  using  the  division  method,
  we  usually  avoid  certain  values
  of  m (table size). For example, m
  should not be a power of 2, since if m
  = 2^p  , then h(k) is just the p lowest-order bits of k.

Let's suppose the possible elements are only between 1 and 10000 and I picked the table size as 128. How can 127 be better?
So 128 is 2^6 (1000000) and 127 is 0111111. What difference does this make? All numbers (when hashed) are still going to be the p lowest-order bits of k for 127 too. Did I get something wrong?

I'm looking for some examples as I really can't understand why is this bad. Thanks a lot in advance!

PS: I am aware of:
Hash table: why size should be prime?

答:
I believe that it just has to do with the fact that computers work
  with in base 2. Something similar happens with base 10.

...

Picking a big enough, non-power-of-two number will make sure the hash function really is a function of all the input bits, rather than
  a subset of them.

From Why hash tables should use a prime-number size.


问:
SSIS how to build unique filename in Expression
I would like to create random unique filename in SSIS using expression builder for Flat file connection Manager - ConnectionString.

Should be like: "Custom name" + "unique part" + "csv"

Actualy a timestamp in miliseconds would do.

Any idea?

答:
I found that it was easy to find how to create the expression but difficult to find instructions on how to set your output filename to use this expression.  It is not a straightforward process.  Here is an answer to this problem.  I hope this helps somebody.

https://blogs.msdn.microsoft.com/sqlgardner/2015/06/18/ssis-tip-using-a-file-path-parameter-for-multiple-flat-files/#comment-1755


问:
Dynamically adding a button using jquery
I've got an mvc app in .net that i'm trying to dynamically add buttons. Below is a sample of the jquery i'm using. It's a fairly long sequence of html that's appended but it works and those buttons are added. But when the buttons click they don't seem to activate a click event handler that i've got.

```<code>$('#imageCont').append('<div class="row tier" id="tier'+ tierIdCount +'"  ><hr/><h3>Tier</h3><button type="button" class="btn btn-default addPerson">Add Person</button><button type="button" class="btn btn-default removePerson">Remove Person</button></div>');
</code>```

Thanks.

答:
I imagine you have event handler with jQuery like this:

```<code>$('.removePerson').on('click',
   function(e){
       //do some stuff
   });
</code>```

And if you changed this first line with

```<code>$(document).on('click', '.removePerson',
   function(e){
       //do some stuff
   });
</code>```

everything should start working as you expect. Dynamically added html elements have to use delegated events, because listeners are attached to elements which are already present in DOM

Body:
I've got an mvc app in .net that i'm trying to dynamically add buttons. Below is a sample of the jquery i'm using. It's a fairly long sequence of html that's appended but it works and those buttons are added. But when the buttons click they don't seem to activate a click event handler that i've got.

$('#imageCont').append('

Tier
<button type="button" class="btn btn-default addPerson">Add Person</button><button type="button" class="btn btn-default removePerson">Remove Person</button>
');

Thanks.

Body:
I imagine you have event handler with jQuery like this:

$('.removePerson').on('click',
   function(e){
       //do some stuff
   });

And if you changed this first line with

$(document).on('click', '.removePerson',
   function(e){
       //do some stuff
   });

everything should start working as you expect. Dynamically added html elements have to use delegated events, because listeners are attached to elements which are already present in DOM


问:
Build grid rows based on columns widths array PHP
I have an array of column widths +  content that I need to process and build row  based on them.

```<code>$content = array(
    '100',
    '80',
    '25',
    '25',
    '25',
    '25',
    '50',
    '50',
    '-1',
    '33.333333333333',
    '33.333333333333',
    '33.333333333333',
    '50',
    '50',
    '100',
    '16.666666666667',
    '-1'
);
</code>```

-1  means that this is not a column , but a text or shortcode and it should not be wrapped in to row.

from the above array desired processed array should be

```<code>$content = array(
    '[row]100[/row]',
    '[row]80[/row]',
    '[row]25',
    '25',
    '25',
    '25[/row]',
    '[row]50',
    '50[/row]',
    '-1',
    '[row]33.333333333333',
    '33.333333333333',
    '33.333333333333[/row]',
    '[row]50',
    '50[/row]',
    '[row]100[/row]',
    '[row]16.666666666667[/row]',
    '-1'
);
</code>```

I have tried a loop with a starting accumulator 0 that I was adding width from loop but is simply buggy.

Any help is appreciated.

答:
Map your array.</p>

```<code>$start = [
    '100',
    '80',
    '25',
    // ...removed for brevity
];

function process(array $data) {
    $output = array_map(function ($row, $index) use ($data) {
        if ($row == '-1') {
            return '-1';
        }

        $value = $row;

        $previousIndex = $index - 1;
        $nextIndex = $index + 1;

        // Check previous row
        if (
            // There's a row and it's different
            (isset($data[$previousIndex]) && $data[$previousIndex] != $row)
            ||
            // There's no row, we're on the beggining of the list
            !isset($data[$previousIndex])
        ) {
            $value = '[row]' . $value;
        }

        // Check next row
        if (
            // There is a next row and it's different
            (isset($data[$nextIndex]) && $data[$nextIndex] != $row)
            ||
            // There's no next row, we're on the end of the list
            !isset($data[$nextIndex])
        ) {
            $value = $value . '[/row]';
        }

        return $value;
    }, $data, array_keys($data));

    return $output;
}
</code>```

Body:
I have an array of column widths +  content that I need to process and build row  based on them.

$content = array(
    '100',
    '80',
    '25',
    '25',
    '25',
    '25',
    '50',
    '50',
    '-1',
    '33.333333333333',
    '33.333333333333',
    '33.333333333333',
    '50',
    '50',
    '100',
    '16.666666666667',
    '-1'
);

-1  means that this is not a column , but a text or shortcode and it should not be wrapped in to row.

from the above array desired processed array should be

$content = array(
    '[row]100[/row]',
    '[row]80[/row]',
    '[row]25',
    '25',
    '25',
    '25[/row]',
    '[row]50',
    '50[/row]',
    '-1',
    '[row]33.333333333333',
    '33.333333333333',
    '33.333333333333[/row]',
    '[row]50',
    '50[/row]',
    '[row]100[/row]',
    '[row]16.666666666667[/row]',
    '-1'
);

I have tried a loop with a starting accumulator 0 that I was adding width from loop but is simply buggy.

Any help is appreciated.

Body:
Map your array.

$start = [
    '100',
    '80',
    '25',
    // ...removed for brevity
];

function process(array $data) {
    $output = array_map(function ($row, $index) use ($data) {
        if ($row == '-1') {
            return '-1';
        }

        $value = $row;

        $previousIndex = $index - 1;
        $nextIndex = $index + 1;

        // Check previous row
        if (
            // There's a row and it's different
            (isset($data[$previousIndex]) && $data[$previousIndex] != $row)
            ||
            // There's no row, we're on the beggining of the list
            !isset($data[$previousIndex])
        ) {
            $value = '[row]' . $value;
        }

        // Check next row
        if (
            // There is a next row and it's different
            (isset($data[$nextIndex]) && $data[$nextIndex] != $row)
            ||
            // There's no next row, we're on the end of the list
            !isset($data[$nextIndex])
        ) {
            $value = $value . '[/row]';
        }

        return $value;
    }, $data, array_keys($data));

    return $output;
}


问:
Unable to run react-native tutorial due to TransformError with .babelrc
I am unable to get react-native run-ios to work on the basic Hello World application that Facebook ships here.

The error that appears every single time is:

TransformError: ENOENT: no such file or directory, open <path>/.babelrc

When I open .babelrc, all it says is:

```<code>{
"presets": ["react-native"]
}
</code>```

Googling this error shows the following pages:

https://github.com/facebook/react-native/issues/7906 (I tried ./node_modules/react-native/packager/packager.sh start --reset-cache, no effect)

https://github.com/facebook/react-native/issues/7666
(I do not understand the cause and resolution of this error per this thread)

https://github.com/erikras/react-redux-universal-hot-example/issues/1266
(This does not seem to be related to my issue)

https://github.com/goatslacker/alt/issues/558
(I attempted to remove .babelrc but it had no effect)

My version is:

$ react-native --version
react-native-cli: 2.0.1
react-native: 0.42.3

I am running OSX 10.12.2, XC 8.3

Can anyone explain the cause, and propose a resolution? Thanks!

答: I had a packager running in another window from an old project that I needed to kill. Once I did that, it started working again.</p>

Body:
I am unable to get react-native run-ios to work on the basic Hello World application that Facebook ships here.

The error that appears every single time is:

TransformError: ENOENT: no such file or directory, open <path>/.babelrc

When I open .babelrc, all it says is:

{
"presets": ["react-native"]
}

Googling this error shows the following pages:

https://github.com/facebook/react-native/issues/7906 (I tried ./node_modules/react-native/packager/packager.sh start --reset-cache, no effect)

https://github.com/facebook/react-native/issues/7666
(I do not understand the cause and resolution of this error per this thread)

https://github.com/erikras/react-redux-universal-hot-example/issues/1266
(This does not seem to be related to my issue)

https://github.com/goatslacker/alt/issues/558
(I attempted to remove .babelrc but it had no effect)

My version is:

$ react-native --version
react-native-cli: 2.0.1
react-native: 0.42.3

I am running OSX 10.12.2, XC 8.3

Can anyone explain the cause, and propose a resolution? Thanks!


问:
Can I specify or select a member of a class (and use it as parameter )?
For example, let's say I have:

```<code>class AB { float a,b; };
</code>```

How do I write one function that can process either a or b, based on a parameter that's passed in, in a "proper" way? I want to do something like this:

```<code>float getSqrt(AB x, ClassMemberSelector s)
{ return sqrt(x.s); }

AB x;
getSqrt(x, SelectClassMember(AB::a) ); //get square root of x.a
getSqrt(x, SelectClassMember(AB::b) ); //get square root of x.b
</code>```

答:
Sure, here are three examples:

1)

```<code>float getSqrt(const AB& ab, function<float(const AB&)> selector)
{
    return sqrt(selector(ab));
}
</code>```

which simplifies to (thanks to NathanOliver's comment):

```<code>template<typename SelectorT>
float getSqrt(AB ab, SelectorT selector)
{
    return sqrt(selector(ab));
}
</code>```

(this version is better, as it avoids copying a lambda into std::function)

and usage (same for both versions):

```<code>cout << getSqrt(x, [](const AB& ab) { return ab.a; }) << endl;
cout << getSqrt(x, [](const AB& ab) { return ab.b; }) << endl;
</code>```

2)

Another possibility would be to use a pointer to member:

```<code>float getSqrt(const AB& ab, float AB::*selector)
{
    return sqrt(ab.*selector);
}
</code>```

and usage:

```<code>cout << getSqrt(x, &AB::a) << endl;
cout << getSqrt(x, &AB::b) << endl;
</code>```

3)

And an example using TMP trait-like overload selection:

```<code>struct SelectAMemberT {};
struct SelectBMemberT {};

template<typename SelectorT>
float getSqrt(const AB& ab, SelectorT);

template<>
float getSqrt(const AB& ab, SelectAMemberT)
{
    return sqrt(ab.a);
}

template<>
float getSqrt(const AB& ab, SelectBMemberT)
{
    return sqrt(ab.b);
}

const SelectAMemberT SelectAMember;
const SelectBMemberT SelectBMember;
</code>```

and usage:

```<code>cout << getSqrt(x, SelectAMember) << endl;
cout << getSqrt(x, SelectBMember) << endl;
</code>```

Body:
For example, let's say I have:

class AB { float a,b; };

How do I write one function that can process either a or b, based on a parameter that's passed in, in a "proper" way? I want to do something like this:

float getSqrt(AB x, ClassMemberSelector s)
{ return sqrt(x.s); }

AB x;
getSqrt(x, SelectClassMember(AB::a) ); //get square root of x.a
getSqrt(x, SelectClassMember(AB::b) ); //get square root of x.b

Body:
Sure, here are three examples:

1)

float getSqrt(const AB& ab, function<float(const AB&)> selector)
{
    return sqrt(selector(ab));
}

which simplifies to (thanks to NathanOliver's comment):

template<typename SelectorT>
float getSqrt(AB ab, SelectorT selector)
{
    return sqrt(selector(ab));
}

(this version is better, as it avoids copying a lambda into std::function)

and usage (same for both versions):

cout << getSqrt(x, [](const AB& ab) { return ab.a; }) << endl;
cout << getSqrt(x, [](const AB& ab) { return ab.b; }) << endl;

2)

Another possibility would be to use a pointer to member:

float getSqrt(const AB& ab, float AB::*selector)
{
    return sqrt(ab.*selector);
}

and usage:

cout << getSqrt(x, &AB::a) << endl;
cout << getSqrt(x, &AB::b) << endl;

3)

And an example using TMP trait-like overload selection:

struct SelectAMemberT {};
struct SelectBMemberT {};

template<typename SelectorT>
float getSqrt(const AB& ab, SelectorT);

template<>
float getSqrt(const AB& ab, SelectAMemberT)
{
    return sqrt(ab.a);
}

template<>
float getSqrt(const AB& ab, SelectBMemberT)
{
    return sqrt(ab.b);
}

const SelectAMemberT SelectAMember;
const SelectBMemberT SelectBMember;

and usage:

cout << getSqrt(x, SelectAMember) << endl;
cout << getSqrt(x, SelectBMember) << endl;


问:
sp_getapplock not working? I would expect the following code to make a table inaccessible for other sessions however this is not the case
run the following in a sql server session

```<code>    CREATE DATABASE locktest
    GO

    CREATE TABLE locktest.dbo.lock_this_table (id INT)
    BEGIN TRAN
        EXEC locktest..sp_getapplock @Resource = 'lock_this_table',@LockMode = 'Exclusive'
</code>```

In a separate window, execute the following code, I would expect it to hang whilst the first transaction remains open, any idea why it doesn't?

```<code>SELECT * FROM locktest.dbo.lock_this_table

INSERT INTO  locktest.dbo.lock_this_table
SELECT 4
</code>```

答:
sp_getapplock doesn't lock tables. It is a non-SQL-Server-object locker. What does it lock, then? It locks the uniquely-named, non-case-sensitive string value called @Resource. This means that other users will only be blocked if they also use sp_getapplockto attempt to acquire a lock on the identical string value of@Resource` as was already locked by another connection.

To exclusively lock a table, you can just use this:

```<code>BEGIN TRAN;
SELECT TOP 0 * FROM locktest.dbo.lock_this_table WITH (TABLOCKX, HOLDLOCK);
-- Until the transaction is committed, this lock will be held
COMMIT TRAN;
</code>```

Then if you do any operation to the table before the above transaction is committed, such as:

```<code>SELECT * FROM locktest.dbo.lock;
</code>```

Then you will be blocked.

Body:
run the following in a sql server session

    CREATE DATABASE locktest
    GO

    CREATE TABLE locktest.dbo.lock_this_table (id INT)
    BEGIN TRAN
        EXEC locktest..sp_getapplock @Resource = 'lock_this_table',@LockMode = 'Exclusive'

In a separate window, execute the following code, I would expect it to hang whilst the first transaction remains open, any idea why it doesn't?

SELECT * FROM locktest.dbo.lock_this_table

INSERT INTO  locktest.dbo.lock_this_table
SELECT 4

Body:
sp_getapplock doesn't lock tables. It is a non-SQL-Server-object locker. What does it lock, then? It locks the uniquely-named, non-case-sensitive string value called @Resource. This means that other users will only be blocked if they also use sp_getapplockto attempt to acquire a lock on the identical string value of@Resource` as was already locked by another connection.

To exclusively lock a table, you can just use this:

BEGIN TRAN;
SELECT TOP 0 * FROM locktest.dbo.lock_this_table WITH (TABLOCKX, HOLDLOCK);
-- Until the transaction is committed, this lock will be held
COMMIT TRAN;

Then if you do any operation to the table before the above transaction is committed, such as:

SELECT * FROM locktest.dbo.lock;

Then you will be blocked.


问:
Having trouble manipulating the DOM using JQuery
I am working on Hands-On: Manipulating the DOM using JQuery in Microsoft Dev211.1 introduction to HTML and JavaScript. This code is supposed to update the H1 and H3 elements in html. I have went over the code compared to what is in the instructions and I cant get it to work. Here is my code:</p>

```<code> <!DOCTYPE html>
 <html lang="en-US">
    <head>
       <title>HTML Page</title>
       <script type="text/javascript" src="https://code.jquery.com/jquery-   2.2.2.min.js"></script>
       <script type="text/javascript" src="js/script.js"></script>
    </head>
    <body>
        <h1>H1 Header</h1>
        <hr />
        <h3>H3 Header</h3>
        <hr />
        <h3>Another H3 Header</h3>
    </body>
</html>

//JavaScript Code
$(document).ready(function () {
    manipulateDOM();
});

function manipulateDOM() {
    var h1Headers = $('h1');
    var h3Headers = $('h3');
}

 h1Headers.text('Hello World');
 h3Headers.css('color', '#37887D');
 h3Headers.first().css('text-decoration', 'line-through');
</code>```

答:
In Addition to Shakti's answer, you can change manipulateDOM() function to accept arguments so that you can use it in different places.

    $(document).ready(function () {
        var h1_header = $('h1');
        var h3_header = $('h3');

      manipulateDOM(h1_header,h3_header);
    });

    function manipulateDOM(h1Headers, h3Headers) {
     h1Headers.text('Hello World');
     h3Headers.css('color', '#37887D');
     h3Headers.first().css('text-decoration', 'line-through');
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<body>
            <h1>H1 Header</h1>
            <hr />
            <h3>H3 Header</h3>
            <hr />
            <h3>Another H3 Header</h3>
        </body></code>```

Body:
I am working on Hands-On: Manipulating the DOM using JQuery in Microsoft Dev211.1 introduction to HTML and JavaScript. This code is supposed to update the H1 and H3 elements in html. I have went over the code compared to what is in the instructions and I cant get it to work. Here is my code:

 <!DOCTYPE html>

       <title>HTML Page</title>

H1 Header

H3 Header

Another H3 Header

//JavaScript Code
$(document).ready(function () {
    manipulateDOM();
});

function manipulateDOM() {
    var h1Headers = $('h1');
    var h3Headers = $('h3');
}

 h1Headers.text('Hello World');
 h3Headers.css('color', '#37887D');
 h3Headers.first().css('text-decoration', 'line-through');

Body:
In Addition to Shakti's answer, you can change manipulateDOM() function to accept arguments so that you can use it in different places.

    $(document).ready(function () {
        var h1_header = $('h1');
        var h3_header = $('h3');

      manipulateDOM(h1_header,h3_header);
    });

    function manipulateDOM(h1Headers, h3Headers) {
     h1Headers.text('Hello World');
     h3Headers.css('color', '#37887D');
     h3Headers.first().css('text-decoration', 'line-through');
    }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<body>
            <h1>H1 Header</h1>
            <hr />
            <h3>H3 Header</h3>
            <hr />
            <h3>Another H3 Header</h3>
        </body>


问:
How do I get the function of the curve in an image?
I need get function of the curve, because i need to calculate to get lenght curve.
Firstly I try to get the function from curve

```<code>[rows, columns, numberOfColorBands] = size(grayImage);
if numberOfColorBands > 1
   grayImage = grayImage(:, :, 2); % Take green channel.
end
subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize);
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
binaryImage = grayImage < 100;
subplot(2, 2, 2);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize);
axis on;
[rows, columns] = find(binaryImage);
coefficients = polyfit(columns, rows, 3);
fittedX = linspace(min(columns), max(columns), 500);
fittedY = polyval(coefficients, fittedX);
subplot(2,2,3:4);

plot(fittedX, fittedY, 'b-', 'linewidth', 4);
grid on;
xlabel('X', 'FontSize', fontSize);
ylabel('Y', 'FontSize', fontSize);
hold on;
plot(columns, rows, 'r+', 'LineWidth', 2, 'MarkerSize', 10);
</code>```

the test image is next curve

答:
The formula for arc length (s) is

```<code>  s = Integral Sqrt[1 + (dy/dx)^2] dx,
</code>```

where the limits of the integral at the two x end points. This isn't very tractable for most curves, so you have to resort to adding up small linear pieces.

Body:
I need get function of the curve, because i need to calculate to get lenght curve.
Firstly I try to get the function from curve

[rows, columns, numberOfColorBands] = size(grayImage);
if numberOfColorBands > 1
   grayImage = grayImage(:, :, 2); % Take green channel.
end
subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize);
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
binaryImage = grayImage < 100;
subplot(2, 2, 2);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize);
axis on;
[rows, columns] = find(binaryImage);
coefficients = polyfit(columns, rows, 3);
fittedX = linspace(min(columns), max(columns), 500);
fittedY = polyval(coefficients, fittedX);
subplot(2,2,3:4);

plot(fittedX, fittedY, 'b-', 'linewidth', 4);
grid on;
xlabel('X', 'FontSize', fontSize);
ylabel('Y', 'FontSize', fontSize);
hold on;
plot(columns, rows, 'r+', 'LineWidth', 2, 'MarkerSize', 10);

the test image is next curve

Body:
The formula for arc length (s) is

  s = Integral Sqrt[1 + (dy/dx)^2] dx,

where the limits of the integral at the two x end points. This isn't very tractable for most curves, so you have to resort to adding up small linear pieces.


问:
checkbox $.change is being triggered by itself and looping because it is being modified inside $.change
I have a group of checkboxes that when you click ONE, they should ALL be checked.

When a user clicks one checkbox, it checks all the other checkboxes starting with that class name. What I want is for the user to click a checkbox, and $(".atpSelections").change is triggered only once per click.

Here's the code:

```<code>        $(".atpSelections").change(function() {
            console.log("CHANGED");

            //Check ALL other checkboxes starting with that class name:
            var className = $(this).attr("class");
            className=className.replace("atpSelections ", "");
            className=className.trim();
            className=className.split("-");

            //Get current checkbox state
            var currentState = $(this).attr("checked");

            //Now loop through all other checkboxes starting
            //with the same class name and check them:
            $("input[class*='"+className[0]+"-']").each(function(i){
                    //THIS IS TRIGGERING "$(".atpSelections").change"!!
                    if(currentState && currentState=="checked")
                    {
                        $(this).prop('checked', true);
                    }else
                    {
                        $(this).prop('checked', false);
                    }
                });
        });
</code>```

The Problem

The problem is that when the user clicks one checkbox, the $(".atpSelections").change method gets triggered over and over because $(this).prop('checked', true); triggers $(".atpSelections").change again, and it just goes round and round.

So 1 click to a checkbox triggers 100s "change" events, when I only want it triggered once.

How do I alter the checkbox's state inside $(".atpSelections").change without triggering $(".atpSelections").change again?

Attempts

I tried changing $(".atpSelections").change to $(".atpSelections").click but it had the same issue. I think $(this).prop('checked', true); triggers the click event.

Solution

I used @James 's answer and changed

var currentState = $(this).attr("checked");

to

var currentState = $(this).prop("checked") ? "checked" : "";

and it worked perfectly! Thanks.

Here's the JSFiddle: https://jsfiddle.net/zL7amo0y/

答:
The problem is with your currentState variable. Please do a console.log on it. I'm guessing it's undefined?

Below is your code fixed in both jQuery and Vanialla JS.

JQuery:

       $(".atpSelections").change(function() {

            var currentState = $(this).prop("checked");
            console.log(currentState);

            $("input[name='checkboxToCheck']").each(function(i){
                    if(currentState)
                    {
                        $(this).prop('checked', true);
                    }else
                    {
                        $(this).prop('checked', false);
                    }
                });
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myForm">
   <label for="checkbox1">Main Checkbox:</label>
   <input class="atpSelections" value="checkbox1" type="checkbox" id="checkbox1" />

   <label for="checkbox2">Checkbox2:</label>
   <input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />

   <label for="checkbox3">Checkbox3:</label>
   <input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
  </form></code>```

Vanilla JS:

   var checkbox = document.getElementById("checkbox1")
   var checkboxToCheck = document.getElementsByName("checkboxToCheck");
   checkboxToCheck = [].slice.call(checkboxToCheck);

   function checkAllBoxes() {

    checkboxToCheck.forEach((element) => {
     if (checkbox.checked) {
      element.checked = true;
     } else {
      element.checked = false;
     }
    });

   }

   checkbox.addEventListener("change", checkAllBoxes);```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <form name="myForm">
   <label for="checkbox1">Main Checkbox:</label>
   <input value="checkbox1" type="checkbox" id="checkbox1" />

   <label for="checkbox2">Checkbox2:</label>
   <input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />

   <label for="checkbox3">Checkbox3:</label>
   <input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
  </form></code>```

Body:
I have a group of checkboxes that when you click ONE, they should ALL be checked.

When a user clicks one checkbox, it checks all the other checkboxes starting with that class name. What I want is for the user to click a checkbox, and $(".atpSelections").change is triggered only once per click.

Here's the code:

        $(".atpSelections").change(function() {
            console.log("CHANGED");

            //Check ALL other checkboxes starting with that class name:
            var className = $(this).attr("class");
            className=className.replace("atpSelections ", "");
            className=className.trim();
            className=className.split("-");

            //Get current checkbox state
            var currentState = $(this).attr("checked");

            //Now loop through all other checkboxes starting
            //with the same class name and check them:
            $("input[class*='"+className[0]+"-']").each(function(i){
                    //THIS IS TRIGGERING "$(".atpSelections").change"!!
                    if(currentState && currentState=="checked")
                    {
                        $(this).prop('checked', true);
                    }else
                    {
                        $(this).prop('checked', false);
                    }
                });
        });

The Problem

The problem is that when the user clicks one checkbox, the $(".atpSelections").change method gets triggered over and over because $(this).prop('checked', true); triggers $(".atpSelections").change again, and it just goes round and round.

So 1 click to a checkbox triggers 100s "change" events, when I only want it triggered once.

How do I alter the checkbox's state inside $(".atpSelections").change without triggering $(".atpSelections").change again?

Attempts

I tried changing $(".atpSelections").change to $(".atpSelections").click but it had the same issue. I think $(this).prop('checked', true); triggers the click event.

Solution

I used @James 's answer and changed

var currentState = $(this).attr("checked");

to

var currentState = $(this).prop("checked") ? "checked" : "";

and it worked perfectly! Thanks.

Here's the JSFiddle: https://jsfiddle.net/zL7amo0y/

Body:
The problem is with your currentState variable. Please do a console.log on it. I'm guessing it's undefined?

Below is your code fixed in both jQuery and Vanialla JS.

JQuery:

       $(".atpSelections").change(function() {

            var currentState = $(this).prop("checked");
            console.log(currentState);

            $("input[name='checkboxToCheck']").each(function(i){
                    if(currentState)
                    {
                        $(this).prop('checked', true);
                    }else
                    {
                        $(this).prop('checked', false);
                    }
                });
        });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myForm">
   <label for="checkbox1">Main Checkbox:</label>
   <input class="atpSelections" value="checkbox1" type="checkbox" id="checkbox1" />

   <label for="checkbox2">Checkbox2:</label>
   <input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />

   <label for="checkbox3">Checkbox3:</label>
   <input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
  </form>

Vanilla JS:

   var checkbox = document.getElementById("checkbox1")
   var checkboxToCheck = document.getElementsByName("checkboxToCheck");
   checkboxToCheck = [].slice.call(checkboxToCheck);

   function checkAllBoxes() {

    checkboxToCheck.forEach((element) => {
     if (checkbox.checked) {
      element.checked = true;
     } else {
      element.checked = false;
     }
    });

   }

   checkbox.addEventListener("change", checkAllBoxes);

  <form name="myForm">
   <label for="checkbox1">Main Checkbox:</label>
   <input value="checkbox1" type="checkbox" id="checkbox1" />

   <label for="checkbox2">Checkbox2:</label>
   <input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />

   <label for="checkbox3">Checkbox3:</label>
   <input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
  </form>


问:
How to bind the values of the itemsource (array of strings) to a label in a ListView
I have an array of strings, that I have set as the item source of a ListView. The ListView now has the same amount of rows as the array has elements. However I don't know what to set the binding as. I know for a Dictionary I set 'Value' which works fine.

```<code>string[] array = {"1","2","3"};
MyListView.ItemsSource = array;
</code>```

XAML

```<code><ListView x:Name="MyListView">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Label Text="{Binding Value, StringFormat='The value : {0:N}'}" />
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

答:
If you want to bind directly to the value of the object itself, use the "." syntax for the path</p>

```<code><Label Text="{Binding .}" />
</code>```

Body:
I have an array of strings, that I have set as the item source of a ListView. The ListView now has the same amount of rows as the array has elements. However I don't know what to set the binding as. I know for a Dictionary I set 'Value' which works fine.

string[] array = {"1","2","3"};
MyListView.ItemsSource = array;

XAML

<ListView x:Name="MyListView">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>

            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Body:
If you want to bind directly to the value of the object itself, use the "." syntax for the path

<Label Text="{Binding .}" />


问:
Is it possible to send traceroutes from Linux Azure VM?
I have created a Linux Azure VM. And I want to send traceroutes from it to my home ip address. However traceroute times out on every hop.
I have configured the VM to have public static IP address.
And to have inbound and outbound rules for all ports.

Does anybody know what else needs to be configured there in order to successfully send a traceroute?

An interesting fact is that traceroutes succeed from Windows Server Azure VM, but not from Linux Ubuntu 16.04.

The VM has a static IP attached in both cases: Linux and Windows.

One more detail: On Windows Azure VM first 5 hops do not reply, but other ones do. On Linux Azure VM every hop doesn't reply.

答:
Jason Ye - MSFT's information is correct, but his answer doesn't actually answer your question.

Traceroue doesn't work on Azure since Azure, by default blocks all ICMP traffic. Since traceroute identifies hops by receiving an ICMP packet (ICMP Time to Live expired) from each hop, you don't see any hops.

This is the same reason why ping doesn't work to from the Internet to machines within Azure.

To work around that, you can give your VM an instance IP address.


问:
How to expose a remote controller
I need help at Spring

I want to send request on the remote controller (http://123.123.123.123/vehicles/all)...

example..

```<code>@Controller
@RequestMapping("/vehicles")
public class AutoController {

    AutoService autoserv;

    @Autowired
    public AutoController(AutoService autoserv) {
        this.autoserv = autoserv;
    }

    @RequestMapping(value = "/all")
    public Result<Car> all() {
        List<Car> autlst = autoserv.getAuto();
        return new Result<Car>(autlst);
    }
}
</code>```

from my a local application and get response List..
How does that..? Thanks

答:
Looks like you're trying to implement RESTful Webservices?

http://en.wikipedia.org/wiki/Representational_State_Transfer

If this is the case have a look on the following pages to get you started:

http://www.stupidjavatricks.com/?p=54

http://www.informit.com/guides/content.aspx?g=java&seqNum=544

ContentLicense: CC BY-SA 2.5

Title: How to expose a remote controller

Body:
I need help at Spring

I want to send request on the remote controller (http://123.123.123.123/vehicles/all)...

example..

@Controller
@RequestMapping("/vehicles")
public class AutoController {

    AutoService autoserv;

    @Autowired
    public AutoController(AutoService autoserv) {
        this.autoserv = autoserv;
    }

    @RequestMapping(value = "/all")
    public Result<Car> all() {
        List<Car> autlst = autoserv.getAuto();
        return new Result<Car>(autlst);
    }
}

from my a local application and get response List..
How does that..? Thanks


问:
Working with streams in PDFrw for Python?
I'm trying to read in an example PDF with PDFrw. The PDF contains the phrase Hello Matthew in the bottom left corner at coordinates (100, 100). When I attempt to output the text (if I even can?) I get a stream of data. I can't seem to figure out how to get that as text.

```<code>>>> import pdfrw

>>> file_object = pdfrw.PdfReader("Hello.pdf")
>>> file_object
{'/ID': ['<f643bc0910dfb67725d53e11054f4609>', '<f643bc0910dfb67725d53e11054f4609>'], '/Info': (5, 0), '/Root': {'/Outl
ines': (8, 0), '/PageMode': '/UseNone', '/Pages': {'/Count': '1', '/Kids': [{'/Contents': (7, 0), '/MediaBox': ['0', '0
', '595.2756', '841.8898'], '/Parent': {...}, '/Resources': {'/Font': (1, 0), '/ProcSet': ['/PDF', '/Text', '/ImageB',
'/ImageC', '/ImageI']}, '/Rotate': '0', '/Trans': {}, '/Type': '/Page'}], '/Type': '/Pages'}, '/Type': '/Catalog'}, '/S
ize': '9'}

>>> file_object.pages[0]
{'/Contents': (7, 0), '/MediaBox': ['0', '0', '595.2756', '841.8898'], '/Parent': {'/Count': '1', '/Kids': [{...}], '/T
ype': '/Pages'}, '/Resources': {'/Font': (1, 0), '/ProcSet': ['/PDF', '/Text', '/ImageB', '/ImageC', '/ImageI']}, '/Rot
ate': '0', '/Trans': {}, '/Type': '/Page'}

>>> file_object.pages[0].keys()
['/Contents', '/MediaBox', '/Parent', '/Resources', '/Rotate', '/Trans', '/Type']

>>> file_object.pages[0].Contents
{'/Filter': ['/ASCII85Decode', '/FlateDecode'], '/Length': '102'}

>>> file_object.pages[0].Contents.stream
'GapQh0E=F,0U\\H3T\\pNYT^QKk?tc>IP,;W#U1^23ihPEM_?CW4KISi90EC-p>QkRte=<%V"lI7]P)Rn29neZ[Kb,htEWn&q7Q2"V~>'
</code>```

答:
That stream is compressed.  You can tell that by the dictionary /Filter parameter.

Unfortunately, pdfrw does not (yet?) know how to decompress with that type of filter.  If you run your pdf through something like pdftk first to decompress it, you might see something more reasonable.

Disclaimer:  I am the primary pdfrw author.

But...

Even then, especially for non-ASCII fonts, character to glyph mapping in PDFs is complicated, so you won't always see something that looks reasonable.

If you really want to deeply examine text PDF files, pdfminer might be more useful -- pdfrw has not yet really grown the tools to do that too well.

Body:
I'm trying to read in an example PDF with PDFrw. The PDF contains the phrase Hello Matthew in the bottom left corner at coordinates (100, 100). When I attempt to output the text (if I even can?) I get a stream of data. I can't seem to figure out how to get that as text.

>>> import pdfrw

>>> file_object = pdfrw.PdfReader("Hello.pdf")
>>> file_object
{'/ID': ['<f643bc0910dfb67725d53e11054f4609>', '<f643bc0910dfb67725d53e11054f4609>'], '/Info': (5, 0), '/Root': {'/Outl
ines': (8, 0), '/PageMode': '/UseNone', '/Pages': {'/Count': '1', '/Kids': [{'/Contents': (7, 0), '/MediaBox': ['0', '0
', '595.2756', '841.8898'], '/Parent': {...}, '/Resources': {'/Font': (1, 0), '/ProcSet': ['/PDF', '/Text', '/ImageB',
'/ImageC', '/ImageI']}, '/Rotate': '0', '/Trans': {}, '/Type': '/Page'}], '/Type': '/Pages'}, '/Type': '/Catalog'}, '/S
ize': '9'}

>>> file_object.pages[0]
{'/Contents': (7, 0), '/MediaBox': ['0', '0', '595.2756', '841.8898'], '/Parent': {'/Count': '1', '/Kids': [{...}], '/T
ype': '/Pages'}, '/Resources': {'/Font': (1, 0), '/ProcSet': ['/PDF', '/Text', '/ImageB', '/ImageC', '/ImageI']}, '/Rot
ate': '0', '/Trans': {}, '/Type': '/Page'}

>>> file_object.pages[0].keys()
['/Contents', '/MediaBox', '/Parent', '/Resources', '/Rotate', '/Trans', '/Type']

>>> file_object.pages[0].Contents
{'/Filter': ['/ASCII85Decode', '/FlateDecode'], '/Length': '102'}

>>> file_object.pages[0].Contents.stream
'GapQh0E=F,0U\\H3T\\pNYT^QKk?tc>IP,;W#U1^23ihPEM_?CW4KISi90EC-p>QkRte=<%V"lI7]P)Rn29neZ[Kb,htEWn&q7Q2"V~>'


问:
How to write a DSL based on free monad?
I'm playing with free monads in Haskell and I got stuck with defining the functions that lift the functor constructors in the Free monad.

I have the AppF functor as a sum of several functors, each representing an effect. One of these functors is DbTrF, representing db transactions effects.

So my AppF is defined like this:

```<code>data AppF a =
  DbTr (DbTrF a)
  | ... functors for the other types of effects
  deriving (Functor)
</code>```

my DbTrF is defined like this:

```<code>data Op i r =
  Get i
  | Insert i r
  | Delete i
  | Update i (r -> r)

data DbTrF a =
  UserTb (Op UserId UserData) (Maybe UserData -> a)
  | SessionTb (Op SessionId SessionData) (Maybe SessionData -> a)
  | ... here is the code for other tables
  deriving(Functor)
</code>```

then I would like to have a transact function

```<code>transact :: Table i r t-> Op i r -> AppM (Maybe r)
</code>```

...which I would like to use like this:

```<code>transactExample = transact UserTb (Get someUserId)
</code>```

For that I want to introduce the type Table as the function which takes an operation and returns a DbTrF value:

```<code>newtype Table i r a = Table {tbId :: Op i r -> (Maybe r -> a) -> DbTrF a}
</code>```

My attempt would be something like this:

```<code>transact (Table tb) op = liftF (DbTr (tb op ???))
</code>```

but I'm not sure what to put instead of the question marks.

Is this a good direction to follow or am I doing it wrong?

Thanks!

答:
Let's try to instantiate the body of the function progressively, keeping track of the expected type in the remaining hole:

```<code>transact :: Table i r a -> Op i r -> AppM (Maybe r)
transact (Table tb) op
  = ??? :: AppM (Maybe r)
  = liftF (??? :: AppF (Maybe r))
  = liftF (DbTr (??? :: DbTrF (Maybe r)))
  = liftF (DbTr (tb op (??? :: Maybe r -> Maybe r))
</code>```

But we also have, from the type of Table tb, tb :: Op i r -> (Maybe r -> a) -> DbTrF a. Therefore a ~ Maybe r, and we can just solve the hole above using id, with a small change on the type of transact.

```<code>transact :: Table i r (Maybe r) -> Op i r -> AppM (Maybe r)
transact (Table tb) op = liftF (DbTr (tb op id))
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to write a DSL based on free monad?

Body:
I'm playing with free monads in Haskell and I got stuck with defining the functions that lift the functor constructors in the Free monad.

I have the AppF functor as a sum of several functors, each representing an effect. One of these functors is DbTrF, representing db transactions effects.

So my AppF is defined like this:

data AppF a =
  DbTr (DbTrF a)
  | ... functors for the other types of effects
  deriving (Functor)

my DbTrF is defined like this:

data Op i r =
  Get i
  | Insert i r
  | Delete i
  | Update i (r -> r)

data DbTrF a =
  UserTb (Op UserId UserData) (Maybe UserData -> a)
  | SessionTb (Op SessionId SessionData) (Maybe SessionData -> a)
  | ... here is the code for other tables
  deriving(Functor)

then I would like to have a transact function

transact :: Table i r t-> Op i r -> AppM (Maybe r)

...which I would like to use like this:

transactExample = transact UserTb (Get someUserId)

For that I want to introduce the type Table as the function which takes an operation and returns a DbTrF value:

newtype Table i r a = Table {tbId :: Op i r -> (Maybe r -> a) -> DbTrF a}

My attempt would be something like this:

transact (Table tb) op = liftF (DbTr (tb op ???))

but I'm not sure what to put instead of the question marks.

Is this a good direction to follow or am I doing it wrong?

Thanks!

Body:
Let's try to instantiate the body of the function progressively, keeping track of the expected type in the remaining hole:

transact :: Table i r a -> Op i r -> AppM (Maybe r)
transact (Table tb) op
  = ??? :: AppM (Maybe r)
  = liftF (??? :: AppF (Maybe r))
  = liftF (DbTr (??? :: DbTrF (Maybe r)))
  = liftF (DbTr (tb op (??? :: Maybe r -> Maybe r))

But we also have, from the type of Table tb, tb :: Op i r -> (Maybe r -> a) -> DbTrF a. Therefore a ~ Maybe r, and we can just solve the hole above using id, with a small change on the type of transact.

transact :: Table i r (Maybe r) -> Op i r -> AppM (Maybe r)
transact (Table tb) op = liftF (DbTr (tb op id))


问:
Enable event windowActivated (JFrame) from JPanel
I have this problem: I'm builting a game. I'm trying check if the missionA is complete, pass to MissionB.

I have a StageClass (extends JFrame), this:

```<code>public class Stage extends JFrame {
  Scene missionOne;
public Stage(){
  //Code
  missionOne=new Scene();
  add(missionOne);
  addWindowListener(new java.awt.event.WindowAdapter(){
        public void windowActivated(java.awt.event.WindowEvent evt){
            checkMissionState();
        }
    });
}

private void checkMissionState(){
        if(missionOne.complete()){
            //ChangeMission
        }
    }
}
</code>```

In the scene class:

```<code>public class Scene extends JPanel implements ActionListener,KeyListener {
   //Allcode
   public boolean complete(){
     boolean sw=false;
     //Verify a list of conditions
     return sw;
   }
</code>```

When mission is complete, I don't get execute checkMissionState(). The reason is that the focus in this moment is Scene. I tried windowLostFocus, windowDeactivated and doesn't execute too.

I can get a solution sending on the screen a JOptionPane message from complete()

```<code>public class Scene extends JPanel implements ActionListener,KeyListener {
  //Allcode

   public boolean complete(){
     boolean sw=false;
     //Verify a list of conditions
    if(sw) JOptionPane.showMessageDialog(null,"Mission is complete");
      return sw;
}
</code>```

Works. But this quit Jugagability at Game.

I'm searching a form of execute checkMissionState() in JFrame without                            sending JOptionPane message.

How could do it?

答:
In your Scene class, you can implement FocusListener interface and override the following methods.

```<code>@Override
public void focusGained(FocusEvent fe){
    System.out.println("Focus gained in JPanel");
}

@Override
public void focusLost(FocusEvent fe){
    System.out.println("Focus lost in JPanel");
}
</code>```

Add following statement in your Scene class constructor.

```<code>addFocusListener(this);
</code>```

Not knowing what action you performed when focus lost or gained, you can implement your appropriate game action against focusLost and focusGained events.

Body:
I have this problem: I'm builting a game. I'm trying check if the missionA is complete, pass to MissionB.

I have a StageClass (extends JFrame), this:

public class Stage extends JFrame {
  Scene missionOne;
public Stage(){
  //Code
  missionOne=new Scene();
  add(missionOne);
  addWindowListener(new java.awt.event.WindowAdapter(){
        public void windowActivated(java.awt.event.WindowEvent evt){
            checkMissionState();
        }
    });
}

private void checkMissionState(){
        if(missionOne.complete()){
            //ChangeMission
        }
    }
}

In the scene class:

public class Scene extends JPanel implements ActionListener,KeyListener {
   //Allcode
   public boolean complete(){
     boolean sw=false;
     //Verify a list of conditions
     return sw;
   }

When mission is complete, I don't get execute checkMissionState(). The reason is that the focus in this moment is Scene. I tried windowLostFocus, windowDeactivated and doesn't execute too.

I can get a solution sending on the screen a JOptionPane message from complete()

public class Scene extends JPanel implements ActionListener,KeyListener {
  //Allcode

   public boolean complete(){
     boolean sw=false;
     //Verify a list of conditions
    if(sw) JOptionPane.showMessageDialog(null,"Mission is complete");
      return sw;
}

Works. But this quit Jugagability at Game.

I'm searching a form of execute checkMissionState() in JFrame without                            sending JOptionPane message.

How could do it?

Body:
In your Scene class, you can implement FocusListener interface and override the following methods.

@Override
public void focusGained(FocusEvent fe){
    System.out.println("Focus gained in JPanel");
}

@Override
public void focusLost(FocusEvent fe){
    System.out.println("Focus lost in JPanel");
}

Add following statement in your Scene class constructor.

addFocusListener(this);

Not knowing what action you performed when focus lost or gained, you can implement your appropriate game action against focusLost and focusGained events.


问:
Tkinter icon configuration error with Python 2.7
I try to change the ugly Tkinter logo, at top left, follow the documentation, however I get error.
Probably is trivial trouble or related with Python version, mine is 2.7.

But the interesting thing is if you run first without change icon, and after run the script bellow it change without trouble, however if you run the script at first time give the follow error:

TclError: bitmap "C:\Program Files\Anaconda2\DLLs\sca.ico" not defined

My script:

```<code>from Tkinter import *
root = Tk()

root.iconbitmap(r'C:\Program Files\Anaconda2\DLLs\sca.ico')
root.mainloop()
</code>```

My new icon is in this path: C:\Program Files\Anaconda2\DLLs\sca.ico'

答: Change root.iconbitmap(C:\Program Files\Anaconda2\DLLs\sca.ico) to root.wm_iconbitmap(C:\Program Files\Anaconda2\DLLs\sca.ico) and it might work.

Body:
I try to change the ugly Tkinter logo, at top left, follow the documentation, however I get error.
Probably is trivial trouble or related with Python version, mine is 2.7.

But the interesting thing is if you run first without change icon, and after run the script bellow it change without trouble, however if you run the script at first time give the follow error:

TclError: bitmap "C:\Program Files\Anaconda2\DLLs\sca.ico" not defined

My script:

from Tkinter import *
root = Tk()

root.iconbitmap(r'C:\Program Files\Anaconda2\DLLs\sca.ico')
root.mainloop()

My new icon is in this path: C:\Program Files\Anaconda2\DLLs\sca.ico'


问:
backendless app crash after its first use
i tried to use backendless as my backend, and i read the documentation i used their sample codes, when i run my app it crashes with following error

backendlessTest[9984:8668361] *** Terminating app due to uncaught
  exception of class 'Fault' libc++abi.dylib: terminating with uncaught
  exception of type Fault
      (lldb)

my code is

```<code>#import "ViewController.h"
#import "Backendless.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    BackendlessUser *user = [BackendlessUser new];
    user.email = @"rawandahmad698@gmail.com";
    user.password = @"mypassisHidden";
    [backendless.userService registering:user];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
</code>```

答:
See the error handling page of the docs:
https://backendless.com/documentation/users/ios/users_error_handling.htm

Specifically add a try/catch block and make sure to handle a scenario when an error is thrown. The error will contain the details on what went wrong.

Body:
i tried to use backendless as my backend, and i read the documentation i used their sample codes, when i run my app it crashes with following error

backendlessTest[9984:8668361] *** Terminating app due to uncaught
  exception of class 'Fault' libc++abi.dylib: terminating with uncaught
  exception of type Fault
      (lldb)

my code is

#import "ViewController.h"
#import "Backendless.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    BackendlessUser *user = [BackendlessUser new];
    user.email = @"rawandahmad698@gmail.com";
    user.password = @"mypassisHidden";
    [backendless.userService registering:user];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


问:
Kong 0.10.x - JWT authentication get token access
On Kong document: https://getkong.org/plugins/jwt/#create-a-jwt-credential

After that step, how to i can get  access token?

it's like: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhMzZjMzA0OWIzNjI0OWEzYzlmODg5MWNiMTI3MjQzYyIsImV4cCI6MTQ0MjQzMDA1NCwibmJmIjoxNDQyNDI2NDU0LCJpYXQiOjE0NDI0MjY0NTR9.AhumfY35GFLuEEjrOXiaADo7Ae6gt_8VLwX7qffhQN4

My issue:

User request Kong server get a access_token

Kong server result a access_token

User use that access_token to verify authentication on hosts (ex: kong:8000/products), after verified successfully, Kong server will points upstream_url (ex: my.api.com/products)

Please help to clear that.

Thank you so much

答: Using the values returned by the API you'll be able to create the token yourself. In order to help you with that, you can use an existing implementation like this one in Node.js https://github.com/jwtk/njwt</p>


问:
Regex_match for particular character of given string c++
I am trying to find the match the characters of a string(s) to a specific set of characters ("aeiou").

Once matched, I intend to reverse the order of the vowels.

I get an error for matching function for regex_match(). Not sure if I can pass a character as an argument for a regex_match?

EDIT:
    ERROR: no matching function for call to 'regex_match(__gnu_cxx::__alloc_traits >::value_type&, std::__cxx11::regex&)'

This is what my code looks like:

```<code>string reverseVowels(string s) {

    vector<int> v;
    std::regex r("[aeiou]");

    for (int i=0;i<s.length();j++)       //find all vowels and push back to vector
    {
        if (std::regex_match(s[i],r)))
        {
            v.push_back(i);
        }
    }

    for (int j=0;j<v.size()/2;j++)      //swap first and last element
    {
        char temp=s[v[j]];
        s[v[i]]=s[v[v.size()-1]];
        s[v[v.size()-1-j]]=temp;
    }
    return s;
}
</code>```

答:
The first parameter mentioned in the regex_match() documentation is a string, you've got send a string, otherwise, warnings or errors could be generated and even if they don't show up, you can't expect it to work properly.

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

std::string reverseVowels(std::string s) {

    std::vector<int> v;
    std::regex r("[aeiou]");

    for (uint i = 0; i < s.length(); i++) {

        std::string single = s.substr(i, 1);

        if (std::regex_match(single, r)) {

            v.push_back(i);

        }

    }

    for (uint j = 0; j < (v.size()/2); j++) {

        char ch = s[v[j]];

        s[v[j]] = s[v[v.size()-j-1]];
        s[v[v.size()-j-1]] = ch;

    }

    return s;
}

int main() {

    std::cout << reverseVowels("Mateus");

    return 0;
}
</code>```

Body:
I am trying to find the match the characters of a string(s) to a specific set of characters ("aeiou").

Once matched, I intend to reverse the order of the vowels.

I get an error for matching function for regex_match(). Not sure if I can pass a character as an argument for a regex_match?

EDIT:
    ERROR: no matching function for call to 'regex_match(__gnu_cxx::__alloc_traits >::value_type&, std::__cxx11::regex&)'

This is what my code looks like:

string reverseVowels(string s) {

    vector<int> v;
    std::regex r("[aeiou]");

    for (int i=0;i<s.length();j++)       //find all vowels and push back to vector
    {
        if (std::regex_match(s[i],r)))
        {
            v.push_back(i);
        }
    }

    for (int j=0;j<v.size()/2;j++)      //swap first and last element
    {
        char temp=s[v[j]];
        s[v[i]]=s[v[v.size()-1]];
        s[v[v.size()-1-j]]=temp;
    }
    return s;
}

Body:
The first parameter mentioned in the regex_match() documentation is a string, you've got send a string, otherwise, warnings or errors could be generated and even if they don't show up, you can't expect it to work properly.

#include <iostream>
#include <string>
#include <vector>
#include <regex>

std::string reverseVowels(std::string s) {

    std::vector<int> v;
    std::regex r("[aeiou]");

    for (uint i = 0; i < s.length(); i++) {

        std::string single = s.substr(i, 1);

        if (std::regex_match(single, r)) {

            v.push_back(i);

        }

    }

    for (uint j = 0; j < (v.size()/2); j++) {

        char ch = s[v[j]];

        s[v[j]] = s[v[v.size()-j-1]];
        s[v[v.size()-j-1]] = ch;

    }

    return s;
}

int main() {

    std::cout << reverseVowels("Mateus");

    return 0;
}


问:
PHP - Add form element before submit - Buy Button
I need to dynamically add form elements to an HTML form as soon as the Submit button is clicked but before the POST data is sent to a server. The new elements must be "read" from a PHP file on my server.

HISTORY:
Currently my HTML form has "hidden" fields that are submitted to another server for processing. I have no control over the other server. My problem is that anyone can edit these hidden fields.

How can I dynamically add form elements to the POST data as soon as the form is submitted?

答:
You can post the data to your server and after it post again to the external server with the new elements attached.

Your job is done on server side.

See also:

php server-to-server post?


问:
Xbox Live API for Windows Phone
If my game targets both Windows, Xbox, and Windows Phone - is the API supported on Windows Phone? or should I do a check and if it's Phone not use the APIs?</p>

答:
You can use the Xbox Live API with any Windows 10 UWP project which includes Windows 10 Phone. There are no restrictions other than your internet access to connect to the service.

If your game is based on C++ just incorporate the NuGet package like described here: https://developer.microsoft.com/en-us/games/xbox/docs/xboxlive/get-started/creators/getting-started-uwp-vs-creators

If your game is based on C# it is a little bit more complicated as you have to include the existing API source files by yourself. You will find the source code here: https://github.com/Microsoft/xbox-live-api-csharp

Title: Xbox Live API for Windows Phone


问:
How to check sense hat screen on|off using node.js
I am working in raspberry pi using sense-hat . Now i am using sense hat simulator in node-red. Now I have to check what is the status of sense-hat screen. How can I do this?

I have tried by using:

msg.payload.screen=="on"

and

msg.screen=="on"

but didnt work. can any one please help me?

I have also tried:
msg.background=="off|on" and msg.device=="off|on"

答:
Not at all sure what you are actually trying to do, but this should help.

The SenseHat frame buffer is an 8x8 matrix of LEDs. That means there are 64 LED's and you write a 16-bit RGB565 value to each address in /dev/fb1 to make the LED come on a certain colour. 64 LEDs at 2 bytes each makes 128 bytes.

So, to turn off all the LEDs, you can send a bunch (128 bytes) of zeroes:

```<code>dd if=/dev/zero of=/dev/fb1 bs=128 count=1
</code>```

And to turn on the first few LEDs with random colours:

```<code>echo AnyJunk > /dev/fb1
</code>```

So, if you want to check all the LEDs are off, you need to compare the 128 bytes in the framebuffer to zero. You can do that by generating 128 bytes of zeroes and then running cmp like this:

```<code>cmp <(cat /dev/fb1) <(dd if=/dev/zero bs=128 count=1)
</code>```

So, for an example:

```<code>echo AnyJunk > /dev/fb1      # Turn some LEDs on

# Check all zero, but they are not so the comparison fails
cmp <(cat /dev/fb1) <(dd if=/dev/zero bs=128 count=1)
1+0 records in
1+0 records out
128 bytes (128 B) copied, 0.000237917 s, 538 kB/s
/dev/fd/63 /dev/fd/62 differ: byte 1, line 1

echo $?
1
</code>```

Turn all LEDs off and check again:

```<code>dd if=/dev/zero of=/dev/fb1 bs=128 count=1

cmp <(cat /dev/fb1) <(dd if=/dev/zero bs=128 count=1)
1+0 records in
1+0 records out
128 bytes (128 B) copied, 0.000289063 s, 443 kB/s

echo $?
0
</code>```

Keywords: Raspberry Pi, RPi, SenseHat, Sense Hat, framebuffer, /dev/fb, RGB565, LED, matrix, commandline, command-line

Body:
Not at all sure what you are actually trying to do, but this should help.

The SenseHat frame buffer is an 8x8 matrix of LEDs. That means there are 64 LED's and you write a 16-bit RGB565 value to each address in /dev/fb1 to make the LED come on a certain colour. 64 LEDs at 2 bytes each makes 128 bytes.

So, to turn off all the LEDs, you can send a bunch (128 bytes) of zeroes:

dd if=/dev/zero of=/dev/fb1 bs=128 count=1

And to turn on the first few LEDs with random colours:

echo AnyJunk > /dev/fb1

So, if you want to check all the LEDs are off, you need to compare the 128 bytes in the framebuffer to zero. You can do that by generating 128 bytes of zeroes and then running cmp like this:

cmp <(cat /dev/fb1) <(dd if=/dev/zero bs=128 count=1)

So, for an example:

echo AnyJunk > /dev/fb1      # Turn some LEDs on

# Check all zero, but they are not so the comparison fails
cmp <(cat /dev/fb1) <(dd if=/dev/zero bs=128 count=1)
1+0 records in
1+0 records out
128 bytes (128 B) copied, 0.000237917 s, 538 kB/s
/dev/fd/63 /dev/fd/62 differ: byte 1, line 1

echo $?
1

Turn all LEDs off and check again:

dd if=/dev/zero of=/dev/fb1 bs=128 count=1

cmp <(cat /dev/fb1) <(dd if=/dev/zero bs=128 count=1)
1+0 records in
1+0 records out
128 bytes (128 B) copied, 0.000289063 s, 443 kB/s

echo $?
0

Keywords: Raspberry Pi, RPi, SenseHat, Sense Hat, framebuffer, /dev/fb, RGB565, LED, matrix, commandline, command-line


问:
Windows XP socket error with recv()
I'm having a strange behaviour with the recv() function.

My C++ (MFC) application with WinSock implements a simple HTTP client (non-blocking socket) for accessing HTML pages on a web server. Some of these pages are taking a few seconds for loading. On Windows 7 this is not a problem, because recv() also returns partial data. But on Windows XP the recv() function always returns SOCKET_ERROR and the error code is WSAEWOULDBLOCK. Only when the connection is finished the data is returned in one access.

Does anyone know this problem? How can I force Windows XP to also receive partial data?

I setted the buffer size (SO_RCVBUF) to 1000 Bytes. On Windows 7 this is also reflected to the TCP Window Size - on XP not.

The real problem which I have with this issue is, that I don't know how to check if the connection is still alive or not. How can I check if a connection is still alive? Or how can I specify a timeout (max time between two received packets from the server)?

答:
You can't expect recv to give you any data on a non-blocking socket.  If there's no data available it returns WOULDBLOCK.  You just need to call recv again (normally after select notifies you some data is available).  Whether you get data on the first (or any) call is going to depend on how fast the server is sending it.

When the socket is closed you'll get a different error from recv, like WSAECONNRESET or WSAENOTCONN.  select will also notify you when the socket is closed.

Title: Windows XP socket error with recv()


问:
Using "dialogclose" event in jQuery mobile
I would like an image to change once clicked and change back once the dialog it links to is closed.
I actually found a solution to what I was trying to do on this site, right here However, upon modifying it to suit my needs it does not work, Can anybody pinpoint what I am missing?

HTML:

```<code><div data-role="footer" data-position="fixed" data-id="myFooter">
  <div class="navBar" id="bah" data-role="navbar">
    <a href="#menu" id="burgerMenu" data-rel="popup">
      <img id="burger" src="resources/burger.png" alt=""/>
    </a>
  </div>
</div>
</code>```

jQuery:

$(document).ready(function()
{
    $("#bah").on("dialogclose", function(event)
    {
        $("#burger").attr("src","resources/burger.png");
    });
});
```

答:
Use jQM pagecreate event instead of the regular jQuery ready
For popup clode, the correct event is popupafterclose
The popup id in your example is menu not bah.

```<code>$(document).on("pagecreate","#page1", function(){
    $("#menu").on("popupafterclose", function(event) {
        $("#burger").prop("src","http://lorempixel.com/24/24/technics/1/");
    });
});
</code>```

DEMO

Body:
I would like an image to change once clicked and change back once the dialog it links to is closed.
I actually found a solution to what I was trying to do on this site, right here However, upon modifying it to suit my needs it does not work, Can anybody pinpoint what I am missing?

HTML:

jQuery:

$(document).ready(function()
{
    $("#bah").on("dialogclose", function(event)
    {
        $("#burger").attr("src","resources/burger.png");
    });
});

Body:
Use jQM pagecreate event instead of the regular jQuery ready
For popup clode, the correct event is popupafterclose
The popup id in your example is menu not bah.

$(document).on("pagecreate","#page1", function(){
    $("#menu").on("popupafterclose", function(event) {
        $("#burger").prop("src","http://lorempixel.com/24/24/technics/1/");
    });
});

DEMO


问:
C# folders and sub folders
How to do this:

Check if folder upload exists (if nor then create it) ~/ uploads

Check if subfolder with username exists ~/uploads/folder with username

It as to check for each case individually because I could add a new user to the system and of course the folder uploads alredy exists, just need to create a sub folder with username

答:
try this:</p>

```<code>var path = string.Format(@"{0}Uploads\{1}",Request.PhysicalApplicationPath,
    HttpContext.Current.User.Identity.Name);
if (!Directory.Exists(path))
    Directory.CreateDirectory(path);
</code>```

Title: C# folders and sub folders

Body:
try this:

var path = string.Format(@"{0}Uploads\{1}",Request.PhysicalApplicationPath,
    HttpContext.Current.User.Identity.Name);
if (!Directory.Exists(path))
    Directory.CreateDirectory(path);


问:
Python comtypes with MS Access
I have the following Python 2.7 code that works perfectly on a Windows 7 machine:

```<code>from comtypes.client import CreateObject
app = CreateObject('Access.Application')
from comtypes.gen import Access
DBEngine = app.DBEngine
</code>```

On two others (Windows 7 and Windows 10) with MS Access 365 installed (latest version), I get the following error:

```<code>_ctypes.COMError: (-2147312566, 'Erreur lors du chargement de la biblioth\xe8que/DLL du type.', (None, None, None, 0, None))
</code>```

(Meaning "Error loading DLL library)

I assume it's a DLL issue. Reinstalling Office didn't solve it. Has anyone already met that issue? Otherwise, what would be the general method to find the problem/fix it?

答:
Why not using win32com.client for that? comtypes is not so stable and is useful for custom COM interfaces (where other approach is impossible). All MS Office products have nice and standard IDispatch COM interface that are reachable by win32com.client. Standard PyWin32 docs describe "Excel.Application" example, but it can be easily applied for MS Access as well.

Fortunately there are several examples on StackOverflow:

Python code for running ms-Access Module Subroutine

Python Create Access database using win32com

Title: Python comtypes with MS Access

Body:
I have the following Python 2.7 code that works perfectly on a Windows 7 machine:

from comtypes.client import CreateObject
app = CreateObject('Access.Application')
from comtypes.gen import Access
DBEngine = app.DBEngine

On two others (Windows 7 and Windows 10) with MS Access 365 installed (latest version), I get the following error:

_ctypes.COMError: (-2147312566, 'Erreur lors du chargement de la biblioth\xe8que/DLL du type.', (None, None, None, 0, None))

(Meaning "Error loading DLL library)

I assume it's a DLL issue. Reinstalling Office didn't solve it. Has anyone already met that issue? Otherwise, what would be the general method to find the problem/fix it?


问:
How to avoid duplicates populating array with async service
I have a component that fetches content from a service to process it. The thing is I can have multiple calls to this function, which results in duplicates on my array. I the following workaround:

    getOptions(): Observable<PickQuality[]> {
    console.log("MY LENGTH: ", this.options.length) // <=== Always returns 0 because the callback hasn't run yet
    if(this.options.length == 0) {
        this.championService.getChampions()
            .subscribe(champions => {
                champions.forEach(champion => this.options.push(new PickQuality(champion, 0)));
                this.reevaluate();
                this.optionsSubject.next(this.options);
            });

        return this.optionsSubject.asObservable();
    }
    else
        return Observable.of(this.options);
}
```

<p>and it didn't work, and then I tried the following trick inside the callback (where the <code>this.options.length</code> is correctly recognized):</p>

<pre class="lang-ts prettyprint-override"><code>                    if(this.options.length != 0) return; // <=== Looks bad!
</code>```

which actually worked but seemed extremely inefficient to me, since the call to my service is still executed. How can I fix this?

答:
I'd recommend to restructure your code a little:

```<code>if (this.options.length == 0) {
    let source = this.championService.getChampions()
        .share();

    source.subscribe(champions => {
        // ... whatever
        this.options = whateverResult;
    });

    return source;
} else {
    return Observable.of(this.options);
}
</code>```

Now you can avoid using Subjects and return the source Observable which represents the HTTP request and is shared via the share() operator. This means there's only one HTTP request and its result is sent to this internal subscribe() call as well as to the subscriber outside this method.

Body:
I have a component that fetches content from a service to process it. The thing is I can have multiple calls to this function, which results in duplicates on my array. I the following workaround:

    getOptions(): Observable<PickQuality[]> {
    console.log("MY LENGTH: ", this.options.length) // <=== Always returns 0 because the callback hasn't run yet
    if(this.options.length == 0) {
        this.championService.getChampions()
            .subscribe(champions => {
                champions.forEach(champion => this.options.push(new PickQuality(champion, 0)));
                this.reevaluate();
                this.optionsSubject.next(this.options);
            });

        return this.optionsSubject.asObservable();
    }
    else
        return Observable.of(this.options);
}

and it didn't work, and then I tried the following trick inside the callback (where the this.options.length is correctly recognized):

                    if(this.options.length != 0) return; // <=== Looks bad!

which actually worked but seemed extremely inefficient to me, since the call to my service is still executed. How can I fix this?

Body:
I'd recommend to restructure your code a little:

if (this.options.length == 0) {
    let source = this.championService.getChampions()
        .share();

    source.subscribe(champions => {
        // ... whatever
        this.options = whateverResult;
    });

    return source;
} else {
    return Observable.of(this.options);
}

Now you can avoid using Subjects and return the source Observable which represents the HTTP request and is shared via the share() operator. This means there's only one HTTP request and its result is sent to this internal subscribe() call as well as to the subscriber outside this method.


问:
How to append from JSON after filter on key value
I have a JSON where I use a jQuery $.each function to append the data to a table. I do an if statement to check if a value matches a string.

In my last table column, I need to get data from another text filter. So if the data value matches my filter, then append it as the last td

```<code>dataset = [
  "river": {
    "year": "2016",
    "name": "Silver Creek",
    "series": "Caught fish",
    "weight": "100 kg",

  },
  "river": {
    "year": "2016",
    "name": "Silver Creek",
    "series": "Released fish",
    "weight": "60 kg"
  }
];

$(dataset).each(function(i, data){

  if (data.year === "2016" && data.series === "Caught fish") {
    $('tbody').append('<tr class="river"><td>' + this.year + '</td><td>' + this.name + </td><td>' + this.weight + </td></tr>')
  } if (data.year === "2016" && data.series === "Released fish") {
    $('tr.river').append('<td>' + this.weight + '</td>')
  }

});
</code>```

The code above does not do but I want, but may be a hint of what I want to achieve.

What I need as a table row:

```<code>YEAR | NAME         | CAUGHT | RELEASED
2016 | Silver Creek | 100 kg | 60 kg
</code>```

Any suggestions? Could I build a new variable based on the dataset outside the $.each function?

答:
Use the :contains selector for released fish to see if the year and waterbody already exist in the table:

var dataset = [
  {"year": "2015","name": "Cedar Creek","series": "Caught fish","weight": "90 kg"},
  {"year": "2016","name": "Silver Creek","series": "Caught fish","weight": "60 kg"},
  {"year": "2015","name": "Cedar Creek","series": "Released fish","weight": "40 kg"},
  {"year": "2016","name": "Silver Creek","series": "Released fish","weight": "60 kg"}
];

dataset.forEach(function(data) {
  if(data.series === 'Caught fish') {
    $('tbody').append('
' + data.year + '' + data.name + '' + data.weight);
  } else {
    $('tr:contains(' + (data.year + data.name) + ')').append('' + data.weight);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>tr > * {border: 1px solid #ddd;}</code>```

YEARNAMECAUGHTRELEASED

```

Body:
I have a JSON where I use a jQuery $.each function to append the data to a table. I do an if statement to check if a value matches a string.

In my last table column, I need to get data from another text filter. So if the data value matches my filter, then append it as the last td

dataset = [
  "river": {
    "year": "2016",
    "name": "Silver Creek",
    "series": "Caught fish",
    "weight": "100 kg",

  },
  "river": {
    "year": "2016",
    "name": "Silver Creek",
    "series": "Released fish",
    "weight": "60 kg"
  }
];

$(dataset).each(function(i, data){

  if (data.year === "2016" && data.series === "Caught fish") {
    $('tbody').append('
' + this.year + '	' + this.name + 	' + this.weight +
')
  } if (data.year === "2016" && data.series === "Released fish") {
    $('tr.river').append('' + this.weight + '	')
  }

});

The code above does not do but I want, but may be a hint of what I want to achieve.

What I need as a table row:

YEAR | NAME         | CAUGHT | RELEASED
2016 | Silver Creek | 100 kg | 60 kg

Any suggestions? Could I build a new variable based on the dataset outside the $.each function?

Body:
Use the :contains selector for released fish to see if the year and waterbody already exist in the table:

var dataset = [
  {"year": "2015","name": "Cedar Creek","series": "Caught fish","weight": "90 kg"},
  {"year": "2016","name": "Silver Creek","series": "Caught fish","weight": "60 kg"},
  {"year": "2015","name": "Cedar Creek","series": "Released fish","weight": "40 kg"},
  {"year": "2016","name": "Silver Creek","series": "Released fish","weight": "60 kg"}
];

dataset.forEach(function(data) {
  if(data.series === 'Caught fish') {
    $('tbody').append('<tr class="river"><td>' + data.year + '<td>' + data.name + '<td>' + data.weight);
  } else {
    $('tr:contains(' + (data.year + data.name) + ')').append('<td>' + data.weight);
  }
});

tr > * {border: 1px solid #ddd;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr><th>YEAR<th>NAME<th>CAUGHT<th>RELEASED
</table>