text:
/*
    Controller for runs.
*/
var RunsCtrl = function($scope, $routeParams, Project, Run, Job, globalState) {
    $scope.global_state = globalState;
    globalState.data.page = 'runs';
    globalState.initialize($routeParams.project, function() {

        $scope.runFilter = function(state) {
            return function(run) {
                return (run.get_state() == state);
            };
        };

        $scope.enqueueEnabledFilter = function(bool) {
            return function(run) {
                return (run.get_job().enqueue_is_enabled == bool);
            };
        };

        $scope.setTab = function(tabId) {
            globalState.data.runTab = tabId;
        };

        $scope.runs = globalState.getRuns();

        // show run details
        if ($routeParams.run) {
            $scope.run = Run.get({id: $routeParams.run}, function() {
                // is there a better way?
                $('#modal').modal().on('hide', function() { history.go(-1); });
            });
        }

    });
};

/*
    Controller for jobs.
*/
var JobListCtrl = function($scope, $routeParams, Project, Job, JobTemplate, Worker, Run, Group, globalState, dtformat) {
    globalState.data.page = 'jobs';
    globalState.initialize($routeParams.project, function() {
        $scope.global_state = globalState;
        $scope.jobs = globalState.getAllJobs();
        $scope.job_templates = globalState.getAllJobTemplates();

        $scope.showDetails = function() {
            globalState.data.jobTab = 'details';

            // Get scheduled runs for this job
            Run.all({job: $routeParams.job, state: 'scheduled'}, function(scheduledRuns) {
                $scope.scheduled_runs = scheduledRuns;
            });
        };

        // function for displaying script content
        $scope.showScript = function() {
            globalState.data.jobTab = 'script';
        };

        // function for displaying recent runs of a job
        $scope.showRecentRuns = function() {
            globalState.data.jobTab = 'runs';

            // get recent runs and build the chart
            Run.get({job: $routeParams.job, state: 'completed', limit: 100}, function(recentRuns) {
                $scope.recent_runs = [];
                angular.forEach(recentRuns.objects, function(run) {
                    $scope.recent_runs.push(new Run(run));
                });
                var chartData = [['Run', 'Duration (seconds)']];

                angular.forEach($scope.recent_runs, function(run) {
                    chartData.push([dtformat.formatDateTime(run.start_dts), run.get_duration_sec()]);
                });

                chartData = google.visualization.arrayToDataTable(chartData);
                var chart = new google.visualization.AreaChart(document.getElementById('run-performance-graph'));
                chart.draw(chartData, {
                    'axisTitlesPosition': 'none',
                    'legend': {'position': 'none'},
                    'hAxis': {'direction': -1, 'textPosition': 'none', 'gridlines': {'count': 0}},
                    'vAxis': {'gridlines': {'count': 3}}
                });

            });
        };

        // show job details
        if ($routeParams.job) {
            $scope.job = Job.get({id: $routeParams.job});
            if (globalState.data.jobTab == 'runs') {
                // make sure that we update the recent runs
                $scope.showRecentRuns();
            } else if (globalState.data.jobTab == 'details') {
                // make sure that we update the next scheduled runs
                $scope.showDetails();
            }
        }

        // show run details
        if ($routeParams.run) {
            $scope.run = Run.get({id: $routeParams.run}, function() {
                // is there a better way?
                $('#modal').modal().on('hide', function() { history.go(-1); });
            });
        }
    });
};

/*
    Controller which redirects to:

    * The last selected project
    * Failing that, the first project in the list

*/
var RedirectToProjectCtrl = function($location, Project, localStorageService) {
    Project.all({}, function(projects) {
        var redirectUrl = '/no-projects/';
        var selectedProjectId = localStorageService.get('selectedProjectId');

        // take the first project from the list (if there are any projects)
        if (projects.length > 0) {
            redirectUrl = '/project/'+ projects[0].id +'/runs/';
        }

        // if selectedProjectId exists, check if that project-id is in the list
        // of available projects
        if (selectedProjectId !== null) {
            angular.forEach(projects, function(project) {
                if (selectedProjectId == project.id) {
                    redirectUrl = '/project/' + project.id + '/runs/';
                }
            });
        }

        $location.path(redirectUrl);
    });
};

/*
    Controller when there are no projects available.
*/
var NoProjectsCtrl = function($location, Project) {
    // Redirect the user when projects or permissions were added.
    Project.all({}, function(projects) {
        if (projects.length > 0) {
            $location.path('/');
        }
    });
};

/*
    Controller for selecting projects.
*/
var ProjectCtrl = function($scope, $routeParams, Project, globalState) {
    $scope.project = Project.get({id: $routeParams.project});
    $scope.projects = Project.all();
    $scope.global_state = globalState;

    // it seems that if we have multiple controllers (called from the template
    // with ng-controller and from the routeProvider), only one $scope is
    // watched?
    var digest = function() {
        $scope.$digest();
        setTimeout(digest, 1000);
    };

    setTimeout(digest, 1000);
};

/*
    Controller for run actions.
*/
var RunActionCtrl = function($scope, $routeParams, globalState, Run, Job, Group, KillRequest) {
    var getPermissionsForJob = function(jobId) {
        $scope.auth_permissions = false;
        $scope.job = Job.get({id: jobId}, function(job) {
            job.get_job_template(function(jobTemplate) {
                jobTemplate.get_project(function(project) {
                    Group.all({}, function(groups) {
                        angular.forEach(groups, function(group) {
                            if(project.auth_groups.indexOf(group.resource_uri) >= 0) {
                                $scope.auth_permissions = true;
                            }
                        });
                    });
                });
            });
        });
    };

    $scope.killRun = function() {
        if(!confirm('Are you sure you want to kill this run?')) {
            return false;
        }

        var killRequest = new KillRequest({
            run: $scope.run.resource_uri
        });
        killRequest.$create(function() {
            $scope.kill_request = killRequest;
        });
    };

    if ($routeParams.run !== undefined) {
        Run.get({id: $routeParams.run}, function(run) {
            getPermissionsForJob(run.job.split('/').splice(-2, 1)[0]);
        });
    }

};

/*
    Controller for job actions.
*/
var JobActionCtrl = function($scope, $routeParams, $route, Job, Group, Run, globalState, globalCache) {
    // set $scope.auth_permissions to true if the user has auth permissions
    // for the given jobId.
    var getPermissionsForJob = function(jobId) {
        $scope.auth_permissions = false;
        $scope.job = Job.get({id: jobId}, function(job) {
            job.get_job_template(function(jobTemplate) {
                jobTemplate.get_project(function(project) {
                    globalState.getAllGroups(function(groups) {
                        angular.forEach(groups, function(group) {
                            if(project.auth_groups.indexOf(group.resource_uri) >= 0) {
                                $scope.auth_permissions = true;
                            }
                        });
                    });
                });
            });
        });
    };

    // function for scheduling a job
    $scope.scheduleNow = function(withChildren) {
        if (!confirm('Are you sure you want to schedule this job?')) {
            return false;
        }

        var newRun = new Run({
            job: $scope.job.resource_uri,
            is_manual: true,
            schedule_children: withChildren,
            schedule_dts: moment().format('YYYY-MM-DD HH:mm:ssZ')
        });
        newRun.$create(function() {
            $scope.scheduled_run = newRun;
        });
    };

    // function for setting enqueue_is_enabled attribute on job model
    $scope.toggleEnqueue = function(toValue) {
        if (toValue === true) {
            if (confirm('Are you sure you want to enable the enqueueing of this job?')) {
                $scope.job.enqueue_is_enabled = toValue;
                $scope.job.$save(function(){
                    // invalidate the cache
                    globalCache.remove('job.' + $scope.job.id);
                    globalCache.remove('job.all');
                    if ($routeParams.job) {
                        $route.reload();
                    }
                });
            }
        } else if (toValue === false) {
            if (confirm('Are you sure you want to suspend the enqueueing of this job? If suspended, the job will not be added to the worker queue. This will not affect already running jobs.\n\nNote: this will as well affect the children of this job!')) {
                $scope.job.enqueue_is_enabled = toValue;
                $scope.job.$save(function() {
                    // invalidate the cache
                    globalCache.remove('job.' + $scope.job.id);
                    globalCache.remove('job.all');
                    if ($routeParams.job) {
                        $route.reload();
                    }
                });
            }
        }
    };

    if ($routeParams.job !== undefined) {
        getPermissionsForJob($routeParams.job);
    } else if ($routeParams.run !== undefined) {
        Run.get({id: $routeParams.run}, function(run) {
            getPermissionsForJob(run.job.split('/').splice(-2, 1)[0]);
        });
    }
};


text:
package org.elasticsearch.painless;

import org.apache.lucene.search.Scorer;
import org.elasticsearch.search.lookup.LeafDocLookup;

import java.util.BitSet;
import java.util.Map;

/**
 * The superclass used to build all Painless scripts on top of.
 */
public abstract class Executable {

    private final String name;
    private final String source;
    private final BitSet statements;

    public Executable(String name, String source, BitSet statements) {
        this.name = name;
        this.source = source;
        this.statements = statements;
    }

    public String getName() {
        return name;
    }

    public String getSource() {
        return source;
    }

    /**
     * Finds the start of the first statement boundary that is
     * on or before {@code offset}. If one is not found, {@code -1}
     * is returned.
     */
    public int getPreviousStatement(int offset) {
        return statements.previousSetBit(offset);
    }

    /**
     * Finds the start of the first statement boundary that is
     * after {@code offset}. If one is not found, {@code -1}
     * is returned.
     */
    public int getNextStatement(int offset) {
        return statements.nextSetBit(offset+1);
    }

    public abstract Object execute(
        final Map<String, Object> params, final Scorer scorer, final LeafDocLookup doc, final Object value);
}

redpajama_set_name: RedPajamaGithub


text:
package org.elasticsearch.common.geo.builders;

import java.util.ArrayList;

import com.vividsolutions.jts.geom.Coordinate;

public class PolygonBuilder extends BasePolygonBuilder<PolygonBuilder> {

    public PolygonBuilder() {
        this(new ArrayList<Coordinate>(), Orientation.RIGHT);
    }

    public PolygonBuilder(Orientation orientation) {
        this(new ArrayList<Coordinate>(), orientation);
    }

    protected PolygonBuilder(ArrayList<Coordinate> points, Orientation orientation) {
        super(orientation);
        this.shell = new Ring<>(this, points);
    }

    @Override
    public PolygonBuilder close() {
        super.close();
        return this;
    }
}


text:
package pacman.model.behaviour;

import jade.core.Agent;
import pacman.model.agent.GhostAgent;
import pacman.model.board.Board;
import pacman.model.board.Cell;
import pacman.model.board.CellType;
import pacman.model.board.Coord2D;
import pacman.model.board.Direction;
import pacman.model.core.Constant;

public class GhostLeaveHouseNextBehaviour extends GhostLeaveHouseBehaviour
{

    // Game control properties
    private boolean startMoving;    // TRUE if the initial house delay time has finished - FALSE otherwise

    public GhostLeaveHouseNextBehaviour(Agent agent, Board board, Cell cell)
    {
        super(agent, board, cell);
    }

    @Override
    public void onStart()
    {
        startMoving = false;

        // Delays a time before starts moving
        try { Thread.sleep(Constant.GHOST_LEAVE_HOUSE_DELAY); } catch (InterruptedException ex) {}

        startMoving = true;
    }

