text:
package se.kth.scs.partitioning.policy;

import java.util.List;
import se.kth.scs.partitioning.Partition;
import se.kth.scs.partitioning.Vertex;

/**
 *
 * @author Hooman
 */
public interface PartitionSelectionPolicy {

  public Partition allocateNextEdge(Vertex v1, Vertex v2, List<Partition> partitions);
}

redpajama_set_name: RedPajamaGithub


text:
// RTM.Tools
// RTM.Component.CameraMovementDetector
// CameraMovementDetectorComponent.cs
//
// Created by Bartosz Rachwal.
// Copyright (c) 2015 Bartosz Rachwal. The National Institute of Advanced Industrial Science and Technology, Japan. All rights reserved.

using System;
using OpenRTM.Core;
using RTM.Component.CameraMovementDetector.MovementDetector;
using RTM.DTO;

namespace RTM.Component.CameraMovementDetector.Component
{
    [Component(Category = "CameraMovement", Name = "CameraMovementDetector")]
    [DetailProfile(
        Description = "Camera Movement Detector Component",
        Language = "C#",
        LanguageType = "Compile",
        MaxInstance = 1,
        Vendor = "AIST",
        Version = "1.0.0")]
    [CustomProfile("CreationDate", "2015/08/11")]
    [CustomProfile("Author", "Bartosz Rachwal")]
    public class CameraMovementDetectorComponent : DataFlowComponent
    {
        [InPort(PortName = "camera")] private readonly InPort<CameraImage> inport = new InPort<CameraImage>();

        [OutPort(PortName = "camera")] private readonly OutPort<CameraImage> outportCamera = new OutPort<CameraImage>();

        [OutPort(PortName = "vectors")] private readonly OutPort<Vectors> outportVectors = new OutPort<Vectors>();

        private ICameraMovementDetector cameraMovementDetector;

        public ICameraMovementDetector CameraMovementDetector
        {
            get { return cameraMovementDetector; }
            set
            {
                cameraMovementDetector = value;
                if (value == null)
                {
                    return;
                }
                CameraMovementDetector.NewImage += OnNewImage;
                cameraMovementDetector.NewVectors += OnNewVectors;
            }
        }

        private void OnNewVectors(object sender, EventArgs e)
        {
            outportVectors.Write(CameraMovementDetector.Vectors);
        }

        private void OnNewImage(object sender, EventArgs e)
        {
            outportCamera.Write(CameraMovementDetector.Image);
        }

        protected override ReturnCode_t OnActivated(int execHandle)
        {
            inport.OnWrite += OnWrite;
            return base.OnActivated(execHandle);
        }

        private void OnWrite(CameraImage image)
        {
            CameraMovementDetector.ProcessImage(image);
        }

        protected override ReturnCode_t OnDeactivated(int execHandle)
        {
            inport.OnWrite -= OnWrite;
            return base.OnDeactivated(execHandle);
        }
    }
}


text:
import React from 'react';
import NotFound from './NotFound';

const title = 'Page Not Found';

export default {

  path: '(.*)',

  action() {
    return {
      title,
      component: <NotFound title={title} />,
      status: 404,
    };
  },

};


text:
package com.google.cloud.vmmigration.v1.samples;

// [START vmmigration_v1_generated_vmmigrationclient_createtargetproject_async]
import com.google.api.core.ApiFuture;
import com.google.cloud.vmmigration.v1.CreateTargetProjectRequest;
import com.google.cloud.vmmigration.v1.LocationName;
import com.google.cloud.vmmigration.v1.TargetProject;
import com.google.cloud.vmmigration.v1.VmMigrationClient;
import com.google.longrunning.Operation;

public class AsyncCreateTargetProject {

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

  public static void asyncCreateTargetProject() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (VmMigrationClient vmMigrationClient = VmMigrationClient.create()) {
      CreateTargetProjectRequest request =
          CreateTargetProjectRequest.newBuilder()
              .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
              .setTargetProjectId("targetProjectId1290130307")
              .setTargetProject(TargetProject.newBuilder().build())
              .setRequestId("requestId693933066")
              .build();
      ApiFuture<Operation> future =
          vmMigrationClient.createTargetProjectCallable().futureCall(request);
      // Do something.
      Operation response = future.get();
    }
  }
}
// [END vmmigration_v1_generated_vmmigrationclient_createtargetproject_async]


text:
const BASE_URL = '/api/'; // normal baseURL
// const BASE_URL = 'http://localhost:3013/api/'; // testing purposes

export default BASE_URL;


text:
package integration

import (
	"encoding/json"
	"fmt"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	computebeta "google.golang.org/api/compute/v0.beta"
	"google.golang.org/api/compute/v1"
)

