问:
How to sort (to group) unique data using SQL only, without PHP?
In order to retrieve some unique data from a table, I use the following code:

```<code>$query = $this->Controller->AnotherController->find('all', array('fields' => ['id', 'name', 'email']));
$query->hydrate(false);
$data = $query->distinct()->toArray();
</code>```

This call gives me data in this format:

```<code>[
    (int) 0 => [
        'id' => '1',
        'name' => 'somename',
        'email' => 'example@example.com'
    ],
    (int) 1 => [
        'id' => '2',
        'name' => 'anothername',
        'email' => 'anotherexample@example.com'
    ]
]
</code>```

I want to receive this data in such format:

```<code>[
        (string) 'id' => ['1', '2'],
        (string) 'name' => ['name', 'anothername'],
        (string) 'email' => ['example@example.com', 'anotherexample@example.com']
]
</code>```

Is it possible to do that using SQL only? I mean without post-sorting.

答:
Something like group_concat is the way to go here.
https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html

What it basically does, is to concat a field with a separator (default is comma) while grouping results based on a certain field. In your case you can add a pseudo-field with a value, which you can use to group the whole query.

```<code>SELECT GROUP_CONCAT(id) as id, GROUP_CONCAT(email) as email, 1 as pseudo_field from yourtable group by pseudo_field;
</code>```

Now your part: You have to find out, how to implement it nicely into your PHP-framework model, if you need to ;-)

Body:
In order to retrieve some unique data from a table, I use the following code:

$query = $this->Controller->AnotherController->find('all', array('fields' => ['id', 'name', 'email']));
$query->hydrate(false);
$data = $query->distinct()->toArray();

This call gives me data in this format:

[
    (int) 0 => [
        'id' => '1',
        'name' => 'somename',
        'email' => 'example@example.com'
    ],
    (int) 1 => [
        'id' => '2',
        'name' => 'anothername',
        'email' => 'anotherexample@example.com'
    ]
]

I want to receive this data in such format:

[
        (string) 'id' => ['1', '2'],
        (string) 'name' => ['name', 'anothername'],
        (string) 'email' => ['example@example.com', 'anotherexample@example.com']
]

Is it possible to do that using SQL only? I mean without post-sorting.

Body:
Something like group_concat is the way to go here.
https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html

What it basically does, is to concat a field with a separator (default is comma) while grouping results based on a certain field. In your case you can add a pseudo-field with a value, which you can use to group the whole query.

SELECT GROUP_CONCAT(id) as id, GROUP_CONCAT(email) as email, 1 as pseudo_field from yourtable group by pseudo_field;

Now your part: You have to find out, how to implement it nicely into your PHP-framework model, if you need to ;-)


来源: stackexchange

问:
Convert string[] to Int[] without losing leading zeros
Input:

```<code>string param = "1100,1110,0110,0001";
</code>```

Output:

```<code>int[] matrix = new[]
    {
              1,1,0,0,
              1,1,1,0,
              0,1,1,0,
              0,0,0,1
    };
</code>```

What I did?

First of all I splited string to string[].

```<code>string[] resultantArray = param.Split(',');
</code>```

Created one method, where I passed my string[].

```<code>var intArray = toIntArray(resultantArray);

static private int[] toIntArray(string[] strArray)
{
    int[] intArray = new int[strArray.Length];
    for (int i = 0; i < strArray.Length; i++)
    {
        intArray[i] = int.Parse(strArray[i]);
    }

    return intArray;
}
</code>```

Issue?

I tried many solutions of SO, but none of them helped me.

Ended up with array without leading zeroes.

答:
What about this? </p>

```<code>        string input = "1100,1110,0110,0001";

        var result = input
            .Split(',')
            .Select(e => e.ToCharArray()
                .Select(f => int.Parse(f.ToString())).ToArray())
            .ToArray();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Input:

string param = "1100,1110,0110,0001";

Output:

int[] matrix = new[]
    {
              1,1,0,0,
              1,1,1,0,
              0,1,1,0,
              0,0,0,1
    };

What I did?

First of all I splited string to string[].

string[] resultantArray = param.Split(',');

Created one method, where I passed my string[].

var intArray = toIntArray(resultantArray);

static private int[] toIntArray(string[] strArray)
{
    int[] intArray = new int[strArray.Length];
    for (int i = 0; i < strArray.Length; i++)
    {
        intArray[i] = int.Parse(strArray[i]);
    }

    return intArray;
}

Issue?

I tried many solutions of SO, but none of them helped me.

Ended up with array without leading zeroes.

Body:
What about this?

        string input = "1100,1110,0110,0001";

        var result = input
            .Split(',')
            .Select(e => e.ToCharArray()
                .Select(f => int.Parse(f.ToString())).ToArray())
            .ToArray();


问:
Ways to speed up code with multiple IF statements
I've been working on this code all day and have finally gotten everything to work perfectly. The only problem, is that the code does run pretty slow. Considering that it will be used on a workbook with thousands of rows I would like to change that. I am extremely new to vba so there is probably stuff in here that is wrong or seems like a bad shortcut. I think I added a couple of ways that could speed it up but i didnt know if anything else could be done. </p>

```<code> Sub Degree_Workboook_Names_major1()

 Application.ScreenUpdating = False
 Application.DisplayStatusBar = False
 Application.EnableEvents = False

'Inserts a new column after column H named department names
 range("I1").EntireColumn.Insert
 range("I1").Value = "DeptName"

 Dim abbrRange As range              'range to hold the columns with the department names
 Set abbrRange = range("H:H")

'Writes the department name in the the department name column next to the associated abbr

 For Each cell In abbrRange

            If cell.Value = "ACC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Accounting"
            End If

            If cell.Value = "ACS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Adolescent, Career and Special Education"
            End If

            If cell.Value = "AES" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Animal and Equine Science"
            End If

            If cell.Value = "AGR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Agricultural Science"
            End If

            If cell.Value = "AHS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Applied Health Sciences"
            End If

            If cell.Value = "AHT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Veterinary Technology and Pre-Veterinary Medicine"
            End If

            If cell.Value = "Art" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Art and Design"
            End If

            If cell.Value = "BIO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Biology"
            End If

            If cell.Value = "BPA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "CCD" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Center for Communication Disorders"
            End If

            If cell.Value = "CEAO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Bachelor of Integrated Studies Program"
            End If

            If cell.Value = "CHE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Chemistry"
            End If

            If cell.Value = "CLH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Community Leadership and Human Services"
            End If

            If cell.Value = "COM" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Organizational Communication"
            End If

            If cell.Value = "CSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Computer Science and Information Systems"
            End If

            If cell.Value = "ECO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Economics and Finance"
            End If

            If cell.Value = "ELE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Early Childhood and Elementary Education"
            End If

            If cell.Value = "ENPH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of English and Philosophy"
            End If

            If cell.Value = "ELSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Educational Studies, Leadership and Counseling"
            End If

            If cell.Value = "GSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Geosciences"
            End If

            If cell.Value = "HFA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Liberal Arts"
            End If

            If cell.Value = "HIS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of History"
            End If

            If cell.Value = "INDC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "IOE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "JMC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Journalism and Mass Communications"
            End If

            If cell.Value = "MAT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Mathematics and Statistics"
            End If

            If cell.Value = "MLA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Modern Languages"
            End If

            If cell.Value = "MMB" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "MSP" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Military Science Program"
            End If

            If cell.Value = "MUS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Music"
            End If

            If cell.Value = "NUR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Nursing"
            End If

            If cell.Value = "OSH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Occupational Safety and Health"
            End If

            If cell.Value = "POL" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Political Science and Sociology"
            End If

            If cell.Value = "PSY" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Psychology"
            End If

            If cell.Value = "THR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Theatre"
            End If

 Next

 'Inserts a new column after column H named department names
range("M1").EntireColumn.Insert
range("M1").Value = "DeptName"

'Dim abbrRange As range              'range to hold the columns with the   dpeartment names
Set abbrRange = range("L:L")

'Writes the department name in the the department name column next to the associated abbr