    @Override
    @SuppressWarnings("SleepWhileInLoop")
    public void onTick()
    {
        if (!(((GhostAgent) myAgent).isGameRunning()) && startMoving
                && !((GhostAgent) myAgent).isHouseLeft())
        {
            return;
        }

        Coord2D myPosition = myCell.getPosition();
        Coord2D doorPosition = board.getGhostDoor().getPosition();

        for (Direction direction : Direction.values())
        {
            Coord2D myNewPosition = new Coord2D(myPosition.x + direction.xInc, myPosition.y + direction.yInc);

            // Found the door
            if (doorPosition.equals(myNewPosition))
            {
                // Leaves the house
                System.out.println(myAgent.getLocalName() + " leaving house by " + direction.toString().toLowerCase());
                board.moveCell(myCell, myNewPosition);
                ((GhostAgent) myAgent).setHouseLeft(true);
                board.print();

                // Advices the next ghost (if any) to leave his house
                adviceNextGhost();
                myAgent.removeBehaviour(this);

                // Delays a time before the next ghost leaves the door
                try { Thread.sleep(Constant.MOVEMENT_DELAY * 2); } catch (InterruptedException ex) {}

                return;
            }
        }

        // Else, keeps looking for it
        Direction currentDirection = ((GhostAgent) myAgent).getCurrentDirection();
        for (Direction direction : Direction.values())
        {
            Coord2D myNewPosition = new Coord2D(myPosition.x + direction.xInc, myPosition.y + direction.yInc);

            Cell nearCell = board.getCell(myNewPosition);
            if (CellType.GHOST_HOUSE == nearCell.getType())
            {
                if (null == currentDirection)
                {
                    currentDirection = direction;
                    ((GhostAgent) myAgent).setCurrentDirection(direction);
                }

                if (currentDirection == direction)
                {
                    System.out.println(myAgent.getLocalName() + " is moving to " + direction);
                    board.moveCell(myCell, myNewPosition);
                    board.print();

                    break;
                }
            }
        }
    }

}


text:
namespace {

// Used to generate a unique id when emitting the "Long Navigation to First
// Contentful Paint" trace event.
int g_num_trace_events_in_process = 0;

// The threshold to emit a trace event is the 99th percentile
// of the histogram on Windows Stable as of Feb 26th, 2020.
constexpr base::TimeDelta kFirstContentfulPaintTraceThreshold =
    base::Milliseconds(12388);

// TODO(bmcquade): If other observers want to log histograms based on load type,
// promote this enum to page_load_metrics_observer.h.
enum PageLoadType {
  LOAD_TYPE_NONE = 0,
  LOAD_TYPE_RELOAD,
  LOAD_TYPE_FORWARD_BACK,
  LOAD_TYPE_NEW_NAVIGATION
};

PageLoadType GetPageLoadType(ui::PageTransition transition) {
  if (transition & ui::PAGE_TRANSITION_FORWARD_BACK) {
    return LOAD_TYPE_FORWARD_BACK;
  }
  if (ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_RELOAD)) {
    return LOAD_TYPE_RELOAD;
  }
  if (ui::PageTransitionIsNewNavigation(transition)) {
    return LOAD_TYPE_NEW_NAVIGATION;
  }
  NOTREACHED() << "Received PageTransition with no matching PageLoadType.";
  return LOAD_TYPE_NONE;
}

void RecordFirstMeaningfulPaintStatus(
    internal::FirstMeaningfulPaintStatus status) {
  UMA_HISTOGRAM_ENUMERATION(internal::kHistogramFirstMeaningfulPaintStatus,
                            status,
                            internal::FIRST_MEANINGFUL_PAINT_LAST_ENTRY);
}

std::unique_ptr<base::trace_event::TracedValue> FirstInputDelayTraceData(
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  std::unique_ptr<base::trace_event::TracedValue> data =
      std::make_unique<base::trace_event::TracedValue>();
  data->SetDouble(
      "firstInputDelayInMilliseconds",
      timing.interactive_timing->first_input_delay->InMillisecondsF());
  data->SetDouble(
      "navStartToFirstInputTimestampInMilliseconds",
      timing.interactive_timing->first_input_timestamp->InMillisecondsF());
  return data;
}

// TODO(crbug/1097328): Remove collecting visits to support.google.com after
// language settings update fully launches.
#if BUILDFLAG(IS_CHROMEOS_ASH)
void RecordVisitToLanguageSettingsSupportPage(const GURL& url) {
  if (url.is_empty() || !url.DomainIs("support.google.com"))
    return;

  // Keep these pages in order with SettingsLanguagesSupportPage in enums.xml
  std::vector<std::string> kSupportPages = {
      "chrome/answer/173424?co=GENIE.Platform%3DDesktop",
      "chromebook/answer/1059490",
      "chromebook/answer/1059492",
  };
  const size_t num_pages = 3;
  for (size_t i = 0; i < num_pages; ++i) {
    if (url.spec().find(kSupportPages[i]) != std::string::npos) {
      UMA_HISTOGRAM_ENUMERATION("ChromeOS.Settings.Languages.SupportPageVisits",
                                i, num_pages);
      return;
    }
  }
}
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

}  // namespace

