问:
PHP array element always returns false
I'm trying to populate a set of checkboxes based on stored form data. Unfortunately, the isSelected element only seems to return false. Here's the code:

```<code>if($field['type'] == 'checkbox'){
    $inputs = $field['inputs'];
    $count = '0';
    foreach($inputs as $input){
        if(($user_meta[$input['id']] !== '') && (isset($user_meta[$input['id']]))){
           $select = true;
        }
        else{
            $select = false;
        }
        $field['choices'][$count] = array(
            'text' => $field['choices'][$count]['text'],
            'value' => $field['choices'][$count]['value'] ,
            'isSelected' => $select );
        var_dump($select);
        var_dump($field['isSelected']);
        $count = $count + '1';
    }
}
</code>```

The var_dump of $select correctly returns boolean true and false values where it should. But the isSelected element always returns an empty string. This is true even when I replace the $select variable with a hardcoded true value, or use 1 and 0 instead of true and false.

I'm sure I'm missing something very basic, but I've had no luck finding a solution so far. I'd be grateful for any help!

Edit

Thanks to @Barmar I have a little more information on the problem. It's failing when I try to assign a value to $field['choices'][$count]['isSelected']. The log shows "PHP Notice: Indirect modification of overloaded element of GF_Field_Checkbox has no effect". Unfortunately, I can't see why that would be a problem here, as from what I can tell that error normally comes from using __get/set methods which I'm not actually making use of in this case. I also tried solutions suggested in "Indirect modification of overloaded element of SplFixedArray has no effect" to no avail. Is there some kind of setting or configuration that might be preventing this assignment?

答:
I believe I spotted the error. As a note, you don't need to have the $count variable in the array creation since you are going from 0++. Also the count can be shorthanded to $count++;

It looks like this is incorrect var_dump($field['isSelected']); and you meant var_dump($field['choices'][$count]['isSelected']);

```<code>$field['choices'][] = array(
        'text' => $field['choices'][$count]['text'],
        'value' => $field['choices'][$count]['value'] ,
        'isSelected' => $select );
var_dump($select);
var_dump($field['choices'][$count]['isSelected']);
$count++;
</code>```

Title: PHP array element always returns false

Body:
I'm trying to populate a set of checkboxes based on stored form data. Unfortunately, the isSelected element only seems to return false. Here's the code:

if($field['type'] == 'checkbox'){
    $inputs = $field['inputs'];
    $count = '0';
    foreach($inputs as $input){
        if(($user_meta[$input['id']] !== '') && (isset($user_meta[$input['id']]))){
           $select = true;
        }
        else{
            $select = false;
        }
        $field['choices'][$count] = array(
            'text' => $field['choices'][$count]['text'],
            'value' => $field['choices'][$count]['value'] ,
            'isSelected' => $select );
        var_dump($select);
        var_dump($field['isSelected']);
        $count = $count + '1';
    }
}

The var_dump of $select correctly returns boolean true and false values where it should. But the isSelected element always returns an empty string. This is true even when I replace the $select variable with a hardcoded true value, or use 1 and 0 instead of true and false.

I'm sure I'm missing something very basic, but I've had no luck finding a solution so far. I'd be grateful for any help!

Edit

Thanks to @Barmar I have a little more information on the problem. It's failing when I try to assign a value to $field['choices'][$count]['isSelected']. The log shows "PHP Notice: Indirect modification of overloaded element of GF_Field_Checkbox has no effect". Unfortunately, I can't see why that would be a problem here, as from what I can tell that error normally comes from using __get/set methods which I'm not actually making use of in this case. I also tried solutions suggested in "Indirect modification of overloaded element of SplFixedArray has no effect" to no avail. Is there some kind of setting or configuration that might be preventing this assignment?

Body:
I believe I spotted the error. As a note, you don't need to have the $count variable in the array creation since you are going from 0++. Also the count can be shorthanded to $count++;

It looks like this is incorrect var_dump($field['isSelected']); and you meant var_dump($field['choices'][$count]['isSelected']);

$field['choices'][] = array(
        'text' => $field['choices'][$count]['text'],
        'value' => $field['choices'][$count]['value'] ,
        'isSelected' => $select );
var_dump($select);
var_dump($field['choices'][$count]['isSelected']);
$count++;


来源: stackexchange

问:
collect information from one sheet and place it to a different sheet in vba
I have two excel sheets in the same workbook. sheet1 and sheet2.
in sheet1 i generate dates for each month. for example column z1 will be 3/1/2017, AA1 will be 3/2/2017, AB1 will be 3/3/2017 etc. till the end date of a month.

Then in sheet2 i have some numbers in column N,O,P. every day these numbers could be different.

In column C of both sheet1 and sheet2 are SN stored.

Now I am trying to collect the values from column N,O,P from sheet2 (N+O+P), and store them in sheet1 in column that head = Date   by the same SN.
i am trying to use the following code but this does not work.

could anyone help me with this

```<code>Sub registrereren()
Dim FirstDate As Date
Dim LastDate As Date
Dim NextDate As Date
Dim r As Long

Dim j As Long
Dim lastrow1 As Long

FirstDate = DateSerial(Year(Date), Month(Date), 1)
LastDate = DateSerial(Year(Date), Month(Date) + 1, 0)
lastrow1 = Sheets("Registration").Range("C" & Rows.Count).End(xlUp).Row

For r = 27 To LastDate

If Cells(1, r) = Date Then
 Next r

   For j = 2 To lastrow1

   Sheets("Sheet1").Cells(j, r).Value = WorksheetFunction.VLookup(Sheets("Sheet1").Range("C" & j).Value * 1, Sheets("Sheet2").Range("C2 : P3000"), 11 + 12 + 13, 0)

    Next j
 End If

End Sub
</code>```

答:
The Next r is misplaced. It should be after the End If

The resulting code looks like this:

```<code>Sub registrereren()
    Dim FirstDate As Date
    Dim LastDate As Date
    Dim NextDate As Date
    Dim r As Long
    Dim j As Long
    Dim lastrow1 As Long

    FirstDate = DateSerial(Year(Date), Month(Date), 1)
    LastDate = DateSerial(Year(Date), Month(Date) + 1, 0)
    lastrow1 = Sheets("Registration").Range("C" & Rows.Count).End(xlUp).Row

    For r = 27 To LastDate
        If Cells(1, r) = Date Then
            For j = 2 To lastrow1
                Sheets("Sheet1").Cells(j, r).Value = WorksheetFunction.VLookup(Sheets("Sheet1").Range("C" & j).Value * 1, Sheets("Sheet2").Range("C2 : P3000"), 11 + 12 + 13, 0)
            Next j
        End If
    Next r
End Sub
</code>```

The VBA editor makes it easy to indent code. Whenever you start a sub, function, loop, select case, or if statement, get in the habit of indenting the next line by hitting the tab key. When you are done with the block, use the backspace key to get you back to the previous levels of indentation. Furthermore, there are options on the editor ribbon which allows you to indent or dedent whole blocks of code.

Once you get in the habit of doing this, it should jump out at you when a block isn't terminated the correct way. On the other hand, your sporadic and inconsistent indentation made it hard to perceive what was the problem with Next r.

The above code compiles, but I wasn't able to test it in any easy way since I'm not sure how your spreadsheet is laid out. If it still doesn't work, you have another problem with the code and could either edit your question or perhaps ask another question if you need to (once you isolate what the problem is).

ContentLicense: CC BY-SA 3.0

Body:
I have two excel sheets in the same workbook. sheet1 and sheet2.
in sheet1 i generate dates for each month. for example column z1 will be 3/1/2017, AA1 will be 3/2/2017, AB1 will be 3/3/2017 etc. till the end date of a month.

Then in sheet2 i have some numbers in column N,O,P. every day these numbers could be different.

In column C of both sheet1 and sheet2 are SN stored.

Now I am trying to collect the values from column N,O,P from sheet2 (N+O+P), and store them in sheet1 in column that head = Date   by the same SN.
i am trying to use the following code but this does not work.

could anyone help me with this

Sub registrereren()
Dim FirstDate As Date
Dim LastDate As Date
Dim NextDate As Date
Dim r As Long

Dim j As Long
Dim lastrow1 As Long

FirstDate = DateSerial(Year(Date), Month(Date), 1)
LastDate = DateSerial(Year(Date), Month(Date) + 1, 0)
lastrow1 = Sheets("Registration").Range("C" & Rows.Count).End(xlUp).Row

For r = 27 To LastDate

If Cells(1, r) = Date Then
 Next r

   For j = 2 To lastrow1

   Sheets("Sheet1").Cells(j, r).Value = WorksheetFunction.VLookup(Sheets("Sheet1").Range("C" & j).Value * 1, Sheets("Sheet2").Range("C2 : P3000"), 11 + 12 + 13, 0)

    Next j
 End If

End Sub

Body:
The Next r is misplaced. It should be after the End If

The resulting code looks like this:

Sub registrereren()
    Dim FirstDate As Date
    Dim LastDate As Date
    Dim NextDate As Date
    Dim r As Long
    Dim j As Long
    Dim lastrow1 As Long

    FirstDate = DateSerial(Year(Date), Month(Date), 1)
    LastDate = DateSerial(Year(Date), Month(Date) + 1, 0)
    lastrow1 = Sheets("Registration").Range("C" & Rows.Count).End(xlUp).Row

    For r = 27 To LastDate
        If Cells(1, r) = Date Then
            For j = 2 To lastrow1
                Sheets("Sheet1").Cells(j, r).Value = WorksheetFunction.VLookup(Sheets("Sheet1").Range("C" & j).Value * 1, Sheets("Sheet2").Range("C2 : P3000"), 11 + 12 + 13, 0)
            Next j
        End If
    Next r
End Sub

The VBA editor makes it easy to indent code. Whenever you start a sub, function, loop, select case, or if statement, get in the habit of indenting the next line by hitting the tab key. When you are done with the block, use the backspace key to get you back to the previous levels of indentation. Furthermore, there are options on the editor ribbon which allows you to indent or dedent whole blocks of code.

Once you get in the habit of doing this, it should jump out at you when a block isn't terminated the correct way. On the other hand, your sporadic and inconsistent indentation made it hard to perceive what was the problem with Next r.

