text:
package edu.tamu.tcat.account;

import java.util.UUID;

/**
 * A representation of an entity that can be authenticated by the system such as a user,
 * organization, software agent, or other actor. An account is a minimalist entity that serves
 * to identify the account and carry information critical to use within any application. It
 * does not carry any additional details that are application-specific. That information should
 * be provided by an application-specific account data store.
 *
 *
An account is intended to be a lightweight data structure for use in virtually any
 * application that needs the notion of a user account. Accounts correspond 1:1 to a UUID to
 * allow simple mapping and lookups, and to allow the UUID to be serialized in place of an
 * account for network transactions and Account Data persistence.
 *
 *
To use an application, the user must have an Account within the scope of that
 * application. The simple case of this is that the application's data store has a list of
 * all user accounts, and the user selects the account on login. The account selection process
 * is typically done by the user entering credentials for a known authentication provider,
 * the application validating the credentials with that provider, and then looking up in a
 * mapping what account the credentials apply to. This mapping may be done automatically in
 * some cases, or the account may be created by the application if credential validation is
 * successful to ease the maintenance of separate accounts from authentication system
 * credentials.
 *
 *
The rationale of requiring an account known to the application is founded in the ability
 * of application administrators to have control over user accounts. App admins can disable
 * or delete accounts, removing the user's ability to log in or all traces of their history
 * with the application, but only if accounts are not implicitly tied to some external
 * system. Applications must also be able to store information associated with credentials
 * stored in systems that are not mutable by the application and should not maintain storage
 * of the credentials themselves. To store information associated with an account, an
 * application must be able to uniquely identify the account (via credentials) and map that
 * identifier to the storage area.
 *
 *
An account has the following fields:
 *

 *
UUID

 *
display name

 *
is-active

 *

 *
 *
These fields are not exhaustive of all application use, but are the baseline.
 *
 *
An inactive Account is one that cannot be authorized to act in the system (that is, it
 * is not allowed log in or to act on any of the roles or permissions that it has been
 * assigned) but it can be re-activated. This might happen, for example, to disable an account
 * for failure to pay or abide by system policies, to lock an account that requires a
 * password reset or to temporarily disable a group.
 *
 *
Certain systems may have a notion of a "deleted" account which is not expunged from the
 * database with access control maintained by the Account Store. In this case, a deleted
 * account is one that cannot be authorized to act and cannot be restored by the
 * system (through normal operations). By flagging accounts as deleted (rather than simply
 * removing them) the system retains historical information that may be useful for audit
 * history, data integrity or learning about user preferences and behavior. With respect to
 * 'normal' use of the system, a deleted account does not exist. The Account Store may
 * provide accessors for deleted accounts in API beyond that which is required by the framework.
 */
public interface Account
{
   /**
    * A globally unique identifier for this account. This is the primary encapsulated and
    * exportable identifier.
    *
    * @return The account id.
    */
   UUID getId();

   /**
    * Get a display name for the account, which is often a "user name" but not typically a
    * person's name.
    * @since 2.0
    */
   String getDisplayName();

   /**
    * Indicates whether this account is currently active within the system. Note that it is
    * common to require access to account information (for example for historical purposes or
    * within audit trails). Application-specific account data may provide additional detail
    * about the reason an account is no longer active and guide application-specific controls
    * over whether that account can be re-activated.
    *
    *
Note that the account status is independent from the login method. For example, a
    * particular authentication mechanism may be restricted due to too many failed attempts
    * or permissions being revoked from a third-party authority such as Facebook without
    * affecting the active/inactive status of the account.
    *
    * @return {@code true} if this account is active.
    */
   boolean isActive();
}


text:
package org.apache.flink.runtime.util;

import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.JobID;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.core.io.InputSplit;
import org.apache.flink.core.testutils.CommonTestUtils;
import org.apache.flink.runtime.blob.BlobCacheService;
import org.apache.flink.runtime.blob.PermanentBlobCache;
import org.apache.flink.runtime.blob.TransientBlobCache;
import org.apache.flink.runtime.broadcast.BroadcastVariableManager;
import org.apache.flink.runtime.checkpoint.CheckpointMetrics;
import org.apache.flink.runtime.checkpoint.TaskStateSnapshot;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.deployment.InputGateDeploymentDescriptor;
import org.apache.flink.runtime.deployment.ResultPartitionDeploymentDescriptor;
import org.apache.flink.runtime.execution.ExecutionState;
import org.apache.flink.runtime.execution.librarycache.FallbackLibraryCacheManager;
import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
import org.apache.flink.runtime.executiongraph.JobInformation;
import org.apache.flink.runtime.executiongraph.TaskInformation;
import org.apache.flink.runtime.filecache.FileCache;
import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.runtime.io.disk.iomanager.IOManagerAsync;
import org.apache.flink.runtime.io.network.NetworkEnvironment;
import org.apache.flink.runtime.io.network.netty.PartitionProducerStateChecker;
import org.apache.flink.runtime.io.network.partition.ResultPartitionConsumableNotifier;
import org.apache.flink.runtime.io.network.partition.ResultPartitionID;
import org.apache.flink.runtime.jobgraph.IntermediateDataSetID;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.memory.MemoryManager;
import org.apache.flink.runtime.operators.testutils.UnregisteredTaskMetricsGroup;
import org.apache.flink.runtime.query.TaskKvStateRegistry;
import org.apache.flink.runtime.taskexecutor.TaskManagerConfiguration;
import org.apache.flink.runtime.taskmanager.CheckpointResponder;
import org.apache.flink.runtime.taskmanager.Task;
import org.apache.flink.runtime.taskmanager.TaskActions;
import org.apache.flink.runtime.taskmanager.TaskExecutionState;
import org.apache.flink.runtime.taskmanager.TaskManagerActions;
import org.apache.flink.runtime.taskmanager.TaskManagerRuntimeInfo;
import org.apache.flink.runtime.testutils.TestJvmProcess;
import org.apache.flink.util.OperatingSystem;
import org.apache.flink.util.SerializedValue;

import org.junit.Test;

import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import static org.junit.Assume.assumeTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Test that verifies the behavior of blocking shutdown hooks and of the
 * {@link JvmShutdownSafeguard} that guards against it.
 */
public class JvmExitOnFatalErrorTest {

	@Test
	public void testExitJvmOnOutOfMemory() throws Exception {
		// this test works only on linux
		assumeTrue(OperatingSystem.isLinux());

		// to check what went wrong (when the test hangs) uncomment this line
//		ProcessEntryPoint.main(new String[0]);

		final KillOnFatalErrorProcess testProcess = new KillOnFatalErrorProcess();

		try {
			testProcess.startProcess();
			testProcess.waitFor();
		}
		finally {
			testProcess.destroy();
		}
	}

	// ------------------------------------------------------------------------
	//  Blocking Process Implementation
	// ------------------------------------------------------------------------

	private static final class KillOnFatalErrorProcess extends TestJvmProcess {

		public KillOnFatalErrorProcess() throws Exception {}

		@Override
		public String getName() {
			return "KillOnFatalErrorProcess";
		}

		@Override
		public String[] getJvmArgs() {
			return new String[0];
		}

		@Override
		public String getEntryPointClassName() {
			return ProcessEntryPoint.class.getName();
		}
	}

	// ------------------------------------------------------------------------

	public static final class ProcessEntryPoint {