namespace internal {

const char kHistogramDomContentLoaded[] =
    "PageLoad.DocumentTiming.NavigationToDOMContentLoadedEventFired";
const char kBackgroundHistogramDomContentLoaded[] =
    "PageLoad.DocumentTiming.NavigationToDOMContentLoadedEventFired.Background";
const char kHistogramLoad[] =
    "PageLoad.DocumentTiming.NavigationToLoadEventFired";
const char kBackgroundHistogramLoad[] =
    "PageLoad.DocumentTiming.NavigationToLoadEventFired.Background";
const char kHistogramFirstPaint[] =
    "PageLoad.PaintTiming.NavigationToFirstPaint";
const char kBackgroundHistogramFirstPaint[] =
    "PageLoad.PaintTiming.NavigationToFirstPaint.Background";
const char kHistogramFirstImagePaint[] =
    "PageLoad.PaintTiming.NavigationToFirstImagePaint";
const char kBackgroundHistogramFirstImagePaint[] =
    "PageLoad.PaintTiming.NavigationToFirstImagePaint.Background";
const char kHistogramFirstContentfulPaint[] =
    "PageLoad.PaintTiming.NavigationToFirstContentfulPaint";
const char kBackgroundHistogramFirstContentfulPaint[] =
    "PageLoad.PaintTiming.NavigationToFirstContentfulPaint.Background";
const char kHistogramFirstContentfulPaintInitiatingProcess[] =
    "PageLoad.Internal.PaintTiming.NavigationToFirstContentfulPaint."
    "InitiatingProcess";
const char kHistogramFirstMeaningfulPaint[] =
    "PageLoad.Experimental.PaintTiming.NavigationToFirstMeaningfulPaint";
const char kHistogramLargestContentfulPaint[] =
    "PageLoad.PaintTiming.NavigationToLargestContentfulPaint2";
const char kHistogramLargestContentfulPaintContentType[] =
    "PageLoad.Internal.PaintTiming.LargestContentfulPaint.ContentType";
const char kHistogramLargestContentfulPaintMainFrame[] =
    "PageLoad.PaintTiming.NavigationToLargestContentfulPaint2.MainFrame";
const char kHistogramLargestContentfulPaintMainFrameContentType[] =
    "PageLoad.Internal.PaintTiming.LargestContentfulPaint.MainFrame."
    "ContentType";
const char kHistogramLargestContentfulPaintCrossSiteSubFrame[] =
    "PageLoad.PaintTiming.NavigationToLargestContentfulPaint2."
    "CrossSiteSubFrame";

const char kHistogramNumInteractions[] =
    "PageLoad.InteractiveTiming.NumInteractions";
const char kHistogramUserInteractionLatencyHighPercentile2MaxEventDuration[] =
    "PageLoad.InteractiveTiming.UserInteractionLatency.HighPercentile2."
    "MaxEventDuration";
const char kHistogramAverageUserInteractionLatencyOverBudgetMaxEventDuration[] =
    "PageLoad.InteractiveTiming.AverageUserInteractionLatencyOverBudget."
    "MaxEventDuration";
const char
    kHistogramSlowUserInteractionLatencyOverBudgetHighPercentile2MaxEventDuration
        [] = "PageLoad.InteractiveTiming.SlowUserInteractionLatencyOverBudget."
             "HighPercentile2.MaxEventDuration";
const char kHistogramSumOfUserInteractionLatencyOverBudgetMaxEventDuration[] =
    "PageLoad.InteractiveTiming.SumOfUserInteractionLatencyOverBudget."
    "MaxEventDuration";
const char kHistogramWorstUserInteractionLatencyMaxEventDuration[] =
    "PageLoad.InteractiveTiming.WorstUserInteractionLatency.MaxEventDuration";

const char kHistogramFirstInputDelay[] =
    "PageLoad.InteractiveTiming.FirstInputDelay4";
const char kHistogramFirstInputTimestamp[] =
    "PageLoad.InteractiveTiming.FirstInputTimestamp4";
const char kHistogramLongestInputDelay[] =
    "PageLoad.InteractiveTiming.LongestInputDelay4";
const char kHistogramLongestInputTimestamp[] =
    "PageLoad.InteractiveTiming.LongestInputTimestamp4";
const char kHistogramParseStartToFirstMeaningfulPaint[] =
    "PageLoad.Experimental.PaintTiming.ParseStartToFirstMeaningfulPaint";
const char kHistogramParseStartToFirstContentfulPaint[] =
    "PageLoad.PaintTiming.ParseStartToFirstContentfulPaint";
const char kBackgroundHistogramParseStartToFirstContentfulPaint[] =
    "PageLoad.PaintTiming.ParseStartToFirstContentfulPaint.Background";
const char kHistogramParseStart[] =
    "PageLoad.ParseTiming.NavigationToParseStart";
const char kBackgroundHistogramParseStart[] =
    "PageLoad.ParseTiming.NavigationToParseStart.Background";
const char kHistogramParseDuration[] = "PageLoad.ParseTiming.ParseDuration";
const char kBackgroundHistogramParseDuration[] =
    "PageLoad.ParseTiming.ParseDuration.Background";
const char kHistogramParseBlockedOnScriptLoad[] =
    "PageLoad.ParseTiming.ParseBlockedOnScriptLoad";
const char kBackgroundHistogramParseBlockedOnScriptLoad[] =
    "PageLoad.ParseTiming.ParseBlockedOnScriptLoad.Background";
const char kHistogramParseBlockedOnScriptLoadDocumentWrite[] =
    "PageLoad.ParseTiming.ParseBlockedOnScriptLoadFromDocumentWrite";
const char kBackgroundHistogramParseBlockedOnScriptLoadDocumentWrite[] =
    "PageLoad.ParseTiming.ParseBlockedOnScriptLoadFromDocumentWrite."
    "Background";
const char kHistogramParseBlockedOnScriptExecution[] =
    "PageLoad.ParseTiming.ParseBlockedOnScriptExecution";
const char kHistogramParseBlockedOnScriptExecutionDocumentWrite[] =
    "PageLoad.ParseTiming.ParseBlockedOnScriptExecutionFromDocumentWrite";

const char kHistogramFirstContentfulPaintNoStore[] =
    "PageLoad.PaintTiming.NavigationToFirstContentfulPaint.NoStore";

const char kHistogramFirstContentfulPaintHiddenWhileFlushing[] =
    "PageLoad.PaintTiming.NavigationToFirstContentfulPaint.HiddenWhileFlushing";

const char kHistogramLoadTypeFirstContentfulPaintReload[] =
    "PageLoad.PaintTiming.NavigationToFirstContentfulPaint.LoadType."
    "Reload";
const char kHistogramLoadTypeFirstContentfulPaintReloadByGesture[] =
    "PageLoad.PaintTiming.NavigationToFirstContentfulPaint.LoadType."
    "Reload.UserGesture";
const char kHistogramLoadTypeFirstContentfulPaintForwardBack[] =
    "PageLoad.PaintTiming.NavigationToFirstContentfulPaint.LoadType."
    "ForwardBackNavigation";
const char kHistogramLoadTypeFirstContentfulPaintForwardBackNoStore[] =
    "PageLoad.PaintTiming.NavigationToFirstContentfulPaint.LoadType."
    "ForwardBackNavigation.NoStore";
const char kHistogramLoadTypeFirstContentfulPaintNewNavigation[] =
    "PageLoad.PaintTiming.NavigationToFirstContentfulPaint.LoadType."
    "NewNavigation";

const char kHistogramPageTimingForegroundDuration[] =
    "PageLoad.PageTiming.ForegroundDuration";
const char kHistogramPageTimingForegroundDurationAfterPaint[] =
    "PageLoad.PageTiming.ForegroundDuration.AfterPaint";
const char kHistogramPageTimingForegroundDurationNoCommit[] =
    "PageLoad.PageTiming.ForegroundDuration.NoCommit";
const char kHistogramPageTimingForegroundDurationWithPaint[] =
    "PageLoad.PageTiming.ForegroundDuration.WithPaint";
const char kHistogramPageTimingForegroundDurationWithoutPaint[] =
    "PageLoad.PageTiming.ForegroundDuration.WithoutPaint";

const char kHistogramLoadTypeParseStartReload[] =
    "PageLoad.ParseTiming.NavigationToParseStart.LoadType.Reload";
const char kHistogramLoadTypeParseStartForwardBack[] =
    "PageLoad.ParseTiming.NavigationToParseStart.LoadType."
    "ForwardBackNavigation";
const char kHistogramLoadTypeParseStartForwardBackNoStore[] =
    "PageLoad.ParseTiming.NavigationToParseStart.LoadType."
    "ForwardBackNavigation.NoStore";
const char kHistogramLoadTypeParseStartNewNavigation[] =
    "PageLoad.ParseTiming.NavigationToParseStart.LoadType.NewNavigation";

const char kHistogramFirstForeground[] =
    "PageLoad.PageTiming.NavigationToFirstForeground";

const char kHistogramUserGestureNavigationToForwardBack[] =
    "PageLoad.PageTiming.ForegroundDuration.PageEndReason."
    "ForwardBackNavigation.UserGesture";

const char kHistogramForegroundToFirstPaint[] =
    "PageLoad.PaintTiming.ForegroundToFirstPaint";
const char kHistogramForegroundToFirstContentfulPaint[] =
    "PageLoad.PaintTiming.ForegroundToFirstContentfulPaint";

const char kHistogramFirstContentfulPaintUserInitiated[] =
    "PageLoad.PaintTiming.NavigationToFirstContentfulPaint.UserInitiated";

const char kHistogramFirstMeaningfulPaintStatus[] =
    "PageLoad.Experimental.PaintTiming.FirstMeaningfulPaintStatus";

const char kHistogramCachedResourceLoadTimePrefix[] =
    "PageLoad.Experimental.PageTiming.CachedResourceLoadTime.";
const char kHistogramCommitSentToFirstSubresourceLoadStart[] =
    "PageLoad.Experimental.PageTiming.CommitSentToFirstSubresourceLoadStart";
const char kHistogramNavigationToFirstSubresourceLoadStart[] =
    "PageLoad.Experimental.PageTiming.NavigationToFirstSubresourceLoadStart";
const char kHistogramResourceLoadTimePrefix[] =
    "PageLoad.Experimental.PageTiming.ResourceLoadTime.";
const char kHistogramTotalSubresourceLoadTimeAtFirstContentfulPaint[] =
    "PageLoad.Experimental.PageTiming."
    "TotalSubresourceLoadTimeAtFirstContentfulPaint";
const char kHistogramFirstEligibleToPaint[] =
    "PageLoad.Experimental.PaintTiming.NavigationToFirstEligibleToPaint";
const char kHistogramFirstEligibleToPaintToFirstPaint[] =
    "PageLoad.Experimental.PaintTiming.FirstEligibleToPaintToFirstPaint";

const char kHistogramFirstNonScrollInputAfterFirstPaint[] =
    "PageLoad.InputTiming.NavigationToFirstNonScroll.AfterPaint";
const char kHistogramFirstScrollInputAfterFirstPaint[] =
    "PageLoad.InputTiming.NavigationToFirstScroll.AfterPaint";

const char kHistogramPageLoadTotalBytes[] =
    "PageLoad.Experimental.Bytes.Total2";
const char kHistogramPageLoadNetworkBytes[] =
    "PageLoad.Experimental.Bytes.Network";
const char kHistogramPageLoadCacheBytes[] =
    "PageLoad.Experimental.Bytes.Cache2";
const char kHistogramPageLoadNetworkBytesIncludingHeaders[] =
    "PageLoad.Experimental.Bytes.NetworkIncludingHeaders";
const char kHistogramPageLoadUnfinishedBytes[] =
    "PageLoad.Experimental.Bytes.Unfinished";

const char kHistogramPageLoadCpuTotalUsage[] = "PageLoad.Cpu.TotalUsage";
const char kHistogramPageLoadCpuTotalUsageForegrounded[] =
    "PageLoad.Cpu.TotalUsageForegrounded";

const char kHistogramLoadTypeTotalBytesForwardBack[] =
    "PageLoad.Experimental.Bytes.Total2.LoadType.ForwardBackNavigation";
const char kHistogramLoadTypeNetworkBytesForwardBack[] =
    "PageLoad.Experimental.Bytes.Network.LoadType.ForwardBackNavigation";
const char kHistogramLoadTypeCacheBytesForwardBack[] =
    "PageLoad.Experimental.Bytes.Cache2.LoadType.ForwardBackNavigation";

const char kHistogramLoadTypeTotalBytesReload[] =
    "PageLoad.Experimental.Bytes.Total2.LoadType.Reload";
const char kHistogramLoadTypeNetworkBytesReload[] =
    "PageLoad.Experimental.Bytes.Network.LoadType.Reload";
const char kHistogramLoadTypeCacheBytesReload[] =
    "PageLoad.Experimental.Bytes.Cache2.LoadType.Reload";

const char kHistogramLoadTypeTotalBytesNewNavigation[] =
    "PageLoad.Experimental.Bytes.Total2.LoadType.NewNavigation";
const char kHistogramLoadTypeNetworkBytesNewNavigation[] =
    "PageLoad.Experimental.Bytes.Network.LoadType.NewNavigation";
const char kHistogramLoadTypeCacheBytesNewNavigation[] =
    "PageLoad.Experimental.Bytes.Cache2.LoadType.NewNavigation";

const char kHistogramInputToNavigation[] =
    "PageLoad.Experimental.InputTiming.InputToNavigationStart";
const char kBackgroundHistogramInputToNavigation[] =
    "PageLoad.Experimental.InputTiming.InputToNavigationStart.Background";
const char kHistogramInputToNavigationLinkClick[] =
    "PageLoad.Experimental.InputTiming.InputToNavigationStart.FromLinkClick";
const char kHistogramInputToNavigationOmnibox[] =
    "PageLoad.Experimental.InputTiming.InputToNavigationStart.FromOmnibox";
const char kHistogramInputToFirstPaint[] =
    "PageLoad.Experimental.PaintTiming.InputToFirstPaint";
const char kBackgroundHistogramInputToFirstPaint[] =
    "PageLoad.Experimental.PaintTiming.InputToFirstPaint.Background";
const char kHistogramInputToFirstContentfulPaint[] =
    "PageLoad.Experimental.PaintTiming.InputToFirstContentfulPaint";
const char kBackgroundHistogramInputToFirstContentfulPaint[] =
    "PageLoad.Experimental.PaintTiming.InputToFirstContentfulPaint.Background";

const char kHistogramBackForwardCacheEvent[] =
    "PageLoad.BackForwardCache.Event";

// Navigation metrics from the navigation start.
const char kHistogramNavigationTimingNavigationStartToFirstRequestStart[] =
    "PageLoad.Experimental.NavigationTiming.NavigationStartToFirstRequestStart";
const char kHistogramNavigationTimingNavigationStartToFirstResponseStart[] =
    "PageLoad.Experimental.NavigationTiming."
    "NavigationStartToFirstResponseStart";
const char kHistogramNavigationTimingNavigationStartToFirstLoaderCallback[] =
    "PageLoad.Experimental.NavigationTiming."
    "NavigationStartToFirstLoaderCallback";
const char kHistogramNavigationTimingNavigationStartToFinalRequestStart[] =
    "PageLoad.Experimental.NavigationTiming.NavigationStartToFinalRequestStart";
const char kHistogramNavigationTimingNavigationStartToFinalResponseStart[] =
    "PageLoad.Experimental.NavigationTiming."
    "NavigationStartToFinalResponseStart";
const char kHistogramNavigationTimingNavigationStartToFinalLoaderCallback[] =
    "PageLoad.Experimental.NavigationTiming."
    "NavigationStartToFinalLoaderCallback";
const char kHistogramNavigationTimingNavigationStartToNavigationCommitSent[] =
    "PageLoad.Experimental.NavigationTiming."
    "NavigationStartToNavigationCommitSent";

// Navigation metrics between milestones.
const char kHistogramNavigationTimingFirstRequestStartToFirstResponseStart[] =
    "PageLoad.Experimental.NavigationTiming."
    "FirstRequestStartToFirstResponseStart";
const char kHistogramNavigationTimingFirstResponseStartToFirstLoaderCallback[] =
    "PageLoad.Experimental.NavigationTiming."
    "FirstResponseStartToFirstLoaderCallback";
const char kHistogramNavigationTimingFinalRequestStartToFinalResponseStart[] =
    "PageLoad.Experimental.NavigationTiming."
    "FinalRequestStartToFinalResponseStart";
const char kHistogramNavigationTimingFinalResponseStartToFinalLoaderCallback[] =
    "PageLoad.Experimental.NavigationTiming."
    "FinalResponseStartToFinalLoaderCallback";
const char
    kHistogramNavigationTimingFinalLoaderCallbackToNavigationCommitSent[] =
        "PageLoad.Experimental.NavigationTiming."
        "FinalLoaderCallbackToNavigationCommitSent";

// V8 memory usage metrics.
const char kHistogramMemoryMainframe[] =
    "PageLoad.Experimental.Memory.Core.MainFrame.Max";
const char kHistogramMemorySubframeAggregate[] =
    "PageLoad.Experimental.Memory.Core.Subframe.Aggregate.Max";
const char kHistogramMemoryTotal[] =
    "PageLoad.Experimental.Memory.Core.Total.Max";
const char kHistogramMemoryUpdateReceived[] =
    "PageLoad.Experimental.Memory.Core.UpdateReceived";

}  // namespace internal

UmaPageLoadMetricsObserver::UmaPageLoadMetricsObserver()
    : transition_(ui::PAGE_TRANSITION_LINK),
      was_no_store_main_resource_(false),
      cache_bytes_(0),
      network_bytes_(0),
      network_bytes_including_headers_(0),
      redirect_chain_size_(0) {}

UmaPageLoadMetricsObserver::~UmaPageLoadMetricsObserver() {}

page_load_metrics::PageLoadMetricsObserver::ObservePolicy
UmaPageLoadMetricsObserver::OnRedirect(
    content::NavigationHandle* navigation_handle) {
  redirect_chain_size_++;
  return CONTINUE_OBSERVING;
}

page_load_metrics::PageLoadMetricsObserver::ObservePolicy
UmaPageLoadMetricsObserver::OnCommit(
    content::NavigationHandle* navigation_handle,
    ukm::SourceId source_id) {
  transition_ = navigation_handle->GetPageTransition();
  const net::HttpResponseHeaders* headers =
      navigation_handle->GetResponseHeaders();
  if (headers) {
    was_no_store_main_resource_ =
        headers->HasHeaderValue("cache-control", "no-store");
  }
  UMA_HISTOGRAM_COUNTS_100("PageLoad.Navigation.RedirectChainLength",
                           redirect_chain_size_);
  navigation_handle_timing_ = navigation_handle->GetNavigationHandleTiming();

  // TODO(crbug/1097328): Remove collecting visits to support.google.com after
  // language settings update fully launches.
#if BUILDFLAG(IS_CHROMEOS_ASH)
  RecordVisitToLanguageSettingsSupportPage(navigation_handle->GetURL());
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)
  return CONTINUE_OBSERVING;
}

void UmaPageLoadMetricsObserver::OnDomContentLoadedEventStart(
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  if (page_load_metrics::WasStartedInForegroundOptionalEventInForeground(
          timing.document_timing->dom_content_loaded_event_start,
          GetDelegate())) {
    PAGE_LOAD_HISTOGRAM(
        internal::kHistogramDomContentLoaded,
        timing.document_timing->dom_content_loaded_event_start.value());
  } else {
    PAGE_LOAD_HISTOGRAM(
        internal::kBackgroundHistogramDomContentLoaded,
        timing.document_timing->dom_content_loaded_event_start.value());
  }
}