var _ = Describe("VM", func() {
	It("creates a VM with an invalid configuration and receives an error message with logs", func() {
		request := fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				  "machine_type": "n1-standard-error"
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v"
					}
				  }
				},
				[],
				{}
			  ]
			}`, existingStemcell, networkName)
		resp, err := execCPI(request)
		Expect(err).ToNot(HaveOccurred())
		Expect(resp.Error.Message).ToNot(BeEmpty())
		Expect(resp.Log).ToNot(BeEmpty())
	})

	It("executes the VM lifecycle", func() {
		var vmCID string
		By("creating a VM")
		request := fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				  "machine_type": "n1-standard-1",
				  "zone": "%v"
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v"
					}
				  }
				},
				[],
				{
				  "bosh": {
					  "group_name": "micro-google-dummy-dummy",
					  "groups": ["micro-google", "dummy", "dummy", "micro-google-dummy", "dummy-dummy", "micro-google-dummy-dummy-too-long-and-should-be-truncated-to-an-acceptable-length"]
				  }
				}
			  ]
			}`, existingStemcell, zone, networkName)
		vmCID = assertSucceedsWithResult(request).(string)

		By("locating the VM")
		request = fmt.Sprintf(`{
			  "method": "has_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		exists := assertSucceedsWithResult(request).(bool)
		Expect(exists).To(Equal(true))

		By("setting the VM's metadata")
		m := map[string]string{
			"director":           "val-that-is-definitely-for-sure-absolutely-longer-than-the-allowable-enforced-63-char-limit-and-should-be-truncated",
			"name":               "val_with_underscores_ending_in_dash-",
			"deployment":         "deployment-name",
			"job":                "job-name",
			"index":              "0",
			"integration-delete": "",
		}
		expectLabels := map[string]string{
			"director":           "val-that-is-definitely-for-sure-absolutely-longer-than-the-al",
			"name":               "val-with-underscores-ending-in-dash",
			"deployment":         "deployment-name",
			"job":                "job-name",
			"index":              "n0",
			"integration-delete": "",
			"micro-google":       "",
			"dummy":              "",
			"micro-google-dummy": "",
			"dummy-dummy":        "",
			"micro-google-dummy-dummy-too-long-and-should-be-truncated-to": "",
		}
		mj, _ := json.Marshal(m)
		request = fmt.Sprintf(`{
			  "method": "set_vm_metadata",
			  "arguments": [
				"%v",
				%v
			  ]
			}`, vmCID, string(mj))
		assertSucceeds(request)
		assertValidVMB(vmCID, func(instance *computebeta.Instance) {
			// Labels should be an exact match
			Expect(instance.Labels).To(BeEquivalentTo(expectLabels))
		})

		By("rebooting the VM")
		request = fmt.Sprintf(`{
			  "method": "reboot_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		assertSucceeds(request)

		By("deleting the VM")
		request = fmt.Sprintf(`{
			  "method": "delete_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		assertSucceeds(request)

	})

	It("can create a VM with tags", func() {
		By("creating a VM")
		var vmCID string
		request := fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				   "machine_type": "n1-standard-1",
					"zone": "%v",
				   "tags": ["tag1", "tag2"]
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v"
					}
				  }
				},
				[],
				{}
			  ]
			}`, existingStemcell, zone, networkName)
		vmCID = assertSucceedsWithResult(request).(string)
		assertValidVM(vmCID, func(instance *compute.Instance) {
			Expect(instance.Tags.Items).To(ConsistOf("integration-delete", "tag1", "tag2"))
		})

		By("deleting the VM")
		request = fmt.Sprintf(`{
			  "method": "delete_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		assertSucceeds(request)
	})

	It("can create a VM with overlapping VM and network tags and VM properties that override network properties", func() {
		By("creating a VM")
		var vmCID string
		request := fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				   "machine_type": "n1-standard-1",
				   "zone": "%v",
				   "tags": ["tag1", "tag2", "integration-delete"],
				   "ephemeral_external_ip": false,
				   "ip_forwarding": false
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v",
					  "ephemeral_external_ip": true,
					  "ip_forwarding": true
					}
				  }
				},
				[],
				{}
			  ]
			}`, existingStemcell, zone, networkName)
		vmCID = assertSucceedsWithResult(request).(string)
		assertValidVM(vmCID, func(instance *compute.Instance) {
			Expect(instance.Tags.Items).To(ConsistOf("integration-delete", "tag1", "tag2"))
			Expect(instance.CanIpForward).To(Equal(false))
			Expect(instance.NetworkInterfaces[0].AccessConfigs).To(BeEmpty())
		})

		By("deleting the VM")
		request = fmt.Sprintf(`{
			  "method": "delete_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		assertSucceeds(request)
	})

	It("can create a VM with a public IP in a network with public IPs disabled ", func() {
		By("creating a VM")
		var vmCID string
		request := fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				   "machine_type": "n1-standard-1",
				   "zone": "%v",
				   "tags": ["tag1", "tag2", "integration-delete"],
				   "ephemeral_external_ip": true,
				   "ip_forwarding": false
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v",
					  "ephemeral_external_ip": false,
					  "ip_forwarding": true
					}
				  }
				},
				[],
				{}
			  ]
			}`, existingStemcell, zone, networkName)
		vmCID = assertSucceedsWithResult(request).(string)
		assertValidVM(vmCID, func(instance *compute.Instance) {
			Expect(instance.Tags.Items).To(ConsistOf("integration-delete", "tag1", "tag2"))
			Expect(instance.CanIpForward).To(Equal(false))
			Expect(instance.NetworkInterfaces[0].AccessConfigs[0].Name).ToNot(BeEmpty())
		})

		By("deleting the VM")
		request = fmt.Sprintf(`{
			  "method": "delete_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		assertSucceeds(request)
	})
	It("executes the VM lifecycle with disk attachment hints", func() {
		By("creating two disks")
		var request, diskCID, diskCID2, vmCID string
		request = fmt.Sprintf(`{
			  "method": "create_disk",
			  "arguments": [32768, {"zone": "%v"}, ""]
			}`, zone)
		diskCID = assertSucceedsWithResult(request).(string)
		diskCID2 = assertSucceedsWithResult(request).(string)

		By("creating a VM with the disk attachment hints")
		request = fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				  "machine_type": "n1-standard-1",
				  "zone": "%v"
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v"
					}
				  }
				},
				["%v", "%v"],
				{}
			  ]
			}`, existingStemcell, zone, networkName, diskCID, diskCID2)
		vmCID = assertSucceedsWithResult(request).(string)

		By("deleting the disks")
		request = fmt.Sprintf(`{
			  "method": "delete_disk",
			  "arguments": ["%v"]
			}`, diskCID)
		assertSucceeds(request)

		request = fmt.Sprintf(`{
			  "method": "delete_disk",
			  "arguments": ["%v"]
			}`, diskCID2)
		assertSucceeds(request)

		By("deleting the VM")
		request = fmt.Sprintf(`{
			  "method": "delete_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		assertSucceeds(request)
	})

	It("executes the VM lifecycle with custom machine type", func() {
		By("creating a VM")
		var vmCID string
		request := fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				  "cpu": 2,
				  "ram": 5120,
				  "zone": "%v"
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v"
					}
				  }
				},
				[],
				{}
			  ]
			}`, existingStemcell, zone, networkName)
		vmCID = assertSucceedsWithResult(request).(string)

		By("deleting the VM")
		request = fmt.Sprintf(`{
			  "method": "delete_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		assertSucceeds(request)
	})

	It("executes the VM lifecycle in a specific zone", func() {
		By("creating a VM")
		var vmCID string

		request := fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				  "machine_type": "n1-standard-1",
				  "zone": "%v"
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v"
					}
				  }
				},
				[],
				{}
			  ]
			}`, existingStemcell, zone, networkName)
		vmCID = assertSucceedsWithResult(request).(string)

		By("deleting the VM")
		request = fmt.Sprintf(`{
			  "method": "delete_vm",
			  "arguments": ["%v"]
			}`, vmCID)
	})

	It("executes the VM lifecycle with automatic restart disabled", func() {
		By("creating a VM")
		var vmCID string
		request := fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				  "machine_type": "n1-standard-1",
				  "zone": "%v",
				  "automatic_restart": false
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v"
					}
				  }
				},
				[],
				{}
			  ]
			}`, existingStemcell, zone, networkName)
		vmCID = assertSucceedsWithResult(request).(string)

		By("deleting the VM")
		request = fmt.Sprintf(`{
			  "method": "delete_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		assertSucceeds(request)
	})

	It("execute the VM lifecycle with OnHostMaintenance modified", func() {
		By("creating a VM")
		var vmCID string

		request := fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				  "machine_type": "n1-standard-1",
				  "zone": "%v",
				  "on_host_maintenance": "TERMINATE"
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v"
					}
				  }
				},
				[],
				{}
			  ]
			}`, existingStemcell, zone, networkName)

		By("deleting the VM")
		vmCID = assertSucceedsWithResult(request).(string)
		request = fmt.Sprintf(`{
			  "method": "delete_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		assertSucceeds(request)
	})

	It("can execute the VM lifecycle with a preemptible VM", func() {
		By("creating a VM")
		var vmCID string

		request := fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				  "machine_type": "n1-standard-1",
				  "zone": "%v",
				  "preemtible": true
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v"
					}
				  }
				},
				[],
				{}
			  ]
			}`, existingStemcell, zone, networkName)
		vmCID = assertSucceedsWithResult(request).(string)

		By("deleting the VM")
		request = fmt.Sprintf(`{
			  "method": "delete_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		assertSucceeds(request)
	})

	var vmCID string
	It("executes the VM lifecycle with default service scopes and no service account", func() {
		By("creating a VM")
		request := fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				  "machine_type": "n1-standard-1",
				  "zone": "%v",
				  "service_scopes": ["cloud-platform", "devstorage.read_write"]
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v"
					}
				  }
				},
				[],
				{}
			  ]
			}`, existingStemcell, zone, networkName)
		vmCID = assertSucceedsWithResult(request).(string)
		assertValidVM(vmCID, func(instance *compute.Instance) {
			// Labels should be an exact match
			Expect(instance.ServiceAccounts[0].Scopes).To(Not(BeEmpty()))
		})

		By("deleting the VM")
		request = fmt.Sprintf(`{
			  "method": "delete_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		assertSucceeds(request)
	})

	It("executes the VM lifecycle with a custom service account and scopes", func() {
		By("creating a VM")
		var vmCID string
		request := fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				  "machine_type": "n1-standard-1",
				  "zone": "%v",
				  "service_account": "%v",
				  "service_scopes": ["devstorage.read_write"]
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v"
					}
				  }
				},
				[],
				{}
			  ]
			}`, existingStemcell, zone, serviceAccount, networkName)
		vmCID = assertSucceedsWithResult(request).(string)
		assertValidVM(vmCID, func(instance *compute.Instance) {
			// Labels should be an exact match
			Expect(instance.ServiceAccounts[0].Scopes).To(Not(BeEmpty()))
			Expect(instance.ServiceAccounts[0].Email).To(Equal(serviceAccount))
		})

		By("deleting the VM")
		request = fmt.Sprintf(`{
			  "method": "delete_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		assertSucceeds(request)
	})

	It("executes the VM lifecycle with a custom service account and no scopes", func() {
		By("creating a VM")
		var vmCID string
		request := fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				  "machine_type": "n1-standard-1",
				  "zone": "%v",
				  "service_account": "%v"
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v"
					}
				  }
				},
				[],
				{}
			  ]
			}`, existingStemcell, zone, serviceAccount, networkName)
		vmCID = assertSucceedsWithResult(request).(string)
		assertValidVM(vmCID, func(instance *compute.Instance) {
			// Labels should be an exact match
			Expect(instance.ServiceAccounts[0].Scopes).To(Not(BeEmpty()))
			Expect(instance.ServiceAccounts[0].Email).To(Equal(serviceAccount))
		})

		By("deleting the VM")
		request = fmt.Sprintf(`{
			  "method": "delete_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		assertSucceeds(request)
	})

	It("executes the VM lifecycle with a backend service", func() {
		justInstances := func(ig *compute.InstanceGroupsListInstances) []string {
			instances := make([]string, len(ig.Items))
			for _, i := range ig.Items {
				instances = append(instances, i.Instance)
			}
			return instances
		}
		By("creating a VM")
		var vmCID string
		request := fmt.Sprintf(`{
			  "method": "create_vm",
			  "arguments": [
				"agent",
				"%v",
				{
				  "machine_type": "n1-standard-1",
				  "zone": "%v",
				  "backend_service": "%v"
				},
				{
				  "default": {
					"type": "dynamic",
					"cloud_properties": {
					  "tags": ["integration-delete"],
					  "network_name": "%v"
					}
				  }
				},
				[],
				{}
			  ]
			}`, existingStemcell, zone, backendService, networkName)
		vmCID = assertSucceedsWithResult(request).(string)

		ig, err := computeService.InstanceGroups.ListInstances(googleProject, zone, instanceGroup, &compute.InstanceGroupsListInstancesRequest{InstanceState: "RUNNING"}).Do()
		Expect(err).ToNot(HaveOccurred())
		Expect(justInstances(ig)).To(ContainElement(ContainSubstring(vmCID)))

		By("deleting the VM and confirming its removal from backend service instance group")
		toggleAsyncDelete()
		request = fmt.Sprintf(`{
			  "method": "delete_vm",
			  "arguments": ["%v"]
			}`, vmCID)
		assertSucceeds(request)
		toggleAsyncDelete()
		ig, err = computeService.InstanceGroups.ListInstances(googleProject, zone, instanceGroup, &compute.InstanceGroupsListInstancesRequest{InstanceState: "RUNNING"}).Do()
		Expect(err).ToNot(HaveOccurred())
		Expect(justInstances(ig)).ToNot(ContainElement(ContainSubstring(vmCID)))
	})

})


text:
package org.spongepowered.common.world.gen;

import static com.google.common.base.Preconditions.checkNotNull;

import com.flowpowered.math.vector.Vector2i;
import net.minecraft.block.BlockFalling;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.util.BlockPos;
import net.minecraft.util.IProgressUpdate;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.biome.BiomeGenBase.SpawnListEntry;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ChunkPrimer;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.ChunkProviderGenerate;
import org.spongepowered.api.world.extent.ImmutableBiomeArea;
import org.spongepowered.api.world.extent.MutableBlockVolume;
import org.spongepowered.api.world.gen.BiomeGenerator;
import org.spongepowered.api.world.gen.GeneratorPopulator;
import org.spongepowered.common.util.gen.ByteArrayMutableBiomeBuffer;
import org.spongepowered.common.util.gen.ChunkPrimerBuffer;

import java.util.List;
import java.util.Random;

/**
 * Similar class to {@link ChunkProviderGenerate}, but instead gets its blocks
 * from a custom chunk generator.
 */
public final class CustomChunkProviderGenerate implements IChunkProvider {

    private static final Vector2i CHUNK_AREA = new Vector2i(16, 16);

    private final BiomeGenerator biomeGenerator;
    private final GeneratorPopulator baseGenerator;
    private final List<GeneratorPopulator> generatorPopulators;
    private final World world;
    private final ByteArrayMutableBiomeBuffer cachedBiomes;

    /**
     * Gets the chunk generator from the given generator populator and biome
     * generator.
     *
     * @param world The world to bind the chunk provider to.
     * @param biomeGenerator Biome generator used to generate chunks.
     * @param baseGenerator The base generator
     * @param generatorPopulators The generator populators
     * @return The chunk generator.
     * @throws IllegalArgumentException If the generator populator cannot be
     *         bound to the given world.
     */
    public static IChunkProvider of(World world, BiomeGenerator biomeGenerator, GeneratorPopulator baseGenerator,
        List<GeneratorPopulator> generatorPopulators) {
        if (baseGenerator instanceof SpongeGeneratorPopulator) {
            // Unwrap instead of wrap
            return ((SpongeGeneratorPopulator) baseGenerator).getHandle(world);
        }
        // Wrap a custom GeneratorPopulator implementation
        return new CustomChunkProviderGenerate(world, biomeGenerator, baseGenerator, generatorPopulators);
    }

    private CustomChunkProviderGenerate(World world, BiomeGenerator biomeGenerator, GeneratorPopulator baseGenerator,
        List<GeneratorPopulator> generatorPopulators) {
        this.world = checkNotNull(world, "world");
        this.baseGenerator = checkNotNull(baseGenerator, "baseGenerator");
        this.biomeGenerator = checkNotNull(biomeGenerator, "biomeGenerator");
        this.generatorPopulators = checkNotNull(generatorPopulators, "generatorPopulators");

        // Make initially empty biome cache
        this.cachedBiomes = new ByteArrayMutableBiomeBuffer(Vector2i.ZERO, CHUNK_AREA);
        this.cachedBiomes.detach();
    }

    public GeneratorPopulator getBaseGenerator() {
        return this.baseGenerator;
    }

    @Override
    public void populate(IChunkProvider chunkProvider, int chunkX, int chunkZ) {
        Random random = new Random(chunkX * 341873128712L + chunkZ * 132897987541L);
        BlockFalling.fallInstantly = true;

        // Calling the events makes the Sponge-added populators fire
        // TODO Deamon says he'll figure this one out soon

        BlockFalling.fallInstantly = false;
    }