		public static void main(String[] args) throws Exception {

			System.err.println("creating task");

			// we suppress process exits via errors here to not
			// have a test that exits accidentally due to a programming error
			try {
				final Configuration taskManagerConfig = new Configuration();
				taskManagerConfig.setBoolean(TaskManagerOptions.KILL_ON_OUT_OF_MEMORY, true);

				final JobID jid = new JobID();
				final JobVertexID jobVertexId = new JobVertexID();
				final ExecutionAttemptID executionAttemptID = new ExecutionAttemptID();
				final AllocationID slotAllocationId = new AllocationID();

				final SerializedValue<ExecutionConfig> execConfig = new SerializedValue<>(new ExecutionConfig());

				final JobInformation jobInformation = new JobInformation(
						jid, "Test Job", execConfig, new Configuration(),
						Collections.emptyList(), Collections.emptyList());

				final TaskInformation taskInformation = new TaskInformation(
						jobVertexId, "Test Task", 1, 1, OomInvokable.class.getName(), new Configuration());

				final MemoryManager memoryManager = new MemoryManager(1024 * 1024, 1);
				final IOManager ioManager = new IOManagerAsync();

				final NetworkEnvironment networkEnvironment = mock(NetworkEnvironment.class);
				when(networkEnvironment.createKvStateTaskRegistry(jid, jobVertexId)).thenReturn(mock(TaskKvStateRegistry.class));

				final TaskManagerRuntimeInfo tmInfo = TaskManagerConfiguration.fromConfiguration(taskManagerConfig);

				final Executor executor = Executors.newCachedThreadPool();

				BlobCacheService blobService =
					new BlobCacheService(mock(PermanentBlobCache.class), mock(TransientBlobCache.class));

				Task task = new Task(
						jobInformation,
						taskInformation,
						executionAttemptID,
						slotAllocationId,
						0,       // subtaskIndex
						0,       // attemptNumber
						Collections.<ResultPartitionDeploymentDescriptor>emptyList(),
						Collections.<InputGateDeploymentDescriptor>emptyList(),
						0,       // targetSlotNumber
						null,    // taskStateHandles,
						memoryManager,
						ioManager,
						networkEnvironment,
						new BroadcastVariableManager(),
						new NoOpTaskManagerActions(),
						new NoOpInputSplitProvider(),
						new NoOpCheckpointResponder(),
					blobService,
						new FallbackLibraryCacheManager(),
						new FileCache(tmInfo.getTmpDirectories()),
						tmInfo,
						new UnregisteredTaskMetricsGroup(),
						new NoOpResultPartitionConsumableNotifier(),
						new NoOpPartitionProducerStateChecker(),
						executor);

				System.err.println("starting task thread");

				task.startTaskThread();
			}
			catch (Throwable t) {
				System.err.println("ERROR STARTING TASK");
				t.printStackTrace();
			}

			System.err.println("parking the main thread");
			CommonTestUtils.blockForeverNonInterruptibly();
		}

		public static final class OomInvokable extends AbstractInvokable {

			@Override
			public void invoke() throws Exception {
				throw new OutOfMemoryError();
			}
		}

		private static final class NoOpTaskManagerActions implements TaskManagerActions {

			@Override
			public void notifyFinalState(ExecutionAttemptID executionAttemptID) {}

			@Override
			public void notifyFatalError(String message, Throwable cause) {}

			@Override
			public void failTask(ExecutionAttemptID executionAttemptID, Throwable cause) {}

			@Override
			public void updateTaskExecutionState(TaskExecutionState taskExecutionState) {}
		}

		private static final class NoOpInputSplitProvider implements InputSplitProvider {

			@Override
			public InputSplit getNextInputSplit(ClassLoader userCodeClassLoader) {
				return null;
			}
		}

		private static final class NoOpCheckpointResponder implements CheckpointResponder {

			@Override
			public void acknowledgeCheckpoint(JobID j, ExecutionAttemptID e, long i, CheckpointMetrics c, TaskStateSnapshot s) {}

			@Override
			public void declineCheckpoint(JobID j, ExecutionAttemptID e, long l, Throwable t) {}
		}

		private static final class NoOpResultPartitionConsumableNotifier implements ResultPartitionConsumableNotifier {

			@Override
			public void notifyPartitionConsumable(JobID j, ResultPartitionID p, TaskActions t) {}
		}

		private static final class NoOpPartitionProducerStateChecker implements PartitionProducerStateChecker {