For Each cell In abbrRange

            If cell.Value = "ACC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Accounting"
            End If

            If cell.Value = "ACS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Adolescent, Career and Special Education"
            End If

            If cell.Value = "AES" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Animal and Equine Science"
            End If

            If cell.Value = "AGR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Agricultural Science"
            End If

            If cell.Value = "AHS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Applied Health Sciences"
            End If

            If cell.Value = "AHT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Veterinary Technology and Pre-Veterinary Medicine"
            End If

            If cell.Value = "Art" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Art and Design"
            End If

            If cell.Value = "BIO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Biology"
            End If

            If cell.Value = "BPA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "CCD" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Center for Communication Disorders"
            End If

            If cell.Value = "CEAO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Bachelor of Integrated Studies Program"
            End If

            If cell.Value = "CHE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Chemistry"
            End If

            If cell.Value = "CLH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Community Leadership and Human Services"
            End If

            If cell.Value = "COM" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Organizational Communication"
            End If

            If cell.Value = "CSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Computer Science and Information Systems"
            End If

            If cell.Value = "ECO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Economics and Finance"
            End If

            If cell.Value = "ELE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Early Childhood and Elementary Education"
            End If

            If cell.Value = "ENPH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of English and Philosophy"
            End If

            If cell.Value = "ELSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Educational Studies, Leadership and Counseling"
            End If

            If cell.Value = "GSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Geosciences"
            End If

            If cell.Value = "HFA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Liberal Arts"
            End If

            If cell.Value = "HIS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of History"
            End If

            If cell.Value = "INDC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "IOE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "JMC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Journalism and Mass Communications"
            End If

            If cell.Value = "MAT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Mathematics and Statistics"
            End If

            If cell.Value = "MLA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Modern Languages"
            End If

            If cell.Value = "MMB" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "MSP" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Military Science Program"
            End If

            If cell.Value = "MUS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Music"
            End If

            If cell.Value = "NUR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Nursing"
            End If

            If cell.Value = "OSH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Occupational Safety and Health"
            End If

            If cell.Value = "POL" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Political Science and Sociology"
            End If

            If cell.Value = "PSY" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Psychology"
            End If

            If cell.Value = "THR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Theatre"
            End If

Next

range("I:I").HorizontalAlignment = xlLeft
range("M:M").HorizontalAlignment = xlLeft

Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True

End Sub
</code>```

答:
I would recommend to use switch-case statements instead of if statement. See here: https://www.tutorialspoint.com/vba/vba_switch_statement.htm

The problem on your code is, that all if statements are getting checked even if the first one is applicable.

Body:
I've been working on this code all day and have finally gotten everything to work perfectly. The only problem, is that the code does run pretty slow. Considering that it will be used on a workbook with thousands of rows I would like to change that. I am extremely new to vba so there is probably stuff in here that is wrong or seems like a bad shortcut. I think I added a couple of ways that could speed it up but i didnt know if anything else could be done.

 Sub Degree_Workboook_Names_major1()

 Application.ScreenUpdating = False
 Application.DisplayStatusBar = False
 Application.EnableEvents = False

'Inserts a new column after column H named department names
 range("I1").EntireColumn.Insert
 range("I1").Value = "DeptName"

 Dim abbrRange As range              'range to hold the columns with the department names
 Set abbrRange = range("H:H")

'Writes the department name in the the department name column next to the associated abbr

 For Each cell In abbrRange

            If cell.Value = "ACC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Accounting"
            End If

            If cell.Value = "ACS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Adolescent, Career and Special Education"
            End If

            If cell.Value = "AES" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Animal and Equine Science"
            End If

            If cell.Value = "AGR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Agricultural Science"
            End If

            If cell.Value = "AHS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Applied Health Sciences"
            End If

            If cell.Value = "AHT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Veterinary Technology and Pre-Veterinary Medicine"
            End If

            If cell.Value = "Art" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Art and Design"
            End If

            If cell.Value = "BIO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Biology"
            End If

            If cell.Value = "BPA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "CCD" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Center for Communication Disorders"
            End If

            If cell.Value = "CEAO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Bachelor of Integrated Studies Program"
            End If

            If cell.Value = "CHE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Chemistry"
            End If

            If cell.Value = "CLH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Community Leadership and Human Services"
            End If

            If cell.Value = "COM" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Organizational Communication"
            End If

            If cell.Value = "CSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Computer Science and Information Systems"
            End If

            If cell.Value = "ECO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Economics and Finance"
            End If

            If cell.Value = "ELE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Early Childhood and Elementary Education"
            End If

            If cell.Value = "ENPH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of English and Philosophy"
            End If

            If cell.Value = "ELSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Educational Studies, Leadership and Counseling"
            End If

            If cell.Value = "GSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Geosciences"
            End If

            If cell.Value = "HFA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Liberal Arts"
            End If

            If cell.Value = "HIS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of History"
            End If

            If cell.Value = "INDC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "IOE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "JMC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Journalism and Mass Communications"
            End If

            If cell.Value = "MAT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Mathematics and Statistics"
            End If

            If cell.Value = "MLA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Modern Languages"
            End If

            If cell.Value = "MMB" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "MSP" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Military Science Program"
            End If

            If cell.Value = "MUS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Music"
            End If

            If cell.Value = "NUR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Nursing"
            End If

            If cell.Value = "OSH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Occupational Safety and Health"
            End If

            If cell.Value = "POL" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Political Science and Sociology"
            End If

            If cell.Value = "PSY" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Psychology"
            End If

            If cell.Value = "THR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Theatre"
            End If

 Next

 'Inserts a new column after column H named department names
range("M1").EntireColumn.Insert
range("M1").Value = "DeptName"

'Dim abbrRange As range              'range to hold the columns with the   dpeartment names
Set abbrRange = range("L:L")

'Writes the department name in the the department name column next to the associated abbr

For Each cell In abbrRange

            If cell.Value = "ACC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Accounting"
            End If

            If cell.Value = "ACS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Adolescent, Career and Special Education"
            End If

            If cell.Value = "AES" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Animal and Equine Science"
            End If

            If cell.Value = "AGR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Agricultural Science"
            End If

            If cell.Value = "AHS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Applied Health Sciences"
            End If

            If cell.Value = "AHT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Veterinary Technology and Pre-Veterinary Medicine"
            End If

            If cell.Value = "Art" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Art and Design"
            End If

            If cell.Value = "BIO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Biology"
            End If

            If cell.Value = "BPA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "CCD" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Center for Communication Disorders"
            End If

            If cell.Value = "CEAO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Bachelor of Integrated Studies Program"
            End If

            If cell.Value = "CHE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Chemistry"
            End If

            If cell.Value = "CLH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Community Leadership and Human Services"
            End If

            If cell.Value = "COM" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Organizational Communication"
            End If

            If cell.Value = "CSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Computer Science and Information Systems"
            End If

            If cell.Value = "ECO" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Economics and Finance"
            End If

            If cell.Value = "ELE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Early Childhood and Elementary Education"
            End If

            If cell.Value = "ENPH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of English and Philosophy"
            End If

            If cell.Value = "ELSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Educational Studies, Leadership and Counseling"
            End If

            If cell.Value = "GSC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Geosciences"
            End If

            If cell.Value = "HFA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Liberal Arts"
            End If

            If cell.Value = "HIS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of History"
            End If

            If cell.Value = "INDC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "IOE" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Institute of Engineering"
            End If

            If cell.Value = "JMC" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Journalism and Mass Communications"
            End If

            If cell.Value = "MAT" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Mathematics and Statistics"
            End If

            If cell.Value = "MLA" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Modern Languages"
            End If

            If cell.Value = "MMB" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Management, Marketing and Business Administration"
            End If

            If cell.Value = "MSP" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Military Science Program"
            End If

            If cell.Value = "MUS" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Music"
            End If

            If cell.Value = "NUR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Nursing"
            End If

            If cell.Value = "OSH" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Occupational Safety and Health"
            End If

            If cell.Value = "POL" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Political Science and Sociology"
            End If

            If cell.Value = "PSY" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Psychology"
            End If

            If cell.Value = "THR" Then
            cell.Activate
            ActiveCell.Offset(0, 1).Activate
            ActiveCell.Value = "Department of Theatre"
            End If

Next

range("I:I").HorizontalAlignment = xlLeft
range("M:M").HorizontalAlignment = xlLeft

Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True

End Sub


问:
MVC Routing to controller in another project 404 error
I have created an "area" in another project.  This area is loaded dynamically when the application starts using reflection.  After loading the dll, I manually load the area from the loaded assembly by calling RegisterArea.  Also, the project cshtml files are moved from the loaded area's directory into the main web app's directory when the project builds.

In the AreaRegistration in the other project, I set the following route.

```<code>context.MapRoute(
   "Client_default",
   "PrintPage/{action}/{id}",
   new
   {
      controller = "PrintPage",
      action = "APrintPage",
      id = UrlParameter.Optional
   },
   new[] {
      "AppName.Client.WebApp.Controllers"
   }
);
</code>```

The PrintPageController is in the AppName.Client.WebApp.Controllers namespace in the dynamically loaded dll.  When I try to navigate to the action using ~/PrintPage/APrintPage I am getting a 404 error. I downloaded the Route Debugger Package in an attempt to see if the route just wasn't getting mapped properly.  However, the debugger is indicating that not only is the route mapped, but is matching the url provided.

My controller method signatures:

```<code>[HttpGet]
public ActionResult ViolationResult()