    @Override
    public boolean func_177460_a(IChunkProvider chunkProvider, Chunk chunk, int chunkX, int chunkZ) {
        // This method normally places ocean monuments in existing chunks
        return false;
    }

    @Override
    public List<SpawnListEntry> getPossibleCreatures(EnumCreatureType creatureType, BlockPos pos) {
        BiomeGenBase biome = this.world.getBiomeGenForCoords(pos);
        @SuppressWarnings("unchecked")
        List<SpawnListEntry> creatures = biome.getSpawnableList(creatureType);
        return creatures;
    }

    @Override
    public BlockPos getStrongholdGen(World worldIn, String structureName, BlockPos position) {
        // Maybe allow to register stronghold locations?
        return null;
    }

    @Override
    public void recreateStructures(Chunk chunk, int chunkX, int chunkZ) {
        // No structure support
    }

    @Override
    public Chunk provideChunk(int chunkX, int chunkZ) {

        // Generate biomes
        this.cachedBiomes.reuse(new Vector2i(chunkX << 4, chunkZ << 4));
        this.biomeGenerator.generateBiomes(this.cachedBiomes);

        // Generate base terrain
        ChunkPrimer chunkprimer = new ChunkPrimer();
        MutableBlockVolume blockBuffer = new ChunkPrimerBuffer(chunkprimer, chunkX, chunkZ);
        ImmutableBiomeArea biomeBuffer = this.cachedBiomes.getImmutableBiomeCopy();
        this.baseGenerator.populate((org.spongepowered.api.world.World) this.world, blockBuffer, biomeBuffer);

        // Apply the generator populators to complete the blockBuffer
        for (GeneratorPopulator populator : this.generatorPopulators) {
            populator.populate((org.spongepowered.api.world.World) this.world, blockBuffer, biomeBuffer);
        }

        // Assemble chunk
        Chunk chunk = new Chunk(this.world, chunkprimer, chunkX, chunkZ);
        byte[] biomeArray = chunk.getBiomeArray();
        System.arraycopy(this.cachedBiomes.detach(), 0, biomeArray, 0, biomeArray.length);
        chunk.generateSkylightMap();

        return chunk;
    }

    // Methods below are simply mirrors of the methods in ChunkProviderGenerate

    @Override
    public Chunk provideChunk(BlockPos blockPosIn) {
        return provideChunk(blockPosIn.getX() >> 4, blockPosIn.getZ() >> 4);
    }

    @Override
    public int getLoadedChunkCount() {
        return 0;
    }

    @Override
    public String makeString() {
        return "RandomLevelSource";
    }

    @Override
    public boolean canSave() {
        return true;
    }

    @Override
    public boolean saveChunks(boolean bool, IProgressUpdate progressUpdate) {
        return true;
    }

    @Override
    public void saveExtraData() {
    }

    @Override
    public boolean unloadQueuedChunks() {
        return false;
    }

    @Override
    public boolean chunkExists(int x, int z) {
        return true;
    }

}


text: An app that presents a grid of the most popular and highest rated movies


text:
export * from './page-summary-alert';
export * from './page-summary-content';
export * from './page-summary-image';
export * from './page-summary-key-info';
export * from './page-summary-status';
export * from './page-summary-subtitle';
export * from './page-summary-title';
export * from './page-summary.component';
export * from './page-summary.module';


text:
/**
 * \file
 * \brief x86-32 interrupt/exception handling utility functions
 */

/*
 * Copyright (c) 2007, 2008, 2009, 2010, 2011, ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
 */

/*********************************************************************
 *
 * Copyright (C) 2003-2004,  Karlsruhe University
 *
 * File path:     glue/v4-amd64/hwirq.h
 * Description:   Macros to define interrupt handler stubs for AMD64
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $Id: hwirq.h,v 1.3 2006/10/19 22:57:35 ud3 Exp $
 *
 ********************************************************************/

#include <kernel.h>
#include <stdio.h>
#include <string.h>
#include <irq.h>
#include <gdb_stub.h>
#include <x86.h>
#include <dispatch.h>
#include <wakeup.h>
#include <pic.h>
#include <arch/x86/apic.h>
#include <barrelfish_kpi/dispatcher_shared_target.h>
#include <asmoffsets.h>
#include <trace/trace.h>
#include <exec.h>
#ifdef __scc__
#       include <rck.h>
#else
#       include <arch/x86/ipi_notify.h>
#endif
#include <arch/x86/timing.h>
#include <arch/x86/syscall.h>
#include <barrelfish_kpi/cpu_arch.h>

#ifdef FPU_LAZY_CONTEXT_SWITCH
#  include <fpu.h>
#endif

/**
 * \brief Define IRQ handler number 'num'.
 *
 * This defines an interrupt handler for vector #num. The way this is done is
 * quite tricky: A block of assembly is emitted, with a label pointing to
 * the beginning of that block. The label is made known as a symbol by
 * having a C function _declaration_ directly in front of the block. The
 * symbol has to be defined extern, so it is global, but its ELF visibility
 * is set "hidden", so that the symbol does not end up in the GOT. This is
 * very important for keeping the code position-independent.
 *
 * The NOERR/ERR variants depend on whether the hardware delivers an error code.
 */
#define HW_EXCEPTION_NOERR(num)                                         \
    void __attribute__ ((visibility ("hidden"))) hwexc_##num(void);     \
    __asm (                                                             \
           "\t.text                                        \n\t"        \
           "\t.type hwexc_"#num",@function                 \n\t"        \
           "hwexc_"#num":                                  \n\t"        \
           "pushl $0                /* dummy error code */ \n\t"        \
           "pushl $"#num"           /* vector number */    \n\t"        \
           "jmp    hwexc_common     /* common stuff */     \n\t"        \
                                                                        )

#define HW_EXCEPTION_ERR(num)                                           \
    void __attribute__ ((visibility ("hidden"))) hwexc_##num(void);     \
    __asm (                                                             \
           "\t.text                                        \n\t"        \
           "\t.type hwexc_"#num",@function                 \n\t"        \
           "hwexc_"#num":                                  \n\t"        \
           "pushl $"#num"           /* vector number */    \n\t"        \
           "jmp    hwexc_common     /* common stuff */     \n\t"        \
                                                                        )

#define XHW_IRQ(num)                                                    \
    void __attribute__ ((visibility ("hidden"))) hwirq_##num(void);     \
    __asm (                                                             \
           "\t.text                                        \n\t"        \
           "\t.type hwirq_"#num",@function                 \n\t"        \
           "hwirq_"#num":                                  \n\t"        \
           "pushl $"#num"           /* vector number */    \n\t"        \
           "jmp    hwirq_common     /* common stuff */     \n\t"        \
                                                                        )
/// Noop wrapper for HW_IRQ to deal with CPP stringification problems
#define HW_IRQ(num) XHW_IRQ(num)

#define STR(x) #x
#define XTR(x) STR(x)

