问:
countdown timer on alert box in android
How do i display a countdown timer in my alert box .i want to notify the user that the session will end in 5 minutes and show a timer running in the alert pop up box in android</p>

答:
The following code creates a prompt as you described. It adds a count down timer to a default action button.

Dialog Listener Class

```<code>private static class DialogTimeoutListener
        implements DialogInterface.OnShowListener, DialogInterface.OnDismissListener {
    private static final int AUTO_DISMISS_MILLIS = 5 * 60 * 1000;
    private CountDownTimer mCountDownTimer;

    @Override
    public void onShow(final DialogInterface dialog) {
        final Button defaultButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
        final CharSequence positiveButtonText = defaultButton.getText();
        mCountDownTimer = new CountDownTimer(AUTO_DISMISS_MILLIS, 100) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (millisUntilFinished > 60000) {
                    defaultButton.setText(String.format(
                            Locale.getDefault(), "%s (%d:%02d)",
                            positiveButtonText,
                            TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
                            TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished % 60000)
                    ));
                } else {
                    defaultButton.setText(String.format(
                            Locale.getDefault(), "%s (%d)",
                            positiveButtonText,
                            TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) + 1 //add one so it never displays zero
                    ));
                }
            }

            @Override
            public void onFinish() {
                if (((AlertDialog) dialog).isShowing()) {
                    // TODO: call your logout method
                    dialog.dismiss();
                }
            }
        };
        mCountDownTimer.start();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        mCountDownTimer.cancel();
    }
</code>```

Alert Dialog

```<code>AlertDialog dialog = new AlertDialog.Builder(this)
        .setTitle("Session Timeout")
        .setMessage("Due to inactivity, you will soon be logged out.")
        .setPositiveButton("Extend Session", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO: call your log out method
            }
        })
        .setNegativeButton("Log Out Now", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO: call method to extend session
            }
        })
        .create();
DialogTimeoutListener listener = new DialogTimeoutListener();
dialog.setOnShowListener(listener);
dialog.setOnDismissListener(listener);
dialog.show();
</code>```

Title: countdown timer on alert box in android

Body:
The following code creates a prompt as you described. It adds a count down timer to a default action button.

Dialog Listener Class

private static class DialogTimeoutListener
        implements DialogInterface.OnShowListener, DialogInterface.OnDismissListener {
    private static final int AUTO_DISMISS_MILLIS = 5 * 60 * 1000;
    private CountDownTimer mCountDownTimer;

    @Override
    public void onShow(final DialogInterface dialog) {
        final Button defaultButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
        final CharSequence positiveButtonText = defaultButton.getText();
        mCountDownTimer = new CountDownTimer(AUTO_DISMISS_MILLIS, 100) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (millisUntilFinished > 60000) {
                    defaultButton.setText(String.format(
                            Locale.getDefault(), "%s (%d:%02d)",
                            positiveButtonText,
                            TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
                            TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished % 60000)
                    ));
                } else {
                    defaultButton.setText(String.format(
                            Locale.getDefault(), "%s (%d)",
                            positiveButtonText,
                            TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) + 1 //add one so it never displays zero
                    ));
                }
            }

            @Override
            public void onFinish() {
                if (((AlertDialog) dialog).isShowing()) {
                    // TODO: call your logout method
                    dialog.dismiss();
                }
            }
        };
        mCountDownTimer.start();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        mCountDownTimer.cancel();
    }

Alert Dialog

AlertDialog dialog = new AlertDialog.Builder(this)
        .setTitle("Session Timeout")
        .setMessage("Due to inactivity, you will soon be logged out.")
        .setPositiveButton("Extend Session", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO: call your log out method
            }
        })
        .setNegativeButton("Log Out Now", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO: call method to extend session
            }
        })
        .create();
DialogTimeoutListener listener = new DialogTimeoutListener();
dialog.setOnShowListener(listener);
dialog.setOnDismissListener(listener);
dialog.show();


来源: stackexchange

问:
R: How to add the values of each objects in a list of different objects
I am attempting to count the values associated with each different object/team to determine which team has the highest value.
I have a created a matrix where one column states the home team, one column is the visiting team and the last column gives the value of 1, 0 or NA. If the value is 1 the home team won, 0 the visiting team wins, and NA means a tie occurred.

Here is what my matrix (winners) looks like:

```<code>      home_team      visit_team     home_outcomes
 [1,] "Brewers"      "Marlins"      "1"
 [2,] "Rockies"      "Giants"       "0"
 [3,] "Rangers"      "Cardinals"    "0"
 [4,] "Nationals"    "Cubs"         "1"
 [5,] "Braves"       "Nationals"    "1"
 [6,] "Pirates"      "Reds"         "1"
 [7,] "Rays"         "Mariners"     "1"
 [8,] "Orioles"      "Dodgers"      "0"
 [9,] "Marlins"      "Reds"         "1"
[10,] "Mets"         "Royals"       "1"
</code>```

The full matrix is 703 rows.

I am looking to count the values and see which team has won the most amount of games.

I have tried an array of methods to tackle this, but I am brand new to R and am a bit confused. Any help is appreciated!

okay. I am literally brand new to R and any coding in general, so when asked to dput() my code, I believe this is what I am being asked to do. Thanks everyone! Great community!