[HttpGet]
public ActionResult ViolationWarning(int[] ids)
</code>```

Now, I am not surprised that the second one might have issues getting routed properly, but I am lost on why the first action is not getting hit.

答:
Ended up figuring it out.  The default controller factory (System.Web.Mvc.DefaultControllerFactory) contained a controller type cache (System.Web.Mvc.ControllerTypeCache).  The type cache loads the controller types from an internal file "MVC-ControllerTypeCache.xml" embedded in the assembly when the project is built.  Since the assemblies containing the views that where loaded at runtime and not built with the project, the controller type cache did not contain a type for the controller even though the route matched.  No controller means 404 error.

For a fix, I simply created a class inheriting from System.Web.Mvc.DefaultControllerFactory, overrode the method GetControllerType, and used my own implementation of the controller type cache that grabs all the classes implementing IController from the loaded assemblies and then uses that cache to determine the controller type.

Note: Some of the code was copied from the DefaultControllerFactory due to certain members being declared internal.

```<code>public class ControllerFactory : DefaultControllerFactory
{
    private static volatile Dictionary<string, Lookup<string, Type>> _ctcache;
    private static readonly object Lock = new object();

    private static Dictionary<string, Lookup<string, Type>> ControllerTypeCache
    {
        get
        {
            if (_ctcache != null)
                return _ctcache;

            FillTypeCache();

            return _ctcache;
        }
    }

    protected override Type GetControllerType(RequestContext requestContext, string controllerName)
    {
        var routeData = requestContext.RouteData;

        //This comes from the DefaultControllerFactory.  I don't use attribute routing.
        if (routeData?.Values.ContainsKey("MS_DirectRouteMatches") ?? false)
            throw new NotImplementedException();

        object obj = null;
        if (!(routeData?.DataTokens.TryGetValue("Namespaces", out obj) ?? false))
            return null;

        var namespaces = (obj as IEnumerable<string>)?.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();

        if ((namespaces == null) || !namespaces.Any())
            return null;

        return ControllerTypeCache[controllerName].SingleOrDefault(x => namespaces.Any(y => IsNamespaceMatch(y, x.Key)))?
            .SingleOrDefault();
    }

    private static void FillTypeCache()
    {
        lock (Lock)
        {
            if (_ctcache != null)
                return;

            var isController = new Func<Type, bool>(x => x.GetInterfaces().Any(y => y == typeof(IController)));

            var asm = System.Reflection.Assembly.GetExecutingAssembly();
            var defaultControllers = asm.GetTypes().Where(isController);

            //Loaded is a class containing items initialized at Application_Start
            //FromConfig is an IEnumerable<System.Reflection.Assembly>
            var loadedControllers = Loaded.FromConfig.SelectMany(x => x.GetTypes().Where(isController));

            _ctcache = defaultControllers.Union(loadedControllers)
                .GroupBy(x => x.Name)
                .ToDictionary(x => x.Key.Replace("Controller", ""), types => types.ToLookup(y => y.Namespace) as Lookup<string, Type>);
        }
    }

    //Lifted from the DefaultControllerFactory since it's an internal method.
    private static bool IsNamespaceMatch(string requestedNamespace, string targetNamespace)
    {
        if (requestedNamespace == null)
        {
            return false;
        }
        if (requestedNamespace.Length == 0)
        {
            return true;
        }
        if (!requestedNamespace.EndsWith(".*", StringComparison.OrdinalIgnoreCase))
        {
            return string.Equals(requestedNamespace, targetNamespace, StringComparison.OrdinalIgnoreCase);
        }
        requestedNamespace = requestedNamespace.Substring(0, requestedNamespace.Length - ".*".Length);
        if (!targetNamespace.StartsWith(requestedNamespace, StringComparison.OrdinalIgnoreCase))
        {
            return false;
        }
        return (requestedNamespace.Length == targetNamespace.Length) || (targetNamespace[requestedNamespace.Length] == '.');
    }
}
</code>```

Finally, at Application_Start, make the following call.

```<code>ControllerBuilder.Current.SetControllerFactory(new ControllerFactory());
</code>```

Body:
I have created an "area" in another project.  This area is loaded dynamically when the application starts using reflection.  After loading the dll, I manually load the area from the loaded assembly by calling RegisterArea.  Also, the project cshtml files are moved from the loaded area's directory into the main web app's directory when the project builds.

In the AreaRegistration in the other project, I set the following route.

context.MapRoute(
   "Client_default",
   "PrintPage/{action}/{id}",
   new
   {
      controller = "PrintPage",
      action = "APrintPage",
      id = UrlParameter.Optional
   },
   new[] {
      "AppName.Client.WebApp.Controllers"
   }
);

The PrintPageController is in the AppName.Client.WebApp.Controllers namespace in the dynamically loaded dll.  When I try to navigate to the action using ~/PrintPage/APrintPage I am getting a 404 error. I downloaded the Route Debugger Package in an attempt to see if the route just wasn't getting mapped properly.  However, the debugger is indicating that not only is the route mapped, but is matching the url provided.

My controller method signatures:

[HttpGet]
public ActionResult ViolationResult()

[HttpGet]
public ActionResult ViolationWarning(int[] ids)

Now, I am not surprised that the second one might have issues getting routed properly, but I am lost on why the first action is not getting hit.

Body:
Ended up figuring it out.  The default controller factory (System.Web.Mvc.DefaultControllerFactory) contained a controller type cache (System.Web.Mvc.ControllerTypeCache).  The type cache loads the controller types from an internal file "MVC-ControllerTypeCache.xml" embedded in the assembly when the project is built.  Since the assemblies containing the views that where loaded at runtime and not built with the project, the controller type cache did not contain a type for the controller even though the route matched.  No controller means 404 error.

For a fix, I simply created a class inheriting from System.Web.Mvc.DefaultControllerFactory, overrode the method GetControllerType, and used my own implementation of the controller type cache that grabs all the classes implementing IController from the loaded assemblies and then uses that cache to determine the controller type.

Note: Some of the code was copied from the DefaultControllerFactory due to certain members being declared internal.

public class ControllerFactory : DefaultControllerFactory
{
    private static volatile Dictionary<string, Lookup<string, Type>> _ctcache;
    private static readonly object Lock = new object();

    private static Dictionary<string, Lookup<string, Type>> ControllerTypeCache
    {
        get
        {
            if (_ctcache != null)
                return _ctcache;

            FillTypeCache();

            return _ctcache;
        }
    }

    protected override Type GetControllerType(RequestContext requestContext, string controllerName)
    {
        var routeData = requestContext.RouteData;

        //This comes from the DefaultControllerFactory.  I don't use attribute routing.
        if (routeData?.Values.ContainsKey("MS_DirectRouteMatches") ?? false)
            throw new NotImplementedException();

        object obj = null;
        if (!(routeData?.DataTokens.TryGetValue("Namespaces", out obj) ?? false))
            return null;

        var namespaces = (obj as IEnumerable<string>)?.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();

        if ((namespaces == null) || !namespaces.Any())
            return null;

        return ControllerTypeCache[controllerName].SingleOrDefault(x => namespaces.Any(y => IsNamespaceMatch(y, x.Key)))?
            .SingleOrDefault();
    }

    private static void FillTypeCache()
    {
        lock (Lock)
        {
            if (_ctcache != null)
                return;

            var isController = new Func<Type, bool>(x => x.GetInterfaces().Any(y => y == typeof(IController)));

            var asm = System.Reflection.Assembly.GetExecutingAssembly();
            var defaultControllers = asm.GetTypes().Where(isController);

            //Loaded is a class containing items initialized at Application_Start
            //FromConfig is an IEnumerable<System.Reflection.Assembly>
            var loadedControllers = Loaded.FromConfig.SelectMany(x => x.GetTypes().Where(isController));

            _ctcache = defaultControllers.Union(loadedControllers)
                .GroupBy(x => x.Name)
                .ToDictionary(x => x.Key.Replace("Controller", ""), types => types.ToLookup(y => y.Namespace) as Lookup<string, Type>);
        }
    }

    //Lifted from the DefaultControllerFactory since it's an internal method.
    private static bool IsNamespaceMatch(string requestedNamespace, string targetNamespace)
    {
        if (requestedNamespace == null)
        {
            return false;
        }
        if (requestedNamespace.Length == 0)
        {
            return true;
        }
        if (!requestedNamespace.EndsWith(".*", StringComparison.OrdinalIgnoreCase))
        {
            return string.Equals(requestedNamespace, targetNamespace, StringComparison.OrdinalIgnoreCase);
        }
        requestedNamespace = requestedNamespace.Substring(0, requestedNamespace.Length - ".*".Length);
        if (!targetNamespace.StartsWith(requestedNamespace, StringComparison.OrdinalIgnoreCase))
        {
            return false;
        }
        return (requestedNamespace.Length == targetNamespace.Length) || (targetNamespace[requestedNamespace.Length] == '.');
    }
}

Finally, at Application_Start, make the following call.

ControllerBuilder.Current.SetControllerFactory(new ControllerFactory());


问:
How to select and delete files from a grid using a checkbox
I am currently working on a Directory Browser using PHP and I've stumbled upon a roadblock. I would like to be able to have a user select files using checkboxes, then delete them when they click a button, however I'm not sure how to go about this due to being new to PHP and web development in general. Here is my code so far for the user interface:

```<code>                            <a href="#" onClick="rec('deletestuff')">
                            <span title="Delete Selected" class="fa fa-trash fa-lg"></span>
                            <!--Delete Selected-->
                        </a>
                    </li>
                </ul>
                <script type="text/javascript">
                    function rec(deletestuff) {
                        $('#newCode').load('delete_selected.php' deletestuff);
                    }
                </script>
