问:
Javascript Date.UTC() returns previous day
I have the following method implemented for the date picker. </p>

```<code>getMyDate: function(date){
  var year = date.find('.year').val(); // fetch the selected date from picker
  var day = date.find('.day').val();
  var month = date.find('month').val()-1;

  return new Date(Date.UTC(year,month,day)); // This is always returning previous day
}
</code>```

<p>Can someone tell me how to get the correct date based on the picker selection? </p>

答:
The UTC() method returns the number of milliseconds between a specified date and midnight of January 1, 1970, according to universal time.
I think the reason of your issue is timezone.
So, please change the date with your timezone.

Please check following example

```<code>var offset = -8;
new Date( Date.UTC(2020, 1, 8) + offset * 3600 * 1000).toUTCString().replace( / GMT$/, "" )

"Fri, 07 Feb 2020 16:00:00"

var offset = +8;
new Date( Date.UTC(2020, 1, 8) + offset * 3600 * 1000).toUTCString().replace( / GMT$/, "" )
"Sat, 08 Feb 2020 08:00:00"
</code>```

Body:
I have the following method implemented for the date picker.

getMyDate: function(date){
  var year = date.find('.year').val(); // fetch the selected date from picker
  var day = date.find('.day').val();
  var month = date.find('month').val()-1;

  return new Date(Date.UTC(year,month,day)); // This is always returning previous day
}

Can someone tell me how to get the correct date based on the picker selection?

Body:
The UTC() method returns the number of milliseconds between a specified date and midnight of January 1, 1970, according to universal time.
I think the reason of your issue is timezone.
So, please change the date with your timezone.

Please check following example

var offset = -8;
new Date( Date.UTC(2020, 1, 8) + offset * 3600 * 1000).toUTCString().replace( / GMT$/, "" )

"Fri, 07 Feb 2020 16:00:00"

var offset = +8;
new Date( Date.UTC(2020, 1, 8) + offset * 3600 * 1000).toUTCString().replace( / GMT$/, "" )
"Sat, 08 Feb 2020 08:00:00"


来源: stackexchange

问:
Statsmodel SARIMAX Fitted values ('seasonally adjusted') look like they are one period ahead of the true data
I am having some trouble using Statmodel's SARIMAX function to do seasonal adjustments for a data series I have. The code is below but generally my process is that I am testing a variety of SARIMA parameters on my data, picking the one with the lowest AIC, running the model, and then getting the fitted values. The issue is that for some datasets the fitted values (seasonally adjusted) basically just look like my original data shifted backwards from one period. Is there anything I am doing glaringly wrong here?

```<code>def seasonal_fit(data_to_fit, column_name):
    # finding sarima parameters
    p = d = q = range(0, 2)
    pdq = list(itertools.product(p, d, q))
    seasonal_pdq = [(x[0], x[1], x[2], 12)
                    for x in list(itertools.product(p, d, q))]

    param_dict = []
    keys = ['Parameters', 'Seasonal Parameters', 'AIC']

    for param in pdq:
        for param_seasonal in seasonal_pdq:
            try:
                mod = sm.tsa.statespace.SARIMAX(data_to_fit, order=param,
                                                seasonal_order=param_seasonal, enforce_stationarity=False, enforce_invertibility=False)
                # , enforce_stationarity=False, enforce_invertibility=False)
                results = mod.fit()
                insert = [param, param_seasonal, results.aic]
                param_dict.append(dict(zip(keys, insert)))
            except:
                continue
    param_dict = pd.DataFrame(param_dict)
    best_fit = param_dict.loc[param_dict['AIC'].idxmin()]

    mod = sm.tsa.statespace.SARIMAX(data_to_fit,
                                    order=(
                                        best_fit['Parameters'][0], best_fit['Parameters'][1], best_fit['Parameters'][2]),
                                    seasonal_order=(best_fit['Seasonal Parameters'][0], best_fit['Seasonal Parameters']
                                                    [1], best_fit['Seasonal Parameters'][2], best_fit['Seasonal Parameters'][3]), enforce_stationarity=False, enforce_invertibility=False)
    results = mod.fit()
    pdb.set_trace()
    fitted_values = pd.DataFrame(results.fittedvalues)
</code>```