```<code>    structure(c("Brewers", "Rockies", "Rangers", "Nationals", "Braves",
"Pirates", "Rays", "Orioles", "Marlins", "Mets", "Rockies", "Padres",
"Royals", "Rangers", "White", "Reds", "Dodgers", "Tigers", "Yankees",
"Cubs", "Yankees", "Tigers", "Athletics", "Tigers", "Mariners",
"Brewers", "Brewers", "Reds", "Cubs", "Rays", "Indians", "Twins",
"Rays", "Angels", "Marlins", "Pirates", "Rockies", "Orioles",
"Indians", "Astros", "Blue", "Reds", "Padres", "Blue", "Rangers",
"Royals", "Athletics", "Tigers", "Brewers", "Diamondbacks", "Orioles",
"Phillies", "Red", "Mets", "Orioles", "Athletics", "Mets", "Padres",
"Reds", "Phillies", "Rangers", "Cubs", "Phillies", "Orioles",
"Red", "Giants", "Red", "Cardinals", "Angels", "Padres", "Yankees",
"Yankees", "Rangers", "Cardinals", "Rockies", "Marlins", "White",
"Mets", "Rockies", "Diamondbacks", "Cubs", "Rockies", "Marlins",
"Blue", "White", "Yankees", "Indians", "Rangers", "Red", "Orioles",
"Marlins", "Rays", "Rangers", "Giants", "Cubs", "Dodgers", "Nationals",
"Orioles", "Diamondbacks", "Cubs", "Braves", "Cubs", "Tigers",
"Astros", "Padres", "Dodgers", "Cardinals", "Cubs", "Twins",
"Cardinals", "Tigers", "Reds", "Marlins", "Astros", "Blue", "Giants",
"Giants", "Yankees", "Mets", "Dodgers", "Rangers", "Reds", "Phillies",
"Padres", "White", "Braves", "Reds", "Padres", "Rangers", "Nationals",
"Cardinals", "White", "Pirates", "Red", "Twins", "Tigers", "Nationals",
"Braves", "Reds", "Marlins", "Astros", "Orioles", "Diamondbacks",
"Athletics", "Royals", "Athletics", "Cubs", "Rockies", "Orioles",
"Mets", "Rays", "Angels", "Reds", "Tigers", "Padres", "Dodgers",
"Cubs", "Mets", "Angels", "Athletics", "Astros", "White", "Reds",
"Athletics", "Braves", "Athletics", "Orioles", "Twins", "Rockies",
"Reds", "Reds", "Rays", "Diamondbacks", "Marlins", "Yankees",
"Astros", "Rockies", "Orioles", "Indians", "Cardinals", "Padres",
"Mets", "Royals", "Marlins", "Tigers", "Marlins", "Braves", "Rays",
"Red", "Rangers", "Mariners", "Marlins", "Athletics", "Cardinals",
"Mariners", "Diamondbacks", "Red", "Tigers", "White", "Royals",
"Twins", "Rays", "Red", "Rays", "White", "Twins", "Giants", "Mets",
"Padres", "Giants", "Cubs", "Mariners", "Giants", "Rays", "Dodgers",
"Blue", "Phillies", "Cardinals", "Mariners", "Cubs", "Cardinals",
"Yankees", "Indians", "Athletics", "Royals", "Rangers", "Rangers",
"Mets", "Yankees", "Astros", "Dodgers", "White", "Athletics",
"Marlins", "Dodgers", "Brewers", "Rockies", "Nationals", "Phillies",
"Marlins", "Angels", "Red", "Cubs", "Rockies", "Athletics", "Giants",
"Mets", "Orioles", "Tigers", "Pirates", "Yankees", "Padres",
"Cardinals", "Astros", "Athletics", "Marlins", "Twins", "Nationals",
"Braves", "Yankees", "Cardinals", "Mets", "Blue", "Phillies",
"Twins", "Orioles", "Royals", "Phillies", "Twins", "Orioles",
"Red", "Brewers", "Dodgers", "Cardinals", "Orioles", "Yankees",
"Athletics", "Mets", "Rays", "Brewers", "Royals", "Dodgers",
"Pirates", "Nationals", "Mets", "Dodgers", "Red", "Cardinals",
"Twins", "Cardinals", "Blue", "Braves", "Giants", "Twins", "Cubs",
"Indians", "Cardinals", "Royals", "Giants", "Phillies", "Mariners",
"Reds", "Royals", "Giants", "Astros", "Braves", "Rays", "Padres",
"Blue", "Marlins", "Rockies", "Diamondbacks", "Reds", "White",
"Mets", "Rays", "White", "Mets", "Padres", "Astros", "Angels",
"Padres", "Pirates", "Pirates", "Reds", "Orioles", "Athletics",
"Giants", "Braves", "Twins", "Rays", "Brewers", "Nationals",
"Marlins", "Twins", "Phillies", "Giants", "Athletics", "Pirates",
"Mets", "Astros", "Rays", "Yankees", "Twins", "Rangers", "Diamondbacks",
"Yankees", "Angels", "Cubs", "Indians", "Tigers", "White", "Tigers",
"Cardinals", "Brewers", "Diamondbacks", "Mariners", "Nationals",
"Marlins", "White", "Tigers", "Rockies", "Diamondbacks", "Cubs",
"Indians", "Marlins", "Rockies", "Padres", "Nationals", "Dodgers",
"Brewers", "Rockies", "Braves", "Phillies", "Twins", "Yankees",
"Cubs", "Rangers", "Mets", "Tigers", "Astros", "Rangers", "Yankees",
"Giants", "Padres", "Orioles", "Yankees", "Phillies", "Astros",
"Royals", "Cardinals", "Rockies", "Mariners", "Angels", "Cardinals",
"Dodgers", "White", "Nationals", "Red", "Royals", "Tigers", "Rangers",
"Red", "Athletics", "Rays", "Angels", "Phillies", "Brewers",
"Rangers", "Royals", "Phillies", "Pirates", "Tigers", "Nationals",
"Rays", "White", "Red", "Rays", "Giants", "Giants", "Royals",
"Twins", "Red", "Nationals", "All", "Astros", "Pirates", "Brewers",
"White", "Royals", "Cubs", "Tigers", "Brewers", "Yankees", "White",
"Diamondbacks", "Angels", "Diamondbacks", "Indians", "Blue",
"Angels", "Marlins", "Indians", "Blue", "Giants", "Rays", "Twins",
"Red", "Phillies", "Cubs", "Nationals", "Twins", "Indians", "Rays",
"Pirates", "Padres", "Mets", "Marlins", "Rangers", "Braves",
"Rays", "Rangers", "White", "Braves", "Yankees", "Cubs", "Blue",
"Mets", "White", "Brewers", "Royals", "Angels", "Indians", "Nationals",
"Nationals", "Blue", "Rays", "Indians", "Pirates", "Mets", "Marlins",
"Marlins", "Marlins", "Giants", "Yankees", "Giants", "Nationals",
"Mets", "Indians", "Angels", "Yankees", "Marlins", "Mets", "Rockies",
"Orioles", "Indians", "Blue", "Twins", "Orioles", "Blue", "Angels",
"Phillies", "Blue", "Athletics", "Brewers", "Astros", "Orioles",
"Mets", "Athletics", "Tigers", "Mariners", "Dodgers", "Rays",
"Yankees", "Phillies", "Reds", "Brewers", "Red", "White", "Rays",
"Tigers", "Indians", "White", "Red", "Twins", "Marlins", "Nationals",
"Mariners", "Blue", "Marlins", "Mariners", "Dodgers", "Mets",
"Marlins", "Rangers", "Marlins", "Dodgers", "Dodgers", "Padres",
"Rays", "Rays", "Diamondbacks", "Marlins", "Indians", "Marlins",
"Astros", "Angels", "Tigers", "Tigers", "Twins", "White", "Phillies",
"Diamondbacks", "Mariners", "Indians", "Dodgers", "Athletics",
"Royals", "Brewers", "Dodgers", "Astros", "Brewers", "Reds",
"Nationals", "Angels", "Astros", "Indians", "Athletics", "Padres",
"Nationals", "Yankees", "Blue", "Red", "Cubs", "Brewers", "Rangers",
"Pirates", "Mets", "Yankees", "Reds", "Cubs", "Rangers", "Pirates",
"Rays", "Yankees", "Royals", "Giants", "Royals", "Cubs", "Mariners",
"Astros", "Rockies", "Mets", "Pirates", "Reds", "Athletics",
"Cubs", "Royals", "Giants", "Twins", "Mariners", "Twins", "Rangers",
"Brewers", "Reds", "Rays", "Orioles", "Red", "Dodgers", "Tigers",
"Brewers", "Angels", "Astros", "Nationals", "Brewers", "Athletics",
"Rangers", "Rangers", "Indians", "Mariners", "Yankees", "Cardinals",
"Royals", "Tigers", "Indians", "Red", "Indians", "Blue", "Tigers",
"White", "Giants", "Mets", "Rangers", "Diamondbacks", "Athletics",
"Rays", "Brewers", "Marlins", "Phillies", "Marlins", "Phillies",
"Diamondbacks", "Brewers", "Red", "Yankees", "Nationals", "Athletics",
"Astros", "Astros", "Twins", "Giants", "Red", "Marlins", "Blue",
"Dodgers", "Braves", "Indians", "Blue", "Mets", "Blue", "Diamondbacks",
"Phillies", "Yankees", "Royals", "Diamondbacks", "Yankees", "Athletics",
"Dodgers", "Pirates", "Orioles", "Cubs", "Mets", "Phillies",
"Mets", "Reds", "Rockies", "Red", "Marlins", "Braves", "Royals",
"Mariners", "Yankees", "Red", "Dodgers", "Dodgers", "Nationals",
"Indians", "Indians", "Padres", "Marlins", "Twins", "Braves",
"Astros", "Braves", "Diamondbacks", "Athletics", "Cubs", "Reds",
"Athletics", "Braves", "Mariners", "Pirates", "Blue", "Blue",
"Royals", "Cubs", "Giants", "Athletics", "Yankees", "Dodgers",
"Yankees", "Mariners", "Astros", "Diamondbacks", "Diamondbacks",
"Brewers", "Mets", "Dodgers", "Braves", "Phillies", "Athletics",
"Angels", "Mariners", "Reds", "Rockies", "Reds", "Indians", "Nationals",
"Indians", "Mets", "Rockies", "Rays", "Rockies", "Mets", "Padres",
"Orioles", "Brewers", "Reds", "Twins", "Indians", "Pirates",
"Braves", "Astros", "Twins", "Nationals", "Twins", "Blue", "Pirates",
"Pirates", "Indians", "Mariners", "Mets", "Marlins", "Giants",
"Cardinals", "Cubs", "Nationals", "Reds", "Mariners", "Dodgers",
"Reds", "Royals", "Dodgers", "Mets", "Indians", "Athletics",
"Rays", "Dodgers", "Giants", "Angels", "Indians", "Cardinals",
"Royals", "Nationals", "Rangers", "Sox", "Athletics", "Rockies",
"Braves", "Padres", "Marlins", "Rangers", "Twins", "Nationals",
"Orioles", "Mariners", "Mets", "Mets", "Yankees", "Royals", "Twins",
"Mariners", "Astros", "Rangers", "Braves", "Athletics", "Astros",
"Twins", "Angels", "Twins", "Cubs", "Reds", "Yankees", "Tigers",
"Yankees", "Cubs", "Rays", "Brewers", "Royals", "Cubs", "Giants",
"Diamondbacks", "Cubs", "Cardinals", "Cardinals", "Twins", "Padres",
"Dodgers", "Jays", "Braves", "Astros", "Giants", "Twins", "Pirates",
"Mariners", "Pirates", "Dodgers", "Pirates", "Indians", "Jays",
"Pirates", "Rockies", "Dodgers", "Padres", "Nationals", "Astros",
"Cubs", "Athletics", "Twins", "Cubs", "Royals", "Sox", "Diamondbacks",
"Yankees", "Sox", "Braves", "Sox", "Reds", "Marlins", "Sox",
"Dodgers", "Cardinals", "Tigers", "Giants", "Marlins", "Mariners",
"Phillies", "Yankees", "Marlins", "Phillies", "Marlins", "Cubs",
"Sox", "Mets", "Twins", "Royals", "Yankees", "Yankees", "Mets",
"Rays", "Giants", "Marlins", "Reds", "Braves", "Cardinals", "Giants",
"Cubs", "Diamondbacks", "Indians", "Cardinals", "Sox", "Orioles",
"Brewers", "Orioles", "Athletics", "Yankees", "Nationals", "Indians",
"Royals", "Diamondbacks", "Indians", "Giants", "Rangers", "Indians",
"Marlins", "Orioles", "Athletics", "Angels", "Nationals", "Padres",
"Sox", "Brewers", "Twins", "Astros", "Sox", "Jays", "Royals",
"Sox", "Padres", "Marlins", "Athletics", "Angels", "Braves",
"Tigers", "Dodgers", "Twins", "Reds", "Angels", "Phillies", "Jays",
"Mets", "Pirates", "Brewers", "Jays", "Padres", "Nationals",
"Indians", "Yankees", "Cardinals", "Mariners", "Braves", "Angels",
"Diamondbacks", "Phillies", "Rangers", "Twins", "Yankees", "Phillies",
"Nationals", "Jays", "Orioles", "Athletics", "Reds", "Mets",
"Royals", "Cubs", "Pirates", "Giants", "Angels", "Indians", "Jays",
"Mariners", "Tigers", "Tigers", "Yankees", "Jays", "Yankees",
"Mariners", "Padres", "Brewers", "Phillies", "Padres", "Cardinals",
"Giants", "Padres", "Sox", "Cubs", "Astros", "Braves", "Cubs",
"Brewers", "Brewers", "Cubs", "Mets", "Royals", "Mariners", "Tigers",
"Angels", "Angels", "Nationals", "Mariners", "Angels", "Reds",
"Indians", "Giants", "Diamondbacks", "Marlins", "Athletics",
"Dodgers", "Dodgers", "Mets", "Sox", "Athletics", "Braves", "Indians",
"Brewers", "Mariners", "Marlins", "Cardinals", "Jays", "Twins",
"Phillies", "Jays", "Cubs", "Pirates", "Angels", "Angels", "Cardinals",
"Phillies", "Pirates", "Orioles", "Braves", "Brewers", "Tigers",
"Sox", "Cubs", "Mets", "Angels", "Athletics", "Marlins", "Royals",
"Sox", "Orioles", "Cubs", "Giants", "Cubs", "Yankees", "Tigers",
"Indians", "Padres", "Orioles", "Padres", "Rays", "Brewers",
"Marlins", "Royals", "Braves", "Padres", "Twins", "Marlins",
"Nationals", "Giants", "Tigers", "Diamondbacks", "Phillies",
"Brewers", "Diamondbacks", "Sox", "Mets", "Twins", "Diamondbacks",
"Marlins", "Athletics", "Diamondbacks", "Rays", "Padres", "Twins",
"Brewers", "Twins", "Pirates", "Royals", "Phillies", "Giants",
"Reds", "Phillies", "Royals", "Braves", "Tigers", "Tigers", "Marlins",
"Diamondbacks", "Rangers", "Rangers", "Cardinals", "Athletics",
"Tigers", "Giants", "Astros", "Royals", "Nationals", "Rockies",
"Indians", "Sox", "Diamondbacks", "Mets", "Rays", "Royals", "Jays",
"Nationals", "Royals", "Rockies", "Dodgers", "Twins", "Tigers",
"Padres", "Braves", "Royals", "Mets", "Diamondbacks", "Rangers",
"Phillies", "Jays", "Twins", "Rangers", "Jays", "Reds", "Dodgers",
"Jays", "Rangers", "Cardinals", "Padres", "Phillies", "Royals",
"Marlins", "Sox", "Pirates", "Sox", "Reds", "Sox", "Phillies",
"Phillies", "Diamondbacks", "Sox", "Cardinals", "Diamondbacks",
"Jays", "Tigers", "Rays", "Rockies", "Astros", "Giants", "Rangers",
"Rays", "Mariners", "Orioles", "Cubs", "Rays", "Rays", "Angels",
"Twins", "Angels", "Sox", "Mets", "Diamondbacks", "Yankees",
"Rangers", "Mets", "Rockies", "Astros", "Sox", "Indians", "Tigers",
"Rangers", "Angels", "Twins", "Angels", "Royals", "Astros", "Sox",
"Reds", "Angels", "Sox", "Rockies", "Brewers", "Angels", "Braves",
"Twins", "Yankees", "Mariners", "Rockies", "Dodgers", "Dodgers",
"Angels", "Tigers", "Orioles", "Astros", "All-Stars", "Rays",
"Brewers", "Diamondbacks", "Royals", "Tigers", "Brewers", "Jays",
"Rockies", "Athletics", "Indians", "Braves", "Sox", "Nationals",
"Sox", "Mariners", "Twins", "Cardinals", "Tigers", "Rangers",
"Mariners", "Indians", "Indians", "Sox", "Marlins", "Pirates",
"Dodgers", "Athletics", "Brewers", "Sox", "Phillies", "Dodgers",
"Marlins", "Brewers", "Tigers", "Jays", "Orioles", "Mariners",
"Astros", "Marlins", "Indians", "Phillies", "Sox", "Tigers",
"Royals", "Mets", "Mariners", "Brewers", "Jays", "Marlins", "Phillies",
"Rockies", "Sox", "Tigers", "Mets", "Phillies", "Tigers", "Dodgers",
"Tigers", "Sox", "Mariners", "Marlins", "Phillies", "Nationals",
"Angels", "Dodgers", "Sox", "Nationals", "Cubs", "Brewers", "Sox",
"Dodgers", "Yankees", "Sox", "Twins", "Yankees", "Yankees", "Cardinals",
"Rays", "Rangers", "Pirates", "Yankees", "Sox", "Cubs", "Brewers",
"Rays", "Yankees", "Giants", "Jays", "Athletics", "Cubs", "Indians",
"Cardinals", "Jays", "Tigers", "Mariners", "Sox", "Astros", "Twins",
"Mariners", "Indians", "Mets", "Phillies", "Jays", "Diamondbacks",
"Braves", "Astros", "Jays", "Nationals", "Nationals", "Angels",
"Reds", "Brewers", "Giants", "Marlins", "Marlins", "Orioles",
"Cubs", "Rockies", "Sox", "Mets", "Mariners", "Jays", "Twins",
"Rays", "Royals", "Cubs", "Padres", "Orioles", "Sox", "Rangers",
"Padres", "Tigers", "Cardinals", "Nationals", "Cubs", "Cardinals",
"Reds", "Padres", "Brewers", "Dodgers", "Padres", "Sox", "Royals",
"Brewers", "Mets", "Marlins", "Diamondbacks", "Jays", "Pirates",
"Reds", "Astros", "Phillies", "Indians", "Royals", "Angels",
"Marlins", "Tigers", "Brewers", "Tigers", "Sox", "Angels", "Indians",
"Twins", "Cardinals", "Padres", "Athletics", "Marlins", "Nationals",
"Brewers", "Pirates", "Astros", "Athletics", "Sox", "Padres",
"Sox", "Astros", "Rays", "Rockies", "Cardinals", "Brewers", "Orioles",
"Rays", "Twins", "Giants", "Orioles", "Twins", "Mariners", "Mariners",
"Mets", "Reds", "Reds", "Royals", "Cardinals", "Yankees", "Pirates",
"Twins", "Reds", "Athletics", "Royals", "Reds", "Jays", "Mariners",
"Yankees", "Yankees", "Indians", "Cubs", "Reds", "Sox", "Nationals",
"Mariners", "Pirates", "Mets", "Twins", "Braves", "Cardinals",
"Nationals", "Padres", "Mariners", "Padres", "Orioles", "Mets",
"Sox", "Nationals", "Rangers", "Royals", "Diamondbacks", "Orioles",
"Giants", "Yankees", "Cardinals", "Rockies", "Sox", "Sox", "Reds",
"Rays", "Braves", "Tigers", "Diamondbacks", "Jays", "Rangers",
"Jays", "Reds", "Mets", "Reds", "Dodgers", "Royals", "Phillies",
"Giants", "Braves", "Rockies", "Dodgers", "Mariners", "Indians",
"Cubs", "Indians", "Twins", "Jays", "Astros", "Indians", "Nationals",
"Diamondbacks", "Royals", "Yankees", "Jays", "Dodgers", "Sox",
"Mets", "Brewers", "Rockies", "Giants", "Rangers", "Cardinals",
"Pirates", "Giants", "Nationals", "Indians", "Orioles", "Orioles",
"Giants", "Twins", "Cardinals", "Braves", "Giants", "Tigers",
"Rockies", "Sox", "Indians", "Braves", "Mets", "Orioles", "Pirates",
"Cardinals", "Mariners", "Nationals", "Jays", "Indians", "Twins",
"Angels", "Nationals", "Diamondbacks", "Cubs", "Sox", "Mets",
"Reds", "Cardinals", "Giants", "Yankees", "Cubs", "Marlins",
"Reds", "Padres", "Rangers", "Marlins", "Astros", "Athletics",
"Cardinals", "Mets", "Rangers", "Yankees", "Braves", "Indians",
"Giants", "Sox", "Marlins", "Sox", "Angels", "Phillies", "1",
"0", "0", "1", "1", "1", "1", "0", "1", "1", "1", "1", "1", "1",
"1", "1", "1", "1", "0", "0", "1", "1", "1", "0", "0", "0", "0",
"1", "1", "0", "0", "1", "1", "1", "0", "1", "1", "1", "1", "0",
"1", "0", "1", "1", "0", "0", "0", "0", "0", "0", "0", "1", "0",
"0", "0", "1", "0", "0", "1", "0", "0", "0", "1", "0", "0", "1",
"1", NA, "0", "1", "0", "0", "0", "0", "1", "0", "0", "1", "0",
"1", "1", "1", "0", "1", "1", "0", "0", "1", "1", "0", "1", "0",
"1", "1", "1", "0", "1", "0", "1", "0", "1", "0", "0", "0", "1",
"0", "1", "0", "0", "0", "0", "1", "1", "0", "1", "1", "1", "1",
"1", "0", "1", "0", "1", "1", "1", "0", "0", "1", "1", "1", "0",
"0", "0", "0", "1", "1", "0", "0", "1", "1", "0", "0", "1", "0",
"1", "1", "0", "1", "0", "1", "0", "1", "0", "0", "1", "1", "0",
"0", "1", "1", "0", "1", "1", "0", "1", "0", "1", "1", "0", "0",
"1", "0", "0", "0", "1", "0", "1", "1", "0", "0", "0", "0", "1",
"1", "1", "1", "1", "0", "0", "1", "0", NA, "1", "1", "0", "0",
"1", "0", "0", "1", "1", "1", "1", "0", "1", "0", "1", "0", "0",
"0", "0", "0", "0", "1", "1", "0", "1", "0", "1", "1", "0", NA,
"0", "0", "0", "1", "1", "1", "0", "1", "0", "0", "0", "0", "1",
"1", "1", "1", "1", "0", "1", "0", "1", "1", "1", "0", "1", "1",
"0", "0", "1", "0", "1", "1", "1", "0", "0", "0", "1", "0", "1",
"1", "1", "1", "1", "0", "0", "1", "1", "0", "0", "1", "1", "1",
"0", "1", "1", "0", NA, "1", "0", "0", "1", "0", "0", "1", "1",
"0", "1", "0", "0", "1", "1", "0", "0", "0", "0", "0", "0", "0",
"1", "1", "1", "1", "0", "1", "1", "0", "0", "1", "1", "1", "0",
"1", "1", "1", "1", "0", "1", "1", "1", "1", "0", "1", "0", "1",
"0", "1", "1", "0", "1", "1", "1", "0", "1", "1", "0", "0", "1",
"0", "0", "1", "0", "0", "0", "0", "1", "1", "1", "0", "0", "0",
"1", "1", "1", "0", "1", "0", "0", "1", "1", "1", "1", "0", "1",
"1", "1", "1", "0", "1", "1", "0", "1", "1", "0", "1", "0", "0",
"0", "1", "0", "1", "1", "0", "1", "1", "0", "0", "0", "0", "0",
"0", "0", "1", "0", "0", "1", "0", "0", "1", "0", "1", "1", "1",
"1", "0", "1", "1", "1", "1", "0", "1", "0", "0", "0", "0", "1",
"1", "0", "1", "1", "0", "0", "0", "1", "1", "0", "0", "1", "0",
"1", "1", "1", "0", "1", "0", "0", "0", "0", "0", "1", "0", "0",
"1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "0", "0",
"0", "0", "0", "1", "1", "1", "0", "0", "0", "0", "0", "1", "0",
"1", "0", "1", "1", "0", "0", "0", "1", "0", "1", "0", "1", "0",
"1", "1", "1", "0", "0", "1", NA, "0", "1", "1", "0", "1", "1",
"0", "1", "0", "1", "0", "1", "0", "0", "0", "0", "0", "0", "1",
"1", "0", "1", "1", "1", "0", "1", "1", "1", "0", "1", "1", "1",
"1", "1", "1", "0", "0", "0", "0", "0", "1", "0", "0", "1", "1",
"1", "1", "0", "0", "1", "0", "1", "1", "0", "1", "1", "0", "0",
"0", "0", "1", "1", "0", "1", "1", "0", "0", "1", "0", "0", "0",
"0", "1", "0", "0", "0", "1", NA, "0", "0", "0", "1", "0", "1",
"0", "0", "1", "1", "0", "0", "1", "0", "0", "0", "0", "1", "1",
"0", "0", "0", "0", "1", "0", "1", "0", "0", "1", "0", "0", "1",
"1", "1", "0", "0", "1", "0", "1", "0", "1", "1", "1", "1", "1",
"1", "0", "0", "0", "1", "0", "1", "1", "1", "1", "1", "0", "0",
"1", "1", "0", "0", "1", "1", "0", "1", "1", "1", "1", "1", "0",
"1", "1", "1", "1", "1", "1", "1", "0", "0", "0", "1", "0", "0",
"1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "0", "1", "1",
"1", "0", "1", "0", "0", "1", "1", "1", "0", "1", "0", "0", "0",
"1", "0", "1", "0", "1", "0", NA, "0", "0", "0", "0", "0", "0",
"1", "1", "1", "1", "1", "1", "1", "0", "0", "1", "1", "1", "0",
"0", "1", "1", "1", "0", "1", "1", "0", "0", "0", "0", "1", "0",
"0", "1", "1", "0", "1", "1", "0", "1", "0", "1", "1", "1", "1",
"1", "1", "1", "1", "0", "0", "0", "0", "1", "1", "0", "0", "1",
"1", "1", "0", "1", "0", "0", "1", "1", "1", "0"), .Dim = c(752L,
3L), .Dimnames = list(NULL, c("home_team", "visit_team", "home_outcomes"
)))
</code>```