<span class="selected col-md-2 col-sm-2 col-xs-1 text-right">
                                <form method="get">
                                    <input type="checkbox" name="selected[]" value="'.$file.'">
                                </form>

                            </span>
</code>```

then in a seperate PHP file I wrote this algorithm to handle the delete functionality

```<code><?php

foreach($_POST['selected[]'] as $file) {
    if(file_exists($lister->getDirectoryPath() . $file)) {
        unlink($lister->getDirectoryPath() . $file);
        echo "<script type='text/javascript'>alert('Files deleted
successfully.');</script>";
    }
    elseif(is_dir($file)) {
        rmdir($file);
        echo "<script type='text/javascript'>alert('Files deleted successfully.');</script>";
    }
}

?>
</code>```

I am pretty sure that I am not performing the handling between the several different types of scripts correctly (specifically having the javascript send its information to the php), however I need some pointers as to where exactly I am failing at this in order to correct it. If needed, I can share more of my source code as it is based on the PHP DirectoryLister found here: https://github.com/DirectoryLister/DirectoryLister

Thanks!

答:
First, make sure that you're sending the right data to your PHP script. Currently, on click you're calling the function 'rec' and passing it the string 'deletestuff'. You're then passing that string to your script and trying to reference the list of selected checkboxes in your script which you never passed.

As for passing the list of selected checkboxes to your script, there are a number of ways to do that. Since you're already using jQuery, I would recommend iterating through all the checkbox elements

```<code>$('input[type=checkbox]').each(function () {
    if (this.checked) {
       toDelete.push(this.id);
   }
});
</code>```

seeing if they have the attribute checked equal to true, building a list of 'toDelete' from those, and then passing that list to the script through your function.

Body:
I am currently working on a Directory Browser using PHP and I've stumbled upon a roadblock. I would like to be able to have a user select files using checkboxes, then delete them when they click a button, however I'm not sure how to go about this due to being new to PHP and web development in general. Here is my code so far for the user interface:

                                <form method="get">
                                    <input type="checkbox" name="selected[]" value="'.$file.'">
                                </form>

then in a seperate PHP file I wrote this algorithm to handle the delete functionality

<?php

foreach($_POST['selected[]'] as $file) {
    if(file_exists($lister->getDirectoryPath() . $file)) {
        unlink($lister->getDirectoryPath() . $file);
        echo "";
    }
    elseif(is_dir($file)) {
        rmdir($file);
        echo "";
    }
}

?>

I am pretty sure that I am not performing the handling between the several different types of scripts correctly (specifically having the javascript send its information to the php), however I need some pointers as to where exactly I am failing at this in order to correct it. If needed, I can share more of my source code as it is based on the PHP DirectoryLister found here: https://github.com/DirectoryLister/DirectoryLister

Thanks!

Body:
First, make sure that you're sending the right data to your PHP script. Currently, on click you're calling the function 'rec' and passing it the string 'deletestuff'. You're then passing that string to your script and trying to reference the list of selected checkboxes in your script which you never passed.

As for passing the list of selected checkboxes to your script, there are a number of ways to do that. Since you're already using jQuery, I would recommend iterating through all the checkbox elements

$('input[type=checkbox]').each(function () {
    if (this.checked) {
       toDelete.push(this.id);
   }
});

seeing if they have the attribute checked equal to true, building a list of 'toDelete' from those, and then passing that list to the script through your function.


问:
Ruby/Rails - Get the previous Friday? (Friday of last week)
Is there a way to get the previous Friday's date in Rails?  I've seen ways to get the closest Friday, or the previous Monday or Sunday, but I specifically need the last Friday.

So up until and including Friday of this current week, it'd be the previous week's Friday. Then starting on Saturday, it'd be the Friday a day before.

For example:

Saturday, March 4th through Friday, March 10th -> Friday, March 3rd

Saturday, March 11th through Friday, March. 17th -> Friday, March 10th

答:
Here's a way to do it without any conditionals. This will accept a Date, Time, or DateTime object.

```<code>def prior_friday(date)
  days_before = (date.wday + 1) % 7 + 1
  date.to_date - days_before
end
</code>```

Now you can do any of these:

```<code>>> prior_friday(Date.today)
=> Fri, 24 Mar 2017
>> prior_friday(Date.tomorrow)
=> Fri, 31 Mar 2017
>> prior_friday(Date.new(2017,4,4))
=> Fri, 31 Mar 2017
>> prior_friday(Time.now)
=> Fri, 24 Mar 2017
>> prior_friday(DateTime.tomorrow)
=> Fri, 31 Mar 2017
>> prior_friday(1.year.from_now)
=> Fri, 30 Mar 2018
</code>```

For different days of the week, change the integer added to date.wday before the mod is applied:

```<code>def prior_monday(date)
  days_before = (date.wday + 5) % 7 + 1
  date.to_date - days_before
end
</code>```

Or make a universal method:

```<code>def prior_weekday(date, weekday)
  weekday_index = Date::DAYNAMES.reverse.index(weekday)
  days_before = (date.wday + weekday_index) % 7 + 1
  date.to_date - days_before
end
</code>```

Examples run on Saturday, August 4, 2018:

```<code>>> prior_weekday(Date.today, 'Saturday')
Sat, 28 Jul 2018
>> prior_weekday(Date.today, 'Friday')
Fri, 03 Aug 2018
>> prior_weekday(Date.tomorrow, 'Friday')
Fri, 03 Aug 2018
>> prior_weekday(Date.tomorrow, 'Saturday')
Sat, 04 Aug 2018
>> prior_weekday(Date.tomorrow, 'Sunday')
Sun, 29 Jul 2018
</code>```

Body:
Here's a way to do it without any conditionals. This will accept a Date, Time, or DateTime object.

def prior_friday(date)
  days_before = (date.wday + 1) % 7 + 1
  date.to_date - days_before
end

Now you can do any of these:

>> prior_friday(Date.today)
=> Fri, 24 Mar 2017
>> prior_friday(Date.tomorrow)
=> Fri, 31 Mar 2017
>> prior_friday(Date.new(2017,4,4))
=> Fri, 31 Mar 2017
>> prior_friday(Time.now)
=> Fri, 24 Mar 2017
>> prior_friday(DateTime.tomorrow)
=> Fri, 31 Mar 2017
>> prior_friday(1.year.from_now)
=> Fri, 30 Mar 2018

For different days of the week, change the integer added to date.wday before the mod is applied:

def prior_monday(date)
  days_before = (date.wday + 5) % 7 + 1
  date.to_date - days_before
end

Or make a universal method:

def prior_weekday(date, weekday)
  weekday_index = Date::DAYNAMES.reverse.index(weekday)
  days_before = (date.wday + weekday_index) % 7 + 1
  date.to_date - days_before
end

Examples run on Saturday, August 4, 2018:

>> prior_weekday(Date.today, 'Saturday')
Sat, 28 Jul 2018
>> prior_weekday(Date.today, 'Friday')
Fri, 03 Aug 2018
>> prior_weekday(Date.tomorrow, 'Friday')
Fri, 03 Aug 2018
>> prior_weekday(Date.tomorrow, 'Saturday')
Sat, 04 Aug 2018
>> prior_weekday(Date.tomorrow, 'Sunday')
Sun, 29 Jul 2018

ContentLicense: CC BY-SA 4.0


问:
Android converting stream to byte array Out of Memory Exceptions
I have ran into a situation where I am getting out of memory exceptions when trying to convert an input stream into a byte array. On newer Android phones it's no problem, but some of these cheaper models are experiencing it. Here is the method I'm using. Is there a more efficient way to do this?</p>

```<code>public byte[] convertStreamToByteArray(InputStream is) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  byte[] buff = new byte[1024];
  int i = 0;
  while ((i = is.read(buff, 0, buff.length)) > 0) {
    baos.write(buff, 0, i);
  }
  return baos.toByteArray();
}
</code>```

答:
There is, do not copy all the data from the stream to memory.

Why do you need to do so ?

Can't you read and consume the stream data as it comes without holding the whole data in memory ?

If you need some buffering, buffer as small as you can for it to be consumable/processed and throw that buffer away and create a new one so that you have as less memory used at a time as possible.

Body:
I have ran into a situation where I am getting out of memory exceptions when trying to convert an input stream into a byte array. On newer Android phones it's no problem, but some of these cheaper models are experiencing it. Here is the method I'm using. Is there a more efficient way to do this?

public byte[] convertStreamToByteArray(InputStream is) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  byte[] buff = new byte[1024];
  int i = 0;
  while ((i = is.read(buff, 0, buff.length)) > 0) {
    baos.write(buff, 0, i);
  }
  return baos.toByteArray();
}


问:
PHP Move_uploaded_file not moving my file to directory
I am making an image uploading feature for a program I am developing however I cant seem to get move_uploaded_file to actually move my file and I am not sure why.

I am receiving the form data as I can see the data when I use the print_r function print_r($_FILES)

My directory struct is as follows
root->app->lib->uploadCode.php and root->app->images

I dont get any errors.
I am running this on ubuntu 16.04 with php7 installed

Here is my code.

```<code><?php
error_reporting(E_ALL);
if(!empty($_FILES['newImage']['name']))
{
    $fname = $_FILES['newImage']['name'];
    $fext = explode(".",$fname);
    $sex = array("jpg", "jpeg", "JPG", "JPEG", "png", "PNG");//Supported extensions
    //Check if file extension supported
    $extRes = array_intersect($fext, $sex);//Checks to see if file uploaded extension exists in the supported extension array
    if(count($extRes) == 1)
    {
        print_r($_FILES);
        $name = $_FILES['newImage']['name'];
        $ext = end($fext);
        $tmp = $_FILES['newImage']['tmp_name'];
        $path = '/../images/';
        $newName = uniqid().".".$ext;
        /*if(move_uploaded_file($tmp,$path.$newName))
        {
            echo "uploaded";
        }
        else
            {
                echo "not uploaded";
                echo $path.$newName;
            }*/

        move_uploaded_file($tmp,$path.$newName);
    }
    elseif(count($extRes) > 1)
        {//More than just one file extension was found possibly something like image.png.jpg
            echo 02;
        }
        else
            {// Nothing was found so wrong file type was used
                echo 01;
            }
}else
    {//Do if no image was uploaded
        echo 00;
    }