The above code compiles, but I wasn't able to test it in any easy way since I'm not sure how your spreadsheet is laid out. If it still doesn't work, you have another problem with the code and could either edit your question or perhaps ask another question if you need to (once you isolate what the problem is).


问:
UITableView - footer of last section scrolls off the bottom of the screen. How to prevent?
I have a grouped UITableView.  I've implemented tableView(:titleForHeaderInSection:) and tableView(:titleForFooterInSection:).  As I scroll a long table, I can see that the section headers and footers contain the expected data.  When I get to the bottom of the table and I drag up to see the footer of the last section, it has the correct data, but when I release my finger, the footer scrolls back down past the bottom of the screen and out of view.  The last cell of the last section is what appears at the bottom of the screen rather than the footer of the last section.

How to fix it?
There's the last section and its footer.  My finger is still on the screen

When I release my finger, the final footer slides off the bottom of the screen.

答:
I think it's blocked by the tabbar.

If using storyborad, reset the constraint of your tableView.

If not, you need to set the frame of your tableView correctly.


问:
create a variable to replace variables in a model in R
When writing statistic model, I usually use a lot of co-variables to adjust the model, so I need to rewrite the variable again and again. Even though I could copy and paste, the model looks very long. Could I create a variable which could replace many variables? E.g.:

```<code>fm <- lm(y ~ a+b+c+d+e, data)
</code>```

I could create a variable like: model1 = a+b+c+d+e, then the model looks like:

```<code>fm <-lm(y ~ model1, data)
</code>```

I tried many ways, but it did successful, like model1 <- c(a+b+c+d),

Could someone help me with this?

答:
how about saving it as a formula?

```<code>model <- ~a+b+c+d
</code>```

You can then extract the terms using terms, or update the formula using update

Example:

```<code>model <- mpg ~ disp + wt + cyl

lm(model, mtcars)
## Call:
## lm(formula = model, data = mtcars)
##
## Coefficients:
## (Intercept)         disp           wt          cyl
##   41.107678     0.007473    -3.635677    -1.784944

model <- update(model, ~. + qsec)
lm(model, mtcars)
## Call:
## lm(formula = model, data = mtcars)
##
## Coefficients:
## (Intercept)         disp           wt          cyl         qsec
##    30.17771      0.01029     -4.55318     -1.24109      0.55277
</code>```

Edit:
As Kristoffer Winther Balling mentioned in the comments, a cleverer way to do this is to save the formula as a string (e.g. "mpg ~ disp + wt + cyl") and then use as.formula. You can then use familiar paste or other string manipulation functions to change the formula.

Body:
When writing statistic model, I usually use a lot of co-variables to adjust the model, so I need to rewrite the variable again and again. Even though I could copy and paste, the model looks very long. Could I create a variable which could replace many variables? E.g.:

fm <- lm(y ~ a+b+c+d+e, data)

I could create a variable like: model1 = a+b+c+d+e, then the model looks like:

fm <-lm(y ~ model1, data)

I tried many ways, but it did successful, like model1 <- c(a+b+c+d),

Could someone help me with this?

Body:
how about saving it as a formula?

model <- ~a+b+c+d

You can then extract the terms using terms, or update the formula using update

Example:

model <- mpg ~ disp + wt + cyl

lm(model, mtcars)
## Call:
## lm(formula = model, data = mtcars)
##
## Coefficients:
## (Intercept)         disp           wt          cyl
##   41.107678     0.007473    -3.635677    -1.784944

model <- update(model, ~. + qsec)
lm(model, mtcars)
## Call:
## lm(formula = model, data = mtcars)
##
## Coefficients:
## (Intercept)         disp           wt          cyl         qsec
##    30.17771      0.01029     -4.55318     -1.24109      0.55277

Edit:
As Kristoffer Winther Balling mentioned in the comments, a cleverer way to do this is to save the formula as a string (e.g. "mpg ~ disp + wt + cyl") and then use as.formula. You can then use familiar paste or other string manipulation functions to change the formula.


问:
auto scaling spins up multiple compute nodes in cfncluster
when I try to run a single job 'hellojob.sh' in the cfncluster multiple compute nodes spun up. It is a very simple job.please find my script below.

hellojob.sh

```<code>#!/bin/bash
sleep 30
echo "Hello World from $(hostname)"
</code>```

can anyone please tell me how to avoid autoscaling spin up to multiple compute nodes.

please find my config file below:

```<code>[root@ip-00-00-0-1000 .cfncluster]# cat config
[aws]
aws_region_name = us-east-1
aws_access_key_id = ***************
aws_secret_access_key = *******************

[cluster default]
vpc_settings = testdev-dev
key_name = testdev-developers
initial_queue_size = 0
s3_read_write_resource =*
pre_install = s3://cfncluster/pre_install_script.sh

[vpc testdev-dev]
master_subnet_id = subnet-*****
vpc_id = vpc-*****
additional_sg=sg-*****
vpc_security_group_id =sg-*****
use_public_ips=false

[global]
update_check = true
sanity_check = true
cluster_template = default

[scaling]
scaling_cooldown = 2000
</code>```

答:
You should be able to solve this by including the scaling_threshold (and optionally scaling_threshold2) parameters in your scaling configuration. The scaling_threshold parameter determines the number of instances to add when an autoscaling ScaleUp event is triggered. See a snippet of my config below as an example</p>

```<code>## Scaling settings
#[scaling custom]
# Threshold for triggering CloudWatch ScaleUp action
# (defaults to 4 for default template)
scaling_threshold = 1
# Number of instances to add when called CloudWatch ScaleUp action
# (defaults to 2 for default template)
scaling_adjustment = 1
# Threshold for triggering CloudWatch ScaleUp2 action
# (defaults to 4 for default template)
scaling_threshold2 = 10
# Number of instances to add when called CloudWatch ScaleUp2 action
# (defaults to 20 for default template)
scaling_adjustment2 = 2
</code>```

Body:
when I try to run a single job 'hellojob.sh' in the cfncluster multiple compute nodes spun up. It is a very simple job.please find my script below.

hellojob.sh

#!/bin/bash
sleep 30
echo "Hello World from $(hostname)"

can anyone please tell me how to avoid autoscaling spin up to multiple compute nodes.

please find my config file below:

[root@ip-00-00-0-1000 .cfncluster]# cat config
[aws]
aws_region_name = us-east-1
aws_access_key_id = ***************
aws_secret_access_key = *******************

[cluster default]
vpc_settings = testdev-dev
key_name = testdev-developers
initial_queue_size = 0
s3_read_write_resource =*
pre_install = s3://cfncluster/pre_install_script.sh

[vpc testdev-dev]
master_subnet_id = subnet-*****
vpc_id = vpc-*****
additional_sg=sg-*****
vpc_security_group_id =sg-*****
use_public_ips=false

[global]
update_check = true
sanity_check = true
cluster_template = default

[scaling]
scaling_cooldown = 2000

Body:
You should be able to solve this by including the scaling_threshold (and optionally scaling_threshold2) parameters in your scaling configuration. The scaling_threshold parameter determines the number of instances to add when an autoscaling ScaleUp event is triggered. See a snippet of my config below as an example

## Scaling settings
#[scaling custom]
# Threshold for triggering CloudWatch ScaleUp action
# (defaults to 4 for default template)
scaling_threshold = 1
# Number of instances to add when called CloudWatch ScaleUp action
# (defaults to 2 for default template)
scaling_adjustment = 1
# Threshold for triggering CloudWatch ScaleUp2 action
# (defaults to 4 for default template)
scaling_threshold2 = 10
# Number of instances to add when called CloudWatch ScaleUp2 action
# (defaults to 20 for default template)
scaling_adjustment2 = 2


问:
stack overflow exception in std::list and std::vector
I am making a test program to check the time for storage of std::list, std::vector, and array. I want to store 2 million random integers in each container. However, std::list and std::vector makes stack overflow exception when about 1550 integers is stored. How can I avoid it except decreasing the number of integers?</p>

```<code>#include <list>
#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

void insert(list<short>& l, const short& value);
void _insert(list<short>& l, list<short>::iterator it, const short& value);
void insert(vector<short>& v, const short& value);
void _insert(vector<short>& v, vector<short>::iterator it, const short& value);
void insert(short arr[], int& logicalSize, const int& physicalSize, const short& value);
void _insert(short arr[], int& logicalSize, const int& physicalSize, const short& value, int& cur);

int main() {
    clock_t start, end;
    srand(time(nullptr));

    const int SIZE = 2000000;
    const short RANGE = 10000;
    list<short> l;
    vector<short> v;
    short* arr = new short[SIZE];
    int logicalSize = 0;

    // list
    cout << "List storage time test...";
    start = clock();
    for (int i = 0; i < SIZE; i++) {
        insert(l, (short)(rand() % (2 * RANGE + 1) - RANGE));
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    // vector
    cout << "Vector storage time test...";
    start = clock();
    for (int i = 0; i < SIZE; i++) {
        insert(v, (short)(rand() % (2 * RANGE + 1) - RANGE));
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    // array
    start = clock();
    cout << "Array storage time test...";
    for (int i = 0; i < SIZE; i++) {
        try {
            insert(arr, logicalSize, SIZE, (short)(rand() % (2 * RANGE + 1) - RANGE));
        }
        catch (string s) {
            cout << s << endl;
            system("pause");
            exit(-1);
        }
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    delete[] arr;
    system("pause");
    return 0;
}

void insert(list<short>& l, const short& value) {
    _insert(l, l.begin(), value);
}

void _insert(list<short>& l, list<short>::iterator it, const short& value) {
    if (it == l.end() || value < *it) {
        l.insert(it, value);
        return;
    }
    else {
        it++;
        return _insert(l, it, value);
    }
}

void insert(vector<short>& v, const short& value) {
    _insert(v, v.begin(), value);
}

void _insert(vector<short>& v, vector<short>::iterator it, const short& value) {
    if (it == v.end()) {
        v.push_back(value);
        return;
    } else if (value < *it) {
        v.insert(it, value);
        return;
    } else {
        it++;
        return _insert(v, it, value);
    }
}

void insert(short arr[], int& logicalSize, const int& physicalSize, const short& value) {
    int cur = 0;
    _insert(arr, logicalSize, physicalSize, value, cur);
}

void _insert(short arr[], int& logicalSize, const int& physicalSize, const short& value, int& cur) {
    if (cur >= physicalSize) throw string("No space for array.");

    if (cur == logicalSize) {
        arr[cur] = value;
        logicalSize++;
        return;
    } else if (value < arr[cur]) {
        for (int i = logicalSize - 1; i >= cur; i--) {
            arr[i + 1] = arr[i];
        }
        arr[cur] = value;
        logicalSize++;
        return;
    } else {
        return _insert(arr, logicalSize, physicalSize, value, ++cur);
    }
}
</code>```