答:
Below is a quick piece of code that outputs a data.frame with two columns - one is the name of the team, the other is the number of wins (home or away) that team achieved.

This code assumes you structure your data as you mentioned in your question. I have called the matrix 'myMatrix' but you can substitute this however you like.

uniqueTeams <- c(myMatrix[,1],myMatrix[,2])
uniqueTeams <- unique(uniqueTeams)

This first concatonates all the team names in both the home and away team column, then shortens this vector to only include unique values (One vector element per team).

```<code>numTeams <- length(uniqueTeams)
teamWins <- data.frame("Team Name"=uniqueTeams,"No. of Wins"=rep(0,numTeams))
</code>```

This part calculates the number of unuque teams and creates the data.frame which we will store the results in later.

```<code>for (i in 1:numTeams){

  temp <- as.matrix(myMatrix[ myMatrix[,1] == uniqueTeams[i] & myMatrix[,3] == "1",3])
  teamWins[i,2] <- nrow(temp)

  temp <- as.matrix(myMatrix[ myMatrix[,2] == uniqueTeams[i] & myMatrix[,3] == "0",3])
  teamWins[i,2] <- teamWins[i,2] + nrow(temp)

}
</code>```

Finally, I loop through each unique team name. Firstly I create a temporary sub matrix for that team, when they were playing at home and  won and assign the number of rows as my
'No. of Wins' column in the output data frame. I also check if the same team played away and won and add the number of rows in that submatrix to the overall value.

What you are left with is a data.frame with two columns. One is the name of the team, the other the number of overall wins as mentioned earlier.

There may be better ways of tackling this, but this is just what I came up with off the top of my head.

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to count the values associated with each different object/team to determine which team has the highest value.
I have a created a matrix where one column states the home team, one column is the visiting team and the last column gives the value of 1, 0 or NA. If the value is 1 the home team won, 0 the visiting team wins, and NA means a tie occurred.

Here is what my matrix (winners) looks like:

      home_team      visit_team     home_outcomes
 [1,] "Brewers"      "Marlins"      "1"
 [2,] "Rockies"      "Giants"       "0"
 [3,] "Rangers"      "Cardinals"    "0"
 [4,] "Nationals"    "Cubs"         "1"
 [5,] "Braves"       "Nationals"    "1"
 [6,] "Pirates"      "Reds"         "1"
 [7,] "Rays"         "Mariners"     "1"
 [8,] "Orioles"      "Dodgers"      "0"
 [9,] "Marlins"      "Reds"         "1"
[10,] "Mets"         "Royals"       "1"

The full matrix is 703 rows.

I am looking to count the values and see which team has won the most amount of games.

I have tried an array of methods to tackle this, but I am brand new to R and am a bit confused. Any help is appreciated!