__asm (
    ".text                                              \n\t"
    "   .type hwexc_common ,@function                   \n\t"
    "hwexc_common:                                      \n\t"
    "testb $3, 12(%esp) /* if CS.CPL == 0 */            \n\t"
    "jz kernel_fault                                    \n\t"

    /* User exception: save full state and return to the user.
     * This path could be optimized by only saving the non-volatile
     * registers (since the kernel's C path will maintain them), and
     * having the user-mode code save them if needed. Since the
     * current user code always does need them, we just save the full
     * set here. */

    /* decide where to save the state, the options are:
     *    pagefault and enabled -> enabled save area
     *    pagefault while disabled or any other trap -> trap save area
     */
    "pushl %ecx                                         \n\t"
    "call __i686.get_pc_thunk.cx                        \n\t"
    "addl $_GLOBAL_OFFSET_TABLE_, %ecx                  \n\t"
    "movl dcb_current@GOTOFF(%ecx), %ecx /* ecx = dcb_current */       \n\t"
    "movl "XTR(OFFSETOF_DCB_DISP)"(%ecx), %ecx /* ecx = dcb_current->disp */\n\t"
    "cmpl $14, 4(%esp)       /* is pagefault? */        \n\t"
    "jne save_trap                                      \n\t"
    "cmpl $0, "XTR(OFFSETOF_DISP_DISABLED)"(%ecx) /* disp->disabled ? */\n\t"
    "jne save_trap                                      \n\t"
    "pushl %ebx                                         \n\t"
    "movl 4*4(%esp), %ebx     /* ebx = faulting IP */   \n\t"
    "cmpl "XTR(OFFSETOF_DISP_X86_32_CRIT_PC_LOW)"(%ecx), %ebx /* crit_pc_low <= rip? */\n\t"
    "jae disabled_test                                  \n\t"
    "\nsave_enabled:                                    \n\t"
    "popl %ebx                                          \n\t"
    "addl $"XTR(OFFSETOF_DISP_X86_32_ENABLED_AREA)", %ecx /* ecx = enabled_save_area */\n\t"
    "jmp do_save                                        \n\t"
    "\ndisabled_test:                                   \n\t"
    "cmpl "XTR(OFFSETOF_DISP_X86_32_CRIT_PC_HIGH)"(%ecx), %ebx /* crit_pc_high > rip? */\n\t"
    "jae save_enabled                                   \n\t"
    "popl %ebx                                          \n\t"
    "\nsave_trap:                                       \n\t"
    "addl $"XTR(OFFSETOF_DISP_X86_32_TRAP_AREA)", %ecx /* trap_save_area */\n\t"

    /* save to the save area. at this point, ecx = save area ptr,
     * esp+8 = exception num, esp+16 = CPU-stacked error and registers */
    "\ndo_save:                                         \n\t"
    "movl %eax,  0*4(%ecx)                              \n\t"
    "popl %eax                    /* original ecx */    \n\t"
    "movl %ebx,  1*4(%ecx)                              \n\t"
    "movl %eax,  2*4(%ecx)                              \n\t"
    "movl %edx,  3*4(%ecx)                              \n\t"
    "movl %esi,  4*4(%ecx)                              \n\t"
    "movl %edi,  5*4(%ecx)                              \n\t"
    "movl %ebp,  6*4(%ecx)                              \n\t"
    "mov %fs, "XTR(OFFSETOF_FS_REG)"(%ecx)              \n\t"
    "mov %gs, "XTR(OFFSETOF_GS_REG)"(%ecx)              \n\t"
    "pushl %ecx                                         \n\t"
    "lea 3*4(%esp), %ecx                                \n\t"
    "pushl %ecx                                         \n\t"
    "calll generic_handle_user_exception                \n\t"
    /* Get all the function arguments off the stack again */
    "addl $4*4, %esp                                    \n\t"
    // Load disp->udisp into EDI
    "call __i686.get_pc_thunk.di                        \n\t"
    "addl $_GLOBAL_OFFSET_TABLE_, %edi                  \n\t"
    "movl dcb_current@GOTOFF(%edi), %edi /* edi = dcb_current */       \n\t"
    "movl "XTR(OFFSETOF_DCB_DISP)"(%edi), %edi /* edi = dcb_current->disp */\n\t"
    "movl "XTR(OFFSETOF_DISP_UDISP)"(%edi), %edi /* edi = disp->udisp */\n\t"
    "iretl                                              \n\t"

    /* a kernel fault means something bad happened, so we stack
     * everything for the debugger to use, in the GDB frame format */
    "\nkernel_fault:                                    \n\t"
    "pushl $0x10     /* SS */                           \n\t"
    "pushl 4*4(%esp) /* CS */                           \n\t"
    "pushl 6*4(%esp) /* EFLAGS */                       \n\t"
    "pushl 5*4(%esp) /* EIP */                          \n\t"
    "pushl %esp      /* ESP */                          \n\t"
    "pushl %ebp                                         \n\t"
    "pushl %edi                                         \n\t"
    "pushl %esi                                         \n\t"
    "pushl %edx                                         \n\t"
    "pushl %ecx                                         \n\t"
    "pushl %ebx                                         \n\t"
    "pushl %eax                                         \n\t"
    "pushl %esp              /* save area ptr*/         \n\t"
    "pushl 14*4(%esp)        /* error code   */         \n\t"
    "pushl 14*4(%esp)        /* vector number */        \n\t"
    "call generic_handle_kernel_exception               \n\t"

    /* (Device) interrupt. */
    "   .type hwirq_common ,@function                   \n\t"
    "hwirq_common:                                      \n\t"
    /* If happened in kernel_mode, simply make userspace runnable */
    "testb $3, 8(%esp)  /* if CS.CPL == 0 */            \n\t"
    "jz call_handle_irq                                 \n\t"

    /* Happened in user mode.
     * we need to save everything to the dispatcher. */
    /* decide where to save the state, either enabled or disabled save areas */
    "pushl %edx                                         \n\t"
    "call __i686.get_pc_thunk.dx                        \n\t"
    "addl $_GLOBAL_OFFSET_TABLE_, %edx                  \n\t"
    "movl dcb_current@GOTOFF(%edx), %edx /* edx = dcb_current */       \n\t"
    "movl "XTR(OFFSETOF_DCB_DISP)"(%edx), %edx /* edx = dcb_current->disp */\n\t"
    "cmpl $0, "XTR(OFFSETOF_DISP_DISABLED)"(%edx) /* disp->disabled ? */\n\t"
    "jne irq_save_disabled                              \n\t"
    "pushl %ebx                                         \n\t"
    "movl 3*4(%esp), %ebx     /* ebx = faulting IP */   \n\t"
    "cmpl "XTR(OFFSETOF_DISP_X86_32_CRIT_PC_LOW)"(%edx), %ebx /* crit_pc_low <= rip? */\n\t"
    "jae irq_disabled_test                              \n\t"
    "\nirq_save_enabled:                                \n\t"
    "popl %ebx                                          \n\t"
    "addl $"XTR(OFFSETOF_DISP_X86_32_ENABLED_AREA)", %edx /* edx = enabled_save_area */\n\t"
    "jmp irq_do_save                                    \n\t"
    "\nirq_disabled_test:                               \n\t"
    "cmpl "XTR(OFFSETOF_DISP_X86_32_CRIT_PC_HIGH)"(%edx), %ebx /* crit_pc_high > rip? */\n\t"
    "jae irq_save_enabled                               \n\t"
    "popl %ebx                                          \n\t"
    "\nirq_save_disabled:                               \n\t"
    "addl $"XTR(OFFSETOF_DISP_X86_32_DISABLED_AREA)", %edx /* disabled_save_area */\n\t"

    /* save to the save area. at this point, edx = save area ptr,
     * esp+8 = vector number, esp+12 = CPU-stacked regisers */
    "\nirq_do_save:                                     \n\t"
    "movl %eax,  0*4(%edx)                              \n\t"
    "movl %ebx,  1*4(%edx)                              \n\t"
    "movl %ecx,  2*4(%edx)                              \n\t"
    "popl %eax                    /* original edx */    \n\t"
    "movl %eax,  3*4(%edx)                              \n\t"
    "movl %esi,  4*4(%edx)                              \n\t"
    "movl %edi,  5*4(%edx)                              \n\t"
    "movl %ebp,  6*4(%edx)                              \n\t"
    "mov %fs, "XTR(OFFSETOF_FS_REG)"(%edx)              \n\t"
    "mov %gs, "XTR(OFFSETOF_GS_REG)"(%edx)              \n\t"
    "lea 4(%esp), %esi            /* CPU save area */   \n\t"
    "pushl %esi                                         \n\t"
    "pushl %edx                                         \n\t"
    "calll generic_handle_irq /* NB: edx = disp save ptr*/\n\t"

    "\ncall_handle_irq:                                 \n\t"
    "calll handle_irq                                   \n\t"
);

// CPU exceptions
HW_EXCEPTION_NOERR(0);
HW_EXCEPTION_NOERR(1);
HW_EXCEPTION_NOERR(2);
HW_EXCEPTION_NOERR(3);
HW_EXCEPTION_NOERR(4);
HW_EXCEPTION_NOERR(5);
HW_EXCEPTION_NOERR(6);
HW_EXCEPTION_NOERR(7);
HW_EXCEPTION_ERR(8);
HW_EXCEPTION_NOERR(9);
HW_EXCEPTION_ERR(10);
HW_EXCEPTION_ERR(11);
HW_EXCEPTION_ERR(12);
HW_EXCEPTION_ERR(13);
HW_EXCEPTION_ERR(14);
HW_EXCEPTION_NOERR(16);
HW_EXCEPTION_ERR(17);
HW_EXCEPTION_NOERR(18);
HW_EXCEPTION_NOERR(19);

// Classic PIC interrupts
HW_IRQ(32);
HW_IRQ(33);
HW_IRQ(34);
HW_IRQ(35);
HW_IRQ(36);
HW_IRQ(37);
HW_IRQ(38);
HW_IRQ(39);
HW_IRQ(40);
HW_IRQ(41);
HW_IRQ(42);
HW_IRQ(43);
HW_IRQ(44);
HW_IRQ(45);
HW_IRQ(46);
HW_IRQ(47);

// Generic interrupts
HW_IRQ(48);
HW_IRQ(49);
HW_IRQ(50);
HW_IRQ(51);
HW_IRQ(52);
HW_IRQ(53);
HW_IRQ(54);
HW_IRQ(55);
HW_IRQ(56);
HW_IRQ(57);
HW_IRQ(58);
HW_IRQ(59);
HW_IRQ(60);
HW_IRQ(61);

// Trace IPIs
HW_IRQ(62);
HW_IRQ(63);

// Local APIC interrupts
HW_IRQ(249);
HW_IRQ(250);
HW_IRQ(251);
HW_IRQ(252);
HW_IRQ(253);
HW_IRQ(254);

// Reserved as "unhandled exception" handler
HW_EXCEPTION_NOERR(666);

#define ERR_PF_PRESENT          (1 << 0)
#define ERR_PF_READ_WRITE       (1 << 1)
#define ERR_PF_USER_SUPERVISOR  (1 << 2)
#define ERR_PF_RESERVED         (1 << 3)
#define ERR_PF_INSTRUCTION      (1 << 4)

/// Number of (reserved) hardware exceptions
#define NEXCEPTIONS             32

/// Size of hardware IRQ dispatch table == #NIDT - #NEXCEPTIONS exceptions
#define NDISPATCH               (NIDT - NEXCEPTIONS)

/**
 * \brief Interrupt Descriptor Table (IDT) for processor this kernel is running
 * on.
 */
static struct gate_descriptor idt[NIDT] __attribute__ ((aligned (16)));

/**
 * \brief User-space IRQ dispatch table.
 *
 * This is essentially a big CNode holding #NDISPATCH capability
 * entries to local endpoints of user-space applications listening to
 * the interrupts.
 */
static struct cte irq_dispatch[NDISPATCH];

/// System call entry point
void syscall_entry(void);

/**
 * \brief Send interrupt notification to user-space listener.
 *
 * Sends an interrupt notification IDC to a local endpoint that
 * listens for IRQ notifications.
 *
 * \param irq   IRQ# to send in notification.
 */
static void send_user_interrupt(int irq)
{
    assert(irq >= 0 && irq < NDISPATCH);
    struct capability   *cap = &irq_dispatch[irq].cap;

    // Return on null cap (unhandled interrupt)
    if(cap->type == ObjType_Null) {
        printk(LOG_WARN, "unhandled IRQ %d\n", irq);
        return;
    }

    // Otherwise, cap needs to be an endpoint
    assert(cap->type == ObjType_EndPoint);
    errval_t err = lmp_deliver_notification(cap);
    if (err_is_fail(err)) {
        if (err_no(err) == SYS_ERR_LMP_BUF_OVERFLOW) {
            struct dispatcher_shared_generic *disp =
                get_dispatcher_shared_generic(cap->u.endpoint.listener->disp);
            printk(LOG_DEBUG, "%.*s: IRQ message buffer overflow\n",
                   DISP_NAME_LEN, disp->name);
        } else {
            printk(LOG_ERR, "Unexpected error delivering IRQ\n");
        }
    }

#ifdef SCHEDULER_RR
    /* XXX: run the handler dispatcher immediately
     * we shouldn't do this (we should let the scheduler decide), but because
     * our default scheduler is braindead, this is a quick hack to make sure
     * that mostly-sane things happen
     */
    dispatch(cap->u.endpoint.listener);
#else
    dispatch(schedule());
#endif
}

errval_t irq_table_set(unsigned int nidt, capaddr_t endpoint)
{
    errval_t err;
    struct cte *recv;

    err = caps_lookup_slot(&dcb_current->cspace.cap, endpoint,
                           CPTR_BITS, &recv, CAPRIGHTS_WRITE);
    if (err_is_fail(err)) {
        return err_push(err, SYS_ERR_IRQ_LOOKUP);
    }

    assert(recv != NULL);

    // Return w/error if cap is not an endpoint
    if(recv->cap.type != ObjType_EndPoint) {
        return SYS_ERR_IRQ_NOT_ENDPOINT;
    }

    // Return w/error if no listener on endpoint
    if(recv->cap.u.endpoint.listener == NULL) {
        return SYS_ERR_IRQ_NO_LISTENER;
    }

    if(nidt < NDISPATCH) {
        // check that we don't overwrite someone else's handler
        if (irq_dispatch[nidt].cap.type != ObjType_Null) {
            printf("kernel: installing new handler for IRQ %d\n", nidt);
        }
        err = caps_copy_to_cte(&irq_dispatch[nidt], recv, false, 0, 0);
#if 0
        if (err_is_ok(err)) {
            // Unmask interrupt if on PIC
            if(nidt < 16) {
                pic_toggle_irq(nidt, true);
            }
        }
#endif
        return err;
    } else {
        return SYS_ERR_IRQ_INVALID;
    }
}

errval_t irq_table_delete(unsigned int nidt)
{
    if(nidt < NDISPATCH) {
        irq_dispatch[nidt].cap.type = ObjType_Null;
#if 0
        pic_toggle_irq(nidt, false);
#endif
        return SYS_ERR_OK;
    } else {
        return SYS_ERR_IRQ_INVALID;
    }
}