答: In case anyone stumbles upon this I found the answer myself after a bit of searching. Here is one of the sources (https://stats.stackexchange.com/questions/330928/time-series-prediction-shifted). Basically -- ARIMA by its nature lags and uses priors to predict forward. You're necessarily going to see the curve shifted to the right by x periods, with x being the number of differences that occur. Lesson learned is don't be surprised when something weird happens when you try to implement something you don't fully understand...</p>

ContentLicense: CC BY-SA 4.0

Body:
I am having some trouble using Statmodel's SARIMAX function to do seasonal adjustments for a data series I have. The code is below but generally my process is that I am testing a variety of SARIMA parameters on my data, picking the one with the lowest AIC, running the model, and then getting the fitted values. The issue is that for some datasets the fitted values (seasonally adjusted) basically just look like my original data shifted backwards from one period. Is there anything I am doing glaringly wrong here?

def seasonal_fit(data_to_fit, column_name):
    # finding sarima parameters
    p = d = q = range(0, 2)
    pdq = list(itertools.product(p, d, q))
    seasonal_pdq = [(x[0], x[1], x[2], 12)
                    for x in list(itertools.product(p, d, q))]

    param_dict = []
    keys = ['Parameters', 'Seasonal Parameters', 'AIC']

    for param in pdq:
        for param_seasonal in seasonal_pdq:
            try:
                mod = sm.tsa.statespace.SARIMAX(data_to_fit, order=param,
                                                seasonal_order=param_seasonal, enforce_stationarity=False, enforce_invertibility=False)
                # , enforce_stationarity=False, enforce_invertibility=False)
                results = mod.fit()
                insert = [param, param_seasonal, results.aic]
                param_dict.append(dict(zip(keys, insert)))
            except:
                continue
    param_dict = pd.DataFrame(param_dict)
    best_fit = param_dict.loc[param_dict['AIC'].idxmin()]

    mod = sm.tsa.statespace.SARIMAX(data_to_fit,
                                    order=(
                                        best_fit['Parameters'][0], best_fit['Parameters'][1], best_fit['Parameters'][2]),
                                    seasonal_order=(best_fit['Seasonal Parameters'][0], best_fit['Seasonal Parameters']
                                                    [1], best_fit['Seasonal Parameters'][2], best_fit['Seasonal Parameters'][3]), enforce_stationarity=False, enforce_invertibility=False)
    results = mod.fit()
    pdb.set_trace()
    fitted_values = pd.DataFrame(results.fittedvalues)


问:
Zerofill with Doctrine2
It looks like an easy task, but I can't get it done:

How do I define a column to be UNSIGNED ZEROFILL with Doctrine2?

I can't find any information about it in the docs.

Thx for any help!

答: Use the (non-portable) columnDefinition property in the @Column annotation.

ContentLicense: CC BY-SA 3.0

Title: Zerofill with Doctrine2


问:
Transparent navigation bar iOS 13
Can't create transparent NavigationBar iOS 13.

I have custom UINavigationBar, where I configure UINavigationBarAppearance in

```<code>override init(frame: CGRect) {
    super.init(frame: frame)
    self.configure()
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
    self.configure()
}
</code>```

Configuration code:

```<code>let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
appearance.shadowColor = .clear
appearance.backgroundColor = .clear
</code>```

And set it to:

```<code>self.compactAppearance = appearance
self.standardAppearance = appearance
self.scrollEdgeAppearance = appearance
</code>```

And by the result I have this:

Expected result: NavigationBar should be transparent

答:
Works for me:</p>

```<code>self.compactAppearance = appearance
self.standardAppearance = appearance
self.scrollEdgeAppearance = appearance
self.backgroundColor = appearance.backgroundColor
</code>```

Title: Transparent navigation bar iOS 13

Body:
Can't create transparent NavigationBar iOS 13.

I have custom UINavigationBar, where I configure UINavigationBarAppearance in

override init(frame: CGRect) {
    super.init(frame: frame)
    self.configure()
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
    self.configure()
}

Configuration code:

let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
appearance.shadowColor = .clear
appearance.backgroundColor = .clear

And set it to:

self.compactAppearance = appearance
self.standardAppearance = appearance
self.scrollEdgeAppearance = appearance

And by the result I have this:

Expected result: NavigationBar should be transparent

Body:
Works for me:

self.compactAppearance = appearance
self.standardAppearance = appearance
self.scrollEdgeAppearance = appearance
self.backgroundColor = appearance.backgroundColor


问:
C program to find the duplicate values from an m×n matrix using malloc() and free()
SO i was solving this problem and i get this output

**But i am expecting output like this **

what is my mistake here?
I know i don't code efficiently and i want to know how can i make this code more compact any suggestions will be helpful as i am still learning these things.

```<code>#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int main()
{
    int i,j,k,l,f=0,x=0,q=0,row,column,size;
    int res[100];

    printf("Enter the row: ");
    scanf("%d",&row);
    printf("Enter the column: ");
    scanf("%d",&column);
    size= row*column;

    int **arr;
    arr=(int**)malloc(row * sizeof(int));
    for(i=0;i<row;i++)
    {
        arr[i] = (int*)malloc(column*sizeof(int));
    }

    for(i=0;i<row;i++)
    {
        for (j=0;j<column;j++)
        {
            printf("Enter the value at row %d and column %d : ",i,j);
            scanf("%d",(*(arr+i)+j));

        }
    }
    for(i=0;i<row;i++)
    {
        for (j=0;j<column;j++)
        {
            printf("\nThe value at row %d and column %d : %d",i,j,*(*(arr+i)+j));

        }
    }
    printf("\nThe duplicate value(s) are:\n");
    for(i=0; i<row; i++)
    {
        for(j=0; j<column; j++)
        {

            for(k=0; k<row; k++)
            {
                for(l=0; l<column; l++)
                {
                    if(*(*(arr+i)+j)== *(*(arr+k)+l))
                    {
                        f=f+1;
                    }
                    if(f>1)
                    {
                        printf("%d in positions (%d,%d)",*(*(arr+i)+j),k,l);
                    }
                }
            }f=0;
        }
    }

    free(arr);
}
</code>```

答:
This is closer to the original code.

skip duplicates that are found closer to the beginning of arr so those are only printed once.

Use a first flag to print the first indices of the first pair of matching values.

pending stores a set of indices to defer printing. This allows printing the last set of indices with a leading and while printing any other indices with a leanding comma.

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

int scanint ( int *value) {
    int result = 0;
    result = scanf ( "%d", value);//ampersand not needed. value is int *
    if ( 0 == result) {//could not parse an int from input
        while ( '\n' != ( result = getchar ( ))) {//read until newline
            if ( EOF == result) {
                fprintf ( stderr, "EOF\n");
                exit ( EXIT_FAILURE);
            }
        }
        return 0;
    }
    return 1;
}

int main()
{
    int eachrow = 0;
    int eachcol = 0;
    int row = 0;
    int column = 0;
    int result = 0;

    do {
        printf ( "Enter the row: ");
        fflush ( stdout);
        result = scanint ( &row);
    } while ( 0 == result);
    do {
        printf ( "Enter the column: ");
        fflush ( stdout);
        result = scanint ( &column);
    } while ( 0 == result);

    int **arr = NULL;

    if ( NULL == ( arr = malloc ( sizeof *arr * row))) {
        fprintf ( stderr, "malloc arr problem\n");
        exit ( EXIT_FAILURE);
    }
    for ( eachrow = 0; eachrow < row; ++eachrow) {
        if ( NULL == ( arr[eachrow] = malloc ( sizeof **arr * column))) {
            fprintf ( stderr, "malloc arr[] problem\n");
            while ( eachrow) {
                eachrow--;
                free ( arr[eachrow]);
            }
            free ( arr);
            exit ( EXIT_FAILURE);
        }
    }

    for ( eachrow = 0; eachrow < row; ++eachrow) {
        for ( eachcol = 0; eachcol < column; ++eachcol) {
            do {
                printf ( "Enter the value for (%d %d) : ", eachrow, eachcol);
                fflush ( stdout);
                result = scanint ( &arr[eachrow][eachcol]);
            } while ( 0 == result);
        }
    }
    for ( eachrow = 0; eachrow < row; ++eachrow) {
        for ( eachcol = 0; eachcol < column; ++eachcol) {
            printf ( "The value at (%d %d) : %d\n", eachrow, eachcol, arr[eachrow][eachcol]);
        }
    }

    char pending[30] = "";
    int checkrow = 0;
    int checkcol = 0;
    int skip = 0;
    int first = 0;
    int title = 0;
    int line = 1;

    for ( eachrow = 0; eachrow < row; ++eachrow) {
        for ( eachcol = 0; eachcol < column; ++eachcol) {
            first = 0;//will need to print the first part of line
            pending[0] = 0;//nothing pending
            for ( checkrow = 0; checkrow < row; ++checkrow) {
                skip = 0;//do not skip
                for ( checkcol = 0; checkcol < column; ++checkcol) {
                    if ( arr[eachrow][eachcol] == arr[checkrow][checkcol]) {//match
                        if ( checkrow * column + checkcol > eachrow * column + eachcol) {//subsequent match
                            if ( ! title) {
                                title = 1;
                                printf ( "\nThe duplicate value(s) are:\n");
                            }
                            if ( ! first) {//need to print first part of line
                                first = 1;//printed
                                printf ( "%d.  %d in positions (%d,%d)"
                                , line, arr[eachrow][eachcol], eachrow, eachcol);
                            }
                            if ( pending[0]) {//print pending indices
                                printf ( ", %s", pending);
                            }
                            sprintf ( pending, "(%d,%d)", checkrow, checkcol);//copy indices to pending
                        }
                        else {//current or previous match
                            //ignore current match    ( checkrow * column + checkcol == eachrow * column + eachcol)
                            if ( checkrow * column + checkcol < eachrow * column + eachcol) {//previous match
                                skip = 1;//need to skip checkcol and checkrow
                                break;//out of for checkcol loop
                            }
                        }
                    }
                }
                if ( skip) {
                    break;//out of checkrow loop
                }
            }
            if ( first) {//there were matches
                printf ( " and %s\n", pending);//print  and  with pending indices
            }
        }
    }
    if ( ! title) {
        printf ( "\nNo duplicates\n");
    }

    for ( eachrow = 0; eachrow < row; ++eachrow) {
        free ( arr[eachrow]);
    }
    free(arr);
}
</code>```

Body:
SO i was solving this problem and i get this output

**But i am expecting output like this **

what is my mistake here?
I know i don't code efficiently and i want to know how can i make this code more compact any suggestions will be helpful as i am still learning these things.

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int main()
{
    int i,j,k,l,f=0,x=0,q=0,row,column,size;
    int res[100];

    printf("Enter the row: ");
    scanf("%d",&row);
    printf("Enter the column: ");
    scanf("%d",&column);
    size= row*column;

    int **arr;
    arr=(int**)malloc(row * sizeof(int));
    for(i=0;i<row;i++)
    {
        arr[i] = (int*)malloc(column*sizeof(int));
    }

    for(i=0;i<row;i++)
    {
        for (j=0;j<column;j++)
        {
            printf("Enter the value at row %d and column %d : ",i,j);
            scanf("%d",(*(arr+i)+j));

        }
    }
    for(i=0;i<row;i++)
    {
        for (j=0;j<column;j++)
        {
            printf("\nThe value at row %d and column %d : %d",i,j,*(*(arr+i)+j));

        }
    }
    printf("\nThe duplicate value(s) are:\n");
    for(i=0; i<row; i++)
    {
        for(j=0; j<column; j++)
        {

            for(k=0; k<row; k++)
            {
                for(l=0; l<column; l++)
                {
                    if(*(*(arr+i)+j)== *(*(arr+k)+l))
                    {
                        f=f+1;
                    }
                    if(f>1)
                    {
                        printf("%d in positions (%d,%d)",*(*(arr+i)+j),k,l);
                    }
                }
            }f=0;
        }
    }

    free(arr);
}

Body:
This is closer to the original code.

skip duplicates that are found closer to the beginning of arr so those are only printed once.

Use a first flag to print the first indices of the first pair of matching values.

pending stores a set of indices to defer printing. This allows printing the last set of indices with a leading and while printing any other indices with a leanding comma.

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

int scanint ( int *value) {
    int result = 0;
    result = scanf ( "%d", value);//ampersand not needed. value is int *
    if ( 0 == result) {//could not parse an int from input
        while ( '\n' != ( result = getchar ( ))) {//read until newline
            if ( EOF == result) {
                fprintf ( stderr, "EOF\n");
                exit ( EXIT_FAILURE);
            }
        }
        return 0;
    }
    return 1;
}

int main()
{
    int eachrow = 0;
    int eachcol = 0;
    int row = 0;
    int column = 0;
    int result = 0;

    do {
        printf ( "Enter the row: ");
        fflush ( stdout);
        result = scanint ( &row);
    } while ( 0 == result);
    do {
        printf ( "Enter the column: ");
        fflush ( stdout);
        result = scanint ( &column);
    } while ( 0 == result);

    int **arr = NULL;

    if ( NULL == ( arr = malloc ( sizeof *arr * row))) {
        fprintf ( stderr, "malloc arr problem\n");
        exit ( EXIT_FAILURE);
    }
    for ( eachrow = 0; eachrow < row; ++eachrow) {
        if ( NULL == ( arr[eachrow] = malloc ( sizeof **arr * column))) {
            fprintf ( stderr, "malloc arr[] problem\n");
            while ( eachrow) {
                eachrow--;
                free ( arr[eachrow]);
            }
            free ( arr);
            exit ( EXIT_FAILURE);
        }
    }

    for ( eachrow = 0; eachrow < row; ++eachrow) {
        for ( eachcol = 0; eachcol < column; ++eachcol) {
            do {
                printf ( "Enter the value for (%d %d) : ", eachrow, eachcol);
                fflush ( stdout);
                result = scanint ( &arr[eachrow][eachcol]);
            } while ( 0 == result);
        }
    }
    for ( eachrow = 0; eachrow < row; ++eachrow) {
        for ( eachcol = 0; eachcol < column; ++eachcol) {
            printf ( "The value at (%d %d) : %d\n", eachrow, eachcol, arr[eachrow][eachcol]);
        }
    }

    char pending[30] = "";
    int checkrow = 0;
    int checkcol = 0;
    int skip = 0;
    int first = 0;
    int title = 0;
    int line = 1;

    for ( eachrow = 0; eachrow < row; ++eachrow) {
        for ( eachcol = 0; eachcol < column; ++eachcol) {
            first = 0;//will need to print the first part of line
            pending[0] = 0;//nothing pending
            for ( checkrow = 0; checkrow < row; ++checkrow) {
                skip = 0;//do not skip
                for ( checkcol = 0; checkcol < column; ++checkcol) {
                    if ( arr[eachrow][eachcol] == arr[checkrow][checkcol]) {//match
                        if ( checkrow * column + checkcol > eachrow * column + eachcol) {//subsequent match
                            if ( ! title) {
                                title = 1;
                                printf ( "\nThe duplicate value(s) are:\n");
                            }
                            if ( ! first) {//need to print first part of line
                                first = 1;//printed
                                printf ( "%d.  %d in positions (%d,%d)"
                                , line, arr[eachrow][eachcol], eachrow, eachcol);
                            }
                            if ( pending[0]) {//print pending indices
                                printf ( ", %s", pending);
                            }
                            sprintf ( pending, "(%d,%d)", checkrow, checkcol);//copy indices to pending
                        }
                        else {//current or previous match
                            //ignore current match    ( checkrow * column + checkcol == eachrow * column + eachcol)
                            if ( checkrow * column + checkcol < eachrow * column + eachcol) {//previous match
                                skip = 1;//need to skip checkcol and checkrow
                                break;//out of for checkcol loop
                            }
                        }
                    }
                }
                if ( skip) {
                    break;//out of checkrow loop
                }
            }
            if ( first) {//there were matches
                printf ( " and %s\n", pending);//print  and  with pending indices
            }
        }
    }
    if ( ! title) {
        printf ( "\nNo duplicates\n");
    }

    for ( eachrow = 0; eachrow < row; ++eachrow) {
        free ( arr[eachrow]);
    }
    free(arr);
}


问:
python: minimum value within specified bounds for an array
Say I have an array  a = [-1.2, 1, 0.5, 4, 5, 3]

Is there a way to find a min element which is within a=0.2 to b=2

In this particular example the answer will be 0.5.

I want to perform this computation in python. .

Body:
If you can use numpy:

a = np.array([-1.2, 1, 0.5, 4, 5, 3])
min(a[(a<2) & (a > 0.2)])


问:
using javascript array method to print the value of x
Could someone explain following code to me and what happens in x.join = x.shift;?

x = [5, 10, 15];

x.join = x.shift;

if (x == 5 && x == 10 && x == 15)
  console.log('good');```

答:
When you are doing the x== it calls toString. They replace join() with shift() which pulls off the first index.

x = [5, 10, 15];

console.log(x.toString())

x.join = x.shift;

console.log(x.toString())
console.log(x.toString())
console.log(x.toString())```

Please do not do this....

Body:
When you are doing the x== it calls toString. They replace join() with shift() which pulls off the first index.

x = [5, 10, 15];

console.log(x.toString())

x.join = x.shift;

console.log(x.toString())
console.log(x.toString())
console.log(x.toString())

Please do not do this....


问:
App Script to delete rows if cells match values from list
I'm trying to delete rows when a specific cell in the row matches any value from a list from another sheet. Existing solutions I find only deal with a single value to be matched.

The script I have below either deletes the wrong rows (the cell doesn't match any values in the list) or returns the error 'rows are out of bounds'. Any pointers appreciated.

```<code>function main() {

  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Sheet1");
  var ssData = sheet.getRange('A2:I').getValues();

  var negSheet = ss.getSheetByName("negs");
  var negValues = negSheet.getRange('A1:B').getValues();

  Logger.log(negValues);

  for(var i = 0; i < ssData.length; i++) {

    var row = ssData[i];
    var matched = row[2];

    if(matched == "")
      break;

    Logger.log(matched);

    for(var j = 0; j < negValues.length; j++) {

      var negRow = negValues[j];
      var negVal = negRow[0];

      if(negVal == "")
        break;

      var rowsDeleted = 1;
      for(k = 0; k < ssData.length; k++) {

      if (matched == negVal) {
        sheet.deleteRow(rowsDeleted);
        rowsDeleted--; // Deleted a row

        continue;

      } else {
        rowsDeleted++; // Go to the next row

  }

      }

  }

  }}
</code>```

答:
Try this:

```<code>function deleteRowsWithValuesThatHaveMatchesinList() {
  const ss=SpreadsheetApp.getActive();
  const list=ss.getSheetByName('List');
  const rg=list.getRange(1,1,list.getLastRow(),1);//assuming list is in column 1
  const lvA=rg.getValues().map(function(r){return r[0]});
  const sh=ss.getSheetByName('Sheet');
  const rg1=sh.getDataRange();
  const vs=rg1.getValues();
  let d=0;
  let x='index of column you searching for'
  vs.forEach(function(r,i){
    if(lvA.indexOf(r[x])!=-1) {
      sh.deleteRow(i+1-d++);
    }
  });
}
</code>```

Maybe this:

```<code>function deleteRowsWithValuesThatHaveMatchesinList() {
  const ss=SpreadsheetApp.getActive();
  const list=ss.getSheetByName('List');
  const rg=list.getRange(1,1,list.getLastRow(),1);//assuming list is in column 1
  const lvA=rg.getValues().map(function(r){return r[0]});
  const sh=ss.getSheetByName('Sheet');
  const rg1=sh.getDataRange();
  const vs=rg1.getValues();
  let d=0;
  let x='index of column you searching for'
  vs.forEach(function(r,i){
    for(var j=0;j<lvA.lengh;j++) {
      if(lvA.join('~~~').indexOf(r[x])!=-1){
        sh.deleteRow(i+1-d++);
      }
    }
  });
}
</code>```

Body:
I'm trying to delete rows when a specific cell in the row matches any value from a list from another sheet. Existing solutions I find only deal with a single value to be matched.

The script I have below either deletes the wrong rows (the cell doesn't match any values in the list) or returns the error 'rows are out of bounds'. Any pointers appreciated.

function main() {

  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Sheet1");
  var ssData = sheet.getRange('A2:I').getValues();

  var negSheet = ss.getSheetByName("negs");
  var negValues = negSheet.getRange('A1:B').getValues();

  Logger.log(negValues);

  for(var i = 0; i < ssData.length; i++) {

    var row = ssData[i];
    var matched = row[2];

    if(matched == "")
      break;

    Logger.log(matched);

    for(var j = 0; j < negValues.length; j++) {

      var negRow = negValues[j];
      var negVal = negRow[0];

      if(negVal == "")
        break;

      var rowsDeleted = 1;
      for(k = 0; k < ssData.length; k++) {

      if (matched == negVal) {
        sheet.deleteRow(rowsDeleted);
        rowsDeleted--; // Deleted a row

        continue;

      } else {
        rowsDeleted++; // Go to the next row

  }

      }

  }

  }}

Body:
Try this:

function deleteRowsWithValuesThatHaveMatchesinList() {
  const ss=SpreadsheetApp.getActive();
  const list=ss.getSheetByName('List');
  const rg=list.getRange(1,1,list.getLastRow(),1);//assuming list is in column 1
  const lvA=rg.getValues().map(function(r){return r[0]});
  const sh=ss.getSheetByName('Sheet');
  const rg1=sh.getDataRange();
  const vs=rg1.getValues();
  let d=0;
  let x='index of column you searching for'
  vs.forEach(function(r,i){
    if(lvA.indexOf(r[x])!=-1) {
      sh.deleteRow(i+1-d++);
    }
  });
}

Maybe this:

function deleteRowsWithValuesThatHaveMatchesinList() {
  const ss=SpreadsheetApp.getActive();
  const list=ss.getSheetByName('List');
  const rg=list.getRange(1,1,list.getLastRow(),1);//assuming list is in column 1
  const lvA=rg.getValues().map(function(r){return r[0]});
  const sh=ss.getSheetByName('Sheet');
  const rg1=sh.getDataRange();
  const vs=rg1.getValues();
  let d=0;
  let x='index of column you searching for'
  vs.forEach(function(r,i){
    for(var j=0;j<lvA.lengh;j++) {
      if(lvA.join('~~~').indexOf(r[x])!=-1){
        sh.deleteRow(i+1-d++);
      }
    }
  });
}


问:
How to move a shortcut in google drive
I need to move a shortcut file from one destination to another using google apps script.
Usually I would move a file or folder like this:

```<code>function move(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sStamdata = ss.getSheetByName("New");
  var folderOld = DriveApp.getFolderById(folderOldId);
  var destination = DriveApp.getFolderById(folderId);
  var id = sStamdata.getRange('D77').getValue();
  var file = DriveApp.getFileById(id);

     folderOld.removeFile(file)
     destination.addFile(file)
</code>```

But this doesn't work with shortcuts. Any ideas?

答:
How about this answer?

Modification points:

It seems that in the current stage, the shortcut cannot be moved using Drive service. I think that this might be resolve in the future update.

So as the current workaround, in this answer, I would like to propose to use the method of "Files: patch" Drive API v2, because Drive API of Advanced Google services is used.

When your script is modified, please modify as follows.

Modified script:

Before you run the script, please enable Drive API at Advanced Google services.

```<code>function move(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sStamdata = ss.getSheetByName("New");
//  var folderOld = DriveApp.getFolderById(folderOldId);
//  var destination = DriveApp.getFolderById(folderId);
  var id = sStamdata.getRange('D77').getValue();
//  var file = DriveApp.getFileById(id);

  Drive.Files.patch({parents: [{id: folderId}]}, id);  // Added
}
</code>```

folderId is the destination folder ID.

Please confirm the file ID of the shortcut again.

Note:

For example, when the file ID of the shortcut is confirmed with the shared link using the browser, the file ID is ID of the original file. Please be careful this.

References:

Advanced Google services

Files: patch

Title: How to move a shortcut in google drive

Body:
I need to move a shortcut file from one destination to another using google apps script.
Usually I would move a file or folder like this:

function move(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sStamdata = ss.getSheetByName("New");
  var folderOld = DriveApp.getFolderById(folderOldId);
  var destination = DriveApp.getFolderById(folderId);
  var id = sStamdata.getRange('D77').getValue();
  var file = DriveApp.getFileById(id);

     folderOld.removeFile(file)
     destination.addFile(file)

But this doesn't work with shortcuts. Any ideas?

Body:
How about this answer?

Modification points:

It seems that in the current stage, the shortcut cannot be moved using Drive service. I think that this might be resolve in the future update.

So as the current workaround, in this answer, I would like to propose to use the method of "Files: patch" Drive API v2, because Drive API of Advanced Google services is used.

When your script is modified, please modify as follows.

Modified script:

Before you run the script, please enable Drive API at Advanced Google services.

function move(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sStamdata = ss.getSheetByName("New");
//  var folderOld = DriveApp.getFolderById(folderOldId);
//  var destination = DriveApp.getFolderById(folderId);
  var id = sStamdata.getRange('D77').getValue();
//  var file = DriveApp.getFileById(id);

  Drive.Files.patch({parents: [{id: folderId}]}, id);  // Added
}

folderId is the destination folder ID.

Please confirm the file ID of the shortcut again.

Note:

For example, when the file ID of the shortcut is confirmed with the shared link using the browser, the file ID is ID of the original file. Please be careful this.

References:

Advanced Google services

Files: patch


问:
Add line automatically
I'm new to VBA and I have the code below to automatically add a line when there is some content in a cell in column B. However, I'd like to modify the formula so that if I change the content within a cell that already had content in it or delete the content in a cell and rewrite something within the same cell later it doesnt add an extra line.
Many thanks!</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

'Test if change is in column B and only one cell changed
If Not Intersect(Target, Me.Columns("B")) Is Nothing And _
        Target.Cells.Count = 1 Then

    If len(Target)>0 then
          Target.Offset(1, 0).EntireRow.Insert Shift:=xlDown      'Insert row below data entry
         'Target.EntireRow.Insert Shift:=xlDown       'Insert row above data entry
    End If
End If

End Sub

</code>```

答:
Assuming that you are inserting a row below to neaten up the document and make it easier to read the data (a blank row, that will always remain blank), then you could add a simple logic check using CountA before inserting the line to see whether there is already a blank row below the target cell. If there is a blank row it won't add one, if there isn't then it will add one:</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

'Test if change is in column B and only one cell changed
If Not Intersect(Target, Me.Columns("B")) Is Nothing And _
        Target.Cells.Count = 1 Then

    If Len(Target) > 0 And Application.CountA(Rows(Target.Offset(1).Row)) <> 0 Then 'New condition added here
          Target.Offset(1, 0).EntireRow.Insert Shift:=xlDown      'Insert row below data entry
         'Target.EntireRow.Insert Shift:=xlDown       'Insert row above data entry
    End If
End If

End Sub
</code>```

Title: Add line automatically

Body:
I'm new to VBA and I have the code below to automatically add a line when there is some content in a cell in column B. However, I'd like to modify the formula so that if I change the content within a cell that already had content in it or delete the content in a cell and rewrite something within the same cell later it doesnt add an extra line.
Many thanks!

Private Sub Worksheet_Change(ByVal Target As Range)

'Test if change is in column B and only one cell changed
If Not Intersect(Target, Me.Columns("B")) Is Nothing And _
        Target.Cells.Count = 1 Then

    If len(Target)>0 then
          Target.Offset(1, 0).EntireRow.Insert Shift:=xlDown      'Insert row below data entry
         'Target.EntireRow.Insert Shift:=xlDown       'Insert row above data entry
    End If
End If

End Sub

Body:
Assuming that you are inserting a row below to neaten up the document and make it easier to read the data (a blank row, that will always remain blank), then you could add a simple logic check using CountA before inserting the line to see whether there is already a blank row below the target cell. If there is a blank row it won't add one, if there isn't then it will add one:

Private Sub Worksheet_Change(ByVal Target As Range)

'Test if change is in column B and only one cell changed
If Not Intersect(Target, Me.Columns("B")) Is Nothing And _
        Target.Cells.Count = 1 Then

    If Len(Target) > 0 And Application.CountA(Rows(Target.Offset(1).Row)) <> 0 Then 'New condition added here
          Target.Offset(1, 0).EntireRow.Insert Shift:=xlDown      'Insert row below data entry
         'Target.EntireRow.Insert Shift:=xlDown       'Insert row above data entry
    End If
End If

End Sub


问:
Creating Schema in Firebase database with NodeJS
I am not a pro in JS/NodeJS and I have some experience using express-mongoose.

Now, I prefer MVC approach, meaning creating schema and importing it.

Since, Firebase database also happens to be no sql database, I decided on doing exactly what I am suppose to do in mongoose but unfortunately I am unable to understand.

To say the least, I have created index.js which is my entry point of the app.

And as per firebase docs, I am initialising it like this (index.js)

```<code>const admin = require("firebase-admin");

//Firbade config file
const firebaseConfig = require("./functions-config.json")

admin.initializeApp({
    credential: admin.credential.cert(firebaseConfig),
    databaseURL: "https://functions-firebase-43a59.firebaseio.com"
})

const db = admin.firestore()
</code>```

.

Question: Can we create schema in firebase db as we are used to creating in mongoose

i.e this is the example of creating mongoose schema in NodeJS (models/user.js)

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

const userSchema = new mongoose.Schema({
    fullName: String,
    email: String,
    image: String,
    gender: String,
    profile_id: String,
    createdAt: {type: Date, default: Date.now}
})

module.exports = mongoose.model('User', userSchema);
</code>```

答:
Yes, you can create db schema for firestore in node js using class. There are a few third party libraries for firestore ORM (Object-relational Mapper) available:

https://www.npmjs.com/package/fireorm

https://www.npmjs.com/package/firebase-firestorm

https://www.npmjs.com/package/typesaurus

https://www.npmjs.com/package/@typeheim/orm-on-fire

Body:
I am not a pro in JS/NodeJS and I have some experience using express-mongoose.

Now, I prefer MVC approach, meaning creating schema and importing it.

Since, Firebase database also happens to be no sql database, I decided on doing exactly what I am suppose to do in mongoose but unfortunately I am unable to understand.

To say the least, I have created index.js which is my entry point of the app.

And as per firebase docs, I am initialising it like this (index.js)

const admin = require("firebase-admin");

//Firbade config file
const firebaseConfig = require("./functions-config.json")

admin.initializeApp({
    credential: admin.credential.cert(firebaseConfig),
    databaseURL: "https://functions-firebase-43a59.firebaseio.com"
})

const db = admin.firestore()

.

Question: Can we create schema in firebase db as we are used to creating in mongoose

i.e this is the example of creating mongoose schema in NodeJS (models/user.js)

const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
    fullName: String,
    email: String,
    image: String,
    gender: String,
    profile_id: String,
    createdAt: {type: Date, default: Date.now}
})