void UmaPageLoadMetricsObserver::OnLoadEventStart(
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  if (page_load_metrics::WasStartedInForegroundOptionalEventInForeground(
          timing.document_timing->load_event_start, GetDelegate())) {
    PAGE_LOAD_HISTOGRAM(internal::kHistogramLoad,
                        timing.document_timing->load_event_start.value());
  } else {
    PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramLoad,
                        timing.document_timing->load_event_start.value());
  }
}

void UmaPageLoadMetricsObserver::OnFirstPaintInPage(
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  first_paint_ = GetDelegate().GetNavigationStart() +
                 timing.paint_timing->first_paint.value();
  if (page_load_metrics::WasStartedInForegroundOptionalEventInForeground(
          timing.paint_timing->first_paint, GetDelegate())) {
    PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstPaint,
                        timing.paint_timing->first_paint.value());
    if (timing.paint_timing->first_eligible_to_paint) {
      PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstEligibleToPaint,
                          timing.paint_timing->first_eligible_to_paint.value());
      PAGE_LOAD_HISTOGRAM(
          internal::kHistogramFirstEligibleToPaintToFirstPaint,
          timing.paint_timing->first_paint.value() -
              timing.paint_timing->first_eligible_to_paint.value());
    }

    if (timing.input_to_navigation_start) {
      PAGE_LOAD_HISTOGRAM(internal::kHistogramInputToFirstPaint,
                          timing.input_to_navigation_start.value() +
                              timing.paint_timing->first_paint.value());
    }
  } else {
    PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstPaint,
                        timing.paint_timing->first_paint.value());
    if (timing.input_to_navigation_start) {
      PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramInputToFirstPaint,
                          timing.input_to_navigation_start.value() +
                              timing.paint_timing->first_paint.value());
    }
  }

  if (page_load_metrics::WasStartedInBackgroundOptionalEventInForeground(
          timing.paint_timing->first_paint, GetDelegate())) {
    PAGE_LOAD_HISTOGRAM(internal::kHistogramForegroundToFirstPaint,
                        timing.paint_timing->first_paint.value() -
                            GetDelegate().GetTimeToFirstForeground().value());
  }
}

void UmaPageLoadMetricsObserver::OnFirstImagePaintInPage(
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  if (page_load_metrics::WasStartedInForegroundOptionalEventInForeground(
          timing.paint_timing->first_image_paint, GetDelegate())) {
    PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstImagePaint,
                        timing.paint_timing->first_image_paint.value());
  } else {
    PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstImagePaint,
                        timing.paint_timing->first_image_paint.value());
  }
}

void UmaPageLoadMetricsObserver::OnFirstContentfulPaintInPage(
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  DCHECK(timing.paint_timing->first_contentful_paint);
  if (page_load_metrics::WasStartedInForegroundOptionalEventInForeground(
          timing.paint_timing->first_contentful_paint, GetDelegate())) {
    PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaint,
                        timing.paint_timing->first_contentful_paint.value());
    PAGE_LOAD_HISTOGRAM(internal::kHistogramParseStartToFirstContentfulPaint,
                        timing.paint_timing->first_contentful_paint.value() -
                            timing.parse_timing->parse_start.value());

    PAGE_LOAD_HISTOGRAM(
        internal::kHistogramTotalSubresourceLoadTimeAtFirstContentfulPaint,
        total_subresource_load_time_);

    // Emit a trace event to highlight a long navigation to first contentful
    // paint.
    if (timing.paint_timing->first_contentful_paint.value() >
        kFirstContentfulPaintTraceThreshold) {
      base::TimeTicks navigation_start = GetDelegate().GetNavigationStart();
      TRACE_EVENT_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP0(
          "latency", "Long Navigation to First Contentful Paint",
          TRACE_ID_LOCAL(g_num_trace_events_in_process), navigation_start);
      TRACE_EVENT_NESTABLE_ASYNC_END_WITH_TIMESTAMP0(
          "latency", "Long Navigation to First Contentful Paint",
          TRACE_ID_LOCAL(g_num_trace_events_in_process),
          navigation_start +
              timing.paint_timing->first_contentful_paint.value());
      g_num_trace_events_in_process++;
    }

    UMA_HISTOGRAM_ENUMERATION(
        internal::kHistogramFirstContentfulPaintInitiatingProcess,
        GetDelegate().GetUserInitiatedInfo().browser_initiated
            ? content::PROCESS_TYPE_BROWSER
            : content::PROCESS_TYPE_RENDERER,
        content::PROCESS_TYPE_CONTENT_END);

    if (was_no_store_main_resource_) {
      PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaintNoStore,
                          timing.paint_timing->first_contentful_paint.value());
    }

    // TODO(bmcquade): consider adding a histogram that uses
    // UserInputInfo.user_input_event.
    if (GetDelegate().GetUserInitiatedInfo().browser_initiated ||
        GetDelegate().GetUserInitiatedInfo().user_gesture) {
      PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaintUserInitiated,
                          timing.paint_timing->first_contentful_paint.value());
    }

    if (timing.input_to_navigation_start) {
      PAGE_LOAD_HISTOGRAM(internal::kHistogramInputToNavigation,
                          timing.input_to_navigation_start.value());
      PAGE_LOAD_HISTOGRAM(
          internal::kHistogramInputToFirstContentfulPaint,
          timing.input_to_navigation_start.value() +
              timing.paint_timing->first_contentful_paint.value());

      if (ui::PageTransitionCoreTypeIs(transition_, ui::PAGE_TRANSITION_LINK)) {
        PAGE_LOAD_HISTOGRAM(internal::kHistogramInputToNavigationLinkClick,
                            timing.input_to_navigation_start.value());
      } else if (ui::PageTransitionCoreTypeIs(transition_,
                                              ui::PAGE_TRANSITION_GENERATED) ||
                 ui::PageTransitionCoreTypeIs(transition_,
                                              ui::PAGE_TRANSITION_TYPED)) {
        PAGE_LOAD_HISTOGRAM(internal::kHistogramInputToNavigationOmnibox,
                            timing.input_to_navigation_start.value());
      }
    }

    if (GetDelegate().GetTimeToFirstBackground()) {
      // We were started in the foreground, and got FCP while in foreground, but
      // became hidden while propagating the FCP value from Blink into the PLM
      // observer. In this case, we will have missed the FCP UKM value, since it
      // is logged in UkmPageLoadMetricsObserver::OnHidden.
      PAGE_LOAD_HISTOGRAM(
          internal::kHistogramFirstContentfulPaintHiddenWhileFlushing,
          timing.paint_timing->first_contentful_paint.value());
    }

    switch (GetPageLoadType(transition_)) {
      case LOAD_TYPE_RELOAD:
        PAGE_LOAD_HISTOGRAM(
            internal::kHistogramLoadTypeFirstContentfulPaintReload,
            timing.paint_timing->first_contentful_paint.value());
        // TODO(bmcquade): consider adding a histogram that uses
        // UserInputInfo.user_input_event.
        if (GetDelegate().GetUserInitiatedInfo().browser_initiated ||
            GetDelegate().GetUserInitiatedInfo().user_gesture) {
          PAGE_LOAD_HISTOGRAM(
              internal::kHistogramLoadTypeFirstContentfulPaintReloadByGesture,
              timing.paint_timing->first_contentful_paint.value());
        }
        break;
      case LOAD_TYPE_FORWARD_BACK:
        PAGE_LOAD_HISTOGRAM(
            internal::kHistogramLoadTypeFirstContentfulPaintForwardBack,
            timing.paint_timing->first_contentful_paint.value());
        if (was_no_store_main_resource_) {
          PAGE_LOAD_HISTOGRAM(
              internal::
                  kHistogramLoadTypeFirstContentfulPaintForwardBackNoStore,
              timing.paint_timing->first_contentful_paint.value());
        }
        break;
      case LOAD_TYPE_NEW_NAVIGATION:
        PAGE_LOAD_HISTOGRAM(
            internal::kHistogramLoadTypeFirstContentfulPaintNewNavigation,
            timing.paint_timing->first_contentful_paint.value());
        break;
      case LOAD_TYPE_NONE:
        NOTREACHED();
        break;
    }
  } else {
    PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstContentfulPaint,
                        timing.paint_timing->first_contentful_paint.value());
    PAGE_LOAD_HISTOGRAM(
        internal::kBackgroundHistogramParseStartToFirstContentfulPaint,
        timing.paint_timing->first_contentful_paint.value() -
            timing.parse_timing->parse_start.value());
    if (timing.input_to_navigation_start) {
      PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramInputToNavigation,
                          timing.input_to_navigation_start.value());
      PAGE_LOAD_HISTOGRAM(
          internal::kBackgroundHistogramInputToFirstContentfulPaint,
          timing.input_to_navigation_start.value() +
              timing.paint_timing->first_contentful_paint.value());
    }
  }

  if (page_load_metrics::WasStartedInBackgroundOptionalEventInForeground(
          timing.paint_timing->first_contentful_paint, GetDelegate())) {
    PAGE_LOAD_HISTOGRAM(internal::kHistogramForegroundToFirstContentfulPaint,
                        timing.paint_timing->first_contentful_paint.value() -
                            GetDelegate().GetTimeToFirstForeground().value());
  }
}

void UmaPageLoadMetricsObserver::OnFirstMeaningfulPaintInMainFrameDocument(
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  if (page_load_metrics::WasStartedInForegroundOptionalEventInForeground(
          timing.paint_timing->first_meaningful_paint, GetDelegate())) {
    PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstMeaningfulPaint,
                        timing.paint_timing->first_meaningful_paint.value());
    PAGE_LOAD_HISTOGRAM(internal::kHistogramParseStartToFirstMeaningfulPaint,
                        timing.paint_timing->first_meaningful_paint.value() -
                            timing.parse_timing->parse_start.value());
    RecordFirstMeaningfulPaintStatus(internal::FIRST_MEANINGFUL_PAINT_RECORDED);
  } else {
    RecordFirstMeaningfulPaintStatus(
        internal::FIRST_MEANINGFUL_PAINT_BACKGROUNDED);
  }
}

void UmaPageLoadMetricsObserver::OnFirstInputInPage(
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  if (!page_load_metrics::WasStartedInForegroundOptionalEventInForeground(
          timing.interactive_timing->first_input_timestamp, GetDelegate())) {
    return;
  }
  UMA_HISTOGRAM_CUSTOM_TIMES(
      internal::kHistogramFirstInputDelay,
      timing.interactive_timing->first_input_delay.value(),
      base::Milliseconds(1), base::Seconds(60), 50);
  // The pseudo metric of |kHistogramFirstInputDelay|. Only used to assess field
  // trial data quality.
  UMA_HISTOGRAM_CUSTOM_TIMES(
      "UMA.Pseudo.PageLoad.InteractiveTiming.FirstInputDelay4",
      metrics::GetPseudoMetricsSample(
          timing.interactive_timing->first_input_delay.value()),
      base::Milliseconds(1), base::Seconds(60), 50);
  PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstInputTimestamp,
                      timing.interactive_timing->first_input_timestamp.value());
  TRACE_EVENT_MARK_WITH_TIMESTAMP1(
      "loading", "FirstInputDelay::AllFrames::UMA",
      GetDelegate().GetNavigationStart() +
          timing.interactive_timing->first_input_timestamp.value(),
      "data", FirstInputDelayTraceData(timing));
}

void UmaPageLoadMetricsObserver::OnParseStart(
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  if (page_load_metrics::WasStartedInForegroundOptionalEventInForeground(
          timing.parse_timing->parse_start, GetDelegate())) {
    PAGE_LOAD_HISTOGRAM(internal::kHistogramParseStart,
                        timing.parse_timing->parse_start.value());

    switch (GetPageLoadType(transition_)) {
      case LOAD_TYPE_RELOAD:
        PAGE_LOAD_HISTOGRAM(internal::kHistogramLoadTypeParseStartReload,
                            timing.parse_timing->parse_start.value());
        break;
      case LOAD_TYPE_FORWARD_BACK:
        PAGE_LOAD_HISTOGRAM(internal::kHistogramLoadTypeParseStartForwardBack,
                            timing.parse_timing->parse_start.value());
        if (was_no_store_main_resource_) {
          PAGE_LOAD_HISTOGRAM(
              internal::kHistogramLoadTypeParseStartForwardBackNoStore,
              timing.parse_timing->parse_start.value());
        }
        break;
      case LOAD_TYPE_NEW_NAVIGATION:
        PAGE_LOAD_HISTOGRAM(internal::kHistogramLoadTypeParseStartNewNavigation,
                            timing.parse_timing->parse_start.value());
        break;
      case LOAD_TYPE_NONE:
        NOTREACHED();
        break;
    }
  } else {
    PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramParseStart,
                        timing.parse_timing->parse_start.value());
  }
}