/**
 * \brief Handles kernel exceptions
 *
 * \param vec   Vector number of exception
 * \param error Error code from CPU, or 0 for an exception without an error code
 * \param save_area Pointer to save area for registers stacked by trap handler
 */
static __attribute__ ((used,noreturn))
    void generic_handle_kernel_exception(int vec, uint32_t error,
                            struct registers_x86_32 *save_area)
{
    uintptr_t rip = save_area->eip;
    lvaddr_t fault_address;

    if (vec == 666) {
        panic("unhandled kernel exception");
    }

    assert(vec < NEXCEPTIONS);
    // CS.CPL == 0, ie. a kernel-mode fault
    assert((save_area->cs & 0x3) == 0);

    printk(LOG_PANIC, "exception %d (error code 0x%"PRIx32"): ", vec, error);

    switch(vec) {
    case 0:     // Divide Error (#DE)
        printf("divide error\n");
        break;
    case 1:     // Debug Exception (#DB)
        printf("debug exception\n");
        break;
    case 2:     // NMI Interrupt
        printf("NMI Interrupt\n");
        break;
    case 3:     // Breakpoint (#BP)
        printf("breakpoint\n");
        break;
    case 4:     // Overflow (#OF)
        printf("overflow\n");
        break;
    case 5:     // BOUND Range Exceeded (#BR)
        printf("BOUND Range Exceeded\n");
        break;
    case 6:     // Invalid Opcode (#UD)
        printf("invalid opcode\n");
        break;
    case 7:     // Device Not Available (#NM)
        printf("device not available\n");
        break;
    case 8:     // Double fault (#DF)
        printf("double fault\n");
        break;
    case 9:     // Coprocessor Segment Overrun
        printf("coprocessor segment overrun\n");
        break;
    case 10:    // Invalid TSS (#TS)
        printf("invalid TSS\n");
        break;
    case 11:    // Segment Not Present (#NP)
        printf("segment not present\n");
        break;
    case 12:    // Stack Fault (#SS)
        printf("stack fault\n");
        break;
    case 13:    // General Protection Fault (#GP)
        printf("general protection fault\n");
        break;
    case 14:    // Page Fault (#PF)
        printf("%s page fault due to %s%s, while in %s mode%s\n",
               error & ERR_PF_READ_WRITE ? "write" : "read",
               error & ERR_PF_PRESENT ? "access violation" : "page not present",
               error & ERR_PF_RESERVED ? ", reserved bits set in page table"
               : "",
               error & ERR_PF_USER_SUPERVISOR ? "user" : "supervisor",
               error & ERR_PF_INSTRUCTION ? ", by instruction fetch" : "");

        __asm volatile("mov %%cr2, %[fault_address]"
                       : [fault_address] "=r" (fault_address));
        printf("Address that caused the fault: 0x%"PRIxLVADDR"\n", fault_address);
        break;
    case 17:    // Alignment Check Exception (#AC)
        printf("alignment check exception\n");
        break;

    default:
        printf("unhandled exception!\n");
        break;
    }

    if(dcb_current != NULL) {
        dispatcher_handle_t handle = dcb_current->disp;
        struct dispatcher_shared_generic *disp =
            get_dispatcher_shared_generic(handle);

        printf("On behalf of: %.*s\n", DISP_NAME_LEN, disp->name);
    } else {
        printf("No active process\n");
    }

    // Print faulting instruction pointer
    printf("Faulting instruction pointer (or following instruction): "
           "0x%"PRIxPTR" (0x %"PRIxPTR" in binary)\n", rip,
           rip - (uintptr_t)&_start_kernel + X86_32_START_KERNEL_PHYS);

    // Print some important registers
    printf("EAX 0x%"PRIx32" EBX 0x%"PRIx32" ECX 0x%"PRIx32
          " EDX 0x%"PRIx32" ESP 0x%"PRIx32"\n",
           save_area->eax, save_area->ebx,
           save_area->ecx, save_area->edx,
           save_area->esp);

    // Print the top 10 stack words
    printf("Top o' stack:\n");
    for(int i = 0; i < 20; i++) {
        unsigned long *p = (unsigned long *)save_area->esp + i;
        printf("0x%lx ", *p);
    }
    printf("\n");

    // Drop to the debugger
    gdb_handle_exception(vec, (uintptr_t*)save_area);
    panic("gdb_handle_exception returned");
}

/**
 * \brief copies CPU-stacked registers to a dispatcher save area
 */
static void copy_cpu_frame_to_dispatcher(
    uintptr_t * NONNULL COUNT(X86_SAVE_AREA_SIZE) cpu_save_area,
    struct registers_x86_32 *disp_save_area)
{
    // sanity checks
    assert(cpu_save_area[X86_SAVE_SS] == USER_SS);
    assert(cpu_save_area[X86_SAVE_CS] == USER_CS);
    assert((cpu_save_area[X86_SAVE_EFLAGS] & USER_EFLAGS) == USER_EFLAGS);

    disp_save_area->ss = cpu_save_area[X86_SAVE_SS];
    disp_save_area->esp = cpu_save_area[X86_SAVE_ESP];
    disp_save_area->eflags = cpu_save_area[X86_SAVE_EFLAGS];
    disp_save_area->cs = cpu_save_area[X86_SAVE_CS];
    disp_save_area->eip = cpu_save_area[X86_SAVE_EIP];
}

/**
 * \brief Handles user-mode exceptions
 *
 * \param vec   Vector number of exception
 * \param error Error code from CPU, or 0 for an exception without an error code
 * \param cpu_save_area  Pointer to save area for registers stacked by CPU
 * \param disp_save_area Pointer to save area in dispatcher
 */
static __attribute__ ((used))
void generic_handle_user_exception(uintptr_t *cpu_save_area,
                                   struct registers_x86_32 *disp_save_area,
                                   int vec, uint32_t error)
{
    assert(dcb_current->disp_cte.cap.type == ObjType_Frame);
    dispatcher_handle_t handle = dcb_current->disp;
    struct dispatcher_shared_generic *disp =
        get_dispatcher_shared_generic(handle);
    uintptr_t eip = cpu_save_area[X86_SAVE_EIP];
    lvaddr_t fault_address, handler, param;

    assert(vec < NEXCEPTIONS);
    assert((cpu_save_area[X86_SAVE_CS] & 0x3) != 0); // CS.CPL > 0

    copy_cpu_frame_to_dispatcher(cpu_save_area, disp_save_area);

    bool disabled = dcb_current->disabled =
        dispatcher_is_disabled_ip(handle, eip);

    // Store FPU state if it's used
    // Do this for every trap when the current domain used the FPU
    // Do it for FPU not available traps in any case (to save the last FPU user)
    // XXX: Need to reset fpu_dcb when that DCB is deleted
    if(fpu_dcb != NULL &&
       (fpu_dcb == dcb_current || vec == IDT_NM)) {
        struct dispatcher_shared_generic *dst =
            get_dispatcher_shared_generic(fpu_dcb->disp);

        // Turn FPU trap off temporarily for saving its state
        bool trap = fpu_trap_get();
        fpu_trap_off();

        if(fpu_dcb->disabled) {
            fpu_save(dispatcher_get_disabled_fpu_save_area(fpu_dcb->disp));
	    dst->fpu_used = 1;
        } else {
            assert(!fpu_dcb->disabled);
            fpu_save(dispatcher_get_enabled_fpu_save_area(fpu_dcb->disp));
	    dst->fpu_used = 2;
        }

        if(trap) {
            fpu_trap_on();
        }
    }

    if (vec == IDT_PF) { // Page fault
        // Get fault address
        __asm volatile("mov %%cr2, %[fault_address]"
                       : [fault_address] "=r" (fault_address));

        printk(LOG_WARN, "user page fault%s in '%.*s': addr %"PRIxLVADDR
                         " IP %"PRIxPTR"  error %"PRIx32"\n",
               disabled ? " WHILE DISABLED" : "", DISP_NAME_LEN,
               disp->name, fault_address, eip, error);

        /* sanity-check that the trap handler saved in the right place */
        assert((disabled && disp_save_area == dispatcher_get_trap_save_area(handle))
               || (!disabled && disp_save_area == dispatcher_get_enabled_save_area(handle)));
        if (disabled) {
            dcb_current->faults_taken++;
            handler = disp->dispatcher_pagefault_disabled;
        } else {
            handler = disp->dispatcher_pagefault;
        }
        param = fault_address;
    } else if (vec == IDT_NM) {
        debug(SUBSYS_DISPATCH, "FPU trap in %.*s (%p) at 0x%" PRIxPTR ", %s\n",
              DISP_NAME_LEN, disp->name, dcb_current, eip, disabled ? "DISABLED" : "ENABLED");

        /* Intel system programming part 1: 2.3.1, 2.5, 11, 12.5.1
         * clear the TS flag (flag that says, that the FPU is not available)
         */
        clts();

        // Remember FPU-using DCB
        fpu_dcb = dcb_current;

        // Wipe FPU for protection and to initialize it in case we trapped while
        // disabled
        fpu_init();

        if(disabled) {
            // Initialize FPU (done earlier) and ignore trap
            dispatch(dcb_current);
        } else {
            // defer trap to user-space
            // FPUs are switched eagerly while disabled, there should be no trap
            assert(disp_save_area == dispatcher_get_trap_save_area(handle));
            handler = disp->dispatcher_trap;
            param = vec;
        }
    } else if (vec == IDT_NMI) {
        printk(LOG_WARN, "NMI - ignoring\n");
        dispatch(schedule());
    } else if (vec == IDT_MF) {
        uint16_t fpu_status;

        __asm volatile("fnstsw %0" : "=a" (fpu_status));

        printk(LOG_WARN, "FPU error%s in '%.*s': IP %"PRIxPTR" FPU status %x\n",
               disabled ? " WHILE DISABLED" : "", DISP_NAME_LEN,
               disp->name, eip, fpu_status);

        handler = disp->dispatcher_trap;
        param = vec;
    } else { // All other traps
        printk(LOG_WARN, "user trap #%d in '%.*s': IP %"PRIxPTR
                         ", error %"PRIu32"\n",
               vec, DISP_NAME_LEN, disp->name, eip, error);
        assert(disp_save_area == dispatcher_get_trap_save_area(handle));
        if(vec != 1) {
            dcb_current->faults_taken++;
        }

        handler = disp->dispatcher_trap;
        param = vec;
    }

    // Make unrunnable if it has taken too many faults
    if (dcb_current->faults_taken > 2) {
        printk(LOG_WARN, "generic_handle_user_exception: too many faults, "
               "making domain unrunnable\n");
        dcb_current->faults_taken = 0; // just in case it gets restarted
        scheduler_remove(dcb_current);
        dispatch(schedule());
    }

    /* resume user to save area */
    disp->disabled = 1;
    cpu_save_area[X86_SAVE_EIP] = handler;
    cpu_save_area[X86_SAVE_EFLAGS] = USER_EFLAGS;

    /* XXX: get GCC to load up the argument registers before returning */
    register uintptr_t arg0 __asm ("%eax") = param;
    register uintptr_t arg1 __asm ("%ecx") = error;
    register uintptr_t arg2 __asm ("%edx") = eip;
    __asm volatile("" :: "r" (arg0), "r" (arg1), "r" (arg2));
}