module.exports = mongoose.model('User', userSchema);


问:
Font-weight not working on specif areas of a website
On this website, I'm unable to remove the bold property from the bold text (text starts with "Conforme o art. 43...").

What is most intriguing is that the font-weight command below applies normally to all parts of the referred site, except for the bold part.

I'm using the following code in Stylebot (Chrome Extension):

```<code>    div {
    font-family: Open Sans;
    font-size: 14.49px;
    text-align: justify;
    text-justify: auto;
    font-weight: 300;
}
</code>```

How can I get this done? Thanks in advance!

Body:
On this website, I'm unable to remove the bold property from the bold text (text starts with "Conforme o art. 43...").

What is most intriguing is that the font-weight command below applies normally to all parts of the referred site, except for the bold part.

I'm using the following code in Stylebot (Chrome Extension):

    div {
    font-family: Open Sans;
    font-size: 14.49px;
    text-align: justify;
    text-justify: auto;
    font-weight: 300;
}

How can I get this done? Thanks in advance!

Body:
The text you are referring to ("Conforme o art. 43...") is inside a span tag that has an inline style style="font-weight: bold,".

An inline style like this will override every CSS rule that you define in an external style sheet or in a <style> tag inside the header of your page, so you need to

...either erase this style tag in the HTML code (if it's actually there), or

...if it's not there, it's inserted via javascript. So you need to find out which javascript inserts this code into the HTML code and erase or deactivate that code.

EDIT / Additional note: The code of the answer which you just accepted will apply that CSS rule either to all direct children elements of any div or (second option) even apply it to all  elements in your page. I strongly doubt that you want either of this, since most likely your pages will consist of more than what you showed us...


问:
Programatically create form with trigger disabled automatically
TL;DR: How to programmatically create a form with a trigger that doesn't get disabled.

```<code>function createdFormTrigger(e) {
  var result = {};
  var responses = e.response.getItemResponses();
  for (var i = 0; i < responses.length; i++) {
      var title = responses[i].getItem().getTitle();
      var response = responses[i].getResponse();
      result[title] = response;
  }
  var db = FirebaseApp.getDatabaseByUrl("https://firebase-livedata.com");
  var form = FormApp.getActiveForm();

  db.pushData(form.getTitle(), result)
}

function onFormSubmit(e) {
  var email = e.response.getRespondentEmail();
  var form = FormApp.create("Form " + e.response.getId())
  form.addEditor(email)
  ScriptApp.newTrigger('createdFormTrigger')
    .forForm(form)
    .onFormSubmit()
    .create();
}
</code>```

I create a form with a trigger (onFormSubmit) that active on form submit. The trigger will programmatically create a new form and assign it with trigger createdFormTrigger. The trigger is created but always get disabled automatically (picture attached), is there a way so it doesn't get disabled automatically?

I've added library needed (Firebase), set scopes ("https://www.googleapis.com/auth/forms" & "https://www.googleapis.com/auth/forms.currentonly"), and made sure that I run a correct form. Can anybody please help me?

答:
The trigger is disabled automatically because the form to which the trigger is attached doesn't include a bounded script project.

One possible to solution is rather than creating a form from scratch make a copy of a form that already has a bounded script project which already include the function to be called by the trigger.

Body:
TL;DR: How to programmatically create a form with a trigger that doesn't get disabled.

function createdFormTrigger(e) {
  var result = {};
  var responses = e.response.getItemResponses();
  for (var i = 0; i < responses.length; i++) {
      var title = responses[i].getItem().getTitle();
      var response = responses[i].getResponse();
      result[title] = response;
  }
  var db = FirebaseApp.getDatabaseByUrl("https://firebase-livedata.com");
  var form = FormApp.getActiveForm();

  db.pushData(form.getTitle(), result)
}

function onFormSubmit(e) {
  var email = e.response.getRespondentEmail();
  var form = FormApp.create("Form " + e.response.getId())
  form.addEditor(email)
  ScriptApp.newTrigger('createdFormTrigger')
    .forForm(form)
    .onFormSubmit()
    .create();
}

I create a form with a trigger (onFormSubmit) that active on form submit. The trigger will programmatically create a new form and assign it with trigger createdFormTrigger. The trigger is created but always get disabled automatically (picture attached), is there a way so it doesn't get disabled automatically?

I've added library needed (Firebase), set scopes ("https://www.googleapis.com/auth/forms" & "https://www.googleapis.com/auth/forms.currentonly"), and made sure that I run a correct form. Can anybody please help me?


问:
how can I find out font size used by best fit in imagemagick

This question is related to http://www.imagemagick.org/Usage/text/#caption_bestfit .

Suppose I am writing a single digit number using font "Comic-Sans-MS-Bold" in 40x40 area so that it occupies maximum space and does not overflow.

Say imagemagick chose font size 'x' .

If I were to write a two digit number using font "Comic-Sans-MS-Bold" in 40x40 area.

Then imagemagick would choose some other font size 'y' .

Is there a debug option or some other method using which I can find out what font size was decided for writing a particular text in specified area .

Actually, I need that font size so that I can specify it explicitly in my tkinter script when I create similiar image using draw text over canvas.

Thanks.

BTW , imagemagick forum is locked .

答:
Here is a better way to do that in ImageMagick.

```<code>convert -size 200x50 -background white -font candice caption:"This Is Some Text" -format "%[caption:pointsize]\n" info:
</code>```

23

Body:
Here is a better way to do that in ImageMagick.

convert -size 200x50 -background white -font candice caption:"This Is Some Text" -format "%[caption:pointsize]\n" info:

23


答:
The problem might be in the way you pass data to np.array. The rows of array should be tuples.

 a = np.array([( 0.9607611 ,  0.19538569,  0.        )], dtype='f8, f8, i4')
```

<p>will create an array</p>

<pre class="lang-py prettyprint-override"><code>array([(0.9607611, 0.19538569, 0)],
      dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<i4')])
</code>```

Title: Ndarray of lists with mix of floats and integers?

Body:
I have an array of lists (corr: N-Dimensional array)

s_cluster_data
Out[410]:
array([[ 0.9607611 ,  0.19538569,  0.        ],
       [ 1.03990463,  0.22274072,  0.        ],
       [ 1.09430461,  0.22603228,  0.        ],
       ...,
       [ 1.10802461, -0.54190659,  2.        ],
       [ 0.9288097 , -0.49195368,  2.        ],
       [ 0.81606986, -0.47141286,  2.        ]])

I would like to make the third column an integer. I've tried to assign dtype as such

dtype=[('A','f8'),('B','f8'),('C','i4')]

s_cluster_data = np.array(s_cluster_data, dtype=dtype)
s_cluster_data

Out[414]:
array([[( 0.9607611 ,  0.9607611 , 0), ( 0.19538569,  0.19538569, 0),
        ( 0.        ,  0.        , 0)],
       [( 1.03990463,  1.03990463, 1), ( 0.22274072,  0.22274072, 0),
        ( 0.        ,  0.        , 0)],
       [( 1.09430461,  1.09430461, 1), ( 0.22603228,  0.22603228, 0),
        ( 0.        ,  0.        , 0)],
       ...,
       dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<i4')])

Which creates an array of lists of tuples (corr: array with dtype), with each index in lists becoming a separate tuple.

I've also tried to take apart the array, read it in as array of tuples, but return back to original state.

list_cluster = s_cluster_data.tolist() # py list
tuple_cluster = [tuple(l) for l in list_cluster] # list of tuples

dtype=[('A','f8'),('B','f8'),('C','i4')]
sd_cluster_data = np.array(tuple_cluster, dtype=dtype) # array of tuples with dtype
sd_cluster_data

Out:   ...,
       (1.0020371 , -0.56034073, 2), (1.18264038, -0.55773913, 2),
       (1.00550194, -0.55359672, 2), (1.10802461, -0.54190659, 2),
       (0.9288097 , -0.49195368, 2), (0.81606986, -0.47141286, 2)],
      dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<i4')])

So ideally the above output is what I would like to see, but with array of lists, not array of tuples.
I tried to take the array apart and merge it back as lists

x_val_arr = np.array([x[0] for x in sd_cluster_data])
y_val_arr = np.array([x[1] for x in sd_cluster_data])
cluster_id_arr = np.array([x[2] for x in sd_cluster_data])

coordinates_arr = np.stack((x_val_arr,y_val_arr,cluster_id_arr),axis=1)

But once again I get floats in the third column

coordinates_arr
Out[416]:
array([[ 0.9607611 ,  0.19538569,  0.        ],
       [ 1.03990463,  0.22274072,  0.        ],
       [ 1.09430461,  0.22603228,  0.        ],
       ...,
       [ 1.10802461, -0.54190659,  2.        ],
       [ 0.9288097 , -0.49195368,  2.        ],
       [ 0.81606986, -0.47141286,  2.        ]])

So this is probably a question due to my lack of domain knowledge, but do ndarrays not support mixed data types if it consists of lists, not tuples?

Body:
The problem might be in the way you pass data to np.array. The rows of array should be tuples.

 a = np.array([( 0.9607611 ,  0.19538569,  0.        )], dtype='f8, f8, i4')

will create an array

array([(0.9607611, 0.19538569, 0)],
      dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<i4')])


问:
Graphics drawstring UTF8 Chinese Characters
Preface:  We sell machines that tell you the quality of the air.  We have a touch screen display that we recently upgraded to support Chinese.  I wrote a C# application that connects to the device serially and attempts to draw the screen so users can connect to their device remotely and control it.  This works great until you put the device into Chinese, then my C# app draws all the symbols as their ASCII equivalent (not Chinese symbols).

I use the Graphics library to do all my drawing, in which I call the DrawString method to draw text on the screen.  I have a picturebox in which I am doing the graphics drawing on.  How do I draw the Chinese correctly?

Code:

```<code>private Bitmap image;
private Color gForeColor;
private Color gBackColor;
private Font gFont;
private int gTextsize;
private int gLineSize;
private StringFormat gTextAlign;

private void Initialize()
{
    gForeColor = Color.Black;
    gTextsize = 14;
    gLineSize = 1;
    gFont = new Font("Microsoft Sans Serif", gTextsize, FontStyle.Regular);
    gTextAlign = new StringFormat();
    gTextAlign.LineAlignment = StringAlignment.Center;
    gTextAlign.Alignment = StringAlignment.Near;
    gTextAlign.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
    image = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
}

private void DrawText(string Text, int X1, int Y1)
{
    using (Graphics g = Graphics.FromImage(image))
    {
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

        SolidBrush sb = new SolidBrush(gForeColor); //Foreground
        SolidBrush bb = new SolidBrush(gBackColor); //Background

        g.DrawString(Text, gFont, sb, X1, Y1, gTextAlign);
        pictureBox1.Invalidate();   //refresh

        gTextAlign.Alignment = StringAlignment.Near;    //horizontal alignment reverts to Left after a text display command is issued
    }
}
</code>```

I tried adding this line
Text = Encoding.UTF8.GetString(Encoding.Default.GetBytes(Text)); To try and decode the text properly but now it prints '??????' instead of the ASCII letters or Chinese symbols.

Example:

English

Chinese

Edit:  It seems the ReadExisting() from the SerialPort was converting all the bytes into '??????'. I stopped using ReadExisting and switched to Read which keeps the raw bytes. So now I'm getting the correct ASCII, but still not Chinese. I re-added my line Text = Encoding.UTF8.GetString(Encoding.Default.GetBytes(Text)); and now I'm getting Chinese with some extra symbols that aren't correct. Am I using the wrong encoding?

答: Are you sure, that you can use Microsoft Sans Serif with Chinese? I highly doubt.

Body:
Preface:  We sell machines that tell you the quality of the air.  We have a touch screen display that we recently upgraded to support Chinese.  I wrote a C# application that connects to the device serially and attempts to draw the screen so users can connect to their device remotely and control it.  This works great until you put the device into Chinese, then my C# app draws all the symbols as their ASCII equivalent (not Chinese symbols).

I use the Graphics library to do all my drawing, in which I call the DrawString method to draw text on the screen.  I have a picturebox in which I am doing the graphics drawing on.  How do I draw the Chinese correctly?

Code:

private Bitmap image;
private Color gForeColor;
private Color gBackColor;
private Font gFont;
private int gTextsize;
private int gLineSize;
private StringFormat gTextAlign;

private void Initialize()
{
    gForeColor = Color.Black;
    gTextsize = 14;
    gLineSize = 1;
    gFont = new Font("Microsoft Sans Serif", gTextsize, FontStyle.Regular);
    gTextAlign = new StringFormat();
    gTextAlign.LineAlignment = StringAlignment.Center;
    gTextAlign.Alignment = StringAlignment.Near;
    gTextAlign.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
    image = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
}

private void DrawText(string Text, int X1, int Y1)
{
    using (Graphics g = Graphics.FromImage(image))
    {
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

        SolidBrush sb = new SolidBrush(gForeColor); //Foreground
        SolidBrush bb = new SolidBrush(gBackColor); //Background

        g.DrawString(Text, gFont, sb, X1, Y1, gTextAlign);
        pictureBox1.Invalidate();   //refresh

        gTextAlign.Alignment = StringAlignment.Near;    //horizontal alignment reverts to Left after a text display command is issued
    }
}

I tried adding this line
Text = Encoding.UTF8.GetString(Encoding.Default.GetBytes(Text)); To try and decode the text properly but now it prints '??????' instead of the ASCII letters or Chinese symbols.

Example:

English

Chinese

Edit:  It seems the ReadExisting() from the SerialPort was converting all the bytes into '??????'. I stopped using ReadExisting and switched to Read which keeps the raw bytes. So now I'm getting the correct ASCII, but still not Chinese. I re-added my line Text = Encoding.UTF8.GetString(Encoding.Default.GetBytes(Text)); and now I'm getting Chinese with some extra symbols that aren't correct. Am I using the wrong encoding?


问:
'firebase/main.dart': Failed assertion
I have made a simple baby names project using firebase on flutter,
after successfully going throught the tutorial, the app gives this error : " package:firebase_demo/main.dart': Failed assertion: line 86 pos 16: 'map['votes] ! = null': is not true. "

Help for the same.

MY CODE -:

```<code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

final dummySnapshot = [
  {"name": "Filip", "votes": 15},
  {"name": "Abraham", "votes": 14},
  {"name": "Richard", "votes": 11},
  {"name": "Ike", "votes": 10},
  {"name": "Justin", "votes": 1},
];

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Baby Names',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() {
    return _MyHomePageState();
  }
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Baby Name Votes')),
      body: _buildBody(context),
    );
  }

  Widget _buildBody(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('baby').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return LinearProgressIndicator();

        return _buildList(context, snapshot.data.documents);
      },
    );
  }

  Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot)  {
    return ListView(
      padding: const EdgeInsets.only(top: 20.0),
      children: snapshot.map((data) => _buildListItem(context, data)).toList(),
    );
  }

  Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
    final record = Record.fromSnapshot(data);

    return Padding(
      key: ValueKey(record.name),
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.circular(5.0),
        ),
        child: ListTile(
          title: Text(record.name),
          trailing: Text(record.votes.toString()),
          onTap: () => print(record),
        ),
      ),
    );
  }
}

class Record {
  final String name;
  final int votes;
  final DocumentReference reference;

  Record.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        assert(map['votes'] != null),
        name = map['name'],
        votes = map['votes'];

  Record.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);

  @override
  String toString() => "Record<$name:$votes>";
}
</code>```

Output :

Performing hot restart...
Syncing files to device Redmi Note 4...
Restarted application in 1,994ms.
I/flutter ( 2257): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 2257): The following assertion was thrown building StreamBuilder(dirty, state:
I/flutter ( 2257): _StreamBuilderBaseState>#94c3a):
I/flutter ( 2257): 'package:firebase_demo/main.dart': Failed assertion: line 86 pos 16: 'map['votes'] != null': is not
I/flutter ( 2257): true.
I/flutter ( 2257):
I/flutter ( 2257): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 2257): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 2257): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 2257):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 2257):
I/flutter ( 2257): When the exception was thrown, this was the stack:
I/flutter ( 2257): #2      new Record.fromMap (package:firebase_demo/main.dart:86:16)
I/flutter ( 2257): #3      new Record.fromSnapshot (package:firebase_demo/main.dart:91:14)
I/flutter ( 2257): #4      _MyHomePageState._buildListItem (package:firebase_demo/main.dart:59:27)
I/flutter ( 2257): #5      _MyHomePageState._buildList. (package:firebase_demo/main.dart:54:40)
I/flutter ( 2257): #6      MappedListIterable.elementAt (dart:_internal/iterable.dart:414:29)
I/flutter ( 2257): #7      ListIterable.toList (dart:_internal/iterable.dart:219:19)
I/flutter ( 2257): #8      _MyHomePageState._buildList (package:firebase_demo/main.dart:54:71)
I/flutter ( 2257): #9      _MyHomePageState._buildBody. (package:firebase_demo/main.dart:46:16)
I/flutter ( 2257): #10     StreamBuilder.build (package:flutter/src/widgets/async.dart:423:74)
I/flutter ( 2257): #11     _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:125:48)
I/flutter ( 2257): #12     StatefulElement.build (package:flutter/src/widgets/framework.dart:3809:27)
I/flutter ( 2257): #13     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3721:15)
I/flutter ( 2257): #14     Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 2257): #15     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2286:33)
I/flutter ( 2257): #16     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:676:20)
I/flutter ( 2257): #17     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:219:5)
I/flutter ( 2257): #18     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
I/flutter ( 2257): #19     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
I/flutter ( 2257): #20     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
I/flutter ( 2257): #21     _invoke (dart:ui/hooks.dart:154:13)
I/flutter ( 2257): #22     _drawFrame (dart:ui/hooks.dart:143:3)
I/flutter ( 2257): (elided 2 frames from class _AssertionError)
I/flutter ( 2257): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/1.gpu   ( 2257): type=1400 audit(0.0:191179): avc: denied { ioctl } for path="/dev/kgsl-3d0" dev="tmpfs" ino=15394 ioctlcmd=945 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:device:s0 tclass=chr_file permissive=1
I/1.gpu   ( 2257): type=1400 audit(0.0:191180): avc: denied { read write } for path="/dev/kgsl-3d0" dev="tmpfs" ino=15394 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:device:s0 tclass=chr_file permissive=1
I/an.firebasedem( 2257): Waiting for a blocking GC ProfileSaver
I/an.firebasedem( 2257): WaitForGcToComplete blocked ProfileSaver on ProfileSaver for 30.771ms