</code>```

`

答: Either remove the opening slash from $path = '/../images/'; or set the full path, e.g. /home/username/images/ for example

Body:
I am making an image uploading feature for a program I am developing however I cant seem to get move_uploaded_file to actually move my file and I am not sure why.

I am receiving the form data as I can see the data when I use the print_r function print_r($_FILES)

My directory struct is as follows
root->app->lib->uploadCode.php and root->app->images

I dont get any errors.
I am running this on ubuntu 16.04 with php7 installed

Here is my code.

<?php
error_reporting(E_ALL);
if(!empty($_FILES['newImage']['name']))
{
    $fname = $_FILES['newImage']['name'];
    $fext = explode(".",$fname);
    $sex = array("jpg", "jpeg", "JPG", "JPEG", "png", "PNG");//Supported extensions
    //Check if file extension supported
    $extRes = array_intersect($fext, $sex);//Checks to see if file uploaded extension exists in the supported extension array
    if(count($extRes) == 1)
    {
        print_r($_FILES);
        $name = $_FILES['newImage']['name'];
        $ext = end($fext);
        $tmp = $_FILES['newImage']['tmp_name'];
        $path = '/../images/';
        $newName = uniqid().".".$ext;
        /*if(move_uploaded_file($tmp,$path.$newName))
        {
            echo "uploaded";
        }
        else
            {
                echo "not uploaded";
                echo $path.$newName;
            }*/

        move_uploaded_file($tmp,$path.$newName);
    }
    elseif(count($extRes) > 1)
        {//More than just one file extension was found possibly something like image.png.jpg
            echo 02;
        }
        else
            {// Nothing was found so wrong file type was used
                echo 01;
            }
}else
    {//Do if no image was uploaded
        echo 00;
    }

`


问:
Need to associate unique integer value with classes
Alright, so I have a base class which we'll call TFruit. From this there are various descendants like TApple, TOrange and so on. I need to save the properties of the descendant classes to a file.

In order to be able to create the right class when loading the data, each class needs to have an ID that I write to the file before writing the actual data. Currently, I've come up with the following way of doing it:

```<code>type
  TFruit = class
    const ID = 0;
  end;

  TApple = class(TFruit)
    const ID = 1;
  end;

  TOrange = class(TFruit)
    const ID = 2;
  end;
</code>```

Testing this, I found out that I need to be super careful which class I declare. If I use this:

```<code>  var Fruit: TFruit;

  Fruit := TOrange.Create;
</code>```

...then Fruit.ID will return zero. However, declaring Fruit as a TOrange will yield the expected result Fruit.ID = 2 (anyone know why?)

So basically, am I doing this right or is there a better way to do it? Having to create a class function and return a value from there seems very ugly by comparison (extra function declaration, implementation and code).

答:
there are many possibilities, for example:</p>

```<code>function TFruit.GetClassId(): Word;
begin
  Result := CRC16(ClassName);
end;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Alright, so I have a base class which we'll call TFruit. From this there are various descendants like TApple, TOrange and so on. I need to save the properties of the descendant classes to a file.

In order to be able to create the right class when loading the data, each class needs to have an ID that I write to the file before writing the actual data. Currently, I've come up with the following way of doing it:

type
  TFruit = class
    const ID = 0;
  end;

  TApple = class(TFruit)
    const ID = 1;
  end;

  TOrange = class(TFruit)
    const ID = 2;
  end;

Testing this, I found out that I need to be super careful which class I declare. If I use this:

  var Fruit: TFruit;

  Fruit := TOrange.Create;

...then Fruit.ID will return zero. However, declaring Fruit as a TOrange will yield the expected result Fruit.ID = 2 (anyone know why?)

So basically, am I doing this right or is there a better way to do it? Having to create a class function and return a value from there seems very ugly by comparison (extra function declaration, implementation and code).

Body:
there are many possibilities, for example:

function TFruit.GetClassId(): Word;
begin
  Result := CRC16(ClassName);
end;


问:
laravel passport doesnt support authorization grant type?
I am having an issue using the authorization grant in laravel/passport. I usually get this error:

{"error":"unsupported_grant_type","message":"The authorization grant type is not supported by the authorization server.","hint":"Check the grant_type parameter"}

First of all it takes me to login page, when i login it throws the above error. However the password grant works fine.

I created my client using: php artisan passport:client

答: try body raw and Content-Type application/json


问:
What's the point of setting Reuse Identifier for Collection View Cell in Interface Builder?
Collection Reusable Views, including Collection View Cells (which is a subclass), have a field in Interface Builder called "Identifier" with prompt "Reuse Identifier".

However, you normally use it by registering it with the UICollectionView using the –registerNib:forCellWithReuseIdentifier: and –registerNib:forSupplementaryViewOfKind:withReuseIdentifier: methods, where you also specify a reuse identifier.

So then what's the point of setting one in Interface Builder? It seems to make no difference whether you set it there or not.

答:
I just came across a situation myself where there most definitely is a difference in behaviour between having the reuse identifier set in Interface Builder and not having it set. (This is along the lines of what @LESANG is alluding to in their answer; that the reuse identifier should be left blank when creating cells in a separate nib file. I wanted to include some more details of when/why this is the case)

In my case, I had a custom cell that I wanted to be usable by multiple different view controllers. In order to share the cell, I created a separate nib file for the cell, configured the view hierarchy, and assigned a reuse identifier in Interface Builder. Each view controller then registers the cell using register(_:forCellWithReuseIdentifier:), and passing in the same reuse identifier as set in IB.

However, for one of my view controllers, I actually wanted to register different cells (different reuse identifiers) but using the same nib*. But simply passing in a different reuse identifier causes the app to crash, complaining:

view reuse identifier in nib (<reuse identifier in nib>) does not match the identifier used to register the nib (<reuse identifier when registering programmatically>)

So to solve this, there must be no reuse identifier specified in the nib itself. By removing the identifier in the nib, the identifier specified in register(_:forCellWithReuseIdentifier:) is used instead, and cells are dequeued correctly.

It's worth noting, therefore, that when defining cells in nib files, there appears to be no point whatsoever in coding the reuse identifier into the nib – any views that want to use that cell must register it manually in code anyway, at which point the reuse identifier specified there might as well be used rather than the one in the nib. In this scenario, it seems that all the identifier in the nib does is take precedence over the programmatically registered identifier, and cause a crash should you attempt to use a different identifier.

*Sure, I could create a new nib file with the same/similar view hierarchy and a different reuse identifier, but then should I need to change the cell configuration I'd have to make the same change across multiple files.


问:
How to take inputs and display their sum using stdin and stdout
I wrote a simple code to add two numbers with stdin and stdout to take input and display output respectively:

```<code>import sys
print("Inputs:")
for one in sys.stdin:
    break
int(one)

for two in sys.stdin:
    break
int(two)

three = 0

print("Output:")
three = one + two

sys.stdout.write(three)
</code>```

The output i get is:

```<code>Inputs:
1
2
Output:
1
2
</code>```

The expected output was 3. But what I got is show in above output.

I tried the same code using input():

```<code>one = int(input())

two = int(input())

three = one + two

print(three)
</code>```

And the output I got was 3. What is missing in my first code?

答:
I think what you're trying to do is:

```<code>aNumber = input('Enter a number: ')
anotherNumber = input('Enter another number: ')
print(int(aNumber) + int(anotherNumber))
</code>```

To do this using stdin/out you can use:

```<code>import sys
print("Inputs:")
one = sys.stdin.readline()
two = sys.stdin.readline()
print("Output:")
three = int(one) + int(two)
four = str(three)
sys.stdout.write(four)
</code>```

Body:
I wrote a simple code to add two numbers with stdin and stdout to take input and display output respectively:

import sys
print("Inputs:")
for one in sys.stdin:
    break
int(one)

for two in sys.stdin:
    break
int(two)

three = 0

print("Output:")
three = one + two

