问:
Attach a policy to multiple iam roles
I need to attach a policy to all iam roles. however I dont want to add the policy or invoke the policy module in each role.

Can we use for_each as below to attach policy to each role in the list?

```<code>resource "aws_iam_role_policy_attachment" "test-attach" {
 for_each = toset(var.roles)
 role       = each.value
 policy_arn = "aws_iam_policy.test-attach[0].arn
}
</code>```

答:
Yes, you can do it this way, but your syntax for policy_arn should not be a half-quoted string:

```<code>resource "aws_iam_role_policy_attachment" "test-attach" {
 for_each = toset(var.roles)

 role       = each.value
 policy_arn = aws_iam_policy.test-attach[0].arn
}
</code>```

This assumes you have a list(string) of role names in var.roles.

Run a terraform plan to see if the result matches your expectation.

Title: Attach a policy to multiple iam roles

Body:
I need to attach a policy to all iam roles. however I dont want to add the policy or invoke the policy module in each role.

Can we use for_each as below to attach policy to each role in the list?

resource "aws_iam_role_policy_attachment" "test-attach" {
 for_each = toset(var.roles)
 role       = each.value
 policy_arn = "aws_iam_policy.test-attach[0].arn
}

Body:
Yes, you can do it this way, but your syntax for policy_arn should not be a half-quoted string:

resource "aws_iam_role_policy_attachment" "test-attach" {
 for_each = toset(var.roles)

 role       = each.value
 policy_arn = aws_iam_policy.test-attach[0].arn
}

This assumes you have a list(string) of role names in var.roles.

Run a terraform plan to see if the result matches your expectation.


来源: stackexchange

问:
lists of anagrams in python using two for loops
I need to write a function that takes a list of strings , and return a list that have lists of anagrams words. I need to use 2 for loops for that exercise. Words that are not anagrams to anything will be one item list inside the big list

example output:

```<code>>>> list_of_words = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']
>>> sort_anagrams(list_of_words)
[['deltas', 'desalt', 'slated', 'salted', 'staled', 'lasted'],
 ['retainers', 'ternaries'], ['pants'], ['generating', 'greatening'],
['smelters', 'termless', 'resmelts']]
</code>```

im getting the items sorted but dont know how to continue... heres my code:

```<code>def sort_anagrams(list_of_strings):
    sorted_list = list()
    temp_list = list()
    temp2_list = list()
    for item in list_of_strings:
        temp_list.append("".join(sorted(item)))
    print(temp_list)
</code>```