void UmaPageLoadMetricsObserver::OnParseStop(
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  base::TimeDelta parse_duration = timing.parse_timing->parse_stop.value() -
                                   timing.parse_timing->parse_start.value();
  if (page_load_metrics::WasStartedInForegroundOptionalEventInForeground(
          timing.parse_timing->parse_stop, GetDelegate())) {
    PAGE_LOAD_HISTOGRAM(internal::kHistogramParseDuration, parse_duration);
    PAGE_LOAD_HISTOGRAM(
        internal::kHistogramParseBlockedOnScriptLoad,
        timing.parse_timing->parse_blocked_on_script_load_duration.value());
    PAGE_LOAD_HISTOGRAM(
        internal::kHistogramParseBlockedOnScriptLoadDocumentWrite,
        timing.parse_timing
            ->parse_blocked_on_script_load_from_document_write_duration
            .value());
    PAGE_LOAD_HISTOGRAM(
        internal::kHistogramParseBlockedOnScriptExecution,
        timing.parse_timing->parse_blocked_on_script_execution_duration
            .value());
    PAGE_LOAD_HISTOGRAM(
        internal::kHistogramParseBlockedOnScriptExecutionDocumentWrite,
        timing.parse_timing
            ->parse_blocked_on_script_execution_from_document_write_duration
            .value());
  } else {
    PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramParseDuration,
                        parse_duration);
    PAGE_LOAD_HISTOGRAM(
        internal::kBackgroundHistogramParseBlockedOnScriptLoad,
        timing.parse_timing->parse_blocked_on_script_load_duration.value());
    PAGE_LOAD_HISTOGRAM(
        internal::kBackgroundHistogramParseBlockedOnScriptLoadDocumentWrite,
        timing.parse_timing
            ->parse_blocked_on_script_load_from_document_write_duration
            .value());
  }
}

void UmaPageLoadMetricsObserver::OnComplete(
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  RecordNavigationTimingHistograms();
  RecordTimingHistograms(timing);
  RecordByteAndResourceHistograms(timing);
  RecordCpuUsageHistograms();
  RecordForegroundDurationHistograms(timing, base::TimeTicks());
  RecordV8MemoryHistograms();
}

page_load_metrics::PageLoadMetricsObserver::ObservePolicy
UmaPageLoadMetricsObserver::FlushMetricsOnAppEnterBackground(
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  // FlushMetricsOnAppEnterBackground is invoked on Android in cases where the
  // app is about to be backgrounded, as part of the Activity.onPause()
  // flow. After this method is invoked, Chrome may be killed without further
  // notification, so we record final metrics collected up to this point.
  if (GetDelegate().DidCommit()) {
    RecordNavigationTimingHistograms();
    RecordTimingHistograms(timing);
    RecordByteAndResourceHistograms(timing);
    RecordCpuUsageHistograms();
    RecordV8MemoryHistograms();
  }
  RecordForegroundDurationHistograms(timing, base::TimeTicks::Now());
  return STOP_OBSERVING;
}

void UmaPageLoadMetricsObserver::OnFailedProvisionalLoad(
    const page_load_metrics::FailedProvisionalLoadInfo& failed_load_info) {
  // Provide an empty PageLoadTiming, since we don't have any timing metrics
  // for failed provisional loads.
  RecordForegroundDurationHistograms(page_load_metrics::mojom::PageLoadTiming(),
                                     base::TimeTicks());
}

void UmaPageLoadMetricsObserver::OnLoadedResource(
    const page_load_metrics::ExtraRequestCompleteInfo&
        extra_request_complete_info) {
  const net::LoadTimingInfo& timing_info =
      *extra_request_complete_info.load_timing_info;
  if (timing_info.receive_headers_end.is_null())
    return;

  base::StringPiece destination = network::RequestDestinationToString(
      extra_request_complete_info.request_destination);
  if (destination.empty())
    destination = "empty";

  base::TimeDelta delta =
      timing_info.receive_headers_end - timing_info.request_start;
  if (extra_request_complete_info.was_cached) {
    base::UmaHistogramMediumTimes(
        base::StrCat(
            {internal::kHistogramCachedResourceLoadTimePrefix, destination}),
        delta);
  } else {
    base::UmaHistogramMediumTimes(
        base::StrCat({internal::kHistogramResourceLoadTimePrefix, destination}),
        delta);
  }

  // Rest of the method only operates on subresource loads.
  if (extra_request_complete_info.request_destination ==
      network::mojom::RequestDestination::kDocument) {
    return;
  }

  total_subresource_load_time_ += delta;

  // Rest of the method only logs metrics for the first subresource load.
  if (received_first_subresource_load_)
    return;

  received_first_subresource_load_ = true;
  PAGE_LOAD_HISTOGRAM(
      internal::kHistogramNavigationToFirstSubresourceLoadStart,
      timing_info.request_start - GetDelegate().GetNavigationStart());

  base::TimeTicks commit_sent_time =
      navigation_handle_timing_.navigation_commit_sent_time;
  if (!commit_sent_time.is_null()) {
    PAGE_LOAD_HISTOGRAM(
        internal::kHistogramCommitSentToFirstSubresourceLoadStart,
        timing_info.request_start - commit_sent_time);
  }
}

void UmaPageLoadMetricsObserver::OnUserInput(
    const blink::WebInputEvent& event,
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  base::TimeTicks now;

  if (first_paint_.is_null())
    return;

  // Track clicks after first paint for possible click burst.
  click_tracker_.OnUserInput(event);

  if (!received_non_scroll_input_after_first_paint_) {
    if (event.GetType() == blink::WebInputEvent::Type::kGestureTap ||
        event.GetType() == blink::WebInputEvent::Type::kMouseUp) {
      received_non_scroll_input_after_first_paint_ = true;
      if (now.is_null())
        now = base::TimeTicks::Now();
      PAGE_LOAD_HISTOGRAM(
          internal::kHistogramFirstNonScrollInputAfterFirstPaint,
          now - first_paint_);
    }
  }
  if (!received_scroll_input_after_first_paint_ &&
      event.GetType() == blink::WebInputEvent::Type::kGestureScrollBegin) {
    received_scroll_input_after_first_paint_ = true;
    if (now.is_null())
      now = base::TimeTicks::Now();
    PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstScrollInputAfterFirstPaint,
                        now - first_paint_);
  }
}

void UmaPageLoadMetricsObserver::OnResourceDataUseObserved(
    content::RenderFrameHost* rfh,
    const std::vector<page_load_metrics::mojom::ResourceDataUpdatePtr>&
        resources) {
  for (auto const& resource : resources) {
    if (resource->is_complete) {
      if (resource->cache_type ==
          page_load_metrics::mojom::CacheType::kNotCached) {
        network_bytes_ += resource->encoded_body_length;
      } else {
        cache_bytes_ += resource->encoded_body_length;
      }
    }
    network_bytes_including_headers_ += resource->delta_bytes;
  }
}

void UmaPageLoadMetricsObserver::RecordNavigationTimingHistograms() {
  const base::TimeTicks navigation_start_time =
      GetDelegate().GetNavigationStart();
  const content::NavigationHandleTiming& timing = navigation_handle_timing_;

  // Record metrics for navigation only when all relevant milestones are
  // recorded and in the expected order. It is allowed that they have the same
  // value for some cases (e.g., internal redirection for HSTS).
  if (navigation_start_time.is_null() ||
      timing.first_request_start_time.is_null() ||
      timing.first_response_start_time.is_null() ||
      timing.first_loader_callback_time.is_null() ||
      timing.final_request_start_time.is_null() ||
      timing.final_response_start_time.is_null() ||
      timing.final_loader_callback_time.is_null() ||
      timing.navigation_commit_sent_time.is_null()) {
    return;
  }
  // TODO(https://crbug.com/1076710): Change these early-returns to DCHECKs
  // after the issue 1076710 is fixed.
  if (navigation_start_time > timing.first_request_start_time ||
      timing.first_request_start_time > timing.first_response_start_time ||
      timing.first_response_start_time > timing.first_loader_callback_time ||
      timing.first_loader_callback_time > timing.navigation_commit_sent_time) {
    return;
  }
  if (navigation_start_time > timing.final_request_start_time ||
      timing.final_request_start_time > timing.final_response_start_time ||
      timing.final_response_start_time > timing.final_loader_callback_time ||
      timing.final_loader_callback_time > timing.navigation_commit_sent_time) {
    return;
  }
  DCHECK_LE(timing.first_request_start_time, timing.final_request_start_time);
  DCHECK_LE(timing.first_response_start_time, timing.final_response_start_time);
  DCHECK_LE(timing.first_loader_callback_time,
            timing.final_loader_callback_time);

  // Record the elapsed time from the navigation start milestone.
  PAGE_LOAD_HISTOGRAM(
      internal::kHistogramNavigationTimingNavigationStartToFirstRequestStart,
      timing.first_request_start_time - navigation_start_time);
  PAGE_LOAD_HISTOGRAM(
      internal::kHistogramNavigationTimingNavigationStartToFirstResponseStart,
      timing.first_response_start_time - navigation_start_time);
  PAGE_LOAD_HISTOGRAM(
      internal::kHistogramNavigationTimingNavigationStartToFirstLoaderCallback,
      timing.first_loader_callback_time - navigation_start_time);

  PAGE_LOAD_HISTOGRAM(
      internal::kHistogramNavigationTimingNavigationStartToFinalRequestStart,
      timing.final_request_start_time - navigation_start_time);
  PAGE_LOAD_HISTOGRAM(
      internal::kHistogramNavigationTimingNavigationStartToFinalResponseStart,
      timing.final_response_start_time - navigation_start_time);
  PAGE_LOAD_HISTOGRAM(
      internal::kHistogramNavigationTimingNavigationStartToFinalLoaderCallback,
      timing.final_loader_callback_time - navigation_start_time);

  PAGE_LOAD_HISTOGRAM(
      internal::kHistogramNavigationTimingNavigationStartToNavigationCommitSent,
      timing.navigation_commit_sent_time - navigation_start_time);

  // Record the intervals between milestones.
  PAGE_LOAD_HISTOGRAM(
      internal::kHistogramNavigationTimingFirstRequestStartToFirstResponseStart,
      timing.first_response_start_time - timing.first_request_start_time);
  PAGE_LOAD_HISTOGRAM(
      internal::
          kHistogramNavigationTimingFirstResponseStartToFirstLoaderCallback,
      timing.first_loader_callback_time - timing.first_response_start_time);

  PAGE_LOAD_HISTOGRAM(
      internal::kHistogramNavigationTimingFinalRequestStartToFinalResponseStart,
      timing.final_response_start_time - timing.final_request_start_time);
  PAGE_LOAD_HISTOGRAM(
      internal::
          kHistogramNavigationTimingFinalResponseStartToFinalLoaderCallback,
      timing.final_loader_callback_time - timing.final_response_start_time);

  PAGE_LOAD_HISTOGRAM(
      internal::
          kHistogramNavigationTimingFinalLoaderCallbackToNavigationCommitSent,
      timing.navigation_commit_sent_time - timing.final_loader_callback_time);
}