/// Handle an IRQ that arrived, either while in user or kernel mode (HLT)
static __attribute__ ((used)) void handle_irq(int vector)
{
    debug(SUBSYS_DISPATCH, "IRQ vector %d while %s\n", vector,
          dcb_current ? (dcb_current->disabled ? "disabled": "enabled") : "in kernel");

    int irq = vector - NEXCEPTIONS;

    // if we were in wait_for_interrupt(), unmask timer before running userspace
    if (dcb_current == NULL && kernel_ticks_enabled) {
        apic_unmask_timer();
    }

    // APIC timer interrupt: handle in kernel and reschedule
    if (vector == APIC_TIMER_INTERRUPT_VECTOR) {
        apic_eoi();
        assert(kernel_ticks_enabled);
        // Ignore timeslice if it happens too closely (less than half
        // of the TSC ticks that are supposed to pass) to the last.
        // In that case we have just synced timers and see a spurious
        // APIC timer interrupt.
        uint64_t tsc_now = rdtsc();
        if(tsc_now - tsc_lasttime >
           (kernel_timeslice * timing_get_tsc_per_ms()) / 2) {
            kernel_now += kernel_timeslice;
        }
        tsc_lasttime = tsc_now;
        trace_event(TRACE_SUBSYS_KERNEL, TRACE_EVENT_TIMER, kernel_now);
        wakeup_check(kernel_now);
    } else if (vector == APIC_ERROR_INTERRUPT_VECTOR) {
        printk(LOG_ERR, "APIC error interrupt fired!\n"); // XXX: do something?
        apic_eoi();
    } else if (vector == APIC_INTER_CORE_VECTOR) {
        apic_eoi();
#ifdef __scc__
        rck_handle_notification();
#else
        ipi_handle_notify();
#endif
    } else if (vector == 63) {
        // Record snapshot of current state
        trace_snapshot();

        // Record the running domain at the start of a trace
#ifdef TRACE_CSWITCH
        trace_event(TRACE_SUBSYS_KERNEL,
                    TRACE_EVENT_CSWITCH,
                    (uint32_t)(lvaddr_t)dcb_current & 0xFFFFFFFF);
#endif

        apic_eoi();
    }
#if 0
 else if (irq >= 0 && irq <= 15) { // classic PIC device interrupt
     printk(LOG_NOTE, "got interrupt %d!\n", irq);

        apic_eoi();

        // only handle PIC interrupts on the BSP core
        if (apic_is_bsp()) {
            if (pic_have_interrupt(irq)) {
                pic_eoi(irq);
                send_user_interrupt(irq);
            } else { // no interrupt pending, check for a different one (!)
                irq = pic_pending_interrupt();
                if (irq == -1) { // really nothing pending
                    printk(LOG_NOTE, "spurious interrupt (IRQ %d)\n", irq);
                } else { // why does this happen?! -AB
                    printk(LOG_NOTE, "IRQ %d reported on wrong vector (%d)\n",
                           irq, vector - NEXCEPTIONS);
                    pic_eoi(irq);
                    send_user_interrupt(irq);
                }
            }
        }
    }
#endif
    else { // APIC device interrupt (or IPI)
        //printk(LOG_NOTE, "interrupt %d vector %d!\n", irq, vector);
        apic_eoi();
#ifdef __scc__
        // Gotta reset the line
        rck_reset_lint1();
#endif
        send_user_interrupt(irq);
    }

    // reschedule (because the runnable processes may have changed) and dispatch
    /* FIXME: the round-robin scheduler doesn't do the best thing here:
     * it always picks the next task, but we only really want to do that on
     * a timer tick
     */
    dispatch(schedule());
    panic("dispatch() returned");
}

/**
 * \brief Handles device interrupts that arrive while in user mode
 *
 * \param vector    Vector number
 * \param cpu_save_area  Pointer to save area for registers stacked by CPU
 * \param disp_save_area Pointer to save area in dispatcher
 */
static __attribute__ ((used)) void
generic_handle_irq(struct registers_x86_32 *disp_save_area, uintptr_t *cpu_save_area,
                   int vector)
{
    assert(dcb_current->disp_cte.cap.type == ObjType_Frame);
    dispatcher_handle_t handle = dcb_current->disp;
    uintptr_t eip = cpu_save_area[X86_SAVE_EIP];
    assert(vector < NIDT && vector >= NEXCEPTIONS);

    // Copy CPU-saved registers to dispatcher save area
    copy_cpu_frame_to_dispatcher(cpu_save_area, disp_save_area);

    /* sanity-check that the trap handler saved in the right place,
     * and update disabled flag in DCB */
    if (disp_save_area == dispatcher_get_disabled_save_area(handle)) {
        assert(dispatcher_is_disabled_ip(handle, eip));
        dcb_current->disabled = 1;
    } else {
        assert(disp_save_area == dispatcher_get_enabled_save_area(handle));
        assert(!dispatcher_is_disabled_ip(handle, eip));
        dcb_current->disabled = 0;
    }

    handle_irq(vector);
}

/* Utility function for code below; initialises a gate_descriptor */
static void setgd(struct gate_descriptor *gd, void (* handler)(void),
                  int type, int dpl, int selector)
{
    memset(gd, 0, sizeof(struct gate_descriptor));
    gd->gd_looffset = (uintptr_t)handler & ((1UL << 16) - 1);
    gd->gd_hioffset = (uintptr_t)handler >> 16;
    gd->gd_selector = selector;
    gd->gd_type = type;
    gd->gd_dpl = dpl;
    gd->gd_p = 1;
}

/**
 * \brief Sets up the default IDT for current CPU.
 */
void setup_default_idt(void)
{
    struct region_descriptor region = {         // set default IDT
        .rd_limit = NIDT * sizeof(idt[0]) - 1,
        .rd_base = (uint32_t)&idt
    };
    int i;

    // reset IDT
    memset((void *)&idt, 0, NIDT * sizeof(idt[0]));

    // initialize IDT with default generic handlers
    for (i = 0; i < NIDT; i++)
        setgd(&idt[i], hwexc_666, SDT_SYSIGT, SEL_KPL,
              GSEL(KCODE_SEL, SEL_KPL));

    /* Setup exception handlers */
    setgd(&idt[0], hwexc_0, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[1], hwexc_1, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[2], hwexc_2, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[3], hwexc_3, SDT_SYSIGT, SEL_UPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[4], hwexc_4, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[5], hwexc_5, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[6], hwexc_6, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[7], hwexc_7, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[8], hwexc_8, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[9], hwexc_9, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[10], hwexc_10, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[11], hwexc_11, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[12], hwexc_12, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[13], hwexc_13, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[14], hwexc_14, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    // Interrupt 15 is undefined
    setgd(&idt[16], hwexc_16, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[17], hwexc_17, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[18], hwexc_18, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[19], hwexc_19, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    // Interrupts 20 - 31 are reserved

    /* Setup classic PIC interrupt handlers */
    setgd(&idt[32], hwirq_32, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[33], hwirq_33, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[34], hwirq_34, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[35], hwirq_35, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[36], hwirq_36, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[37], hwirq_37, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[38], hwirq_38, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[39], hwirq_39, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[40], hwirq_40, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[41], hwirq_41, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[42], hwirq_42, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[43], hwirq_43, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[44], hwirq_44, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[45], hwirq_45, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[46], hwirq_46, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[47], hwirq_47, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));

    // Setup generic interrupt handlers
    setgd(&idt[48], hwirq_48, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[49], hwirq_49, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[50], hwirq_50, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[50], hwirq_50, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[51], hwirq_51, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[52], hwirq_52, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[53], hwirq_53, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[54], hwirq_54, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[55], hwirq_55, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[56], hwirq_56, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[57], hwirq_57, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[58], hwirq_58, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[59], hwirq_59, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[60], hwirq_60, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[61], hwirq_61, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));

    // XXX Interrupts used for TRACE IPIs
    setgd(&idt[62], hwirq_62, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[63], hwirq_63, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));

    // Setup local APIC interrupt handlers
    setgd(&idt[249], hwirq_249, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[250], hwirq_250, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[251], hwirq_251, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[252], hwirq_252, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[253], hwirq_253, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));
    setgd(&idt[254], hwirq_254, SDT_SYSIGT, SEL_KPL, GSEL(KCODE_SEL, SEL_KPL));

    // Setup system call interrupt
    setgd(&idt[255], syscall_entry, SDT_SYSIGT, SEL_UPL,
          GSEL(KCODE_SEL, SEL_KPL));

    /* Load IDT register */
    __asm volatile("lidt %0" :: "m" (region));
}


text:
class Post < ActiveRecord::Base
  has_markup :content, :required => true, :syntax => :markdown, :cache_html => true
end


text:
class PropertyUnit < ActiveRecord::Base
  attr_accessible :property_id, :unit_id

  belongs_to :property
  belongs_to :unit

  validates_presence_of :property_id, :unit_id
end


text:
<?php
/**
 * @see https://help.shopify.com/api/reference/discounts/discountcode Shopify API Reference for PriceRule
 */

namespace PHPShopify;

/**
 * --------------------------------------------------------------------------
 * DiscountCode -> Batch action
 * --------------------------------------------------------------------------
 *
 */

class Batch extends ShopifyResource
{
    /**
     * @inheritDoc
     */
    protected $resourceKey = 'batch';

    protected function getResourcePath()
    {
        return $this->resourceKey;
    }

    protected function wrapData($dataArray, $dataKey = null)
    {
        return ['discount_codes' => $dataArray];
    }

}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SoftwareThresher.Settings.Search;

namespace SoftwareThresherTests.Settings.Search {
   [TestClass]
   public class OpenGrokParameterTests {
      [TestMethod]
      public void ToString_NoFormatting()
      {
         const string label = "fin";
         const string value = "it";

         var parameter = new OpenGrokParameter(label, value);

         Assert.AreEqual("fin=it", parameter.ToString());
      }

      [TestMethod]
      public void ToString_ValueContainsAQuoteVariablee_EscapesQuote() {
         const string value = "it\"s";

         var parameter = new OpenGrokParameter("one", value);

         Assert.IsTrue(parameter.ToString().EndsWith("=it\\\"s"));
      }
      [TestMethod]
      public void ToString_ValueContainsSpaces_PutsQuotesAroundTheValue() {
         const string value = "it is";

         var parameter = new OpenGrokParameter("one", value);

         Assert.IsTrue(parameter.ToString().EndsWith("=\"it is\""));
      }
   }
}


text:
package com.alibaba.dubbo.remoting.handler;

import com.alibaba.dubbo.common.utils.ConcurrentHashSet;
import com.alibaba.dubbo.remoting.Channel;
import com.alibaba.dubbo.remoting.ChannelHandler;
import com.alibaba.dubbo.remoting.RemotingException;

import java.util.Collections;
import java.util.Set;