			@Override
			public CompletableFuture<ExecutionState> requestPartitionProducerState(
					JobID jobId, IntermediateDataSetID intermediateDataSetId, ResultPartitionID r) {
				return null;
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.kordamp.jipsy.processor.testutils;

import java.io.*;
import java.util.concurrent.atomic.AtomicBoolean;

public final class TestOutput {

    private static final TestWriter out = new TestWriter("out");
    private static final TestWriter err = new TestWriter("err");

    private TestOutput() {
        throw new UnsupportedOperationException();
    }

    public static TestWriter out() {
        return out;
    }

    public static TestWriter err() {
        return err;
    }

    public static void enableAll() {
        out.setEnabled(true);
        err.setEnabled(true);
    }

    public static void disableAll() {
        out.setEnabled(false);
        err.setEnabled(false);
    }

    public static final class TestWriter {

        private final AtomicBoolean enabled = new AtomicBoolean(true);
        private final AtomicBoolean recording = new AtomicBoolean(false);

        private final ByteArrayOutputStream captured = new ByteArrayOutputStream(5000);
        private final PrintStream original;

        private TestWriter(String name) {
            if ("out".equals(name)) {
                original = System.out;
                System.setOut(new PrintStream(new TestOutputStream(name, System.out)));
            } else {
                original = System.err;
                System.setErr(new PrintStream(new TestOutputStream(name, System.err)));
            }
        }

        public void record() {
            recording.set(true);
        }

        public void stop() {
            recording.set(false);
        }

        public PrintStream bypass() {
            return original;
        }

        public String play() {
            try {
                return captured.toString("UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }

        public String stopPlayAndReset() {
            stop();
            String result = play();
            reset();
            return result;
        }

        public void reset() {
            captured.reset();
        }

        public boolean isEnabled() {
            return enabled.get();
        }

        public void setEnabled(boolean enabled) {
            this.enabled.set(enabled);
        }

        private class TestOutputStream extends OutputStream {
            private final OutputStream parent;
            private final String name;

            private TestOutputStream(String name, OutputStream parent) {
                this.parent = parent;
                this.name = name;
            }

            @Override
            public void write(int b) throws IOException {
                parent.write(b);
                if (!enabled.get()) {
                    throw new IllegalStateException("Writing to System." + name + " is not allowed.");
                }
                if (recording.get()) {
                    captured.write(b);
                }
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Descriptors;
using OrchardCore.DisplayManagement.Html;
using OrchardCore.DisplayManagement.Implementation;
using OrchardCore.DisplayManagement.Shapes;

namespace OrchardCore.Navigation
{
    public class PagerShapesTableProvider : IShapeTableProvider
    {
        public void Discover(ShapeTableBuilder builder)
        {
            builder.Describe("Pager")
                .OnCreated(created =>
                {
                    // Initializes the common properties of a Pager shape
                    // such that views can safely add values to them.
                    created.Shape.Properties["ItemClasses"] = new List<string>();
                    created.Shape.Properties["ItemAttributes"] = new Dictionary<string, string>();
                })
                .OnDisplaying(displaying =>
                {
                    if (displaying.Shape.TryGetProperty("PagerId", out string pagerId) && !String.IsNullOrEmpty(pagerId))
                    {
                        displaying.Shape.Metadata.Alternates.Add("Pager__" + EncodeAlternateElement(pagerId));
                    };
                });

            builder.Describe("PagerSlim")
                .OnCreated(created =>
                {
                    // Initializes the common properties of a Pager shape
                    // such that views can safely add values to them.
                    created.Shape.Properties["ItemClasses"] = new List<string>();
                    created.Shape.Properties["ItemAttributes"] = new Dictionary<string, string>();
                })
                .OnDisplaying(displaying =>
                {
                    if (displaying.Shape.TryGetProperty("PagerId", out string pagerId) && !String.IsNullOrEmpty(pagerId))
                    {
                        displaying.Shape.Metadata.Alternates.Add("Pager__" + EncodeAlternateElement(pagerId));
                    };
                });

            builder.Describe("Pager_Gap")
                .OnDisplaying(displaying =>
                {
                    var shape = displaying.Shape;

                    if (shape.TryGetProperty("Pager", out IShape pager) && pager.TryGetProperty("PagerId", out string pagerId) && !String.IsNullOrEmpty(pagerId))
                    {
                        displaying.Shape.Metadata.Alternates.Add("Pager_Gap__" + EncodeAlternateElement(pagerId));
                    }
                });

            builder.Describe("Pager_First")
                .OnDisplaying(displaying =>
                {
                    var shape = displaying.Shape;

                    if (shape.TryGetProperty("Pager", out IShape pager) && pager.TryGetProperty("PagerId", out string pagerId) && !String.IsNullOrEmpty(pagerId))
                    {
                        displaying.Shape.Metadata.Alternates.Add("Pager_First__" + EncodeAlternateElement(pagerId));
                    }
                });

            builder.Describe("Pager_Previous")
                .OnDisplaying(displaying =>
                {
                    var shape = displaying.Shape;

                    if (shape.TryGetProperty("Pager", out IShape pager) && pager.TryGetProperty("PagerId", out string pagerId) && !String.IsNullOrEmpty(pagerId))
                    {
                        displaying.Shape.Metadata.Alternates.Add("Pager_Previous__" + EncodeAlternateElement(pagerId));
                    }
                });

            builder.Describe("Pager_Next")
                .OnDisplaying(displaying =>
                {
                    var shape = displaying.Shape;

                    if (shape.TryGetProperty("Pager", out IShape pager) && pager.TryGetProperty("PagerId", out string pagerId) && !String.IsNullOrEmpty(pagerId))
                    {
                        displaying.Shape.Metadata.Alternates.Add("Pager_Next__" + EncodeAlternateElement(pagerId));
                    }
                });

            builder.Describe("Pager_Last")
                .OnDisplaying(displaying =>
                {
                    var shape = displaying.Shape;

                    if (shape.TryGetProperty("Pager", out IShape pager) && pager.TryGetProperty("PagerId", out string pagerId) && !String.IsNullOrEmpty(pagerId))
                    {
                        displaying.Shape.Metadata.Alternates.Add("Pager_Last__" + EncodeAlternateElement(pagerId));
                    }
                });

            builder.Describe("Pager_CurrentPage")
                .OnDisplaying(displaying =>
                {
                    var shape = displaying.Shape;

                    if (shape.TryGetProperty("Pager", out IShape pager) && pager.TryGetProperty("PagerId", out string pagerId) && !String.IsNullOrEmpty(pagerId))
                    {
                        displaying.Shape.Metadata.Alternates.Add("Pager_CurrentPage__" + EncodeAlternateElement(pagerId));
                    }
                });

            builder.Describe("Pager_Links")
                .OnDisplaying(displaying =>
                {
                    if (displaying.Shape.TryGetProperty("PagerId", out string pagerId))
                    {
                        displaying.Shape.Metadata.Alternates.Add("Pager_Links__" + EncodeAlternateElement(pagerId));
                    }
                });
        }

        private static string EncodeAlternateElement(string alternateElement)
        {
            return alternateElement.Replace("-", "__").Replace('.', '_');
        }
    }

    public class PagerShapes : IShapeAttributeProvider
    {
        private readonly IStringLocalizer S;

        public PagerShapes(IStringLocalizer<PagerShapes> localizer)
        {
            S = localizer;
        }

        [Shape]
        public async Task<IHtmlContent> Pager_Links(Shape shape, DisplayContext displayContext, IShapeFactory shapeFactory, IHtmlHelper Html,
            string PagerId,
            int Page,
            int PageSize,
            double TotalItemCount,
            int? Quantity,
            object FirstText,
            object PreviousText,
            object NextText,
            object LastText,
            object GapText,
            bool ShowNext)
        {
            var noFollow = shape.Attributes.ContainsKey("rel") && shape.Attributes["rel"] == "no-follow";
            var currentPage = Page;
            if (currentPage < 1)
                currentPage = 1;

            var pageSize = PageSize;

            var numberOfPagesToShow = Quantity ?? 0;
            if (Quantity == null || Quantity < 0)
                numberOfPagesToShow = 7;

            var totalPageCount = pageSize > 0 ? (int)Math.Ceiling(TotalItemCount / pageSize) : 1;

            // return shape early if pager is not needed.
            if (totalPageCount < 2)
            {
                shape.Metadata.Type = "List";
                return await displayContext.DisplayHelper.ShapeExecuteAsync(shape);
            }

            var firstText = FirstText ?? S["<<"];
            var previousText = PreviousText ?? S["<"];
            var nextText = NextText ?? S[">"];
            var lastText = LastText ?? S[">>"];
            var gapText = GapText ?? S["..."];

            var httpContextAccessor = displayContext.ServiceProvider.GetService<IHttpContextAccessor>();
            var httpContext = httpContextAccessor.HttpContext;

            var routeData = new RouteValueDictionary(Html.ViewContext.RouteData.Values);

            if (httpContext != null)
            {
                var queryString = httpContext.Request.Query;
                if (queryString != null)
                {
                    foreach (var key in from string key in queryString.Keys where key != null && !routeData.ContainsKey(key) let value = queryString[key] select key)
                    {
                        routeData[key] = queryString[key];
                    }
                }
            }

            // specific cross-requests route data can be passed to the shape directly (e.g., OrchardCore.Users)
            var shapeRouteData = shape.GetProperty<RouteData>("RouteData");
            if (shapeRouteData != null)
            {
                foreach (var rd in shapeRouteData.Values)
                {
                    routeData[rd.Key] = rd.Value;
                }
            }

            var firstPage = Math.Max(1, Page - (numberOfPagesToShow / 2));
            var lastPage = Math.Min(totalPageCount, Page + (numberOfPagesToShow / 2));

            var pageKey = String.IsNullOrEmpty(PagerId) ? "pagenum" : PagerId;

            shape.Classes.Add("pager");
            shape.Metadata.Alternates.Clear();
            shape.Metadata.Type = "List";

            // first and previous pages
            if ((Page > 1) && (routeData.ContainsKey(pageKey)))
            {
                routeData.Remove(pageKey); // to keep from having "page=1" in the query string
            }

            // first
            var firstItem = await shapeFactory.CreateAsync("Pager_First", Arguments.From(new
            {
                Value = firstText,
                RouteValues = new RouteValueDictionary(routeData),
                Pager = shape,
                Disabled = Page < 2
            }));

            if (noFollow)
            {
                firstItem.Attributes["rel"] = "no-follow";
            }

            await shape.AddAsync(firstItem);

            // previous
            if ((Page > 1) && (currentPage > 2))
            { // also to keep from having "page=1" in the query string
                routeData[pageKey] = currentPage - 1;
            }

            var previousItem = await shapeFactory.CreateAsync("Pager_Previous", Arguments.From(new
            {
                Value = previousText,
                RouteValues = new RouteValueDictionary(routeData),
                Pager = shape,
                Disabled = Page < 2
            }));

            if (noFollow)
            {
                previousItem.Attributes["rel"] = "no-follow";
            }

            await shape.AddAsync(previousItem);

            // gap at the beginning of the pager
            if (firstPage > 1 && numberOfPagesToShow > 0)
            {
                await shape.AddAsync(await shapeFactory.CreateAsync("Pager_Gap", Arguments.From(new
                {
                    Value = gapText,
                    Pager = shape
                })));
            }

            // page numbers
            if (numberOfPagesToShow > 0 && lastPage > 1)
            {
                for (var p = firstPage; p <= lastPage; p++)
                {
                    if (p == currentPage)
                    {
                        routeData[pageKey] = currentPage;
                        var currentPageItem = await shapeFactory.CreateAsync("Pager_CurrentPage", Arguments.From(new
                        {
                            Value = p,
                            RouteValues = new RouteValueDictionary(routeData),
                            Pager = shape
                        }));

                        if (noFollow)
                        {
                            currentPageItem.Attributes["rel"] = "no-follow";
                        }

                        await shape.AddAsync(currentPageItem);
                    }
                    else
                    {
                        if (p == 1)
                        {
                            routeData.Remove(pageKey);
                        }
                        else
                        {
                            routeData[pageKey] = p;
                        }

                        var pagerItem = await shapeFactory.CreateAsync("Pager_Link", Arguments.From(new
                        {
                            Value = p,
                            RouteValues = new RouteValueDictionary(routeData),
                            Pager = shape
                        }));

                        if (p > currentPage)
                        {
                            pagerItem.Attributes["rel"] = noFollow ? "no-follow" : "next";
                        }
                        else if (p < currentPage)
                        {
                            pagerItem.Attributes["rel"] = noFollow ? "no-follow" : "prev";
                        }

                        await shape.AddAsync(pagerItem);
                    }
                }
            }

            // gap at the end of the pager
            if (lastPage < totalPageCount && numberOfPagesToShow > 0)
            {
                await shape.AddAsync(await shapeFactory.CreateAsync("Pager_Gap", Arguments.From(new
                {
                    Value = gapText,
                    Pager = shape
                })));
            }

            // Next
            routeData[pageKey] = Page + 1;
            var pagerNextItem = await shapeFactory.CreateAsync("Pager_Next", Arguments.From(new
            {
                Value = nextText,
                RouteValues = new RouteValueDictionary(routeData),
                Pager = shape,
                Disabled = Page >= totalPageCount && !ShowNext
            }));

            if (noFollow)
            {
                pagerNextItem.Attributes["rel"] = "no-follow";
            }

            await shape.AddAsync(pagerNextItem);

            // Last
            routeData[pageKey] = totalPageCount;
            var pagerLastItem = await shapeFactory.CreateAsync("Pager_Last", Arguments.From(new
            {
                Value = lastText,
                RouteValues = new RouteValueDictionary(routeData),
                Pager = shape,
                Disabled = Page >= totalPageCount
            }));

            if (noFollow)
            {
                pagerLastItem.Attributes["rel"] = "no-follow";
            }

            await shape.AddAsync(pagerLastItem);

            return await displayContext.DisplayHelper.ShapeExecuteAsync(shape);
        }

        [Shape]
        public Task<IHtmlContent> Pager(Shape shape, DisplayContext displayContext)
        {
            shape.Metadata.Alternates.Clear();
            shape.Metadata.Type = "Pager_Links";
            return displayContext.DisplayHelper.ShapeExecuteAsync(shape);
        }

        [Shape]
        public async Task<IHtmlContent> PagerSlim(Shape shape, DisplayContext displayContext, IShapeFactory shapeFactory, IHtmlHelper Html,
            object PreviousText,
            object NextText,
            string PreviousClass,
            string NextClass,
            Dictionary<string, string> UrlParams)
        {
            var noFollow = shape.Attributes.ContainsKey("rel") && shape.Attributes["rel"] == "no-follow";
            var previousText = PreviousText ?? S["<"];
            var nextText = NextText ?? S[">"];

            shape.Classes.Add("pager");
            shape.Metadata.Alternates.Clear();
            shape.Metadata.Type = "List";

            var routeData = new RouteValueDictionary(Html.ViewContext.RouteData.Values);

            // Allows to pass custom url params to PagerSlim
            if (UrlParams != null)
            {
                foreach (var item in UrlParams)
                {
                    routeData.Add(item.Key, item.Value);
                }
            }

            if (shape.TryGetProperty("Before", out string before))
            {
                var beforeRouteData = new RouteValueDictionary(routeData)
                {
                    ["before"] = before
                };

                var previousItem = await shapeFactory.CreateAsync("Pager_Previous", Arguments.From(new
                {
                    Value = previousText,
                    RouteValues = beforeRouteData,
                    Pager = shape
                }));

                if (noFollow)
                {
                    previousItem.Attributes["rel"] = "no-follow";
                }

                await shape.AddAsync(previousItem);
                shape.Properties["FirstClass"] = PreviousClass;
            }

            if (shape.TryGetProperty("After", out string after))
            {
                var afterRouteData = new RouteValueDictionary(routeData)
                {
                    ["after"] = after
                };

                var nextItem = await shapeFactory.CreateAsync("Pager_Next", Arguments.From(new
                {
                    Value = nextText,
                    RouteValues = afterRouteData,
                    Pager = shape
                }));

                if (noFollow)
                {
                    nextItem.Attributes["rel"] = "no-follow";
                }

                await shape.AddAsync(nextItem);
                shape.Properties["LastClass"] = NextClass;
            }

            return await displayContext.DisplayHelper.ShapeExecuteAsync(shape);
        }

        [Shape]
        public Task<IHtmlContent> Pager_First(Shape shape, DisplayContext displayContext)
        {
            shape.Metadata.Alternates.Clear();
            shape.Metadata.Type = "Pager_Link";
            return displayContext.DisplayHelper.ShapeExecuteAsync(shape);
        }

        [Shape]
        public Task<IHtmlContent> Pager_Previous(Shape shape, DisplayContext displayContext)
        {
            shape.Metadata.Alternates.Clear();
            shape.Metadata.Type = "Pager_Link";

            if (!shape.Attributes.ContainsKey("rel"))
            {
                shape.Attributes["rel"] = "prev";
            }

            return displayContext.DisplayHelper.ShapeExecuteAsync(shape);
        }

        [Shape]
        public Task<IHtmlContent> Pager_CurrentPage(Shape shape, DisplayContext displayContext)
        {
            shape.Metadata.Alternates.Clear();
            shape.Metadata.Type = "Pager_Link";
            var parentTag = shape.GetProperty<TagBuilder>("Tag");
            parentTag.AddCssClass("active");

            return displayContext.DisplayHelper.ShapeExecuteAsync(shape);
        }

        [Shape]
        public Task<IHtmlContent> Pager_Next(Shape shape, DisplayContext displayContext)
        {
            shape.Metadata.Alternates.Clear();
            shape.Metadata.Type = "Pager_Link";

            if (!shape.Attributes.ContainsKey("rel"))
            {
                shape.Attributes["rel"] = "next";
            }

            return displayContext.DisplayHelper.ShapeExecuteAsync(shape);
        }

        [Shape]
        public Task<IHtmlContent> Pager_Last(Shape shape, DisplayContext displayContext)
        {
            shape.Metadata.Alternates.Clear();
            shape.Metadata.Type = "Pager_Link";
            return displayContext.DisplayHelper.ShapeExecuteAsync(shape);
        }

        [Shape]
        public Task<IHtmlContent> Pager_Link(Shape shape, DisplayContext displayContext)
        {
            shape.Metadata.Alternates.Clear();
            shape.Metadata.Type = "ActionLink";
            return displayContext.DisplayHelper.ShapeExecuteAsync(shape);
        }

        [Shape]
        public IHtmlContent ActionLink(Shape shape, IUrlHelper Url, object Value, bool Disabled = false)
        {
            if (Disabled)
            {
                if (shape.TryGetProperty("Tag", out TagBuilder tagBuilder))
                {
                    tagBuilder.AddCssClass("disabled");
                }
            }

            var routeValues = shape.GetProperty<RouteValueDictionary>("RouteValues") ?? new RouteValueDictionary();
            if (!Disabled)
            {
                shape.Attributes["href"] = Url.Action((string)routeValues["action"], (string)routeValues["controller"], routeValues);
            }
            else
            {
                shape.Attributes.Remove("href");
            }

            var tag = shape.GetTagBuilder("a");

            tag.InnerHtml.AppendHtml(CoerceHtmlString(Value));
            return tag;
        }

        [Shape]
        public Task<IHtmlContent> Pager_Gap(IShape shape, DisplayContext displayContext)
        {
            shape.Metadata.Alternates.Clear();
            shape.Metadata.Type = "Pager_Link";
            var parentTag = shape.GetProperty<TagBuilder>("Tag");
            parentTag.AddCssClass("disabled");
            return displayContext.DisplayHelper.ShapeExecuteAsync(shape);
        }

        private static IHtmlContent CoerceHtmlString(object value)
        {
            if (value == null)
            {
                return HtmlString.Empty;
            }

            if (value is IHtmlContent result)
            {
                return result;
            }

            return new HtmlContentString(value.ToString());
        }
    }
}


text:
namespace base {
namespace sequence_manager {
class TaskQueue;
}  // namespace sequence_manager
namespace trace_event {
class BlameContext;
}  // namespace trace_event
}  // namespace base

namespace ukm {
class UkmRecorder;
}

namespace blink {

class MainThreadSchedulerTest;
class WebSchedulingTaskQueue;

namespace scheduler {

class MainThreadSchedulerImpl;
class MainThreadTaskQueue;
class PageSchedulerImpl;
class ResourceLoadingTaskRunnerHandleImpl;

namespace main_thread_scheduler_impl_unittest {
class MainThreadSchedulerImplTest;
}

namespace frame_scheduler_impl_unittest {
class FrameSchedulerImplTest;
}

namespace page_scheduler_impl_unittest {
class PageSchedulerImplTest;
}

class PLATFORM_EXPORT FrameSchedulerImpl : public FrameScheduler,
                                           FrameTaskQueueController::Delegate {
 public:
  FrameSchedulerImpl(PageSchedulerImpl* page_scheduler,
                     FrameScheduler::Delegate* delegate,
                     base::trace_event::BlameContext* blame_context,
                     FrameScheduler::FrameType frame_type);
  FrameSchedulerImpl(const FrameSchedulerImpl&) = delete;
  FrameSchedulerImpl& operator=(const FrameSchedulerImpl&) = delete;
  ~FrameSchedulerImpl() override;

  // FrameOrWorkerScheduler implementation:
  void SetPreemptedForCooperativeScheduling(Preempted) override;

  // FrameScheduler implementation:
  void SetFrameVisible(bool frame_visible) override;
  bool IsFrameVisible() const override;

  bool IsPageVisible() const override;

  void SetPaused(bool frame_paused) override;
  void SetShouldReportPostedTasksWhenDisabled(bool should_report) override;

  void SetCrossOriginToMainFrame(bool cross_origin) override;
  bool IsCrossOriginToMainFrame() const override;

  void SetIsAdFrame(bool is_ad_frame) override;
  bool IsAdFrame() const override;

  void TraceUrlChange(const String& url) override;
  void AddTaskTime(base::TimeDelta time) override;
  FrameScheduler::FrameType GetFrameType() const override;
  scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner(TaskType) override;

  // Returns a wrapper around an instance of MainThreadTaskQueue which is
  // maintained in |resource_loading_task_queues_| map. The main thread task
  // queue is removed from the map and detached from both the main thread and
  // the frame schedulers when the wrapper instance goes out of scope.
  std::unique_ptr<WebResourceLoadingTaskRunnerHandle>
  CreateResourceLoadingTaskRunnerHandle() override;

  std::unique_ptr<WebResourceLoadingTaskRunnerHandle>
  CreateResourceLoadingMaybeUnfreezableTaskRunnerHandle() override;
  WebAgentGroupScheduler* GetAgentGroupScheduler() override;
  PageScheduler* GetPageScheduler() const override;
  void DidStartProvisionalLoad(bool is_main_frame) override;
  void DidCommitProvisionalLoad(bool is_web_history_inert_commit,
                                NavigationType navigation_type) override;
  WebScopedVirtualTimePauser CreateWebScopedVirtualTimePauser(
      const WTF::String& name,
      WebScopedVirtualTimePauser::VirtualTaskDuration duration) override;

  void OnFirstContentfulPaintInMainFrame() override;
  void OnDomContentLoaded() override;
  void OnFirstMeaningfulPaint() override;
  void OnLoad() override;
  bool IsWaitingForContentfulPaint() const;
  bool IsWaitingForMeaningfulPaint() const;

  // An "ordinary" FrameScheduler is responsible for a frame whose parent page
  // is a fully-featured page owned by a web view (as opposed to, e.g.: a Page
  // created by an SVGImage). Virtual for testing.
  virtual bool IsOrdinary() const;

  bool IsExemptFromBudgetBasedThrottling() const override;
  std::unique_ptr<blink::mojom::blink::PauseSubresourceLoadingHandle>
  GetPauseSubresourceLoadingHandle() override;

  void OnStartedUsingFeature(SchedulingPolicy::Feature feature,
                             const SchedulingPolicy& policy) override;
  void OnStoppedUsingFeature(SchedulingPolicy::Feature feature,
                             const SchedulingPolicy& policy) override;

  base::WeakPtr<FrameScheduler> GetWeakPtr() override;
  base::WeakPtr<const FrameSchedulerImpl> GetWeakPtr() const;
  base::WeakPtr<FrameSchedulerImpl> GetInvalidatingOnBFCacheRestoreWeakPtr();

  void ReportActiveSchedulerTrackedFeatures() override;

  scoped_refptr<base::SingleThreadTaskRunner> ControlTaskRunner();

  void UpdatePolicy();

  // Whether the frame is opted-out from CPU time throttling and intensive wake
  // up throttling.
  bool opted_out_from_aggressive_throttling() const {
    return opted_out_from_aggressive_throttling_;
  }

  void OnTraceLogEnabled() { tracing_controller_.OnTraceLogEnabled(); }

  void SetPageVisibilityForTracing(PageVisibilityState page_visibility);
  void SetPageFrozenForTracing(bool frozen);

  // Computes the priority of |task_queue| if it is associated to this frame
  // scheduler. Note that the main thread's policy should be upto date to
  // compute the correct priority.
  base::sequence_manager::TaskQueue::QueuePriority ComputePriority(
      MainThreadTaskQueue* task_queue) const;

  ukm::SourceId GetUkmSourceId() override;
  ukm::UkmRecorder* GetUkmRecorder();

  // FrameTaskQueueController::Delegate implementation.
  void OnTaskQueueCreated(
      MainThreadTaskQueue*,
      base::sequence_manager::TaskQueue::QueueEnabledVoter*) override;

  void SetOnIPCTaskPostedWhileInBackForwardCacheHandler();
  void DetachOnIPCTaskPostedWhileInBackForwardCacheHandler();
  void OnIPCTaskPostedWhileInBackForwardCache(uint32_t ipc_hash,
                                              const char* ipc_interface_name);

  // Returns the list of active features which currently tracked by the
  // scheduler for back-forward cache metrics.
  WTF::HashSet<SchedulingPolicy::Feature>
  GetActiveFeaturesTrackedForBackForwardCacheMetrics() override;

  std::unique_ptr<WebSchedulingTaskQueue> CreateWebSchedulingTaskQueue(
      WebSchedulingPriority) override;
  void OnWebSchedulingTaskQueuePriorityChanged(MainThreadTaskQueue*);
  void OnWebSchedulingTaskQueueDestroyed(MainThreadTaskQueue*);

  const base::UnguessableToken& GetAgentClusterId() const;

  void WriteIntoTrace(perfetto::TracedValue context) const;
  void WriteIntoTrace(perfetto::TracedProto<
                      perfetto::protos::pbzero::RendererMainThreadTaskExecution>
                          proto) const;

 protected:
  FrameSchedulerImpl(MainThreadSchedulerImpl* main_thread_scheduler,
                     PageSchedulerImpl* parent_page_scheduler,
                     FrameScheduler::Delegate* delegate,
                     base::trace_event::BlameContext* blame_context,
                     FrameScheduler::FrameType frame_type);

  // This will construct a subframe that is not linked to any main thread or
  // page scheduler. Should be used only for testing purposes.
  FrameSchedulerImpl();

  void OnShutdownResourceLoadingTaskQueue(
      scoped_refptr<MainThreadTaskQueue> task_queue);

  void DidChangeResourceLoadingPriority(
      scoped_refptr<MainThreadTaskQueue> task_queue,
      net::RequestPriority priority);

  scoped_refptr<MainThreadTaskQueue> GetTaskQueue(TaskType);

 private:
  friend class PageSchedulerImpl;
  friend class main_thread_scheduler_impl_unittest::MainThreadSchedulerImplTest;
  friend class frame_scheduler_impl_unittest::FrameSchedulerImplTest;
  friend class page_scheduler_impl_unittest::PageSchedulerImplTest;
  friend class PerAgentSchedulingBaseTest;
  friend class ResourceLoadingTaskRunnerHandleImpl;
  friend class ::blink::MainThreadSchedulerTest;

  // A class that adds and removes itself from the passed in weak pointer. While
  // one exists, resource loading is paused.
  class PauseSubresourceLoadingHandleImpl
      : public blink::mojom::blink::PauseSubresourceLoadingHandle {
   public:
    // This object takes a reference in |frame_scheduler| preventing resource
    // loading in the frame until the reference is released during destruction.
    explicit PauseSubresourceLoadingHandleImpl(
        base::WeakPtr<FrameSchedulerImpl> frame_scheduler);
    PauseSubresourceLoadingHandleImpl(
        const PauseSubresourceLoadingHandleImpl&) = delete;
    PauseSubresourceLoadingHandleImpl& operator=(
        const PauseSubresourceLoadingHandleImpl&) = delete;
    ~PauseSubresourceLoadingHandleImpl() override;

   private:
    base::WeakPtr<FrameSchedulerImpl> frame_scheduler_;
  };

  void DetachFromPageScheduler();
  void RemoveThrottleableQueueFromBudgetPools(MainThreadTaskQueue*);
  void ApplyPolicyToThrottleableQueue();
  bool ShouldThrottleTaskQueues() const;
  SchedulingLifecycleState CalculateLifecycleState(
      ObserverType type) const override;
  void UpdateQueuePolicy(
      MainThreadTaskQueue* queue,
      base::sequence_manager::TaskQueue::QueueEnabledVoter* voter);

  void AddPauseSubresourceLoadingHandle();
  void RemovePauseSubresourceLoadingHandle();

  void OnAddedAggressiveThrottlingOptOut();
  void OnRemovedAggressiveThrottlingOptOut();

  std::unique_ptr<ResourceLoadingTaskRunnerHandleImpl>
  CreateResourceLoadingTaskRunnerHandleImpl();

  FrameTaskQueueController* FrameTaskQueueControllerForTest() {
    return frame_task_queue_controller_.get();
  }

  // Create the QueueTraits for a specific TaskType. This returns absl::nullopt
  // for loading tasks and non-frame-level tasks.
  static MainThreadTaskQueue::QueueTraits CreateQueueTraitsForTaskType(
      TaskType);

  // Reset the state which should not persist across navigations.
  void ResetForNavigation();

  // Same as GetActiveFeaturesTrackedForBackForwardCacheMetrics, but returns
  // a mask instead of a set.
  uint64_t GetActiveFeaturesTrackedForBackForwardCacheMetricsMask() const;

  base::WeakPtr<FrameOrWorkerScheduler> GetSchedulingAffectingFeatureWeakPtr()
      override;

  void MoveTaskQueuesToCorrectWakeUpBudgetPool();

  // Create QueueTraits for the default (non-finch) task queues.
  static MainThreadTaskQueue::QueueTraits ThrottleableTaskQueueTraits();
  static MainThreadTaskQueue::QueueTraits DeferrableTaskQueueTraits();
  static MainThreadTaskQueue::QueueTraits PausableTaskQueueTraits();
  static MainThreadTaskQueue::QueueTraits UnpausableTaskQueueTraits();
  static MainThreadTaskQueue::QueueTraits FreezableTaskQueueTraits();
  static MainThreadTaskQueue::QueueTraits ForegroundOnlyTaskQueueTraits();
  static MainThreadTaskQueue::QueueTraits
  CanRunWhenVirtualTimePausedTaskQueueTraits();
  static MainThreadTaskQueue::QueueTraits LoadingTaskQueueTraits();
  static MainThreadTaskQueue::QueueTraits UnfreezableLoadingTaskQueueTraits();
  static MainThreadTaskQueue::QueueTraits LoadingControlTaskQueueTraits();
  static MainThreadTaskQueue::QueueTraits FindInPageTaskQueueTraits();
  static MainThreadTaskQueue::QueueTraits InputBlockingQueueTraits();

  const FrameScheduler::FrameType frame_type_;

  bool is_ad_frame_;

  // A running tally of (wall) time spent in tasks for this frame.
  // This is periodically forwarded and zeroed out.
  base::TimeDelta task_time_;

  TraceableVariableController tracing_controller_;
  std::unique_ptr<FrameTaskQueueController> frame_task_queue_controller_;

  using ResourceLoadingTaskQueuePriorityMap =
      WTF::HashMap<scoped_refptr<MainThreadTaskQueue>,
                   base::sequence_manager::TaskQueue::QueuePriority>;

  // Queue to priority map of resource loading task queues created by
  // |frame_task_queue_controller_| via CreateResourceLoadingTaskRunnerHandle.
  ResourceLoadingTaskQueuePriorityMap resource_loading_task_queue_priorities_;

  MainThreadSchedulerImpl* const main_thread_scheduler_;  // NOT OWNED
  PageSchedulerImpl* parent_page_scheduler_;              // NOT OWNED
  FrameScheduler::Delegate* delegate_;                    // NOT OWNED
  base::trace_event::BlameContext* blame_context_;        // NOT OWNED
  SchedulingLifecycleState throttling_state_;
  TraceableState<bool, TracingCategory::kInfo> frame_visible_;
  TraceableState<bool, TracingCategory::kInfo> frame_paused_;
  TraceableState<FrameOriginType, TracingCategory::kInfo> frame_origin_type_;
  TraceableState<bool, TracingCategory::kInfo> subresource_loading_paused_;
  StateTracer<TracingCategory::kInfo> url_tracer_;
  TraceableState<bool, TracingCategory::kInfo> task_queues_throttled_;
  Vector<MainThreadTaskQueue::ThrottleHandle> throttled_task_queue_handles_;
  TraceableState<bool, TracingCategory::kInfo>
      preempted_for_cooperative_scheduling_;
  // TODO(https://crbug.com/827113): Trace the count of opt-outs.
  int aggressive_throttling_opt_out_count_;
  TraceableState<bool, TracingCategory::kInfo>
      opted_out_from_aggressive_throttling_;
  size_t subresource_loading_pause_count_;

  BackForwardCacheDisablingFeatureTracker
      back_forward_cache_disabling_feature_tracker_;

  base::sequence_manager::TaskQueue::QueuePriority
      default_loading_task_priority_ =
          base::sequence_manager::TaskQueue::QueuePriority::kNormalPriority;

  // These are the states of the Page.
  // They should be accessed via GetPageScheduler()->SetPageState().
  // they are here because we don't support page-level tracing yet.
  TraceableState<bool, TracingCategory::kInfo> page_frozen_for_tracing_;
  TraceableState<PageVisibilityState, TracingCategory::kInfo>
      page_visibility_for_tracing_;

  TraceableState<bool, TracingCategory::kInfo> waiting_for_dom_content_loaded_;
  TraceableState<bool, TracingCategory::kInfo> waiting_for_contentful_paint_;
  TraceableState<bool, TracingCategory::kInfo> waiting_for_meaningful_paint_;
  TraceableState<bool, TracingCategory::kInfo> waiting_for_load_;

  std::unique_ptr<power_scheduler::PowerModeVoter> loading_power_mode_voter_;

  // TODO(altimin): Remove after we have have 1:1 relationship between frames
  // and documents.
  base::WeakPtrFactory<FrameSchedulerImpl> document_bound_weak_factory_{this};

  // WeakPtrFactory for tracking IPCs posted to frames cached in the
  // back-forward cache. These weak pointers are invalidated when the page is
  // restored from the cache.
  base::WeakPtrFactory<FrameSchedulerImpl>
      invalidating_on_bfcache_restore_weak_factory_{this};

  mutable base::WeakPtrFactory<FrameSchedulerImpl> weak_factory_{this};
};

}  // namespace scheduler
}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_MAIN_THREAD_FRAME_SCHEDULER_IMPL_H_


text:
import {Component, Inject, Input, OnInit} from "@angular/core";
import {AccessControlService} from "../../services/AccessControlService";
import AccessConstants from "../../constants/AccessConstants";

@Component({
    templateUrl:"./access-denied.component.html"
})
export class AccessDeniedComponent implements OnInit{

    @Input()
    stateParams:any;

    permissions:string[] = []

    missingPermissions:string[] = [];

    constructor(@Inject("AccessControlService") private accessControlService:AccessControlService) {}

    ngOnInit(){
        if(this.stateParams && this.stateParams.attemptedState) {
            if(this.stateParams.attemptedState.data.permissions) {
                this.permissions = this.stateParams.attemptedState.data.permissions;
                this.missingPermissions = this.accessControlService.findMissingPermissions(this.stateParams.attemptedState.data.permissions);
            }
            else  if(this.stateParams.attemptedState.data.permissionsKey) {
                this.permissions = AccessConstants.getStatePermissions(this.stateParams.attemptedState.data.permissionsKey);
                this.missingPermissions = this.accessControlService.findMissingPermissions(this.permissions);
            }

        }
    }
}


text:
require 'session_guard'

class PrisonerDetailsController < ApplicationController
  include CookieGuard
  include SessionGuardOnUpdateOnly
  before_filter :logstasher_add_visit_id_from_session, only: :update

  def edit
    session[:visit] ||= new_session
    logstasher_add_visit_id(visit.visit_id)
    response.set_cookie 'cookies-enabled', value: 1, secure: request.ssl?, httponly: true, domain: service_domain, path: '/'
  end

  def update
    if (visit.prisoner = Prisoner.new(prisoner_params)).valid?
      instant_booking = Rails.configuration.prison_data[visit.prisoner.prison_name][:instant_booking]
      if instant_booking && !killswitch_active?
        redirect_to instant_edit_visitors_details_path
      else
        redirect_to deferred_edit_visitors_details_path
      end
    else
      if visit.prisoner.errors[:number].any?
        STATSD_CLIENT.increment('pvb.app.invalid_prisoner_number')
      end
      redirect_to edit_prisoner_details_path
    end
  end

  def prisoner_params
    dob = [:'date_of_birth(3i)', :'date_of_birth(2i)', :'date_of_birth(1i)']
    if params[:date_of_birth_native].present?
      params[:prisoner][:date_of_birth] = Date.parse(params[:date_of_birth_native])
      dob.map{|d| params[:prisoner].delete(d)}
    else
      date_of_birth = dob.map do |key|
        params[:prisoner].delete(key).to_i
      end
      params[:prisoner][:date_of_birth] = Date.new(*date_of_birth.reverse)
    end
    ParamUtils.trim_whitespace_from_values(params.require(:prisoner).permit(:first_name, :last_name, :date_of_birth, :number, :prison_name))
  rescue ArgumentError
    ParamUtils.trim_whitespace_from_values(params.require(:prisoner).permit(:first_name, :last_name, :number, :prison_name))
  end

  def new_session
    Visit.new(visit_id: SecureRandom.hex, prisoner: Prisoner.new, visitors: [], slots: [])
  end

  def service_domain
    SERVICE_DOMAIN
  end

  def killswitch_active?
    ENV['API_KILLSWITCH']
  end
end


text:
namespace gui
{

LayerRenderer::~LayerRenderer()
{
  DestroyRenderers();
}

void LayerRenderer::Build(ref_ptr<dp::GpuProgramManager> mng)
{
  for (TRenderers::value_type & r : m_renderers)
    r.second->Build(mng);
}

void LayerRenderer::Render(ref_ptr<dp::GpuProgramManager> mng, ScreenBase const & screen)
{
  DrapeGui::GetRulerHelper().ResetTextDirtyFlag();
  DrapeGui::GetRulerHelper().Update(screen);
  for (TRenderers::value_type & r : m_renderers)
    r.second->Render(screen, mng);
}

void LayerRenderer::Merge(ref_ptr<LayerRenderer> other)
{
  bool activeOverlayFound = false;
  for (TRenderers::value_type & r : other->m_renderers)
  {
    TRenderers::iterator it = m_renderers.find(r.first);
    if (it != m_renderers.end())
    {
      auto newActiveOverlay = r.second->FindHandle(m_activeOverlayId);
      bool const updateActive = (m_activeOverlay != nullptr && newActiveOverlay != nullptr);
      it->second = move(r.second);
      if (!activeOverlayFound && updateActive)
      {
        activeOverlayFound = true;
        m_activeOverlay = newActiveOverlay;
        if (m_activeOverlay != nullptr)
          m_activeOverlay->OnTapBegin();
      }
    }
    else
    {
      m_renderers.insert(make_pair(r.first, move(r.second)));
    }
  }

  other->m_renderers.clear();
}

void LayerRenderer::SetLayout(TWidgetsLayoutInfo const & info)
{
  for (auto node : info)
  {
    auto renderer = m_renderers.find(node.first);
    if (renderer != m_renderers.end())
      renderer->second->SetPivot(node.second);
  }
}

void LayerRenderer::DestroyRenderers()
{
  m_renderers.clear();
}

void LayerRenderer::AddShapeRenderer(EWidget widget, drape_ptr<ShapeRenderer> && shape)
{
  if (shape == nullptr)
    return;

  VERIFY(m_renderers.insert(make_pair(widget, move(shape))).second, ());
}

bool LayerRenderer::OnTouchDown(m2::RectD const & touchArea)
{
  for (TRenderers::value_type & r : m_renderers)
  {
    m_activeOverlay = r.second->ProcessTapEvent(touchArea);
    if (m_activeOverlay != nullptr)
    {
      m_activeOverlayId = m_activeOverlay->GetFeatureID();
      m_activeOverlay->OnTapBegin();
      return true;
    }
  }

  return false;
}

void LayerRenderer::OnTouchUp(m2::RectD const & touchArea)
{
  if (m_activeOverlay != nullptr)
  {
    if (m_activeOverlay->IsTapped(touchArea))
      m_activeOverlay->OnTap();

    m_activeOverlay->OnTapEnd();
    m_activeOverlay = nullptr;
    m_activeOverlayId = FeatureID();
  }
}

void LayerRenderer::OnTouchCancel(m2::RectD const & touchArea)
{
  UNUSED_VALUE(touchArea);
  if (m_activeOverlay != nullptr)
  {
    m_activeOverlay->OnTapEnd();
    m_activeOverlay = nullptr;
    m_activeOverlayId = FeatureID();
  }
}

namespace
{

class ScaleLabelHandle : public MutableLabelHandle
{
  using TBase = MutableLabelHandle;
public:
  ScaleLabelHandle(uint32_t id, ref_ptr<dp::TextureManager> textures)
    : TBase(id, dp::LeftBottom, m2::PointF::Zero(), textures)
    , m_scale(0)
  {
    SetIsVisible(true);
  }

  bool Update(ScreenBase const & screen) override
  {
    int newScale = df::GetDrawTileScale(screen);
    if (m_scale != newScale)
    {
      m_scale = newScale;
      SetContent("Scale : " + strings::to_string(m_scale));
    }

    float vs = df::VisualParams::Instance().GetVisualScale();
    m2::PointF offset(10.0f * vs, 30.0f * vs);

    SetPivot(glsl::ToVec2(m2::PointF(screen.PixelRect().LeftBottom()) + offset));
    return TBase::Update(screen);
  }

private:
  int m_scale;
};

} // namespace

drape_ptr<LayerRenderer> LayerCacher::RecacheWidgets(TWidgetsInitInfo const & initInfo, ref_ptr<dp::TextureManager> textures)
{
  using TCacheShape = function<m2::PointF (Position anchor, ref_ptr<LayerRenderer> renderer, ref_ptr<dp::TextureManager> textures)>;
  static map<EWidget, TCacheShape> cacheFunctions
  {
    make_pair(WIDGET_COMPASS, bind(&LayerCacher::CacheCompass, this, _1, _2, _3)),
    make_pair(WIDGET_RULER, bind(&LayerCacher::CacheRuler, this, _1, _2, _3)),
    make_pair(WIDGET_COPYRIGHT, bind(&LayerCacher::CacheCopyright, this, _1, _2, _3)),
    make_pair(WIDGET_SCALE_LABEL, bind(&LayerCacher::CacheScaleLabel, this, _1, _2, _3))
  };

  drape_ptr<LayerRenderer> renderer = make_unique_dp<LayerRenderer>();
  for (auto node : initInfo)
  {
    auto cacheFunction = cacheFunctions.find(node.first);
    if (cacheFunction != cacheFunctions.end())
      cacheFunction->second(node.second, make_ref(renderer), textures);
  }

  // Flush gui geometry.
  GLFunctions::glFlush();

  return renderer;
}

drape_ptr<LayerRenderer> LayerCacher::RecacheChoosePositionMark(ref_ptr<dp::TextureManager> textures)
{
  m2::PointF const surfSize = DrapeGui::Instance().GetSurfaceSize();
  drape_ptr<LayerRenderer> renderer = make_unique_dp<LayerRenderer>();

  ChoosePositionMark positionMark = ChoosePositionMark(Position(surfSize * 0.5f, dp::Center));
  renderer->AddShapeRenderer(WIDGET_CHOOSE_POSITION_MARK, positionMark.Draw(textures));

  // Flush gui geometry.
  GLFunctions::glFlush();

  return renderer;
}

m2::PointF LayerCacher::CacheCompass(Position const & position, ref_ptr<LayerRenderer> renderer,
                                     ref_ptr<dp::TextureManager> textures)
{
  m2::PointF compassSize;
  Compass compass = Compass(position);
  drape_ptr<ShapeRenderer> shape = compass.Draw(compassSize, textures, bind(&DrapeGui::CallOnCompassTappedHandler,
                                                                            &DrapeGui::Instance()));

  renderer->AddShapeRenderer(WIDGET_COMPASS, move(shape));

  return compassSize;
}

m2::PointF LayerCacher::CacheRuler(Position const & position, ref_ptr<LayerRenderer> renderer,
                                   ref_ptr<dp::TextureManager> textures)
{
  m2::PointF rulerSize;
  renderer->AddShapeRenderer(WIDGET_RULER,
                             Ruler(position).Draw(rulerSize, textures));
  return rulerSize;
}

m2::PointF LayerCacher::CacheCopyright(Position const & position, ref_ptr<LayerRenderer> renderer,
                                       ref_ptr<dp::TextureManager> textures)
{
  m2::PointF size;
  renderer->AddShapeRenderer(WIDGET_COPYRIGHT,
                             CopyrightLabel(position).Draw(size, textures));

  return size;
}

m2::PointF LayerCacher::CacheScaleLabel(Position const & position, ref_ptr<LayerRenderer> renderer, ref_ptr<dp::TextureManager> textures)
{
  MutableLabelDrawer::Params params;
  params.m_alphabet = "Scale: 1234567890";
  params.m_maxLength = 10;
  params.m_anchor = position.m_anchor;
  params.m_font = DrapeGui::GetGuiTextFont();
  params.m_pivot = position.m_pixelPivot;
  params.m_handleCreator = [textures](dp::Anchor, m2::PointF const &)
  {
    return make_unique_dp<ScaleLabelHandle>(EGuiHandle::GuiHandleScaleLabel, textures);
  };

  drape_ptr<ShapeRenderer> scaleRenderer = make_unique_dp<ShapeRenderer>();
  m2::PointF size = MutableLabelDrawer::Draw(params, textures, bind(&ShapeRenderer::AddShape, scaleRenderer.get(), _1, _2));

  renderer->AddShapeRenderer(WIDGET_SCALE_LABEL, move(scaleRenderer));
  return size;
}

} // namespace gui