答:
Make sure your fields in the Firebase match with the proprieties of Record.

e.g:
name matches name field from the database
votes matches votes field from the database

Title: 'firebase/main.dart': Failed assertion

Body:
I have made a simple baby names project using firebase on flutter,
after successfully going throught the tutorial, the app gives this error : " package:firebase_demo/main.dart': Failed assertion: line 86 pos 16: 'map['votes] ! = null': is not true. "

Help for the same.

MY CODE -:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

final dummySnapshot = [
  {"name": "Filip", "votes": 15},
  {"name": "Abraham", "votes": 14},
  {"name": "Richard", "votes": 11},
  {"name": "Ike", "votes": 10},
  {"name": "Justin", "votes": 1},
];

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Baby Names',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() {
    return _MyHomePageState();
  }
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Baby Name Votes')),
      body: _buildBody(context),
    );
  }

  Widget _buildBody(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('baby').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return LinearProgressIndicator();

        return _buildList(context, snapshot.data.documents);
      },
    );
  }

  Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot)  {
    return ListView(
      padding: const EdgeInsets.only(top: 20.0),
      children: snapshot.map((data) => _buildListItem(context, data)).toList(),
    );
  }

  Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
    final record = Record.fromSnapshot(data);

    return Padding(
      key: ValueKey(record.name),
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.circular(5.0),
        ),
        child: ListTile(
          title: Text(record.name),
          trailing: Text(record.votes.toString()),
          onTap: () => print(record),
        ),
      ),
    );
  }
}