public class MockedChannelHandler implements ChannelHandler {
    //    ConcurrentMap<String, Channel> channels = new ConcurrentHashMap<String, Channel>();
    ConcurrentHashSet<Channel> channels = new ConcurrentHashSet<Channel>();

    public void connected(Channel channel) throws RemotingException {
        channels.add(channel);
    }

    public void disconnected(Channel channel) throws RemotingException {
        channels.remove(channel);
    }

    public void sent(Channel channel, Object message) throws RemotingException {
        channel.send(message);
    }

    public void received(Channel channel, Object message) throws RemotingException {
        //echo
        channel.send(message);
    }

    public void caught(Channel channel, Throwable exception) throws RemotingException {
        throw new RemotingException(channel, exception);

    }

    public Set<Channel> getChannels() {
        return Collections.unmodifiableSet(channels);
    }
}


text:
<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="stylesheets/default.css">
  <link href='http://fonts.googleapis.com/css?family=Poiret+One' rel='stylesheet' type='text/css'>
  <meta charset="UTF-8">
  <title>Welcome to my homepage</title>

Sid Watal

Thought and Projects

        Home
        Blog
        About
        Projects

There and Back

My journey through Dev Bootcamp and Coding

GPS 1.2 Challenge

JavaScript Cheatsheet

    Contact via Email All opinions are nobody's because they are probably wrong.


text:
package workday

import (
	"os"
	"path/filepath"
)

func createParentDirs(fpath string) error {
	parent := filepath.Dir(fpath)
	return os.MkdirAll(parent, 0777)
}

func fileExists(fpath string) (bool, error) {
	if _, err := os.Stat(fpath); err != nil {
		if os.IsNotExist(err) {
			return false, nil
		}
		return false, err
	}
	return true, nil
}

func createFileIfNotExists(fpath string) error {
	if exists, err := fileExists(fpath); err != nil {
		return err
	} else if !exists {
		f, err := os.Create(fpath)
		if err != nil {
			return err
		}
		if err := f.Close(); err != nil {
			return err
		}
	}
	return nil
}


text:
using System;
using System.Globalization;

#if SITEMANAGEMENT
namespace Kudu.SiteManagement
#else
namespace Kudu.Core.Infrastructure
#endif
{

    public class CommandLineException : Exception
    {
        public CommandLineException(string executablePath, string arguments, string message)
            : base(String.Format(CultureInfo.InvariantCulture, "{0}{1}{2} {3}", message, System.Environment.NewLine, executablePath, arguments))
        {
        }

        public int ExitCode { get; set; }
        public string Output { get; set; }
        public string Error { get; set; }

        public override string ToString()
        {
            return String.Format(CultureInfo.InvariantCulture, "ExitCode: {0}, Output: {1}, Error: {2}, {3}",
                this.ExitCode,
                this.Output,
                this.Error,
                base.ToString());
        }
    }
}