okay. I am literally brand new to R and any coding in general, so when asked to dput() my code, I believe this is what I am being asked to do. Thanks everyone! Great community!

    structure(c("Brewers", "Rockies", "Rangers", "Nationals", "Braves",
"Pirates", "Rays", "Orioles", "Marlins", "Mets", "Rockies", "Padres",
"Royals", "Rangers", "White", "Reds", "Dodgers", "Tigers", "Yankees",
"Cubs", "Yankees", "Tigers", "Athletics", "Tigers", "Mariners",
"Brewers", "Brewers", "Reds", "Cubs", "Rays", "Indians", "Twins",
"Rays", "Angels", "Marlins", "Pirates", "Rockies", "Orioles",
"Indians", "Astros", "Blue", "Reds", "Padres", "Blue", "Rangers",
"Royals", "Athletics", "Tigers", "Brewers", "Diamondbacks", "Orioles",
"Phillies", "Red", "Mets", "Orioles", "Athletics", "Mets", "Padres",
"Reds", "Phillies", "Rangers", "Cubs", "Phillies", "Orioles",
"Red", "Giants", "Red", "Cardinals", "Angels", "Padres", "Yankees",
"Yankees", "Rangers", "Cardinals", "Rockies", "Marlins", "White",
"Mets", "Rockies", "Diamondbacks", "Cubs", "Rockies", "Marlins",
"Blue", "White", "Yankees", "Indians", "Rangers", "Red", "Orioles",
"Marlins", "Rays", "Rangers", "Giants", "Cubs", "Dodgers", "Nationals",
"Orioles", "Diamondbacks", "Cubs", "Braves", "Cubs", "Tigers",
"Astros", "Padres", "Dodgers", "Cardinals", "Cubs", "Twins",
"Cardinals", "Tigers", "Reds", "Marlins", "Astros", "Blue", "Giants",
"Giants", "Yankees", "Mets", "Dodgers", "Rangers", "Reds", "Phillies",
"Padres", "White", "Braves", "Reds", "Padres", "Rangers", "Nationals",
"Cardinals", "White", "Pirates", "Red", "Twins", "Tigers", "Nationals",
"Braves", "Reds", "Marlins", "Astros", "Orioles", "Diamondbacks",
"Athletics", "Royals", "Athletics", "Cubs", "Rockies", "Orioles",
"Mets", "Rays", "Angels", "Reds", "Tigers", "Padres", "Dodgers",
"Cubs", "Mets", "Angels", "Athletics", "Astros", "White", "Reds",
"Athletics", "Braves", "Athletics", "Orioles", "Twins", "Rockies",
"Reds", "Reds", "Rays", "Diamondbacks", "Marlins", "Yankees",
"Astros", "Rockies", "Orioles", "Indians", "Cardinals", "Padres",
"Mets", "Royals", "Marlins", "Tigers", "Marlins", "Braves", "Rays",
"Red", "Rangers", "Mariners", "Marlins", "Athletics", "Cardinals",
"Mariners", "Diamondbacks", "Red", "Tigers", "White", "Royals",
"Twins", "Rays", "Red", "Rays", "White", "Twins", "Giants", "Mets",
"Padres", "Giants", "Cubs", "Mariners", "Giants", "Rays", "Dodgers",
"Blue", "Phillies", "Cardinals", "Mariners", "Cubs", "Cardinals",
"Yankees", "Indians", "Athletics", "Royals", "Rangers", "Rangers",
"Mets", "Yankees", "Astros", "Dodgers", "White", "Athletics",
"Marlins", "Dodgers", "Brewers", "Rockies", "Nationals", "Phillies",
"Marlins", "Angels", "Red", "Cubs", "Rockies", "Athletics", "Giants",
"Mets", "Orioles", "Tigers", "Pirates", "Yankees", "Padres",
"Cardinals", "Astros", "Athletics", "Marlins", "Twins", "Nationals",
"Braves", "Yankees", "Cardinals", "Mets", "Blue", "Phillies",
"Twins", "Orioles", "Royals", "Phillies", "Twins", "Orioles",
"Red", "Brewers", "Dodgers", "Cardinals", "Orioles", "Yankees",
"Athletics", "Mets", "Rays", "Brewers", "Royals", "Dodgers",
"Pirates", "Nationals", "Mets", "Dodgers", "Red", "Cardinals",
"Twins", "Cardinals", "Blue", "Braves", "Giants", "Twins", "Cubs",
"Indians", "Cardinals", "Royals", "Giants", "Phillies", "Mariners",
"Reds", "Royals", "Giants", "Astros", "Braves", "Rays", "Padres",
"Blue", "Marlins", "Rockies", "Diamondbacks", "Reds", "White",
"Mets", "Rays", "White", "Mets", "Padres", "Astros", "Angels",
"Padres", "Pirates", "Pirates", "Reds", "Orioles", "Athletics",
"Giants", "Braves", "Twins", "Rays", "Brewers", "Nationals",
"Marlins", "Twins", "Phillies", "Giants", "Athletics", "Pirates",
"Mets", "Astros", "Rays", "Yankees", "Twins", "Rangers", "Diamondbacks",
"Yankees", "Angels", "Cubs", "Indians", "Tigers", "White", "Tigers",
"Cardinals", "Brewers", "Diamondbacks", "Mariners", "Nationals",
"Marlins", "White", "Tigers", "Rockies", "Diamondbacks", "Cubs",
"Indians", "Marlins", "Rockies", "Padres", "Nationals", "Dodgers",
"Brewers", "Rockies", "Braves", "Phillies", "Twins", "Yankees",
"Cubs", "Rangers", "Mets", "Tigers", "Astros", "Rangers", "Yankees",
"Giants", "Padres", "Orioles", "Yankees", "Phillies", "Astros",
"Royals", "Cardinals", "Rockies", "Mariners", "Angels", "Cardinals",
"Dodgers", "White", "Nationals", "Red", "Royals", "Tigers", "Rangers",
"Red", "Athletics", "Rays", "Angels", "Phillies", "Brewers",
"Rangers", "Royals", "Phillies", "Pirates", "Tigers", "Nationals",
"Rays", "White", "Red", "Rays", "Giants", "Giants", "Royals",
"Twins", "Red", "Nationals", "All", "Astros", "Pirates", "Brewers",
"White", "Royals", "Cubs", "Tigers", "Brewers", "Yankees", "White",
"Diamondbacks", "Angels", "Diamondbacks", "Indians", "Blue",
"Angels", "Marlins", "Indians", "Blue", "Giants", "Rays", "Twins",
"Red", "Phillies", "Cubs", "Nationals", "Twins", "Indians", "Rays",
"Pirates", "Padres", "Mets", "Marlins", "Rangers", "Braves",
"Rays", "Rangers", "White", "Braves", "Yankees", "Cubs", "Blue",
"Mets", "White", "Brewers", "Royals", "Angels", "Indians", "Nationals",
"Nationals", "Blue", "Rays", "Indians", "Pirates", "Mets", "Marlins",
"Marlins", "Marlins", "Giants", "Yankees", "Giants", "Nationals",
"Mets", "Indians", "Angels", "Yankees", "Marlins", "Mets", "Rockies",
"Orioles", "Indians", "Blue", "Twins", "Orioles", "Blue", "Angels",
"Phillies", "Blue", "Athletics", "Brewers", "Astros", "Orioles",
"Mets", "Athletics", "Tigers", "Mariners", "Dodgers", "Rays",
"Yankees", "Phillies", "Reds", "Brewers", "Red", "White", "Rays",
"Tigers", "Indians", "White", "Red", "Twins", "Marlins", "Nationals",
"Mariners", "Blue", "Marlins", "Mariners", "Dodgers", "Mets",
"Marlins", "Rangers", "Marlins", "Dodgers", "Dodgers", "Padres",
"Rays", "Rays", "Diamondbacks", "Marlins", "Indians", "Marlins",
"Astros", "Angels", "Tigers", "Tigers", "Twins", "White", "Phillies",
"Diamondbacks", "Mariners", "Indians", "Dodgers", "Athletics",
"Royals", "Brewers", "Dodgers", "Astros", "Brewers", "Reds",
"Nationals", "Angels", "Astros", "Indians", "Athletics", "Padres",
"Nationals", "Yankees", "Blue", "Red", "Cubs", "Brewers", "Rangers",
"Pirates", "Mets", "Yankees", "Reds", "Cubs", "Rangers", "Pirates",
"Rays", "Yankees", "Royals", "Giants", "Royals", "Cubs", "Mariners",
"Astros", "Rockies", "Mets", "Pirates", "Reds", "Athletics",
"Cubs", "Royals", "Giants", "Twins", "Mariners", "Twins", "Rangers",
"Brewers", "Reds", "Rays", "Orioles", "Red", "Dodgers", "Tigers",
"Brewers", "Angels", "Astros", "Nationals", "Brewers", "Athletics",
"Rangers", "Rangers", "Indians", "Mariners", "Yankees", "Cardinals",
"Royals", "Tigers", "Indians", "Red", "Indians", "Blue", "Tigers",
"White", "Giants", "Mets", "Rangers", "Diamondbacks", "Athletics",
"Rays", "Brewers", "Marlins", "Phillies", "Marlins", "Phillies",
"Diamondbacks", "Brewers", "Red", "Yankees", "Nationals", "Athletics",
"Astros", "Astros", "Twins", "Giants", "Red", "Marlins", "Blue",
"Dodgers", "Braves", "Indians", "Blue", "Mets", "Blue", "Diamondbacks",
"Phillies", "Yankees", "Royals", "Diamondbacks", "Yankees", "Athletics",
"Dodgers", "Pirates", "Orioles", "Cubs", "Mets", "Phillies",
"Mets", "Reds", "Rockies", "Red", "Marlins", "Braves", "Royals",
"Mariners", "Yankees", "Red", "Dodgers", "Dodgers", "Nationals",
"Indians", "Indians", "Padres", "Marlins", "Twins", "Braves",
"Astros", "Braves", "Diamondbacks", "Athletics", "Cubs", "Reds",
"Athletics", "Braves", "Mariners", "Pirates", "Blue", "Blue",
"Royals", "Cubs", "Giants", "Athletics", "Yankees", "Dodgers",
"Yankees", "Mariners", "Astros", "Diamondbacks", "Diamondbacks",
"Brewers", "Mets", "Dodgers", "Braves", "Phillies", "Athletics",
"Angels", "Mariners", "Reds", "Rockies", "Reds", "Indians", "Nationals",
"Indians", "Mets", "Rockies", "Rays", "Rockies", "Mets", "Padres",
"Orioles", "Brewers", "Reds", "Twins", "Indians", "Pirates",
"Braves", "Astros", "Twins", "Nationals", "Twins", "Blue", "Pirates",
"Pirates", "Indians", "Mariners", "Mets", "Marlins", "Giants",
"Cardinals", "Cubs", "Nationals", "Reds", "Mariners", "Dodgers",
"Reds", "Royals", "Dodgers", "Mets", "Indians", "Athletics",
"Rays", "Dodgers", "Giants", "Angels", "Indians", "Cardinals",
"Royals", "Nationals", "Rangers", "Sox", "Athletics", "Rockies",
"Braves", "Padres", "Marlins", "Rangers", "Twins", "Nationals",
"Orioles", "Mariners", "Mets", "Mets", "Yankees", "Royals", "Twins",
"Mariners", "Astros", "Rangers", "Braves", "Athletics", "Astros",
"Twins", "Angels", "Twins", "Cubs", "Reds", "Yankees", "Tigers",
"Yankees", "Cubs", "Rays", "Brewers", "Royals", "Cubs", "Giants",
"Diamondbacks", "Cubs", "Cardinals", "Cardinals", "Twins", "Padres",
"Dodgers", "Jays", "Braves", "Astros", "Giants", "Twins", "Pirates",
"Mariners", "Pirates", "Dodgers", "Pirates", "Indians", "Jays",
"Pirates", "Rockies", "Dodgers", "Padres", "Nationals", "Astros",
"Cubs", "Athletics", "Twins", "Cubs", "Royals", "Sox", "Diamondbacks",
"Yankees", "Sox", "Braves", "Sox", "Reds", "Marlins", "Sox",
"Dodgers", "Cardinals", "Tigers", "Giants", "Marlins", "Mariners",
"Phillies", "Yankees", "Marlins", "Phillies", "Marlins", "Cubs",
"Sox", "Mets", "Twins", "Royals", "Yankees", "Yankees", "Mets",
"Rays", "Giants", "Marlins", "Reds", "Braves", "Cardinals", "Giants",
"Cubs", "Diamondbacks", "Indians", "Cardinals", "Sox", "Orioles",
"Brewers", "Orioles", "Athletics", "Yankees", "Nationals", "Indians",
"Royals", "Diamondbacks", "Indians", "Giants", "Rangers", "Indians",
"Marlins", "Orioles", "Athletics", "Angels", "Nationals", "Padres",
"Sox", "Brewers", "Twins", "Astros", "Sox", "Jays", "Royals",
"Sox", "Padres", "Marlins", "Athletics", "Angels", "Braves",
"Tigers", "Dodgers", "Twins", "Reds", "Angels", "Phillies", "Jays",
"Mets", "Pirates", "Brewers", "Jays", "Padres", "Nationals",
"Indians", "Yankees", "Cardinals", "Mariners", "Braves", "Angels",
"Diamondbacks", "Phillies", "Rangers", "Twins", "Yankees", "Phillies",
"Nationals", "Jays", "Orioles", "Athletics", "Reds", "Mets",
"Royals", "Cubs", "Pirates", "Giants", "Angels", "Indians", "Jays",
"Mariners", "Tigers", "Tigers", "Yankees", "Jays", "Yankees",
"Mariners", "Padres", "Brewers", "Phillies", "Padres", "Cardinals",
"Giants", "Padres", "Sox", "Cubs", "Astros", "Braves", "Cubs",
"Brewers", "Brewers", "Cubs", "Mets", "Royals", "Mariners", "Tigers",
"Angels", "Angels", "Nationals", "Mariners", "Angels", "Reds",
"Indians", "Giants", "Diamondbacks", "Marlins", "Athletics",
"Dodgers", "Dodgers", "Mets", "Sox", "Athletics", "Braves", "Indians",
"Brewers", "Mariners", "Marlins", "Cardinals", "Jays", "Twins",
"Phillies", "Jays", "Cubs", "Pirates", "Angels", "Angels", "Cardinals",
"Phillies", "Pirates", "Orioles", "Braves", "Brewers", "Tigers",
"Sox", "Cubs", "Mets", "Angels", "Athletics", "Marlins", "Royals",
"Sox", "Orioles", "Cubs", "Giants", "Cubs", "Yankees", "Tigers",
"Indians", "Padres", "Orioles", "Padres", "Rays", "Brewers",
"Marlins", "Royals", "Braves", "Padres", "Twins", "Marlins",
"Nationals", "Giants", "Tigers", "Diamondbacks", "Phillies",
"Brewers", "Diamondbacks", "Sox", "Mets", "Twins", "Diamondbacks",
"Marlins", "Athletics", "Diamondbacks", "Rays", "Padres", "Twins",
"Brewers", "Twins", "Pirates", "Royals", "Phillies", "Giants",
"Reds", "Phillies", "Royals", "Braves", "Tigers", "Tigers", "Marlins",
"Diamondbacks", "Rangers", "Rangers", "Cardinals", "Athletics",
"Tigers", "Giants", "Astros", "Royals", "Nationals", "Rockies",
"Indians", "Sox", "Diamondbacks", "Mets", "Rays", "Royals", "Jays",
"Nationals", "Royals", "Rockies", "Dodgers", "Twins", "Tigers",
"Padres", "Braves", "Royals", "Mets", "Diamondbacks", "Rangers",
"Phillies", "Jays", "Twins", "Rangers", "Jays", "Reds", "Dodgers",
"Jays", "Rangers", "Cardinals", "Padres", "Phillies", "Royals",
"Marlins", "Sox", "Pirates", "Sox", "Reds", "Sox", "Phillies",
"Phillies", "Diamondbacks", "Sox", "Cardinals", "Diamondbacks",
"Jays", "Tigers", "Rays", "Rockies", "Astros", "Giants", "Rangers",
"Rays", "Mariners", "Orioles", "Cubs", "Rays", "Rays", "Angels",
"Twins", "Angels", "Sox", "Mets", "Diamondbacks", "Yankees",
"Rangers", "Mets", "Rockies", "Astros", "Sox", "Indians", "Tigers",
"Rangers", "Angels", "Twins", "Angels", "Royals", "Astros", "Sox",
"Reds", "Angels", "Sox", "Rockies", "Brewers", "Angels", "Braves",
"Twins", "Yankees", "Mariners", "Rockies", "Dodgers", "Dodgers",
"Angels", "Tigers", "Orioles", "Astros", "All-Stars", "Rays",
"Brewers", "Diamondbacks", "Royals", "Tigers", "Brewers", "Jays",
"Rockies", "Athletics", "Indians", "Braves", "Sox", "Nationals",
"Sox", "Mariners", "Twins", "Cardinals", "Tigers", "Rangers",
"Mariners", "Indians", "Indians", "Sox", "Marlins", "Pirates",
"Dodgers", "Athletics", "Brewers", "Sox", "Phillies", "Dodgers",
"Marlins", "Brewers", "Tigers", "Jays", "Orioles", "Mariners",
"Astros", "Marlins", "Indians", "Phillies", "Sox", "Tigers",
"Royals", "Mets", "Mariners", "Brewers", "Jays", "Marlins", "Phillies",
"Rockies", "Sox", "Tigers", "Mets", "Phillies", "Tigers", "Dodgers",
"Tigers", "Sox", "Mariners", "Marlins", "Phillies", "Nationals",
"Angels", "Dodgers", "Sox", "Nationals", "Cubs", "Brewers", "Sox",
"Dodgers", "Yankees", "Sox", "Twins", "Yankees", "Yankees", "Cardinals",
"Rays", "Rangers", "Pirates", "Yankees", "Sox", "Cubs", "Brewers",
"Rays", "Yankees", "Giants", "Jays", "Athletics", "Cubs", "Indians",
"Cardinals", "Jays", "Tigers", "Mariners", "Sox", "Astros", "Twins",
"Mariners", "Indians", "Mets", "Phillies", "Jays", "Diamondbacks",
"Braves", "Astros", "Jays", "Nationals", "Nationals", "Angels",
"Reds", "Brewers", "Giants", "Marlins", "Marlins", "Orioles",
"Cubs", "Rockies", "Sox", "Mets", "Mariners", "Jays", "Twins",
"Rays", "Royals", "Cubs", "Padres", "Orioles", "Sox", "Rangers",
"Padres", "Tigers", "Cardinals", "Nationals", "Cubs", "Cardinals",
"Reds", "Padres", "Brewers", "Dodgers", "Padres", "Sox", "Royals",
"Brewers", "Mets", "Marlins", "Diamondbacks", "Jays", "Pirates",
"Reds", "Astros", "Phillies", "Indians", "Royals", "Angels",
"Marlins", "Tigers", "Brewers", "Tigers", "Sox", "Angels", "Indians",
"Twins", "Cardinals", "Padres", "Athletics", "Marlins", "Nationals",
"Brewers", "Pirates", "Astros", "Athletics", "Sox", "Padres",
"Sox", "Astros", "Rays", "Rockies", "Cardinals", "Brewers", "Orioles",
"Rays", "Twins", "Giants", "Orioles", "Twins", "Mariners", "Mariners",
"Mets", "Reds", "Reds", "Royals", "Cardinals", "Yankees", "Pirates",
"Twins", "Reds", "Athletics", "Royals", "Reds", "Jays", "Mariners",
"Yankees", "Yankees", "Indians", "Cubs", "Reds", "Sox", "Nationals",
"Mariners", "Pirates", "Mets", "Twins", "Braves", "Cardinals",
"Nationals", "Padres", "Mariners", "Padres", "Orioles", "Mets",
"Sox", "Nationals", "Rangers", "Royals", "Diamondbacks", "Orioles",
"Giants", "Yankees", "Cardinals", "Rockies", "Sox", "Sox", "Reds",
"Rays", "Braves", "Tigers", "Diamondbacks", "Jays", "Rangers",
"Jays", "Reds", "Mets", "Reds", "Dodgers", "Royals", "Phillies",
"Giants", "Braves", "Rockies", "Dodgers", "Mariners", "Indians",
"Cubs", "Indians", "Twins", "Jays", "Astros", "Indians", "Nationals",
"Diamondbacks", "Royals", "Yankees", "Jays", "Dodgers", "Sox",
"Mets", "Brewers", "Rockies", "Giants", "Rangers", "Cardinals",
"Pirates", "Giants", "Nationals", "Indians", "Orioles", "Orioles",
"Giants", "Twins", "Cardinals", "Braves", "Giants", "Tigers",
"Rockies", "Sox", "Indians", "Braves", "Mets", "Orioles", "Pirates",
"Cardinals", "Mariners", "Nationals", "Jays", "Indians", "Twins",
"Angels", "Nationals", "Diamondbacks", "Cubs", "Sox", "Mets",
"Reds", "Cardinals", "Giants", "Yankees", "Cubs", "Marlins",
"Reds", "Padres", "Rangers", "Marlins", "Astros", "Athletics",
"Cardinals", "Mets", "Rangers", "Yankees", "Braves", "Indians",
"Giants", "Sox", "Marlins", "Sox", "Angels", "Phillies", "1",
"0", "0", "1", "1", "1", "1", "0", "1", "1", "1", "1", "1", "1",
"1", "1", "1", "1", "0", "0", "1", "1", "1", "0", "0", "0", "0",
"1", "1", "0", "0", "1", "1", "1", "0", "1", "1", "1", "1", "0",
"1", "0", "1", "1", "0", "0", "0", "0", "0", "0", "0", "1", "0",
"0", "0", "1", "0", "0", "1", "0", "0", "0", "1", "0", "0", "1",
"1", NA, "0", "1", "0", "0", "0", "0", "1", "0", "0", "1", "0",
"1", "1", "1", "0", "1", "1", "0", "0", "1", "1", "0", "1", "0",
"1", "1", "1", "0", "1", "0", "1", "0", "1", "0", "0", "0", "1",
"0", "1", "0", "0", "0", "0", "1", "1", "0", "1", "1", "1", "1",
"1", "0", "1", "0", "1", "1", "1", "0", "0", "1", "1", "1", "0",
"0", "0", "0", "1", "1", "0", "0", "1", "1", "0", "0", "1", "0",
"1", "1", "0", "1", "0", "1", "0", "1", "0", "0", "1", "1", "0",
"0", "1", "1", "0", "1", "1", "0", "1", "0", "1", "1", "0", "0",
"1", "0", "0", "0", "1", "0", "1", "1", "0", "0", "0", "0", "1",
"1", "1", "1", "1", "0", "0", "1", "0", NA, "1", "1", "0", "0",
"1", "0", "0", "1", "1", "1", "1", "0", "1", "0", "1", "0", "0",
"0", "0", "0", "0", "1", "1", "0", "1", "0", "1", "1", "0", NA,
"0", "0", "0", "1", "1", "1", "0", "1", "0", "0", "0", "0", "1",
"1", "1", "1", "1", "0", "1", "0", "1", "1", "1", "0", "1", "1",
"0", "0", "1", "0", "1", "1", "1", "0", "0", "0", "1", "0", "1",
"1", "1", "1", "1", "0", "0", "1", "1", "0", "0", "1", "1", "1",
"0", "1", "1", "0", NA, "1", "0", "0", "1", "0", "0", "1", "1",
"0", "1", "0", "0", "1", "1", "0", "0", "0", "0", "0", "0", "0",
"1", "1", "1", "1", "0", "1", "1", "0", "0", "1", "1", "1", "0",
"1", "1", "1", "1", "0", "1", "1", "1", "1", "0", "1", "0", "1",
"0", "1", "1", "0", "1", "1", "1", "0", "1", "1", "0", "0", "1",
"0", "0", "1", "0", "0", "0", "0", "1", "1", "1", "0", "0", "0",
"1", "1", "1", "0", "1", "0", "0", "1", "1", "1", "1", "0", "1",
"1", "1", "1", "0", "1", "1", "0", "1", "1", "0", "1", "0", "0",
"0", "1", "0", "1", "1", "0", "1", "1", "0", "0", "0", "0", "0",
"0", "0", "1", "0", "0", "1", "0", "0", "1", "0", "1", "1", "1",
"1", "0", "1", "1", "1", "1", "0", "1", "0", "0", "0", "0", "1",
"1", "0", "1", "1", "0", "0", "0", "1", "1", "0", "0", "1", "0",
"1", "1", "1", "0", "1", "0", "0", "0", "0", "0", "1", "0", "0",
"1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "0", "0",
"0", "0", "0", "1", "1", "1", "0", "0", "0", "0", "0", "1", "0",
"1", "0", "1", "1", "0", "0", "0", "1", "0", "1", "0", "1", "0",
"1", "1", "1", "0", "0", "1", NA, "0", "1", "1", "0", "1", "1",
"0", "1", "0", "1", "0", "1", "0", "0", "0", "0", "0", "0", "1",
"1", "0", "1", "1", "1", "0", "1", "1", "1", "0", "1", "1", "1",
"1", "1", "1", "0", "0", "0", "0", "0", "1", "0", "0", "1", "1",
"1", "1", "0", "0", "1", "0", "1", "1", "0", "1", "1", "0", "0",
"0", "0", "1", "1", "0", "1", "1", "0", "0", "1", "0", "0", "0",
"0", "1", "0", "0", "0", "1", NA, "0", "0", "0", "1", "0", "1",
"0", "0", "1", "1", "0", "0", "1", "0", "0", "0", "0", "1", "1",
"0", "0", "0", "0", "1", "0", "1", "0", "0", "1", "0", "0", "1",
"1", "1", "0", "0", "1", "0", "1", "0", "1", "1", "1", "1", "1",
"1", "0", "0", "0", "1", "0", "1", "1", "1", "1", "1", "0", "0",
"1", "1", "0", "0", "1", "1", "0", "1", "1", "1", "1", "1", "0",
"1", "1", "1", "1", "1", "1", "1", "0", "0", "0", "1", "0", "0",
"1", "0", "1", "0", "1", "0", "1", "0", "1", "0", "0", "1", "1",
"1", "0", "1", "0", "0", "1", "1", "1", "0", "1", "0", "0", "0",
"1", "0", "1", "0", "1", "0", NA, "0", "0", "0", "0", "0", "0",
"1", "1", "1", "1", "1", "1", "1", "0", "0", "1", "1", "1", "0",
"0", "1", "1", "1", "0", "1", "1", "0", "0", "0", "0", "1", "0",
"0", "1", "1", "0", "1", "1", "0", "1", "0", "1", "1", "1", "1",
"1", "1", "1", "1", "0", "0", "0", "0", "1", "1", "0", "0", "1",
"1", "1", "0", "1", "0", "0", "1", "1", "1", "0"), .Dim = c(752L,
3L), .Dimnames = list(NULL, c("home_team", "visit_team", "home_outcomes"
)))