class Record {
  final String name;
  final int votes;
  final DocumentReference reference;

  Record.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        assert(map['votes'] != null),
        name = map['name'],
        votes = map['votes'];

  Record.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);

  @override
  String toString() => "Record<$name:$votes>";
}

Output :

Performing hot restart...
Syncing files to device Redmi Note 4...
Restarted application in 1,994ms.
I/flutter ( 2257): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 2257): The following assertion was thrown building StreamBuilder(dirty, state:
I/flutter ( 2257): _StreamBuilderBaseState>#94c3a):
I/flutter ( 2257): 'package:firebase_demo/main.dart': Failed assertion: line 86 pos 16: 'map['votes'] != null': is not
I/flutter ( 2257): true.
I/flutter ( 2257):
I/flutter ( 2257): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 2257): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 2257): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 2257):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 2257):
I/flutter ( 2257): When the exception was thrown, this was the stack:
I/flutter ( 2257): #2      new Record.fromMap (package:firebase_demo/main.dart:86:16)
I/flutter ( 2257): #3      new Record.fromSnapshot (package:firebase_demo/main.dart:91:14)
I/flutter ( 2257): #4      _MyHomePageState._buildListItem (package:firebase_demo/main.dart:59:27)
I/flutter ( 2257): #5      _MyHomePageState._buildList. (package:firebase_demo/main.dart:54:40)
I/flutter ( 2257): #6      MappedListIterable.elementAt (dart:_internal/iterable.dart:414:29)
I/flutter ( 2257): #7      ListIterable.toList (dart:_internal/iterable.dart:219:19)
I/flutter ( 2257): #8      _MyHomePageState._buildList (package:firebase_demo/main.dart:54:71)
I/flutter ( 2257): #9      _MyHomePageState._buildBody. (package:firebase_demo/main.dart:46:16)
I/flutter ( 2257): #10     StreamBuilder.build (package:flutter/src/widgets/async.dart:423:74)
I/flutter ( 2257): #11     _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:125:48)
I/flutter ( 2257): #12     StatefulElement.build (package:flutter/src/widgets/framework.dart:3809:27)
I/flutter ( 2257): #13     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3721:15)
I/flutter ( 2257): #14     Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 2257): #15     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2286:33)
I/flutter ( 2257): #16     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:676:20)
I/flutter ( 2257): #17     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:219:5)
I/flutter ( 2257): #18     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
I/flutter ( 2257): #19     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
I/flutter ( 2257): #20     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
I/flutter ( 2257): #21     _invoke (dart:ui/hooks.dart:154:13)
I/flutter ( 2257): #22     _drawFrame (dart:ui/hooks.dart:143:3)
I/flutter ( 2257): (elided 2 frames from class _AssertionError)
I/flutter ( 2257): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/1.gpu   ( 2257): type=1400 audit(0.0:191179): avc: denied { ioctl } for path="/dev/kgsl-3d0" dev="tmpfs" ino=15394 ioctlcmd=945 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:device:s0 tclass=chr_file permissive=1
I/1.gpu   ( 2257): type=1400 audit(0.0:191180): avc: denied { read write } for path="/dev/kgsl-3d0" dev="tmpfs" ino=15394 scontext=u:r:untrusted_app_27:s0:c512,c768 tcontext=u:object_r:device:s0 tclass=chr_file permissive=1
I/an.firebasedem( 2257): Waiting for a blocking GC ProfileSaver
I/an.firebasedem( 2257): WaitForGcToComplete blocked ProfileSaver on ProfileSaver for 30.771ms