sys.stdout.write(three)

The output i get is:

Inputs:
1
2
Output:
1
2

The expected output was 3. But what I got is show in above output.

I tried the same code using input():

one = int(input())

two = int(input())

three = one + two

print(three)

And the output I got was 3. What is missing in my first code?

Body:
I think what you're trying to do is:

aNumber = input('Enter a number: ')
anotherNumber = input('Enter another number: ')
print(int(aNumber) + int(anotherNumber))

To do this using stdin/out you can use:

import sys
print("Inputs:")
one = sys.stdin.readline()
two = sys.stdin.readline()
print("Output:")
three = int(one) + int(two)
four = str(three)
sys.stdout.write(four)


问:
EF entity is not saving child property of same entity type on update
I am using ASP.NET MVC 5 and Entity Framework 6. I have a page that allows the user to enter Process information. One aspect of this information is to choose from a drop down the Starting Process. This class roughly looks like:

**

```<code>public class SupportProcess
  {
    [Key]
    public int ProcessId { get; set; }
    [DisplayName("Starting process?")]
    public virtual SupportProcess StartProcess { get; set; }
    public string Name { get; set; }
    [DisplayName("When is this run?")]
    public virtual ProcessSchedule ProcessSchedule { get; set; }
    [DisplayName("")]
    public string Description { get; set; }
    [DisplayName("Expected Result")]
    public string ExpectedResult { get; set; }
  }
</code>```

**

I am using a view model that has properties for the SupportProcess, the selected start process, and a list of processes to populate the drop down on the view.

```<code>  public class SupportProcessViewModel
  {
    public SupportProcess SupportProcess { get; set; }
    public int SelectedStartProcess { get; set; }
    public List<SupportProcess> Processes { get; set; }

    public SupportProcessViewModel()
    {
      this.SupportProcess = new SupportProcess();
    }
  }
</code>```

My Edit post action looks like:

```<code>   [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(SupportProcessViewModel vm)
    {
        if (ModelState.IsValid)
        {

      if (vm.SelectedStartProcess > 0)
      {
        vm.SupportProcess.StartProcess = db.SupportProcesses.Find(vm.SelectedStartProcess);
      }
        db.Entry(vm.SupportProcess).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(vm);
}
</code>```

The issue is that, while vm.SelectedStartProcess is not null and has a proper value, it never gets saved to the database. The database shows this field as StartProcess_ProcessId. Also of note is that a process may have 0 or 1 Starting processes.

I'm wondering if the fact that EF has made this property in the database table a foreign key, which would, in essence, point to the same table, is somehow causing the issue. I'm all ears for suggestions.

I'll also add that the Create Post action works as expected. This must be something to do with conveying to EF that the StartProcess property also needs to be updated on the entity..That's a guess though...

```<code>    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create( SupportProcessViewModel vm)
    {
        if (ModelState.IsValid)
        {
            if(vm.SelectedStartProcess > 0) {
              vm.SupportProcess.StartProcess = db.SupportProcesses.Find(vm.SelectedStartProcess);
            }
            db.SupportProcesses.Add(vm.SupportProcess);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(vm);
    }
</code>```

答:
I think your Edit ActionResult should look something like this

```<code>    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(SupportProcessViewModel vm)
    {
        if (ModelState.IsValid)
        {

      if (vm.SelectedStartProcess > 0)
      {
        vm.SupportProcess.StartProcess = db.SupportProcesses.Find(vm.SelectedStartProcess);
      }
        db.SupportProcess.Attach(vm.SupportProcess);
        db.Entry(vm.SupportProcess).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(vm);
}
</code>```

Body:
I am using ASP.NET MVC 5 and Entity Framework 6. I have a page that allows the user to enter Process information. One aspect of this information is to choose from a drop down the Starting Process. This class roughly looks like:

**

public class SupportProcess
  {
    [Key]
    public int ProcessId { get; set; }
    [DisplayName("Starting process?")]
    public virtual SupportProcess StartProcess { get; set; }
    public string Name { get; set; }
    [DisplayName("When is this run?")]
    public virtual ProcessSchedule ProcessSchedule { get; set; }
    [DisplayName("")]
    public string Description { get; set; }
    [DisplayName("Expected Result")]
    public string ExpectedResult { get; set; }
  }

**

I am using a view model that has properties for the SupportProcess, the selected start process, and a list of processes to populate the drop down on the view.

  public class SupportProcessViewModel
  {
    public SupportProcess SupportProcess { get; set; }
    public int SelectedStartProcess { get; set; }
    public List<SupportProcess> Processes { get; set; }

    public SupportProcessViewModel()
    {
      this.SupportProcess = new SupportProcess();
    }
  }