答:
However, std::list and std::vector makes stack overflow exception when about 1550 integers is stored

Just write it iteratively

```<code>void insert(list<short>& l, const short& value) {
    list<short>::iterator it = l.begin();
    for (;it != l.end() && value < *it;it++);
    l.insert(it, value);
}
</code>```

You can use the same idea for vector... You can even reuse the function:

```<code>void insert(list<short>& l, const short& value) {
    list<short>::iterator it = getIterator(l.begin(),l.end(),value);
    l.insert(it, value);
}

void insert(vector<short>& v, const short& value) {
    vector<short>::iterator it = getIterator(l.begin(),l.end(),value);
    v.insert(it, value);
}

template<class InputIterator>
void getIterator(InputIterator it,InputIterator end){
    while (it != end && value < *it) {
        it++;
    }
    return it;
}
</code>```

Body:
I am making a test program to check the time for storage of std::list, std::vector, and array. I want to store 2 million random integers in each container. However, std::list and std::vector makes stack overflow exception when about 1550 integers is stored. How can I avoid it except decreasing the number of integers?

#include <list>
#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

void insert(list<short>& l, const short& value);
void _insert(list<short>& l, list<short>::iterator it, const short& value);
void insert(vector<short>& v, const short& value);
void _insert(vector<short>& v, vector<short>::iterator it, const short& value);
void insert(short arr[], int& logicalSize, const int& physicalSize, const short& value);
void _insert(short arr[], int& logicalSize, const int& physicalSize, const short& value, int& cur);