text:
{-# LANGUAGE ForeignFunctionInterface #-}
module Clingo.Raw.Basic
(
    errorString,
    errorCode,
    errorMessage,
    setError,
    warningString,
    version
)
where

import Foreign
import Foreign.C
import Control.Monad.IO.Class
import Clingo.Raw.Enums

foreign import ccall "clingo.h clingo_error_string" errorStringFFI ::
    ClingoError -> IO CString
foreign import ccall "clingo.h clingo_error_code" errorCodeFFI ::
    IO ClingoError
foreign import ccall "clingo.h clingo_error_message" errorMessageFFI ::
    IO CString
foreign import ccall "clingo.h clingo_set_error" setErrorFFI ::
    ClingoError -> CString -> IO ()
foreign import ccall "clingo.h clingo_warning_string" warningStringFFI ::
    ClingoWarning -> IO CString
foreign import ccall "clingo.h clingo_version" versionFFI ::
    Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()

errorString :: MonadIO m => ClingoError -> m CString
errorString = liftIO . errorStringFFI

errorCode :: MonadIO m => m ClingoError
errorCode = liftIO errorCodeFFI

errorMessage :: MonadIO m => m CString
errorMessage = liftIO errorMessageFFI

setError :: MonadIO m => ClingoError -> CString -> m ()
setError a b = liftIO $ setErrorFFI a b

warningString :: MonadIO m => ClingoWarning -> m CString
warningString = liftIO . warningStringFFI

version :: MonadIO m => Ptr CInt -> Ptr CInt -> Ptr CInt -> m ()
version a b c = liftIO $ versionFFI a b c


text:
<!DOCTYPE html>

    <title>Component • Web Components @SydJS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="/component/rsvp/build/build.css">

Home

Polymer

Component

Component RSVP


text:
taskkill /IM python.exe /f
start cmd /k c:\ProgramData\Anaconda3\python Arby2.py ETH
start cmd /k c:\ProgramData\Anaconda3\python Arby2.py LTC
start cmd /k c:\ProgramData\Anaconda3\python ArbyBinGdx.py
exit


text:
title: Farey sequence
localeTitle: تسلسل Farey
---
## تسلسل Farey

هذا هو كعب. [ساعد مجتمعنا على توسيعه](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/rosetta-code/farey-sequence/index.md) .

[سيساعدك دليل النمط السريع هذا على ضمان قبول طلب السحب](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
<?php

namespace fpoirotte\Pssht;

/**
 * Interface for an encryption/decryption algorithm.
 */
interface EncryptionInterface extends AlgorithmInterface
{
    /**
     * Construct an encryption/decryption algorithm.
     *
     *  \param string $iv
     *      Initialization vector for the algorithm.
     *
     *  \param string $key
     *      Encryption/decrytion key.
     */
    public function __construct($iv, $key);

    /**
     * Get the algorithm's key size.
     *
     *  \retval int
     *      Key size (in bytes).
     */
    public static function getKeySize();

    /**
     * Get the algorithm's IV size.
     *
     *  \retval int
     *      Initialization vector size (in bytes).
     */
    public static function getIVSize();

    /**
     * Get the algorithm's block size.
     *
     *  \retval int
     *      Block size (in bytes).
     */
    public static function getBlockSize();

    /**
     * Encrypt data using the algorithm.
     *
     *  \param int $seqno
     *      Sequence number.
     *
     *  \param string $data
     *      Data to encrypt.
     *
     *  \retval string
     *      Encrypted data.
     */
    public function encrypt($seqno, $data);

    /**
     * Decrypt data using the algorithm.
     *
     *  \param int $seqno
     *      Sequence number.
     *
     *  \param string $data
     *      Data to decrypt.
     *
     *  \retval string
     *      Decrypted data.
     */
    public function decrypt($seqno, $data);
}


text:
package org.apache.druid.timeline.partition;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import org.apache.druid.data.input.StringTuple;

import javax.annotation.Nullable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * See {@link BuildingShardSpec} for how this class is used.
 *
 * @see SingleDimensionShardSpec
 */
public class BuildingSingleDimensionShardSpec extends BuildingDimensionRangeShardSpec
{
  private final String dimension;

  @Nullable
  private final String start;

  @Nullable
  private final String end;

  @JsonCreator
  public BuildingSingleDimensionShardSpec(
      @JsonProperty("bucketId") int bucketId,
      @JsonProperty("dimension") String dimension,
      @JsonProperty("start") @Nullable String start,
      @JsonProperty("end") @Nullable String end,
      @JsonProperty("partitionNum") int partitionNum
  )
  {
    super(
        bucketId,
        dimension == null ? Collections.emptyList() : Collections.singletonList(dimension),
        start == null ? null : StringTuple.create(start),
        end == null ? null : StringTuple.create(end),
        partitionNum
    );
    this.dimension = dimension;
    this.start = start;
    this.end = end;
  }

  @JsonValue
  public Map<String, Object> getSerializableObject()
  {
    Map<String, Object> jsonMap = new HashMap<>();
    jsonMap.put("dimension", dimension);
    jsonMap.put("start", start);
    jsonMap.put("end", end);
    jsonMap.put("bucketId", getBucketId());
    jsonMap.put("partitionNum", getPartitionNum());

    return jsonMap;
  }

  public String getDimension()
  {
    return dimension;
  }

  @Nullable
  public String getStart()
  {
    return start;
  }

  @Nullable
  public String getEnd()
  {
    return end;
  }

  @Override
  public SingleDimensionShardSpec convert(int numCorePartitions)
  {
    return new SingleDimensionShardSpec(dimension, start, end, getPartitionNum(), numCorePartitions);
  }

  @Override
  public <T> PartitionChunk<T> createChunk(T obj)
  {
    return new NumberedPartitionChunk<>(getPartitionNum(), 0, obj);
  }

  @Override
  public String getType()
  {
    return Type.BUILDING_SINGLE_DIM;
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    BuildingSingleDimensionShardSpec that = (BuildingSingleDimensionShardSpec) o;
    return getBucketId() == that.getBucketId() &&
           getPartitionNum() == that.getPartitionNum() &&
           Objects.equals(dimension, that.dimension) &&
           Objects.equals(start, that.start) &&
           Objects.equals(end, that.end);
  }

  @Override
  public int hashCode()
  {
    return Objects.hash(getBucketId(), dimension, start, end, getPartitionNum());
  }

  @Override
  public String toString()
  {
    return "BuildingSingleDimensionShardSpec{" +
           "bucketId=" + getBucketId() +
           ", dimension='" + dimension + '\'' +
           ", start='" + start + '\'' +
           ", end='" + end + '\'' +
           ", partitionNum=" + getPartitionNum() +
           '}';
  }
}


text:
=========================

a manager class for  the meteor reactive variable class (https://github.com/ruzz/Meteor-ReactiveVariable.git) which probably makes the ReactiveVariable a much more interesting and useful tool in your toolbox.

feel free to pull, fork, frak, or pontificate. i'm open like an all night diner.

## Install:
`mrt add reactive-variable-manager` (i haven't yet released it on atmosphere, please check back)

## Initialization:

```javascript
var manager = new ReactiveVariableManager( optionalConfigObject );
```
it can take an optional config object on creation with optional properties

### Initialization Config Properties:
#### initialize:
  an array of ReactiveVariable config objects (see ReactiveVariable for examples)

#### errorHandler:
  an optional errorHandler function of your choosing.
  your function will recieve one variable  ```errorString``` use it wisely.

#### example:
```javascript
{
  initialize: [
    {
        name: "selectedGame",
        defaultValue: 'game1',
        dictionary: Session
    },
    {
        name: "selectedRoom",
        defaultValue: 'room1',
        dictionary: Session
    }
  ],
  errorHandler: function( errorString ){
    console.log( 'this is the error string', errorString );
  }
}
```

## API:

the api more or less wraps the existing known api for ReactiveVariable so you should probably read that api at some point but for the impatient among you.

### get( name )

  ```manager.get( 'selectedGame' ); //returns game1```

### set( name, value )

  ```manager.set( 'selectedGame', 'game2' ); //selected game is now 'game2' ```

### has( name )

  ```manager.has( 'selectedGame' ); //returns true```

### baseValue( name )
  this is super handy if you have a hook not firing as expected, you can see what the pre-hook values are

  ```manager.baseValue( 'selectedGame' ); //returns baseValue of ReactiveVariable```

### native( name )
  returns the native ReactiveVariable not just its value.

  ```reactiveVar = manager.native( 'selectedGame' ); //returns the native ReactiveVariable object```

### empty()
  emptys **ALL** the managed ReactiveVariables. this will likely break your whole app, be careful.

  ```manager.empty(); //all your hard work is gone gone gone```

### registerReactiveVariable( ReactiveVariableConfigObject )
  creates and registers a new reactive variable

  ```manager.registerReactiveVariable( ReactiveVariableConfigObject );```

### unregisterReactiveVariable( name )
  removes/destroys a managed ReactiveVariable

  ```manager.unregisterReactiveVariable( 'selectedGame' );```

### list()
  returns an array of registered ReactiveVariable names

  ```manager.list(); // ["selectedGame", "selectedRoom"]```


text:
"use strict";

var puppeteer;
try {
  puppeteer = require('puppeteer');
} catch (err) {
  throw new Error(
    "Unable to run tests in Chrome because the required dependencies are " +
    "not available. Please note that JSHint does not support development " +
    "using versions of Node.js which are no longer maintained."
  );
}
var createTestServer = require("./helpers/browser/server");
var port = process.env.NODE_PORT || 8045;
const browser = puppeteer.launch({ headless: true, args: ["--no-sandbox", "--disable-setuid-sandbox"] }).then(async browser => {
  const page = await browser.newPage();
  createTestServer(port, function(server) {
    page.on("console", msg => console.log("", msg.text()));

    page.exposeFunction("callChrome", text=> {
      browser.close();
      process.exit();
    });

    page.on('error', err=> {
      console.log('error: ', err);
    });

    return page.goto("http://localhost:" + port, {
      waitUntil: "load"
    });
  });
});


text:
NS_ASSUME_NONNULL_BEGIN

@class MTIRenderPipeline;

@protocol MTIGeometryRenderingContext <NSObject>

@property (nonatomic, readonly, strong) MTIRenderPipeline *renderPipeline;

@property (nonatomic, readonly, strong) id<MTLDevice> device;

@end

@protocol MTIGeometry <NSObject, NSCopying>

- (void)encodeDrawCallWithCommandEncoder:(id<MTLRenderCommandEncoder>)commandEncoder
                                 context:(id<MTIGeometryRenderingContext>)context;

@end

NS_ASSUME_NONNULL_END

#if __has_include(<MetalPetal/MetalPetal.h>)
#import <MetalPetal/MTIRenderPipeline.h>
#else
#import "MTIRenderPipeline.h"
#endif

NS_ASSUME_NONNULL_BEGIN

@interface MTIRenderPipeline (MTIGeometryRenderingContext) <MTIGeometryRenderingContext>

@end

NS_ASSUME_NONNULL_END


text:
layout: single
title: "Magnet CTF Week 10 - Network analysis in RAM"
date: '2020-12-15T01:00:00+09:00'

tags:
  - infosec
  - dfir
  - CTF
  - Magnet
modified_time: ""
---

Magnet Forensics is running a *weekly* forensic CTF. More information can be found on their [blog](https://www.magnetforensics.com/blog/magnet-weekly-ctf-challenge/). It is a fun way to practice, so let's get to it!

### CTF Posts

[Week 1](https://dfir.science/2020/10/Magnet-CTF-Week-1-Timestamps-of-doom.html) | [Week 2](https://dfir.science/2020/10/Magnet-CTF-Week-2-URLs-in-Pictures-in-Pictures.html) | [Week 3](https://dfir.science/2020/10/Magnet-CTF-Week-3-Failed-connections.html) | [Week 4](https://dfir.science/2020/11/Magnet-CTF-Week-4-GUIDSWAP-and-drop.html) | [Week 5](https://dfir.science/2020/11/Magnet-CTF-Week-5-HDFS.html) | [Week 6](https://dfir.science/2020/11/Magnet-CTF-Week-6-Riddle-ELF.html) | [Week 7](https://dfir.science/2020/11/Magnet-CTF-Week-7-Hadoop-Nodes.html) | [Week 8](https://dfir.science/2020/12/Magnet-CTF-Week-8-Persistence-in-plain-sight.html) | [Week 9](https://dfir.science/2020/12/Magnet-CTF-Week-9-digging-through-memory.html)

### Getting Started

New image for December! It can be found [here](https://drive.google.com/drive/folders/10fYCrNI46FT9l3LaJ9dj5gLxjlLtdnPo?usp=sharing). This is a memory image, and this week has multiple questions. Note: I may jump between Volatility 2.6 and 3 as I'm playing around.

> Q1: *At the time of the RAM collection (20-Apr-20 23:23:26- Imageinfo) there was an established connection to a Google Server. What was the Remote IP address and port number? format: "xxx.xxx.xx.xxx:xxx"

The IP format gives a bit of a hint. We know the third octet is two digits and the rest are three. The port is also (probably) 443 since it's def not 80. Let's use Volatility to check the established connections (at the time of imaging).

```bash
$ ./vol -f memdump-001.0.mem --profile=Win7SP1x64 netscan | grep -i established
Volatility Foundation Volatility Framework 2.6
0x13d48f540        TCPv4    192.168.10.146:54279           151.101.116.106:443  ESTABLISHED      -1
0x13ec87cd0        TCPv4    192.168.10.146:54282           172.253.63.188:443   ESTABLISHED      -1
0x13ece73b0        TCPv4    192.168.10.146:54281           13.35.82.31:443      ESTABLISHED      -1
0x13ecf8010        TCPv4    192.168.10.146:54280           13.35.82.102:443     ESTABLISHED      -1
```

Lucky for us only one Google IP address is listed, and it is in the correct format. Trying ```172.253.63.188:443``` and **BING!** Success.

> Q2: What was the Local IP address and port number? same format as part 1

In the prior command, the number on the right is the public IP the system is connecting to. The number on the left (starting with 192.168) is the *private* (local) IP address of the system. Trying ```192.168.10.146:54282``` and **BING!** Success.

> Q3: What was the URL?

First, check for a browser process and get it's ID. I bet it is Chrome.

```bash
$ ./vol -f memdump-001.0.mem --profile=Win7SP1x64 pslist | grep -i chrome
Volatility Foundation Volatility Framework 2.6
0xfffffa8031e2c2c0 chrome.exe             3384   2672     30     1039      1      0 2020-04-20 23:17:07 UTC+0000
0xfffffa8032429060 chrome.exe             3392   3384      7       95      1      0 2020-04-20 23:17:07 UTC+0000
0xfffffa80324ca5c0 chrome.exe             3492   3384      2       56      1      0 2020-04-20 23:17:09 UTC+0000
```

The PID we are interested in is ```3384```. We want to dump the history file from the Chrome process.

```bash
$ ./vol -f memdump-001.0.mem --profile=Win7SP1x64 dumpfiles -D dump/ -r History$ -i -p 3384
Volatility Foundation Volatility Framework 2.6
DataSectionObject 0xfffffa80325ccb30   3384   \Device\HarddiskVolume1\Users\Warren\AppData\Local\Google\Chrome\User Data\Default\History
SharedCacheMap 0xfffffa80325ccb30   3384   \Device\HarddiskVolume1\Users\Warren\AppData\Local\Google\Chrome\User Data\Default\History
```

This gives us ```file.3384.0xfffffa80311c7eb0.dat```. If we open that with an SQLite viewer, go to the ```URLs``` table, sort by ```last_visit_time```, and you will see https://google.com. Trying, and **BING!** Success.

> Q4: What user was responsible for this activity based on the profile?

We can see in the previous command that the user account appears to be "Warren", but just to check let's look at the hashdump.

```bash
$ ./vol -f memdump-001.0.mem --profile=Win7SP1x64 hashdump
Volatility Foundation Volatility Framework 2.6
Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
**Warren**:1000:aad3b435b51404eeaad3b435b51404ee:2aa81fb8c8cdfd8f420f7f94615036b0:::
```

Confirmed. Trying "Warren" and **BING!** Success.

> Q5: How long was this user looking at this browser with this version of Chrome?

This question was quite nasty. I kept thinking about prefetch timelines, but didn't think of a way to find the exact time viewed. I tried building process execution timelines, but that wasn't it. I turned to the Windows Registry. After a lot of hacking around I figured it must be UserAssist.

```bash
$ ./vol -f memdump-001.0.mem --profile=Win7SP1x64 userassist | grep -A 4 -i Chrome
Volatility Foundation Volatility Framework 2.6
REG_BINARY    Chrome          :
Count:          9
Focus Count:    106
Time Focused:   3:36:47.301000
Last updated:   2020-04-20 23:17:07 UTC+0000
--
REG_BINARY    %APPDATA%\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\Google Chrome.lnk :
Count:          7
Focus Count:    0
Time Focused:   0:00:00.507000
Last updated:   2020-04-20 23:17:07 UTC+0000
--
REG_BINARY    C:\Users\Public\Desktop\Google Chrome.lnk :
Count:          2
Focus Count:    0
Time Focused:   0:00:00.502000
Last updated:   2020-02-18 07:43:29 UTC+0000
```

We are interested in the first entry. Specifically, ```Time Focused:   3:36:47.301000```. Trying and **BING!** Success (finally).

## Lessons Learned

I've leared a lot every week of the Magnet CTF. However, memory analysis has really pushed me. I look at a question and think "dang I know where that is on disk, how am I going to carve it?" For some reason I keep wanting to default to "carve." The curve-ball this week was Registry analysis from memory. It's extremely useful, and I'm sure I will use it again.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _02.Print_Company_Information
{
    class printCompanyInfo
    {
        static void Main()
        {
            Console.WriteLine("Please enter company name");
            string companyName = Console.ReadLine();
            Console.WriteLine("Please enter company address");
            string companyAddress = Console.ReadLine();
            Console.WriteLine("Please enter company phone number");
            string companyPhoneNumb = Console.ReadLine();
            Console.WriteLine("Please enter company fax number");
            string companyFax = Console.ReadLine();
            Console.WriteLine("Please enter company web site");
            string companyWebSite = Console.ReadLine();
            Console.WriteLine("Please enter manager first name");
            string managerFN = Console.ReadLine();
            Console.WriteLine("Please enter manager last name");
            string managerLN = Console.ReadLine();
            Console.WriteLine("Please enter manager age");
            int managerAge = int.Parse(Console.ReadLine());
            Console.WriteLine("Please enter manager phone number");
            string managerPhoneNumb = Console.ReadLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine(companyName);
            Console.WriteLine("Address: {0}", companyAddress);
            Console.WriteLine("Tel. {0}", companyPhoneNumb);
            if(companyFax == "")
            {
                Console.WriteLine("Fax: (no fax)");
            }
            else
            {
                Console.WriteLine(companyFax);
            }
            Console.WriteLine("Web site: {0}", companyWebSite);
            Console.WriteLine("Manager: {0} {1}(age: {2}, tel. {3})", managerFN, managerLN, managerAge, managerPhoneNumb);

        }
    }
}