问:
Prevent recalculations of User Defined Functions used in named ranges
I have three UDF's:

```<code>Private Function IsInArray(stringToBeFound As Variant, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function
</code>```

This function checks if something is in the array.

```<code>Private Function data_to_array(data As Range)

Dim arrArray As Variant
Dim cell As Range
Dim z As Integer

z = 0

ReDim arrArray(1 To data.Cells.Count)
For Each cell In data
    z = z + 1
    arrArray(z) = cell.Value
Next cell

data_to_array = arrArray
End Function
</code>```

This function extracts selected range values and puts them into an array.

```<code>Private Function plot_vals(data As Variant, custom_arr As Variant)

Dim arrPlot As Variant
ReDim arrPlot(1 To UBound(data)) As Variant
Dim c As Integer
Dim cl As Integer

cl = 0

For c = 1 To UBound(data)
    cl = cl + 1
    If IsInArray(cl, custom_arr) Then
        arrPlot(cl) = data(cl)
    Else
        arrPlot(cl) = CVErr(xlErrNA)
    End If
Next c

plot_vals = arrPlot
End Function
</code>```

The last UDF loops through the data array from second UDF and if index/position of value in data_array is in custom_array, then it returns its value. Otherwise it puts an error into an array.

Data looks like this:

These functions are used like this in Excel:

data_to_array(A1:A5) - this UDF creates an array(1 to 5) with values from cells A1:A5.

plot_vals(data_to_array(A1:A5), {1,5}) - this UDF creates an array(1 to 5), and uses second argument to retrieve first and fifth values while putting errors in the other indexes. The result is array of for example: {5,error,error,error,1}

If I used the function on above data like this: plot_vals(data_to_array(A1:A5), {1,2}) then the result would be an array {5,4,error,error,error}

That plot_vals UDF is used in named range and that named range is used to plot values on chart.
Data is stored in named range myData and the function in second named range is used like this:
plot_vals(myData,{1,5}).

Everything works, I can plot it on chart, all is good but when the named ranges are used on charts, every time I change something in my workbook all functions are recalculated like... 10 times each one, instead of once. It causes Excel to slow down/freeze if those functions are used many times. I have tried to search about function volatility and how to turn it off (it should be turned off by default?), but nothing seems to be working and I do not know how to stop that from happening. I have tried to recreate this in Excel using standard Excel functions in named ranges, but I cannot find a correct function to do what I want. UDF is exactly what I need.

When these named ranges are NOT used in charts then nothing happens, but as soon as I use the named range on chart then it recalculates everything on even a minor change of a workbook. Minor change meaning - copying / pasting / adding rows etc.

How can I stop that from happening? How to recalculate UDF's only once?

EDIT on further research:

I have tried the potential solutions provided by Charles Williams:
https://fastexcel.wordpress.com/2011/11/25/writing-efficient-vba-udfs-part-7-udfs-calculated-multiple-times/

His potential solutions do not change anything.

I have also tried using Sheet_Change event, changing calculations to manual and then back to automatic. It helps but it clears the clipboard (unacceptable) and it causes issues with my other macros, so it is a "no-go" solution.

It is also worth noting, that as soon as the chart is deleted and the UDF's remain in named ranges, everything is working nice and smooth. But when those named ranges are in chart series formulas, everything is recalculating 100's of times.

答:
Aside from trying to fix the basic problem of how many times your functions get called, you can partially address the slow-down by optimizing the basic performance:

Application.Match is relatively slow unless the data being searched in on a worksheet

Reading a range into an array is slower than reading the whole range at once using its .Value (assuming range is a single area)

So:

```<code>Sub PerfTester()
    Const ARR_SZ As Long = 10

    Dim arr(1 To ARR_SZ), i, n, t, v, m

    'populate a test array
    For i = 1 To ARR_SZ
        arr(i) = i
    Next i

    t = Timer
    For n = 1 To 100000
        v = Round(Rnd * ARR_SZ, 0)
        m = IsInArray(v, arr)  'using match
    Next n
    Debug.Print Timer - t   '~ 1.7 sec

    t = Timer
    For n = 1 To 100000
        v = Round(Rnd * ARR_SZ, 0)
        m = IsInArray2(v, arr) 'using a loop
    Next n
    Debug.Print Timer - t  '~0.11 sec

    t = Timer
    For n = 1 To 100000
        v = data_to_array(Range("A1:A50"))  'using cell-by-cell
    Next n
    Debug.Print Timer - t   '~ 11.5 sec

    t = Timer
    For n = 1 To 100000
        v = data_to_array2(Range("A1:A50"))  'using single read from range
    Next n
    Debug.Print Timer - t  '~ 2.8 sec

End Sub

Private Function IsInArray(stringToBeFound As Variant, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function

Private Function IsInArray2(stringToBeFound As Variant, arr As Variant) As Boolean
    Dim i
    For i = LBound(arr) To UBound(arr)
        If arr(i) = stringToBeFound Then
            IsInArray2 = True
            Exit For
        End If
    Next i
End Function

Private Function data_to_array(data As Range)
    Dim arrArray As Variant, cell As Range, z As Integer
    z = 0
    ReDim arrArray(1 To data.Cells.Count)
    For Each cell In data
        z = z + 1
        arrArray(z) = cell.Value
    Next cell
    data_to_array = arrArray
End Function

Private Function data_to_array2(data As Range)
    Dim arrArray As Variant, cell As Range, z As Long, v
    v = data.Value
    ReDim arrArray(1 To UBound(v, 1))
    For z = 1 To UBound(v, 1)
        arrArray = v(z, 1)
    Next z
    data_to_array2 = arrArray
End Function
</code>```

Body:
I have three UDF's:

Private Function IsInArray(stringToBeFound As Variant, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function

This function checks if something is in the array.

Private Function data_to_array(data As Range)

Dim arrArray As Variant
Dim cell As Range
Dim z As Integer

z = 0

ReDim arrArray(1 To data.Cells.Count)
For Each cell In data
    z = z + 1
    arrArray(z) = cell.Value
Next cell

data_to_array = arrArray
End Function

This function extracts selected range values and puts them into an array.

Private Function plot_vals(data As Variant, custom_arr As Variant)

Dim arrPlot As Variant
ReDim arrPlot(1 To UBound(data)) As Variant
Dim c As Integer
Dim cl As Integer

cl = 0

For c = 1 To UBound(data)
    cl = cl + 1
    If IsInArray(cl, custom_arr) Then
        arrPlot(cl) = data(cl)
    Else
        arrPlot(cl) = CVErr(xlErrNA)
    End If
Next c

plot_vals = arrPlot
End Function

The last UDF loops through the data array from second UDF and if index/position of value in data_array is in custom_array, then it returns its value. Otherwise it puts an error into an array.

Data looks like this:

These functions are used like this in Excel:

data_to_array(A1:A5) - this UDF creates an array(1 to 5) with values from cells A1:A5.

plot_vals(data_to_array(A1:A5), {1,5}) - this UDF creates an array(1 to 5), and uses second argument to retrieve first and fifth values while putting errors in the other indexes. The result is array of for example: {5,error,error,error,1}

If I used the function on above data like this: plot_vals(data_to_array(A1:A5), {1,2}) then the result would be an array {5,4,error,error,error}

That plot_vals UDF is used in named range and that named range is used to plot values on chart.
Data is stored in named range myData and the function in second named range is used like this:
plot_vals(myData,{1,5}).

Everything works, I can plot it on chart, all is good but when the named ranges are used on charts, every time I change something in my workbook all functions are recalculated like... 10 times each one, instead of once. It causes Excel to slow down/freeze if those functions are used many times. I have tried to search about function volatility and how to turn it off (it should be turned off by default?), but nothing seems to be working and I do not know how to stop that from happening. I have tried to recreate this in Excel using standard Excel functions in named ranges, but I cannot find a correct function to do what I want. UDF is exactly what I need.

When these named ranges are NOT used in charts then nothing happens, but as soon as I use the named range on chart then it recalculates everything on even a minor change of a workbook. Minor change meaning - copying / pasting / adding rows etc.

How can I stop that from happening? How to recalculate UDF's only once?

EDIT on further research:

I have tried the potential solutions provided by Charles Williams:
https://fastexcel.wordpress.com/2011/11/25/writing-efficient-vba-udfs-part-7-udfs-calculated-multiple-times/

His potential solutions do not change anything.

I have also tried using Sheet_Change event, changing calculations to manual and then back to automatic. It helps but it clears the clipboard (unacceptable) and it causes issues with my other macros, so it is a "no-go" solution.

It is also worth noting, that as soon as the chart is deleted and the UDF's remain in named ranges, everything is working nice and smooth. But when those named ranges are in chart series formulas, everything is recalculating 100's of times.

Body:
Aside from trying to fix the basic problem of how many times your functions get called, you can partially address the slow-down by optimizing the basic performance:

Application.Match is relatively slow unless the data being searched in on a worksheet

Reading a range into an array is slower than reading the whole range at once using its .Value (assuming range is a single area)

So:

Sub PerfTester()
    Const ARR_SZ As Long = 10

    Dim arr(1 To ARR_SZ), i, n, t, v, m

    'populate a test array
    For i = 1 To ARR_SZ
        arr(i) = i
    Next i

    t = Timer
    For n = 1 To 100000
        v = Round(Rnd * ARR_SZ, 0)
        m = IsInArray(v, arr)  'using match
    Next n
    Debug.Print Timer - t   '~ 1.7 sec

    t = Timer
    For n = 1 To 100000
        v = Round(Rnd * ARR_SZ, 0)
        m = IsInArray2(v, arr) 'using a loop
    Next n
    Debug.Print Timer - t  '~0.11 sec

    t = Timer
    For n = 1 To 100000
        v = data_to_array(Range("A1:A50"))  'using cell-by-cell
    Next n
    Debug.Print Timer - t   '~ 11.5 sec

    t = Timer
    For n = 1 To 100000
        v = data_to_array2(Range("A1:A50"))  'using single read from range
    Next n
    Debug.Print Timer - t  '~ 2.8 sec

End Sub

Private Function IsInArray(stringToBeFound As Variant, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function

Private Function IsInArray2(stringToBeFound As Variant, arr As Variant) As Boolean
    Dim i
    For i = LBound(arr) To UBound(arr)
        If arr(i) = stringToBeFound Then
            IsInArray2 = True
            Exit For
        End If
    Next i
End Function

Private Function data_to_array(data As Range)
    Dim arrArray As Variant, cell As Range, z As Integer
    z = 0
    ReDim arrArray(1 To data.Cells.Count)
    For Each cell In data
        z = z + 1
        arrArray(z) = cell.Value
    Next cell
    data_to_array = arrArray
End Function

Private Function data_to_array2(data As Range)
    Dim arrArray As Variant, cell As Range, z As Long, v
    v = data.Value
    ReDim arrArray(1 To UBound(v, 1))
    For z = 1 To UBound(v, 1)
        arrArray = v(z, 1)
    Next z
    data_to_array2 = arrArray
End Function


来源: stackexchange

问:
In the event object for an onEdit trigger how is it that range get's defined as a real range object and a property identifier at the same time?
I have a little code sample to highlight the difference between an object that I created and the trigger event object.  In the trigger event object I can  use the term e.range along with the standard range class functions and it works fine.  However, I don't really know how to create a psuedo event object so that the range term is more than just the name of a property.

```<code>   function onEdit(e) {
      console.log(JSON.stringify(e));
      var sh=e.range.getSheet();//e.range is a real range object
      if(sh.getName()=='Sheet2' && e.range.columnStart>1) {
        sh.getRange(1,1).setValue(JSON.stringify(e)+ '\n' + e.range.getA1Notation());
        var rg=sh.getRange(e.range.getA1Notation());//e.range is a real range object
        var myObj={value:rg.getValue,range:{columnStart:e.range.columnStart,rowStart:e.range.rowStart,columnEnd:e.range.columnEnd,rowEnd:e.range.rowEnd}};
        console.log(JSON.stringify(myObj));
        try{
          sh.getRange(2,1).setValue(JSON.stringify(myObj)+ '\n' + myObj.range.getA1Notation());//myObj.range is not a real range object
        }
        catch(m) {
          console.log('Error: ' + m);
        }
        try{
          sh.getRange(3,1).setValue(e.range.getValue());
        }
        catch(n) {
          console.log('Error: ' + n);
        }
      }
    }
</code>```

If you edit Sheet2 appropriately you will get the following Stack Driver Logs:

Stackdriver logs

```<code>May 29, 2020, 1:21:30 PM    Debug   {"source":{},"value":"55","user":{"email":"","nickname":""},"range":{"columnEnd":5,"columnStart":5,"rowEnd":3,"rowStart":3},"authMode":"LIMITED"}
May 29, 2020, 1:21:30 PM    Debug   {"range":{"columnStart":5,"rowStart":3,"columnEnd":5,"rowEnd":3}}
May 29, 2020, 1:21:30 PM    Debug   Error: TypeError: myObj.range.getA1Notation is not a function
</code>```

Notice above I cannot use myObj.range with the getA1Notation() method.  (note: I didn't actually expect it to work...I'd like to know how to build the object correctly so that it will work and I haven't stumbled on the correct explanation yet.

So the thing I'd like to learn is how to create a psuedo event object so I can use myObj.range in the same way as I  can use e.range.

I feel real bad after Tanaike has gone to so much trouble.  But my real goal is to be able to create the event object precisely as it is created by the server. So that I could test onEdit()s with a test function calling the onEdit(e) rather than requiring actual edits.  And more importantly I'd really just like know how to build such an object.

I think this says what I'm shooting for.  I want to know how to create the event object precisely as it is provided to us from the onEdit trigger including having e.range to be an object that is equivalent to Class Range and thus capable of utilizing any of the methods found here.  I hope that's possible.  I apologize for these late additions but they were prompted from some of Tanaike's questions.  I'll probably need to review the question again and make it more clear.

This is some code I'm working on and it's far from complete but this is the sort of thing one might do with the knowledge of the answer to my question.

```<code>function onXditTest(row) {
  var row=row||2;
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('OnEditTest');
  const v=sh.getRange(row,1,1,sh.getLastColumn()).getValues()[0];
  const xsh=ss.getSheetByName(v[5]);
  const xrg=xsh.getRange(v[0],v[2],v[1]-v[0]+1,v[3]-v[2]+1);
  const evobj={range:{rowStart:v[0],rowEnd:v[1],columnStart:v[2],columnEnd:v[3]},value:v[4],range:xrg,source:ss};
  onXdit(evobj);
}
</code>```

The real question is how to make evobj so that evobj.range is an object of Class Range and at the sametime have available evobj.range.columnStart, evobj.range.rowStart, evobj.range.columnEnd and evobj.range.rowEnd so that the code under test behaves the same way in onEdit(e) as it does in onXdit(e)

```<code>function onXdit(e) {//changed name so edits dont trigger the function
  e.source.toast('Entry');
  console.log(JSON.stringify(e));
  const sh=e.range.getSheet();
  if(sh.getName()=="Sheet2" && e.range.columnStart==4 && e.value=="TRUE" ) {
    e.source.toast('Past Condition');
    e.range.setValue("FALSE");
  }
}
</code>```

答:
The first function here is executed with the RunOnXdit button in the sidebar and it called the onXdit() function passing a psuedo onEdit trigger event object along with a mode property so that I can distinguish between running in test mode and running in live mode.

```<code>function onXditTest(row) {
  var row=row||2;
  console.log('row: ' + row);
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('OnEditTest');
  const v=sh.getRange(row,1,1,sh.getLastColumn()).getValues()[0];
  const xsh=ss.getSheetByName(v[5]);
  const xrg=xsh.getRange(v[0],v[2],v[1]-v[0]+1,v[3]-v[2]+1);
  var evobj={value:v[4]?"TRUE":"FALSE",source:ss,mode:true};
  evobj.range=xrg;//assign Class Range Object
  evobj.range.rowStart=v[0];
  evobj.range.rowEnd=v[1];
  evobj.range.columnEnd=v[3];
  evobj.range.columnStart=v[2]
  onXdit(evobj);
}
</code>```

The second function can be run from the above function or it can be run from the onEdit trigger with the same code.  The above function is generating a psuedo onEdit trigger event object.  I was totally shocked to realize how easy it was to create it.

```<code>function onXdit(e) {
//function onEdit(e) {
  e.source.toast('Entry');
  console.log(JSON.stringify(e));
  const sh=e.range.getSheet();
  if(sh.getName()=="Sheet2" && e.range.columnStart==4 && e.range.rowStart!=5 && e.value=="TRUE") {
    e.source.toast('Section 2');
    sh.getRange(1,1).setValue(JSON.stringify(e));
    e.range.offset(0,1).setValue('CheckBoxIsOff')
    e.range.setValue("FALSE");
  }
  if(sh.getName()=="Sheet2" && e.range.columnStart==4 && e.range.rowStart==5  && e.value=="TRUE") {
    e.source.toast('Section 2');
    sh.getRange(2,4,4,1).setValue(e.mode?"TRUE":"FALSE");
    //sh.getRange(5,4,1,1).setValue("FALSE");
    sh.getRange(2,5,4,1).setValue("");
  }
}
</code>```

This is Sheet2 which the sheet that is to be connected to the onEdit tester

This is Sheet2 after pressing the Run OnXdit Button

It does exactly what I would have wanted the onEdit() with the same code to have done. I guess my big problem was thinking about it too much.

The image above is just a simple table for providing the appropriate event object for the onXdit() function.

Animation:

ContentLicense: CC BY-SA 4.0

Body:
I have a little code sample to highlight the difference between an object that I created and the trigger event object.  In the trigger event object I can  use the term e.range along with the standard range class functions and it works fine.  However, I don't really know how to create a psuedo event object so that the range term is more than just the name of a property.

   function onEdit(e) {
      console.log(JSON.stringify(e));
      var sh=e.range.getSheet();//e.range is a real range object
      if(sh.getName()=='Sheet2' && e.range.columnStart>1) {
        sh.getRange(1,1).setValue(JSON.stringify(e)+ '\n' + e.range.getA1Notation());
        var rg=sh.getRange(e.range.getA1Notation());//e.range is a real range object
        var myObj={value:rg.getValue,range:{columnStart:e.range.columnStart,rowStart:e.range.rowStart,columnEnd:e.range.columnEnd,rowEnd:e.range.rowEnd}};
        console.log(JSON.stringify(myObj));
        try{
          sh.getRange(2,1).setValue(JSON.stringify(myObj)+ '\n' + myObj.range.getA1Notation());//myObj.range is not a real range object
        }
        catch(m) {
          console.log('Error: ' + m);
        }
        try{
          sh.getRange(3,1).setValue(e.range.getValue());
        }
        catch(n) {
          console.log('Error: ' + n);
        }
      }
    }

If you edit Sheet2 appropriately you will get the following Stack Driver Logs:

Stackdriver logs

May 29, 2020, 1:21:30 PM    Debug   {"source":{},"value":"55","user":{"email":"","nickname":""},"range":{"columnEnd":5,"columnStart":5,"rowEnd":3,"rowStart":3},"authMode":"LIMITED"}
May 29, 2020, 1:21:30 PM    Debug   {"range":{"columnStart":5,"rowStart":3,"columnEnd":5,"rowEnd":3}}
May 29, 2020, 1:21:30 PM    Debug   Error: TypeError: myObj.range.getA1Notation is not a function

Notice above I cannot use myObj.range with the getA1Notation() method.  (note: I didn't actually expect it to work...I'd like to know how to build the object correctly so that it will work and I haven't stumbled on the correct explanation yet.

So the thing I'd like to learn is how to create a psuedo event object so I can use myObj.range in the same way as I  can use e.range.

I feel real bad after Tanaike has gone to so much trouble.  But my real goal is to be able to create the event object precisely as it is created by the server. So that I could test onEdit()s with a test function calling the onEdit(e) rather than requiring actual edits.  And more importantly I'd really just like know how to build such an object.

I think this says what I'm shooting for.  I want to know how to create the event object precisely as it is provided to us from the onEdit trigger including having e.range to be an object that is equivalent to Class Range and thus capable of utilizing any of the methods found here.  I hope that's possible.  I apologize for these late additions but they were prompted from some of Tanaike's questions.  I'll probably need to review the question again and make it more clear.

This is some code I'm working on and it's far from complete but this is the sort of thing one might do with the knowledge of the answer to my question.

function onXditTest(row) {
  var row=row||2;
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('OnEditTest');
  const v=sh.getRange(row,1,1,sh.getLastColumn()).getValues()[0];
  const xsh=ss.getSheetByName(v[5]);
  const xrg=xsh.getRange(v[0],v[2],v[1]-v[0]+1,v[3]-v[2]+1);
  const evobj={range:{rowStart:v[0],rowEnd:v[1],columnStart:v[2],columnEnd:v[3]},value:v[4],range:xrg,source:ss};
  onXdit(evobj);
}

The real question is how to make evobj so that evobj.range is an object of Class Range and at the sametime have available evobj.range.columnStart, evobj.range.rowStart, evobj.range.columnEnd and evobj.range.rowEnd so that the code under test behaves the same way in onEdit(e) as it does in onXdit(e)

function onXdit(e) {//changed name so edits dont trigger the function
  e.source.toast('Entry');
  console.log(JSON.stringify(e));
  const sh=e.range.getSheet();
  if(sh.getName()=="Sheet2" && e.range.columnStart==4 && e.value=="TRUE" ) {
    e.source.toast('Past Condition');
    e.range.setValue("FALSE");
  }
}

Body:
The first function here is executed with the RunOnXdit button in the sidebar and it called the onXdit() function passing a psuedo onEdit trigger event object along with a mode property so that I can distinguish between running in test mode and running in live mode.

function onXditTest(row) {
  var row=row||2;
  console.log('row: ' + row);
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('OnEditTest');
  const v=sh.getRange(row,1,1,sh.getLastColumn()).getValues()[0];
  const xsh=ss.getSheetByName(v[5]);
  const xrg=xsh.getRange(v[0],v[2],v[1]-v[0]+1,v[3]-v[2]+1);
  var evobj={value:v[4]?"TRUE":"FALSE",source:ss,mode:true};
  evobj.range=xrg;//assign Class Range Object
  evobj.range.rowStart=v[0];
  evobj.range.rowEnd=v[1];
  evobj.range.columnEnd=v[3];
  evobj.range.columnStart=v[2]
  onXdit(evobj);
}

The second function can be run from the above function or it can be run from the onEdit trigger with the same code.  The above function is generating a psuedo onEdit trigger event object.  I was totally shocked to realize how easy it was to create it.

function onXdit(e) {
//function onEdit(e) {
  e.source.toast('Entry');
  console.log(JSON.stringify(e));
  const sh=e.range.getSheet();
  if(sh.getName()=="Sheet2" && e.range.columnStart==4 && e.range.rowStart!=5 && e.value=="TRUE") {
    e.source.toast('Section 2');
    sh.getRange(1,1).setValue(JSON.stringify(e));
    e.range.offset(0,1).setValue('CheckBoxIsOff')
    e.range.setValue("FALSE");
  }
  if(sh.getName()=="Sheet2" && e.range.columnStart==4 && e.range.rowStart==5  && e.value=="TRUE") {
    e.source.toast('Section 2');
    sh.getRange(2,4,4,1).setValue(e.mode?"TRUE":"FALSE");
    //sh.getRange(5,4,1,1).setValue("FALSE");
    sh.getRange(2,5,4,1).setValue("");
  }
}

This is Sheet2 which the sheet that is to be connected to the onEdit tester

This is Sheet2 after pressing the Run OnXdit Button

It does exactly what I would have wanted the onEdit() with the same code to have done. I guess my big problem was thinking about it too much.

The image above is just a simple table for providing the appropriate event object for the onXdit() function.

Animation:


问:
Using variable to select covariates for glm
I am running a simulation of multiple experiments using random data to create glm models. In each individual experiment I need to select different covariates to build the glm. Is there a way to use variable names to specify which covariates to use in the formula? For example, for a data frame called data that will contain the heading y plus a set of other headings that changes with each iteration, something like:

```<code>data <- data.frame(x1 = c(1:100),x2 = c(2:101),x3 = c(3:102),x4 = c(4:103),x5 = c(5,104),y = c(6:105))

#Experiment #1:
covars = c(x1,x2,x4)
glm(y ~ sum(covars),data=data)

#Experiment #2:
covars = c(x1,x3,x4,x5)
glm(y ~ sum(covars),data=data)

#Experiment #3:
covars = c(x2,x4,x5)
glm(y ~ sum(covars),data=data)

#etc...
</code>```

So far, I have tried using this approach with the sum & colnames functions but I get the following error: "invalid 'type' (character) of argument"

Thank you!

答:
We can use . to represent all the columns except the dependent column 'y'

```<code>glm(y ~ ., data = data)
</code>```

Body:
I am running a simulation of multiple experiments using random data to create glm models. In each individual experiment I need to select different covariates to build the glm. Is there a way to use variable names to specify which covariates to use in the formula? For example, for a data frame called data that will contain the heading y plus a set of other headings that changes with each iteration, something like:

data <- data.frame(x1 = c(1:100),x2 = c(2:101),x3 = c(3:102),x4 = c(4:103),x5 = c(5,104),y = c(6:105))

#Experiment #1:
covars = c(x1,x2,x4)
glm(y ~ sum(covars),data=data)

#Experiment #2:
covars = c(x1,x3,x4,x5)
glm(y ~ sum(covars),data=data)

#Experiment #3:
covars = c(x2,x4,x5)
glm(y ~ sum(covars),data=data)

#etc...

So far, I have tried using this approach with the sum & colnames functions but I get the following error: "invalid 'type' (character) of argument"

Thank you!

Body:
We can use . to represent all the columns except the dependent column 'y'

glm(y ~ ., data = data)


问:
Need to add Spaces at certain Indexes
So this is data i have,

```<code>s = [2, 8, 15, 23, 28, 43, 47, 55, 63, 72, 79, 82, 89, 97, 102, 112, 120, 125, 131, 141, 148, 156, 163, 167, 180, 188, 193, 210, 222, 227]
</code>```

These are the index position where i need to add spaces,

```<code>d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'
</code>```

My overall goal is split the string in such a way that the Shotforms and the Longforms are seperated,

For EX: This is the output I'm trying to get

CC Carbon Copy CAI Computer Aided Instruction
```

<p>and so on.....</p>

<p>I have calculated the indexes by doing this,</p>

```s = []
for i in range(0, len(d)):
    if d[i].isupper() and d[i+1].islower() and d[i+2].islower():
        s.append(i)
```

<p>When I individually try and add the space using the index, I get an output,</p>

```d[0:s[0]] + ' ' + d[s[0]:]
```

<p>I get the following, which is correct</p>

<pre class="lang-none prettyprint-override"><code>'CC CarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTube
</code>```

But, when I try and iterate over the indexes, i get List out of Range

```<code>temp = []
for i in s:
    print(i)
    temp.append(d[0:s[i]] + ' ' + d[s[i]:])

Traceback (most recent call last):
  File "<input>", line 4, in <module>
IndexError: list index out of range
</code>```

答:
You are iterating over the list elements and still accessing it through index. Which is wrong.

```<code>for i in s:
    print(i) # this will iterate over the list, in that case you do not need indexing.

for i in range(len(s)):
    print(s[i])
</code>```

You need to understand difference between the two.
For ref: https://www.geeksforgeeks.org/iterate-over-a-list-in-python/

For your problem, You may try this -

```<code>words = []
for i in range(len(s)-1):
    words.append(d[s[i]:s[i+1]])
" ".join(words)
</code>```

Title: Need to add Spaces at certain Indexes

Body:
So this is data i have,

s = [2, 8, 15, 23, 28, 43, 47, 55, 63, 72, 79, 82, 89, 97, 102, 112, 120, 125, 131, 141, 148, 156, 163, 167, 180, 188, 193, 210, 222, 227]

These are the index position where i need to add spaces,

d = 'CCCarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTubeCADComputerAidedDesignCADDComputerAidedDesignDraftingCDCompactDiskCDRWCompactDiskRewritableCAMComputerAidedManufacturingCROMComputerizedRangeMotionCDROMCompactDiskReadOnlyMemory'

My overall goal is split the string in such a way that the Shotforms and the Longforms are seperated,

For EX: This is the output I'm trying to get

CC Carbon Copy CAI Computer Aided Instruction

and so on.....

I have calculated the indexes by doing this,

s = []
for i in range(0, len(d)):
    if d[i].isupper() and d[i+1].islower() and d[i+2].islower():
        s.append(i)

When I individually try and add the space using the index, I get an output,

d[0:s[0]] + ' ' + d[s[0]:]

I get the following, which is correct

'CC CarbonCopyCAIComputerAidedInstructionCDMACodeDivisionMultipleAccessCRTCathodeRayTube

But, when I try and iterate over the indexes, i get List out of Range

temp = []
for i in s:
    print(i)
    temp.append(d[0:s[i]] + ' ' + d[s[i]:])

Traceback (most recent call last):
  File "<input>", line 4, in <module>
IndexError: list index out of range

Body:
You are iterating over the list elements and still accessing it through index. Which is wrong.

for i in s:
    print(i) # this will iterate over the list, in that case you do not need indexing.

for i in range(len(s)):
    print(s[i])

You need to understand difference between the two.
For ref: https://www.geeksforgeeks.org/iterate-over-a-list-in-python/

For your problem, You may try this -

words = []
for i in range(len(s)-1):
    words.append(d[s[i]:s[i+1]])
" ".join(words)


问:
Script tag not rendering synchronously
this is the code im working with

```<code><body>

  <script type="text/javascript" src = "http://localhost:3000/common_assets/navbar.js"></script>

  <script type="text/javascript" src = "http://localhost:3000//index.js"></script>

  <h1>MonkaHmm...</h1>

</body>

</code>```

both the scripts render html and they both work the problem is the second script is always rendered last
so the MonkaHmm... comes in at the middle of the page.

this is the code thats in the second script tag

```<code>async function cardData(){
    var response = await fetch('http://localhost:3000/Board_Members.json');
    var carddata =  await response.json();

    carddata.forEach(function(membercard){
      var member_cards = document.createElement("div");
      var code = `
        <div class="member_cards card-4">
          <img class = "img_member" src="http://localhost:3000/IMAGES/jonipic.jpg">
          <div class="description">
            <h5>${membercard.name}</h5>
            <h5>${membercard.title}</h5>
            ${membercard.description}
          </div>

        </div>
        <link rel="stylesheet" type="text/css" href="http://localhost:3000/index.css">
`
      member_cards.innerHTML = code;
      document.body.appendChild(member_cards);
    });
}

cardData();

</code>```

i have a feeling this is happening because of the fetch but its in an async/await function so i thought it would act synchronously but to be honest i have no clue. HELP my fellow pepega coders

答:
I think this could be as simple as changing appendNode to insertBefore

```<code>member_cards.innerHTML = code;
document.body.appendChild(member_cards);
</code>```

to this

```<code>member_cards.innerHTML = code;
let h1 = document.body.getElementsByTagName("H1")[0];
document.body.insertBefore(member_cards, h1);
</code>```

You should put in a check to make sure the getElementsByTagName call returns a value. If it doesn't you can either set a timeout or use your old appendChild call

Title: Script tag not rendering synchronously

Body:
this is the code im working with

MonkaHmm...

both the scripts render html and they both work the problem is the second script is always rendered last
so the MonkaHmm... comes in at the middle of the page.

this is the code thats in the second script tag

async function cardData(){
    var response = await fetch('http://localhost:3000/Board_Members.json');
    var carddata =  await response.json();

    carddata.forEach(function(membercard){
      var member_cards = document.createElement("div");
      var code = `

${membercard.name}

${membercard.title}

            ${membercard.description}

        <link rel="stylesheet" type="text/css" href="http://localhost:3000/index.css">
`
      member_cards.innerHTML = code;
      document.body.appendChild(member_cards);
    });
}

cardData();

i have a feeling this is happening because of the fetch but its in an async/await function so i thought it would act synchronously but to be honest i have no clue. HELP my fellow pepega coders

Body:
I think this could be as simple as changing appendNode to insertBefore

member_cards.innerHTML = code;
document.body.appendChild(member_cards);

to this

member_cards.innerHTML = code;
let h1 = document.body.getElementsByTagName("H1")[0];
document.body.insertBefore(member_cards, h1);

You should put in a check to make sure the getElementsByTagName call returns a value. If it doesn't you can either set a timeout or use your old appendChild call


问:
Xamarin : Adding multiple bindings to multiple collection views on the same page
I am currently trying to build two separate collection views on the same page in Xamarin. I keep getting the error that content is set more than once and also that I've set the content binding more than once. How do I add different bindings to two separate collection views on the same page?

ConsumerOrders.xaml page:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:viewmodels="clr-namespace:Shared.ViewModel"
             mc:Ignorable="d"
             x:Class="Shared.consumerOrders">

    <ContentPage.BindingContext>
        <viewmodels:AddedServicesViewModel />
    </ContentPage.BindingContext>

    <d:ContentPage.BindingContext>
        <viewmodels:PastOrderViewModel />
    </d:ContentPage.BindingContext>

    <ScrollView>

        <CollectionView ItemsSource="{Binding  ViewAddedServices}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="4"/>
                            <!--0-->
                            <RowDefinition Height="30"/>
                            <!--1-->
                            <RowDefinition Height="20"/>
                            <!--2-->
                            <RowDefinition Height=".25"/>
                            <!--3-->
                            <RowDefinition Height="4"/>
                            <!--4-->
                            <RowDefinition Height="Auto"/>
                            <!--5-->
                            <RowDefinition Height="Auto"/>
                            <!--6-->
                            <RowDefinition Height=".25"/>
                            <!--7-->
                            <RowDefinition Height="Auto"/>
                            <!--8-->
                            <RowDefinition Height="Auto"/>
                            <!--9-->
                            <RowDefinition Height=".25"/>
                            <!--10-->
                            <RowDefinition Height="Auto"/>
                            <!--11-->

                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="4"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="4"/>
                        </Grid.ColumnDefinitions>
                        <Label Text="Services added" FontAttributes="Bold" TextColor="#F65506" Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="2" VerticalTextAlignment="End" HorizontalTextAlignment="Start" FontSize="18"/>
                        <Label Grid.Column="1" Grid.Row="7" BackgroundColor="#707070" Grid.ColumnSpan="3"/>
                        <!--This is a line-->
                        <BoxView BackgroundColor="#F0F0F0" Grid.Row="9" Grid.Column="1" Grid.ColumnSpan="3" CornerRadius="22"/>
                        <Label Grid.Column="1" Grid.Row="9" Padding="10" TextColor="Black" FontSize="18" Text="{Binding BusinessName}" VerticalOptions="CenterAndExpand" HorizontalOptions="StartAndExpand" Grid.ColumnSpan="2"/>
                        <Label Grid.Column="3" Grid.Row="9" Padding="0,0,20,0" TextColor="#F65506" FontAttributes="Bold" FontSize="18" Text="View" VerticalOptions="CenterAndExpand" HorizontalOptions="EndAndExpand" Grid.ColumnSpan="2"/>

                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

        <CollectionView ItemsSource="{Binding  ViewQuoteStatus}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="4"/>
                            <!--0-->
                            <RowDefinition Height="30"/>
                            <!--1-->
                            <RowDefinition Height="20"/>
                            <!--2-->
                            <RowDefinition Height=".25"/>
                            <!--3-->
                            <RowDefinition Height="4"/>
                            <!--4-->
                            <RowDefinition Height="Auto"/>
                            <!--5-->
                            <RowDefinition Height="Auto"/>
                            <!--6-->
                            <RowDefinition Height=".25"/>
                            <!--7-->
                            <RowDefinition Height="Auto"/>
                            <!--8-->
                            <RowDefinition Height="Auto"/>
                            <!--9-->
                            <RowDefinition Height=".25"/>
                            <!--10-->
                            <RowDefinition Height="Auto"/>
                            <!--11-->

                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="4"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="4"/>
                        </Grid.ColumnDefinitions>
                        <Label Text="Past Orderrs" FontAttributes="Bold" TextColor="#F65506" Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="2" VerticalTextAlignment="End" HorizontalTextAlignment="Start" FontSize="18"/>
                        <Label Grid.Column="1" Grid.Row="7" BackgroundColor="#707070" Grid.ColumnSpan="3"/>
                        <!--This is a line-->
                        <BoxView BackgroundColor="#F0F0F0" Grid.Row="9" Grid.Column="1" Grid.ColumnSpan="3" CornerRadius="22"/>
                        <Label Grid.Column="1" Grid.Row="9" Padding="10" TextColor="Black" FontSize="18" Text="{Binding BusinessName}" VerticalOptions="CenterAndExpand" HorizontalOptions="StartAndExpand" Grid.ColumnSpan="2"/>
                        <Label Grid.Column="3" Grid.Row="9" Padding="0,0,20,0" TextColor="#F65506" FontAttributes="Bold" FontSize="18" Text="View" VerticalOptions="CenterAndExpand" HorizontalOptions="EndAndExpand" Grid.ColumnSpan="2"/>

                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </ScrollView>
</ContentPage>
</code>```

AddedServicesViewModel.cs :

```<code>using Shared.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace Shared.ViewModel
{
    class AddedServicesViewModel
    {
        readonly IList<AddedServiceStatus> source;

        public ObservableCollection<AddedServiceStatus> ViewAddedServices { get; private set; }

        public AddedServicesViewModel()
        {
            source = new List<AddedServiceStatus>();
            CreateAddedServicesCollection();

        }

        void CreateAddedServicesCollection()
        {
            source.Add(new AddedServiceStatus
            {
                BusinessName = "Duck's Duct Cleaning"

            });

            source.Add(new AddedServiceStatus
            {
                BusinessName = "Rodney's Home Repair"

            });

            ViewAddedServices = new ObservableCollection<AddedServiceStatus>(source);
        }
    }
}
</code>```

PastOrderViewModel :

```<code>using Shared.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace Shared.ViewModel
{
    class PastOrderViewModel
    {

        readonly IList<PastOrderStatus> source;

        public ObservableCollection<PastOrderStatus> ViewPastOrders { get; private set; }

        public PastOrderViewModel()
        {
            source = new List<PastOrderStatus>();
            CreatePastOrderCollection();

        }

        void CreatePastOrderCollection()
        {
            source.Add(new PastOrderStatus
            {
                BusinessName = "Karen's Magnificent Dog Grooming"

            });

            source.Add(new PastOrderStatus
            {
                BusinessName = "Harry's In Home Haircuts"

            });

            source.Add(new PastOrderStatus
            {
                BusinessName = "Shelly's Floral Arrangements"

            });

            ViewPastOrders = new ObservableCollection<PastOrderStatus>(source);
        }
    }
}
</code>```

答:
You can't have two ViewModels binding to a SingleView. (as far a I know)

I see that the DataTemplate in both Collections are the same..... there are many ways to refactor....

You could create two CustomView one with the AddedServicesViewModel and the other with PastOrderViewModel

You can merge the two ViewModels into one, and create a CustomView that it's the collection.

Another thing that I see that It could not work is that you can't have a more than one View Nested in a ScrollView

```<code><ScrollView>
   <StackLayout> /* Or any other Layout, Grid, Absolute, Flex etc...  */
   </StackLayout>
</ScrollView>
</code>```

Another thing is that a CollectionView with orientation vertical in a ScrollView maybe it won't behave as you expect, since the CollectionView with orientation vertical it has Scroll

Two CollectionViews with orientation vertical in the same View it should have a Height, I would do something like this

```<code><Grid>
  <Grid.RowDefinitions>
      <RowDefinition Height="1*"/>
      <RowDefinition Height="1*"/>
  </Grid.RowDefinitions>
  <CollectionView Grid.Row="0" ItemsSource="{Binding  ViewQuoteStatus}"> ... </CollectionView>
  <CollectionView Grid.Row="1" ItemsSource="{Binding  ViewAddedServices}"> ... </CollectionView>
</Grid>
</code>```

or if you create a custom view (custom control)

```<code><Grid>
  <Grid.RowDefinitions>
      <RowDefinition Height="1*"/>
      <RowDefinition Height="1*"/>
  </Grid.RowDefinitions>
  <MyCustomCollectionView Grid.Row="0" ItemsSource="{Binding  ViewQuoteStatus}"> ... </MyCustomCollectionView>
  <MyCustomCollectionView Grid.Row="1" ItemsSource="{Binding  ViewAddedServices}"> ... </MyCustomCollectionView>
</Grid>
</code>```

Body:
I am currently trying to build two separate collection views on the same page in Xamarin. I keep getting the error that content is set more than once and also that I've set the content binding more than once. How do I add different bindings to two separate collection views on the same page?

ConsumerOrders.xaml page:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:viewmodels="clr-namespace:Shared.ViewModel"
             mc:Ignorable="d"
             x:Class="Shared.consumerOrders">

    <ContentPage.BindingContext>
        <viewmodels:AddedServicesViewModel />
    </ContentPage.BindingContext>

    <d:ContentPage.BindingContext>
        <viewmodels:PastOrderViewModel />
    </d:ContentPage.BindingContext>

    <ScrollView>

        <CollectionView ItemsSource="{Binding  ViewAddedServices}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="4"/>

                            <RowDefinition Height="30"/>

                            <RowDefinition Height="20"/>

                            <RowDefinition Height=".25"/>

                            <RowDefinition Height="4"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height=".25"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height=".25"/>

                            <RowDefinition Height="Auto"/>

                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="4"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="4"/>
                        </Grid.ColumnDefinitions>

                        <BoxView BackgroundColor="#F0F0F0" Grid.Row="9" Grid.Column="1" Grid.ColumnSpan="3" CornerRadius="22"/>

                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

        <CollectionView ItemsSource="{Binding  ViewQuoteStatus}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="4"/>

                            <RowDefinition Height="30"/>

                            <RowDefinition Height="20"/>

                            <RowDefinition Height=".25"/>

                            <RowDefinition Height="4"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height=".25"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height=".25"/>

                            <RowDefinition Height="Auto"/>

                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="4"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="4"/>
                        </Grid.ColumnDefinitions>

                        <BoxView BackgroundColor="#F0F0F0" Grid.Row="9" Grid.Column="1" Grid.ColumnSpan="3" CornerRadius="22"/>

                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </ScrollView>
</ContentPage>

AddedServicesViewModel.cs :

using Shared.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace Shared.ViewModel
{
    class AddedServicesViewModel
    {
        readonly IList<AddedServiceStatus> source;

        public ObservableCollection<AddedServiceStatus> ViewAddedServices { get; private set; }

        public AddedServicesViewModel()
        {
            source = new List<AddedServiceStatus>();
            CreateAddedServicesCollection();

        }

        void CreateAddedServicesCollection()
        {
            source.Add(new AddedServiceStatus
            {
                BusinessName = "Duck's Duct Cleaning"

            });

            source.Add(new AddedServiceStatus
            {
                BusinessName = "Rodney's Home Repair"

            });

            ViewAddedServices = new ObservableCollection<AddedServiceStatus>(source);
        }
    }
}

PastOrderViewModel :

using Shared.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace Shared.ViewModel
{
    class PastOrderViewModel
    {

        readonly IList<PastOrderStatus> source;

        public ObservableCollection<PastOrderStatus> ViewPastOrders { get; private set; }

        public PastOrderViewModel()
        {
            source = new List<PastOrderStatus>();
            CreatePastOrderCollection();

        }

        void CreatePastOrderCollection()
        {
            source.Add(new PastOrderStatus
            {
                BusinessName = "Karen's Magnificent Dog Grooming"

            });

            source.Add(new PastOrderStatus
            {
                BusinessName = "Harry's In Home Haircuts"

            });

            source.Add(new PastOrderStatus
            {
                BusinessName = "Shelly's Floral Arrangements"

            });

            ViewPastOrders = new ObservableCollection<PastOrderStatus>(source);
        }
    }
}

Body:
You can't have two ViewModels binding to a SingleView. (as far a I know)

I see that the DataTemplate in both Collections are the same..... there are many ways to refactor....

You could create two CustomView one with the AddedServicesViewModel and the other with PastOrderViewModel

You can merge the two ViewModels into one, and create a CustomView that it's the collection.

Another thing that I see that It could not work is that you can't have a more than one View Nested in a ScrollView

<ScrollView>
   <StackLayout> /* Or any other Layout, Grid, Absolute, Flex etc...  */
   </StackLayout>
</ScrollView>

Another thing is that a CollectionView with orientation vertical in a ScrollView maybe it won't behave as you expect, since the CollectionView with orientation vertical it has Scroll

Two CollectionViews with orientation vertical in the same View it should have a Height, I would do something like this

<Grid>
  <Grid.RowDefinitions>
      <RowDefinition Height="1*"/>
      <RowDefinition Height="1*"/>
  </Grid.RowDefinitions>
  <CollectionView Grid.Row="0" ItemsSource="{Binding  ViewQuoteStatus}"> ... </CollectionView>
  <CollectionView Grid.Row="1" ItemsSource="{Binding  ViewAddedServices}"> ... </CollectionView>
</Grid>

or if you create a custom view (custom control)

<Grid>
  <Grid.RowDefinitions>
      <RowDefinition Height="1*"/>
      <RowDefinition Height="1*"/>
  </Grid.RowDefinitions>
  <MyCustomCollectionView Grid.Row="0" ItemsSource="{Binding  ViewQuoteStatus}"> ... </MyCustomCollectionView>
  <MyCustomCollectionView Grid.Row="1" ItemsSource="{Binding  ViewAddedServices}"> ... </MyCustomCollectionView>
</Grid>


问:
React state Toggle only works once
I want to toggle this one boolean value in the state of one of my components. This is how I'm doing it rn :

```<code>updateProduct(productID) {
this.setState((prevState) => ({
  content:{
    ...prevState.content
  },
  products:{
    ...prevState.products,
    [productID] : {
      ...prevState.products[productID],
      editable : !prevState.editable
    }
  }
 }))
}
</code>```

The problem is: This works, but only once i.e. It toggles the boolean from false to true, but then it gets stuck on being true.

答:
Shouldn't it be:</p>

```<code>editable: !prevState.products[productID].editable
</code>```

Title: React state Toggle only works once

Body:
I want to toggle this one boolean value in the state of one of my components. This is how I'm doing it rn :

updateProduct(productID) {
this.setState((prevState) => ({
  content:{
    ...prevState.content
  },
  products:{
    ...prevState.products,
    [productID] : {
      ...prevState.products[productID],
      editable : !prevState.editable
    }
  }
 }))
}

The problem is: This works, but only once i.e. It toggles the boolean from false to true, but then it gets stuck on being true.

Body:
Shouldn't it be:

editable: !prevState.products[productID].editable


问:
How to create and access dynamic variable names a template function?
I wound up having three extremely similar functions in my code, which were to take separate user inputs for their birth year, month, and day. I want to use the best practices I can even though the code is extremely basic, which is why it's a bit overkill. So right now I have a function that acts as a template and takes three args dateType, typeStr, and typeFormat. I'm trying to use these args to name variables in the three functions that I'll create using the template so that I can later print out the birth date of the person. I'm aware of scope, but I've tried making things global etc etc and it hasn't worked. I don't know if I'm even creating variables that are persistent or if it all gets unassigned once the function is done, and if I am creating variables I can't figure out what they're called as I've tried every possibility.

```<code>def makeTemplateInput(dateType, typeStr, typeFormat):
    def templateInput(dateType, typeStr, typeFormat):
        print('You\'re using the template function. Please input your birth {} in the format {}.\n$ '.format(dateType, typeFormat), end='')
        while True:
            try:
                dateType = input()
                typeStr = dateType
                dateType = int(dateType)

                if dateType > 0:
                    if len(typeStr) != len(typeFormat) and isinstance(dateType, int):
                        print('Your input doesn\'t have {} digits, please use the format {}.\n$ '.format(str(len(typeFormat)), typeFormat), end='')
                        print('strlen: ' + str(len(typeStr)))
                        continue
                    break
                else:
                    print('Your input is not a positive integer!\n$ ', end='')
                    continue

            except ValueError:
                print('Your input is not a valid number, please use the format {} where {} is an integer.\n$ '.format(typeFormat, str(typeFormat[:1])), end='')

        print(dateType)

def yearInput1():
    makeTemplateInput('year', 'yearStr', 'YYYY')

yearInput1()
</code>```

print('Your birthdate is: {}/{}/{}'.format(yearInput1.year, monthInput.monthStr, dayInput.dayStr))

I'm sure it's a mess that misunderstands fundamental things about Python, but I really don't understand what's gone wrong.

答:
A few online classes or some good books can help with some of this confusion. I've created some sample code to hopefully answer your question. Thank you. </p>

```<code>class Calendar:
    def __init__(self, day, month, year): #This can be initialised with the day/month/year
        self.day = day
        self.month = month
        self.year = year

    def displayDate(self): #This will display the dates from the object created/set
        print('day:{} month:{} year:{}'.format(self.day, self.month, self.year))

    def setNewDate(self, otherDay, otherMonth, otherYear): #this sets the class attributes to something else
        print('This was the old values day:{} month:{} year:{}'.format(self.day, self.month, self.year))
        self.day = otherDay
        self.month = otherMonth
        self.year = otherYear
        print('The new values are day:{} month:{} year:{}'.format(self.day, self.month, self.year))

cal = Calendar(6,11,2020)
cal.displayDate()
cal.setNewDate(3,4,2099)
</code>```

Body:
I wound up having three extremely similar functions in my code, which were to take separate user inputs for their birth year, month, and day. I want to use the best practices I can even though the code is extremely basic, which is why it's a bit overkill. So right now I have a function that acts as a template and takes three args dateType, typeStr, and typeFormat. I'm trying to use these args to name variables in the three functions that I'll create using the template so that I can later print out the birth date of the person. I'm aware of scope, but I've tried making things global etc etc and it hasn't worked. I don't know if I'm even creating variables that are persistent or if it all gets unassigned once the function is done, and if I am creating variables I can't figure out what they're called as I've tried every possibility.

def makeTemplateInput(dateType, typeStr, typeFormat):
    def templateInput(dateType, typeStr, typeFormat):
        print('You\'re using the template function. Please input your birth {} in the format {}.\n$ '.format(dateType, typeFormat), end='')
        while True:
            try:
                dateType = input()
                typeStr = dateType
                dateType = int(dateType)

                if dateType > 0:
                    if len(typeStr) != len(typeFormat) and isinstance(dateType, int):
                        print('Your input doesn\'t have {} digits, please use the format {}.\n$ '.format(str(len(typeFormat)), typeFormat), end='')
                        print('strlen: ' + str(len(typeStr)))
                        continue
                    break
                else:
                    print('Your input is not a positive integer!\n$ ', end='')
                    continue

            except ValueError:
                print('Your input is not a valid number, please use the format {} where {} is an integer.\n$ '.format(typeFormat, str(typeFormat[:1])), end='')

        print(dateType)

def yearInput1():
    makeTemplateInput('year', 'yearStr', 'YYYY')

yearInput1()

print('Your birthdate is: {}/{}/{}'.format(yearInput1.year, monthInput.monthStr, dayInput.dayStr))

I'm sure it's a mess that misunderstands fundamental things about Python, but I really don't understand what's gone wrong.

Body:
A few online classes or some good books can help with some of this confusion. I've created some sample code to hopefully answer your question. Thank you.

class Calendar:
    def __init__(self, day, month, year): #This can be initialised with the day/month/year
        self.day = day
        self.month = month
        self.year = year

    def displayDate(self): #This will display the dates from the object created/set
        print('day:{} month:{} year:{}'.format(self.day, self.month, self.year))

    def setNewDate(self, otherDay, otherMonth, otherYear): #this sets the class attributes to something else
        print('This was the old values day:{} month:{} year:{}'.format(self.day, self.month, self.year))
        self.day = otherDay
        self.month = otherMonth
        self.year = otherYear
        print('The new values are day:{} month:{} year:{}'.format(self.day, self.month, self.year))

cal = Calendar(6,11,2020)
cal.displayDate()
cal.setNewDate(3,4,2099)


问:
Build file in Sublime Text 3 to invoke JUnit5 tests
I am trying to configure Sublime Text 3's RunJava.sublime-build file to add an option to execute JUnit 5 test on Mac OS X.

The following works for me from the Mac OS X terminal window:

$ java -jar /Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar -cp /Users/pavlomaistrenko/Documents/GitHub/SvitlanaMo/Java01/ --scan-classpath

My RunJava.sublime-build configuration file is:

```<code>{
    "selector": "source.java",
    "file_patterns": "*.java",
    "working_dir": "$file_path",
    "shell_cmd": "javac -cp .:/Users/pavlomaistrenko/Documents/GitHub/SvitlanaMo/Java01/:/Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar $file_name",
    "variants": [
        {
            "name": "Run class.jar",
            "shell_cmd": "java -cp .:/Users/pavlomaistrenko/Documents/GitHub/SvitlanaMo/Java01/:/Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar $file_base_name"
        },

        {
            "name": "JavaDoc",
            "shell_cmd": "mkdir -p documentation && javadoc -header \"<script type='text/javascript' src='http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'></script>\" -d documentation *.java"
        },

        {
            "name": "JAR",
            "cmd": "javac '$realpath$file' && echo \"Main-Class: $file_base_name\" > Manifest.txt && jar cfm $file_base_name.jar Manifest.txt *.class && rm *.class && java -jar $file_base_name.jar"
        },

        {
            "name": "JUnit5",
            "cmd": "java -jar /Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar -cp $file_path --scan-classpath"
        }

    ]
}
</code>```

Instead of full JUnit 5 output I just get [Finished in X.Xs].

Does JUnit get executed? If so, where is the output?

P.S. I have read Sublime is not a perfect environment for Java, but still.

答:
Finally found out a working build configuration for JUnit5. Here is the snippet:

```<code>{
    "name": "JUnit5 the folder",
    "env": { "user_path": "/Users/pavlomaistrenko/Documents",
     "junit5":  "Junit1.6/junit-platform-console-standalone-1.6.2.jar",
     "project_path": "GitHub/SvitlanaMo/Java01/"
   },
    "shell_cmd": "java -jar \\$user_path/\\$junit5 -cp .:$file_path --scan-classpath"
},
</code>```

Note the double escaping of $ with two backslashes \\ for Mac OS. The env variables are not expanded by Sublime, rather they are set as environment variables for this particular call of java loader (and then expanded by the shell.) See Use custom variables in Sublime Text build system for explanation.

Body:
I am trying to configure Sublime Text 3's RunJava.sublime-build file to add an option to execute JUnit 5 test on Mac OS X.

The following works for me from the Mac OS X terminal window:

$ java -jar /Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar -cp /Users/pavlomaistrenko/Documents/GitHub/SvitlanaMo/Java01/ --scan-classpath

My RunJava.sublime-build configuration file is:

{
    "selector": "source.java",
    "file_patterns": "*.java",
    "working_dir": "$file_path",
    "shell_cmd": "javac -cp .:/Users/pavlomaistrenko/Documents/GitHub/SvitlanaMo/Java01/:/Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar $file_name",
    "variants": [
        {
            "name": "Run class.jar",
            "shell_cmd": "java -cp .:/Users/pavlomaistrenko/Documents/GitHub/SvitlanaMo/Java01/:/Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar $file_base_name"
        },

        {
            "name": "JavaDoc",
            "shell_cmd": "mkdir -p documentation && javadoc -header \"\" -d documentation *.java"
        },

        {
            "name": "JAR",
            "cmd": "javac '$realpath$file' && echo \"Main-Class: $file_base_name\" > Manifest.txt && jar cfm $file_base_name.jar Manifest.txt *.class && rm *.class && java -jar $file_base_name.jar"
        },

        {
            "name": "JUnit5",
            "cmd": "java -jar /Users/pavlomaistrenko/Documents/Junit1.6/junit-platform-console-standalone-1.6.2.jar -cp $file_path --scan-classpath"
        }

    ]
}

Instead of full JUnit 5 output I just get [Finished in X.Xs].

Does JUnit get executed? If so, where is the output?

P.S. I have read Sublime is not a perfect environment for Java, but still.

Body:
Finally found out a working build configuration for JUnit5. Here is the snippet:

{
    "name": "JUnit5 the folder",
    "env": { "user_path": "/Users/pavlomaistrenko/Documents",
     "junit5":  "Junit1.6/junit-platform-console-standalone-1.6.2.jar",
     "project_path": "GitHub/SvitlanaMo/Java01/"
   },
    "shell_cmd": "java -jar \\$user_path/\\$junit5 -cp .:$file_path --scan-classpath"
},

Note the double escaping of $ with two backslashes \\ for Mac OS. The env variables are not expanded by Sublime, rather they are set as environment variables for this particular call of java loader (and then expanded by the shell.) See Use custom variables in Sublime Text build system for explanation.


问:
Return true if none of the letters in the blacklist
Return true if none of the letters in the blacklist
are present in the phrase. If at least one letter from
blacklist is present in the phrase return false;

Comparison should be case insensitive. Meaning 'A' == 'a'.

```<code>/**
     *
     * @param {string} blacklist
     * @param {string} phrase
     *
     * @returns {boolean}
     */
    function hasNoneLetters(blacklist, phrase) {
      console.log(blacklist)
      var x = phrase.includes(blacklist);
      if(x === false){
        return true
      }
      else{
        return false
      }

    }
</code>```

答:
```<code>/**
 *
 * @param {string} blacklist
 * @param {string} phrase
 *
 * @returns {boolean}
 */
function hasNoneLetters(blacklist, phrase) {
  console.log(blacklist)
  var phrase_parts = phrase.split(" ");
  for(var part of phrase_parts) {
    if (blacklist.includes(part)) {
      return false;
    }
  }
  return true;
}
</code>```

Body:
Return true if none of the letters in the blacklist
are present in the phrase. If at least one letter from
blacklist is present in the phrase return false;

Comparison should be case insensitive. Meaning 'A' == 'a'.

/**
     *
     * @param {string} blacklist
     * @param {string} phrase
     *
     * @returns {boolean}
     */
    function hasNoneLetters(blacklist, phrase) {
      console.log(blacklist)
      var x = phrase.includes(blacklist);
      if(x === false){
        return true
      }
      else{
        return false
      }

    }


答:
You need to check for every letter in the blacklist and not the full blacklist at once.

```<code>function hasNoneLetters(blacklist, phrase) {
  let lowerCasePhrase = phrase.toLowerCase();
  for (let letter of blacklist.toLowerCase()) {
    if (lowerCasePhrase.includes(letter)) return false
  }
  return true
}
</code>```

Also, you might want to use a Set where you insert all the letters of the phrase in to optimise the performance. This will get your running time from O(N*M) down to O(max(N, M)), where N and M are the lengths of the inputs.

Title: Return true if none of the letters in the blacklist

Body:
You need to check for every letter in the blacklist and not the full blacklist at once.

function hasNoneLetters(blacklist, phrase) {
  let lowerCasePhrase = phrase.toLowerCase();
  for (let letter of blacklist.toLowerCase()) {
    if (lowerCasePhrase.includes(letter)) return false
  }
  return true
}

Also, you might want to use a Set where you insert all the letters of the phrase in to optimise the performance. This will get your running time from O(N*M) down to O(max(N, M)), where N and M are the lengths of the inputs.


问:
Calculate the sub-solar point on the moon Skyfield
I am following these instructions on measuring crater height in my own moon images: http://www.astro.ex.ac.uk/obs/experiments/lunar/script.html

They require me to calculate the sub-Earth and sub-Solar points on the Moon when the image was taken.
Is there a way to do this in Skyfield? I can only find reference to this being done for sub-Solar points on the Earth using pyephem.

答:
The Skyfield documentation describes getting the lunar longitude and latitude of the sub-Earth point here:

https://rhodesmill.org/skyfield/planetary.html#computing-lunar-libration

It looks like if instead of (earth - moon) you also did the same thing but with the difference (sun - moon), you would get the sub-solar point on the Moon. I’d suggest trying each of those out, and seeing if the values you get back match example values from some other authority you could check against to make sure you're getting values that mean the same thing.

(And, if that approach works, let me know by responding here with a comment, and I'll update the documentation to add a heading to that page of the docs that explicitly mentions the word “sub-Earth point” or “sub-solar point” — since I don’t think the word “libration” makes it obvious to folks needing sub-points that the section will answer their question.)


问:
How to convert Android.Resource.Color to Android.Graphics.Color
I have a value of Android.Resource.Color like Android.Resource.Color.HoloOrangeDark.

I want to covert it to a Android.Graphics.Color.

How can I do that?

答:
Try this in Xamarin also

```<code>int colorIntFG = ContextCompat.GetColor(this, Resource.Color.colorCardDaysFGAlert);

txtView.SetTextColor(new Android.Graphics.Color(colorIntFG));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Try this in Xamarin also

int colorIntFG = ContextCompat.GetColor(this, Resource.Color.colorCardDaysFGAlert);

txtView.SetTextColor(new Android.Graphics.Color(colorIntFG));


问:
Exclude current observation from computation in dplyr pipe
I want to exclude the current observation from the function I am applying to my data in a dplyr pipe, because I want to know the value without this observation.

To keep it simple, let's compute the mean including the current observation and excluding this observation. The solution should be applicable to other computations or function (in my case, the Gini function from DescTools package).

Let's say we look at ice prices of three different ices (ice_id = ice identifier) at three different days (day).

```<code>da <- data.frame(ice_id = c(1,1,1,2,2,2,3,3,3), day = c(1,2,3,1,2,3,1,2,3), price = c(1.60,1.90,1.80,2.10,2.05,2.30,0.50,0.40,0.35))
da
  ice_id day price
1      1   1  1.60
2      1   2  1.90
3      1   3  1.80
4      2   1  2.10
5      2   2  2.05
6      2   3  2.30
7      3   1  0.50
8      3   2  0.40
9      3   3  0.35
</code>```

I want to add one column indicating the mean price of the ice including this day and one column indicating the mean price of the ice excluding this day.

```<code>da = da %>%
  group_by(ice_id) %>%
  mutate(mean_price = mean(price),
         mean_price_without = ?)
</code>```

How can I add the mean price without the current observation itself?

答:
An option using data.table

```<code>library(data.table)
setDT(da)[, .(mean_price = mean(price),
             mean_price_without = sapply(day, function(x) mean(price[-x]))), ice_id]
</code>```

Body:
I want to exclude the current observation from the function I am applying to my data in a dplyr pipe, because I want to know the value without this observation.

To keep it simple, let's compute the mean including the current observation and excluding this observation. The solution should be applicable to other computations or function (in my case, the Gini function from DescTools package).

Let's say we look at ice prices of three different ices (ice_id = ice identifier) at three different days (day).

da <- data.frame(ice_id = c(1,1,1,2,2,2,3,3,3), day = c(1,2,3,1,2,3,1,2,3), price = c(1.60,1.90,1.80,2.10,2.05,2.30,0.50,0.40,0.35))
da
  ice_id day price
1      1   1  1.60
2      1   2  1.90
3      1   3  1.80
4      2   1  2.10
5      2   2  2.05
6      2   3  2.30
7      3   1  0.50
8      3   2  0.40
9      3   3  0.35

I want to add one column indicating the mean price of the ice including this day and one column indicating the mean price of the ice excluding this day.

da = da %>%
  group_by(ice_id) %>%
  mutate(mean_price = mean(price),
         mean_price_without = ?)

How can I add the mean price without the current observation itself?

Body:
An option using data.table

library(data.table)
setDT(da)[, .(mean_price = mean(price),
             mean_price_without = sapply(day, function(x) mean(price[-x]))), ice_id]


答:
You aren't asking a question - with what are you struggling?

If you're wondering why your function isn't working, var x = phrase.includes(blacklist);, will only return true if the entire blacklist appears, in order, within phrase.


问:
working of fork in c language
Now I have a problem in understanding the working of fork() system call.
I write a code which is following :

```<code>#include<stdio.h>
int main()
{
    int a, b;
    b=fork();

    printf("\n the value of b = %d",b);
}
</code>```

The output of  this code is following :

Now I don't understand why the output is like this ?

After that i just add a line to my  code and output is completely different.
my code is following:

```<code>int main()
{
    int a, b;
    b=fork();
</code>```

When i run the code the output is following
 2389my name is manish

```<code> the value of b = 0
</code>```

Now I'm totally confused about the working of fork() call.

My question are following:

How fork() works?

Where the control goes after the fork() call?

Can any body explain why the outputs of codes written in problem?

Why the output of b occurring at different places means in first code
the output of b = 2260 is just before the output b = 0 while the value of b = 2389 is not just before the b = 0?

Please explain me the working of fork in the code written in the problem so that I can learn it properly .

答:
Forking is implemented by the OS.  It basically creates a child process and starts running it after the fork().

The parent process receives the process id of the file process: b=fork(); b has the process id.  The child process get a pid of zero.

(and 4) Because both process can either run in parallel or be time sliced, your output will vary.

You may want to check this out: http://en.wikipedia.org/wiki/Fork_(operating_system)

Title: working of fork in c language

Body:
Now I have a problem in understanding the working of fork() system call.
I write a code which is following :

#include<stdio.h>
int main()
{
    int a, b;
    b=fork();

    printf("\n the value of b = %d",b);
}

The output of  this code is following :

Now I don't understand why the output is like this ?

After that i just add a line to my  code and output is completely different.
my code is following:

int main()
{
    int a, b;
    b=fork();

When i run the code the output is following
 2389my name is manish

 the value of b = 0

Now I'm totally confused about the working of fork() call.

My question are following:

How fork() works?

Where the control goes after the fork() call?

Can any body explain why the outputs of codes written in problem?

Why the output of b occurring at different places means in first code
the output of b = 2260 is just before the output b = 0 while the value of b = 2389 is not just before the b = 0?

Please explain me the working of fork in the code written in the problem so that I can learn it properly .


问:
Swift constant defined with LET sometimes produces EXC_BAD_ACCESS (EXC_I386_GPFLT) on read (OSX)
In my AppDelegate I have a constant for a statusbar icon, used when the application is busy:

```<code>class AppDelegate: NSObject, NSApplicationDelegate {

let busyImage = NSImage(named: "BusyStatus");
...
</code>```

In another class I'm accessing this several times over the time the app is running. On a Macbook Air with SSD I sometimes get an

```<code>EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       EXC_I386_GPFLT

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   libswiftCore.dylib              0x0000000103876cf9 swift_unknownRetain + 41
1   de.test.myapp   0x000000010304743b TestApp.AppDelegate.busyImage.getter : ObjectiveC.NSImage? (in TestApp) (AppDelegate.swift:0)
2   de.test.myapp   0x0000000102f9aa77 TestApp.Sync.(update (TestApp.Sync) -> () -> ()).(closure #2) (in TestApp) (Sync.swift:271)
</code>```

The code there:

```<code>statusBarItem!.image = appDelegate!.busyImage
</code>```

It's in a block called in the Main Thread:

```<code>let updateBlock: () -> () = {

    appDelegate!.statusBarItem!.image = self.appDelegate!.busyImage
        [... other code ...]
 }

 if NSThread.isMainThread()
 {
     updateBlock()
 }
 else
 {
     dispatch_sync(dispatch_get_main_queue(),updateBlock)
 }
</code>```

What can cause this and how to avoid this?

答:
Hello People from the Internet,

My env is macOS 10.15.4 and I am running XCode 11.5 (11E608c) with Swift 5.

I have exactly the same issue with a little piece of code here which fails 100% of the time when using the rotation:

```<code>override func rotate(delta: float2) {
    let sensitivity: Float = 0.005
    rotation.y += delta.x * sensitivity    // FAILS with Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
    _viewMatrix = updateViewMatrix()
}
</code>```

This code does not look weird at all. rotation is a vector of floats defined in the Class as:

```<code>var rotation: float3 = [0, 0, 0]
</code>```

Now, I spent some time trying many versions of the same function and if I rewrite it as:

```<code>override func rotate(delta: float2) {
    let sensitivity: Float = 0.005
    var deltaX: Float = delta.x * sensitivity
    rotation.y += deltaX
    _viewMatrix = updateViewMatrix()
}
</code>```

it now runs smoothly. This is crazy since I see no obvious reason. I do not try to change a constant and even the linter advises me to change the var to let in deltaX definition.

I feel like this is a Swift issue but this is worrying for a 5th version of a language used by many.

I would update my answer if I find a solution or at least a valid explanation.

Live long and prosper lads!

Body:
In my AppDelegate I have a constant for a statusbar icon, used when the application is busy:

class AppDelegate: NSObject, NSApplicationDelegate {

let busyImage = NSImage(named: "BusyStatus");
...

In another class I'm accessing this several times over the time the app is running. On a Macbook Air with SSD I sometimes get an

EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       EXC_I386_GPFLT

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   libswiftCore.dylib              0x0000000103876cf9 swift_unknownRetain + 41
1   de.test.myapp   0x000000010304743b TestApp.AppDelegate.busyImage.getter : ObjectiveC.NSImage? (in TestApp) (AppDelegate.swift:0)
2   de.test.myapp   0x0000000102f9aa77 TestApp.Sync.(update (TestApp.Sync) -> () -> ()).(closure #2) (in TestApp) (Sync.swift:271)

The code there:

statusBarItem!.image = appDelegate!.busyImage

It's in a block called in the Main Thread:

let updateBlock: () -> () = {

    appDelegate!.statusBarItem!.image = self.appDelegate!.busyImage
        [... other code ...]
 }

 if NSThread.isMainThread()
 {
     updateBlock()
 }
 else
 {
     dispatch_sync(dispatch_get_main_queue(),updateBlock)
 }

What can cause this and how to avoid this?

Body:
Hello People from the Internet,

My env is macOS 10.15.4 and I am running XCode 11.5 (11E608c) with Swift 5.

I have exactly the same issue with a little piece of code here which fails 100% of the time when using the rotation:

override func rotate(delta: float2) {
    let sensitivity: Float = 0.005
    rotation.y += delta.x * sensitivity    // FAILS with Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
    _viewMatrix = updateViewMatrix()
}

This code does not look weird at all. rotation is a vector of floats defined in the Class as:

var rotation: float3 = [0, 0, 0]

Now, I spent some time trying many versions of the same function and if I rewrite it as:

override func rotate(delta: float2) {
    let sensitivity: Float = 0.005
    var deltaX: Float = delta.x * sensitivity
    rotation.y += deltaX
    _viewMatrix = updateViewMatrix()
}

it now runs smoothly. This is crazy since I see no obvious reason. I do not try to change a constant and even the linter advises me to change the var to let in deltaX definition.

I feel like this is a Swift issue but this is worrying for a 5th version of a language used by many.

I would update my answer if I find a solution or at least a valid explanation.

Live long and prosper lads!


问:
Error from server (RequestEntityTooLarge): Request entity too large: limit is 3145728 while creating a configMap
I use configMap to feed the init.sql script to initialise my Mysql container in the Kubernetes pod. While that works for most cases I am struggling to convert a larger init.sql file which is 12.2 MB.
I use the following in deployment.yaml to mount the configMap.

```<code>volumeMounts:
- name: init-volume
  mountPath: /docker-entrypoint-initdb.d
</code>```

```<code>volumes:
- name: init-volume
  configMap:
    defaultMode: 420
    name: init-volume
</code>```

The command I use to create the configMap

```<code>kubectl create configMap init-volume --from-file=init.sql
</code>```

I get the error

```<code>Error from server (RequestEntityTooLarge): Request entity too large: limit is 3145728
</code>```

How can I increase this limit/or any other alternate to initialise my database?

答:
How can I increase this limit/or any other alternate to initialise my database?

The .d nomenclature in that path means it will load all files found therein, so the solution is to chop up the init.sql into smaller chunks, name them so that they apply in the right order when viewed with /bin/ls -1, and stick each one into a configmap:

i=1
for fn in *.sql; do
   kubectl create configmap init-sql-$i --from-file="$fn"
   i=$(( i + 1 ))
done
```

<p>then volume mount them into the directory</p>

<pre class="lang-yaml prettyprint-override"><code>volumeMounts:
- name: init-file-1
  mountPath: /docker-entrypoint-initdb.d/file-1.sql
- name: init-file-2
  mountPath: /docker-entrypoint-initdb.d/file-2.sql
# and so forth
</code>```

Body:
I use configMap to feed the init.sql script to initialise my Mysql container in the Kubernetes pod. While that works for most cases I am struggling to convert a larger init.sql file which is 12.2 MB.
I use the following in deployment.yaml to mount the configMap.

volumeMounts:
- name: init-volume
  mountPath: /docker-entrypoint-initdb.d

volumes:
- name: init-volume
  configMap:
    defaultMode: 420
    name: init-volume

The command I use to create the configMap

kubectl create configMap init-volume --from-file=init.sql

I get the error

Error from server (RequestEntityTooLarge): Request entity too large: limit is 3145728

How can I increase this limit/or any other alternate to initialise my database?

Body:
How can I increase this limit/or any other alternate to initialise my database?

The .d nomenclature in that path means it will load all files found therein, so the solution is to chop up the init.sql into smaller chunks, name them so that they apply in the right order when viewed with /bin/ls -1, and stick each one into a configmap:

i=1
for fn in *.sql; do
   kubectl create configmap init-sql-$i --from-file="$fn"
   i=$(( i + 1 ))
done

then volume mount them into the directory

volumeMounts:
- name: init-file-1
  mountPath: /docker-entrypoint-initdb.d/file-1.sql
- name: init-file-2
  mountPath: /docker-entrypoint-initdb.d/file-2.sql
# and so forth


问:
Why is this python list storing only the last input elements
Please explain the following behavior

```<code>import sys
input=sys.stdin.readline

for _ in range(int(input())):
    n=int(input())
    m=int(input())
    vertices=[[0, 0]]*n
    edges=[[0, 0, 0]]*m
    for i in range(m):
        edges[i][0], edges[i][1], edges[i][2]=list(map(int, input().split()))
    for i in range(m):
        print(edges[i][0], edges[i][1], edges[i][2])
</code>```

When the following input is fed into the program:

```<code>1
5
7
1 2 1
2 3 2
2 4 6
5 2 1
5 1 3
4 5 2
3 4 3
</code>```

This output is being produced:

```<code>3 4 3
3 4 3
3 4 3
3 4 3
3 4 3
3 4 3
3 4 3
</code>```

Why is only the last inputs are being stored in all of the elements?

答:
Let's look at this interpreter session:

```<code>>>> a = [[0,0,0]] * 5
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0] = 1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]
</code>```

This is actually a common pitfall in Python. The code translates to something like this

```<code>inner = [0, 0, 0]
a = [inner, inner, inner, inner, inner]
</code>```

This way of writing makes it clearer that you actually create a list where all entries point to the same object (inner).

One way to fix this is to use a list comprehension, this way a new inner list will be created for each list entry:

```<code>vertices=[[0, 0] for _ in range(n)]
edges=[[0, 0, 0] for _ in range(m)]
</code>```

Another fix would be using numpy and declaring a 2D matrix using numpy.zeros(n, 2). Numpy is generally useful for math/numerics-intensive applications.

Body:
Please explain the following behavior

import sys
input=sys.stdin.readline

for _ in range(int(input())):
    n=int(input())
    m=int(input())
    vertices=[[0, 0]]*n
    edges=[[0, 0, 0]]*m
    for i in range(m):
        edges[i][0], edges[i][1], edges[i][2]=list(map(int, input().split()))
    for i in range(m):
        print(edges[i][0], edges[i][1], edges[i][2])

When the following input is fed into the program:

1
5
7
1 2 1
2 3 2
2 4 6
5 2 1
5 1 3
4 5 2
3 4 3

This output is being produced:

3 4 3
3 4 3
3 4 3
3 4 3
3 4 3
3 4 3
3 4 3

Why is only the last inputs are being stored in all of the elements?

Body:
Let's look at this interpreter session:

>>> a = [[0,0,0]] * 5
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0] = 1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]

This is actually a common pitfall in Python. The code translates to something like this

inner = [0, 0, 0]
a = [inner, inner, inner, inner, inner]

This way of writing makes it clearer that you actually create a list where all entries point to the same object (inner).

One way to fix this is to use a list comprehension, this way a new inner list will be created for each list entry:

vertices=[[0, 0] for _ in range(n)]
edges=[[0, 0, 0] for _ in range(m)]

Another fix would be using numpy and declaring a 2D matrix using numpy.zeros(n, 2). Numpy is generally useful for math/numerics-intensive applications.


问:
Ionic is it possible to console the value of stripe card fields
I am using stripe in my application i need to save the user credit card info is it any way to console the values like cardnumber , exp date, and cvc ?

Here is html code

```<code><div *ngIf="checkoutData.form.payment_method =='stripe'" class="stripe-payment">
  <form action="/charge" method="post" id="payment-form">
    <div class="form-row">

      <div id="card-element">
        <!-- A Stripe Element will be inserted here. -->
      </div>

      <!-- Used to display form errors. -->
      <div id="card-errors" class="card-error" role="alert"></div>
    </div>
  </form>
</div>
</code>```

Here is the onclick function

```<code>async onClickStripeSubmit() {
    var ownerInfo = {
        owner: {
            name: this.checkoutData.form.billing_first_name + ' ' + this.checkoutData.form.billing_last_name,
            address: {
                line1: this.checkoutData.form.billing_address_1,
                city: this.checkoutData.form.billing_city,
                postal_code: this.checkoutData.form.billing_postcode,
                country: 'US',
            },
            email: this.checkoutData.form.billing_email
        },
    };
    if (!this.checkoutData.form.shipping) {
            this.checkoutData.form.shipping_first_name = this.checkoutData.form.billing_first_name;
            this.checkoutData.form.shipping_last_name = this.checkoutData.form.billing_last_name;
            this.checkoutData.form.shipping_company = this.checkoutData.form.billing_company;
            this.checkoutData.form.shipping_address_1 = this.checkoutData.form.billing_address_1;
            this.checkoutData.form.shipping_address_2 = this.checkoutData.form.billing_address_2;
            this.checkoutData.form.shipping_city = this.checkoutData.form.billing_city;
            this.checkoutData.form.shipping_country = this.checkoutData.form.billing_country;
            this.checkoutData.form.shipping_state = this.checkoutData.form.billing_state;
            this.checkoutData.form.shipping_postcode = this.checkoutData.form.billing_postcode;
        }
        this.buttonSubmit = true;
        this.PlaceOrder = "Placing Order";
        this.loading = await this.loadingController.create({
            message: 'Loading...',
            translucent: true,
            animated: true,
            backdropDismiss: true
        });
        await this.loading.present();
        console.log(this.cardElement);
        this.stripe.createSource(this.cardElement, ownerInfo).then((result) => {
        console.log(ownerInfo);
        console.log(this.cardElement);
        console.log(result);
            if (result.error) {
                this.loading.dismiss();
                // Inform the user if there was an error
                var errorElement = document.getElementById('card-errors');
                errorElement.textContent = result.error.message;
            } else {
                this.checkoutData.form.stripe_source = result.source.id;
                 console.log(this.checkoutData.form.stripe_source);
                this.stripNewPayment();
            }
        });
}
</code>```

I need to console the value so i can save stripe result reponse is only giving the last 4 digit of card and date only. I need to crack this i dont know how but i need to save these inputs

答:
This is not something that can be done for security reasons and PCI compliance. Elements does not give you access to the raw card details. This is built to meet the requirements for PCI compliance and getting access to the raw card details would put you in a higher scope.

You should never need the raw card details from your customer. You can save the card on a Customer in your Stripe account so that you can charge them again in the future without having to ask for their card details again. This is documented in more details here: https://stripe.com/docs/payments/save-during-payment

Body:
I am using stripe in my application i need to save the user credit card info is it any way to console the values like cardnumber , exp date, and cvc ?

Here is html code

  <form action="/charge" method="post" id="payment-form">

  </form>

Here is the onclick function

async onClickStripeSubmit() {
    var ownerInfo = {
        owner: {
            name: this.checkoutData.form.billing_first_name + ' ' + this.checkoutData.form.billing_last_name,
            address: {
                line1: this.checkoutData.form.billing_address_1,
                city: this.checkoutData.form.billing_city,
                postal_code: this.checkoutData.form.billing_postcode,
                country: 'US',
            },
            email: this.checkoutData.form.billing_email
        },
    };
    if (!this.checkoutData.form.shipping) {
            this.checkoutData.form.shipping_first_name = this.checkoutData.form.billing_first_name;
            this.checkoutData.form.shipping_last_name = this.checkoutData.form.billing_last_name;
            this.checkoutData.form.shipping_company = this.checkoutData.form.billing_company;
            this.checkoutData.form.shipping_address_1 = this.checkoutData.form.billing_address_1;
            this.checkoutData.form.shipping_address_2 = this.checkoutData.form.billing_address_2;
            this.checkoutData.form.shipping_city = this.checkoutData.form.billing_city;
            this.checkoutData.form.shipping_country = this.checkoutData.form.billing_country;
            this.checkoutData.form.shipping_state = this.checkoutData.form.billing_state;
            this.checkoutData.form.shipping_postcode = this.checkoutData.form.billing_postcode;
        }
        this.buttonSubmit = true;
        this.PlaceOrder = "Placing Order";
        this.loading = await this.loadingController.create({
            message: 'Loading...',
            translucent: true,
            animated: true,
            backdropDismiss: true
        });
        await this.loading.present();
        console.log(this.cardElement);
        this.stripe.createSource(this.cardElement, ownerInfo).then((result) => {
        console.log(ownerInfo);
        console.log(this.cardElement);
        console.log(result);
            if (result.error) {
                this.loading.dismiss();
                // Inform the user if there was an error
                var errorElement = document.getElementById('card-errors');
                errorElement.textContent = result.error.message;
            } else {
                this.checkoutData.form.stripe_source = result.source.id;
                 console.log(this.checkoutData.form.stripe_source);
                this.stripNewPayment();
            }
        });
}

I need to console the value so i can save stripe result reponse is only giving the last 4 digit of card and date only. I need to crack this i dont know how but i need to save these inputs


问:
How can get my oracle sqlplus querys into .sql file
I run queries in SQLPlus. Now I want to get all queries into .sql file. how can I do it? please help me.</p>

答:
I don't think that you save all of them, but - you can one by one. Use save command.

```<code>SQL> select empno, ename, job sal
  2  from emp
  3  where deptno = 10;

     EMPNO ENAME      SAL
---------- ---------- ---------
      7782 CLARK      MANAGER
      7839 KING       PRESIDENT
      7934 MILLER     CLERK

SQL> save q1.sql replace
Wrote file q1.sql
</code>```

Only query gets saved, not its result:

```<code>SQL> $type q1.sql
select empno, ename, job sal
from emp
where deptno = 10
/

SQL>
</code>```

As you already closed SQL*Plus, check v$sql. In order to be able to use it, sys should grant you (i.e. the user which will query it) privilege to do so:

```<code>SQL> connect sys/pwd as sysdba
Connected.
SQL> grant select on v_$sql to scott;

Grant succeeded.

SQL> connect scott/tiger
Connected.
</code>```

You'd then spool result into a file:

```<code>SQL> spool q.sql
SQL> select sql_text
  2  from v$sql
  3  where to_date(first_load_time, 'yyyy-mm-dd hh24:mi:ss') >
  4        to_date('30.05.2020 20:50', 'dd.mm.yyyy hh24:mi')
  5    and parsing_schema_name = 'SCOTT';

SQL_TEXT
--------------------------------------------------------------------------------
select empno, ename, job sal from emp where deptno = 10

SQL> spool off
</code>```

Body:
I don't think that you save all of them, but - you can one by one. Use save command.

SQL> select empno, ename, job sal
  2  from emp
  3  where deptno = 10;

     EMPNO ENAME      SAL
---------- ---------- ---------
      7782 CLARK      MANAGER
      7839 KING       PRESIDENT
      7934 MILLER     CLERK

SQL> save q1.sql replace
Wrote file q1.sql

Only query gets saved, not its result:

SQL> $type q1.sql
select empno, ename, job sal
from emp
where deptno = 10
/

SQL>

As you already closed SQL*Plus, check v$sql. In order to be able to use it, sys should grant you (i.e. the user which will query it) privilege to do so:

SQL> connect sys/pwd as sysdba
Connected.
SQL> grant select on v_$sql to scott;

Grant succeeded.

SQL> connect scott/tiger
Connected.

You'd then spool result into a file:

SQL> spool q.sql
SQL> select sql_text
  2  from v$sql
  3  where to_date(first_load_time, 'yyyy-mm-dd hh24:mi:ss') >
  4        to_date('30.05.2020 20:50', 'dd.mm.yyyy hh24:mi')
  5    and parsing_schema_name = 'SCOTT';

SQL_TEXT
--------------------------------------------------------------------------------
select empno, ename, job sal from emp where deptno = 10

SQL> spool off