int main() {
    clock_t start, end;
    srand(time(nullptr));

    const int SIZE = 2000000;
    const short RANGE = 10000;
    list<short> l;
    vector<short> v;
    short* arr = new short[SIZE];
    int logicalSize = 0;

    // list
    cout << "List storage time test...";
    start = clock();
    for (int i = 0; i < SIZE; i++) {
        insert(l, (short)(rand() % (2 * RANGE + 1) - RANGE));
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    // vector
    cout << "Vector storage time test...";
    start = clock();
    for (int i = 0; i < SIZE; i++) {
        insert(v, (short)(rand() % (2 * RANGE + 1) - RANGE));
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    // array
    start = clock();
    cout << "Array storage time test...";
    for (int i = 0; i < SIZE; i++) {
        try {
            insert(arr, logicalSize, SIZE, (short)(rand() % (2 * RANGE + 1) - RANGE));
        }
        catch (string s) {
            cout << s << endl;
            system("pause");
            exit(-1);
        }
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    delete[] arr;
    system("pause");
    return 0;
}

void insert(list<short>& l, const short& value) {
    _insert(l, l.begin(), value);
}

void _insert(list<short>& l, list<short>::iterator it, const short& value) {
    if (it == l.end() || value < *it) {
        l.insert(it, value);
        return;
    }
    else {
        it++;
        return _insert(l, it, value);
    }
}

void insert(vector<short>& v, const short& value) {
    _insert(v, v.begin(), value);
}

void _insert(vector<short>& v, vector<short>::iterator it, const short& value) {
    if (it == v.end()) {
        v.push_back(value);
        return;
    } else if (value < *it) {
        v.insert(it, value);
        return;
    } else {
        it++;
        return _insert(v, it, value);
    }
}

void insert(short arr[], int& logicalSize, const int& physicalSize, const short& value) {
    int cur = 0;
    _insert(arr, logicalSize, physicalSize, value, cur);
}

void _insert(short arr[], int& logicalSize, const int& physicalSize, const short& value, int& cur) {
    if (cur >= physicalSize) throw string("No space for array.");

    if (cur == logicalSize) {
        arr[cur] = value;
        logicalSize++;
        return;
    } else if (value < arr[cur]) {
        for (int i = logicalSize - 1; i >= cur; i--) {
            arr[i + 1] = arr[i];
        }
        arr[cur] = value;
        logicalSize++;
        return;
    } else {
        return _insert(arr, logicalSize, physicalSize, value, ++cur);
    }
}

Body:
However, std::list and std::vector makes stack overflow exception when about 1550 integers is stored

Just write it iteratively

void insert(list<short>& l, const short& value) {
    list<short>::iterator it = l.begin();
    for (;it != l.end() && value < *it;it++);
    l.insert(it, value);
}

You can use the same idea for vector... You can even reuse the function:

void insert(list<short>& l, const short& value) {
    list<short>::iterator it = getIterator(l.begin(),l.end(),value);
    l.insert(it, value);
}

void insert(vector<short>& v, const short& value) {
    vector<short>::iterator it = getIterator(l.begin(),l.end(),value);
    v.insert(it, value);
}

template<class InputIterator>
void getIterator(InputIterator it,InputIterator end){
    while (it != end && value < *it) {
        it++;
    }
    return it;
}


问:
PHPinfo returns blank page
I am totally new to programming.. Was installing the wampserver.. I'm using windows, and I have a file called test.php inside the folder C:\wamp\www . Inside the test.php file, I have this code

```<code><?php phpinfo(); ?>
</code>```

Then I opened the firefox browser and then entered the statement below but it returns a blank page. Is the url below right?
http://localhost/www/test.php

Am I doing the right thing? Tried using the search function but couldn't get it to work. Thanks!

答:
Your URL should be http://localhost/test.php

The "www" folder is your DocumentRoot folder by default. The URL http://localhost/ will point to that folder. Everything after that works like a normal document path.

ContentLicense: CC BY-SA 2.5

Title: PHPinfo returns blank page

Body:
I am totally new to programming.. Was installing the wampserver.. I'm using windows, and I have a file called test.php inside the folder C:\wamp\www . Inside the test.php file, I have this code

<?php phpinfo(); ?>

Then I opened the firefox browser and then entered the statement below but it returns a blank page. Is the url below right?
http://localhost/www/test.php

Am I doing the right thing? Tried using the search function but couldn't get it to work. Thanks!


问:
Intel C++ cannot convert `T **` to `T const * const *`, GCC can

The Problem

Extension of Existing Code

I have a numerical library that has been designed with one “flavor” in mind.
Now I want to generalize this. The basic data structure is a “spinor” which
itself is a multi dimensional matrix. There are lots of functions which take
arrays of these spinors. The generalized functions need to take one such spinor
array for each flavor.

Say there is a function which, minimally, does the following:

```<code>void copy_spinor(Spinor *out, const Spinor *in) {
    std::cout << out << " " << in << "\n";
}
</code>```

My generalization now is this:

```<code>void copy_spinor(Spinor *out[num_flav], const Spinor *const in[num_flav]) {
    std::cout << "Fwd: ";
    copy_spinor(out[0], in[0]);
}
</code>```

In the real code, there is a loop over all num_flav, but that is not really
needed for this demonstration here.

As far as I understand, one has to read this as const Spinor *(in[num_flav]),
so in is a pointer to an array of probably num_flav elements (or another
quantity because foo[] is just *foo in a function parameter) of type
pointer-to-const-spinor.

The problem is that it does not compile when using a Spinor *non_const[2]
(without the const), see my earlier
question. From the answer there I
have learned that this must not compile because within the function
copy_spinor, the pointer non_const[0] could be made to point to some
const array of Spinor *. Then non_const would point to const data.
Therefore that does not work.

My conclusion was that adding another const will make it correct:

```<code>void copy_spinor(Spinor *out[num_flav], const Spinor *const in[num_flav]) {}
</code>```

When I now pass my non_const as the second parameter, the function cannot
change in[0] to anything, because that pointer is now immutable. This has
served me well with GCC 6.3. Now going into production with Intel C++ 17, it
does not work any more.

The minimal working example is the following:

```<code>#include <cstdint>

typedef float Spinor[3][4][2][8];

template <uint8_t num_flav>
class Solver {
  public:
    void copy_spinor(Spinor *out, const Spinor *in) {
        std::cout << out << " " << in << "\n";
    }

    void copy_spinor(Spinor *out[num_flav], const Spinor *const in[num_flav]) {
        std::cout << "Fwd: ";
        copy_spinor(out[0], in[0]);
    }
};

int main(int argc, char **argv) {
    Spinor *s1 = new Spinor[10];
    Spinor *s2 = new Spinor[10];

    Spinor *s1_a[1] = {s1};
    Spinor *s2_a[1] = {s2};

    Solver<1> s;

    s.copy_spinor(s2_a, s1_a);
}
</code>```

On GCC, it apparently resolves to the second copy_spinor overload. The
variable s1_a which takes the role of the previous non_const, is allowed as
an argument.

Problems with Intel C++ 17

Intel C++ 17 however, does not accept that:

```<code>$ icpc -Wall -pedantic const-spinor-const.cpp  --std=c++11
const-spinor-const.cpp(23): error: no instance of overloaded function "Solver<num_flav>::copy_spinor [with num_flav=(uint8_t={unsigned char})'\001']" matches the argument list
            argument types are: (Spinor *[1], Spinor *[1])
            object type is: Solver<(uint8_t)'\001'>
      s.copy_spinor(s2_a, s1_a);
        ^
const-spinor-const.cpp(11): note: this candidate was rejected because arguments do not match
      void copy_spinor(Spinor *out[num_flav], const Spinor *const in[num_flav]) {}
           ^
const-spinor-const.cpp(10): note: this candidate was rejected because arguments do not match
      void copy_spinor(Spinor *out, const Spinor *in) {}
           ^
</code>```

The error message is not particularly helpful because it does not say what
conversion was not allowed. It just seems that the const is the problem.

Is there perhaps something I miss with Intel C++? Is it lacking a feature or
did I make use of an unofficial GCC extension? Is that a bug in Intel C++ or
GCC?

Update: The example also compiles with current Clang.

Non-Template Class

The same issue also persists when the class Solver is not a template class.
Since T a[2] is the same as T a[2] and T *a in a function argument, I can
also just write the function like this, not needing the uint8_t num_flav:

```<code>void copy_spinor(Spinor *out[], const Spinor *const in[]) {
    std::cout << "Fwd: ";
    copy_spinor(out[0], in[0]);
}
</code>```

The error is the same.

Free Functions

The same issue also happens for non-member non-friend non-template functions:

```<code>void free_spinor(Spinor *out, const Spinor *in) {
    std::cout << out << " " << in << "\n";
}

void free_spinor(Spinor *out[], const Spinor *const in[]) {
    std::cout << "Fwd: ";
    free_spinor(out[0], in[0]);
}
</code>```

The error message is just the same:

```<code>$ icpc -Wall -pedantic const-spinor-const.cpp  --std=c++11
const-spinor-const.cpp(97): error: no instance of overloaded function "free_spinor" matches the argument list
            argument types are: (Spinor *[1], Spinor *[1])
      free_spinor(s2_a, s1_a);
      ^
const-spinor-const.cpp(30): note: this candidate was rejected because arguments do not match
  void free_spinor(Spinor *out[], const Spinor *const in[]) {
       ^
const-spinor-const.cpp(26): note: this candidate was rejected because arguments do not match
  void free_spinor(Spinor *out, const Spinor *in) {
       ^
</code>```

Solution Attempts

In order to run the code in production, I see the following options. None of
them are particularly attractive.

What would be a good way to go forward? I can alter my new functions all I
want, but I would like to avoid touching caller code as much as possible.

Const Wrappers

When I change the definition of s1_a in the main function to have the two
const, it compiles:

```<code>const Spinor *const s1_a[1] = {s1};
</code>```

Then the function copy_spinor gets called with the correct argument type.

Every user of the generalized code has to write those const
wrappers for every single function call. That will get really messy.

Remove Const Correctness.

I can remove the left-most const from the function argument parameters. That
compiles cleanly on both compilers. However, I do want to document that I am
not changing anything in that array, therefore its values should be const.

A partial solution would be to use some preprocessor constant that removes the
const for the Intel Compiler only.

```<code>#ifdef __INTEL_COMPILER
#define ICPC_CONST
#else
#define ICPC_CONST const
#endif
</code>```

Perhaps a user has defined some spinor as const. Then I am stuck and need to
have the const there in place:

```<code>void copy_spinor(Spinor *out[num_flav], const Spinor *const in[num_flav]) {
    std::cout << "Fwd: ";
    copy_spinor(out[0], in[0]);
}
</code>```0

It should be easier to add a const than to remove it, so this solution is
pretty lacking. Also the upstream author would likely reject my changes due to
the changes in his code.

Add a non-const Overload for each Function

Adding an overload for each function would be possible. I have two variants of
the generalized function, the second one gets enabled when I work with the
Intel compiler:

```<code>void copy_spinor(Spinor *out[num_flav], const Spinor *const in[num_flav]) {
    std::cout << "Fwd: ";
    copy_spinor(out[0], in[0]);
}
</code>```1

That works well, there is just some duplication of code. Since my added
functions just re-use the existing functions, it is not that much code
duplication. Still a violation of the DRY principle.

Another disadvantage is that the number of overloads is 2^N where N is the
number of parameters that are a const *. There are functions taking up to
three arguments like this, therefore I would need eight copies.

Let the Template Deduce the Constness

Abstracting const Spinor and Spinor away is possible with templates. I
could write the function as a template such that S can be either data type.
Using a static_assert will give a slightly more informative error message.

```<code>void copy_spinor(Spinor *out[num_flav], const Spinor *const in[num_flav]) {
    std::cout << "Fwd: ";
    copy_spinor(out[0], in[0]);
}
</code>```2

Ideally, I would like to specify that S can only be a Spinor or const
Spinor. Perhaps that is possible with C++14 and beyond, I have to stick with
C++11.

This solution looks pretty clean, I can add a template argument and an assert
for each argument in the function. This will scale pretty good and there is no
code duplication. The only downside could be longer compilation time (already
rather long, but not really important) and less useful error messages
(hopefully covered with the static_assert).

The error message when calling it with int ** is the following for GCC:

```<code>const-spinor-const.cpp: In instantiation of 'void Solver<num_flav>::t_copy_spinor(float (**)[3][4][2][8], S* const*) [with S = int; unsigned char num_flav = 1u; Spinor = float [3][4][2][8]]':
const-spinor-const.cpp:86:36:   required from here
const-spinor-const.cpp:40:9: error: static assertion failed: Template parameter must be `const Spinor` or `Spinor`.
         static_assert(std::is_same<Spinor, S>::value ||
         ^~~~~~~~~~~~~
const-spinor-const.cpp:45:20: error: no matching function for call to 'Solver<1u>::copy_spinor(float (*&)[3][4][2][8], int* const&)'
         copy_spinor(out[0], in[0]);
         ~~~~~~~~~~~^~~~~~~~~~~~~~~
const-spinor-const.cpp:29:10: note: candidate: void Solver<num_flav>::copy_spinor(float (*)[3][4][2][8], const float (*)[3][4][2][8]) [with unsigned char num_flav = 1u; Spinor = float [3][4][2][8]]
     void copy_spinor(Spinor *out, const Spinor *in) {
          ^~~~~~~~~~~
const-spinor-const.cpp:29:10: note:   no known conversion for argument 2 from 'int* const' to 'const float (*)[3][4][2][8]'
const-spinor-const.cpp:33:10: note: candidate: void Solver<num_flav>::copy_spinor(float (**)[3][4][2][8], const float (* const*)[3][4][2][8]) [with unsigned char num_flav = 1u; Spinor = float [3][4][2][8]]
     void copy_spinor(Spinor *out[num_flav], const Spinor *const in[num_flav]) {
          ^~~~~~~~~~~
const-spinor-const.cpp:33:10: note:   no known conversion for argument 1 from 'float (*)[3][4][2][8]' to 'float (**)[3][4][2][8]'
</code>```

In the comments it was pointed out to use enable_if. With that, my function
looks like the following:

```<code>template <typename S>
typename std::enable_if<std::is_same<const Spinor, const S>::value,
                        void>::type
t2_copy_spinor(Spinor *out[num_flav], S *const in[num_flav]) {
    std::cout << "Fwd: " << typeid(S).name() << " " << typeName<S>() << " ";
    copy_spinor(out[0], in[0]);
}
</code>```

This is shorter, and perhaps more succint. The error message does not contain
my hand-written message any more , though. At least the error does not occur
within the function copy_spinor but at the calling site, so the user knows
where it went wrong. That is perhaps better. And the enable_if somewhat
explains itself, at least to more experienced template users.

```<code>const-spinor-const.cpp: In function 'int main(int, char**)':
const-spinor-const.cpp:86:37: error: no matching function for call to 'Solver<1u>::t2_copy_spinor(float (* [1])[3][4][2][8], int* [2])'
     s.t2_copy_spinor(s2_a, int_array);
                                     ^
const-spinor-const.cpp:51:5: note: candidate: template<class S> typename std::enable_if<std::is_same<const float [3][4][2][8], const S>::value, void>::type Solver<num_flav>::t2_copy_spinor(float (**)[3][4][2][8], S* const*) [with S = S; unsigned char num_flav = 1u]
     t2_copy_spinor(Spinor *out[num_flav], S *const in[num_flav]) {
     ^~~~~~~~~~~~~~
const-spinor-const.cpp:51:5: note:   template argument deduction/substitution failed:
const-spinor-const.cpp: In substitution of 'template<class S> typename std::enable_if<std::is_same<const float [3][4][2][8], const S>::value, void>::type Solver<num_flav>::t2_copy_spinor(float (**)[3][4][2][8], S* const*) [with S = int]':
const-spinor-const.cpp:86:37:   required from here
const-spinor-const.cpp:51:5: error: no type named 'type' in 'struct std::enable_if<false, void>'
</code>```

The enable_if solution looks better than the static_assert variant.

答:
GCC and clang are right here, Intel C++ is wrong.

The relevant portion of the Standard is Qualification conversions [conv.qual] (the section number may be either 4.4 or 4.5).  The wording has changed between C++11 and C++1z (to become C++17)... but your code which adds const at multiple levels starting with the shallowest, is allowed in all versions (C++03, 11, 14, 1z).

One change of note is that the multi-level const rule now applies to arrays of pointers, where formerly it only applied to multiple pointers.  But we actually are dealing with a multiple pointer, because the array syntax, when found in a parameter declaration, has pointer semantics.

Still, it might be worthwhile to try

```<code>void copy_spinor(Spinor **out, const Spinor *const *in)
</code>```

in case the compiler got confused / failed to adjust array types to pointer types within a function parameter list before applying the rule.

Body:
The Problem

Extension of Existing Code

I have a numerical library that has been designed with one “flavor” in mind.
Now I want to generalize this. The basic data structure is a “spinor” which
itself is a multi dimensional matrix. There are lots of functions which take
arrays of these spinors. The generalized functions need to take one such spinor
array for each flavor.

Say there is a function which, minimally, does the following:

void copy_spinor(Spinor *out, const Spinor *in) {
    std::cout << out << " " << in << "\n";
}

My generalization now is this:

void copy_spinor(Spinor *out[num_flav], const Spinor *const in[num_flav]) {
    std::cout << "Fwd: ";
    copy_spinor(out[0], in[0]);
}

In the real code, there is a loop over all num_flav, but that is not really
needed for this demonstration here.

As far as I understand, one has to read this as const Spinor *(in[num_flav]),
so in is a pointer to an array of probably num_flav elements (or another
quantity because foo[] is just *foo in a function parameter) of type
pointer-to-const-spinor.

The problem is that it does not compile when using a Spinor *non_const[2]
(without the const), see my earlier
question. From the answer there I
have learned that this must not compile because within the function
copy_spinor, the pointer non_const[0] could be made to point to some
const array of Spinor *. Then non_const would point to const data.
Therefore that does not work.

My conclusion was that adding another const will make it correct:

void copy_spinor(Spinor *out[num_flav], const Spinor *const in[num_flav]) {}

When I now pass my non_const as the second parameter, the function cannot
change in[0] to anything, because that pointer is now immutable. This has
served me well with GCC 6.3. Now going into production with Intel C++ 17, it
does not work any more.

The minimal working example is the following:

#include <cstdint>

typedef float Spinor[3][4][2][8];

template <uint8_t num_flav>
class Solver {
  public:
    void copy_spinor(Spinor *out, const Spinor *in) {
        std::cout << out << " " << in << "\n";
    }

    void copy_spinor(Spinor *out[num_flav], const Spinor *const in[num_flav]) {
        std::cout << "Fwd: ";
        copy_spinor(out[0], in[0]);
    }
};

int main(int argc, char **argv) {
    Spinor *s1 = new Spinor[10];
    Spinor *s2 = new Spinor[10];

    Spinor *s1_a[1] = {s1};
    Spinor *s2_a[1] = {s2};

    Solver<1> s;

    s.copy_spinor(s2_a, s1_a);
}

On GCC, it apparently resolves to the second copy_spinor overload. The
variable s1_a which takes the role of the previous non_const, is allowed as
an argument.

Problems with Intel C++ 17

Intel C++ 17 however, does not accept that:

$ icpc -Wall -pedantic const-spinor-const.cpp  --std=c++11
const-spinor-const.cpp(23): error: no instance of overloaded function "Solver<num_flav>::copy_spinor [with num_flav=(uint8_t={unsigned char})'\001']" matches the argument list
            argument types are: (Spinor *[1], Spinor *[1])
            object type is: Solver<(uint8_t)'\001'>
      s.copy_spinor(s2_a, s1_a);
        ^
const-spinor-const.cpp(11): note: this candidate was rejected because arguments do not match
      void copy_spinor(Spinor *out[num_flav], const Spinor *const in[num_flav]) {}
           ^
const-spinor-const.cpp(10): note: this candidate was rejected because arguments do not match
      void copy_spinor(Spinor *out, const Spinor *in) {}
           ^

The error message is not particularly helpful because it does not say what
conversion was not allowed. It just seems that the const is the problem.

Is there perhaps something I miss with Intel C++? Is it lacking a feature or
did I make use of an unofficial GCC extension? Is that a bug in Intel C++ or
GCC?

Update: The example also compiles with current Clang.

Non-Template Class

The same issue also persists when the class Solver is not a template class.
Since T a[2] is the same as T a[2] and T *a in a function argument, I can
also just write the function like this, not needing the uint8_t num_flav:

void copy_spinor(Spinor *out[], const Spinor *const in[]) {
    std::cout << "Fwd: ";
    copy_spinor(out[0], in[0]);
}

The error is the same.

Free Functions

The same issue also happens for non-member non-friend non-template functions:

void free_spinor(Spinor *out, const Spinor *in) {
    std::cout << out << " " << in << "\n";
}

void free_spinor(Spinor *out[], const Spinor *const in[]) {
    std::cout << "Fwd: ";
    free_spinor(out[0], in[0]);
}

The error message is just the same:

$ icpc -Wall -pedantic const-spinor-const.cpp  --std=c++11
const-spinor-const.cpp(97): error: no instance of overloaded function "free_spinor" matches the argument list
            argument types are: (Spinor *[1], Spinor *[1])
      free_spinor(s2_a, s1_a);
      ^
const-spinor-const.cpp(30): note: this candidate was rejected because arguments do not match
  void free_spinor(Spinor *out[], const Spinor *const in[]) {
       ^
const-spinor-const.cpp(26): note: this candidate was rejected because arguments do not match
  void free_spinor(Spinor *out, const Spinor *in) {
       ^

Solution Attempts

In order to run the code in production, I see the following options. None of
them are particularly attractive.

What would be a good way to go forward? I can alter my new functions all I
want, but I would like to avoid touching caller code as much as possible.

Const Wrappers

When I change the definition of s1_a in the main function to have the two
const, it compiles:

const Spinor *const s1_a[1] = {s1};

Then the function copy_spinor gets called with the correct argument type.

Every user of the generalized code has to write those const
wrappers for every single function call. That will get really messy.

Remove Const Correctness.

I can remove the left-most const from the function argument parameters. That
compiles cleanly on both compilers. However, I do want to document that I am
not changing anything in that array, therefore its values should be const.

A partial solution would be to use some preprocessor constant that removes the
const for the Intel Compiler only.

#ifdef __INTEL_COMPILER
#define ICPC_CONST
#else
#define ICPC_CONST const
#endif

Perhaps a user has defined some spinor as const. Then I am stuck and need to
have the const there in place:

const Spinor *s3_a[1] = {s3};

s.copy_spinor(s2_a, s3_a);

It should be easier to add a const than to remove it, so this solution is
pretty lacking. Also the upstream author would likely reject my changes due to
the changes in his code.

Add a non-const Overload for each Function

Adding an overload for each function would be possible. I have two variants of
the generalized function, the second one gets enabled when I work with the
Intel compiler:

void copy_spinor(Spinor *out, const Spinor *in) {
    std::cout << out << " " << in << "\n";
}

void copy_spinor(Spinor *out[num_flav], const Spinor *const in[num_flav]) {
    std::cout << "Fwd: ";
    copy_spinor(out[0], in[0]);
}

#ifdef __INTEL_COMPILER
void copy_spinor(Spinor *out[num_flav], Spinor *const in[num_flav]) {
    std::cout << "Fwd2: ";
    copy_spinor(out[0], in[0]);
}
#endif

That works well, there is just some duplication of code. Since my added
functions just re-use the existing functions, it is not that much code
duplication. Still a violation of the DRY principle.

Another disadvantage is that the number of overloads is 2^N where N is the
number of parameters that are a const *. There are functions taking up to
three arguments like this, therefore I would need eight copies.

Let the Template Deduce the Constness

Abstracting const Spinor and Spinor away is possible with templates. I
could write the function as a template such that S can be either data type.
Using a static_assert will give a slightly more informative error message.

template <typename S>
void copy_spinor(Spinor *out[num_flav], S *const in[num_flav]) {
    static_assert(std::is_same<Spinor, S>::value ||
                      std::is_same<const Spinor, S>::value,
                  "Template parameter must be `const Spinor` or `Spinor`.");

    std::cout << "Fwd: ";
    copy_spinor(out[0], in[0]);
}

Ideally, I would like to specify that S can only be a Spinor or const
Spinor. Perhaps that is possible with C++14 and beyond, I have to stick with
C++11.

This solution looks pretty clean, I can add a template argument and an assert
for each argument in the function. This will scale pretty good and there is no
code duplication. The only downside could be longer compilation time (already
rather long, but not really important) and less useful error messages
(hopefully covered with the static_assert).

The error message when calling it with int ** is the following for GCC:

const-spinor-const.cpp: In instantiation of 'void Solver<num_flav>::t_copy_spinor(float (**)[3][4][2][8], S* const*) [with S = int; unsigned char num_flav = 1u; Spinor = float [3][4][2][8]]':
const-spinor-const.cpp:86:36:   required from here
const-spinor-const.cpp:40:9: error: static assertion failed: Template parameter must be `const Spinor` or `Spinor`.
         static_assert(std::is_same<Spinor, S>::value ||
         ^~~~~~~~~~~~~
const-spinor-const.cpp:45:20: error: no matching function for call to 'Solver<1u>::copy_spinor(float (*&)[3][4][2][8], int* const&)'
         copy_spinor(out[0], in[0]);
         ~~~~~~~~~~~^~~~~~~~~~~~~~~
const-spinor-const.cpp:29:10: note: candidate: void Solver<num_flav>::copy_spinor(float (*)[3][4][2][8], const float (*)[3][4][2][8]) [with unsigned char num_flav = 1u; Spinor = float [3][4][2][8]]
     void copy_spinor(Spinor *out, const Spinor *in) {
          ^~~~~~~~~~~
const-spinor-const.cpp:29:10: note:   no known conversion for argument 2 from 'int* const' to 'const float (*)[3][4][2][8]'
const-spinor-const.cpp:33:10: note: candidate: void Solver<num_flav>::copy_spinor(float (**)[3][4][2][8], const float (* const*)[3][4][2][8]) [with unsigned char num_flav = 1u; Spinor = float [3][4][2][8]]
     void copy_spinor(Spinor *out[num_flav], const Spinor *const in[num_flav]) {
          ^~~~~~~~~~~
const-spinor-const.cpp:33:10: note:   no known conversion for argument 1 from 'float (*)[3][4][2][8]' to 'float (**)[3][4][2][8]'

In the comments it was pointed out to use enable_if. With that, my function
looks like the following:

template <typename S>
typename std::enable_if<std::is_same<const Spinor, const S>::value,
                        void>::type
t2_copy_spinor(Spinor *out[num_flav], S *const in[num_flav]) {
    std::cout << "Fwd: " << typeid(S).name() << " " << typeName<S>() << " ";
    copy_spinor(out[0], in[0]);
}

This is shorter, and perhaps more succint. The error message does not contain
my hand-written message any more , though. At least the error does not occur
within the function copy_spinor but at the calling site, so the user knows
where it went wrong. That is perhaps better. And the enable_if somewhat
explains itself, at least to more experienced template users.

const-spinor-const.cpp: In function 'int main(int, char**)':
const-spinor-const.cpp:86:37: error: no matching function for call to 'Solver<1u>::t2_copy_spinor(float (* [1])[3][4][2][8], int* [2])'
     s.t2_copy_spinor(s2_a, int_array);
                                     ^
const-spinor-const.cpp:51:5: note: candidate: template<class S> typename std::enable_if<std::is_same<const float [3][4][2][8], const S>::value, void>::type Solver<num_flav>::t2_copy_spinor(float (**)[3][4][2][8], S* const*) [with S = S; unsigned char num_flav = 1u]
     t2_copy_spinor(Spinor *out[num_flav], S *const in[num_flav]) {
     ^~~~~~~~~~~~~~
const-spinor-const.cpp:51:5: note:   template argument deduction/substitution failed:
const-spinor-const.cpp: In substitution of 'template<class S> typename std::enable_if<std::is_same<const float [3][4][2][8], const S>::value, void>::type Solver<num_flav>::t2_copy_spinor(float (**)[3][4][2][8], S* const*) [with S = int]':
const-spinor-const.cpp:86:37:   required from here
const-spinor-const.cpp:51:5: error: no type named 'type' in 'struct std::enable_if<false, void>'

The enable_if solution looks better than the static_assert variant.

Body:
GCC and clang are right here, Intel C++ is wrong.

The relevant portion of the Standard is Qualification conversions [conv.qual] (the section number may be either 4.4 or 4.5).  The wording has changed between C++11 and C++1z (to become C++17)... but your code which adds const at multiple levels starting with the shallowest, is allowed in all versions (C++03, 11, 14, 1z).

One change of note is that the multi-level const rule now applies to arrays of pointers, where formerly it only applied to multiple pointers.  But we actually are dealing with a multiple pointer, because the array syntax, when found in a parameter declaration, has pointer semantics.

Still, it might be worthwhile to try

void copy_spinor(Spinor **out, const Spinor *const *in)

in case the compiler got confused / failed to adjust array types to pointer types within a function parameter list before applying the rule.


问:
in db2 , how to delete records from multiple tables
i've been trying many of the solutions found by googling, but none work with this seemingly simple task.

in db2, i want to delete PO and PO lines, based on PO vendor and PO date.

PO and PO lines are linked by PO number. (below don't work)

```<code>DELETE FROM po, po_lines
  WHERE po_lines.po_num = po.po_num
  AND po.vendor = 'AAA' AND po.order_date = CURRENT DATE
</code>```

TIA!

答: I'm don't think it is possible to delete from 2 tables in a single DELETE command. May be you can create a stored procedure with the 2 delete statements and call the stored procedure once.

Body:
i've been trying many of the solutions found by googling, but none work with this seemingly simple task.

in db2, i want to delete PO and PO lines, based on PO vendor and PO date.

PO and PO lines are linked by PO number. (below don't work)

DELETE FROM po, po_lines
  WHERE po_lines.po_num = po.po_num
  AND po.vendor = 'AAA' AND po.order_date = CURRENT DATE

TIA!


问:
How to get verbose results in Mocha tests programmatically?
Is it possible to run Mocha programmatically, yet run it in a "verbose" mode and use the results programmatically?

Right now I am using it in NodeJS via mocha modules (using chai internally in the suite for the assertions).
What I want is to get more data about the failed tests than the generic errors of style: "expected true and got false".

Is there for instance a way to check which assertion failed and why, in case of multiple assertions within a test, or receive more information about a specific test, and if yes, how?

答:
When you run Mocha programmatically, the mocha.run() method returns a Runner object. If you listen to fail events, you'll be able to learn of all test failures. Here's an example adapted from the page I linked to above:

```<code>var Mocha = require('mocha');
var fs = require('fs');
var path = require('path');

var mocha = new Mocha();
var testDir = '.'
fs.readdirSync(testDir).filter(function(file){
    // This gets all files that end with the string test.js (so
    // footest.js, bar_test.js, baz.test.js, etc.
    return file.substr(-7) === 'test.js';
}).forEach(function(file){
    mocha.addFile(path.join(testDir, file));
});

var runner = mocha.run(function(failures){
  process.on('exit', function () {
    process.exit(failures);
  });
});

// This is how we get results.
runner.on('fail', function(test, err){
    console.log(err);
});
</code>```

Is there for instance a way to check which assertion failed and why, in case of multiple assertions within a test, or receive more information about a specific test, and if yes, how?

Mocha does not provide any facility to relate the exception you get through err in the fail handler to a specific assertion. This is due to the fact that Mocha is designed to be used with whatever assertion library you want. It only detects that an assertion has failed when it catches the exception raised by the failing assertion. It does not know anything about the assertions that were successful or the assertions that were not executed because the test ended early on the failing assertion. You may be able to reverse engineer something from the stack trace but Mocha won't help you towards this goal.

Body:
When you run Mocha programmatically, the mocha.run() method returns a Runner object. If you listen to fail events, you'll be able to learn of all test failures. Here's an example adapted from the page I linked to above:

var Mocha = require('mocha');
var fs = require('fs');
var path = require('path');

var mocha = new Mocha();
var testDir = '.'
fs.readdirSync(testDir).filter(function(file){
    // This gets all files that end with the string test.js (so
    // footest.js, bar_test.js, baz.test.js, etc.
    return file.substr(-7) === 'test.js';
}).forEach(function(file){
    mocha.addFile(path.join(testDir, file));
});

var runner = mocha.run(function(failures){
  process.on('exit', function () {
    process.exit(failures);
  });
});

// This is how we get results.
runner.on('fail', function(test, err){
    console.log(err);
});

Is there for instance a way to check which assertion failed and why, in case of multiple assertions within a test, or receive more information about a specific test, and if yes, how?

Mocha does not provide any facility to relate the exception you get through err in the fail handler to a specific assertion. This is due to the fact that Mocha is designed to be used with whatever assertion library you want. It only detects that an assertion has failed when it catches the exception raised by the failing assertion. It does not know anything about the assertions that were successful or the assertions that were not executed because the test ended early on the failing assertion. You may be able to reverse engineer something from the stack trace but Mocha won't help you towards this goal.


问:
Counting Chars in EditText Changed Listener
In my project I have an EditText. I want to count the characters in the EditText, and show that number it in a TextView. I have written the following code and it works fine. However, my problem is when I click Backspace it counts up, but I need to decrement the number. How can I consider Backspace?

```<code>tv = (TextView)findViewById(R.id.charCounts);
textMessage = (EditText)findViewById(R.id.textMessage);
textMessage.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {
        i++;
        tv.setText(String.valueOf(i) + " / " + String.valueOf(charCounts));
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    public void onTextChanged(CharSequence s, int start, int before, int count){}
});
</code>```

答:
how about just getting the length of char in your EditText and display it?

something along the line of

```<code>tv.setText(s.length() + " / " + String.valueOf(charCounts));
</code>```

Body:
In my project I have an EditText. I want to count the characters in the EditText, and show that number it in a TextView. I have written the following code and it works fine. However, my problem is when I click Backspace it counts up, but I need to decrement the number. How can I consider Backspace?

tv = (TextView)findViewById(R.id.charCounts);
textMessage = (EditText)findViewById(R.id.textMessage);
textMessage.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {
        i++;
        tv.setText(String.valueOf(i) + " / " + String.valueOf(charCounts));
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    public void onTextChanged(CharSequence s, int start, int before, int count){}
});

Body:
how about just getting the length of char in your EditText and display it?

something along the line of

tv.setText(s.length() + " / " + String.valueOf(charCounts));


问:
postgres psql script path
I am making a directory of useful sql scripts to use psql. I would like to be able to use them without having to cd to the directory.

Is it possible to configure psql to search a particular path for invoked scripts? Or do I have to invoke them all with fully qualified names?

答:
You could simply place your scripts in your .psqlrc file:

```<code>\set uptime 'select now() - backend_start as uptime from pg_stat_activity where pid = pg_backend_pid();'
</code>```

and then run the query in psql by prepending it with a colon :uptime

OR

if your scripts are long and you wish to better organize them then you could create your scripts directory ~/psqlrc.d or whatever and then (for example) (assuming a *nix OS):

```<code>echo "select now() - backend_start as uptime from pg_stat_activity where pid = pg_backend_pid();" > ~/psqlrc.d/uptime.sql
</code>```

followed by editing your ~/.psqlrc file to add:

```<code>\set uptime '\\i ~/psqlrc.d/uptime.sql'
</code>```

and once again invoke the script by typing :uptime in psql.

Title: postgres psql script path

Body:
You could simply place your scripts in your .psqlrc file:

\set uptime 'select now() - backend_start as uptime from pg_stat_activity where pid = pg_backend_pid();'

and then run the query in psql by prepending it with a colon :uptime

OR

if your scripts are long and you wish to better organize them then you could create your scripts directory ~/psqlrc.d or whatever and then (for example) (assuming a *nix OS):

echo "select now() - backend_start as uptime from pg_stat_activity where pid = pg_backend_pid();" > ~/psqlrc.d/uptime.sql

followed by editing your ~/.psqlrc file to add:

\set uptime '\\i ~/psqlrc.d/uptime.sql'

and once again invoke the script by typing :uptime in psql.


问:
How do I use django-treebeard to build a sitemap?
I have setup a django-treebeard model that has child nodes and what not. How do I now display this in my template? This is what I have so far.

My Models:

```<code>class SiteMapEntry(MP_Node):
    name = models.CharField(max_length=100, null=False, blank=False)
    url = models.CharField(max_length=1000, null=False, blank=False)

    node_order_by = ['name']

    class Meta:
        verbose_name = "Sitemap Entry"
        verbose_name_plural = "Sitemap Entries"

    def __unicode__(self):
        return ('%s - %s' % (self.name, self.url))
</code>```

My Views:

```<code>from django.views.generic import ListView
    class SiteMap(ListView):
        model = SiteMapEntry
        template_name = 'sitemaps.html'
</code>```

My Template:

```<code>{% block content %}
    <h1>Sitemap</h1>

    <br /><br />

    {% for url in object_list %}
<p>{{ url.name }}</p>
<p>{{ url.url }}</p>
    {% endfor %}

{% endblock content %}
</code>```

What this is doing right now, obviously is just listing the nodes and its children without any indenting. How do I list it like a tree in my template?

答:
You can use the get_annotated_list node method to get a data structure you can iterate on in the template:

http://django-treebeard.readthedocs.io/en/stable/api.html#treebeard.models.Node.get_annotated_list

There's also an example there that shows you exactly how to do it:

```<code>{% for item, info in annotated_list %}
    {% if info.open %}
        <ul><li>
    {% else %}
        </li><li>
    {% endif %}

    {{ item }}

    {% for close in info.close %}
        </li></ul>
    {% endfor %}
{% endfor %}
</code>```

Have a look at the dump_bulk method which returns a nested data structure too:

http://django-treebeard.readthedocs.io/en/stable/api.html#treebeard.models.Node.dump_bulk

Hope it's helpful.

Body:
I have setup a django-treebeard model that has child nodes and what not. How do I now display this in my template? This is what I have so far.

My Models:

class SiteMapEntry(MP_Node):
    name = models.CharField(max_length=100, null=False, blank=False)
    url = models.CharField(max_length=1000, null=False, blank=False)

    node_order_by = ['name']

    class Meta:
        verbose_name = "Sitemap Entry"
        verbose_name_plural = "Sitemap Entries"

    def __unicode__(self):
        return ('%s - %s' % (self.name, self.url))

My Views:

from django.views.generic import ListView
    class SiteMap(ListView):
        model = SiteMapEntry
        template_name = 'sitemaps.html'

My Template:

{% block content %}

Sitemap

    {% for url in object_list %}

{{ url.name }}

{{ url.url }}

    {% endfor %}

{% endblock content %}

What this is doing right now, obviously is just listing the nodes and its children without any indenting. How do I list it like a tree in my template?

Body:
You can use the get_annotated_list node method to get a data structure you can iterate on in the template:

http://django-treebeard.readthedocs.io/en/stable/api.html#treebeard.models.Node.get_annotated_list

There's also an example there that shows you exactly how to do it:

{% for item, info in annotated_list %}
    {% if info.open %}
        <ul><li>
    {% else %}
        </li><li>
    {% endif %}

    {{ item }}

    {% for close in info.close %}
        </li></ul>
    {% endfor %}
{% endfor %}

Have a look at the dump_bulk method which returns a nested data structure too:

http://django-treebeard.readthedocs.io/en/stable/api.html#treebeard.models.Node.dump_bulk

Hope it's helpful.


问:
Windows service always "Starting"
I've got an app which I've tested as working as a console application.
I've now converted this to a Windows service, installed it, run it, and it still does it job.

However, it always has a status of Starting.  There doesn't seem to be any logical flag to set on the ServiceBase.

I've setup the service with a bool isRunning flag, and the program runs within a
while (isRunning) {} block.

答:
Are you blocking the return of OnStart?

Normally one would spawn a thread from there to do the work, and let the method return.

Title: Windows service always "Starting"


问:
Subtract percentage of scrollTop from div's width on scroll with jquery
I'm attempting to adjust a div's width on scroll with jQuery, the idea is to have a div's width be reduced by a fraction of the scrolltop value, every time you scroll.

For example say I have a div with a width of 100px, if I scrolled down 20px from the top of the page, and the function declared to subtract 1/2 of the current scrolltop value, the div's width would become 90px.

答:
```<code> var x = 0.5; //define whatever rate you want.

 $(document).scroll(function() { //whenever a scroll is happening -
    $('#divId').width($('#divId').width()-$(document).scrollTop()*x);

    //capture your div's width and set it to a new width that equals
    //to the subtraction between it's original width and the current
    //scrolltop (multiplied by half, as you defined). so in your case
    //if div's width is 100px and scrolltop is 20px, divId's new width
    //will be 100px - (20px * 0.5) = 90px
});
</code>```


问:
How to change primary text in gtk messagedialog in python?
I'm creating program in python with gtk as gui using glade. In that program, I have several message dialog. It's simple if I just make many message dialog for every case I have. But, is it possible to just make one message dialog and use it for different case with different text? It's simple actually. I just need to change primary text and show it. But, I don't find a way to change primary text here and here.

Below is a sample code:

```<code>from gi.repository import Gtk

def clicked1(widget):
    response = dialog1.run()
    if response == Gtk.ResponseType.OK:
        print 'ok'
    else:
        print 'cancel'
        dialog1.destroy()

def clicked2(widget):
    response = dialog2.run()
    if response == Gtk.ResponseType.OK:
        print 'ok'
    else:
        print 'cancel'
        dialog2.destroy()

def clicked3(widget):
    response = dialog3.run()
    if response == Gtk.ResponseType.OK:
        print 'ok'
    else:
        print 'cancel'
        dialog3.destroy()

builder = Gtk.Builder()
builder.add_from_file('gui.glade')
dialog1 = builder.get_object('dialog1')
dialog2 = builder.get_object('dialog2')
dialog3 = builder.get_object('dialog3')
builder.get_object('button1').connect('clicked', clicked1)
builder.get_object('button2').connect('clicked', clicked2)
builder.get_object('button3').connect('clicked', clicked3)
builder.get_object('window1').show_all()
Gtk.main()
</code>```

I want to change it to be something like this

```<code>from gi.repository import Gtk

def clicked1(widget):
    **dialog.set_text(1)**
    response = dialog.run()
    if response == Gtk.ResponseType.OK:
        print 'ok'
    else:
        print 'cancel'
        dialog.destroy()

def clicked2(widget):
    **dialog.set_text(2)**
    response = dialog.run()
    if response == Gtk.ResponseType.OK:
        print 'ok'
    else:
        print 'cancel'
        dialog.destroy()

def clicked3(widget):
    **dialog.set_text(3)**
    response = dialog.run()
    if response == Gtk.ResponseType.OK:
        print 'ok'
    else:
        print 'cancel'
        dialog.destroy()

builder = Gtk.Builder()
builder.add_from_file('gui.glade')
**dialog = builder.get_object('dialog')**
builder.get_object('button1').connect('clicked', clicked1)
builder.get_object('button2').connect('clicked', clicked2)
builder.get_object('button3').connect('clicked', clicked3)
builder.get_object('window1').show_all()
Gtk.main()
</code>```

答:
Maybe a little bit too late, but I was looking for the same thing and I could get a simple yet efficient way of changing primary and secondary texts without calling any GtkMessageDialog pre-built method.

I was just trying to understand how it was not possible to have something easier to change these texts without calling the pre-built methods "set_markup" and "format_secondary_text". Even if "format_secondary_text" works like a charm and de-facto change the second text perfectly, "set_markup" changes the primary text, but not as it should because it does not get as title in presence of the second text, I expected it to become bold, but it is waiting for some PANGO markup, otherwise it is only a simple non-bold text.

Then I opened Idle just to take a look at all methods, properties and so on that might be available for GtkMessageDialog and I found something, as I paste it below:

```<code>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
builder = Gtk.Builder()
#any Glade file with at least 1 GtkMessageDialog
builder.add_from_file("myFile.glade")
#The ID of GtkMessageDialog in Glade
myDialog = builder.get_object("GtkMessageDialog1")

#Below I change primary and secondary texts before running the Dialog.
myDialog.set_property("text","Hello World")
myDialog.set_property("secondary_text","Here I go again.")

myDialog.run()
myDialog.hide()
</code>```

Just pay attention as I wrote using Python 2.7, but the principle must be the same as with Python 3.x.

Body:
I'm creating program in python with gtk as gui using glade. In that program, I have several message dialog. It's simple if I just make many message dialog for every case I have. But, is it possible to just make one message dialog and use it for different case with different text? It's simple actually. I just need to change primary text and show it. But, I don't find a way to change primary text here and here.

Below is a sample code:

from gi.repository import Gtk

def clicked1(widget):
    response = dialog1.run()
    if response == Gtk.ResponseType.OK:
        print 'ok'
    else:
        print 'cancel'
        dialog1.destroy()

def clicked2(widget):
    response = dialog2.run()
    if response == Gtk.ResponseType.OK:
        print 'ok'
    else:
        print 'cancel'
        dialog2.destroy()

def clicked3(widget):
    response = dialog3.run()
    if response == Gtk.ResponseType.OK:
        print 'ok'
    else:
        print 'cancel'
        dialog3.destroy()

builder = Gtk.Builder()
builder.add_from_file('gui.glade')
dialog1 = builder.get_object('dialog1')
dialog2 = builder.get_object('dialog2')
dialog3 = builder.get_object('dialog3')
builder.get_object('button1').connect('clicked', clicked1)
builder.get_object('button2').connect('clicked', clicked2)
builder.get_object('button3').connect('clicked', clicked3)
builder.get_object('window1').show_all()
Gtk.main()

I want to change it to be something like this

from gi.repository import Gtk

def clicked1(widget):
    **dialog.set_text(1)**
    response = dialog.run()
    if response == Gtk.ResponseType.OK:
        print 'ok'
    else:
        print 'cancel'
        dialog.destroy()

def clicked2(widget):
    **dialog.set_text(2)**
    response = dialog.run()
    if response == Gtk.ResponseType.OK:
        print 'ok'
    else:
        print 'cancel'
        dialog.destroy()

def clicked3(widget):
    **dialog.set_text(3)**
    response = dialog.run()
    if response == Gtk.ResponseType.OK:
        print 'ok'
    else:
        print 'cancel'
        dialog.destroy()

builder = Gtk.Builder()
builder.add_from_file('gui.glade')
**dialog = builder.get_object('dialog')**
builder.get_object('button1').connect('clicked', clicked1)
builder.get_object('button2').connect('clicked', clicked2)
builder.get_object('button3').connect('clicked', clicked3)
builder.get_object('window1').show_all()
Gtk.main()

Body:
Maybe a little bit too late, but I was looking for the same thing and I could get a simple yet efficient way of changing primary and secondary texts without calling any GtkMessageDialog pre-built method.

I was just trying to understand how it was not possible to have something easier to change these texts without calling the pre-built methods "set_markup" and "format_secondary_text". Even if "format_secondary_text" works like a charm and de-facto change the second text perfectly, "set_markup" changes the primary text, but not as it should because it does not get as title in presence of the second text, I expected it to become bold, but it is waiting for some PANGO markup, otherwise it is only a simple non-bold text.

Then I opened Idle just to take a look at all methods, properties and so on that might be available for GtkMessageDialog and I found something, as I paste it below:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
builder = Gtk.Builder()
#any Glade file with at least 1 GtkMessageDialog
builder.add_from_file("myFile.glade")
#The ID of GtkMessageDialog in Glade
myDialog = builder.get_object("GtkMessageDialog1")

#Below I change primary and secondary texts before running the Dialog.
myDialog.set_property("text","Hello World")
myDialog.set_property("secondary_text","Here I go again.")

myDialog.run()
myDialog.hide()

Just pay attention as I wrote using Python 2.7, but the principle must be the same as with Python 3.x.


问:
Wordpress Enqueuing Script returns 500 error
I am registering and enqueuing the script in my file functions.php
I got a white page and a console error 500

```<code>add_action( 'ninja_forms_insert_sub', 'ninja_forms_coregistration', 4 );
function ninja_forms_coregistration($sub_id){
    global $ninja_forms_processing;
    if( isset($ninja_forms_processing) && $ninja_forms_processing->data  AND  @$ninja_forms_processing->data['form']['sub_id'] ){
        $form = $ninja_forms_processing->data['form'] ;

        if($ninja_forms_processing->data['form_ID'] == 3){
            wp_enqueue_script('reworldmedia-ninja-forms-allianz-scripts', get_template_directory_uri().'/assets/javascripts/ninja-forms-allianz.js');
        }
        coregistration_send( $form, $ninja_forms_processing );
    }
}
</code>```

Here is my js file content:

```<code>jQuery(document).ready( function(){
    $(".ninja-forms-cont .ninja-forms-form").submit( function() {
        send_GA( "click-submit-form-allianz","submit","click sur allianz form" );
        return false;
    });
});
</code>```

答:
You are not getting the real error message. Try enabling debugging on the functions.php file. Add this to the top of the funuctions.php page.</p>

```<code><?php

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

?>
</code>```

Body:
I am registering and enqueuing the script in my file functions.php
I got a white page and a console error 500

add_action( 'ninja_forms_insert_sub', 'ninja_forms_coregistration', 4 );
function ninja_forms_coregistration($sub_id){
    global $ninja_forms_processing;
    if( isset($ninja_forms_processing) && $ninja_forms_processing->data  AND  @$ninja_forms_processing->data['form']['sub_id'] ){
        $form = $ninja_forms_processing->data['form'] ;

        if($ninja_forms_processing->data['form_ID'] == 3){
            wp_enqueue_script('reworldmedia-ninja-forms-allianz-scripts', get_template_directory_uri().'/assets/javascripts/ninja-forms-allianz.js');
        }
        coregistration_send( $form, $ninja_forms_processing );
    }
}

Here is my js file content:

jQuery(document).ready( function(){
    $(".ninja-forms-cont .ninja-forms-form").submit( function() {
        send_GA( "click-submit-form-allianz","submit","click sur allianz form" );
        return false;
    });
});

Body:
You are not getting the real error message. Try enabling debugging on the functions.php file. Add this to the top of the funuctions.php page.

<?php

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

?>


问:
Spark streaming output not saved to HDFS file
I am trying to save the Spark streaming output to a file on HDFS. Right now, it is not saving any file.

Here is my code :

```<code>StreamingExamples.setStreamingLogLevels();

SparkConf sparkConf = new SparkConf().setAppName("MyTestCOunt");
JavaStreamingContext ssc = new JavaStreamingContext(sparkConf,  new Duration(1000));

JavaReceiverInputDStream<String> lines = ssc.socketTextStream(args[0], Integer.parseInt(args[1]), StorageLevels.MEMORY_AND_DISK_SER);
JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
                @Override
                public Iterable<String> call(String x) {
                 return  Lists.newArrayList(SPACE.split(x));
                }
      });

JavaPairDStream<String, Integer> wordCounts = words.mapToPair(
      new PairFunction<String, String, Integer>() {
        @Override
        public Tuple2<String, Integer> call(String s) {
                 return new Tuple2<String, Integer>(s, 1);
        }
      }).reduceByKey(new Function2<Integer, Integer, Integer>() {
        @Override
        public Integer call(Integer i1, Integer i2) {
          return i1 + i2;
        }
  });

wordCounts.print();
wordCounts.saveAsHadoopFiles("hdfs://mynamenode:8020/user/spark/mystream/","abc");
ssc.start();
ssc.awaitTermination();
</code>```

wordCounts.print() works, but not wordCounts.saveAsHadoopFiles, any ideas why ?

I am running below commands :

1) nc -lk 9999

2) ./bin/run-example org.apache.spark.examples.streaming.NetworkWordCount localhost 9999

Thanks in advance..!!!

答:
I fixed this by changing the Sandbox / Server timezone to my local timezone, as my Twitter account has GMT and my Sandbox has UTC. I have used the following commands to change my Sandbox timezone:

```<code>ntpdate pool.ntp.org
chkconfig ntpd on
ntpdate pool.ntp.org
/etc/init.d/ntpd start
date
</code>```

I haven't restarted my Hadoop services after the timezone change.

Body:
I am trying to save the Spark streaming output to a file on HDFS. Right now, it is not saving any file.

Here is my code :

StreamingExamples.setStreamingLogLevels();

SparkConf sparkConf = new SparkConf().setAppName("MyTestCOunt");
JavaStreamingContext ssc = new JavaStreamingContext(sparkConf,  new Duration(1000));

JavaReceiverInputDStream<String> lines = ssc.socketTextStream(args[0], Integer.parseInt(args[1]), StorageLevels.MEMORY_AND_DISK_SER);
JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
                @Override
                public Iterable<String> call(String x) {
                 return  Lists.newArrayList(SPACE.split(x));
                }
      });

JavaPairDStream<String, Integer> wordCounts = words.mapToPair(
      new PairFunction<String, String, Integer>() {
        @Override
        public Tuple2<String, Integer> call(String s) {
                 return new Tuple2<String, Integer>(s, 1);
        }
      }).reduceByKey(new Function2<Integer, Integer, Integer>() {
        @Override
        public Integer call(Integer i1, Integer i2) {
          return i1 + i2;
        }
  });

wordCounts.print();
wordCounts.saveAsHadoopFiles("hdfs://mynamenode:8020/user/spark/mystream/","abc");
ssc.start();
ssc.awaitTermination();

wordCounts.print() works, but not wordCounts.saveAsHadoopFiles, any ideas why ?

I am running below commands :

1) nc -lk 9999

2) ./bin/run-example org.apache.spark.examples.streaming.NetworkWordCount localhost 9999

Thanks in advance..!!!

Body:
I fixed this by changing the Sandbox / Server timezone to my local timezone, as my Twitter account has GMT and my Sandbox has UTC. I have used the following commands to change my Sandbox timezone:

ntpdate pool.ntp.org
chkconfig ntpd on
ntpdate pool.ntp.org
/etc/init.d/ntpd start
date

I haven't restarted my Hadoop services after the timezone change.


问:
How do I run that database backup and restore scripts from my winform application?
I am developing a small business application which uses Sqlserver 2005 database.

Platform: .Net framework 3.5;
Application type: windows application;
Language: C#

Question:

I need to take and restore the backup from my application. I have the required script generated from SSME.

How do I run that particular script (or scripts) from my winform application?

答:
If you want to do it programatically you can use SMO

Tutorial

OwnerDisplayName: Asad Malik

OwnerDisplayName: cmsjr


问:
How to select first 2 items from an array?
I want to select the first 2 item from an array and also select just first name of each person from an object, not the full name.

These are my codes:

index.html

```<code><body>
<button onclick="loadajax();">laod ajax</button>
<div id = "update"></div>

<script src="jquery.js"></script>
<script src="script.js"></script>
</body>
</code>```

script.js

```<code>function loadajax(){
    var request;
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    } else {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    request.open('GET', 'data.json');
    request.onreadystatechange = function() {
        if ((request.readyState===4) && (request.status===200)) {
            var items = JSON.parse(request.responseText);
            var output = '<ul>';
            for (var key in items) {
                output += '<li>his name is:' + items[key].name + ' with the id of:'+ items[key].id +'</li>';
            }
            output += '</ul>';
            document.getElementById('update').innerHTML = output;
        }
    }
    request.send();
}
</code>```

data.json

```<code>[
  {
    "name":"Barot Bellingham",
    "id":"1"
  },
  {
    "name":"alex benjan",
    "id":"2"
  },
  {
    "name":"jony lekson",
    "id":"3"
  }
]
</code>```

this is the results:

his name is:Barot Bellingham with the id of:1

his name is:alex benjan with the id of:2

his name is:jony lekson with the id of:3

but what I want is this:

his name is:Barot  with the id of:1

his name is:alex  with the id of:2

do you have an idea how to do this?

答:
Another approach returning an array:

```<code>  var jsonArray = [
  {
    "name":"Barot Bellingham",
    "id":"1"
  },
  {
    "name":"alex benjan",
    "id":"2"
  },
  {
    "name":"jony lekson",
    "id":"3"
  }
];

var user = jsonArray .map((user, index) => {
        return { 'id': user.id, 'name' : user.name.split(' ')[0] };
 }).slice(0, 2)
</code>```

output:
//[{"id":"1","name":"Barot"},{"id":"2","name":"alex"}]

Body:
I want to select the first 2 item from an array and also select just first name of each person from an object, not the full name.

These are my codes:

index.html

<button onclick="loadajax();">laod ajax</button>

script.js

function loadajax(){
    var request;
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    } else {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    request.open('GET', 'data.json');
    request.onreadystatechange = function() {
        if ((request.readyState===4) && (request.status===200)) {
            var items = JSON.parse(request.responseText);
            var output = '
';
            for (var key in items) {
                output += '
his name is:' + items[key].name + ' with the id of:'+ items[key].id +'
';
            }
            output += '
';
            document.getElementById('update').innerHTML = output;
        }
    }
    request.send();
}

data.json

[
  {
    "name":"Barot Bellingham",
    "id":"1"
  },
  {
    "name":"alex benjan",
    "id":"2"
  },
  {
    "name":"jony lekson",
    "id":"3"
  }
]

this is the results:

his name is:Barot Bellingham with the id of:1

his name is:alex benjan with the id of:2

his name is:jony lekson with the id of:3

but what I want is this:

his name is:Barot  with the id of:1

his name is:alex  with the id of:2

do you have an idea how to do this?

Body:
Another approach returning an array:

  var jsonArray = [
  {
    "name":"Barot Bellingham",
    "id":"1"
  },
  {
    "name":"alex benjan",
    "id":"2"
  },
  {
    "name":"jony lekson",
    "id":"3"
  }
];

var user = jsonArray .map((user, index) => {
        return { 'id': user.id, 'name' : user.name.split(' ')[0] };
 }).slice(0, 2)

output:
//[{"id":"1","name":"Barot"},{"id":"2","name":"alex"}]