Body:
Below is a quick piece of code that outputs a data.frame with two columns - one is the name of the team, the other is the number of wins (home or away) that team achieved.

This code assumes you structure your data as you mentioned in your question. I have called the matrix 'myMatrix' but you can substitute this however you like.

uniqueTeams <- c(myMatrix[,1],myMatrix[,2])
uniqueTeams <- unique(uniqueTeams)

This first concatonates all the team names in both the home and away team column, then shortens this vector to only include unique values (One vector element per team).

numTeams <- length(uniqueTeams)
teamWins <- data.frame("Team Name"=uniqueTeams,"No. of Wins"=rep(0,numTeams))

This part calculates the number of unuque teams and creates the data.frame which we will store the results in later.

for (i in 1:numTeams){

  temp <- as.matrix(myMatrix[ myMatrix[,1] == uniqueTeams[i] & myMatrix[,3] == "1",3])
  teamWins[i,2] <- nrow(temp)

  temp <- as.matrix(myMatrix[ myMatrix[,2] == uniqueTeams[i] & myMatrix[,3] == "0",3])
  teamWins[i,2] <- teamWins[i,2] + nrow(temp)

}

Finally, I loop through each unique team name. Firstly I create a temporary sub matrix for that team, when they were playing at home and  won and assign the number of rows as my
'No. of Wins' column in the output data frame. I also check if the same team played away and won and add the number of rows in that submatrix to the overall value.

What you are left with is a data.frame with two columns. One is the name of the team, the other the number of overall wins as mentioned earlier.

There may be better ways of tackling this, but this is just what I came up with off the top of my head.


问:
Exact string matching between list and text file data
ViolList is a list with elements ['A 230kv','BCD 120kv (after)','yz ckt 1'] and the txt file has lines such as

Description 'BCD 120kv (after)

line1

Description A 230kv - fg 115 kv ckt 2

line 2

Description yz ckt 1

line 3

Description ...

line...

I need to match them exactly such that A 230kv != A 230kv - fg 115 kv ckt 2

```<code>with open(ContFile.get(), "r") as content_file:
    sectionFound = False
    for line in content_file:
        for x in ViolList:
            x = 'description ' + x
            if x.upper() == line.upper():
                sectionFound = True
                print sectionFound
                break
         if sectionFound == True:
                outfile.write('Found")
</code>```

The below image shows 'line' and 'x' but it still does not return Found:

答:
I think that your problem is that in the lines of your file sometimes have spaces you don't see or need.

It's kind of a guess but you can try to strip your lines, you never know.

So to do that just replace this one:

```<code>if x.upper() == line.upper():
</code>```

by this one:

```<code>if x.upper() == line.upper().strip():
</code>```

also it might be a typo but you wrote:

```<code>outfile.write('Found") # choose one of the quotes
</code>```

finally i just want to point out that with the actual code, if you find a correct line-element match it will constantly keep writing Found for the rest of the list elements, if you don't want that you can also add:

```<code>sectionFound=False
</code>```

right after writing to your outfile , or replace your existing :

```<code>sectionFound=False
</code>```

inside the lines iteration, or:

```<code>break
</code>```

if you don't want to continue the check on other elements of the list.

example of the final thing:

```<code>with open(ContFile, "r") as content_file:
    for line in content_file:
        sectionFound = False
        for x in ViolList:
            x = 'description ' + x
            if x.upper() == line.upper().strip():
                sectionFound = True
                print sectionFound
                break
        if sectionFound == True:
            outfile.write('Found')
</code>```

Hope that was helpful

Body:
ViolList is a list with elements ['A 230kv','BCD 120kv (after)','yz ckt 1'] and the txt file has lines such as

Description 'BCD 120kv (after)

line1

Description A 230kv - fg 115 kv ckt 2

line 2

Description yz ckt 1

line 3

Description ...

line...

I need to match them exactly such that A 230kv != A 230kv - fg 115 kv ckt 2

with open(ContFile.get(), "r") as content_file:
    sectionFound = False
    for line in content_file:
        for x in ViolList:
            x = 'description ' + x
            if x.upper() == line.upper():
                sectionFound = True
                print sectionFound
                break
         if sectionFound == True:
                outfile.write('Found")

The below image shows 'line' and 'x' but it still does not return Found:

Body:
I think that your problem is that in the lines of your file sometimes have spaces you don't see or need.

It's kind of a guess but you can try to strip your lines, you never know.

So to do that just replace this one:

if x.upper() == line.upper():

by this one:

if x.upper() == line.upper().strip():

also it might be a typo but you wrote:

outfile.write('Found") # choose one of the quotes

finally i just want to point out that with the actual code, if you find a correct line-element match it will constantly keep writing Found for the rest of the list elements, if you don't want that you can also add:

sectionFound=False

right after writing to your outfile , or replace your existing :

sectionFound=False

inside the lines iteration, or:

break

if you don't want to continue the check on other elements of the list.

example of the final thing:

with open(ContFile, "r") as content_file:
    for line in content_file:
        sectionFound = False
        for x in ViolList:
            x = 'description ' + x
            if x.upper() == line.upper().strip():
                sectionFound = True
                print sectionFound
                break
        if sectionFound == True:
            outfile.write('Found')

Hope that was helpful


问:
How manipulate element- and groupwise at the same time in multiindex frame?
I have the following dataframe:

```<code>    df=pd.DataFrame(np.random.randint(1,3,27).reshape((9,3)),\
           index= [['KH','KH','KH','KH','KH','KH','KH','KH','KH'],\
                 ['AOK','AOK','AOK','DOK','DOK','DOK','ROK','ROK','ROK'],\
                 ['A','B','C','A','B','C','A','B','C']],\
           columns=['JE','TE','DE']\
           )
     df.index.names = ['Deck','Status','Urs']
     df
Out[116]:
                 JE  TE  DE
Deck Status Urs
KH   AOK    A     1   1   2
            B     1   2   2
            C     2   1   1
     DOK    A     2   2   1
            B     1   2   1
            C     1   2   2
     ROK    A     2   2   2
            B     1   1   2
            C     1   2   1
</code>```

Now i want to simply append a column 'JErel' to it. This column should contain the values from 'JE', but as relative fraction. The fraction should relate to the total sum of the 'Status' index groups.

I can Access the sum via:

```<code>df.loc[('KH','AOK')]['JE'].sum()
Out[117]: 4
</code>```

The column should result in something like:

```<code>1/df.loc[('KH','AOK')]['JE'].sum(),
1/df.loc[('KH','AOK')]['JE'].sum(),
2/df.loc[('KH','AOK')]['JE'].sum() and then,
2/df.loc[('KH','DOK')]['JE'].sum(), ...
</code>```

,,,,
Thats how far i got.

How do i add the column dynamically like with apply(Lambda...) or so?

答:
You can use groupby.transform to calculate the column JE sum which has the same length and index as the original data frame, and then divide JE column by it:

```<code>df['JErel'] = df.JE.div(df.groupby(level=['Deck','Status']).JE.transform('sum'))
df
#                  JE  TE  DE     JErel
# Deck  Status  Urs
#   KH     AOK  A   2   2   1   0.400000
#               B   2   2   1   0.400000
#               C   1   1   2   0.200000
#          DOK  A   1   1   2   0.250000
#               B   2   1   2   0.500000
#               C   1   1   1   0.250000
#          ROK  A   2   1   2   0.333333
#               B   2   1   2   0.333333
#               C   2   1   1   0.333333
</code>```

Body:
I have the following dataframe:

    df=pd.DataFrame(np.random.randint(1,3,27).reshape((9,3)),\
           index= [['KH','KH','KH','KH','KH','KH','KH','KH','KH'],\
                 ['AOK','AOK','AOK','DOK','DOK','DOK','ROK','ROK','ROK'],\
                 ['A','B','C','A','B','C','A','B','C']],\
           columns=['JE','TE','DE']\
           )
     df.index.names = ['Deck','Status','Urs']
     df
Out[116]:
                 JE  TE  DE
Deck Status Urs
KH   AOK    A     1   1   2
            B     1   2   2
            C     2   1   1
     DOK    A     2   2   1
            B     1   2   1
            C     1   2   2
     ROK    A     2   2   2
            B     1   1   2
            C     1   2   1

Now i want to simply append a column 'JErel' to it. This column should contain the values from 'JE', but as relative fraction. The fraction should relate to the total sum of the 'Status' index groups.

I can Access the sum via:

df.loc[('KH','AOK')]['JE'].sum()
Out[117]: 4

The column should result in something like:

1/df.loc[('KH','AOK')]['JE'].sum(),
1/df.loc[('KH','AOK')]['JE'].sum(),
2/df.loc[('KH','AOK')]['JE'].sum() and then,
2/df.loc[('KH','DOK')]['JE'].sum(), ...

,,,,
Thats how far i got.

How do i add the column dynamically like with apply(Lambda...) or so?

Body:
You can use groupby.transform to calculate the column JE sum which has the same length and index as the original data frame, and then divide JE column by it:

df['JErel'] = df.JE.div(df.groupby(level=['Deck','Status']).JE.transform('sum'))
df
#                  JE  TE  DE     JErel
# Deck  Status  Urs
#   KH     AOK  A   2   2   1   0.400000
#               B   2   2   1   0.400000
#               C   1   1   2   0.200000
#          DOK  A   1   1   2   0.250000
#               B   2   1   2   0.500000
#               C   1   1   1   0.250000
#          ROK  A   2   1   2   0.333333
#               B   2   1   2   0.333333
#               C   2   1   1   0.333333


问:
Is it possible to get the size of an entire folder in a URL?
I have an url with a entire folder to download but I would like to get the size of it, or at least calculate it before to download it.
I ask that question, because when I tap directly the url in the web, I can see that there is all the files, and all the files inside that folder :

I tried with that, but it is only for a file, and if you do it in a folder, you only get the ridiculous size of the folder in bytes instead of the entire folder with all files.
StackOverflow get size only for a url file

Is there any way to get it, calculate it, or enumerating all files of the folder to get the HEAD ?

Many thanks.

答:
That page is generated for you by the server as an html page, hence why you are able to see it in the browser. If you are working with this in a native app there are a couple options you can consider;

Parse the HTML document on the device. This approach is potentially quite flaky but you can get all the file/directory names available to you. Once you have built a list of all the file paths you can then perform all of the HEAD requests you need.

Write a server-side script in something like PHP which will provide you the size of the directory that you are wanting to retrieve. This will be much more effective than the first approach as you can do it in one request rather than needing to make a load of HEAD requests and sum up the size on the device. An example of how you might do this.


问:
How to setup Mock of IConfigurationRoot to return value
I have used IConfigurationRoute to access a directory like this.

```<code>if (type == "error") directory = _config.GetValue<string>("Directories:SomeDirectory");
</code>```

_config is IConfigurationRoot injected in the constructor.

I tried the following way to mock it.

```<code>        var mockConfigurationRoot = new Mock<IConfigurationRoot>();
        mockConfigurationRoot.Setup(c => c.GetValue<string>("Directories: SomeDirectory"))
            .Returns("SomeDirectory")
            .Verifiable();
        var config = mockConfigurationRoot.Object;
</code>```

The issue is while running the test Xunit throws the exception saying

"System.NotSupportedException : Expression references a method that
  does not belong to the mocked object"

How can I solve this issue?

答:
Copy the appSettings.json to your Test project root directory and mark it's property as Content and Copy if newer.

```<code>var builder = new ConfigurationBuilder()
      .SetBasePath(Directory.GetCurrentDirectory())
      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
      .AddEnvironmentVariables();
ConfigurationManager.Configuration = builder.Build();
</code>```

ConfigurationManager is a class and it has a static property Configuration. This way the whole application can just access it as ConfigurationManager.Configuration[]

Body:
I have used IConfigurationRoute to access a directory like this.

if (type == "error") directory = _config.GetValue<string>("Directories:SomeDirectory");

_config is IConfigurationRoot injected in the constructor.

I tried the following way to mock it.

        var mockConfigurationRoot = new Mock<IConfigurationRoot>();
        mockConfigurationRoot.Setup(c => c.GetValue<string>("Directories: SomeDirectory"))
            .Returns("SomeDirectory")
            .Verifiable();
        var config = mockConfigurationRoot.Object;

The issue is while running the test Xunit throws the exception saying

"System.NotSupportedException : Expression references a method that
  does not belong to the mocked object"

How can I solve this issue?

Body:
Copy the appSettings.json to your Test project root directory and mark it's property as Content and Copy if newer.

var builder = new ConfigurationBuilder()
      .SetBasePath(Directory.GetCurrentDirectory())
      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
      .AddEnvironmentVariables();
ConfigurationManager.Configuration = builder.Build();

ConfigurationManager is a class and it has a static property Configuration. This way the whole application can just access it as ConfigurationManager.Configuration[]

ContentLicense: CC BY-SA 4.0


问:
Loading local files with Javascript without a web server
I need to write a software that uses HTML5 and canvas.

The whole software should be able to run locally, without the need of a server. So I'm only able to use Javascript, no php.

The difficult part: I have to dynamically fetch the content of text-files which are needed during operation.

For example: When the software starts, I need the "config.json".
And after the user made some desicions, I need "story1.txt" or "story2.txt" and so on.

My Problem:

I can't use Ajax, because Chrome blocks it - local Files aren't allowed to fetch other files' content. I always get an error-Message.

What I've tried so far:

Load Files with Ajax & jQuery

Chrome doesn't allow me to load the file

Load File into script-Tag

Even if I declare the JSON-File as js-Code, I can't access the content of the loaded File

Load File into invisible Iframe, and read its content

Loading works, and I can see the code. But when I try to access the IFrame's content, I get the Chrome Error-Message again:

```<code>"Uncaught SecurityError: Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match."
</code>```

Question:

Is there a way to load a Textfile dynamically, or am I forced to use a Webserver?

答:
Depending on your requirements, using fetch (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) is an option:</p>

```<code>  fetch("./config.json").then(function(res) {
    // res instanceof Response == true.
    if (res.ok) {
      res.json().then(function(data) {
        console.log(data);
      });
    } else {
      console.log("Looks like the response wasn't perfect, got status", res.status);
    }
  }, function(e) {
    console.log("Fetch failed!", e);
  });
</code>```

Body:
I need to write a software that uses HTML5 and canvas.

The whole software should be able to run locally, without the need of a server. So I'm only able to use Javascript, no php.

The difficult part: I have to dynamically fetch the content of text-files which are needed during operation.

For example: When the software starts, I need the "config.json".
And after the user made some desicions, I need "story1.txt" or "story2.txt" and so on.

My Problem:

I can't use Ajax, because Chrome blocks it - local Files aren't allowed to fetch other files' content. I always get an error-Message.

What I've tried so far:

Load Files with Ajax & jQuery

Chrome doesn't allow me to load the file

Load File into script-Tag

Even if I declare the JSON-File as js-Code, I can't access the content of the loaded File

Load File into invisible Iframe, and read its content

Loading works, and I can see the code. But when I try to access the IFrame's content, I get the Chrome Error-Message again:

"Uncaught SecurityError: Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match."

Question:

Is there a way to load a Textfile dynamically, or am I forced to use a Webserver?

Body:
Depending on your requirements, using fetch (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) is an option:

  fetch("./config.json").then(function(res) {
    // res instanceof Response == true.
    if (res.ok) {
      res.json().then(function(data) {
        console.log(data);
      });
    } else {
      console.log("Looks like the response wasn't perfect, got status", res.status);
    }
  }, function(e) {
    console.log("Fetch failed!", e);
  });


问:
Angular Masonry multi-column with percentage width
I have the following template (note I use angular-masonry-directive):

```<code><div masonry='{ "transitionDuration" : "0.4s" , "itemSelector" : ".tile", "columnWidth":1}'>
    <div masonry-tile ng-repeat="item in queryset" class="tile">
        <item  ng-class-odd="'odd'" ng-class-even="'even'"></item>
    </div>
</div>
</code>```

It works great when I specify the width of .odd and .even in pixels, e.g. 600px and 300px, but it does not when I use percentages, e.g. 60% and 30%. Is it even possible with Masonry? If not, what would you suggest? Thanks!

答:
Add percentPosition: true to the masonry settings.  This tells Masonry to compute the width based on a percentage.

```<code><div masonry='{ "transitionDuration" : "0.4s" , "itemSelector" : ".tile",
"columnWidth":1, percentPosition: true}'>
    <div masonry-tile ng-repeat="item in queryset" class="tile">
        <item  ng-class-odd="'odd'" ng-class-even="'even'"></item>
    </div>
</div>
</code>```

See more options here: masonry.desandro.com/options.html

Body:
I have the following template (note I use angular-masonry-directive):

        <item  ng-class-odd="'odd'" ng-class-even="'even'"></item>

It works great when I specify the width of .odd and .even in pixels, e.g. 600px and 300px, but it does not when I use percentages, e.g. 60% and 30%. Is it even possible with Masonry? If not, what would you suggest? Thanks!

Body:
Add percentPosition: true to the masonry settings.  This tells Masonry to compute the width based on a percentage.

<div masonry='{ "transitionDuration" : "0.4s" , "itemSelector" : ".tile",
"columnWidth":1, percentPosition: true}'>
    <div masonry-tile ng-repeat="item in queryset" class="tile">
        <item  ng-class-odd="'odd'" ng-class-even="'even'"></item>
    </div>
</div>

See more options here: masonry.desandro.com/options.html


问:
Mocking an external SSO login in RSpec feature specs with Capybara Webkit
My application redirects to an external party for Single-Sign On (SSO).

Once logged in, that external party redirects that user back to my app's callback route.

This is implemented as follows in the controller:

```<code>SsoController < ApplicationController

  def connect
    # do stuff

    # Redirect to external party with some params
    redirect_to "www.external-party.com?foo=\"bar\""
  end

  def callback
    # Receive response from external party
    response = params[:response]

    # do stuff
  end
end
</code>```

In my feature specs I'd love to actually have this mocked out so I can test the end-to-end functionality from the user's perspective.

I'm using RSpec + Capybara and I'd like to do model the following flow -

User clicks some button (e.g. "sign in")

That button is tied to the connect action above which redirects to some external party

RSpec mocks a response based on the params sent over and sends a POST request back to my app (callback action)

Further business logic to sign in user and take them to their target

I'm unsure of how to do the 3rd step, particularly with intercepting the call, constructing the response, and POST-ing something back

Thanks!

Edit: A POST request back to my app is preferred, but is not a must-have. If it's a GET request or a redirect, I can configure my app to allow those HTTP verbs on the test environment only.

答: Rather than attempting to mock this in the app code (which is discouraged  in feature specs) the cleanest way to do what you want is using a programmable proxy like puffing billy - https://github.com/oesmith/puffing-billy.  That will let you respond to the test browser making a request to "www.external-party.com?foo=\"bar\"" in any way you want.</p>

Body:
My application redirects to an external party for Single-Sign On (SSO).

Once logged in, that external party redirects that user back to my app's callback route.

This is implemented as follows in the controller:

SsoController < ApplicationController

  def connect
    # do stuff

    # Redirect to external party with some params
    redirect_to "www.external-party.com?foo=\"bar\""
  end

  def callback
    # Receive response from external party
    response = params[:response]

    # do stuff
  end
end

In my feature specs I'd love to actually have this mocked out so I can test the end-to-end functionality from the user's perspective.

I'm using RSpec + Capybara and I'd like to do model the following flow -

User clicks some button (e.g. "sign in")

That button is tied to the connect action above which redirects to some external party

RSpec mocks a response based on the params sent over and sends a POST request back to my app (callback action)

Further business logic to sign in user and take them to their target

I'm unsure of how to do the 3rd step, particularly with intercepting the call, constructing the response, and POST-ing something back

Thanks!

Edit: A POST request back to my app is preferred, but is not a must-have. If it's a GET request or a redirect, I can configure my app to allow those HTTP verbs on the test environment only.


问:
Stylecop tells me to add this keyword, but it's redundant - any performance implications?
I use Stylecop for Resharper and whenever I call something in my class, Stylecop tells me to use the this keyword. But the IDE says this is redundant code (which it sure is), so why should I use the this keyword?

Does redundant code mean its not needed (obviously) and the compiler won't even do anything with the this keyword? So I assume the this keyword is just for clarity.

Also, with the CLR, do things like this fall consistently across languages? So if the answer is that the compiler doesn't even touch the this keyword and it is just for presentation and clarity, then the same is true for VB.NET? I assume it is all for clarity as stylecop keeps an eye on this and Fxcop (which I will use later on) keeps an eye on my code's quality from a technical point of view.

Thanks

答:
Most of the time is just for clarity but some times it is required.

```<code>using System;

class Foo
{
    String bar;

    public Foo(String bar)
    {
        this.bar = bar;
    }
}
</code>```

Here you will need this as it serves to disambiguate between the field bar and the constructor parameter bar.  Obviously changing the name of the parameter or field could accomplish the same thing.

OwnerDisplayName: GSS

Body:
Most of the time is just for clarity but some times it is required.

using System;

class Foo
{
    String bar;

    public Foo(String bar)
    {
        this.bar = bar;
    }
}

Here you will need this as it serves to disambiguate between the field bar and the constructor parameter bar.  Obviously changing the name of the parameter or field could accomplish the same thing.

OwnerDisplayName: Andrew Hare

ContentLicense: CC BY-SA 2.5


问:
Find Minimum Date in Collection (Ruby)
I have a collection of DateTime objects. I would like to find which date is the earliest.</p>

答:
Have you tried something like</p>

```<code>collection.min
</code>```

Title: Find Minimum Date in Collection (Ruby)

Body:
Have you tried something like

collection.min


问:
Pentaho: how to retrieve data stored in two files: one for mapping and other for rows
I need read these data and then load them into oracle tables using (if possible) a single spoon transformation.

The data are stored in pairs of two files. Each pair has one file (data-type_yyyymmdd.txt) with each row placed in each line ended with carriage-return and no delimiters between the fields. The key to extracting theses fields is the second file (data-type_yyyymmdd.ref) that contains information to map these fields along the rows. Let's take a look at one example:

data-type_yyyymmdd.ref file layout:

```<code>OPERATION_ID                             A 011
USER                                     A 008
DATE_TRANSACTION                         A 0008
TIME_TRANSACTION                         N 0004
</code>```

The first column is field name, second is the data type (A=alphanumeric, N=numeric), third is the field length. The columns have fixed position along the line.

IMPORTANT: The pairs could have REF file with different structures, but pairs with same kind of REF files (identified by data-type in file name) has the same structure.

data-type_yyyymmdd.txt file layout:

A line of this file

```<code>50593749120ABCDEFGH201701021444
</code>```

The fields for this line have these values:

```<code>OPERATION_ID=50593749120
USER=ABCDEFGH
DATE_TRANSACTION=20170102
TIME_TRANSACTION=1444
</code>```

So the pentaho transformation has to read these files, retrieve the rows/fields and insert them into a table.

How to identify the table to insert these data?

The key is data-type part of file name. We have a set of different tables and the name of them is identified by this part. Each table structure is equivalent to his related REF file. Example:

This file pair userlogins_20170701.ref and userlogins_20170701.txt has data of userlogins oracle table. Let's suppose this pair has the same structure of the example above. So the table has this structure:

```<code>ID - numeric(16)
OPERATION_ID - varchar2(11)
USER - varchar2(8)
DATE_TRANSACTION - varchar2(8)
TIME_TRANSACTION - numeric(4)
</code>```

All tables has the ID field as primary key filled by a sequence database. The other fields follow the REF file structure. fields with A type are mapped to varchars field and N to numeric fields.

答: Here if .ref file will not change you can take stream of data from source file into "copy rows to result" then apply job with setting "run this job for each row" then apply cut string component for each row and set four variables and you can store then in four columns row by row.</p>

Body:
I need read these data and then load them into oracle tables using (if possible) a single spoon transformation.

The data are stored in pairs of two files. Each pair has one file (data-type_yyyymmdd.txt) with each row placed in each line ended with carriage-return and no delimiters between the fields. The key to extracting theses fields is the second file (data-type_yyyymmdd.ref) that contains information to map these fields along the rows. Let's take a look at one example:

data-type_yyyymmdd.ref file layout:

OPERATION_ID                             A 011
USER                                     A 008
DATE_TRANSACTION                         A 0008
TIME_TRANSACTION                         N 0004

The first column is field name, second is the data type (A=alphanumeric, N=numeric), third is the field length. The columns have fixed position along the line.

IMPORTANT: The pairs could have REF file with different structures, but pairs with same kind of REF files (identified by data-type in file name) has the same structure.

data-type_yyyymmdd.txt file layout:

A line of this file

50593749120ABCDEFGH201701021444

The fields for this line have these values:

OPERATION_ID=50593749120
USER=ABCDEFGH
DATE_TRANSACTION=20170102
TIME_TRANSACTION=1444

So the pentaho transformation has to read these files, retrieve the rows/fields and insert them into a table.

How to identify the table to insert these data?

The key is data-type part of file name. We have a set of different tables and the name of them is identified by this part. Each table structure is equivalent to his related REF file. Example:

This file pair userlogins_20170701.ref and userlogins_20170701.txt has data of userlogins oracle table. Let's suppose this pair has the same structure of the example above. So the table has this structure:

ID - numeric(16)
OPERATION_ID - varchar2(11)
USER - varchar2(8)
DATE_TRANSACTION - varchar2(8)
TIME_TRANSACTION - numeric(4)

All tables has the ID field as primary key filled by a sequence database. The other fields follow the REF file structure. fields with A type are mapped to varchars field and N to numeric fields.


问:
Reorder columns in csv file
i'm working im a Python script to get some columns of a csv file. The csv file have the next items

```<code>id,created_time,ad_id,ad_name,adset_id,adset_name,campaign_id,campaign_name,form_id,form_name,travel,full_name,email,phone_number,city
</code>```

and i just want the next columns

```<code>full_name,campaign_name,form_name,travel,email,phone_number,city
</code>```

The thing is that the columns in the original file not always have the same position, but always have the same name

I have this code with an unknown error

```<code>import sys
import csv

with open('originalFile.csv', 'r') as infile, open('file2.csv', 'a') as outfile:
    # output dict needs a list for new column ordering
    fieldnames = ["full_name","campaign_name","form_name","travel","email","phone_number","city"]
    writer = csv.DictWriter(outfile, fieldnames=fieldnames)
    # reorder the header first
    writer.writeheader()
    for row in csv.DictReader(infile):
        if row is not None:
        # writes the reordered rows to the new file
            writer.writerow(row)
</code>```

The error is

```<code>Traceback (most recent call last):
  File "orden.py", line 11, in <module>
    for row in csv.DictReader(infile):
  File "/usr/lib/python2.7/csv.py", line 107, in next
    self.fieldnames
  File "/usr/lib/python2.7/csv.py", line 90, in fieldnames
    self._fieldnames = self.reader.next()
_csv.Error: line contains NULL byte
</code>```

答:
There is an option to ignore extra fields

writer = csv.DictWriter(outfile, fieldnames=fieldnames, extrasaction='ignore')

More info here

Title: Reorder columns in csv file

Body:
i'm working im a Python script to get some columns of a csv file. The csv file have the next items

id,created_time,ad_id,ad_name,adset_id,adset_name,campaign_id,campaign_name,form_id,form_name,travel,full_name,email,phone_number,city

and i just want the next columns

full_name,campaign_name,form_name,travel,email,phone_number,city

The thing is that the columns in the original file not always have the same position, but always have the same name

I have this code with an unknown error

import sys
import csv

with open('originalFile.csv', 'r') as infile, open('file2.csv', 'a') as outfile:
    # output dict needs a list for new column ordering
    fieldnames = ["full_name","campaign_name","form_name","travel","email","phone_number","city"]
    writer = csv.DictWriter(outfile, fieldnames=fieldnames)
    # reorder the header first
    writer.writeheader()
    for row in csv.DictReader(infile):
        if row is not None:
        # writes the reordered rows to the new file
            writer.writerow(row)

The error is

Traceback (most recent call last):
  File "orden.py", line 11, in <module>
    for row in csv.DictReader(infile):
  File "/usr/lib/python2.7/csv.py", line 107, in next
    self.fieldnames
  File "/usr/lib/python2.7/csv.py", line 90, in fieldnames
    self._fieldnames = self.reader.next()
_csv.Error: line contains NULL byte


问:
Will converting lambda functions to normal functions in another compilation unit improve compile time?
I am working on a C++ server project that has been plagued with a growing main() function, and the code base has grown to a point where compilation time is about 6 minutes (in debug mode) even after I make the slightest change to the main() function.  (The main() function is about 5000 lines long!)

I'm using Visual Studio 2017, and (as I understand) the compiler has some pre-compiled header capabilities, as well as capability to not recompile unmodified functions.  But those stuff are currently of little use because most of the logic is in the main() function.

Here's a (very simplified) version of my code:

```<code>struct GrandServer{
    std::map<std::string,std::function<void(std::string)>> request;
    /* some other functions of this server */
};

int main()
{
    SQLClient sql_client;
    auto query_database=[&sql_client](auto&& callback){/*stuff*/};
    GrandServer server;
    server.request["/my_page.html"] = [](std::string&& data){
        // Do stuff
    };
    server.request["/my_page_2.html"] = [](std::string&& data){
        // Do more stuff
    };
    server.request["/my_page_3.html"] = [](std::string&& data){
        // Do even more stuff
    };
    server.request["/my_page_4.html"] = [&query_database](std::string&& data){
        // Do many many callbacks
        query_database([](std::vector<std::string>&& results){
            std::string id = std::move(results.front());
            do_something_else([id = std::move(id)](auto&& param) mutable {
                /* do more stuff, call more functions that will call back, then answer the client */
            });
        });
    };
    /* Many many more lambda functions */
}
</code>```

In essence, the core logic of the whole application is contained within the main() function, by defining lambdas stored in a std::map.  The lambda functions contain a few levels of lambda functions within them, mostly defining (async) callbacks from the database.  The other standalone functions consist mainly of the functions in GrandServer as well as various utility functions (e.g. time conversion, async callback utilities, unicode utilities, etc.) but none of them form the core logic of the application.  This feels like really bad code sprawl :(

I'm thinking of converting all the top-level lambdas (i.e. those stored directly in server.request) into normal standalone member functions into a few separate compilation units like such:

```<code>// split definitions of methods in this class over several compilation units
// header file left out for brevity
struct MyServer{
    SQLClient sql_client;
    void query_database=[this](auto&& callback){/*stuff*/};

    void do_my_page(std::string&& data){
        // Do stuff
    }

    void do_my_page_2(std::string&& data){
        // Do stuff
    }

    void do_my_page_3(std::string&& data){
        // Do stuff
    }

    void do_my_page_4(std::string&& data){
        // Do many many callbacks
        query_database([](std::vector<int>&& results){
            do_something_else([](auto&& param){
                /* do more stuff, call more functions that will call back, then answer the client */
            });
        });
    }
};

// main.cpp
struct GrandServer{
    std::map<std::string,std::function<void(std::string)>> request;
    /* some other functions of this server */
};

int main()
{
    GrandServer server;
    MyServer my_server;
    server.request["/my_page.html"] = [&my_server](auto&&... params){my_server.do_my_page(std::forward<decltype(params)>(params)...);};
    server.request["/my_page_2.html"] = [&my_server](auto&&... params){my_server.do_my_page_2(std::forward<decltype(params)>(params)...);};
    server.request["/my_page_3.html"] = [&my_server](auto&&... params){my_server.do_my_page_3(std::forward<decltype(params)>(params)...);};
    server.request["/my_page_4.html"] = [&my_server](auto&&... params){my_server.do_my_page_4(std::forward<decltype(params)>(params)...);};
    /* Lots more lambda functions */
}
</code>```

While this will reduce the size of main() to something much more tolerable, should I expect this to reduce compilation time significantly?  There will not be any reduction in the number of template instantiations (in fact, I introduced some new template lambda forwarders in main() that should get inlined).

Also note that due to the callbacks and capturing of variables using move semantics, it is not easy to change the inner lambda functions within each logic flow to normal standalone member or non-member functions.  (Template functions and classes cannot be in separate compilation units.)  However, each logic flow is usually no more than 100 lines long so I do not believe that this is necessary.

6 minutes to compile a code base of about 6000-7000 lines seems way too slow, and I would think that this is due to my horrendously long main() function.  Should I expect breaking this function up as I described above to significantly improve the compile time of this project?

答:
Have you copied every single #include <> to stdfafx.h ?? This goes a long way towards reducing compilation times.  The compiler may complain about the precompiled header being too large, but the default size is ridiculously small.

The -Zm option controls the amount allocated for the precompiled header, in megabytes.

I've seen over 10 x improvements in compilation speed for some projects.

If you map a network drive to one of your local disks, there is an easy way to see a further 3x improvement in compilation time.

Here's a solution for that case, it involves replacing the network map to a DOS drive in the registry.  Here's what this gives for my own setup:

```<code>[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\DOS Devices]
"R:"="\DosDevices\D:\devel\build"
"S:"="\DosDevices\D:\devel\src"
</code>```

Body:
I am working on a C++ server project that has been plagued with a growing main() function, and the code base has grown to a point where compilation time is about 6 minutes (in debug mode) even after I make the slightest change to the main() function.  (The main() function is about 5000 lines long!)

I'm using Visual Studio 2017, and (as I understand) the compiler has some pre-compiled header capabilities, as well as capability to not recompile unmodified functions.  But those stuff are currently of little use because most of the logic is in the main() function.

Here's a (very simplified) version of my code:

struct GrandServer{
    std::map<std::string,std::function<void(std::string)>> request;
    /* some other functions of this server */
};

int main()
{
    SQLClient sql_client;
    auto query_database=[&sql_client](auto&& callback){/*stuff*/};
    GrandServer server;
    server.request["/my_page.html"] = [](std::string&& data){
        // Do stuff
    };
    server.request["/my_page_2.html"] = [](std::string&& data){
        // Do more stuff
    };
    server.request["/my_page_3.html"] = [](std::string&& data){
        // Do even more stuff
    };
    server.request["/my_page_4.html"] = [&query_database](std::string&& data){
        // Do many many callbacks
        query_database([](std::vector<std::string>&& results){
            std::string id = std::move(results.front());
            do_something_else([id = std::move(id)](auto&& param) mutable {
                /* do more stuff, call more functions that will call back, then answer the client */
            });
        });
    };
    /* Many many more lambda functions */
}

In essence, the core logic of the whole application is contained within the main() function, by defining lambdas stored in a std::map.  The lambda functions contain a few levels of lambda functions within them, mostly defining (async) callbacks from the database.  The other standalone functions consist mainly of the functions in GrandServer as well as various utility functions (e.g. time conversion, async callback utilities, unicode utilities, etc.) but none of them form the core logic of the application.  This feels like really bad code sprawl :(

I'm thinking of converting all the top-level lambdas (i.e. those stored directly in server.request) into normal standalone member functions into a few separate compilation units like such:

// split definitions of methods in this class over several compilation units
// header file left out for brevity
struct MyServer{
    SQLClient sql_client;
    void query_database=[this](auto&& callback){/*stuff*/};

    void do_my_page(std::string&& data){
        // Do stuff
    }

    void do_my_page_2(std::string&& data){
        // Do stuff
    }

    void do_my_page_3(std::string&& data){
        // Do stuff
    }

    void do_my_page_4(std::string&& data){
        // Do many many callbacks
        query_database([](std::vector<int>&& results){
            do_something_else([](auto&& param){
                /* do more stuff, call more functions that will call back, then answer the client */
            });
        });
    }
};

// main.cpp
struct GrandServer{
    std::map<std::string,std::function<void(std::string)>> request;
    /* some other functions of this server */
};

int main()
{
    GrandServer server;
    MyServer my_server;
    server.request["/my_page.html"] = [&my_server](auto&&... params){my_server.do_my_page(std::forward<decltype(params)>(params)...);};
    server.request["/my_page_2.html"] = [&my_server](auto&&... params){my_server.do_my_page_2(std::forward<decltype(params)>(params)...);};
    server.request["/my_page_3.html"] = [&my_server](auto&&... params){my_server.do_my_page_3(std::forward<decltype(params)>(params)...);};
    server.request["/my_page_4.html"] = [&my_server](auto&&... params){my_server.do_my_page_4(std::forward<decltype(params)>(params)...);};
    /* Lots more lambda functions */
}

While this will reduce the size of main() to something much more tolerable, should I expect this to reduce compilation time significantly?  There will not be any reduction in the number of template instantiations (in fact, I introduced some new template lambda forwarders in main() that should get inlined).

Also note that due to the callbacks and capturing of variables using move semantics, it is not easy to change the inner lambda functions within each logic flow to normal standalone member or non-member functions.  (Template functions and classes cannot be in separate compilation units.)  However, each logic flow is usually no more than 100 lines long so I do not believe that this is necessary.

6 minutes to compile a code base of about 6000-7000 lines seems way too slow, and I would think that this is due to my horrendously long main() function.  Should I expect breaking this function up as I described above to significantly improve the compile time of this project?

Body:
Have you copied every single #include <> to stdfafx.h ?? This goes a long way towards reducing compilation times.  The compiler may complain about the precompiled header being too large, but the default size is ridiculously small.

The -Zm option controls the amount allocated for the precompiled header, in megabytes.

I've seen over 10 x improvements in compilation speed for some projects.

If you map a network drive to one of your local disks, there is an easy way to see a further 3x improvement in compilation time.

Here's a solution for that case, it involves replacing the network map to a DOS drive in the registry.  Here's what this gives for my own setup:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\DOS Devices]
"R:"="\DosDevices\D:\devel\build"
"S:"="\DosDevices\D:\devel\src"


问:
Unexpected output from redirection
I'm encountering a strange problem when redirecting STDOUT and STDERR.  The following works as expected:

```<code>$ gvim --version > /tmp/version.out
$ ls -l /tmp/version.out
-rw-r--r--. 1 blah blah 3419 Jun 27 17:28 /tmp/version.out
</code>```

There are 3419 characters in the output file and when I look at the file, it contains what I expect.

However, it does not work as expected when I do the following:

```<code>$ gvim --version > /tmp/version.out 2> /tmp/version.err
$ ls -latr /tmp/version.*
-rw-r--r--. 1 blah blah 0 Jun 27 17:29 /tmp/version.out
-rw-r--r--. 1 blah blah 0 Jun 27 17:29 /tmp/version.err
</code>```

Notice that both the .out and the .err files are zero length this time.  I tried this with an ls command and it works as expected:

```<code>$ ls . /ZZZ > /tmp/ls.out 2> /tmp/ls.err
$ ls -l /tmp/ls.*
-rw-r--r--. 1 blah blah 50 Jun 27 17:45 /tmp/ls.err
-rw-r--r--. 1 blah blah 33 Jun 27 17:45 /tmp/ls.out
</code>```

Here, the STDERR gets redirected properly:

```<code>$ cat /tmp/ls.err
ls: cannot access /ZZZ: No such file or directory
</code>```

I did an strace on gvim --version and confirmed that it's trying to write the version info to STDOUT (fd 1).  It shouldn't matter either way though since I'm trying to capture both STDOUT and STDERR.

What's going on here?

答:
Congratulations, you just found a bug in gvim!
Correct procedure is to file a new issue on GitHub.

You should first try another variations of the bug, so that developers have the debugging easier.

For example, redirecting only STDERR also causes the error, because there was no output written. Also there was returned success (0), which is obviously an bug.

```<code>$ gvim --version 2> /tmp/version.err
$ echo $?
0
</code>```

By only looking into the code one may search for the bug somewhere in version printing, or anywhere in generic --version argument processing, not being done by gtk.

To answer your question

What is going on?

It's a program error, made by developers of gvim and I would not recommend you to put effort into finding its root cause unless you are experienced with coding vim or if you want to learn, how vim works. In that case, your best shot is to fork the repo and after fixing it, submitting a pull request, so that everyone can benefit from your work.

Title: Unexpected output from redirection

Body:
I'm encountering a strange problem when redirecting STDOUT and STDERR.  The following works as expected:

$ gvim --version > /tmp/version.out
$ ls -l /tmp/version.out
-rw-r--r--. 1 blah blah 3419 Jun 27 17:28 /tmp/version.out

There are 3419 characters in the output file and when I look at the file, it contains what I expect.

However, it does not work as expected when I do the following:

$ gvim --version > /tmp/version.out 2> /tmp/version.err
$ ls -latr /tmp/version.*
-rw-r--r--. 1 blah blah 0 Jun 27 17:29 /tmp/version.out
-rw-r--r--. 1 blah blah 0 Jun 27 17:29 /tmp/version.err

Notice that both the .out and the .err files are zero length this time.  I tried this with an ls command and it works as expected:

$ ls . /ZZZ > /tmp/ls.out 2> /tmp/ls.err
$ ls -l /tmp/ls.*
-rw-r--r--. 1 blah blah 50 Jun 27 17:45 /tmp/ls.err
-rw-r--r--. 1 blah blah 33 Jun 27 17:45 /tmp/ls.out

Here, the STDERR gets redirected properly:

$ cat /tmp/ls.err
ls: cannot access /ZZZ: No such file or directory

I did an strace on gvim --version and confirmed that it's trying to write the version info to STDOUT (fd 1).  It shouldn't matter either way though since I'm trying to capture both STDOUT and STDERR.

What's going on here?

Body:
Congratulations, you just found a bug in gvim!
Correct procedure is to file a new issue on GitHub.

You should first try another variations of the bug, so that developers have the debugging easier.

For example, redirecting only STDERR also causes the error, because there was no output written. Also there was returned success (0), which is obviously an bug.

$ gvim --version 2> /tmp/version.err
$ echo $?
0

By only looking into the code one may search for the bug somewhere in version printing, or anywhere in generic --version argument processing, not being done by gtk.

To answer your question

What is going on?

It's a program error, made by developers of gvim and I would not recommend you to put effort into finding its root cause unless you are experienced with coding vim or if you want to learn, how vim works. In that case, your best shot is to fork the repo and after fixing it, submitting a pull request, so that everyone can benefit from your work.