My Edit post action looks like:

   [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(SupportProcessViewModel vm)
    {
        if (ModelState.IsValid)
        {

      if (vm.SelectedStartProcess > 0)
      {
        vm.SupportProcess.StartProcess = db.SupportProcesses.Find(vm.SelectedStartProcess);
      }
        db.Entry(vm.SupportProcess).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(vm);
}

The issue is that, while vm.SelectedStartProcess is not null and has a proper value, it never gets saved to the database. The database shows this field as StartProcess_ProcessId. Also of note is that a process may have 0 or 1 Starting processes.

I'm wondering if the fact that EF has made this property in the database table a foreign key, which would, in essence, point to the same table, is somehow causing the issue. I'm all ears for suggestions.

I'll also add that the Create Post action works as expected. This must be something to do with conveying to EF that the StartProcess property also needs to be updated on the entity..That's a guess though...

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create( SupportProcessViewModel vm)
    {
        if (ModelState.IsValid)
        {
            if(vm.SelectedStartProcess > 0) {
              vm.SupportProcess.StartProcess = db.SupportProcesses.Find(vm.SelectedStartProcess);
            }
            db.SupportProcesses.Add(vm.SupportProcess);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(vm);
    }

Body:
I think your Edit ActionResult should look something like this

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(SupportProcessViewModel vm)
    {
        if (ModelState.IsValid)
        {

      if (vm.SelectedStartProcess > 0)
      {
        vm.SupportProcess.StartProcess = db.SupportProcesses.Find(vm.SelectedStartProcess);
      }
        db.SupportProcess.Attach(vm.SupportProcess);
        db.Entry(vm.SupportProcess).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(vm);
}


问:
thread building blocks and graphical processing unit
can we execute thread building blocks threads on a Nvidia graphical processing unit? I want to have multiple threads for my tbb code so what should be optimum number for the same and can i use gpu threads instead of cpu threads?  </p>

答:
TBB use threads provided by an operation system. If you want to use some kind of GPU accelerators you can try to use streaming_node (Documentation). It could help you to simplify using OpenCL(for example) for computation.

Streaming_node is a part of TBB Flow graph


问:
fast unitary matrix multiplication with block acceleration
Assume I have a very fast subroutine for fixed size unitary matrix multiplication. (The subroutine may involve hardware acceleration) Say, a function called quantum_unmm_256(A, U, m) right-multiplies a m by 256 matrix A with a 256 by 256 unitary matrix U.

Now I want multiply something with a unitary matrix whose size is multiples of 256, say, a 1280x1280 unitary matrix. What would be a fast algorithm that make best use of the fast subroutine?

All matrices are assumed dense, with 64 or 128 bit float complex type.

答:
This isn't a full answer, but too long for a comment:

It might be easier to work with a (1280x1280) if it were reshaped to (4, 256, 4, 256), and then transposed to (4,4,256,256).  But even that could require a copy() to ensure that the inner most blocks (numpy terms) are contiguous.

It could even be cast as a (4,4) object dtype array, where each element is your 'fast' unitary array.

I could elaborate on those actions if needed, but I suspect you have enough numpy skills to do it.

There are a lot things that are unclear about this question.

why both MATLAB and numpy tags

how is this block acceleration coded - if it's fast it must be compiled code; if so what's the proposed link to interpreted code

what are the constraints on the data structure?  I suspect it must be some sort of contiguous block(s) of data. That's why I suggest the reshape and transpose.


问:
Add .00 (toFixed) only if number has less than two decimal places
I need to add zeroes, so that each number has at least two decimals, but without rounding.  So for example:

```<code>5      --> 5.00
5.1    --> 5.10
5.11   --> 5.11 (no change)
5.111  --> 5.111 (no change)
5.1111 -->  5.1111  (no change)
</code>```

My function is missing an IF to check for less than two decimal places:

```<code>function addZeroes( num ) {
   var num = Number(num);
   if ( //idk ) {
      num = num.toFixed(2);
   }
   return num;
}
</code>```

Thanks!

Posting an alternative answer, in addition to the two below.  (Keep in mind that I'm no expert and this is just for text inputs, not for parsing complex values like colors that could have floating point issues, etc.)

```<code>function addZeroes( value ) {
    //set everything to at least two decimals; removs 3+ zero decimasl, keep non-zero decimals
    var new_value = value*1; //removes trailing zeros
    new_value = new_value+''; //casts it to string

    pos = new_value.indexOf('.');
    if (pos==-1) new_value = new_value + '.00';
    else {
        var integer = new_value.substring(0,pos);
        var decimals = new_value.substring(pos+1);
        while(decimals.length<2) decimals=decimals+'0';
        new_value = integer+'.'+decimals;
    }
    return new_value;
}
</code>```

[This is not a duplicate question.  The question you linked assumes "knowing that they have at least 1 decimal."  Decimal points cannot be assumed in text inputs, and this was making errors.]

答:
Here is a function that will do this, function expects a number</p>

```<code>var addZeroes = function(num) {
  var numberAsString = num.toString();

  if(numberAsString.indexOf('.') === -1) {
    num = num.toFixed(2);
    numberAsString = num.toString();
  } else if (numberAsString.split(".")[1].length < 3) {
    num = num.toFixed(2);
    numberAsString = num.toString();
  }

  return numberAsString
};
</code>```

Body:
I need to add zeroes, so that each number has at least two decimals, but without rounding.  So for example:

5      --> 5.00
5.1    --> 5.10
5.11   --> 5.11 (no change)
5.111  --> 5.111 (no change)
5.1111 -->  5.1111  (no change)

My function is missing an IF to check for less than two decimal places:

function addZeroes( num ) {
   var num = Number(num);
   if ( //idk ) {
      num = num.toFixed(2);
   }
   return num;
}

Thanks!

Posting an alternative answer, in addition to the two below.  (Keep in mind that I'm no expert and this is just for text inputs, not for parsing complex values like colors that could have floating point issues, etc.)

function addZeroes( value ) {
    //set everything to at least two decimals; removs 3+ zero decimasl, keep non-zero decimals
    var new_value = value*1; //removes trailing zeros
    new_value = new_value+''; //casts it to string

    pos = new_value.indexOf('.');
    if (pos==-1) new_value = new_value + '.00';
    else {
        var integer = new_value.substring(0,pos);
        var decimals = new_value.substring(pos+1);
        while(decimals.length<2) decimals=decimals+'0';
        new_value = integer+'.'+decimals;
    }
    return new_value;
}

[This is not a duplicate question.  The question you linked assumes "knowing that they have at least 1 decimal."  Decimal points cannot be assumed in text inputs, and this was making errors.]

Body:
Here is a function that will do this, function expects a number

var addZeroes = function(num) {
  var numberAsString = num.toString();

  if(numberAsString.indexOf('.') === -1) {
    num = num.toFixed(2);
    numberAsString = num.toString();
  } else if (numberAsString.split(".")[1].length < 3) {
    num = num.toFixed(2);
    numberAsString = num.toString();
  }

  return numberAsString
};


问:
Only parameterless constructors and initializers are supported in LINQ to Entities
I have this error in this linq expression :

```<code>var naleznosci = (from nalTmp in db.Naleznosci
                              where nalTmp.idDziecko == idDziec
                              select new Payments
                              (
                                  nalTmp.Dziecko.Imie,
                                  nalTmp.Dziecko.Nazwisko,
                                  nalTmp.Miesiace.Nazwa,
                                  nalTmp.Kwota,
                                  nalTmp.RodzajeOplat.NazwaRodzajuOplaty,
                                  nalTmp.RodzajeOplat.TypyOplat.NazwaTypuOplaty,
                                  nalTmp.DataRozliczenia,
                                  nalTmp.TerminPlatnosci
                              )).ToList();
</code>```

Any idea how solve this problem? I try with any combination of expression... :/

答:
I had the same problem today and my solution was similar to what Yoda listed, however it only works with fluent syntax.

Adapting my solution to your code:
I added the following static method to the object class

```<code>    /// <summary>
    /// use this instead of a parameritized constructor when you need support
    /// for LINQ to entities (fluent syntax only)
    /// </summary>
    /// <returns></returns>
    public static Func<Naleznosci, Payments> Initializer()
    {
        return n => new Payments
        {
             Imie = n.Dziecko.Imie,
             Nazwisko = n.Dziecko.Nazwisko,
             Nazwa = n.Miesiace.Nazwa,
             Kwota = n.Kwota,
             NazwaRodzajuOplaty = n.RodzajeOplat.NazwaRodzajuOplaty,
             NazwaTypuOplaty = n.RodzajeOplat.TypyOplat.NazwaTypuOplaty,
             DataRozliczenia = n.DataRozliczenia,
             TerminPlatnosc = n.TerminPlatnosci
        };
    }
</code>```

and then updated the base query to the following:

```<code>var naleznosci = (from nalTmp in db.Naleznosci
    where nalTmp.idDziecko == idDziec
    select new Payments.Initializer());
</code>```

This is logically equivalent to James Manning's solution with the advantage of pushing the bloat of member initialization to the Class / Data Transfer Object

Note:  Originally I was using more descriptive names that "Initializer"
but after reviewing how I was using it, I found that "Initilizer" was sufficient (at least for my purposes).

Final Note:

After coming up with this solution I was originally thinking it would be simple to share the same code and adapt this to work for Query syntax as well.  I am no longer believe that to be the case.  I think that if you want to be able to use this type of shorthand construction you would need a method for each (query,fluent)   fluent as described above which can exist in the object class itself.

For query syntax an extension method (or some method outside of the base class being used) would be required.  (since query syntax wants to operate an IQueryable rather than T)

Here is a sample of what I used to finally get this to work for query syntax.  (Yoda already nailed this but I think the usage could be clearer because I didn't get it at first)

```<code>/// <summary>
/// use this instead of a parameritized constructor when you need support
/// for LINQ to entities (query syntax only)
/// </summary>
/// <returns></returns>
public static IQueryable<Payments> Initializer(this IQueryable<Naleznosci> source)
{
    return source.Select(
        n => new Payments
        {
            Imie = n.Dziecko.Imie,
            Nazwisko = n.Dziecko.Nazwisko,
            Nazwa = n.Miesiace.Nazwa,
            Kwota = n.Kwota,
            NazwaRodzajuOplaty = n.RodzajeOplat.NazwaRodzajuOplaty,
            NazwaTypuOplaty = n.RodzajeOplat.TypyOplat.NazwaTypuOplaty,
            DataRozliczenia = n.DataRozliczenia,
            TerminPlatnosc = n.TerminPlatnosci
    };
}
</code>```

and the usage

```<code>var naleznosci = (from nalTmp in db.Naleznosci
    where nalTmp.idDziecko == idDziec
    select nalTmp).Initializer().ToList();
</code>```

Body:
I have this error in this linq expression :

var naleznosci = (from nalTmp in db.Naleznosci
                              where nalTmp.idDziecko == idDziec
                              select new Payments
                              (
                                  nalTmp.Dziecko.Imie,
                                  nalTmp.Dziecko.Nazwisko,
                                  nalTmp.Miesiace.Nazwa,
                                  nalTmp.Kwota,
                                  nalTmp.RodzajeOplat.NazwaRodzajuOplaty,
                                  nalTmp.RodzajeOplat.TypyOplat.NazwaTypuOplaty,
                                  nalTmp.DataRozliczenia,
                                  nalTmp.TerminPlatnosci
                              )).ToList();

Any idea how solve this problem? I try with any combination of expression... :/

Body:
I had the same problem today and my solution was similar to what Yoda listed, however it only works with fluent syntax.

Adapting my solution to your code:
I added the following static method to the object class

    /// <summary>
    /// use this instead of a parameritized constructor when you need support
    /// for LINQ to entities (fluent syntax only)
    /// </summary>
    /// <returns></returns>
    public static Func<Naleznosci, Payments> Initializer()
    {
        return n => new Payments
        {
             Imie = n.Dziecko.Imie,
             Nazwisko = n.Dziecko.Nazwisko,
             Nazwa = n.Miesiace.Nazwa,
             Kwota = n.Kwota,
             NazwaRodzajuOplaty = n.RodzajeOplat.NazwaRodzajuOplaty,
             NazwaTypuOplaty = n.RodzajeOplat.TypyOplat.NazwaTypuOplaty,
             DataRozliczenia = n.DataRozliczenia,
             TerminPlatnosc = n.TerminPlatnosci
        };
    }

and then updated the base query to the following:

var naleznosci = (from nalTmp in db.Naleznosci
    where nalTmp.idDziecko == idDziec
    select new Payments.Initializer());

This is logically equivalent to James Manning's solution with the advantage of pushing the bloat of member initialization to the Class / Data Transfer Object

Note:  Originally I was using more descriptive names that "Initializer"
but after reviewing how I was using it, I found that "Initilizer" was sufficient (at least for my purposes).

Final Note:

After coming up with this solution I was originally thinking it would be simple to share the same code and adapt this to work for Query syntax as well.  I am no longer believe that to be the case.  I think that if you want to be able to use this type of shorthand construction you would need a method for each (query,fluent)   fluent as described above which can exist in the object class itself.

For query syntax an extension method (or some method outside of the base class being used) would be required.  (since query syntax wants to operate an IQueryable rather than T)

Here is a sample of what I used to finally get this to work for query syntax.  (Yoda already nailed this but I think the usage could be clearer because I didn't get it at first)

/// <summary>
/// use this instead of a parameritized constructor when you need support
/// for LINQ to entities (query syntax only)
/// </summary>
/// <returns></returns>
public static IQueryable<Payments> Initializer(this IQueryable<Naleznosci> source)
{
    return source.Select(
        n => new Payments
        {
            Imie = n.Dziecko.Imie,
            Nazwisko = n.Dziecko.Nazwisko,
            Nazwa = n.Miesiace.Nazwa,
            Kwota = n.Kwota,
            NazwaRodzajuOplaty = n.RodzajeOplat.NazwaRodzajuOplaty,
            NazwaTypuOplaty = n.RodzajeOplat.TypyOplat.NazwaTypuOplaty,
            DataRozliczenia = n.DataRozliczenia,
            TerminPlatnosc = n.TerminPlatnosci
    };
}

and the usage

var naleznosci = (from nalTmp in db.Naleznosci
    where nalTmp.idDziecko == idDziec
    select nalTmp).Initializer().ToList();


问:
jQuery - Variable Scope Problem
I have the following javascript:

```<code>      $.getJSON('/calculate_quote/' + moulding_1_id, function(data) {
        moulding_1_cost = data.moulding.cost;
        moulding_1_width = data.moulding.width;
      });
      cost_of_moulding = ( ( 2 * ( width + ( 2 * moulding_1_width ) ) + 2 * ( height + ( 2 * moulding_1_width ) ) ) / 1000 ) * moulding_1_cost;
      $('#item_total').html( cost_of_moulding );
</code>```

The problem is that the two variables moulding_1_cost and moulding_1_width are undefined outside of the getJSON call.  How do I make these two variables available outside the getJSON call?

答: You should be doing everything inside the getJSON call to ensure that it happens in the correct order.</p>

Title: jQuery - Variable Scope Problem

Body:
I have the following javascript:

      $.getJSON('/calculate_quote/' + moulding_1_id, function(data) {
        moulding_1_cost = data.moulding.cost;
        moulding_1_width = data.moulding.width;
      });
      cost_of_moulding = ( ( 2 * ( width + ( 2 * moulding_1_width ) ) + 2 * ( height + ( 2 * moulding_1_width ) ) ) / 1000 ) * moulding_1_cost;
      $('#item_total').html( cost_of_moulding );

The problem is that the two variables moulding_1_cost and moulding_1_width are undefined outside of the getJSON call.  How do I make these two variables available outside the getJSON call?


问:
Is it possible to make a real function type in C++ which is callable with itself?
I am trying to write recursion without referencing the function name in C++ by means of Y-combinator. However, I can't figure out the type of the Function in the following attempt:

```<code>#include <iostream>

using std::cin;
using std::cout;

template<class Function> unsigned long factorial1(Function self, unsigned long n) {
    return n ? n * self(self, n - 1) : 1;
}

unsigned long factorial(unsigned long n) {
    return factorial1(factorial1, n);
}

int main() {
    unsigned long n;
    cin >> n;
    cout << factorial(n) << '\n';
    return 0;
}
</code>```

The compiler cannot deduce what is Function, neither can me. Then I tried the following:

```<code>#include <iostream>

using std::cin;
using std::cout;

struct Factorial {
    template<class Function> unsigned long operator()(Function self, unsigned long n) const {
        return n ? n * self(self, n - 1) : 1;
    }
};

unsigned long factorial(unsigned long n) {
    return Factorial()(Factorial(), n);
}

int main() {
    unsigned long n;
    cin >> n;
    cout << factorial(n) << '\n';
    return 0;
}
</code>```

This, when compared to the above example, the difference is I changed the work function to a callable object, which Function is deduced easily as Factorial, leading to the following complete implementation of the combinator:

```<code>#include <iostream>

using std::cin;
using std::cout;

struct Factorial {
    template<class Function> unsigned long operator()(Function self, unsigned long n) const {
        return n ? n * self(self, n - 1) : 1;
    }
};

template<class Function> auto y(Function f) {
    return [f](auto n) {
        return f(f, n);
    };
}

int main() {
    unsigned long n;
    cin >> n;
    cout << y(Factorial())(n) << '\n';
    return 0;
}
</code>```

The question is that, is it possible to rewrite the struct Factorial to a plain function?

答:
You can't pass templates directly, but you could use generic lambda on fly, so in the end it would look like you use the template:

```<code>#define PASS_FUNC(name) [dummy=nullptr](auto&&... args){return name(decltype(args)(args)...);}

template<class Function> unsigned long factorial1(Function self, unsigned long n) {
    return n ? n * self(self, n - 1) : 1;
}

unsigned long factorial(unsigned long n) {
    return factorial1(PASS_FUNC(factorial1), n);
}
</code>```

But I would consider this a hack since lambdas are still function objects.

Body:
I am trying to write recursion without referencing the function name in C++ by means of Y-combinator. However, I can't figure out the type of the Function in the following attempt:

#include <iostream>

using std::cin;
using std::cout;

template<class Function> unsigned long factorial1(Function self, unsigned long n) {
    return n ? n * self(self, n - 1) : 1;
}

unsigned long factorial(unsigned long n) {
    return factorial1(factorial1, n);
}

int main() {
    unsigned long n;
    cin >> n;
    cout << factorial(n) << '\n';
    return 0;
}

The compiler cannot deduce what is Function, neither can me. Then I tried the following:

#include <iostream>

using std::cin;
using std::cout;

struct Factorial {
    template<class Function> unsigned long operator()(Function self, unsigned long n) const {
        return n ? n * self(self, n - 1) : 1;
    }
};

unsigned long factorial(unsigned long n) {
    return Factorial()(Factorial(), n);
}

int main() {
    unsigned long n;
    cin >> n;
    cout << factorial(n) << '\n';
    return 0;
}

This, when compared to the above example, the difference is I changed the work function to a callable object, which Function is deduced easily as Factorial, leading to the following complete implementation of the combinator:

#include <iostream>

using std::cin;
using std::cout;

struct Factorial {
    template<class Function> unsigned long operator()(Function self, unsigned long n) const {
        return n ? n * self(self, n - 1) : 1;
    }
};

template<class Function> auto y(Function f) {
    return [f](auto n) {
        return f(f, n);
    };
}

int main() {
    unsigned long n;
    cin >> n;
    cout << y(Factorial())(n) << '\n';
    return 0;
}

The question is that, is it possible to rewrite the struct Factorial to a plain function?

Body:
You can't pass templates directly, but you could use generic lambda on fly, so in the end it would look like you use the template:

#define PASS_FUNC(name) [dummy=nullptr](auto&&... args){return name(decltype(args)(args)...);}

template<class Function> unsigned long factorial1(Function self, unsigned long n) {
    return n ? n * self(self, n - 1) : 1;
}

unsigned long factorial(unsigned long n) {
    return factorial1(PASS_FUNC(factorial1), n);
}

But I would consider this a hack since lambdas are still function objects.


问:
How to include a closure in an R-package?
I would like to include a closure with the functions of an R package we are writing. The function (and its siblings) will have data in its environment, perform a comparison of input with the data, and return the result. To illustrate, think of a function with an inbuilt telephone directory: you query with a number and the function returns a name.

This function will be called as a helper by several other functions in our R package, so it has to exist once the package is loaded. And we want the function to be available in the package environment, just like any other function.

Should I create it via its factory function in .onLoad() and assign() it to the package environment? Could I ship it as an .RDS? Or RData, or does this violate CRAN policy on "binary executable code"? Or is there a different, canonical way? And where would the code and the data (or the RDS/RData) go in the package directory structure?

(I see that the question of how to document a closure has been discussed here).

答:
For the benefit of anyone stumbling on this question. The solution I finally worked out involved a few steps but is "clean" as far as I can tell.

Put the factory function in a file R/aaa.R to ensure it gets loaded before the closure.

Put the data that the closure uses into the standard inst/extdata/ folder.

Put a file with the closure's name and proper docstring into R/: define the closure as a normal function that just returns nothing. This is necessary so the function is properly exported and known in the package namespace. Immediately call the factory function to create the closure and overwrite the original definition. Note: it's not enough to just bring the data into the factory function as an argument, it actually needs to be accessed before defining the closure. Why? That's because lazy loading won't actually have loaded the data into the environment you need it in unless you access it.

That's all. Summary: create a stub for your closure, then overwrite that with the return value of the factory function.


问:
Function Overloading with const
```<code>struct A
{
    void fn(double a) const {}
    void fn(int a){}
};
int main()
{
    A().fn(1.);
}
</code>```

For the above mentioned function why does the compiler produce an ambiguity; Both the types are different.

答:
Why would you like to pass an int only to a non-const A?

There are two parameters to each member function, this and a. So you require a const A* for this and doublefor a, or non-const A* and int.

And the call doesn't fully match either alternative, as you have non-const Aand double. So the compiler can either convert A() to const A, or doubleto int. And it cannot decide which is the best.

Title: Function Overloading with const

Body:
struct A
{
    void fn(double a) const {}
    void fn(int a){}
};
int main()
{
    A().fn(1.);
}

For the above mentioned function why does the compiler produce an ambiguity; Both the types are different.