答:
hours later, i made it (:
ill post my answer here if someone will need it in the future. feel kinda stupid this simple thing took me so much time</p>

```<code>def sort_anagrams(list_of_strings):
    sorted_list = list()

    for item in list_of_strings:
        temp_list = list()
        for num in range(len(list_of_strings)):
            if sorted(item) == sorted(list_of_strings[num]) and (item not in sorted_list):
                temp_list.append(list_of_strings[num])
        sorted_list.append(temp_list)

    return(duplicate_remove(sorted_list))

def duplicate_remove(list_to_check):
    final_list = []
    for item in list_to_check:
        if item not in final_list:
            final_list.append(item)
    return final_list
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to write a function that takes a list of strings , and return a list that have lists of anagrams words. I need to use 2 for loops for that exercise. Words that are not anagrams to anything will be one item list inside the big list

example output:

>>> list_of_words = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']
>>> sort_anagrams(list_of_words)
[['deltas', 'desalt', 'slated', 'salted', 'staled', 'lasted'],
 ['retainers', 'ternaries'], ['pants'], ['generating', 'greatening'],
['smelters', 'termless', 'resmelts']]

im getting the items sorted but dont know how to continue... heres my code:

def sort_anagrams(list_of_strings):
    sorted_list = list()
    temp_list = list()
    temp2_list = list()
    for item in list_of_strings:
        temp_list.append("".join(sorted(item)))
    print(temp_list)

Body:
hours later, i made it (:
ill post my answer here if someone will need it in the future. feel kinda stupid this simple thing took me so much time

def sort_anagrams(list_of_strings):
    sorted_list = list()

    for item in list_of_strings:
        temp_list = list()
        for num in range(len(list_of_strings)):
            if sorted(item) == sorted(list_of_strings[num]) and (item not in sorted_list):
                temp_list.append(list_of_strings[num])
        sorted_list.append(temp_list)

    return(duplicate_remove(sorted_list))

def duplicate_remove(list_to_check):
    final_list = []
    for item in list_to_check:
        if item not in final_list:
            final_list.append(item)
    return final_list


问:
Record Date values based on another cell's value
I am a beginner in VBA.

I have a Column "A" can have multiple values, of which 2 are "Impact Assessed" or "Ready for retesting".

Problem Statement - I want to record the dates when cell's value is changed to Impact Assessed and Ready for Retesting in 2 separate columns - Column B and Column C, respectively.

Below is my code -

```<code>Private Sub Worksheet_Calculate()

Dim rng As Range
  If Target.CountLarge > 1 Then Exit Sub
Set rng = Application.Intersect(Me.Range("AA:AA"), Target)

If Not rng Is Nothing Then
    Select Case (rng.Value)
        Case "2 - Impact Assessed": rng.Offset(0, 1).Value = Date
        Case "4 - Ready for retesting": rng.Offset(0, 2).Value = Date
    End Select
End If
</code>```

End Sub

答:
You can use something like this:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range, c As Range
    'If Target.CountLarge > 1 Then Exit Sub
    Set rng = Application.Intersect(Me.Range("A:A"), Target)

    If Not rng Is Nothing Then
        For Each c in rng.cells
            Select Case LCase(c.Value)
                Case "impact assessed": c.Offset(0, 1).Value = Date
                Case "ready": c.Offset(0, 2).Value = Date
            End Select
        Next c
    End If
End Sub
</code>```

FYI = Range(Target.Address) is the same (in this case) as Target - no need to get the address just to turn that back into a range.

Body:
I am a beginner in VBA.

I have a Column "A" can have multiple values, of which 2 are "Impact Assessed" or "Ready for retesting".

Problem Statement - I want to record the dates when cell's value is changed to Impact Assessed and Ready for Retesting in 2 separate columns - Column B and Column C, respectively.

Below is my code -

Private Sub Worksheet_Calculate()

Dim rng As Range
  If Target.CountLarge > 1 Then Exit Sub
Set rng = Application.Intersect(Me.Range("AA:AA"), Target)

If Not rng Is Nothing Then
    Select Case (rng.Value)
        Case "2 - Impact Assessed": rng.Offset(0, 1).Value = Date
        Case "4 - Ready for retesting": rng.Offset(0, 2).Value = Date
    End Select
End If

End Sub

Body:
You can use something like this:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range, c As Range
    'If Target.CountLarge > 1 Then Exit Sub
    Set rng = Application.Intersect(Me.Range("A:A"), Target)

    If Not rng Is Nothing Then
        For Each c in rng.cells
            Select Case LCase(c.Value)
                Case "impact assessed": c.Offset(0, 1).Value = Date
                Case "ready": c.Offset(0, 2).Value = Date
            End Select
        Next c
    End If
End Sub

FYI = Range(Target.Address) is the same (in this case) as Target - no need to get the address just to turn that back into a range.


问:
How to select the most recent date for a specific condition in another column in Postgres?
I have a table with a structure like so.

```<code>id|subject|date
1 | email | june 1
1 | call  | may 29
1 | call  | may 15
2 | call  | may 17
2 | call  | may 20
</code>```

I'm trying to create a column with a query called most recent call which has the most recent call date for each id. Like this:

```<code>id|most_recent_call
1 |may 29
2 |may 20
</code>```

I just want to have the most recent date for each id out of all the rows where the subject column equals call

答:
You can just use conditional aggregation:

```<code>select id, max(date) filter(where subject = 'call') most_recent_call
from mytable
group by id
</code>```

This, of course, assumes that column date is of a date-like datatype (as it should be).

Body:
I have a table with a structure like so.

id|subject|date
1 | email | june 1
1 | call  | may 29
1 | call  | may 15
2 | call  | may 17
2 | call  | may 20

I'm trying to create a column with a query called most recent call which has the most recent call date for each id. Like this:

id|most_recent_call
1 |may 29
2 |may 20

I just want to have the most recent date for each id out of all the rows where the subject column equals call

Body:
You can just use conditional aggregation:

select id, max(date) filter(where subject = 'call') most_recent_call
from mytable
group by id

This, of course, assumes that column date is of a date-like datatype (as it should be).


问:
Mapping a Python dictionary to new attributes in an object
I want to map a subset of a dictionary to attributes of a class but with different names. For eg:

```<code>D = { "City" : {
                "Name": "Minneapolis",
                "Weather Forecast": "Sunny with chance of rain",
                "Temperature" : 55
               }
      "State": "MN",
      "Area Code": 651,
      "Country": "US"
    }
</code>```

I want to map the above dictionary to an Object with attributes "Name", "Forecast" and "AreaCode" with values of "Minneapolis", "Sunny with chance of rain" and 651 respectively while ignoring other keys. I also want these attributes to be None if the corresponding keys are not present in the dict. Is there an easy way and direct way to do this without explicitly checking for each specific key?

答:
```<code>from dataclasses import dataclass

@dataclass
class City:
    name: str
    forecast: str
    area_code: int

    @classmethod
    def from_dict(cls, data):
        name = data.get('City').get('Name')
        forecast = data.get('City').get('Weather Forecast')
        area_code = data.get('Area Code')
        return cls(name, forecast, area_code)

# regular use:
c1 = City('Greensboro', 'Sunny', 336)
print(c1)
City(name='Greensboro', forecast='Sunny', area_code=336)

D = { "City" : {
                "Name": "Minneapolis",
                "Weather Forecast": "Sunny with chance of rain",
                "Temperature" : 55
               },
      "State": "MN",
      "Area Code": 651,
      "Country": "US"
    }

# alternate constructor using a dictionary
c2 = City.from_dict(D)
print(c2)
City(name='Minneapolis', forecast='Sunny with chance of rain', area_code=651)
</code>```

Body:
I want to map a subset of a dictionary to attributes of a class but with different names. For eg:

D = { "City" : {
                "Name": "Minneapolis",
                "Weather Forecast": "Sunny with chance of rain",
                "Temperature" : 55
               }
      "State": "MN",
      "Area Code": 651,
      "Country": "US"
    }

I want to map the above dictionary to an Object with attributes "Name", "Forecast" and "AreaCode" with values of "Minneapolis", "Sunny with chance of rain" and 651 respectively while ignoring other keys. I also want these attributes to be None if the corresponding keys are not present in the dict. Is there an easy way and direct way to do this without explicitly checking for each specific key?


问:
Find and replace the text in a cell with Google Script and Google Sheets
I have a Google Sheet where I collect responses and another tab where I see a report for each record.

I want to add manually a number in the cell Writing Points (as in the image below) and click Update to update the cell of that specific record in the responses tab.

I managed to get the row number depending on the student the formula is:

MATCH($D$3,Responses!D:D, 0)

And the column is always BG of the repsonses tab.

How can I achieve this through Google script? I have an idea but I don't know how to do it.

My try:

```<code>row = MATCH($D$3,Responses!D:D, 0)
SpreadsheetApp.getActiveSheet().getRange('BG'+row).setValue(newwritingpoints);
</code>```

I don't know how to conver the match formula into Google script syntax and how to copy and paste the value from that cell to the responses tab.

Google Sheet link:

https://docs.google.com/spreadsheets/d/1dE6UVABhVp7WqEFdC0ptBK2ne6wEA6hCf0Wi6PxcMWE/edit#gid=2032966397

答:
I believe your goal as follows.

When Update() of Google Apps Script is run by the button, you want to retrieve the cells "D3" and "H24" in the sheet Report.

You want to search the value of "D3" from the column "D" in the sheet Responses.

When the value of "D3" and the values of column "D" in the sheet Responses are the same, you want to put the value of "H24" to the same row of the column "BG" in the sheet Responses.

For this, how about this answer? The flow of this sample script is as follows.

Retrieve the values from the cells "D3" and "H24" in the sheet Report.

Retrieve the values from the cells "D2:D" in the sheet Responses.

Create the range list from the retrieved values.

Put the value using the range list.

Sample script:

```<code>function Update() {
  var spreadsheet = SpreadsheetApp.getActive();

  // 1. Retrieve the values from the cells "D3" and "H24" in the sheet `Report`.
  var reportSheet = spreadsheet.getSheetByName("Report");
  var searchText = reportSheet.getRange("D3").getValue();
  var writingPoints = reportSheet.getRange("H24").getValue();

  // 2. Retrieve the values from the cells "D2:D" in the sheet `Responses`.
  var responsesSheet = spreadsheet.getSheetByName("Responses");
  var values = responsesSheet.getRange("D2:D" + responsesSheet.getLastRow()).getValues();

  // 3. Create the range list from the retrieved values.
  var ranges = values.reduce((ar, [d], i) => {
    if (d == searchText) ar.push("BG" + (i + 2));
    return ar;
  }, []);

  // 4. Put the value using the range list.
  responsesSheet.getRangeList(ranges).setValue(writingPoints);
}
</code>```

In this script, it also supposes the case that the value of "D3" might find at several rows in the sheet Responses.

References:

reduce()

Class RangeList

Body:
I have a Google Sheet where I collect responses and another tab where I see a report for each record.

I want to add manually a number in the cell Writing Points (as in the image below) and click Update to update the cell of that specific record in the responses tab.

I managed to get the row number depending on the student the formula is:

MATCH($D$3,Responses!D:D, 0)

And the column is always BG of the repsonses tab.

How can I achieve this through Google script? I have an idea but I don't know how to do it.

My try:

row = MATCH($D$3,Responses!D:D, 0)
SpreadsheetApp.getActiveSheet().getRange('BG'+row).setValue(newwritingpoints);

I don't know how to conver the match formula into Google script syntax and how to copy and paste the value from that cell to the responses tab.

Google Sheet link:

https://docs.google.com/spreadsheets/d/1dE6UVABhVp7WqEFdC0ptBK2ne6wEA6hCf0Wi6PxcMWE/edit#gid=2032966397

Body:
I believe your goal as follows.

When Update() of Google Apps Script is run by the button, you want to retrieve the cells "D3" and "H24" in the sheet Report.

You want to search the value of "D3" from the column "D" in the sheet Responses.

When the value of "D3" and the values of column "D" in the sheet Responses are the same, you want to put the value of "H24" to the same row of the column "BG" in the sheet Responses.

For this, how about this answer? The flow of this sample script is as follows.

Retrieve the values from the cells "D3" and "H24" in the sheet Report.

Retrieve the values from the cells "D2:D" in the sheet Responses.

Create the range list from the retrieved values.

Put the value using the range list.

Sample script:

function Update() {
  var spreadsheet = SpreadsheetApp.getActive();

  // 1. Retrieve the values from the cells "D3" and "H24" in the sheet `Report`.
  var reportSheet = spreadsheet.getSheetByName("Report");
  var searchText = reportSheet.getRange("D3").getValue();
  var writingPoints = reportSheet.getRange("H24").getValue();

  // 2. Retrieve the values from the cells "D2:D" in the sheet `Responses`.
  var responsesSheet = spreadsheet.getSheetByName("Responses");
  var values = responsesSheet.getRange("D2:D" + responsesSheet.getLastRow()).getValues();

  // 3. Create the range list from the retrieved values.
  var ranges = values.reduce((ar, [d], i) => {
    if (d == searchText) ar.push("BG" + (i + 2));
    return ar;
  }, []);

  // 4. Put the value using the range list.
  responsesSheet.getRangeList(ranges).setValue(writingPoints);
}

In this script, it also supposes the case that the value of "D3" might find at several rows in the sheet Responses.

References:

reduce()

Class RangeList


问:
Sum cols where row value is equal to header - Pandas
I am trying to sum columns in a pandas df where the column is equal to a specific value. Using the df below, where ['X'] == 'GrV', I want to sum cols ('GrV A', 'GrV B'). But I'm returning nan values.

```<code>import pandas as pd

df = pd.DataFrame({
    'X' : ['GrV', 'GrX', 'GrY', 'GrZ', 'GrV', 'GrX', 'GrY', 'GrZ'],
    'GrV A' : [4, 2, 6, 5, 1, 2, 5, 6],
    'GrX A' : [3, 4, 5, 1, 2, 5, 6, 2],
    'GrY A' : [5, 2, 2, 6, 5, 1, 5, 4],
    'GrZ A' : [1, 2, 5, 5, 2, 1, 5, 4],
    'GrV B' : [4, 2, 6, 5, 1, 2, 5, 6],
    'GrX B' : [3, 4, 5, 1, 2, 5, 6, 2],
    'GrY B' : [5, 2, 2, 6, 5, 1, 5, 4],
    'GrZ B' : [1, 2, 5, 5, 2, 1, 5, 4],
        })

df['Total'] = df.loc[(df['X'] == 'GrV'), ('GrV A', 'GrV B')].sum()
df['Total'] = df.loc[(df['X'] == 'GrX'), ('GrX A', 'GrX B')].sum()
df['Total'] = df.loc[(df['X'] == 'GrY'), ('GrY A', 'GrY B')].sum()
df['Total'] = df.loc[(df['X'] == 'GrZ'), ('GrZ A', 'GrZ B')].sum()
</code>```

Intended Output:

```<code>     X  GrV A  GrX A  GrY A  GrZ A  GrV B  GrX B  GrY B  GrZ B  Total
0  GrV      4      3      5      1      4      3      5      1      8
1  GrX      2      4      2      2      2      4      2      2      8
2  GrY      6      5      2      5      6      5      2      5      4
3  GrZ      5      1      6      5      5      1      6      5     10
4  GrV      1      2      5      2      1      2      5      2      2
5  GrX      2      5      1      1      2      5      1      1     10
6  GrY      5      6      5      5      5      6      5      5     10
7  GrZ      6      2      4      4      6      2      4      4      8
</code>```

答:
you can do it by using filter to get the columns Gr, use where the first element of column name obtained by split( to get the GrV, GrX, ... part) is equal to the column X and sum along the column:

```<code>df['Total'] = (df.filter(like='Gr')
                 .where(lambda x: df['X'].to_numpy()[:, None]
                                  == x.columns.str.split(' ').str[0].to_numpy())
                 .sum(axis=1)
              )
print (df)
     X  GrV A  GrX A  GrY A  GrZ A  GrV B  GrX B  GrY B  GrZ B  Total
0  GrV      4      3      5      1      4      3      5      1    8.0
1  GrX      2      4      2      2      2      4      2      2    8.0
2  GrY      6      5      2      5      6      5      2      5    4.0
3  GrZ      5      1      6      5      5      1      6      5   10.0
4  GrV      1      2      5      2      1      2      5      2    2.0
5  GrX      2      5      1      1      2      5      1      1   10.0
6  GrY      5      6      5      5      5      6      5      5   10.0
7  GrZ      6      2      4      4      6      2      4      4    8.0
</code>```

Body:
I am trying to sum columns in a pandas df where the column is equal to a specific value. Using the df below, where ['X'] == 'GrV', I want to sum cols ('GrV A', 'GrV B'). But I'm returning nan values.

import pandas as pd

df = pd.DataFrame({
    'X' : ['GrV', 'GrX', 'GrY', 'GrZ', 'GrV', 'GrX', 'GrY', 'GrZ'],
    'GrV A' : [4, 2, 6, 5, 1, 2, 5, 6],
    'GrX A' : [3, 4, 5, 1, 2, 5, 6, 2],
    'GrY A' : [5, 2, 2, 6, 5, 1, 5, 4],
    'GrZ A' : [1, 2, 5, 5, 2, 1, 5, 4],
    'GrV B' : [4, 2, 6, 5, 1, 2, 5, 6],
    'GrX B' : [3, 4, 5, 1, 2, 5, 6, 2],
    'GrY B' : [5, 2, 2, 6, 5, 1, 5, 4],
    'GrZ B' : [1, 2, 5, 5, 2, 1, 5, 4],
        })

df['Total'] = df.loc[(df['X'] == 'GrV'), ('GrV A', 'GrV B')].sum()
df['Total'] = df.loc[(df['X'] == 'GrX'), ('GrX A', 'GrX B')].sum()
df['Total'] = df.loc[(df['X'] == 'GrY'), ('GrY A', 'GrY B')].sum()
df['Total'] = df.loc[(df['X'] == 'GrZ'), ('GrZ A', 'GrZ B')].sum()

Intended Output:

     X  GrV A  GrX A  GrY A  GrZ A  GrV B  GrX B  GrY B  GrZ B  Total
0  GrV      4      3      5      1      4      3      5      1      8
1  GrX      2      4      2      2      2      4      2      2      8
2  GrY      6      5      2      5      6      5      2      5      4
3  GrZ      5      1      6      5      5      1      6      5     10
4  GrV      1      2      5      2      1      2      5      2      2
5  GrX      2      5      1      1      2      5      1      1     10
6  GrY      5      6      5      5      5      6      5      5     10
7  GrZ      6      2      4      4      6      2      4      4      8

Body:
you can do it by using filter to get the columns Gr, use where the first element of column name obtained by split( to get the GrV, GrX, ... part) is equal to the column X and sum along the column:

df['Total'] = (df.filter(like='Gr')
                 .where(lambda x: df['X'].to_numpy()[:, None]
                                  == x.columns.str.split(' ').str[0].to_numpy())
                 .sum(axis=1)
              )
print (df)
     X  GrV A  GrX A  GrY A  GrZ A  GrV B  GrX B  GrY B  GrZ B  Total
0  GrV      4      3      5      1      4      3      5      1    8.0
1  GrX      2      4      2      2      2      4      2      2    8.0
2  GrY      6      5      2      5      6      5      2      5    4.0
3  GrZ      5      1      6      5      5      1      6      5   10.0
4  GrV      1      2      5      2      1      2      5      2    2.0
5  GrX      2      5      1      1      2      5      1      1   10.0
6  GrY      5      6      5      5      5      6      5      5   10.0
7  GrZ      6      2      4      4      6      2      4      4    8.0


问:
Pass a range of ranges to a variadic function
The Phobos documentation shows the following example of ranges passed to a variadic function

```<code>int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
int[] c = [ 0, 1, 4, 5, 7, 8 ];
assert(equal(setIntersection(a, a), a));
assert(equal(setIntersection(a, b), [1, 2, 4, 7][]));
assert(equal(setIntersection(a, b, c), [1, 4, 7][]));
</code>```

But what if you have a range of ranges, and you don't know in advance how many elements it will contain, like

```<code>int[][] a = [[1,2,3,4],[1,2,4,5],[1,3,4,5]];
</code>```

The only thing I can think of is

```<code>if (a.length > 1) {
    auto res = array(setIntersection(a[0], a[1]));
    for (int i = 2; i < a.length; i++)
        res = array(setIntersection(res, a[i]));
    writeln(res);
}
</code>```

Which works. But I was hoping to be able to pass the argument directly to the function, like setIntersection(a.tupleof) or something like that (I know that tupleof doesn't work here).

答:
if you don't know how many elements a will have you won't be able to expand it into a tuple at compile time (and consequently pass it into a function)

so that for loop is your best bet (or implement your own setIntersection that can take a range of ranges)

ContentLicense: CC BY-SA 3.0

Body:
The Phobos documentation shows the following example of ranges passed to a variadic function

int[] a = [ 1, 2, 4, 5, 7, 9 ];
int[] b = [ 0, 1, 2, 4, 7, 8 ];
int[] c = [ 0, 1, 4, 5, 7, 8 ];
assert(equal(setIntersection(a, a), a));
assert(equal(setIntersection(a, b), [1, 2, 4, 7][]));
assert(equal(setIntersection(a, b, c), [1, 4, 7][]));

But what if you have a range of ranges, and you don't know in advance how many elements it will contain, like

int[][] a = [[1,2,3,4],[1,2,4,5],[1,3,4,5]];

The only thing I can think of is

if (a.length > 1) {
    auto res = array(setIntersection(a[0], a[1]));
    for (int i = 2; i < a.length; i++)
        res = array(setIntersection(res, a[i]));
    writeln(res);
}

Which works. But I was hoping to be able to pass the argument directly to the function, like setIntersection(a.tupleof) or something like that (I know that tupleof doesn't work here).


问:
How to create new variables on the basis of timepoints in R
I have problems creating new variables (V0, V1, V2) based on three timepoints (t0, t1, t2) in a long format data set. To run my analysis I need to separate the ratings which are at the moment in one column in a long format data set separated by timepoints . However, when I try to create a new variable for each timepoint, I obtain values for all three timepoints in each of the new variables instead of only the selected ones or an error message. Or instead of creating a new variable with only the scores of e.g. t0, all measurements in the df of t1 and t2 are excluded, probably due to the filter function I used. Probably the problem is also that my data is at the moment in the long format and the variables I try to create should be in a wide format.

I tried different variants of the following code:

```<code>NewVar1 <- df %>% group_by(subject) %>%
  mutate(NewVar1=Score[timepoint=="t0"]) %>% filter(timepoint!= "t1") %>% filter(N_cycle_phase!= "t2")
</code>```

This, I did for the three timepoints respectively.
I would be very grateful for any suggestions how to tackle this problem.

答:
It isn't clear what all your variables are but using reshape should work.

```<code>df%>%
dcast(variables_in_your_data_set_to_not_change ~ variable_to_change_to_width, value.var = "variable_name_of_values_to_be_changed")
</code>```

so something like

```<code>df%>%dcast(subject ~ timepoint, value.var = "Score")
</code>```

If you have other variables in your dataset, just add them after subject like subject + var2 + var3 ~ ... You then should have your three columns with separate timepoints.

You can rename those variables to be V0 ,V1, V2, if you want by using mutate:

```<code>library(dplyr)

    df%>%
    mutate(V0 = t0,
    V1 = t1,
    V2 = t2)

</code>```

Body:
I have problems creating new variables (V0, V1, V2) based on three timepoints (t0, t1, t2) in a long format data set. To run my analysis I need to separate the ratings which are at the moment in one column in a long format data set separated by timepoints . However, when I try to create a new variable for each timepoint, I obtain values for all three timepoints in each of the new variables instead of only the selected ones or an error message. Or instead of creating a new variable with only the scores of e.g. t0, all measurements in the df of t1 and t2 are excluded, probably due to the filter function I used. Probably the problem is also that my data is at the moment in the long format and the variables I try to create should be in a wide format.

I tried different variants of the following code:

NewVar1 <- df %>% group_by(subject) %>%
  mutate(NewVar1=Score[timepoint=="t0"]) %>% filter(timepoint!= "t1") %>% filter(N_cycle_phase!= "t2")

This, I did for the three timepoints respectively.
I would be very grateful for any suggestions how to tackle this problem.

Body:
It isn't clear what all your variables are but using reshape should work.

df%>%
dcast(variables_in_your_data_set_to_not_change ~ variable_to_change_to_width, value.var = "variable_name_of_values_to_be_changed")

so something like

df%>%dcast(subject ~ timepoint, value.var = "Score")

If you have other variables in your dataset, just add them after subject like subject + var2 + var3 ~ ... You then should have your three columns with separate timepoints.

You can rename those variables to be V0 ,V1, V2, if you want by using mutate:

library(dplyr)

    df%>%
    mutate(V0 = t0,
    V1 = t1,
    V2 = t2)


问:
MVC JS deletethisproduct is not defined at HTMLAnchorElement.onclick (VM457 Index:40)
i get this error when i click the button:

deletethisproduct is not defined at HTMLAnchorElement.onclick

i know it's not the best idea to use onclick but i'm using it because i want to get the product id from the model for this instance and pass it to the function

this is my link:

```<code><a href="#" class="btn btn-danger" onclick="deletethisproduct(@item.product_id)">Delete </a>
</code>```

and this is the js function:

```<code>@section scripts{
@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">

    var deletethisproduct = function (productid) {
        $.ajax({
            method: 'POST',
            url: "/Cart/deletecart",
            data: { "id": productid },
            success: function (data) {
                console.log(data);
                //  $("#mymodalBodyDiv").html(data);
            },
            error: function (msg) {
                alert("something wrong" + msg);
            }
        });
    }
</script>
}
</code>```

so why it's not defined ? and is there any other idea that can i get the product-id for this instance and pass it to the function without the onclick() ?

Edit: i think jquery is not read or something like that i don't know why although i am using it in another view with the same links!

```<code><button class="btn btn-dange mythis">this </button>
</code>```

i tried simply to alert from this button but nothing has happen no alert and no errors appeared in the console it also didn't say that "$" is not defined !

```<code>$('.mythis').click(function () {
        alert("hiiii")
    }
</code>```

答:
Try this using jquery

It's more easy to use jquery for that type of thing (I think).

The link :

```<code><a class="btn btn-danger delete" data-id="@item.product_id">Delete </a>
</code>```

The function :

```<code>@section scripts{
        @Scripts.Render("~/bundles/jquery")
        <script type="text/javascript">

            $('.delete').click(function(){
                var productid = $(this).attr("data-id");
                $.ajax({
                    method: 'POST',
                    url: "/Cart/deletecart",
                    data: { "id": productid },
                    success: function (data) {
                        console.log(data);
                        //  $("#mymodalBodyDiv").html(data);
                    },
                    error: function (msg) {
                        alert("something wrong" + msg);
                    }
                });
            });
        </script>
    }
</code>```

The "data-id" can be acces from jquery using .attr https://api.jquery.com/attr/

Body:
i get this error when i click the button:

deletethisproduct is not defined at HTMLAnchorElement.onclick

i know it's not the best idea to use onclick but i'm using it because i want to get the product id from the model for this instance and pass it to the function

this is my link:

Delete

and this is the js function:

@section scripts{
@Scripts.Render("~/bundles/jquery")

}

so why it's not defined ? and is there any other idea that can i get the product-id for this instance and pass it to the function without the onclick() ?

Edit: i think jquery is not read or something like that i don't know why although i am using it in another view with the same links!

<button class="btn btn-dange mythis">this </button>

i tried simply to alert from this button but nothing has happen no alert and no errors appeared in the console it also didn't say that "$" is not defined !

$('.mythis').click(function () {
        alert("hiiii")
    }

Body:
Try this using jquery

It's more easy to use jquery for that type of thing (I think).

The link :

<a class="btn btn-danger delete" data-id="@item.product_id">Delete </a>

The function :

@section scripts{
        @Scripts.Render("~/bundles/jquery")
        <script type="text/javascript">

            $('.delete').click(function(){
                var productid = $(this).attr("data-id");
                $.ajax({
                    method: 'POST',
                    url: "/Cart/deletecart",
                    data: { "id": productid },
                    success: function (data) {
                        console.log(data);
                        //  $("#mymodalBodyDiv").html(data);
                    },
                    error: function (msg) {
                        alert("something wrong" + msg);
                    }
                });
            });
        </script>
    }

The "data-id" can be acces from jquery using .attr https://api.jquery.com/attr/


问:
Picture loaded from Camera Roll too stretched in portrait mode
I am having trouble with UIView which is feeding by an image from Camera Roll.

When I pick a picture which was taken in the portrait mode the view always stretch the picture too high, but when I rotate my device the picture is stretched fine.

```

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if(info){
        {
            [artView removeFromSuperview];
            artView = nil;
            artView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

            artView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
            artView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
            artView.contentMode = UIViewContentModeScaleAspectFill;

[self.contentView addSubview:artView];

```

Any help is appreciated.

答:
Your code looks good except it leaks and you have too many opening braces and no closing braces.

You probably want it to look like this:

```<code>- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if (info) {
        [artView removeFromSuperview];
        artView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

        artView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
        artView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        artView.contentMode = UIViewContentModeScaleAspectFill;

        [self.contentView addSubview:artView];
        [artView release];
    }
}
</code>```

UIViewContentModeScaleAspectFill shouldn't stretch the image. It should clip it. Perhaps UIViewContentModeScaleAspectFit is what you're looking for?

Body:
I am having trouble with UIView which is feeding by an image from Camera Roll.

When I pick a picture which was taken in the portrait mode the view always stretch the picture too high, but when I rotate my device the picture is stretched fine.

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if(info){
        {
            [artView removeFromSuperview];
            artView = nil;
            artView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

            artView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
            artView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
            artView.contentMode = UIViewContentModeScaleAspectFill;

[self.contentView addSubview:artView];

Any help is appreciated.

Body:
Your code looks good except it leaks and you have too many opening braces and no closing braces.

You probably want it to look like this:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if (info) {
        [artView removeFromSuperview];
        artView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

        artView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
        artView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        artView.contentMode = UIViewContentModeScaleAspectFill;

        [self.contentView addSubview:artView];
        [artView release];
    }
}

UIViewContentModeScaleAspectFill shouldn't stretch the image. It should clip it. Perhaps UIViewContentModeScaleAspectFit is what you're looking for?


问:
Xcode settings problem when running simulator
I am very new to swift programming
I opened Xcode and changed some settings. one of which causes Xcode after exiting simulator to open AppDelegate and exit main.storyboard so I need every time to open it back again
how can I change that so after running simulator and exiting it stays at the main.storyboard screen unchanged???
thnx

答:
I think your app is somehow crashing and its throws you to app delegate.
Also do check if you pu any breakpoint there. Also check you set main interface in the settings


问:
How to ignore all css written outside of specific component of a large project?
I am having trouble localizing css within a very large project. Essentially, I had 2 products, to which I added a third product. However, for my third product, I used tailwind.

Now, I am having trouble only using the tailwind css and ignoring the rest of the css written across the app. How can I ignore the bootstrap and other css written across the app?

I've tried css resets, and I've also directly inputted the tailwind output but nothing has worked. Any advice/help would be awesome, thank you! (screenshots attached)

[1] https://imgur.com/a/AkuGNeP

答: delete bootstrap.min.css then clear your page's browser cache and u'll be all set </p>


问:
Productory with lambda function in Python
Suppose we have a function f(x) = f_1(x)f_2(x)...f_D(x). How can I implement this function f as a productory with a lambda function?

I need this to integrate a productory.

Example f_i = x[i]**m:

```<code> lambda m: x[0]**m*x[1]**m*x[2]**m....x[D-1]**m
</code>```

答:
If you really want to use lambda, you could pass one to functools.reduce:

```<code>from functools import reduce

def product_integrate(values, m):
    return reduce(lambda x, y: x * y ** m, values)
</code>```

Or as @chepner suggests in the comments, a more efficient solution would be to make use of operator.mul:

```<code>from functools import reduce
from operator import mul

def product_integrate(values, m):
    return reduce(mul, values) ** m
</code>```

Usage:

```<code>>>> product_integrate([1,2,3,4,5], 2)
14400
</code>```

Body:
Suppose we have a function f(x) = f_1(x)f_2(x)...f_D(x). How can I implement this function f as a productory with a lambda function?

I need this to integrate a productory.

Example f_i = x[i]**m:

 lambda m: x[0]**m*x[1]**m*x[2]**m....x[D-1]**m

Body:
If you really want to use lambda, you could pass one to functools.reduce:

from functools import reduce

def product_integrate(values, m):
    return reduce(lambda x, y: x * y ** m, values)

Or as @chepner suggests in the comments, a more efficient solution would be to make use of operator.mul:

from functools import reduce
from operator import mul

def product_integrate(values, m):
    return reduce(mul, values) ** m

Usage:

>>> product_integrate([1,2,3,4,5], 2)
14400


问:
Rspec test failed on Circle CI (Ruby on Rails 5.2.3)
Rspec test is success in development environment but it's failed on Circle CI.
I don't know　solution in this case.

This is test code and error code.

```<code>require 'rails_helper'
require 'webmock'

describe SuggestsController, type: :request do
  describe 'GET data by Ajax' do
    before do
      WebMock.stub_request(
        :get, "https://...........herokuapp.com...../api/suggests"
      ).with(
        headers: { 'Authorization' => 'Bearer api123' },
        query: hash_including({ :keyword => "ru", :max_num => "3" })
      ).to_return(
        body: ['ruby', 'ruby for women', 'ruby for men'].to_json,
        status: 200,
        headers: { 'Content-Type' => 'application/json' }
      )
    end

    it 'get response200' do
      get '/potepan/suggest'
      expect(response.status).to eq(200)
    end

    it 'Getting keyword "ru" you get 3 suggesting word ' do
      get '/potepan/suggest', params: { keyword: 'ru', max_num: 3 }
      expect(JSON.parse(response.body)).to eq ['ruby', 'ruby for women', 'ruby for men']
    end
  end
end
</code>```

this is controller

```<code>require 'httpclient'

class MyApp::SuggestsController < ApplicationController
  def suggest
    client = HTTPClient.new
    uri = Rails.application.credentials.api[:suggest_url]
    header = { "Authorization" => "Bearer #{Rails.application.credentials.api[:suggest_key]}" }
    query = {
      "keyword" => params[:keyword],
      "max_num" => params[:max_num],
    }
    response = client.get(uri, query, header)

    if response.status == 200
      render json: JSON.parse(response.body)
    else
      render json: [], status: response.status
    end
  end
end

</code>```

And this is error code

enter image description here

Accoding to error code Circle CI don't read credentials.yml.enc so I added
RAILS_MASTER_KEY: ${RAILS_MASTER_KEY}
like that in docker-compose.ci.yml

```<code>.......
    ports:
      - '3000:3000'
    environment:
      MYSQL_USERNAME: root
      MYSQL_PASSWORD: password
      MYSQL_HOST: mysql
      REDIS_URL: "redis://redis:6379"
      RAILS_MASTER_KEY: ${RAILS_MASTER_KEY}
    depends_on:
      - mysql
      - redis
    networks:
      - default
    command: bundle exec rails server -b 0.0.0.0
</code>```

but failed
and when I deploy this by using git push heroku, I can get suggesting word. so speculate that get suggeting word data by Ajax.
this is Jquery code

```<code>jQuery(document).ready(function() {
  $('.form-control').autocomplete({
    source: function(request, response) {
      $.ajax({
        type: 'GET',
        url: '/MyApp/suggest',
        data: {
          keyword: request.term,
          max_num: 5
        },
        dataType: "json"
      }).then(
        function(data) {
          response(data);
        },
        function(xhr, ts, err) {
          alert('${xhr.status}ERROR: ');
          $('.form-control').off();
        }
      );
    },
    atutoFocus: true
  });
});
</code>```

答:
The RAILS_MASTER_KEY should be added to your project's environment variables through their web app. Otherwise you would need to paste it directly into docker-compose.ci.yml which is certainly not recommended if you're committing this to a repo.

The actual RAILS_MASTER_KEY should be stored locally in a master.key file.

Relevant documentation: https://circleci.com/docs/2.0/env-vars/#:~:text=In%20the%20CircleCI%20application%2C%20go,enter%20a%20name%20and%20value.

Body:
Rspec test is success in development environment but it's failed on Circle CI.
I don't know　solution in this case.

This is test code and error code.

require 'rails_helper'
require 'webmock'

describe SuggestsController, type: :request do
  describe 'GET data by Ajax' do
    before do
      WebMock.stub_request(
        :get, "https://...........herokuapp.com...../api/suggests"
      ).with(
        headers: { 'Authorization' => 'Bearer api123' },
        query: hash_including({ :keyword => "ru", :max_num => "3" })
      ).to_return(
        body: ['ruby', 'ruby for women', 'ruby for men'].to_json,
        status: 200,
        headers: { 'Content-Type' => 'application/json' }
      )
    end

    it 'get response200' do
      get '/potepan/suggest'
      expect(response.status).to eq(200)
    end

    it 'Getting keyword "ru" you get 3 suggesting word ' do
      get '/potepan/suggest', params: { keyword: 'ru', max_num: 3 }
      expect(JSON.parse(response.body)).to eq ['ruby', 'ruby for women', 'ruby for men']
    end
  end
end

this is controller

require 'httpclient'

class MyApp::SuggestsController < ApplicationController
  def suggest
    client = HTTPClient.new
    uri = Rails.application.credentials.api[:suggest_url]
    header = { "Authorization" => "Bearer #{Rails.application.credentials.api[:suggest_key]}" }
    query = {
      "keyword" => params[:keyword],
      "max_num" => params[:max_num],
    }
    response = client.get(uri, query, header)

    if response.status == 200
      render json: JSON.parse(response.body)
    else
      render json: [], status: response.status
    end
  end
end

And this is error code

enter image description here

Accoding to error code Circle CI don't read credentials.yml.enc so I added
RAILS_MASTER_KEY: ${RAILS_MASTER_KEY}
like that in docker-compose.ci.yml

.......
    ports:
      - '3000:3000'
    environment:
      MYSQL_USERNAME: root
      MYSQL_PASSWORD: password
      MYSQL_HOST: mysql
      REDIS_URL: "redis://redis:6379"
      RAILS_MASTER_KEY: ${RAILS_MASTER_KEY}
    depends_on:
      - mysql
      - redis
    networks:
      - default
    command: bundle exec rails server -b 0.0.0.0

but failed
and when I deploy this by using git push heroku, I can get suggesting word. so speculate that get suggeting word data by Ajax.
this is Jquery code

jQuery(document).ready(function() {
  $('.form-control').autocomplete({
    source: function(request, response) {
      $.ajax({
        type: 'GET',
        url: '/MyApp/suggest',
        data: {
          keyword: request.term,
          max_num: 5
        },
        dataType: "json"
      }).then(
        function(data) {
          response(data);
        },
        function(xhr, ts, err) {
          alert('${xhr.status}ERROR: ');
          $('.form-control').off();
        }
      );
    },
    atutoFocus: true
  });
});


问:
purrr + dplyr NSE issues inside a user written function
After a lot of trial and error and consultation with previous answers such as How to detect if bare variable or string I think I have gotten most of what I need done myself.  But I'm eager to understand if I'm making some bad assumptions or approaching the problem foolishly before I carry my "solution" into production.

Consider the following data:

library(dplyr)
library(purrr)
library(tidyselect)

set.seed(1111)
dat1 <- data.frame(Region = rep(c("r1","r2"), each = 100),
                   State = rep(c("NY","MA","FL","GA"), each = 10),
                   Loc = rep(c("a","b","c","d","e","f","g","h"),each = 5),
                   ID = rep(c(1:10), each = 2),
                   var1 = rnorm(200),
                   var2 = rnorm(200),
                   var3 = rnorm(200),
                   var4 = rnorm(200),
                   var5 = rnorm(200))
```

<p>I want to write a function that does quite a few things but I'll start with a minimum reproducible example.  I want to get <code>tidied</code> <code>aov</code> results back either for a singular case <code>var1 ~ State</code> or for a pair of matched lists using <code>map2</code> with one list containing <em>"outcomes"</em> the other <em>"predictors"</em>.  They're never identical from use to use and the variables, unlike my example, rarely lend themselves to easy solutions like <code>starts_with</code>.</p>

<p>Two specific issues and a generic question.</p>

<p>Issue #1 - I've given up on allowing end users (including me) to pass in bare variable names always gets me in trouble later. In accordance with the reference above is something like my code the fastest most reliable way to catch them and tell the user? (I put a comment in the code to indicate where I'm talking about.</p>

<p>Issue #2 - Through basically trail and error I think I solved my other problem which is in generating some text for use later as a label.  I found lots of solutions when I'm not using the function with <code>map2</code> but only this one seems to work with map2.  It seems so convoluted I can't believe it's a good choice... (again comments in code to show where)</p>

<p>Generic question: I've added the recommended <code>tidyselect::all_of</code> because these might be ambiguous lists, why am I still having to guard against the <code>.x</code> and <code>.y</code> being seen as calls as opposed to just markers for iteration?</p>

<pre class="lang-r prettyprint-override"><code>MyFunction <- function(data,
                 groupvar,
                 var) {
  # Issue #1 is this best way to warn/stop user?
  lst <- as.list(match.call())

  if (is.symbol(lst$groupvar) || is.symbol(lst$var)) {
    stop("Please quote all variables")
  }

  # Issue #2 I want the group label but if I don't include
  # this if logic it errors with " Error: Can't convert a call to a string"
  # when I run it with purrr::map2
  if (!is.call(groupvar)) {
     grouplabel <- rlang::as_name(rlang::enquo(groupvar))
  }

  data <-
    dplyr::select(
      .data = data,
      var = {{ var }},
      groupvar = {{ groupvar }}
    )

  aov_object <- aov(var ~ groupvar, data = data)
  aov_results <- broom::tidy(aov_object) %>%
    mutate(term = if_else(term != "Residuals", grouplabel, term))
  return(aov_results)
}

# Expected output

MyFunction(data = dat1, groupvar = "State", var = "var1") # works
#> # A tibble: 2 x 6
#>   term         df  sumsq meansq statistic p.value
#>   <chr>     <dbl>  <dbl>  <dbl>     <dbl>   <dbl>
#> 1 State         3   1.75  0.582     0.485   0.693
#> 2 Residuals   196 235.    1.20     NA      NA

MyFunction(data = dat1, groupvar = State, var = var1) # warns appropriately
#> Error in MyFunction(data = dat1, groupvar = State, var = var1): Please quote all variables

# Quick test of `map2`
grouping_vars <- names(dat1[,1:3])
names(grouping_vars) <- names(dat1[,1:3])

outcome_vars <- names(dat1[,5:7])
names(outcome_vars) <- names(dat1[,5:7])

names(outcome_vars) <- paste(outcome_vars, "~", grouping_vars)

# get multiple results this is where issue #2 comes in but this is what I want it to look like.

map2(.x = outcome_vars,
     .y = grouping_vars,
     .f = ~ MyFunction(dat = dat1,
                 var = tidyselect::all_of(.x),
                 groupvar = tidyselect::all_of(.y)))
#> $`var1 ~ Region`
#> # A tibble: 2 x 6
#>   term         df    sumsq meansq statistic p.value
#>   <chr>     <dbl>    <dbl>  <dbl>     <dbl>   <dbl>
#> 1 Region        1   0.0512 0.0512    0.0427   0.836
#> 2 Residuals   198 237.     1.20     NA       NA
#>
#> $`var2 ~ State`
#> # A tibble: 2 x 6
#>   term         df  sumsq meansq statistic p.value
#>   <chr>     <dbl>  <dbl>  <dbl>     <dbl>   <dbl>
#> 1 State         3   5.05  1.68       2.07   0.106
#> 2 Residuals   196 159.    0.814     NA     NA
#>
#> $`var3 ~ Loc`
#> # A tibble: 2 x 6
#>   term         df  sumsq meansq statistic p.value
#>   <chr>     <dbl>  <dbl>  <dbl>     <dbl>   <dbl>
#> 1 Loc           7   5.09  0.727     0.772   0.612
#> 2 Residuals   192 181.    0.943    NA      NA
</code>```

答:
I have resolved issue #1.  Your function works whether the variable names are quoted or not.

```<code>MyFunction <- function(data,
                       groupvar,
                       var) {
  # Issue #1 is this best way to warn/stop user?
  lst <- as.list(match.call())

  if (is.symbol(lst$groupvar)) {
    q <- paste0("groupvar")
    varname <- expr('$'(lst,!!q))
    gval <- eval_tidy(varname)
    groupvarc <- as.character(gval)
  }else{groupvarc <- eval_tidy(lst$groupvar)}

  if (is.symbol(lst$var)) {
    v <- paste0("var")
    varnam <- expr('$'(lst,!!v))
    vval <- eval_tidy(varnam)
    varc <- as.character(vval)
  }else{varc <- eval_tidy(lst$var)}

  grouplabel <- groupvarc[1]

  data <- dplyr::select(.data = data,
                        var = varc[[1]],
                        groupvar = groupvarc[[1]] )

  aov_object <- aov(var ~ groupvar, data = data)
  aov_results <- broom::tidy(aov_object)  %>%
     mutate(term = if_else(term != "Residuals", grouplabel, term))
  return(aov_results)
}

MyFunction(data = dat1, groupvar = "State", var = "var1") # works

MyFunction(data = dat1, groupvar = State, var = var1) # Also works
</code>```

For multiple variables you will need to make it a function and cycle it through lapply.  Also, it will tidy up my repeating the same code two times for issue #1.  I hope this helps you to move forward.

Body:
After a lot of trial and error and consultation with previous answers such as How to detect if bare variable or string I think I have gotten most of what I need done myself.  But I'm eager to understand if I'm making some bad assumptions or approaching the problem foolishly before I carry my "solution" into production.

Consider the following data:

library(dplyr)
library(purrr)
library(tidyselect)

set.seed(1111)
dat1 <- data.frame(Region = rep(c("r1","r2"), each = 100),
                   State = rep(c("NY","MA","FL","GA"), each = 10),
                   Loc = rep(c("a","b","c","d","e","f","g","h"),each = 5),
                   ID = rep(c(1:10), each = 2),
                   var1 = rnorm(200),
                   var2 = rnorm(200),
                   var3 = rnorm(200),
                   var4 = rnorm(200),
                   var5 = rnorm(200))

I want to write a function that does quite a few things but I'll start with a minimum reproducible example.  I want to get tidied aov results back either for a singular case var1 ~ State or for a pair of matched lists using map2 with one list containing "outcomes" the other "predictors".  They're never identical from use to use and the variables, unlike my example, rarely lend themselves to easy solutions like starts_with.

Two specific issues and a generic question.

Issue #1 - I've given up on allowing end users (including me) to pass in bare variable names always gets me in trouble later. In accordance with the reference above is something like my code the fastest most reliable way to catch them and tell the user? (I put a comment in the code to indicate where I'm talking about.

Issue #2 - Through basically trail and error I think I solved my other problem which is in generating some text for use later as a label.  I found lots of solutions when I'm not using the function with map2 but only this one seems to work with map2.  It seems so convoluted I can't believe it's a good choice... (again comments in code to show where)

Generic question: I've added the recommended tidyselect::all_of because these might be ambiguous lists, why am I still having to guard against the .x and .y being seen as calls as opposed to just markers for iteration?

MyFunction <- function(data,
                 groupvar,
                 var) {
  # Issue #1 is this best way to warn/stop user?
  lst <- as.list(match.call())

  if (is.symbol(lst$groupvar) || is.symbol(lst$var)) {
    stop("Please quote all variables")
  }

  # Issue #2 I want the group label but if I don't include
  # this if logic it errors with " Error: Can't convert a call to a string"
  # when I run it with purrr::map2
  if (!is.call(groupvar)) {
     grouplabel <- rlang::as_name(rlang::enquo(groupvar))
  }

  data <-
    dplyr::select(
      .data = data,
      var = {{ var }},
      groupvar = {{ groupvar }}
    )

  aov_object <- aov(var ~ groupvar, data = data)
  aov_results <- broom::tidy(aov_object) %>%
    mutate(term = if_else(term != "Residuals", grouplabel, term))
  return(aov_results)
}

# Expected output

MyFunction(data = dat1, groupvar = "State", var = "var1") # works
#> # A tibble: 2 x 6
#>   term         df  sumsq meansq statistic p.value
#>   <chr>     <dbl>  <dbl>  <dbl>     <dbl>   <dbl>
#> 1 State         3   1.75  0.582     0.485   0.693
#> 2 Residuals   196 235.    1.20     NA      NA

MyFunction(data = dat1, groupvar = State, var = var1) # warns appropriately
#> Error in MyFunction(data = dat1, groupvar = State, var = var1): Please quote all variables

# Quick test of `map2`
grouping_vars <- names(dat1[,1:3])
names(grouping_vars) <- names(dat1[,1:3])

outcome_vars <- names(dat1[,5:7])
names(outcome_vars) <- names(dat1[,5:7])

names(outcome_vars) <- paste(outcome_vars, "~", grouping_vars)

# get multiple results this is where issue #2 comes in but this is what I want it to look like.

map2(.x = outcome_vars,
     .y = grouping_vars,
     .f = ~ MyFunction(dat = dat1,
                 var = tidyselect::all_of(.x),
                 groupvar = tidyselect::all_of(.y)))
#> $`var1 ~ Region`
#> # A tibble: 2 x 6
#>   term         df    sumsq meansq statistic p.value
#>   <chr>     <dbl>    <dbl>  <dbl>     <dbl>   <dbl>
#> 1 Region        1   0.0512 0.0512    0.0427   0.836
#> 2 Residuals   198 237.     1.20     NA       NA
#>
#> $`var2 ~ State`
#> # A tibble: 2 x 6
#>   term         df  sumsq meansq statistic p.value
#>   <chr>     <dbl>  <dbl>  <dbl>     <dbl>   <dbl>
#> 1 State         3   5.05  1.68       2.07   0.106
#> 2 Residuals   196 159.    0.814     NA     NA
#>
#> $`var3 ~ Loc`
#> # A tibble: 2 x 6
#>   term         df  sumsq meansq statistic p.value
#>   <chr>     <dbl>  <dbl>  <dbl>     <dbl>   <dbl>
#> 1 Loc           7   5.09  0.727     0.772   0.612
#> 2 Residuals   192 181.    0.943    NA      NA

Body:
I have resolved issue #1.  Your function works whether the variable names are quoted or not.

MyFunction <- function(data,
                       groupvar,
                       var) {
  # Issue #1 is this best way to warn/stop user?
  lst <- as.list(match.call())

  if (is.symbol(lst$groupvar)) {
    q <- paste0("groupvar")
    varname <- expr('$'(lst,!!q))
    gval <- eval_tidy(varname)
    groupvarc <- as.character(gval)
  }else{groupvarc <- eval_tidy(lst$groupvar)}

  if (is.symbol(lst$var)) {
    v <- paste0("var")
    varnam <- expr('$'(lst,!!v))
    vval <- eval_tidy(varnam)
    varc <- as.character(vval)
  }else{varc <- eval_tidy(lst$var)}

  grouplabel <- groupvarc[1]

  data <- dplyr::select(.data = data,
                        var = varc[[1]],
                        groupvar = groupvarc[[1]] )

  aov_object <- aov(var ~ groupvar, data = data)
  aov_results <- broom::tidy(aov_object)  %>%
     mutate(term = if_else(term != "Residuals", grouplabel, term))
  return(aov_results)
}

MyFunction(data = dat1, groupvar = "State", var = "var1") # works

MyFunction(data = dat1, groupvar = State, var = var1) # Also works

For multiple variables you will need to make it a function and cycle it through lapply.  Also, it will tidy up my repeating the same code two times for issue #1.  I hope this helps you to move forward.


问:
it is need to calculate the coordinate of the intersection point that is between the road and the designated distance from the starting point
Knowning the coordinate of the starting point on a road ，it is need to calculate the coordinate of the intersection point that is between the road and the designated distance from the starting point。This kind of question just like the SDO-LRS.LOCATE_PT function in oracle spatial 。Does have the similiar API on GeoTools or neo4j spatial?</p>

答:
I just pushed some code to Neoj4-Spatial to wrap the JTS method LengthIndexedLine.extractPoint with a new method locatePoint that behaves the same as the Oracle SDO_LRS.LOCATE_PT methods. So, at least on trunk, Neo4j-Spatial now has this capability. In reality the code for this is trivial, since it wraps the JTS code, so the capabilities have always been there, but now look a little more like the Oracle API.

The previously mentioned GSoC projects will try to standardize the API somewhat, so that a more complete set of functions is available in an intuitive way.


问:
Curl Error 56 in PHP when sending Request Web Service
I send a REQUEST through SOAP to a Web Service that has a self-signed certificate, for which I apply the following functions so that it is omitted

```<code>        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 0,
</code>```

But I get the following error code:

```<code>CURL error: 56
</code>```

Do some research and according to the Curl (https://curl.haxx.se/libcurl/c/libcurl-errors.html) error listing this is due to Failure with receiving network data.

What other function can I apply so that this error is overcome?

```<code>        $curl_options = array(
        CURLOPT_URL => $url,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_TIMEOUT =>20

    );
</code>```

答:
I solved the problem by adding SOAPAction in my header:</p>

```<code>$headers = array("Content-type: text/xml;charset=\"utf-8\"", "Accept: text/xml", "SOAPAction: http://direccion.com/Crear", "Content-length: ".strlen($xml), );
</code>```

Body:
I send a REQUEST through SOAP to a Web Service that has a self-signed certificate, for which I apply the following functions so that it is omitted

        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 0,

But I get the following error code:

CURL error: 56

Do some research and according to the Curl (https://curl.haxx.se/libcurl/c/libcurl-errors.html) error listing this is due to Failure with receiving network data.

What other function can I apply so that this error is overcome?

        $curl_options = array(
        CURLOPT_URL => $url,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_TIMEOUT =>20

    );

Body:
I solved the problem by adding SOAPAction in my header:

$headers = array("Content-type: text/xml;charset=\"utf-8\"", "Accept: text/xml", "SOAPAction: http://direccion.com/Crear", "Content-length: ".strlen($xml), );


问:
Tuples: No matching function for call to 'get'
I have 3 structs : Student, Citizen, Employee. I want user to be able to choose what struct they want to work with (std::vector of structs, actually). Since there's no way to define type at runtime, I created all 3 vectors, but will use only one of them (depending on the user's choice), others will stay empty:

```<code>std::vector<Student> container_student;
std::vector<Citizen> container_citizen;
std::vector<Employee> container_employee;
auto containers = make_tuple(container_student, container_citizen, container_employee);
std::cout << "Enter:\n0 to operate \"Student\" struct\n1 to operate \"Citizen\" struct\n2 to operate \"Employee\" struct\n";
std::cin >> container_type;
auto container = std::get<container_type>(containers);
</code>```

But I get No matching function for call to 'get', even though container_type is an int and containers is a tuple.

Edit: understandable, auto can't make magic and I still try to make container's type to depend on runtime. But even if I try to use std::get<container_type>(containers) (probably define would help) instead of container in functions etc., I get the same error, which is not understandable.

答:
Unfortunately, what you're proposing isn't possible in C++. The C++ typing and template system works at compile-time, where information read in from the user isn't available. As a result, anything passed into a template's angle braces needs to be determinable at compile-time. In your case, the number the user enters, indicating which option they want to select, is only knowable at runtime.

There are some routes you could take to achieve the same result, though. For example, one option would be to do something like this:

```<code>if (container_type == 0) {
    auto container = std::get<0>(containers);
    /* ... */
} else if (container_type == 1) {
    auto container = std::get<1>(containers);
    /* ... */
} /* etc */
</code>```

Here, all the template angle braces are worked out at compile-time. (Then again, if this is what you're going to be doing, you wouldn't need the tuple at all. ^_^)

Another option would be to use templates, like this:

```<code>template <typename T> void doSomething(std::vector<T>& container) {
    /* Put your code here */
}

/* Then, back in main... */

if (container_type == 0) {
    doSomething(container_student);
} else if (container_type == 1) {
    doSomething(container_citizen);
} /* etc */
</code>```

This still requires you to insert some code to map from integer types to the functions you want to call, but it leaves you the freedom to have a container variable (the one in doSomething) that you can treat generically at that point.

It's basically the Fundamental Theorem of Software Engineering in action - all problems can be solved by adding another layer of indirection. :-)

Hope this helps!

Body:
I have 3 structs : Student, Citizen, Employee. I want user to be able to choose what struct they want to work with (std::vector of structs, actually). Since there's no way to define type at runtime, I created all 3 vectors, but will use only one of them (depending on the user's choice), others will stay empty:

std::vector<Student> container_student;
std::vector<Citizen> container_citizen;
std::vector<Employee> container_employee;
auto containers = make_tuple(container_student, container_citizen, container_employee);
std::cout << "Enter:\n0 to operate \"Student\" struct\n1 to operate \"Citizen\" struct\n2 to operate \"Employee\" struct\n";
std::cin >> container_type;
auto container = std::get<container_type>(containers);

But I get No matching function for call to 'get', even though container_type is an int and containers is a tuple.

Edit: understandable, auto can't make magic and I still try to make container's type to depend on runtime. But even if I try to use std::get<container_type>(containers) (probably define would help) instead of container in functions etc., I get the same error, which is not understandable.

Body:
Unfortunately, what you're proposing isn't possible in C++. The C++ typing and template system works at compile-time, where information read in from the user isn't available. As a result, anything passed into a template's angle braces needs to be determinable at compile-time. In your case, the number the user enters, indicating which option they want to select, is only knowable at runtime.

There are some routes you could take to achieve the same result, though. For example, one option would be to do something like this:

if (container_type == 0) {
    auto container = std::get<0>(containers);
    /* ... */
} else if (container_type == 1) {
    auto container = std::get<1>(containers);
    /* ... */
} /* etc */

Here, all the template angle braces are worked out at compile-time. (Then again, if this is what you're going to be doing, you wouldn't need the tuple at all. ^_^)

Another option would be to use templates, like this:

template <typename T> void doSomething(std::vector<T>& container) {
    /* Put your code here */
}

/* Then, back in main... */

if (container_type == 0) {
    doSomething(container_student);
} else if (container_type == 1) {
    doSomething(container_citizen);
} /* etc */

This still requires you to insert some code to map from integer types to the functions you want to call, but it leaves you the freedom to have a container variable (the one in doSomething) that you can treat generically at that point.

It's basically the Fundamental Theorem of Software Engineering in action - all problems can be solved by adding another layer of indirection. :-)

Hope this helps!


问:
I want to copy only the last one of the text in the input box using js or jquery
The logic for copying the value of the input box when clicking the input box is as follows.

<input type="text" value="{{p.filename}}" id="file_{{p.id}}" size=100 onclick="copy_for_file_name({{p.id}})">

function copy_for_file_name(id){
    var copyText = document.getElementById("file_"+id);
    copyText.select();
    copyText.setSelectionRange(0, 99999); /*For mobile devices*/
    document.execCommand("copy");
    // alert("copy is completed")
}
```

<p>At this time, if the value of the input box is </p>

```challenge/templates/challenge/challenge_list.html
```

Can the code be modified so that only challenge_list.html is copied
when the onclick event is executed?

答:
Here's a way how you could do it:

function copy_for_file_name(id){
    var copyText = document.getElementById("file_"+id);
    // get the original text value
    const org = copyText.value;
    const match = org.match(/\/([^/]+?\.\w+)\s*$/);
    if(match) {
      // if found file name, replace with it temporarily
      copyText.value = match[1];
    }
    copyText.select();
    copyText.setSelectionRange(0, 99999); /*For mobile devices*/
    document.execCommand("copy");
    // restore the text value
    copyText.value = org;
    alert("copy is completed")
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" value="challenge/templates/challenge/challenge_list.html" id="file_1" size=100 onclick="copy_for_file_name(1)"></code>```

Body:
The logic for copying the value of the input box when clicking the input box is as follows.

<input type="text" value="{{p.filename}}" id="file_{{p.id}}" size=100 onclick="copy_for_file_name({{p.id}})">

function copy_for_file_name(id){
    var copyText = document.getElementById("file_"+id);
    copyText.select();
    copyText.setSelectionRange(0, 99999); /*For mobile devices*/
    document.execCommand("copy");
    // alert("copy is completed")
}

At this time, if the value of the input box is

challenge/templates/challenge/challenge_list.html

Can the code be modified so that only challenge_list.html is copied
when the onclick event is executed?

Body:
Here's a way how you could do it:

function copy_for_file_name(id){
    var copyText = document.getElementById("file_"+id);
    // get the original text value
    const org = copyText.value;
    const match = org.match(/\/([^/]+?\.\w+)\s*$/);
    if(match) {
      // if found file name, replace with it temporarily
      copyText.value = match[1];
    }
    copyText.select();
    copyText.setSelectionRange(0, 99999); /*For mobile devices*/
    document.execCommand("copy");
    // restore the text value
    copyText.value = org;
    alert("copy is completed")
}

<input type="text" value="challenge/templates/challenge/challenge_list.html" id="file_1" size=100 onclick="copy_for_file_name(1)">


问:
I don't want to reload the page with post request
I create form, the popup window (in the same file with the form) and the script that creates the post request when the user clicks the button, but when I click the button the page relaoded automatically and the popup window never appears

*I want to pass a parameter from the form to popup window in order to identify the product that the user selected.

My code is below:

*The form is inside of a loop in order to create many items

index.php

```<code>while($row = mysqli_fetch_assoc($select_all_products)) {
    $product_id = $row['id'];
    $product_name = $row['name'];
    $product_price1 = $row['price1'];
    $product_price2 = $row['price2'];
    $product_price3 = $row['price3'];
    $product_image= $row['photo'];

        ?>

         <div class="col-lg-6 col-md-6 item-entry mb-4">
         <form method="post" >
            <a href="#" class="product-item md-height bg-gray d-block">
            <?php  echo "<img width='300px' height='300px' src='images/$product_image'  alt='Image' class='img-fluid'>"; ?>
            </a>
            <h2 class="item-title"><a href="#"><?php echo $product_name; ?></a></h2>
            <input  id="id" type="hidden" name="id" value="<?php echo $product_id; ?>">
            <label>shop1: </label>
              <strong class="item-price"><?php echo $product_price1 ."\xE2\x82\xAc".str_repeat(' ', 5) ; ?></strong>
                <label>shop2 </label>
              <strong class="item-price"><?php echo $product_price2 ."\xE2\x82\xAc".str_repeat(' ', 5) ; ?></strong>
                <label>shop3 </label>
              <strong class="item-price"><?php echo $product_price3 ."\xE2\x82\xAc" .str_repeat(' ', 3) ; ?></strong>

            <button  type="submit" onclick="loadData(this.getAttribute('data-id'));" data-id="<?php echo $product_id; ?>" class="btn btn-primary btn-sm rounded" data-toggle="modal" data-target="#myModal">Change Price<i class="fas fa-tags"></i></button>
        </form>
        </div>

<?php
    }
?>
</code>```

popup window :

```<code><!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
</code>```

script :

```<code><script type="application/javascript">
    function loadData(id) {
        id.preventDefault();
        $.ajax({
            url: "price.php",
            method: "POST",
            data: {get_data: 1, id: id},
            success: function (response) {
                console.log(response);
            }
        });
    }
</script>
</code>```

From the console log I found that the post request send it but with reload page and for this reason the the popup window never appears. 1

What I can do in order the page not reloaded ,the pop up appeared get the post request?
Thank you

答:
To prevent the form from being submitted and hence the page refresh, you should call preventDefault on the form's onsubmit event, like this: <form method="post" onsubmit="event.preventDefault()">. It also works returning false like this: <form method="post" onsubmit="return false">.

I've made an example with the php part removed so you can see. Hope this helps.

Body:
I create form, the popup window (in the same file with the form) and the script that creates the post request when the user clicks the button, but when I click the button the page relaoded automatically and the popup window never appears

*I want to pass a parameter from the form to popup window in order to identify the product that the user selected.

My code is below:

*The form is inside of a loop in order to create many items

index.php

while($row = mysqli_fetch_assoc($select_all_products)) {
    $product_id = $row['id'];
    $product_name = $row['name'];
    $product_price1 = $row['price1'];
    $product_price2 = $row['price2'];
    $product_price3 = $row['price3'];
    $product_image= $row['photo'];

        ?>

         <form method="post" >

            <?php  echo ""; ?>

<?php echo $product_name; ?>

            <input  id="id" type="hidden" name="id" value="<?php echo $product_id; ?>">
            shop1:
              <?php echo $product_price1 ."\xE2\x82\xAc".str_repeat(' ', 5) ; ?>
                shop2
              <?php echo $product_price2 ."\xE2\x82\xAc".str_repeat(' ', 5) ; ?>
                shop3
              <?php echo $product_price3 ."\xE2\x82\xAc" .str_repeat(' ', 3) ; ?>

            <button  type="submit" onclick="loadData(this.getAttribute('data-id'));" data-id="<?php echo $product_id; ?>" class="btn btn-primary btn-sm rounded" data-toggle="modal" data-target="#myModal">Change Price</button>
        </form>

<?php
    }
?>

popup window :

        <button type="button" class="close" data-dismiss="modal">×Close</button>

Modal title

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

script :

From the console log I found that the post request send it but with reload page and for this reason the the popup window never appears. 1

What I can do in order the page not reloaded ,the pop up appeared get the post request?
Thank you


问:
Best way to test FileNotFound handling
I'm relatively new to testing and still getting my head around some of the fundamentals. I have a method that I would like to test which basically creates a different file name if the supplied already exists (I've pasted the code below).

I need a way of testing that the method returns a different (but also unique) name if the file already exists. What's the best way of testing this within Visual Studio's unit testing? Is it to create a file as part of the test and then delete it or is there a better way?

```<code>public static FileInfo SafeFileName(this FileInfo value)
{
    if (value == null) throw new ArgumentNullException("value");

    FileInfo fi = value;

    //Check the directory exists -if it doesn't create it as we won't move out of this dir
    if (!fi.Directory.Exists)
        fi.Directory.Create();

    //It does so create a new name
    int counter = 1;
    string pathStub = Path.Combine(fi.Directory.FullName, fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length));

    // Keep renaming it until we have a safe filename
    while (fi.Exists)
        fi = new FileInfo(String.Concat(pathStub, "_", counter++, fi.Extension));

    return fi;
}
</code>```

答:
Here are two testing methods (using a Visual Studio unit testing project) for the two scenarios:

```<code>    // using System.IO;

    [TestMethod]
    public void WhenFileExists()
    {
        // Create a file
        string existingFilename = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
        using (File.Open(existingFilename, FileMode.CreateNew)) { }

        // Check its existence
        Assert.IsTrue(File.Exists(existingFilename));

        // Call method to be tested
        string newFilename = DummyCreateFile(existingFilename);

        // Check filenames are different
        Assert.AreNotEqual<string>(existingFilename, newFilename);

        // Check the new file exists
        Assert.IsTrue(File.Exists(newFilename));
    }

    [TestMethod]
    public void WhenFileDoesNotExist()
    {
        // Get a filename but do not create it yet
        string existingFilename = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

        // Check the file does not exist
        Assert.IsFalse(File.Exists(existingFilename));

        // Call method to be tested
        string newFilename = DummyCreateFile(existingFilename);

        // Check the file was created with the filename passed as parameter
        Assert.AreEqual<string>(existingFilename, newFilename);

        // Check the new file exists
        Assert.IsTrue(File.Exists(newFilename));
    }

    private string DummyCreateFile(string filename)
    {
        try
        {
            using (File.Open(filename, FileMode.CreateNew)) { }
            return filename;
        }
        catch
        {
            string newFilename = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            using (File.Open(newFilename, FileMode.CreateNew)) { }
            return newFilename;
        }
    }
</code>```

The tested method is slightly changed in that it takes (and returns) a string argument instead of FileInfo for simplicity reasons.

Title: Best way to test FileNotFound handling

Body:
I'm relatively new to testing and still getting my head around some of the fundamentals. I have a method that I would like to test which basically creates a different file name if the supplied already exists (I've pasted the code below).

I need a way of testing that the method returns a different (but also unique) name if the file already exists. What's the best way of testing this within Visual Studio's unit testing? Is it to create a file as part of the test and then delete it or is there a better way?

public static FileInfo SafeFileName(this FileInfo value)
{
    if (value == null) throw new ArgumentNullException("value");

    FileInfo fi = value;

    //Check the directory exists -if it doesn't create it as we won't move out of this dir
    if (!fi.Directory.Exists)
        fi.Directory.Create();

    //It does so create a new name
    int counter = 1;
    string pathStub = Path.Combine(fi.Directory.FullName, fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length));

    // Keep renaming it until we have a safe filename
    while (fi.Exists)
        fi = new FileInfo(String.Concat(pathStub, "_", counter++, fi.Extension));

    return fi;
}

Body:
Here are two testing methods (using a Visual Studio unit testing project) for the two scenarios:

    // using System.IO;

    [TestMethod]
    public void WhenFileExists()
    {
        // Create a file
        string existingFilename = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
        using (File.Open(existingFilename, FileMode.CreateNew)) { }

        // Check its existence
        Assert.IsTrue(File.Exists(existingFilename));

        // Call method to be tested
        string newFilename = DummyCreateFile(existingFilename);

        // Check filenames are different
        Assert.AreNotEqual<string>(existingFilename, newFilename);

        // Check the new file exists
        Assert.IsTrue(File.Exists(newFilename));
    }

    [TestMethod]
    public void WhenFileDoesNotExist()
    {
        // Get a filename but do not create it yet
        string existingFilename = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

        // Check the file does not exist
        Assert.IsFalse(File.Exists(existingFilename));

        // Call method to be tested
        string newFilename = DummyCreateFile(existingFilename);

        // Check the file was created with the filename passed as parameter
        Assert.AreEqual<string>(existingFilename, newFilename);

        // Check the new file exists
        Assert.IsTrue(File.Exists(newFilename));
    }

    private string DummyCreateFile(string filename)
    {
        try
        {
            using (File.Open(filename, FileMode.CreateNew)) { }
            return filename;
        }
        catch
        {
            string newFilename = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            using (File.Open(newFilename, FileMode.CreateNew)) { }
            return newFilename;
        }
    }

The tested method is slightly changed in that it takes (and returns) a string argument instead of FileInfo for simplicity reasons.


问:
Why switching to alert through selenium is not stable?
Why switching to alert through selenium is not stable?

For example.

1. Run a code and all good.  Everything worked out well.
But if this code is run in a few minutes, then there may be errors.
There is no element you can click on, for example. And so on.

2. On one site there is an alert window.

```<code>alert = driver.switch_to_alert()
alert.dismiss()
</code>```

So I close it. But he works through time. All is well, then errors.

```<code>for al in range(3):
    try:
        alert = driver.switch_to_alert()
        alert.dismiss()
        time.sleep(randint(1, 3))
    except:
        pass
</code>```

I wrote and everything works out as it should.

But I think that this is not beautiful.

Why is everything so unstable?

Thank you very much.

答:
This will click the OK button on the alert:

```<code>driver.switch_to.alert.accept()
</code>```

This will click the CANCEL button on the alert:

```<code>driver.switch_to.alert.dismiss()
</code>```

Body:
Why switching to alert through selenium is not stable?

For example.

1. Run a code and all good.  Everything worked out well.
But if this code is run in a few minutes, then there may be errors.
There is no element you can click on, for example. And so on.

2. On one site there is an alert window.

alert = driver.switch_to_alert()
alert.dismiss()

So I close it. But he works through time. All is well, then errors.

for al in range(3):
    try:
        alert = driver.switch_to_alert()
        alert.dismiss()
        time.sleep(randint(1, 3))
    except:
        pass

I wrote and everything works out as it should.

But I think that this is not beautiful.

Why is everything so unstable?

Thank you very much.

Body:
This will click the OK button on the alert:

driver.switch_to.alert.accept()

This will click the CANCEL button on the alert:

driver.switch_to.alert.dismiss()


问:
Don't Validate untouched fields in Formik and Yup on submitting if field is not empty
I have this validation schema for a form made using withFormik() used in my React application, Here validateJql() is my custom validation function for yup

```<code>validationSchema: Yup.object().shape({
            rework: Yup.string().required("Rework query is required").validateJql(),
            originalEstimate: Yup.string().required("Original Estimate query is required").validateJql()
        })
</code>```

and my form Component is like this:

```<code>const addSomeForm = (props) => {
    const {
        values,
        touched,
        errors,
        isSubmitting,
        handleChange,
        handleSubmit,
    } = props;

return (
        <form onSubmit={handleSubmit}>
             <div className="form-group">
                  <div>
                      <label htmlFor="name" className="col-form-label"><b>Rework Query:</b></label>
                      <textarea id="query.rework" rows="5" type="text" className="form-control" placeholder="Enter JQL with aggregate Function" value={values.query.rework} onChange={handleChange} required />
                       {errors.query && errors.query.rework && touched.query && <span className="alert label"> <strong>{errors.query.rework}</strong></span>}
                   </div>
             </div>
             <div className="form-group">
                 <div>
                      <label htmlFor="name" className="col-form-label"><b>Original Estimate:</b></label>
                       <textarea id="query.originalEstimate" rows="5" type="text" className="form-control" placeholder="Enter JQL with aggregate Function" value={values.query.originalEstimate} onChange={handleChange} required />
                       {errors.query && errors.query.originalEstimate && touched.query && <span className="alert label"> <strong>{errors.query.originalEstimate}</strong></span>}
                 </div>
             </div>
       </form>
    )
</code>```

Now, what I want to do is not to run validation on form submit if the field rework and originalEstimate is not touched and also not empty. How can I achieve this with withFormik HOC or Yup? I have partially been through Yup docs and Formik docs but could not find something to fit with my problem.

This is the case after submitting the form once and editing after that for minor tweaks in some of those multiple fields. if there are multiple fields and only some are edited, I don't want to run validation for all the fields existed.

Thank you in advance.

答:
This is the default desired behavior as stated in formik docs but i think you can do the following:

Instead of using validationSchema, use validate function.

Validate function will work the same way your validationSchema works. You just need to use Yup programmatically from a function with mixed.validate

So you can have the full control of all the props in your form. You could also use the getFieldMeta to get the touched and value of the field and use that in your validation. Or get those props from touched object in form with getIn

Something like:

```<code>
// Some util functions
function mapYupErrorsToFormikErrors(err: { inner: any[] }) {
  return err.inner
    .filter((i: { path: any }) => !!i.path)
    .reduce(
      (curr: any, next: { path: any; errors: any[] }) => ({
        ...curr,
        [next.path]: next.errors[0],
      }),
      {},
    )
}

function validateSchema(values: object, schema: Schema<object>) {
  return schema
    .validate(values, {
      abortEarly: false,
      strict: false,
    })
    .then(() => {
      return {}
    })
    .catch(mapYupErrorsToFormikErrors)
}

// Your validation function, as you are using `withFormik` you will have the props present

function validateFoo(values, props) {
  const { touched, value } = props.getFieldMeta('fooFieldName') // (or props.form.getFieldmeta, not sure)

  const errors = validateSchema(values, yourYupSchema)

  if (!touched && !value && errors.fooFieldName) {
    delete errors.fooFieldName
  }

  return errors
}

</code>```

Well, touched might not work for your use case because formik probably would set it to true on submission, but there you have all the props and you can use something different, like the empty value or some other state prop you manually set. You got all the control there.

Body:
I have this validation schema for a form made using withFormik() used in my React application, Here validateJql() is my custom validation function for yup

validationSchema: Yup.object().shape({
            rework: Yup.string().required("Rework query is required").validateJql(),
            originalEstimate: Yup.string().required("Original Estimate query is required").validateJql()
        })

and my form Component is like this:

const addSomeForm = (props) => {
    const {
        values,
        touched,
        errors,
        isSubmitting,
        handleChange,
        handleSubmit,
    } = props;

return (
        <form onSubmit={handleSubmit}>

                      Rework Query:
                      <textarea id="query.rework" rows="5" type="text" className="form-control" placeholder="Enter JQL with aggregate Function" value={values.query.rework} onChange={handleChange} required />
                       {errors.query && errors.query.rework && touched.query &&  {errors.query.rework}}

                      Original Estimate:
                       <textarea id="query.originalEstimate" rows="5" type="text" className="form-control" placeholder="Enter JQL with aggregate Function" value={values.query.originalEstimate} onChange={handleChange} required />
                       {errors.query && errors.query.originalEstimate && touched.query &&  {errors.query.originalEstimate}}

       </form>
    )

Now, what I want to do is not to run validation on form submit if the field rework and originalEstimate is not touched and also not empty. How can I achieve this with withFormik HOC or Yup? I have partially been through Yup docs and Formik docs but could not find something to fit with my problem.

This is the case after submitting the form once and editing after that for minor tweaks in some of those multiple fields. if there are multiple fields and only some are edited, I don't want to run validation for all the fields existed.

Thank you in advance.

Body:
This is the default desired behavior as stated in formik docs but i think you can do the following:

Instead of using validationSchema, use validate function.

Validate function will work the same way your validationSchema works. You just need to use Yup programmatically from a function with mixed.validate

So you can have the full control of all the props in your form. You could also use the getFieldMeta to get the touched and value of the field and use that in your validation. Or get those props from touched object in form with getIn

Something like:

// Some util functions
function mapYupErrorsToFormikErrors(err: { inner: any[] }) {
  return err.inner
    .filter((i: { path: any }) => !!i.path)
    .reduce(
      (curr: any, next: { path: any; errors: any[] }) => ({
        ...curr,
        [next.path]: next.errors[0],
      }),
      {},
    )
}

function validateSchema(values: object, schema: Schema<object>) {
  return schema
    .validate(values, {
      abortEarly: false,
      strict: false,
    })
    .then(() => {
      return {}
    })
    .catch(mapYupErrorsToFormikErrors)
}

// Your validation function, as you are using `withFormik` you will have the props present

function validateFoo(values, props) {
  const { touched, value } = props.getFieldMeta('fooFieldName') // (or props.form.getFieldmeta, not sure)

  const errors = validateSchema(values, yourYupSchema)

  if (!touched && !value && errors.fooFieldName) {
    delete errors.fooFieldName
  }

  return errors
}

Well, touched might not work for your use case because formik probably would set it to true on submission, but there you have all the props and you can use something different, like the empty value or some other state prop you manually set. You got all the control there.


问:
Bash versus Zsh: An Array Question with Example
Here is an example of an array that works in Bash but not Zsh. Can someone explain why it fails and what the suitable syntax for Zsh would be to get the same results?

I know bash is index 0 and Zsh is index 1 but Im not understanding how this applies in this context.

```<code>#!/bin/bash
USER_LIST=$( ls /Users | grep -v -e 'Shared' -e 'Guest' )

for TARGET_USER in "${USER_LIST[@]}"; do
    TARGET_FILE="/Users/${TARGET_USER}/Library/Application Support/foo/example.txt"
    if [[ -e "$TARGET_FILE" ]]; then
        echo "The file '$TARGET_FILE' exists for user '$TARGET_USER'. It will be deleted now..."
        rm -f "$TARGET_FILE"
    else
         echo "The file '$TARGET_FILE' does NOT exist for user '$TARGET_USER'. No action required."
    fi
done
</code>```

答:
Use a glob to define the array.</p>

```<code># bash
shopt -s extglob
USER_LIST=( /Users/!(Shared|Guest) )
USER_LIST=( "${USER_LIST[@]#/Users/}" )

# zsh
setopt kshglob
USER_LIST=( /Users/!(Shared|Guest) )
USER_LIST=($USER_LIST:t)
</code>```

Body:
Here is an example of an array that works in Bash but not Zsh. Can someone explain why it fails and what the suitable syntax for Zsh would be to get the same results?

I know bash is index 0 and Zsh is index 1 but Im not understanding how this applies in this context.

#!/bin/bash
USER_LIST=$( ls /Users | grep -v -e 'Shared' -e 'Guest' )

for TARGET_USER in "${USER_LIST[@]}"; do
    TARGET_FILE="/Users/${TARGET_USER}/Library/Application Support/foo/example.txt"
    if [[ -e "$TARGET_FILE" ]]; then
        echo "The file '$TARGET_FILE' exists for user '$TARGET_USER'. It will be deleted now..."
        rm -f "$TARGET_FILE"
    else
         echo "The file '$TARGET_FILE' does NOT exist for user '$TARGET_USER'. No action required."
    fi
done

Body:
Use a glob to define the array.

# bash
shopt -s extglob
USER_LIST=( /Users/!(Shared|Guest) )
USER_LIST=( "${USER_LIST[@]#/Users/}" )

# zsh
setopt kshglob
USER_LIST=( /Users/!(Shared|Guest) )
USER_LIST=($USER_LIST:t)


问:
How to passing parameter from component.ts to server.ts using ionic angular?
I want to get the id from route and use it in my detail_kejadian function to get data from database.
it shows error Undefined index id, and Http failure during parsing for..
What's wrong with it?

This is my component.ts file

```<code>export class DetailkejadianComponent implements OnInit {

  constructor(public ks:KejadianService, public route:ActivatedRoute) { }

  ngOnInit() {

    var idkejadian:number=this.route.snapshot.params['id'];
    this.detail_Kejadian(idkejadian);
  }

  detailkej = [];

  detail_Kejadian(id){
    this.ks.detailKejadian(id).subscribe(
      (data) => {this.detailkej = data}
    );
  }

}
</code>```

this is the function in my service.ts file

```<code>  detailKejadian(idkejadian):Observable<any> {

    return this.http.get("http://localhost/matawarga/detailkejadian.php?id=idkejadian");

  }
}
</code>```

答:
You are not passing the argument in your detailKejadian method, this string you use in this.http.get is always the same.

You could concatenate the value like this:

```<code>detailKejadian(idkejadian):Observable<any> {

    return this.http.get(`http://localhost/matawarga/detailkejadian.php?id=${idkejadian}`);

}
</code>```

Notice the use of backticks ()  instead of apostrophes or double quotes, and the template literal${idkejadian}`.

You could also configure the http request.

Body:
I want to get the id from route and use it in my detail_kejadian function to get data from database.
it shows error Undefined index id, and Http failure during parsing for..
What's wrong with it?

This is my component.ts file

export class DetailkejadianComponent implements OnInit {

  constructor(public ks:KejadianService, public route:ActivatedRoute) { }

  ngOnInit() {

    var idkejadian:number=this.route.snapshot.params['id'];
    this.detail_Kejadian(idkejadian);
  }

  detailkej = [];

  detail_Kejadian(id){
    this.ks.detailKejadian(id).subscribe(
      (data) => {this.detailkej = data}
    );
  }

}

this is the function in my service.ts file

  detailKejadian(idkejadian):Observable<any> {

    return this.http.get("http://localhost/matawarga/detailkejadian.php?id=idkejadian");

  }
}

Body:
You are not passing the argument in your detailKejadian method, this string you use in this.http.get is always the same.

You could concatenate the value like this:

detailKejadian(idkejadian):Observable<any> {

    return this.http.get(`http://localhost/matawarga/detailkejadian.php?id=${idkejadian}`);

}

Notice the use of backticks ()  instead of apostrophes or double quotes, and the template literal${idkejadian}`.

You could also configure the http request.


问:
TortoiseHg - cmdserver: timed out
I'm getting the following error with pretty much any operation with TortoiseHg - commit, push, update. Lots of people seem to get code 255 but I haven't found much if anything on code 0 (or perhaps code -1). Anybody know a solution? Command line works fine, as does SourceTree (though the latter is hideously slow).

Windows 7 64 bit, TortoiseHg version 4.1.1, Mercurial 4.1.1, Python 2.7.10, PyQt-4.11.4, Qt-4.8.7. I would tag this tortoise-hg but apparently that doesn't exist and I don't have the rep to create it.

答:
I found the answer here: https://groups.google.com/forum/#!topic/mercurial-ja/1bskOMqLDmw and translated.

Try increasing the timeout for now. The default is 5 seconds.

[tortoisehg]
  cmdserver.readtimeout = 300

If this helps, I think the hg process is stalled for some reason. If
  it doesn't, there may be dust in the interprocess communication.

Note that readtimeout is the timeout for inter-process communication,
  so it has nothing to do with the time required for pull processing.

Add the following to your .hgrc file for the repository affected

```<code>[tortoisehg]
cmdserver.readtimeout = 300
</code>```

It worked for me - no more dust ;)

Title: TortoiseHg - cmdserver: timed out

Body:
I found the answer here: https://groups.google.com/forum/#!topic/mercurial-ja/1bskOMqLDmw and translated.

Try increasing the timeout for now. The default is 5 seconds.

[tortoisehg]
  cmdserver.readtimeout = 300

If this helps, I think the hg process is stalled for some reason. If
  it doesn't, there may be dust in the interprocess communication.

Note that readtimeout is the timeout for inter-process communication,
  so it has nothing to do with the time required for pull processing.

Add the following to your .hgrc file for the repository affected

[tortoisehg]
cmdserver.readtimeout = 300

It worked for me - no more dust ;)


问:
A better class to update property files?
Though java.util.properties allows reading and writing properties file, the writing does not preserve the formatting. Not surprising, because it is not tied to the property file.

Is there a PropertyFile class out there -- or some such -- that preserves comments and blank lines and updates property values in place?

答:
Just in response to Jince Martin who was having trouble with trailing spaces in the written properties files e.g. key = value instead of key=value.

You can call layout.setGlobalSeparator("=") to get around this.

OwnerDisplayName: Hemal Pandya