问:
Why jQuery click event listener isn't registered on WooCommerce button?
I have a WooCommerce based shop, and I am trying to implement some event tracking based on user actions.
I would like to run a custom JS function when the user clicks on the Place order button, which is the final step before paying.

This is the code of the button:

```<code><button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="Place order" data-value="Place order">Place order</button>
</code>```

In my script I have this:

```<code>jQuery(document).ready(function ($) {
  // here are some other handlers

  $("#place_order").click(() => {
    alert("click");
  });
});
</code>```

When I log the result of $("#place_order"), it seems jQuery can find the element:

```<code>a.fn.init [button#place_order.button.alt, context: document, selector: "#place_order"]
</code>```

But in the devtools window of google chrome, there's no click handler for this button (under the Event Listeners tab) and the function is not ran.

I have other click events wired up in the very same document.ready function, in a similar way, which works just fine.

Add to cart button:

```<code><button type="submit" name="add-to-cart" value="2819" class="single_add_to_cart_button button alt">Add to cart</button>
</code>```

script:

```<code>$("button[name=add-to-cart]").on("click", () => {
  console.log("product added to cart"); // This works fine and visible under Event Listeners tab
});
</code>```

I've tried using the selector "button[name=woocommerce_checkout_place_order]" and with .on("click") too.

So what could be the reason my event listener for the place order button is not getting added, or is getting removed?

Is there a way I can check if handlers are removed from the button by other scripts? I'm thinking maybe WooCommerce removes it for some reason.

答:
As for checkout "place order" submit event is delegated to the <form> by WooCommerce, you will need to delegate the click event to the <form> too this way:

```<code>jQuery(function($){
    $('form.woocommerce-checkout').on( 'click', "#place_order", function(event){
        event.preventDefault(); // Disable submit for testing

        console.log("click");
        alert("click");
    });
});
</code>```

Or the same thing embedded in a function (targeting checkout page):

```<code>add_action('wp_footer', 'my_checkout_js_script');
function my_checkout_js_script() {
    // Only on checkout page
    if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script type='text/javascript'>
        jQuery(function($){
            $('form.woocommerce-checkout').on( 'click', "#place_order", function(event){
                event.preventDefault(); // Disable submit for testing

                console.log("click");
                alert("click");
            });
        });
    </script>
    <?php
    endif;
}
</code>```

Code goes in functions.php file of your active child theme (or active theme).

Now as you will see it works.

Related: jQuery - Understanding Event Delegation

Body:
I have a WooCommerce based shop, and I am trying to implement some event tracking based on user actions.
I would like to run a custom JS function when the user clicks on the Place order button, which is the final step before paying.

This is the code of the button:

<button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="Place order" data-value="Place order">Place order</button>

In my script I have this:

jQuery(document).ready(function ($) {
  // here are some other handlers

  $("#place_order").click(() => {
    alert("click");
  });
});

When I log the result of $("#place_order"), it seems jQuery can find the element:

a.fn.init [button#place_order.button.alt, context: document, selector: "#place_order"]

But in the devtools window of google chrome, there's no click handler for this button (under the Event Listeners tab) and the function is not ran.

I have other click events wired up in the very same document.ready function, in a similar way, which works just fine.

Add to cart button:

<button type="submit" name="add-to-cart" value="2819" class="single_add_to_cart_button button alt">Add to cart</button>

script:

$("button[name=add-to-cart]").on("click", () => {
  console.log("product added to cart"); // This works fine and visible under Event Listeners tab
});

I've tried using the selector "button[name=woocommerce_checkout_place_order]" and with .on("click") too.

So what could be the reason my event listener for the place order button is not getting added, or is getting removed?

Is there a way I can check if handlers are removed from the button by other scripts? I'm thinking maybe WooCommerce removes it for some reason.

Body:
As for checkout "place order" submit event is delegated to the <form> by WooCommerce, you will need to delegate the click event to the <form> too this way:

jQuery(function($){
    $('form.woocommerce-checkout').on( 'click', "#place_order", function(event){
        event.preventDefault(); // Disable submit for testing

        console.log("click");
        alert("click");
    });
});

Or the same thing embedded in a function (targeting checkout page):

add_action('wp_footer', 'my_checkout_js_script');
function my_checkout_js_script() {
    // Only on checkout page
    if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script type='text/javascript'>
        jQuery(function($){
            $('form.woocommerce-checkout').on( 'click', "#place_order", function(event){
                event.preventDefault(); // Disable submit for testing

                console.log("click");
                alert("click");
            });
        });
    </script>
    <?php
    endif;
}

Code goes in functions.php file of your active child theme (or active theme).

Now as you will see it works.

Related: jQuery - Understanding Event Delegation


问:
Problem with rails + json
my controller admin

```<code>  def index_all_for_question_id

      @answers      = Question.find(params[:id]).answers

    respond_to do |format|
      format.ext_json { render :json => @answers.to_ext_json(:class => Answer, :include => [:respondent]) }
    end
  end
</code>```

my dataStore in extJS

```<code> var answers_datastore = new Ext.data.Store({
    autoLoad: true,
    proxy: new Ext.data.HttpProxy({
       url: '/answers/index_all_for_question_id/<%= @questions.first.id %>?format=ext_json',
        method: 'GET'}),
        reader: answers_reader
        });
</code>```

My question is: When i trying to enter
localhost:3000/answers/index_all_for_question_id/551?format=ext_json for example,

I get :

{"results":2,"answers":[{"answer":{"scale":1,"inquiry_id":277,"created_at":"2011-05-30T07:10:22Z","updated_at":"2011-05-30T07:10:22Z","text":"dfgfdghfdhfdh","id":275,"respondent":{"created_at":"2011-05-16T06:47:08Z","updated_at":"2011-05-16T06:47:08Z","id":109,"user_id":6,"email":"xxx@xxx"}}},{"answer":{"scale":1,"inquiry_id":278,"created_at":"2011-05-31T12:33:36Z","updated_at":"2011-05-31T12:33:36Z","text":"lolololol","id":290,"respondent":{"created_at":"2011-05-25T11:22:55Z","updated_at":"2011-05-25T11:22:55Z","id":110,"user_id":6,"email":"xxx@xxx"}}}]}

SO i dont what it! Every user can enter this line i get answers (if he not an admin). How i can solve this problem? Only admins can see this, for others should be redirect on some page or appears text "Sorry!".

Thank you

答:
I'd use HTTP authentication. Redirect is a bit tricky to implement, here's an example (using sessions):</p>

```<code>class AdminController < ApplicationController
  before_filter :authenticate

  USER_NAME = "admin"
  PASSWORD = "xyz" # PS: you should use hashed passwords

  def admins_only
    render :text => "TOP SECRET STUFF!"
  end

  protected

  def authenticate
    if authenticate_with_http_basic { |u,p| u == USER_NAME && p == PASSWORD }
      true
    else
      if session[:http_auth_requested]
        session[:http_auth_requested] = nil
        redirect_to '/sorry_page' and return false
      end

      session[:http_auth_requested] = 1
      request_http_basic_authentication
    end
  end
end
</code>```

Title: Problem with rails + json

Body:
my controller admin

  def index_all_for_question_id

      @answers      = Question.find(params[:id]).answers

    respond_to do |format|
      format.ext_json { render :json => @answers.to_ext_json(:class => Answer, :include => [:respondent]) }
    end
  end

my dataStore in extJS

 var answers_datastore = new Ext.data.Store({
    autoLoad: true,
    proxy: new Ext.data.HttpProxy({
       url: '/answers/index_all_for_question_id/<%= @questions.first.id %>?format=ext_json',
        method: 'GET'}),
        reader: answers_reader
        });

My question is: When i trying to enter
localhost:3000/answers/index_all_for_question_id/551?format=ext_json for example,

I get :

{"results":2,"answers":[{"answer":{"scale":1,"inquiry_id":277,"created_at":"2011-05-30T07:10:22Z","updated_at":"2011-05-30T07:10:22Z","text":"dfgfdghfdhfdh","id":275,"respondent":{"created_at":"2011-05-16T06:47:08Z","updated_at":"2011-05-16T06:47:08Z","id":109,"user_id":6,"email":"xxx@xxx"}}},{"answer":{"scale":1,"inquiry_id":278,"created_at":"2011-05-31T12:33:36Z","updated_at":"2011-05-31T12:33:36Z","text":"lolololol","id":290,"respondent":{"created_at":"2011-05-25T11:22:55Z","updated_at":"2011-05-25T11:22:55Z","id":110,"user_id":6,"email":"xxx@xxx"}}}]}

SO i dont what it! Every user can enter this line i get answers (if he not an admin). How i can solve this problem? Only admins can see this, for others should be redirect on some page or appears text "Sorry!".

Thank you

Body:
I'd use HTTP authentication. Redirect is a bit tricky to implement, here's an example (using sessions):

class AdminController < ApplicationController
  before_filter :authenticate

  USER_NAME = "admin"
  PASSWORD = "xyz" # PS: you should use hashed passwords

  def admins_only
    render :text => "TOP SECRET STUFF!"
  end

  protected

  def authenticate
    if authenticate_with_http_basic { |u,p| u == USER_NAME && p == PASSWORD }
      true
    else
      if session[:http_auth_requested]
        session[:http_auth_requested] = nil
        redirect_to '/sorry_page' and return false
      end

      session[:http_auth_requested] = 1
      request_http_basic_authentication
    end
  end
end


问:
Why does "delete" operator giving me Access violation
```<code>#include <iostream>

using namespace std;

int *res=new int[0];

int res_size;

void multiply(int y);

void factorial(int x)

{

    res[0]=1;
    res_size=1;
    for (int i=2;i<=x;i++)
        multiply(i);
    for (int i=res_size-1;i>=0;i--)
        cout << res[i];
}

void multiply(int y)

{

    static int prod=1;
    int carry=0;
    for (int i=0;i<res_size;i++)
    {
        prod=res[i]*y+(carry);
        res[i]=prod%10;
        carry=prod/10;
    }
    while (carry)
    {
        res[res_size]=carry%10;
        carry=carry/10;
        res_size++;
    }
}

int main()

{

    int n;
    cout << "Enter a number" << endl;
    cin >> n;
    factorial(n);
    delete[] res;
    return 0;
}
</code>```

<p>When I am using delete[] operator why I am getting </p>

```<code>Access violation reading location at address
</code>```

答:
You allocated an array with zero elements

```<code>int *res=new int[0];
</code>```

You may not write to such an array as you are doing

```<code>res[0]=1;
</code>```

The program has undefined behavior.

Instead of the dynamically allocated array you could use the class template std::vector. In this case you could use the method push_back to add elements to the vector.

Body:
#include <iostream>

using namespace std;

int *res=new int[0];

int res_size;

void multiply(int y);

void factorial(int x)

{

    res[0]=1;
    res_size=1;
    for (int i=2;i<=x;i++)
        multiply(i);
    for (int i=res_size-1;i>=0;i--)
        cout << res[i];
}

void multiply(int y)

{

    static int prod=1;
    int carry=0;
    for (int i=0;i<res_size;i++)
    {
        prod=res[i]*y+(carry);
        res[i]=prod%10;
        carry=prod/10;
    }
    while (carry)
    {
        res[res_size]=carry%10;
        carry=carry/10;
        res_size++;
    }
}

int main()

{

    int n;
    cout << "Enter a number" << endl;
    cin >> n;
    factorial(n);
    delete[] res;
    return 0;
}

When I am using delete[] operator why I am getting

Access violation reading location at address

Body:
You allocated an array with zero elements

int *res=new int[0];

You may not write to such an array as you are doing

res[0]=1;

The program has undefined behavior.

Instead of the dynamically allocated array you could use the class template std::vector. In this case you could use the method push_back to add elements to the vector.


问:
Specifying that model is logit transformed to plot backtransformed trends
I have fitted a lme model in R with a logit transformed response. I have not been able to find a direct command that does the logit transformation so I have done it manually.

```<code>logitr<-log(r/1-r)
</code>```

I then use this as response in my lme model with interaction between two factors and a numerical variable.

```<code>model<-lme(logitr<-factor1*factor2*numeric,random=1|random)
</code>```

Now, R obviously do not know that this model is logit transformed. How can I specify this to R?

I have without luck tried:

```<code>update(model, tran="logit")
</code>```

The reason why I want to specify that the model is logit transformed is because I want to plot the backtransformed results using the function emmip in the emmeans package, showing the trends of the interaction between my variables.

Normally (if I only had factors) I would just use:

```<code>update_refgrid_model<-update(ref_grid(model, tran="logit"))
</code>```

But this approach does not work when I want to use emmip to plot the trends of the interaction between a numerical variable and factors. If I specify:

```<code>emmip(update_refgrid_model, factor1~numeric|factor2, cov.reduce = range, type = "response")
</code>```

then I do not get any trends plotted, only the estimate for the average level on the numerical variable.

So, how can I specify the logit transformation and plot the backtransformed trends of a lme model with factors interacting with numerical variables?

答:
You don't update the model object, you update the reference grid:

```<code>rg = update(ref_grid(model, cov.reduce = range), tran = "logit")
emmip(rg, factor1~numeric|factor2, type = "response")
</code>```

It is possible to update a model with other things, just not the transformation; that is in the update method for emmGrid objects.

Update

Here's an example showing how it works

require(emmeans)
## Loading required package: emmeans

foo = transform(fiber, p = (strength - 25)/25)
foo.lm = lm(log(p/(1-p)) ~ machine*diameter, data = foo)

emm = emmeans(foo.lm, ~diameter|machine,
              tran = "logit", at = list(diameter = 15:32))
## Warning in ref_grid(object, ...): There are unevaluated constants in the response formula
## Auto-detection of the response transformation may be incorrect

emmip(emm, machine ~ diameter)
```

<p><img src="https://i.imgur.com/FImvjEu.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code>emmip(emm, machine ~ diameter, type = "r")
</code>```

Created on 2020-06-02 by the reprex package (v0.3.0)

Body:
I have fitted a lme model in R with a logit transformed response. I have not been able to find a direct command that does the logit transformation so I have done it manually.

logitr<-log(r/1-r)

I then use this as response in my lme model with interaction between two factors and a numerical variable.

model<-lme(logitr<-factor1*factor2*numeric,random=1|random)

Now, R obviously do not know that this model is logit transformed. How can I specify this to R?

I have without luck tried:

update(model, tran="logit")

The reason why I want to specify that the model is logit transformed is because I want to plot the backtransformed results using the function emmip in the emmeans package, showing the trends of the interaction between my variables.

Normally (if I only had factors) I would just use:

update_refgrid_model<-update(ref_grid(model, tran="logit"))

But this approach does not work when I want to use emmip to plot the trends of the interaction between a numerical variable and factors. If I specify:

emmip(update_refgrid_model, factor1~numeric|factor2, cov.reduce = range, type = "response")

then I do not get any trends plotted, only the estimate for the average level on the numerical variable.

So, how can I specify the logit transformation and plot the backtransformed trends of a lme model with factors interacting with numerical variables?

Body:
You don't update the model object, you update the reference grid:

rg = update(ref_grid(model, cov.reduce = range), tran = "logit")
emmip(rg, factor1~numeric|factor2, type = "response")

It is possible to update a model with other things, just not the transformation; that is in the update method for emmGrid objects.

Update

Here's an example showing how it works

require(emmeans)
## Loading required package: emmeans

foo = transform(fiber, p = (strength - 25)/25)
foo.lm = lm(log(p/(1-p)) ~ machine*diameter, data = foo)

emm = emmeans(foo.lm, ~diameter|machine,
              tran = "logit", at = list(diameter = 15:32))
## Warning in ref_grid(object, ...): There are unevaluated constants in the response formula
## Auto-detection of the response transformation may be incorrect

emmip(emm, machine ~ diameter)

emmip(emm, machine ~ diameter, type = "r")

Created on 2020-06-02 by the reprex package (v0.3.0)


问:
Why dosen't setting the className style the React element
I have been trying to add style element to my React, when I would do the following, the style does not show up:

```<code><body>
  <div id="root">
    <script src="https://unpkg.com/react@16.7.0/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.7.0/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone@7.8.3/babel.js"></script>
    <style>
      .box {
        border: 1px solid black;
        display: flex;
        flex-direction: column;
        justify-content: center;
        text-align: center;
      }

      .box--large {
        width: 270px;
        height: 270px;
      }

      .box--medium {
        width: 180px;
        height: 180px;
      }

      .box--small {
        width: 90px;
        height: 90px;
      }
    </style>
    <script type="text/babel">
      const rootElement = document.getElementById("root");
      const element = (
        <div>
        <div className="box box--small">small lightblue box</div>
      </div>
        );
      ReactDOM.render(element, rootElement);
    </script>
</body>

</code>```

But, when I change the code to the following, it works:

```<code><body>
  <div id="root">
    <script src="https://unpkg.com/react@16.7.0/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.7.0/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone@7.8.3/babel.js"></script>
    <script type="text/babel">
      const rootElement = document.getElementById("root");
      const element = (
       <div>
        <div className="box box--small" style={{fontStyle: 'italic',backgroundColor: 'lightblue',width: "90px",height: "90px"}}>small lightblue box</div>
      </div>
        );
      ReactDOM.render(element, rootElement);
    </script>
</body>

</code>```

Essentially, moving the style to the div element when I declare it adds the styling. I understand why the second one works, but why dosen't the first one work?

答:
The reason your css is not applied to the element is not becuase your class is not applied to the element but because your css is removed from the page.
You see you added all your scripts and also your styles into the
 that is used to render your react app. React replaces the contents of that div which removes your styles in your first example.

The second example worked because react rendered the style itself and didn't rely on the stylesheet.

(Just FYI and I'm sure you know this through various tutorials but react is not usually rendered and transpiled in the browser)

Try this:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Your react app</title>
    <script src="https://unpkg.com/react@16.7.0/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.7.0/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone@7.8.3/babel.js"></script>
    <style>
        .box {
            border: 1px solid black;
            display: flex;
            flex-direction: column;
            justify-content: center;
            text-align: center;
        }

        .box--large {
            width: 270px;
            height: 270px;
        }

        .box--medium {
            width: 180px;
            height: 180px;
        }

        .box--small {
            width: 90px;
            height: 90px;
        }
    </style>
</head>
<body>

    <div id="root"></div>

    <script type="text/babel">
        const rootElement = document.getElementById("root");
        const element = (
            <div>
            <div className="box box--small">small lightblue box</div>
        </div>
            );
        ReactDOM.render(element, rootElement);
    </script>
</body>
</html>
</code>```

Body:
I have been trying to add style element to my React, when I would do the following, the style does not show up:

But, when I change the code to the following, it works:

Essentially, moving the style to the div element when I declare it adds the styling. I understand why the second one works, but why dosen't the first one work?

Body:
The reason your css is not applied to the element is not becuase your class is not applied to the element but because your css is removed from the page.
You see you added all your scripts and also your styles into the <div> that is used to render your react app. React replaces the contents of that div which removes your styles in your first example.

The second example worked because react rendered the style itself and didn't rely on the stylesheet.

(Just FYI and I'm sure you know this through various tutorials but react is not usually rendered and transpiled in the browser)

Try this:

<!DOCTYPE html>
<html>
<head>
    <title>Your react app</title>
    <script src="https://unpkg.com/react@16.7.0/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.7.0/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone@7.8.3/babel.js"></script>
    <style>
        .box {
            border: 1px solid black;
            display: flex;
            flex-direction: column;
            justify-content: center;
            text-align: center;
        }

        .box--large {
            width: 270px;
            height: 270px;
        }

        .box--medium {
            width: 180px;
            height: 180px;
        }

        .box--small {
            width: 90px;
            height: 90px;
        }
    </style>
</head>
<body>

    <div id="root"></div>

    <script type="text/babel">
        const rootElement = document.getElementById("root");
        const element = (
            <div>
            <div className="box box--small">small lightblue box</div>
        </div>
            );
        ReactDOM.render(element, rootElement);
    </script>
</body>
</html>


问:
AWS - boto3 EC2 start/stop - automation
I prepared lambda function, I am using python boto3 module, code below. Now I am facing error message "errorMessage": "start_instances() only accepts keyword arguments.". What could be the problem, I was using this automation, and for two weeks I am facing this error.

```<code>import boto3
def lambda_handler(event, context):
    client = boto3.client('ec2')
    ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
    for region in ec2_regions:
        ec2 = boto3.resource('ec2',region_name=region)
        instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
        StoppedInstances = [instance.id for instance in instances]
        for i in StoppedInstances:
            startingInstances = ec2.instances.start(i)
            print(startingInstances)
            print(ec2_regions)
</code>```

Updated version

```<code>import boto3
def lambda_handler(event, context):
    client = boto3.client('ec2')
    #region = 'eu-west-1'
    ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
    for region in ec2_regions:
        ec2 = boto3.resource('ec2',region_name=region)
        instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
        StoppedInstances = [instance.id for instance in instances]
        print(StoppedInstances)
        print(ec2_regions)
        client.start_instances(InstanceIds=StoppedInstances)
</code>```

Lambda role config

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ec2:DescribeInstances",
                "ec2:StartInstances",
                "ec2:StopInstances",
                "ec2:DescribeRegions",
                "ec2:DescribeInstanceStatus"
            ],
            "Resource": "*"
        }
    ]
}
</code>```

Corrected and working code below:

```<code>import boto3
def lambda_handler(event, context):
    client = boto3.client('ec2')
    #region = 'eu-west-1'
    ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
    for region in ec2_regions:
        client = boto3.client('ec2',region_name=region)
        ec2 = boto3.resource('ec2',region_name=region)
        instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
        StoppedInstances = [instance.id for instance in instances]
        for i in StoppedInstances:
            client.start_instances(InstanceIds=[i])
</code>```

答:
I think you could try the following.

Instead

```<code>for i in StoppedInstances:
    startingInstances = ec2.instances.start(i)
</code>```

Can use start_instances:

```<code>client.start_instances(InstanceIds=StoppedInstances)
</code>```

Title: AWS - boto3 EC2 start/stop - automation

Body:
I prepared lambda function, I am using python boto3 module, code below. Now I am facing error message "errorMessage": "start_instances() only accepts keyword arguments.". What could be the problem, I was using this automation, and for two weeks I am facing this error.

import boto3
def lambda_handler(event, context):
    client = boto3.client('ec2')
    ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
    for region in ec2_regions:
        ec2 = boto3.resource('ec2',region_name=region)
        instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
        StoppedInstances = [instance.id for instance in instances]
        for i in StoppedInstances:
            startingInstances = ec2.instances.start(i)
            print(startingInstances)
            print(ec2_regions)

Updated version

import boto3
def lambda_handler(event, context):
    client = boto3.client('ec2')
    #region = 'eu-west-1'
    ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
    for region in ec2_regions:
        ec2 = boto3.resource('ec2',region_name=region)
        instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
        StoppedInstances = [instance.id for instance in instances]
        print(StoppedInstances)
        print(ec2_regions)
        client.start_instances(InstanceIds=StoppedInstances)

Lambda role config

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ec2:DescribeInstances",
                "ec2:StartInstances",
                "ec2:StopInstances",
                "ec2:DescribeRegions",
                "ec2:DescribeInstanceStatus"
            ],
            "Resource": "*"
        }
    ]
}