// This method records values for metrics that were not recorded during any
// other event, or records failure status for metrics that have not been
// collected yet. This is meant to be called at the end of a page lifetime, for
// example, when the user is navigating away from the page.
void UmaPageLoadMetricsObserver::RecordTimingHistograms(
    const page_load_metrics::mojom::PageLoadTiming& main_frame_timing) {
  // Log time to first foreground / time to first background. Log counts that we
  // started a relevant page load in the foreground / background.
  if (!GetDelegate().StartedInForeground() &&
      GetDelegate().GetTimeToFirstForeground()) {
    PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstForeground,
                        GetDelegate().GetTimeToFirstForeground().value());
  }

  const page_load_metrics::ContentfulPaintTimingInfo&
      main_frame_largest_contentful_paint =
          GetDelegate()
              .GetLargestContentfulPaintHandler()
              .MainFrameLargestContentfulPaint();
  if (main_frame_largest_contentful_paint.ContainsValidTime() &&
      WasStartedInForegroundOptionalEventInForeground(
          main_frame_largest_contentful_paint.Time(), GetDelegate())) {
    PAGE_LOAD_HISTOGRAM(internal::kHistogramLargestContentfulPaintMainFrame,
                        main_frame_largest_contentful_paint.Time().value());
    UMA_HISTOGRAM_ENUMERATION(
        internal::kHistogramLargestContentfulPaintMainFrameContentType,
        main_frame_largest_contentful_paint.TextOrImage());
  }

  const page_load_metrics::ContentfulPaintTimingInfo&
      cross_site_sub_frame_contentful_paint =
          GetDelegate()
              .GetLargestContentfulPaintHandler()
              .CrossSiteSubframesLargestContentfulPaint();
  if (cross_site_sub_frame_contentful_paint.ContainsValidTime() &&
      WasStartedInForegroundOptionalEventInForeground(
          cross_site_sub_frame_contentful_paint.Time(), GetDelegate())) {
    PAGE_LOAD_HISTOGRAM(
        internal::kHistogramLargestContentfulPaintCrossSiteSubFrame,
        cross_site_sub_frame_contentful_paint.Time().value());
  }

  const page_load_metrics::ContentfulPaintTimingInfo&
      all_frames_largest_contentful_paint =
          GetDelegate()
              .GetLargestContentfulPaintHandler()
              .MergeMainFrameAndSubframes();
  if (all_frames_largest_contentful_paint.ContainsValidTime() &&
      WasStartedInForegroundOptionalEventInForeground(
          all_frames_largest_contentful_paint.Time(), GetDelegate())) {
    PAGE_LOAD_HISTOGRAM(internal::kHistogramLargestContentfulPaint,
                        all_frames_largest_contentful_paint.Time().value());
    // The pseudo metric of |kHistogramLargestContentfulPaint|. Only used to
    // assess field trial data quality.
    PAGE_LOAD_HISTOGRAM(
        "UMA.Pseudo.PageLoad.PaintTiming.NavigationToLargestContentfulPaint2",
        metrics::GetPseudoMetricsSample(
            all_frames_largest_contentful_paint.Time().value()));
    UMA_HISTOGRAM_ENUMERATION(
        internal::kHistogramLargestContentfulPaintContentType,
        all_frames_largest_contentful_paint.TextOrImage());
    TRACE_EVENT_MARK_WITH_TIMESTAMP1(
        "loading", "NavStartToLargestContentfulPaint::AllFrames::UMA",
        GetDelegate().GetNavigationStart() +
            all_frames_largest_contentful_paint.Time().value(),
        "data", all_frames_largest_contentful_paint.DataAsTraceValue());
  }

  if (main_frame_timing.paint_timing->first_paint &&
      !main_frame_timing.paint_timing->first_meaningful_paint) {
    RecordFirstMeaningfulPaintStatus(
        main_frame_timing.paint_timing->first_contentful_paint
            ? internal::FIRST_MEANINGFUL_PAINT_DID_NOT_REACH_NETWORK_STABLE
            : internal::
                  FIRST_MEANINGFUL_PAINT_DID_NOT_REACH_FIRST_CONTENTFUL_PAINT);
  }

  if (main_frame_timing.interactive_timing->longest_input_timestamp) {
    DCHECK(main_frame_timing.interactive_timing->longest_input_delay);
    UMA_HISTOGRAM_CUSTOM_TIMES(
        internal::kHistogramLongestInputDelay,
        main_frame_timing.interactive_timing->longest_input_delay.value(),
        base::Milliseconds(1), base::Seconds(60), 50);
    PAGE_LOAD_HISTOGRAM(
        internal::kHistogramLongestInputTimestamp,
        main_frame_timing.interactive_timing->longest_input_timestamp.value());
  }

  RecordNormalizedResponsivenessMetrics();
}

void UmaPageLoadMetricsObserver::RecordNormalizedResponsivenessMetrics() {
  const page_load_metrics::NormalizedResponsivenessMetrics&
      normalized_responsiveness_metrics =
          GetDelegate().GetNormalizedResponsivenessMetrics();
  if (!normalized_responsiveness_metrics.num_user_interactions)
    return;
  auto& max_event_durations =
      normalized_responsiveness_metrics.normalized_max_event_durations;

  UmaHistogramCustomTimes(
      internal::kHistogramWorstUserInteractionLatencyMaxEventDuration,
      max_event_durations.worst_latency, base::Milliseconds(1),
      base::Seconds(60), 50);
  UmaHistogramCustomTimes(
      internal::kHistogramSumOfUserInteractionLatencyOverBudgetMaxEventDuration,
      max_event_durations.sum_of_latency_over_budget, base::Milliseconds(1),
      base::Seconds(60), 50);
  UmaHistogramCustomTimes(
      internal::
          kHistogramAverageUserInteractionLatencyOverBudgetMaxEventDuration,
      max_event_durations.sum_of_latency_over_budget /
          normalized_responsiveness_metrics.num_user_interactions,
      base::Milliseconds(1), base::Seconds(60), 50);
  UmaHistogramCustomTimes(
      internal::
          kHistogramSlowUserInteractionLatencyOverBudgetHighPercentile2MaxEventDuration,
      page_load_metrics::ResponsivenessMetricsNormalization::
          ApproximateHighPercentile(
              normalized_responsiveness_metrics.num_user_interactions,
              max_event_durations.worst_ten_latencies_over_budget),
      base::Milliseconds(1), base::Seconds(60), 50);
  UmaHistogramCustomTimes(
      internal::kHistogramUserInteractionLatencyHighPercentile2MaxEventDuration,
      page_load_metrics::ResponsivenessMetricsNormalization::
          ApproximateHighPercentile(
              normalized_responsiveness_metrics.num_user_interactions,
              max_event_durations.worst_ten_latencies),
      base::Milliseconds(1), base::Seconds(60), 50);
  base::UmaHistogramCounts1000(
      internal::kHistogramNumInteractions,
      normalized_responsiveness_metrics.num_user_interactions);
}

void UmaPageLoadMetricsObserver::RecordForegroundDurationHistograms(
    const page_load_metrics::mojom::PageLoadTiming& timing,
    base::TimeTicks app_background_time) {
  absl::optional<base::TimeDelta> foreground_duration =
      page_load_metrics::GetInitialForegroundDuration(GetDelegate(),
                                                      app_background_time);
  if (!foreground_duration)
    return;

  if (GetDelegate().DidCommit()) {
    PAGE_LOAD_LONG_HISTOGRAM(internal::kHistogramPageTimingForegroundDuration,
                             foreground_duration.value());
    if (timing.paint_timing->first_paint &&
        timing.paint_timing->first_paint < foreground_duration) {
      PAGE_LOAD_LONG_HISTOGRAM(
          internal::kHistogramPageTimingForegroundDurationAfterPaint,
          foreground_duration.value() -
              timing.paint_timing->first_paint.value());
      PAGE_LOAD_LONG_HISTOGRAM(
          internal::kHistogramPageTimingForegroundDurationWithPaint,
          foreground_duration.value());
    } else {
      PAGE_LOAD_LONG_HISTOGRAM(
          internal::kHistogramPageTimingForegroundDurationWithoutPaint,
          foreground_duration.value());
    }
  } else {
    PAGE_LOAD_LONG_HISTOGRAM(
        internal::kHistogramPageTimingForegroundDurationNoCommit,
        foreground_duration.value());
  }

  if (GetDelegate().GetPageEndReason() == page_load_metrics::END_FORWARD_BACK &&
      GetDelegate().GetUserInitiatedInfo().user_gesture &&
      !GetDelegate().GetUserInitiatedInfo().browser_initiated &&
      GetDelegate().GetTimeToPageEnd() <= foreground_duration) {
    PAGE_LOAD_HISTOGRAM(internal::kHistogramUserGestureNavigationToForwardBack,
                        GetDelegate().GetTimeToPageEnd().value());
  }
}

void UmaPageLoadMetricsObserver::OnCpuTimingUpdate(
    content::RenderFrameHost* subframe_rfh,
    const page_load_metrics::mojom::CpuTiming& timing) {
  total_cpu_usage_ += timing.task_time;

  if (GetDelegate().GetVisibilityTracker().currently_in_foreground()) {
    foreground_cpu_usage_ += timing.task_time;
  }
}

void UmaPageLoadMetricsObserver::RecordByteAndResourceHistograms(
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  DCHECK_GE(network_bytes_, 0);
  DCHECK_GE(cache_bytes_, 0);
  int64_t total_bytes = network_bytes_ + cache_bytes_;

  PAGE_BYTES_HISTOGRAM(internal::kHistogramPageLoadNetworkBytes,
                       network_bytes_);
  PAGE_BYTES_HISTOGRAM(internal::kHistogramPageLoadCacheBytes, cache_bytes_);
  PAGE_BYTES_HISTOGRAM(internal::kHistogramPageLoadTotalBytes, total_bytes);
  PAGE_BYTES_HISTOGRAM(internal::kHistogramPageLoadNetworkBytesIncludingHeaders,
                       network_bytes_including_headers_);

  size_t unfinished_bytes = 0;
  for (auto const& kv :
       GetDelegate().GetResourceTracker().unfinished_resources())
    unfinished_bytes += kv.second->received_data_length;
  PAGE_BYTES_HISTOGRAM(internal::kHistogramPageLoadUnfinishedBytes,
                       unfinished_bytes);

  switch (GetPageLoadType(transition_)) {
    case LOAD_TYPE_RELOAD:
      PAGE_BYTES_HISTOGRAM(internal::kHistogramLoadTypeNetworkBytesReload,
                           network_bytes_);
      PAGE_BYTES_HISTOGRAM(internal::kHistogramLoadTypeCacheBytesReload,
                           cache_bytes_);
      PAGE_BYTES_HISTOGRAM(internal::kHistogramLoadTypeTotalBytesReload,
                           total_bytes);
      break;
    case LOAD_TYPE_FORWARD_BACK:
      PAGE_BYTES_HISTOGRAM(internal::kHistogramLoadTypeNetworkBytesForwardBack,
                           network_bytes_);
      PAGE_BYTES_HISTOGRAM(internal::kHistogramLoadTypeCacheBytesForwardBack,
                           cache_bytes_);
      PAGE_BYTES_HISTOGRAM(internal::kHistogramLoadTypeTotalBytesForwardBack,
                           total_bytes);
      break;
    case LOAD_TYPE_NEW_NAVIGATION:
      PAGE_BYTES_HISTOGRAM(
          internal::kHistogramLoadTypeNetworkBytesNewNavigation,
          network_bytes_);
      PAGE_BYTES_HISTOGRAM(internal::kHistogramLoadTypeCacheBytesNewNavigation,
                           cache_bytes_);
      PAGE_BYTES_HISTOGRAM(internal::kHistogramLoadTypeTotalBytesNewNavigation,
                           total_bytes);
      break;
    case LOAD_TYPE_NONE:
      NOTREACHED();
      break;
  }
  click_tracker_.RecordClickBurst(GetDelegate().GetPageUkmSourceId());
}

void UmaPageLoadMetricsObserver::RecordCpuUsageHistograms() {
  PAGE_LOAD_HISTOGRAM(internal::kHistogramPageLoadCpuTotalUsage,
                      total_cpu_usage_);
  PAGE_LOAD_HISTOGRAM(internal::kHistogramPageLoadCpuTotalUsageForegrounded,
                      foreground_cpu_usage_);
}