Corrected and working code below:

import boto3
def lambda_handler(event, context):
    client = boto3.client('ec2')
    #region = 'eu-west-1'
    ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
    for region in ec2_regions:
        client = boto3.client('ec2',region_name=region)
        ec2 = boto3.resource('ec2',region_name=region)
        instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
        StoppedInstances = [instance.id for instance in instances]
        for i in StoppedInstances:
            client.start_instances(InstanceIds=[i])

Body:
I think you could try the following.

Instead

for i in StoppedInstances:
    startingInstances = ec2.instances.start(i)

Can use start_instances:

client.start_instances(InstanceIds=StoppedInstances)


问:
Is the emmeans (R) intercept-only function broken?
I've noticed that emmeans (in R) isn't working for an intercept-only estimate after the latest update.

Reproducible example:

```<code>test=lm(mpg~1,mtcars)
library(emmeans)
emmeans::emmeans(test,~1)
</code>```

The output on 2 of my machines (windows and Linux) is:

```<code>> emmeans::emmeans(test,~1)
Error in `[[<-.data.frame`(`*tmp*`, ".wgt.", value = 2) :
  replacement has 1 row, data has 0
</code>```

Is this a known issue, or have I messed up my system somehow?
This used to work I believe.

It does work if you include a variable:

```<code>test2=lm(mpg~as.factor(cyl),mtcars)
emmeans(test2,~cyl)
</code>```

Thanks very much for the help in advance.

答:
It is working fine with emmeans - 1.4.6 on macOS Catalina 10.15.4 and R 4.0

```<code>emmeans::emmeans(test,~1)
# 1       emmean   SE df lower.CL upper.CL
# overall   20.1 1.07 31     17.9     22.3

#Confidence level used: 0.95
</code>```

Body:
I've noticed that emmeans (in R) isn't working for an intercept-only estimate after the latest update.

Reproducible example:

test=lm(mpg~1,mtcars)
library(emmeans)
emmeans::emmeans(test,~1)

The output on 2 of my machines (windows and Linux) is:

> emmeans::emmeans(test,~1)
Error in `[[<-.data.frame`(`*tmp*`, ".wgt.", value = 2) :
  replacement has 1 row, data has 0

Is this a known issue, or have I messed up my system somehow?
This used to work I believe.

It does work if you include a variable:

test2=lm(mpg~as.factor(cyl),mtcars)
emmeans(test2,~cyl)

Thanks very much for the help in advance.

Body:
It is working fine with emmeans - 1.4.6 on macOS Catalina 10.15.4 and R 4.0

emmeans::emmeans(test,~1)
# 1       emmean   SE df lower.CL upper.CL
# overall   20.1 1.07 31     17.9     22.3

#Confidence level used: 0.95


问:
How to push and pop views in Swift UI?
I cannot figure out how to push and pop views in Swift UI. In UIKit, it is so simple and I don't know why I can't find a solution to such a simple issue with the new framework. If anyone could help, that would be great. thanks. </p>

答:
You can use NavigationLink inside NavigationView.

A tutorial can be found here: Displaying a detail screen with NavigationLink.

Links to Apple documentation:

NavigationLink

NavigationView

Title: How to push and pop views in Swift UI?