page_load_metrics::PageLoadMetricsObserver::ObservePolicy
UmaPageLoadMetricsObserver::OnEnterBackForwardCache(
    const page_load_metrics::mojom::PageLoadTiming& timing) {
  UMA_HISTOGRAM_ENUMERATION(
      internal::kHistogramBackForwardCacheEvent,
      internal::PageLoadBackForwardCacheEvent::kEnterBackForwardCache);
  return PageLoadMetricsObserver::OnEnterBackForwardCache(timing);
}

void UmaPageLoadMetricsObserver::OnRestoreFromBackForwardCache(
    const page_load_metrics::mojom::PageLoadTiming& timing,
    content::NavigationHandle* navigation_handle) {
  // This never reaches yet because OnEnterBackForwardCache returns
  // STOP_OBSERVING.
  // TODO(hajimehoshi): After changing OnEnterBackForwardCache to continue
  // observation, remove the above comment.
  UMA_HISTOGRAM_ENUMERATION(
      internal::kHistogramBackForwardCacheEvent,
      internal::PageLoadBackForwardCacheEvent::kRestoreFromBackForwardCache);
}

void UmaPageLoadMetricsObserver::OnV8MemoryChanged(
    const std::vector<page_load_metrics::MemoryUpdate>& memory_updates) {
  DCHECK(base::FeatureList::IsEnabled(features::kV8PerFrameMemoryMonitoring));

  for (const auto& update : memory_updates) {
    memory_update_received_ = true;

    content::RenderFrameHost* render_frame_host =
        content::RenderFrameHost::FromID(update.routing_id);

    if (!render_frame_host)
      continue;

    if (!render_frame_host->GetParent()) {
      // |render_frame_host| is the main frame.
      main_frame_memory_usage_.UpdateUsage(update.delta_bytes);
    } else {
      aggregate_subframe_memory_usage_.UpdateUsage(update.delta_bytes);
    }

    aggregate_total_memory_usage_.UpdateUsage(update.delta_bytes);
  }
}

void UmaPageLoadMetricsObserver::RecordV8MemoryHistograms() {
  if (base::FeatureList::IsEnabled(features::kV8PerFrameMemoryMonitoring)) {
    PAGE_BYTES_HISTOGRAM(internal::kHistogramMemoryMainframe,
                         main_frame_memory_usage_.max_bytes_used());
    PAGE_BYTES_HISTOGRAM(internal::kHistogramMemorySubframeAggregate,
                         aggregate_subframe_memory_usage_.max_bytes_used());
    PAGE_BYTES_HISTOGRAM(internal::kHistogramMemoryTotal,
                         aggregate_total_memory_usage_.max_bytes_used());
    UMA_HISTOGRAM_BOOLEAN(internal::kHistogramMemoryUpdateReceived,
                          memory_update_received_);
  }
}

void UmaPageLoadMetricsObserver::MemoryUsage::UpdateUsage(int64_t delta_bytes) {
  current_bytes_used_ += delta_bytes;
  max_bytes_used_ = std::max(max_bytes_used_, current_bytes_used_);
}


text: require 'dmm/core'


text:
import { Transform, TransformOptions } from "stream";
import { WriteStream } from 'fs';

export interface Format {
  audioFormat: number;
  endianness: 'LE' | 'BE';
  channels: number;
  sampleRate: number;
  byteRate: number;
  blockAlign: number;
  bitDepth: number;
  signed: boolean;
}

export interface UnknownChunk {
  id: string;
  data: any;
}

export class Reader extends Transform {
    constructor(opts?: TransformOptions);

    addListener(event: "format", listener: (format: Format) => void): this;
    addListener(event: "chunk", listener: (unknownChunk: UnknownChunk) => void): this;
    addListener(event: string, listener: (...args: any[]) => void): this;

    on(event: "format", listener: (format: Format) => void): this;
    on(event: "chunk", listener: (unknownChunk: UnknownChunk) => void): this;
    on(event: string, listener: (...args: any[]) => void): this;
}

export interface WriterOptions extends TransformOptions {
  format?: number | undefined;
  channels?: number | undefined;
  sampleRate?: number | undefined;
  bitDepth?: number | undefined;
}

export class Writer extends Transform {
  endianness: 'LE';
  format: number;
  channels: number;
  sampleRate: number;
  bitDepth: number;
  bytesProcessed: number;

  constructor(opts?: WriterOptions);

  addListener(event: "header", listener: (header: Buffer) => void): this;
  addListener(event: string, listener: (...args: any[]) => void): this;

  on(event: "header", listener: (header: Buffer) => void): this;
  on(event: string, listener: (...args: any[]) => void): this;
}

export class FileWriter extends Writer {
  path: string;
  file: WriteStream;

  constructor(path: string, opts?: WriterOptions);

  addListener(event: "done", listener: () => void): this;
  addListener(event: string, listener: (...args: any[]) => void): this;

  on(event: "done", listener: () => void): this;
  on(event: string, listener: (...args: any[]) => void): this;
}


text:
'use strict';

angular.module('core').controller('HomeController', ['$scope', 'Authentication','$location',
	function($scope, Authentication,$location) {
		// This provides Authentication context.
		$scope.authentication = Authentication;

		$scope.createEvent = function(eventName){
			$location.url('/events/create?name='+eventName);
		}
	}

]);


text:
const copyFiles = require('./copyFiles');
const errors = require('../shared/errors');
const Promise = require('bluebird');

function copyExistingFiles(dataDir, versionFolderName, filesToCopy, destinationFolderName) {
	if (!versionFolderName)
		return Promise.reject(errors.create(errors.NO_PREVIOUS_VERSION));

	const srcFolderPath = dataDir + versionFolderName + '/';
	return copyFiles(srcFolderPath, filesToCopy, dataDir, destinationFolderName);
}

module.exports = copyExistingFiles;


text:
package org.radargun.stats.representation;

import java.util.concurrent.TimeUnit;

import org.radargun.config.DefinitionElement;
import org.radargun.stats.OperationStats;
import org.radargun.utils.Utils;

/**
 * Number of operations per second.
 *
 * @author Radim Vansa <rvansa@redhat.com>
 */
public class OperationThroughput {
   /**
    * Inverse to the response time, multiplied by number of threads.
    */
   public final double theoretical;
   /**
    * Actual throughput of the executed operations. May be imprecise if the merged periods are not identical.
    */
   public final double actual;

   public OperationThroughput(double theoretical, double actual) {
      this.theoretical = theoretical;
      this.actual = actual;
   }

   public static OperationThroughput compute(long requests, double responseTimeMean, Object[] args) {
      int threads = getThreads(args);
      long duration = getDuration(args);
      if (duration == 0) return null;
      return new OperationThroughput(TimeUnit.SECONDS.toNanos(1) * threads / responseTimeMean,
            TimeUnit.SECONDS.toNanos(1) * (double) requests / duration);
   }

   public static int getThreads(Object[] args) {
      int threads = Utils.getArg(args, 0, Integer.class);
      if (threads < 0) throw new IllegalArgumentException(String.valueOf(threads));
      return threads;
   }

   public static long getDuration(Object[] args) {
      long duration = Utils.getArg(args, 1, Long.class);
      if (duration < 0) throw new IllegalArgumentException(String.valueOf(duration));
      return duration;
   }

   @DefinitionElement(name = "throughput", doc = "Retrieve throughput.")
   public static class ActualThroughput extends RepresentationType {
      @Override
      public double getValue(OperationStats stats, int threads, long duration) {
         OperationThroughput throughput = stats.getRepresentation(OperationThroughput.class, threads, duration);
         if (throughput == null) throw new IllegalArgumentException("Cannot retrieve throughput from " + stats);
         return throughput.actual;
      }
   }
}


text:
module Squeezable

  def squeeze
    result = []
    previous = nil
    for i in (0...self.length)
      a = self[i]
      result << a unless previous == a
      previous = a
    end
    result
  end

end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <link rel="stylesheet" type="text/css" href="./style/formate.css"/>
  <meta name="author" content="Ingo Berg"/>
  <meta name="keywords" content="math parser, parser, expression evaluator, C++, Mathematical, Expression"/>
  <meta name="description" content="a fast and portable math parser library written in C++"/>

  <title>muParser - a fast math parser library</title>

                <object>

                </object>

                    class documentation

                      math parser download

Start page

                About the parser

                News

                Projects using this lib

                Licence

Features

              Features

              Overview

              Built in functions

              Built in binary operators

Build instructions

              Building on Win32

              Building on BSD/Linux

              Misc build instructions

              Including the files

              Where to ask for help

Math parser interface

              Parser (de)initialization

              Evaluating an expression

              Setting the expression

              Defining identifier charsets

              Defining parser variables

              Explicit variable definition

              Implicit variable definition

              Defining constants

              Defining functions

              Defining operators

              Unary operators

              Binary operators

              Querying variables

              Querying constants

              Value recognition callbacks

              Removing variables/constants

              Error handling

              Example code

              Current version

              Release notes

              Benchmarks

muParser - a fast math parser library

Many applications require the parsing of mathematical expressions.
The main objective of this project is to provide a fast and easy way of
doing this. muParser is an extensible high performance math parser
library. It is based on transforming an expression into a bytecode and
precalculating constant parts of it.

The math parser library is written in pure C++ and should compile on every
standard compliant compiler. I provide you with static libraries and a DLL
version ready for implementation into your projects. The code has been tested
using MS VC++ V7.1 and GCC V3.3.1. It reportedly works on BCB too.

I provide you with three demo projects in order to help you understand its
usage.

But before I go on, I'd like to thank SourceForge for hosting this project. This
pages would not exist without the webspace provided by them and of course I'd like
to thank CodeProject for hosting the original math parser article.

News

    New website

    2006-04-16 14:07 - muParser - A fast math parser library

  The website of muParser has been (slightly) updated and since now it will be available also as docs in the   download page.

  Read More »

  Version 1.25 released

    2006-02-06 03:00 - muParser - A fast math parser library

  The version 1.25 of muParser has been released. Unix users will find this new version much more user-friendly   as it includes a standard configure script and provides a pkg-config template files which allows to easily build
  applications which depend from muParser.

  Read More »

  New Version available

    2005-09-30 13:56 - muParser - A fast math parser library

  The parser archive has been updated to Version 1.22 in order to fix compiler issues with gcc 4.0.

  Read More »

  Class documentation online

    2005-05-07 04:53 - muParser - A fast math parser library

  I have added the class documentation to the homepage. It can be accessed at:

  Read More »

        Homepage and archives added

      2005-04-23 08:50 - muParser - A fast math parser library

    I made two additions to the site:

    I created a new homepage for the project:

    Read More »

    Site news archive »

              © 2005-2006 Ingo Berg

                ^ TOP


text:
@echo off

echo ***********************
echo *                     *
echo * TXT_JOIN.BAT        *
echo * CODED BY 0x776b7364 *
echo *                     *
echo ***********************
echo,
echo TXT_JOIN should be used in conjunction with TXT_SPLIT
echo TXT_JOIN file should be placed in the same directory as target folder
echo.

set /p folder=Enter target folder:
if not exist %folder% (
	echo Error, folder does not exist.
	pause
	goto eof)
set /p file=Enter target output file:
if exist %file% (
	echo Error, file already exists.
	pause
	goto eof)

dir /b %folder% >> dir.txt

FOR /F "tokens=*" %%a in (dir.txt) DO call :1 %%a

goto :eof

:1

set string=%*
set nstring=%string:~4%
echo %nstring% >> output.txt


text:
.class public final enum Landroid/graphics/Paint$Cap;
.super Ljava/lang/Enum;
.source "Paint.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/graphics/Paint;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x4019
    name = "Cap"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Enum",
        "<",
        "Landroid/graphics/Paint$Cap;",
        ">;"
    }
.end annotation

# static fields
.field private static final synthetic $VALUES:[Landroid/graphics/Paint$Cap;

.field public static final enum BUTT:Landroid/graphics/Paint$Cap;

.field public static final enum ROUND:Landroid/graphics/Paint$Cap;

.field public static final enum SQUARE:Landroid/graphics/Paint$Cap;

# instance fields
.field final nativeInt:I

# direct methods
.method static constructor <clinit>()V
    .locals 5

    .prologue
    const/4 v4, 0x2

    const/4 v3, 0x1

    const/4 v2, 0x0

    .line 268
    new-instance v0, Landroid/graphics/Paint$Cap;

    const-string v1, "BUTT"

    invoke-direct {v0, v1, v2, v2}, Landroid/graphics/Paint$Cap;-><init>(Ljava/lang/String;II)V

    sput-object v0, Landroid/graphics/Paint$Cap;->BUTT:Landroid/graphics/Paint$Cap;

    .line 273
    new-instance v0, Landroid/graphics/Paint$Cap;

    const-string v1, "ROUND"

    invoke-direct {v0, v1, v3, v3}, Landroid/graphics/Paint$Cap;-><init>(Ljava/lang/String;II)V

    sput-object v0, Landroid/graphics/Paint$Cap;->ROUND:Landroid/graphics/Paint$Cap;

    .line 278
    new-instance v0, Landroid/graphics/Paint$Cap;

    const-string v1, "SQUARE"

    invoke-direct {v0, v1, v4, v4}, Landroid/graphics/Paint$Cap;-><init>(Ljava/lang/String;II)V

    sput-object v0, Landroid/graphics/Paint$Cap;->SQUARE:Landroid/graphics/Paint$Cap;

    .line 264
    const/4 v0, 0x3

    new-array v0, v0, [Landroid/graphics/Paint$Cap;

    sget-object v1, Landroid/graphics/Paint$Cap;->BUTT:Landroid/graphics/Paint$Cap;

    aput-object v1, v0, v2

    sget-object v1, Landroid/graphics/Paint$Cap;->ROUND:Landroid/graphics/Paint$Cap;

    aput-object v1, v0, v3

    sget-object v1, Landroid/graphics/Paint$Cap;->SQUARE:Landroid/graphics/Paint$Cap;

    aput-object v1, v0, v4

    sput-object v0, Landroid/graphics/Paint$Cap;->$VALUES:[Landroid/graphics/Paint$Cap;

    return-void
.end method

.method private constructor <init>(Ljava/lang/String;II)V
    .locals 0
    .parameter
    .parameter
    .parameter "nativeInt"
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(I)V"
        }
    .end annotation

    .prologue
    .line 280
    invoke-direct {p0, p1, p2}, Ljava/lang/Enum;-><init>(Ljava/lang/String;I)V

    .line 281
    iput p3, p0, Landroid/graphics/Paint$Cap;->nativeInt:I

    .line 282
    return-void
.end method

.method public static valueOf(Ljava/lang/String;)Landroid/graphics/Paint$Cap;
    .locals 1
    .parameter "name"

    .prologue
    .line 264
    const-class v0, Landroid/graphics/Paint$Cap;

    invoke-static {v0, p0}, Ljava/lang/Enum;->valueOf(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;

    move-result-object v0

    check-cast v0, Landroid/graphics/Paint$Cap;

    return-object v0
.end method

.method public static values()[Landroid/graphics/Paint$Cap;
    .locals 1

    .prologue
    .line 264
    sget-object v0, Landroid/graphics/Paint$Cap;->$VALUES:[Landroid/graphics/Paint$Cap;

    invoke-virtual {v0}, [Landroid/graphics/Paint$Cap;->clone()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, [Landroid/graphics/Paint$Cap;

    return-object v0
.end method


text: java -cp log4j-1.2.17.jar org.apache.log4j.net.SocketServer 12345 ./server.properties ./


text:
<?php
/**
 * This class is part of our implementation to log errors in console commands:
 * http://symfony.com/doc/current/cookbook/console/logging.html
 *
 */
namespace Sideclick\CoreBundle\EventListener;

use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Psr\Log\LoggerInterface;

class ErrorLoggerListener
{
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function onConsoleTerminate(ConsoleTerminateEvent $event)
    {
        $statusCode = $event->getExitCode();
        $command = $event->getCommand();

        if ($statusCode === 0) {
            return;
        }

        if ($statusCode > 255) {
            $statusCode = 255;
            $event->setExitCode($statusCode);
        }

        $this->logger->warning(sprintf(
            'Command `%s` exited with status code %d',
            $command->getName(),
            $statusCode
        ));
    }
}


text:
class CreateReports < ActiveRecord::Migration
  def change
    create_table :reports do |t|
      t.text :description
      t.belongs_to :reportable, index: true
      t.belongs_to :user, index: true
      t.timestamps null: false
    end
  end
end


text:
<?php
/**
 * Test the Logger class
 * @author Wolfram Huesken <wolfram.huesken@zalora.com>
 */

namespace Zalora\Punyan;

use Zalora\Punyan\Formatter\Bunyan;

/**
 * @package Zalora\Punyan
 */
class ZLogTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Fetching a not set instance will result in a type error, because we're not (yet) able to return null
     * @expectedException \TypeError
     */
    public function testGetEmptyLogger()
    {
        ZLog::getInstance();
    }

    /**
     * After resetting the instance the TypeError should be back
     * @expectedException \TypeError
     */
    public function testTypeErrorAfterReset() {
        $logger = $this->getMemoryLogger();

        ZLog::setInstance($logger);
        $this->assertEquals($logger, ZLog::getInstance());

        ZLog::resetInstance();
        ZLog::getInstance();
    }

    /**
     * I won't explain that...
     */
    public function testGettersAndSetters() {
        $logger = $this->getMemoryLogger();

        ZLog::setInstance($logger);
        $this->assertEquals($logger, ZLog::getInstance());
    }

    /**
     * Test the trace method
     */
    public function testTrace()
    {
        $logger = $this->getMemoryLogger();
        ZLog::setInstance($logger);

        $time = time();
        $stream = $this->getCurrentStreamFromLogger($logger);
        $formatter = new Bunyan();

        $logEvent = LogEvent::create(ILogger::LEVEL_TRACE, 'PHPUnit', array('time' => $time), 'PHPUnit');
        $logEvent['origin'] = Logger::getLogOrigin(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));

        ZLog::trace('PHPUnit', array('time' => $time));

        $streamContent = stream_get_contents($stream, -1, 0);

        $this->assertEquals(
            json_decode($formatter->format($logEvent), true),
            json_decode($streamContent, true)
        );
    }

    /**
     * Test the trace method with empty logger instance
     * @expectedException \RuntimeException
     */
    public function testEmptyTrace()
    {
        ZLog::resetInstance();
        ZLog::trace('PHPUnit');
    }

    /**
     * Test the debug method
     */
    public function testDebug()
    {
        $logger = $this->getMemoryLogger();
        ZLog::setInstance($logger);

        $time = time();
        $stream = $this->getCurrentStreamFromLogger($logger);
        $formatter = new Bunyan();

        $logEvent = LogEvent::create(ILogger::LEVEL_DEBUG, 'PHPUnit', array('time' => $time), 'PHPUnit');
        $logEvent['origin'] = Logger::getLogOrigin(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));

        ZLog::debug('PHPUnit', array('time' => $time));

        $streamContent = stream_get_contents($stream, -1, 0);

        $this->assertEquals(
            json_decode($formatter->format($logEvent), true),
            json_decode($streamContent, true)
        );
    }

    /**
     * Test the debug method with empty logger instance
     * @expectedException \RuntimeException
     */
    public function testEmptyDebug()
    {
        ZLog::resetInstance();
        ZLog::debug('PHPUnit');
    }

    /**
     * Test the info method
     */
    public function testInfo()
    {
        $logger = $this->getMemoryLogger();
        ZLog::setInstance($logger);

        $time = time();
        $stream = $this->getCurrentStreamFromLogger($logger);
        $formatter = new Bunyan();

        $logEvent = LogEvent::create(ILogger::LEVEL_INFO, 'PHPUnit', array('time' => $time), 'PHPUnit');
        $logEvent['origin'] = Logger::getLogOrigin(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));

        ZLog::info('PHPUnit', array('time' => $time));

        $streamContent = stream_get_contents($stream, -1, 0);

        $this->assertEquals(
            json_decode($formatter->format($logEvent), true),
            json_decode($streamContent, true)
        );
    }

    /**
     * Test the info method with empty logger instance
     * @expectedException \RuntimeException
     */
    public function testEmptyInfo()
    {
        ZLog::resetInstance();
        ZLog::info('PHPUnit');
    }

    /**
     * Test the warn method
     */
    public function testWarn()
    {
        $logger = $this->getMemoryLogger();
        ZLog::setInstance($logger);

        $time = time();
        $stream = $this->getCurrentStreamFromLogger($logger);
        $formatter = new Bunyan();

        $logEvent = LogEvent::create(ILogger::LEVEL_WARN, 'PHPUnit', array('time' => $time), 'PHPUnit');
        $logEvent['origin'] = Logger::getLogOrigin(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));

        ZLog::warn('PHPUnit', array('time' => $time));

        $streamContent = stream_get_contents($stream, -1, 0);

        $this->assertEquals(
            json_decode($formatter->format($logEvent), true),
            json_decode($streamContent, true)
        );
    }

    /**
     * Test the warn method with empty logger instance
     * @expectedException \RuntimeException
     */
    public function testEmptyWarn()
    {
        ZLog::resetInstance();
        ZLog::warn('PHPUnit');
    }

    /**
     * Test the error method
     */
    public function testError()
    {
        $logger = $this->getMemoryLogger();
        ZLog::setInstance($logger);

        $time = time();
        $stream = $this->getCurrentStreamFromLogger($logger);
        $formatter = new Bunyan();

        $logEvent = LogEvent::create(ILogger::LEVEL_ERROR, 'PHPUnit', array('time' => $time), 'PHPUnit');
        $logEvent['origin'] = Logger::getLogOrigin(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));

        ZLog::error('PHPUnit', array('time' => $time));

        $streamContent = stream_get_contents($stream, -1, 0);

        $this->assertEquals(
            json_decode($formatter->format($logEvent), true),
            json_decode($streamContent, true)
        );
    }

    /**
     * Test the error method with empty logger instance
     * @expectedException \RuntimeException
     */
    public function testEmptyError()
    {
        ZLog::resetInstance();
        ZLog::error('PHPUnit');
    }

    /**
     * Test the fatal method
     */
    public function testFatal()
    {
        $logger = $this->getMemoryLogger();
        ZLog::setInstance($logger);

        $time = time();
        $stream = $this->getCurrentStreamFromLogger($logger);
        $formatter = new Bunyan();

        $logEvent = LogEvent::create(ILogger::LEVEL_FATAL, 'PHPUnit', array('time' => $time), 'PHPUnit');
        $logEvent['origin'] = Logger::getLogOrigin(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));

        ZLog::fatal('PHPUnit', array('time' => $time));

        $streamContent = stream_get_contents($stream, -1, 0);

        $this->assertEquals(
            json_decode($formatter->format($logEvent), true),
            json_decode($streamContent, true)
        );
    }

    /**
     * Test the fatal method with empty logger instance
     * @expectedException \RuntimeException
     */
    public function testEmptyFatal()
    {
        ZLog::resetInstance();
        ZLog::fatal('PHPUnit');
    }

    /**
     * @return Logger
     */
    private function getMemoryLogger()
    {
        return new Logger('PHPUnit', array(
            'filters' => array(),
            'writers' => array(
                array('Stream' => array(
                    'url' => 'php://memory',
                    'filters' => array()
                ))
            )
        ));
    }

    /**
     * PHP 7 needs to rewind the SPLObjectStorage before you can extract items with current...
     * @param Logger $logger
     * @return resource
     */
    private function getCurrentStreamFromLogger(Logger $logger)
    {
        $writers = $logger->getWriters();
        $writers->rewind();

        return $writers->current()->getStream();
    }
}


text:
public class MainMenuController : MonoSingleton<MainMenuController> {

	void Start(){
		CheckIsSingleInScene ();
	}

	public void ResumeGame(){
		GameController.Instance.GameIsRunning = true;
	}

	public void Exit(){
		#if UNITY_EDITOR
		UnityEditor.EditorApplication.isPlaying = false;
//		#else
//		Application.Quit();
		#endif
	}
}