text:
/*
 * MinIO Cloud Storage, (C) 2016, 2017, 2018 MinIO, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cmd

import (
	"context"
	"os"
	"path"
	"testing"

	"github.com/minio/minio/pkg/auth"
	"github.com/minio/minio/pkg/event/target"
)

func TestServerConfig(t *testing.T) {
	objLayer, fsDir, err := prepareFS()
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(fsDir)

	if err = newTestConfig(globalMinioDefaultRegion, objLayer); err != nil {
		t.Fatalf("Init Test config failed")
	}

	if globalServerConfig.GetRegion() != globalMinioDefaultRegion {
		t.Errorf("Expecting region `us-east-1` found %s", globalServerConfig.GetRegion())
	}

	// Set new region and verify.
	globalServerConfig.SetRegion("us-west-1")
	if globalServerConfig.GetRegion() != "us-west-1" {
		t.Errorf("Expecting region `us-west-1` found %s", globalServerConfig.GetRegion())
	}

	// Match version.
	if globalServerConfig.GetVersion() != serverConfigVersion {
		t.Errorf("Expecting version %s found %s", globalServerConfig.GetVersion(), serverConfigVersion)
	}

	if err := saveServerConfig(context.Background(), objLayer, globalServerConfig); err != nil {
		t.Fatalf("Unable to save updated config file %s", err)
	}

	// Initialize server config.
	if err := loadConfig(objLayer); err != nil {
		t.Fatalf("Unable to initialize from updated config file %s", err)
	}
}

func TestServerConfigWithEnvs(t *testing.T) {

	os.Setenv("MINIO_BROWSER", "off")
	defer os.Unsetenv("MINIO_BROWSER")

	os.Setenv("MINIO_WORM", "on")
	defer os.Unsetenv("MINIO_WORM")

	os.Setenv("MINIO_ACCESS_KEY", "minio")
	defer os.Unsetenv("MINIO_ACCESS_KEY")

	os.Setenv("MINIO_SECRET_KEY", "minio123")
	defer os.Unsetenv("MINIO_SECRET_KEY")

	os.Setenv("MINIO_REGION", "us-west-1")
	defer os.Unsetenv("MINIO_REGION")

	os.Setenv("MINIO_DOMAIN", "domain.com")
	defer os.Unsetenv("MINIO_DOMAIN")

	defer resetGlobalIsEnvs()

	objLayer, fsDir, err := prepareFS()
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(fsDir)

	if err = newTestConfig(globalMinioDefaultRegion, objLayer); err != nil {
		t.Fatalf("Init Test config failed")
	}

	globalObjLayerMutex.Lock()
	globalObjectAPI = objLayer
	globalObjLayerMutex.Unlock()

	serverHandleEnvVars()

	// Init config
	initConfig(objLayer)

	// Check if serverConfig has browser disabled
	if globalIsBrowserEnabled {
		t.Error("Expected browser to be disabled but it is not")
	}

	// Check if serverConfig returns WORM config from the env
	if !globalServerConfig.GetWorm() {
		t.Error("Expected WORM to be enabled but it is not")
	}

	// Check if serverConfig has region from the environment
	if globalServerConfig.GetRegion() != "us-west-1" {
		t.Errorf("Expected region to be \"us-west-1\", found %v", globalServerConfig.GetRegion())
	}

	// Check if serverConfig has credentials from the environment
	cred := globalServerConfig.GetCredential()

	if cred.AccessKey != "minio" {
		t.Errorf("Expected access key to be `minio`, found %s", cred.AccessKey)
	}

	if cred.SecretKey != "minio123" {
		t.Errorf("Expected access key to be `minio123`, found %s", cred.SecretKey)
	}

	// Check if serverConfig has the correct domain
	if globalDomainNames[0] != "domain.com" {
		t.Errorf("Expected Domain to be `domain.com`, found " + globalDomainNames[0])
	}
}

// Tests config validator..
func TestValidateConfig(t *testing.T) {
	objLayer, fsDir, err := prepareFS()
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(fsDir)

	if err = newTestConfig(globalMinioDefaultRegion, objLayer); err != nil {
		t.Fatalf("Init Test config failed")
	}

	configPath := path.Join(minioConfigPrefix, minioConfigFile)
	v := serverConfigVersion

	testCases := []struct {
		configData string
		shouldPass bool
	}{
		// Test 1 - wrong json
		{`{`, false},

		// Test 2 - empty json
		{`{}`, false},

		// Test 3 - wrong config version
		{`{"version": "10"}`, false},

		// Test 4 - wrong browser parameter
		{`{"version": "` + v + `", "browser": "foo"}`, false},

		// Test 5 - missing credential
		{`{"version": "` + v + `", "browser": "on"}`, false},

		// Test 6 - missing secret key
		{`{"version": "` + v + `", "browser": "on", "credential" : {"accessKey":"minio", "secretKey":""}}`, false},

		// Test 7 - missing region should pass, defaults to 'us-east-1'.
		{`{"version": "` + v + `", "browser": "on", "credential" : {"accessKey":"minio", "secretKey":"minio123"}}`, true},

		// Test 8 - missing browser should pass, defaults to 'on'.
		{`{"version": "` + v + `", "region": "us-east-1", "credential" : {"accessKey":"minio", "secretKey":"minio123"}}`, true},

		// Test 9 - success
		{`{"version": "` + v + `", "browser": "on", "region":"us-east-1", "credential" : {"accessKey":"minio", "secretKey":"minio123"}}`, true},

		// Test 10 - duplicated json keys
		{`{"version": "` + v + `", "browser": "on", "browser": "on", "region":"us-east-1", "credential" : {"accessKey":"minio", "secretKey":"minio123"}}`, false},

		// Test 11 - Test AMQP
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "amqp": { "1": { "enable": true, "url": "", "exchange": "", "routingKey": "", "exchangeType": "", "mandatory": false, "immediate": false, "durable": false, "internal": false, "noWait": false, "autoDeleted": false }}}}`, false},

		// Test 12 - Test NATS
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "nats": { "1": { "enable": true, "address": "", "subject": "", "username": "", "password": "", "token": "", "secure": false, "pingInterval": 0, "streaming": { "enable": false, "clusterID": "", "async": false, "maxPubAcksInflight": 0 } } }}}`, false},

		// Test 13 - Test ElasticSearch
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "elasticsearch": { "1": { "enable": true, "url": "", "index": "" } }}}`, false},

		// Test 14 - Test Redis
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "redis": { "1": { "enable": true, "address": "", "password": "", "key": "" } }}}`, false},

		// Test 15 - Test PostgreSQL
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "postgresql": { "1": { "enable": true, "connectionString": "", "table": "", "host": "", "port": "", "user": "", "password": "", "database": "" }}}}`, false},

		// Test 16 - Test Kafka
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "kafka": { "1": { "enable": true, "brokers": null, "topic": "", "queueDir": "", "queueLimit": 0 } }}}`, false},

		// Test 17 - Test Webhook
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "webhook": { "1": { "enable": true, "endpoint": "" } }}}`, false},

		// Test 18 - Test MySQL
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "mysql": { "1": { "enable": true, "dsnString": "",  "table": "", "host": "", "port": "", "user": "", "password": "", "database": "" }}}}`, false},

		// Test 19 - Test Format for MySQL
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "mysql": { "1": { "enable": true, "dsnString": "",  "format": "invalid", "table": "xxx", "host": "10.0.0.1", "port": "3306", "user": "abc", "password": "pqr", "database": "test1" }}}}`, false},

		// Test 20 - Test valid Format for MySQL
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "mysql": { "1": { "enable": true, "dsnString": "",  "format": "namespace", "table": "xxx", "host": "10.0.0.1", "port": "3306", "user": "abc", "password": "pqr", "database": "test1" }}}}`, true},

		// Test 21 - Test Format for PostgreSQL
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "postgresql": { "1": { "enable": true, "connectionString": "", "format": "invalid", "table": "xxx", "host": "myhost", "port": "5432", "user": "abc", "password": "pqr", "database": "test1" }}}}`, false},

		// Test 22 - Test valid Format for PostgreSQL
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "postgresql": { "1": { "enable": true, "connectionString": "", "format": "namespace", "table": "xxx", "host": "myhost", "port": "5432", "user": "abc", "password": "pqr", "database": "test1" }}}}`, true},

		// Test 23 - Test Format for ElasticSearch
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "elasticsearch": { "1": { "enable": true, "format": "invalid", "url": "example.com", "index": "myindex" } }}}`, false},

		// Test 24 - Test valid Format for ElasticSearch
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "elasticsearch": { "1": { "enable": true, "format": "namespace", "url": "example.com", "index": "myindex" } }}}`, true},

		// Test 25 - Test Format for Redis
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "redis": { "1": { "enable": true, "format": "invalid", "address": "example.com:80", "password": "xxx", "key": "key1" } }}}`, false},

		// Test 26 - Test valid Format for Redis
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "redis": { "1": { "enable": true, "format": "namespace", "address": "example.com:80", "password": "xxx", "key": "key1" } }}}`, true},

		// Test 27 - Test MQTT
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "mqtt": { "1": { "enable": true, "broker": "",  "topic": "", "qos": 0, "username": "", "password": "", "queueDir": "", "queueLimit": 0}}}}`, false},

		// Test 28 - Test NSQ
		{`{"version": "` + v + `", "credential": { "accessKey": "minio", "secretKey": "minio123" }, "region": "us-east-1", "browser": "on", "notify": { "nsq": { "1": { "enable": true, "nsqdAddress": "", "topic": ""} }}}`, false},
	}

	for i, testCase := range testCases {
		if err = saveConfig(context.Background(), objLayer, configPath, []byte(testCase.configData)); err != nil {
			t.Fatal(err)
		}
		_, err = getValidConfig(objLayer)
		if testCase.shouldPass && err != nil {
			t.Errorf("Test %d, should pass but it failed with err = %v", i+1, err)
		}
		if !testCase.shouldPass && err == nil {
			t.Errorf("Test %d, should fail but it succeeded.", i+1)
		}
	}

}

func TestConfigDiff(t *testing.T) {
	testCases := []struct {
		s, t *serverConfig
		diff string
	}{
		// 1
		{&serverConfig{}, nil, "Given configuration is empty"},
		// 2
		{
			&serverConfig{Credential: auth.Credentials{
				AccessKey:  "u1",
				SecretKey:  "p1",
				Expiration: timeSentinel,
			}},
			&serverConfig{Credential: auth.Credentials{
				AccessKey:  "u1",
				SecretKey:  "p2",
				Expiration: timeSentinel,
			}},
			"Credential configuration differs",
		},
		// 3
		{&serverConfig{Region: "us-east-1"}, &serverConfig{Region: "us-west-1"}, "Region configuration differs"},
		// 4
		{
			&serverConfig{StorageClass: storageClassConfig{storageClass{"1", 8}, storageClass{"2", 6}}},
			&serverConfig{StorageClass: storageClassConfig{storageClass{"1", 8}, storageClass{"2", 4}}},
			"StorageClass configuration differs",
		},
		// 5
		{
			&serverConfig{Notify: notifier{AMQP: map[string]target.AMQPArgs{"1": {Enable: true}}}},
			&serverConfig{Notify: notifier{AMQP: map[string]target.AMQPArgs{"1": {Enable: false}}}},
			"AMQP Notification configuration differs",
		},
		// 6
		{
			&serverConfig{Notify: notifier{NATS: map[string]target.NATSArgs{"1": {Enable: true}}}},
			&serverConfig{Notify: notifier{NATS: map[string]target.NATSArgs{"1": {Enable: false}}}},
			"NATS Notification configuration differs",
		},
		// 7
		{
			&serverConfig{Notify: notifier{NSQ: map[string]target.NSQArgs{"1": {Enable: true}}}},
			&serverConfig{Notify: notifier{NSQ: map[string]target.NSQArgs{"1": {Enable: false}}}},
			"NSQ Notification configuration differs",
		},
		// 8
		{
			&serverConfig{Notify: notifier{Elasticsearch: map[string]target.ElasticsearchArgs{"1": {Enable: true}}}},
			&serverConfig{Notify: notifier{Elasticsearch: map[string]target.ElasticsearchArgs{"1": {Enable: false}}}},
			"ElasticSearch Notification configuration differs",
		},
		// 9
		{
			&serverConfig{Notify: notifier{Redis: map[string]target.RedisArgs{"1": {Enable: true}}}},
			&serverConfig{Notify: notifier{Redis: map[string]target.RedisArgs{"1": {Enable: false}}}},
			"Redis Notification configuration differs",
		},
		// 10
		{
			&serverConfig{Notify: notifier{PostgreSQL: map[string]target.PostgreSQLArgs{"1": {Enable: true}}}},
			&serverConfig{Notify: notifier{PostgreSQL: map[string]target.PostgreSQLArgs{"1": {Enable: false}}}},
			"PostgreSQL Notification configuration differs",
		},
		// 11
		{
			&serverConfig{Notify: notifier{Kafka: map[string]target.KafkaArgs{"1": {Enable: true}}}},
			&serverConfig{Notify: notifier{Kafka: map[string]target.KafkaArgs{"1": {Enable: false}}}},
			"Kafka Notification configuration differs",
		},
		// 12
		{
			&serverConfig{Notify: notifier{Webhook: map[string]target.WebhookArgs{"1": {Enable: true}}}},
			&serverConfig{Notify: notifier{Webhook: map[string]target.WebhookArgs{"1": {Enable: false}}}},
			"Webhook Notification configuration differs",
		},
		// 13
		{
			&serverConfig{Notify: notifier{MySQL: map[string]target.MySQLArgs{"1": {Enable: true}}}},
			&serverConfig{Notify: notifier{MySQL: map[string]target.MySQLArgs{"1": {Enable: false}}}},
			"MySQL Notification configuration differs",
		},
		// 14
		{
			&serverConfig{Notify: notifier{MQTT: map[string]target.MQTTArgs{"1": {Enable: true}}}},
			&serverConfig{Notify: notifier{MQTT: map[string]target.MQTTArgs{"1": {Enable: false}}}},
			"MQTT Notification configuration differs",
		},
		// 15
		{
			&serverConfig{Logger: loggerConfig{
				Console: loggerConsole{Enabled: true},
				HTTP:    map[string]loggerHTTP{"1": {Endpoint: "http://address1"}},
			}},
			&serverConfig{Logger: loggerConfig{
				Console: loggerConsole{Enabled: true},
				HTTP:    map[string]loggerHTTP{"1": {Endpoint: "http://address2"}},
			}},
			"Logger configuration differs",
		},
	}

	for i, testCase := range testCases {
		got := testCase.s.ConfigDiff(testCase.t)
		if got != testCase.diff {
			t.Errorf("Test %d: got %s expected %s", i+1, got, testCase.diff)
		}
	}
}


text: The default theme for my personal [site](http://seanl.in).

redpajama_set_name: RedPajamaGithub


text:
Reports any use of == or != to test for Number equality,
instead of an equals() call. With auto-boxing it is easy
to make the mistake of comparing two Integer (or other subclass of java.lang.Number) objects instead
of two ints.

Example:

  void foo(Integer a, Integer b) {
    final boolean bool = a == b;
  }

If a is known to be non null, then it's safe to apply "unsafe" quickfix and get the result like:

  void foo(Integer a, Integer b) {
    final boolean bool = a.equals(b);
  }


text:
START_ATF_NAMESPACE
    namespace Info
    {
        using _SFCONT_DB_BASEInit2_ptr = void (WINAPIV*)(struct _SFCONT_DB_BASE*);
        using _SFCONT_DB_BASEInit2_clbk = void (WINAPIV*)(struct _SFCONT_DB_BASE*, _SFCONT_DB_BASEInit2_ptr);

        using _SFCONT_DB_BASEctor__SFCONT_DB_BASE4_ptr = void (WINAPIV*)(struct _SFCONT_DB_BASE*);
        using _SFCONT_DB_BASEctor__SFCONT_DB_BASE4_clbk = void (WINAPIV*)(struct _SFCONT_DB_BASE*, _SFCONT_DB_BASEctor__SFCONT_DB_BASE4_ptr);
    }; // end namespace Info
END_ATF_NAMESPACE


text:
package org.deeplearning4j.models.sequencevectors.graph.vertex;

import org.deeplearning4j.models.sequencevectors.graph.primitives.Vertex;
import org.deeplearning4j.models.sequencevectors.sequence.SequenceElement;

/**
 * VertexFactory implementation
 *
 * @author raver119@gmail.com
 */
public class AbstractVertexFactory<T extends SequenceElement> implements VertexFactory<T> {

    @Override
    public Vertex<T> create(int vertexIdx) {
        Vertex<T> vertex = new Vertex<>(vertexIdx, null);
        return vertex;
    }

    @Override
    public Vertex<T> create(int vertexIdx, T element) {
        Vertex<T> vertex = new Vertex<>(vertexIdx, element);
        return vertex;
    }
}


text:
from linode import api as linode_api

class APICallMethod:
    """Imitates a method of the Handler class, and calls a specific API method."""
    def __init__(self, api_conn, method_name):
        self._api_conn = api_conn
        self._method = getattr(self._api_conn, method_name)
    def __call__(self, **kwargs):
        return self._method(**kwargs)

class Handler:
    """Passes on API calls to the linode library.

       You must set `api_key` before calling any API methods.

       The API methods you can call are the same as those offered by `linode.api.Api`."""
    def __init__(self):
        self.api_key = None
        self._api = None
    def __getattr__(self, name):
        return APICallMethod(self._get_api(), name)
    def _get_api(self):
        if self.api_key is None:
            raise RuntimeError("You must set the Handler's `api_key` attribute before using it")
        if self._api is None:
            self._api = linode_api.Api(self.api_key)
        return self._api

api_handler = Handler()


text:
#include "PciHostBridge.h"
#include <IntelQNCRegs.h>

//
// We can hardcode the following for a Simple IIO -
// Root Bridge Count within the host bridge
// Root Bridge's device path
// Root Bridge's resource appeture
//
EFI_PCI_ROOT_BRIDGE_DEVICE_PATH    mEfiPciRootBridgeDevicePath[ROOT_BRIDGE_COUNT] = {
  {
    {
      {
        ACPI_DEVICE_PATH,
        ACPI_DP,
        {
          (UINT8) (sizeof (ACPI_HID_DEVICE_PATH)),
          (UINT8) ((sizeof (ACPI_HID_DEVICE_PATH)) >> 8)
        }
      },
      EISA_PNP_ID (0x0A03),
      0
    },
    {
      END_DEVICE_PATH_TYPE,
      END_ENTIRE_DEVICE_PATH_SUBTYPE,
      {
        END_DEVICE_PATH_LENGTH,
        0
      }
    }
  }
};

EFI_HANDLE                         mDriverImageHandle;
PCI_ROOT_BRIDGE_RESOURCE_APERTURE  *mResAperture;

//
// Implementation
//
EFI_STATUS
EFIAPI
InitializePciHostBridge (
  IN EFI_HANDLE         ImageHandle,
  IN EFI_SYSTEM_TABLE   *SystemTable
  )
/*++

Routine Description:

  Entry point of this driver.

Arguments:

  ImageHandle  -  Image handle of this driver.
  SystemTable  -  Pointer to standard EFI system table.

Returns:

  EFI_SUCCESS       -  Succeed.
  EFI_DEVICE_ERROR  -  Fail to install PCI_ROOT_BRIDGE_IO protocol.

--*/
{
  EFI_STATUS                  Status;
  UINTN                       TotalRootBridgeFound;
  PCI_HOST_BRIDGE_INSTANCE    *HostBridge;
  PCI_ROOT_BRIDGE_INSTANCE    *PrivateData;
  UINT64                      AllocAttributes;
  EFI_PHYSICAL_ADDRESS        BaseAddress;

  PrivateData = NULL;

  mDriverImageHandle = ImageHandle;

  //
  // Most systems in the world including complex servers
  // have only one Host Bridge. Create Host Bridge Device Handle
  //
  Status = gBS->AllocatePool(EfiBootServicesData, sizeof(PCI_HOST_BRIDGE_INSTANCE), (VOID **) &HostBridge);
  ASSERT_EFI_ERROR (Status);
  ZeroMem (HostBridge, sizeof (PCI_HOST_BRIDGE_INSTANCE));

  HostBridge->Signature         = PCI_HOST_BRIDGE_SIGNATURE;
  HostBridge->RootBridgeCount   = 1;
  HostBridge->ResourceSubmited  = FALSE;
  HostBridge->CanRestarted      = TRUE;
  //
  // InitializeListHead (&HostBridge->Head);
  //
  HostBridge->ResAlloc.NotifyPhase          = NotifyPhase;
  HostBridge->ResAlloc.GetNextRootBridge    = GetNextRootBridge;
  HostBridge->ResAlloc.GetAllocAttributes   = GetAttributes;
  HostBridge->ResAlloc.StartBusEnumeration  = StartBusEnumeration;
  HostBridge->ResAlloc.SetBusNumbers        = SetBusNumbers;
  HostBridge->ResAlloc.SubmitResources      = SubmitResources;
  HostBridge->ResAlloc.GetProposedResources = GetProposedResources;
  HostBridge->ResAlloc.PreprocessController = PreprocessController;

  Status = gBS->InstallProtocolInterface (
                    &HostBridge->HostBridgeHandle,
                    &gEfiPciHostBridgeResourceAllocationProtocolGuid,
                    EFI_NATIVE_INTERFACE,
                    &HostBridge->ResAlloc
                    );
  if (EFI_ERROR (Status)) {
    gBS->FreePool (HostBridge);
    return EFI_DEVICE_ERROR;
  }

  Status = gBS->AllocatePool (EfiBootServicesData,
                HostBridge->RootBridgeCount * sizeof(PCI_ROOT_BRIDGE_RESOURCE_APERTURE),
                (VOID **) &mResAperture);
  ASSERT_EFI_ERROR (Status);
  ZeroMem (mResAperture, HostBridge->RootBridgeCount * sizeof(PCI_ROOT_BRIDGE_RESOURCE_APERTURE));

  DEBUG ((EFI_D_INFO, "Address of resource Aperture:  %x\n", mResAperture));

  //
  // Create Root Bridge Device Handle in this Host Bridge
  //
  InitializeListHead (&HostBridge->Head);

  TotalRootBridgeFound = 0;

  Status = gBS->AllocatePool ( EfiBootServicesData,sizeof (PCI_ROOT_BRIDGE_INSTANCE), (VOID **) &PrivateData);
  ASSERT_EFI_ERROR (Status);
  ZeroMem (PrivateData, sizeof (PCI_ROOT_BRIDGE_INSTANCE));

  PrivateData->Signature  = PCI_ROOT_BRIDGE_SIGNATURE;
  PrivateData->DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) &mEfiPciRootBridgeDevicePath[TotalRootBridgeFound];
  AllocAttributes         = GetAllocAttributes (TotalRootBridgeFound);

  SimpleIioRootBridgeConstructor (
      &PrivateData->Io,
      HostBridge->HostBridgeHandle,
      &(mResAperture[TotalRootBridgeFound]),
      AllocAttributes
      );
  //
  // Update Root Bridge with UDS resource information
  //
  PrivateData->Aperture.BusBase    = QNC_PCI_HOST_BRIDGE_RESOURCE_APPETURE_BUSBASE;
  PrivateData->Aperture.BusLimit   = QNC_PCI_HOST_BRIDGE_RESOURCE_APPETURE_BUSLIMIT;
  PrivateData->Aperture.Mem32Base  = PcdGet32 (PcdPciHostBridgeMemory32Base);
  PrivateData->Aperture.Mem32Limit = PcdGet32 (PcdPciHostBridgeMemory32Base) + (PcdGet32 (PcdPciHostBridgeMemory32Size) - 1);
  PrivateData->Aperture.IoBase  = PcdGet16 (PcdPciHostBridgeIoBase);
  PrivateData->Aperture.IoLimit = PcdGet16 (PcdPciHostBridgeIoBase) + (PcdGet16 (PcdPciHostBridgeIoSize) - 1);

  DEBUG ((EFI_D_INFO, "PCI Host Bridge BusBase:               %x\n",  QNC_PCI_HOST_BRIDGE_RESOURCE_APPETURE_BUSBASE));
  DEBUG ((EFI_D_INFO, "PCI Host Bridge BusLimit:              %x\n",  QNC_PCI_HOST_BRIDGE_RESOURCE_APPETURE_BUSLIMIT));
  DEBUG ((EFI_D_INFO, "PCI Host Bridge PciResourceMem32Base:  %x\n",  PcdGet32 (PcdPciHostBridgeMemory32Base)));
  DEBUG ((EFI_D_INFO, "PCI Host Bridge PciResourceMem32Limit: %x\n",  PcdGet32 (PcdPciHostBridgeMemory32Base) + (PcdGet32 (PcdPciHostBridgeMemory32Size) - 1)));
  DEBUG ((EFI_D_INFO, "PCI Host Bridge PciResourceMem64Base:  %lX\n", PcdGet64 (PcdPciHostBridgeMemory64Base)));
  DEBUG ((EFI_D_INFO, "PCI Host Bridge PciResourceMem64Limit: %lX\n", PcdGet64 (PcdPciHostBridgeMemory64Base) + (PcdGet64 (PcdPciHostBridgeMemory64Size) - 1)));
  DEBUG ((EFI_D_INFO, "PCI Host Bridge PciResourceIoBase:     %x\n",  PcdGet16 (PcdPciHostBridgeIoBase)));
  DEBUG ((EFI_D_INFO, "PCI Host Bridge PciResourceIoLimit:    %x\n",  PcdGet16 (PcdPciHostBridgeIoBase) + (PcdGet16 (PcdPciHostBridgeIoSize) - 1)));

  PrivateData->Handle = NULL;
  Status = gBS->InstallMultipleProtocolInterfaces (
                  &PrivateData->Handle,
                  &gEfiDevicePathProtocolGuid,
                  PrivateData->DevicePath,
                  &gEfiPciRootBridgeIoProtocolGuid,
                  &PrivateData->Io,
                  NULL
                  );
  ASSERT_EFI_ERROR (Status);

  InsertTailList (&HostBridge->Head, &PrivateData->Link);
  TotalRootBridgeFound++;           // This is a valid rootbridge so imcrement total root bridges found

  //
  // Add PCIE base into Runtime memory so that it can be reported in E820 table
  //
  Status = gDS->AddMemorySpace (
                  EfiGcdMemoryTypeMemoryMappedIo,
                  PcdGet64 (PcdPciExpressBaseAddress),
                  PcdGet64 (PcdPciExpressSize),
                  EFI_MEMORY_RUNTIME | EFI_MEMORY_UC
                  );
  ASSERT_EFI_ERROR(Status);

  BaseAddress = PcdGet64 (PcdPciExpressBaseAddress);

  Status = gDS->AllocateMemorySpace (
                  EfiGcdAllocateAddress,
                  EfiGcdMemoryTypeMemoryMappedIo,
                  0,
                  PcdGet64 (PcdPciExpressSize),
                  &BaseAddress,
                  ImageHandle,
                  NULL
                  );
  ASSERT_EFI_ERROR(Status);

  Status = gDS->SetMemorySpaceAttributes (
                  PcdGet64 (PcdPciExpressBaseAddress),
                  PcdGet64 (PcdPciExpressSize),
                  EFI_MEMORY_RUNTIME
                  );
  ASSERT_EFI_ERROR (Status);

  if (PcdGet16 (PcdPciHostBridgeIoSize) > 0) {
    //
    // At present, we use up the first 4k for fixed ranges like
    // ICH GPIO, ACPI and ISA devices. The first 4k is not
    // tracked through GCD. It should be.
    //
    Status = gDS->AddIoSpace (
                    EfiGcdIoTypeIo,
                    PcdGet16(PcdPciHostBridgeIoBase),
                    PcdGet16(PcdPciHostBridgeIoSize)
                    );
    ASSERT_EFI_ERROR (Status);
  }

  if (PcdGet32(PcdPciHostBridgeMemory32Size) > 0) {
    //
    // Shouldn't the capabilities be UC?
    //
    Status = gDS->AddMemorySpace (
                    EfiGcdMemoryTypeMemoryMappedIo,
                    PcdGet32(PcdPciHostBridgeMemory32Base),
                    PcdGet32(PcdPciHostBridgeMemory32Size),
                    0
                    );
    ASSERT_EFI_ERROR (Status);
  }

  return Status;
}

EFI_STATUS
EFIAPI
NotifyPhase (
  IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
  IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PHASE    Phase
  )
/*++

Routine Description:

  Enter a certain phase of the PCI enumeration process.

Arguments:

  This   -  The EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL instance.
  Phase  -  The phase during enumeration.

Returns:

  EFI_SUCCESS            -  Succeed.
  EFI_INVALID_PARAMETER  -  Wrong phase parameter passed in.
  EFI_NOT_READY          -  Resources have not been submitted yet.

--*/
{
  PCI_HOST_BRIDGE_INSTANCE              *HostBridgeInstance;
  PCI_ROOT_BRIDGE_INSTANCE              *RootBridgeInstance;
  PCI_RESOURCE_TYPE                     Index;
  EFI_LIST_ENTRY                        *List;
  EFI_PHYSICAL_ADDRESS                  BaseAddress;
  UINT64                                AddrLen;
  UINTN                                 BitsOfAlignment;
  UINT64                                Alignment;
  EFI_STATUS                            Status;
  EFI_STATUS                            ReturnStatus;
  PCI_RESOURCE_TYPE                     Index1;
  PCI_RESOURCE_TYPE                     Index2;
  BOOLEAN                               ResNodeHandled[TypeMax];
  UINT64                                MaxAlignment;

  HostBridgeInstance = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);

  switch (Phase) {
    case EfiPciHostBridgeBeginEnumeration:
        if (HostBridgeInstance->CanRestarted) {
          //
          // Reset Root Bridge
          //
          List = HostBridgeInstance->Head.ForwardLink;

          while (List != &HostBridgeInstance->Head) {
            RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
            for (Index = TypeIo; Index < TypeMax; Index++) {
              RootBridgeInstance->ResAllocNode[Index].Type    = Index;
              RootBridgeInstance->ResAllocNode[Index].Base    = 0;
              RootBridgeInstance->ResAllocNode[Index].Length  = 0;
              RootBridgeInstance->ResAllocNode[Index].Status  = ResNone;
            } // for

            List = List->ForwardLink;
          } // while

          HostBridgeInstance->ResourceSubmited  = FALSE;
          HostBridgeInstance->CanRestarted      = TRUE;
        } else {
          //
          // Can not restart
          //
          return EFI_NOT_READY;
        } // if
        break;

    case EfiPciHostBridgeEndEnumeration:
        return EFI_SUCCESS;
        break;

    case EfiPciHostBridgeBeginBusAllocation:
        //
        // No specific action is required here, can perform any chipset specific programing
        //
        HostBridgeInstance->CanRestarted = FALSE;
        return EFI_SUCCESS;
        break;

    case EfiPciHostBridgeEndBusAllocation:
        //
        // No specific action is required here, can perform any chipset specific programing
        //
        // HostBridgeInstance->CanRestarted = FALSE;
        //
        return EFI_SUCCESS;
        break;

    case EfiPciHostBridgeBeginResourceAllocation:
        //
        // No specific action is required here, can perform any chipset specific programing
        //
        // HostBridgeInstance->CanRestarted = FALSE;
        //
        return EFI_SUCCESS;
        break;

    case EfiPciHostBridgeAllocateResources:
        ReturnStatus = EFI_SUCCESS;
        if (HostBridgeInstance->ResourceSubmited) {
          List = HostBridgeInstance->Head.ForwardLink;
          while (List != &HostBridgeInstance->Head) {
            for (Index1 = TypeIo; Index1 < TypeBus; Index1++) {
              ResNodeHandled[Index1] = FALSE;
            }

            RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
            DEBUG ((EFI_D_INFO, "Address of RootBridgeInstance:   %x)\n", RootBridgeInstance));
            DEBUG ((EFI_D_INFO, "  Signature:              %x\n", RootBridgeInstance->Signature));
            DEBUG ((EFI_D_INFO, "  Bus Number Assigned:    %x\n", RootBridgeInstance->BusNumberAssigned));
            DEBUG ((EFI_D_INFO, "  Bus Scan Count:         %x\n", RootBridgeInstance->BusScanCount));

            for (Index1 = TypeIo; Index1 < TypeBus; Index1++) {
              if (RootBridgeInstance->ResAllocNode[Index1].Status == ResNone) {
                ResNodeHandled[Index1] = TRUE;
              } else {
                //
                // Allocate the resource node with max alignment at first
                //
                MaxAlignment = 0;
                Index        = TypeMax;
                for (Index2 = TypeIo; Index2 < TypeBus; Index2++) {
                  if (ResNodeHandled[Index2]) {
                    continue;
                  }
                  if (MaxAlignment <= RootBridgeInstance->ResAllocNode[Index2].Alignment) {
                    MaxAlignment = RootBridgeInstance->ResAllocNode[Index2].Alignment;
                    Index = Index2;
                  }
                } // for

                if (Index < TypeMax) {
                  ResNodeHandled[Index] = TRUE;
                } else {
                  ASSERT (FALSE);
                }

                Alignment = RootBridgeInstance->ResAllocNode[Index].Alignment;

                //
                // Get the number of '1' in Alignment.
                //
                for (BitsOfAlignment = 0; Alignment != 0; BitsOfAlignment++) {
                  Alignment = RShiftU64 (Alignment, 1);
                }

                AddrLen   = RootBridgeInstance->ResAllocNode[Index].Length;
                Alignment = RootBridgeInstance->ResAllocNode[Index].Alignment;

                DEBUG ((EFI_D_INFO, "\n\nResource Type to assign :   %x\n", Index));
                DEBUG ((EFI_D_INFO, "  Length to allocate:       %x\n", RootBridgeInstance->ResAllocNode[Index].Length));
                DEBUG ((EFI_D_INFO, "  Aligment:                 %x\n", Alignment));

                switch (Index) {
                  case TypeIo:
                      if (RootBridgeInstance->Aperture.IoBase < RootBridgeInstance->Aperture.IoLimit) {
                        //
                        // It is impossible for 0xFFFF Alignment for IO16
                        //
                        if (BitsOfAlignment >= 16)
                          Alignment = 0;

                        BaseAddress = RootBridgeInstance->Aperture.IoBase;

                        //
                        // Have to make sure Aligment is handled seeing we are doing direct address allocation
                        //
                        if ((BaseAddress & ~(Alignment)) != BaseAddress)
                          BaseAddress = ((BaseAddress + Alignment) & ~(Alignment));

                        while((BaseAddress + AddrLen) <= RootBridgeInstance->Aperture.IoLimit + 1) {

                          Status = gDS->AllocateIoSpace ( EfiGcdAllocateAddress, EfiGcdIoTypeIo, BitsOfAlignment,
                                                          AddrLen, &BaseAddress, mDriverImageHandle, NULL );

                          if (!EFI_ERROR (Status)) {
                            RootBridgeInstance->ResAllocNode[Index].Base    = (UINT64) BaseAddress;
                            RootBridgeInstance->ResAllocNode[Index].Status  = ResAllocated;
                            goto TypeIoFound;
                          }

                          BaseAddress += (Alignment + 1);
                        } // while

                      } // if

                      TypeIoFound:
                      if (RootBridgeInstance->ResAllocNode[Index].Status  != ResAllocated) {
                        //
                        // No Room at the Inn for this resources request
                        //
                        ReturnStatus = EFI_OUT_OF_RESOURCES;
                      } // if

                      break;

                  case TypeMem32:
                      if (RootBridgeInstance->Aperture.Mem32Base < RootBridgeInstance->Aperture.Mem32Limit) {

                        BaseAddress = RootBridgeInstance->Aperture.Mem32Base;
                        //
                        // Have to make sure Aligment is handled seeing we are doing direct address allocation
                        //
                        if ((BaseAddress & ~(Alignment)) != BaseAddress)
                          BaseAddress = ((BaseAddress + Alignment) & ~(Alignment));

                        while((BaseAddress + AddrLen) <= RootBridgeInstance->Aperture.Mem32Limit + 1) {

                          Status = gDS->AllocateMemorySpace ( EfiGcdAllocateAddress, EfiGcdMemoryTypeMemoryMappedIo,
                                                            BitsOfAlignment, AddrLen, &BaseAddress, mDriverImageHandle, NULL);

                          if (!EFI_ERROR (Status)) {
                            RootBridgeInstance->ResAllocNode[Index].Base    = (UINT64) BaseAddress;
                            RootBridgeInstance->ResAllocNode[Index].Status  = ResAllocated;
                            goto TypeMem32Found;
                          } // if

                          BaseAddress += (Alignment + 1);
                        } // while
                      } // if

                      TypeMem32Found:
                      if (RootBridgeInstance->ResAllocNode[Index].Status  != ResAllocated) {
                        //
                        // No Room at the Inn for this resources request
                        //
                        ReturnStatus = EFI_OUT_OF_RESOURCES;
                      }

                      break;

                  case TypePMem32:
                      StartTypePMem32:
                      if (RootBridgeInstance->Aperture.Mem32Base < RootBridgeInstance->Aperture.Mem32Limit) {

                        BaseAddress = RootBridgeInstance->Aperture.Mem32Limit + 1;
                        BaseAddress -= AddrLen;

                        //
                        // Have to make sure Aligment is handled seeing we are doing direct address allocation
                        //
                        if ((BaseAddress & ~(Alignment)) != BaseAddress)
                          BaseAddress = ((BaseAddress) & ~(Alignment));

                        while(RootBridgeInstance->Aperture.Mem32Base <= BaseAddress) {

                          DEBUG ((EFI_D_INFO, "      Attempting %x allocation at 0x%lx .....", Index, BaseAddress));
                          Status = gDS->AllocateMemorySpace ( EfiGcdAllocateAddress, EfiGcdMemoryTypeMemoryMappedIo,
                                                  BitsOfAlignment, AddrLen, &BaseAddress, mDriverImageHandle, NULL);

                          if (!EFI_ERROR (Status)) {
                            RootBridgeInstance->ResAllocNode[Index].Base    = (UINT64) BaseAddress;
                            RootBridgeInstance->ResAllocNode[Index].Status  = ResAllocated;
                            DEBUG ((EFI_D_INFO, "... Passed!!\n"));
                            goto TypePMem32Found;
                          }
                          DEBUG ((EFI_D_INFO, "... Failed!!\n"));
                          BaseAddress -= (Alignment + 1);
                        } // while
                      } // if

                      TypePMem32Found:
                      if (RootBridgeInstance->ResAllocNode[Index].Status  != ResAllocated) {
                        //
                        // No Room at the Inn for this resources request
                        //
                        ReturnStatus = EFI_OUT_OF_RESOURCES;
                      }

                      break;

                  case TypeMem64:
                  case TypePMem64:
                      if (RootBridgeInstance->ResAllocNode[Index].Status  != ResAllocated) {
                        //
                        // If 64-bit resourcing is not available, then try as PMem32
                        //
                        goto StartTypePMem32;
                      }

                      break;

                  default:
                      break;
                } // End switch (Index)

                DEBUG ((EFI_D_INFO, "Resource Type Assigned:   %x\n", Index));
                if (RootBridgeInstance->ResAllocNode[Index].Status == ResAllocated) {
                  DEBUG ((EFI_D_INFO, "  Base Address Assigned: %x\n", RootBridgeInstance->ResAllocNode[Index].Base));
                  DEBUG ((EFI_D_INFO, "  Length Assigned:       %x\n", RootBridgeInstance->ResAllocNode[Index].Length));
                } else {
                  DEBUG ((DEBUG_ERROR, "  Resource Allocation failed!  There was no room at the inn\n"));
                }

              }
            }

            List = List->ForwardLink;
          }

          if (ReturnStatus == EFI_OUT_OF_RESOURCES) {
            DEBUG ((DEBUG_ERROR, "Resource allocation Failed. Continue booting the system.\n"));
          }

          //
          // Set resource to zero for nodes where allocation fails
          //
          List = HostBridgeInstance->Head.ForwardLink;
          while (List != &HostBridgeInstance->Head) {
            RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
            for (Index = TypeIo; Index < TypeBus; Index++) {
              if (RootBridgeInstance->ResAllocNode[Index].Status != ResAllocated) {
                RootBridgeInstance->ResAllocNode[Index].Length = 0;
              }
            }
            List = List->ForwardLink;
          }
          return ReturnStatus;
        } else {
          return EFI_NOT_READY;
        }
        //
        // HostBridgeInstance->CanRestarted = FALSE;
        //
        break;

    case EfiPciHostBridgeSetResources:
        //
        // HostBridgeInstance->CanRestarted = FALSE;
        //
        break;

    case EfiPciHostBridgeFreeResources:
        //
        // HostBridgeInstance->CanRestarted = FALSE;
        //
        ReturnStatus  = EFI_SUCCESS;
        List          = HostBridgeInstance->Head.ForwardLink;
        while (List != &HostBridgeInstance->Head) {
          RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
          for (Index = TypeIo; Index < TypeBus; Index++) {
            if (RootBridgeInstance->ResAllocNode[Index].Status == ResAllocated) {
              AddrLen     = RootBridgeInstance->ResAllocNode[Index].Length;
              BaseAddress = (EFI_PHYSICAL_ADDRESS) RootBridgeInstance->ResAllocNode[Index].Base;
              switch (Index) {
                case TypeIo:
                    Status = gDS->FreeIoSpace (BaseAddress, AddrLen);
                    if (EFI_ERROR (Status)) {
                      ReturnStatus = Status;
                    }
                    break;

                case TypeMem32:
                    Status = gDS->FreeMemorySpace (BaseAddress, AddrLen);
                    if (EFI_ERROR (Status)) {
                      ReturnStatus = Status;
                    }
                    break;

                case TypePMem32:
                    break;

                case TypeMem64:
                    break;

                case TypePMem64:
                    Status = gDS->FreeMemorySpace (BaseAddress, AddrLen);
                    if (EFI_ERROR (Status)) {
                      ReturnStatus = Status;
                    }
                    break;

                default:
                    break;
              } // end switch (Index)

              RootBridgeInstance->ResAllocNode[Index].Type    = Index;
              RootBridgeInstance->ResAllocNode[Index].Base    = 0;
              RootBridgeInstance->ResAllocNode[Index].Length  = 0;
              RootBridgeInstance->ResAllocNode[Index].Status  = ResNone;
            }
          }

          List = List->ForwardLink;
        }

        HostBridgeInstance->ResourceSubmited  = FALSE;
        HostBridgeInstance->CanRestarted      = TRUE;
        return ReturnStatus;
        break;

    case EfiPciHostBridgeEndResourceAllocation:
        //
        // Resource enumeration is done. Perform any activities that
        // must wait until that time.
        //
        break;

    default:
        return EFI_INVALID_PARAMETER;
  } // End switch (Phase)

  return EFI_SUCCESS;
}

EFI_STATUS
EFIAPI
GetNextRootBridge (
  IN     EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
  IN OUT EFI_HANDLE                                       *RootBridgeHandle
  )
/*++

Routine Description:
  Return the device handle of the next PCI root bridge that is associated with
  this Host Bridge.

Arguments:

  This              -  The EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_ PROTOCOL instance.
  RootBridgeHandle  -  Returns the device handle of the next PCI Root Bridge.
                       On input, it holds the RootBridgeHandle returned by the most
                       recent call to GetNextRootBridge().The handle for the first
                       PCI Root Bridge is returned if RootBridgeHandle is NULL on input.

Returns:

  EFI_SUCCESS            -  Succeed.
  EFI_NOT_FOUND          -  Next PCI root bridge not found.
  EFI_INVALID_PARAMETER  -  Wrong parameter passed in.

--*/
{
  BOOLEAN                   NoRootBridge;
  EFI_LIST_ENTRY            *List;
  PCI_HOST_BRIDGE_INSTANCE  *HostBridgeInstance;
  PCI_ROOT_BRIDGE_INSTANCE  *RootBridgeInstance;

  NoRootBridge        = TRUE;
  HostBridgeInstance  = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
  List                = HostBridgeInstance->Head.ForwardLink;

  while (List != &HostBridgeInstance->Head) {
    NoRootBridge        = FALSE;
    RootBridgeInstance  = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
    if (*RootBridgeHandle == NULL) {
      //
      // Return the first Root Bridge Handle of the Host Bridge
      //
      *RootBridgeHandle = RootBridgeInstance->Handle;
      return EFI_SUCCESS;
    } else {
      if (*RootBridgeHandle == RootBridgeInstance->Handle) {
        //
        // Get next if have
        //
        List = List->ForwardLink;
        if (List != &HostBridgeInstance->Head) {
          RootBridgeInstance  = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
          *RootBridgeHandle   = RootBridgeInstance->Handle;
          return EFI_SUCCESS;
        } else {
          return EFI_NOT_FOUND;
        }
      }
    }

    List = List->ForwardLink;
    //
    // end while
    //
  }

  if (NoRootBridge) {
    return EFI_NOT_FOUND;
  } else {
    return EFI_INVALID_PARAMETER;
  }
}

EFI_STATUS
EFIAPI
GetAttributes (
  IN  EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
  IN  EFI_HANDLE                                       RootBridgeHandle,
  OUT UINT64                                           *Attributes
  )
/*++

Routine Description:
  Returns the attributes of a PCI Root Bridge.

Arguments:

  This              -  The EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_ PROTOCOL instance.
  RootBridgeHandle  -  The device handle of the PCI Root Bridge
                       that the caller is interested in.
  Attributes        -  The pointer to attributes of the PCI Root Bridge.

Returns:

  EFI_SUCCESS            -  Succeed.
  EFI_INVALID_PARAMETER  -  Attributes parameter passed in is NULL or
                            RootBridgeHandle is not an EFI_HANDLE
                            that was returned on a previous call to
                            GetNextRootBridge().

--*/
{
  EFI_LIST_ENTRY            *List;
  PCI_HOST_BRIDGE_INSTANCE  *HostBridgeInstance;
  PCI_ROOT_BRIDGE_INSTANCE  *RootBridgeInstance;

  if (Attributes == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  HostBridgeInstance  = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
  List                = HostBridgeInstance->Head.ForwardLink;

  while (List != &HostBridgeInstance->Head) {
    RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
    if (RootBridgeHandle == RootBridgeInstance->Handle) {
      *Attributes = RootBridgeInstance->RootBridgeAllocAttrib;
      return EFI_SUCCESS;
    }

    List = List->ForwardLink;
  }
  //
  // RootBridgeHandle is not an EFI_HANDLE
  // that was returned on a previous call to GetNextRootBridge()
  //
  return EFI_INVALID_PARAMETER;
}

EFI_STATUS
EFIAPI
StartBusEnumeration (
  IN  EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
  IN  EFI_HANDLE                                       RootBridgeHandle,
  OUT VOID                                             **Configuration
  )
/*++

Routine Description:
  This is the request from the PCI enumerator to set up
  the specified PCI Root Bridge for bus enumeration process.

Arguments:

  This              -  The EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_ PROTOCOL instance.
  RootBridgeHandle  -  The PCI Root Bridge to be set up.
  Configuration     -  Pointer to the pointer to the PCI bus resource descriptor.

Returns:

  EFI_SUCCESS            -  Succeed.
  EFI_OUT_OF_RESOURCES   -  Not enough pool to be allocated.
  EFI_INVALID_PARAMETER  -  RootBridgeHandle is not a valid handle.

--*/
{
  EFI_LIST_ENTRY            *List;
  PCI_HOST_BRIDGE_INSTANCE  *HostBridgeInstance;
  PCI_ROOT_BRIDGE_INSTANCE  *RootBridgeInstance;
  VOID                      *Buffer;
  UINT8                     *Temp;
  EFI_STATUS                Status;
  UINTN                     BusStart;
  UINTN                     BusEnd;
  UINT64                    BusReserve;

  HostBridgeInstance  = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
  List                = HostBridgeInstance->Head.ForwardLink;

  while (List != &HostBridgeInstance->Head) {
    RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
    if (RootBridgeHandle == RootBridgeInstance->Handle) {
      //
      // Set up the Root Bridge for Bus Enumeration
      //
      BusStart  = RootBridgeInstance->Aperture.BusBase;
      BusEnd    = RootBridgeInstance->Aperture.BusLimit;
      BusReserve = RootBridgeInstance->Aperture.BusReserve;
      //
      // Program the Hardware(if needed) if error return EFI_DEVICE_ERROR
      //
      Status = gBS->AllocatePool (
                      EfiBootServicesData,
                      sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) + sizeof (EFI_ACPI_END_TAG_DESCRIPTOR),
                      &Buffer
                      );
      if (EFI_ERROR (Status)) {
        return EFI_OUT_OF_RESOURCES;
      }

      Temp  = (UINT8 *) Buffer;

      ((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp)->Desc                  = ACPI_ADDRESS_SPACE_DESCRIPTOR;
      ((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp)->Len                   = 0x2B;
      ((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp)->ResType               = ACPI_ADDRESS_SPACE_TYPE_BUS;
      ((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp)->GenFlag               = 0;
      ((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp)->SpecificFlag          = 0;
      ((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp)->AddrSpaceGranularity  = 0;
      ((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp)->AddrRangeMin          = BusStart;
      ((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp)->AddrRangeMax          = BusReserve;
      ((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp)->AddrTranslationOffset = 0;
      ((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp)->AddrLen               = BusEnd - BusStart + 1;

      Temp = Temp + sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR);
      ((EFI_ACPI_END_TAG_DESCRIPTOR *) Temp)->Desc = ACPI_END_TAG_DESCRIPTOR;
      ((EFI_ACPI_END_TAG_DESCRIPTOR *) Temp)->Checksum = 0x0;

      *Configuration = Buffer;
      return EFI_SUCCESS;
    }

    List = List->ForwardLink;
  }

  return EFI_INVALID_PARAMETER;
}

EFI_STATUS
EFIAPI
SetBusNumbers (
  IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
  IN EFI_HANDLE                                       RootBridgeHandle,
  IN VOID                                             *Configuration
  )
/*++

Routine Description:
  This function programs the PCI Root Bridge hardware so that
  it decodes the specified PCI bus range.

Arguments:

  This              -  The EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_ PROTOCOL instance.
  RootBridgeHandle  -  The PCI Root Bridge whose bus range is to be programmed.
  Configuration     -  The pointer to the PCI bus resource descriptor.

Returns:

  EFI_SUCCESS            -  Succeed.
  EFI_INVALID_PARAMETER  -  Wrong parameters passed in.

--*/
{
  EFI_LIST_ENTRY            *List;
  PCI_HOST_BRIDGE_INSTANCE  *HostBridgeInstance;
  PCI_ROOT_BRIDGE_INSTANCE  *RootBridgeInstance;
  UINT8                     *Ptr;
  UINTN                     BusStart;
  UINTN                     BusEnd;
  UINTN                     BusLen;

  if (Configuration == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  Ptr = Configuration;

  //
  // Check the Configuration is valid
  //
  if (*Ptr != ACPI_ADDRESS_SPACE_DESCRIPTOR) {
    return EFI_INVALID_PARAMETER;
  }

  if (((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Ptr)->ResType != ACPI_ADDRESS_SPACE_TYPE_BUS) {
    return EFI_INVALID_PARAMETER;
  }

  Ptr += sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR);
  if (*Ptr != ACPI_END_TAG_DESCRIPTOR) {
    return EFI_INVALID_PARAMETER;
  }

  HostBridgeInstance  = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
  List                = HostBridgeInstance->Head.ForwardLink;

  Ptr                 = Configuration;

  while (List != &HostBridgeInstance->Head) {
    RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
    if (RootBridgeHandle == RootBridgeInstance->Handle) {
      BusStart  = (UINTN) ((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Ptr)->AddrRangeMin;
      BusLen    = (UINTN) ((EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Ptr)->AddrLen;
      BusEnd    = BusStart + BusLen - 1;

      if (BusStart > BusEnd) {
        return EFI_INVALID_PARAMETER;
      }

      if ((BusStart < RootBridgeInstance->Aperture.BusBase) || (BusEnd > RootBridgeInstance->Aperture.BusLimit)) {
        return EFI_INVALID_PARAMETER;
      }
      //
      // Update the Bus Range
      //
      RootBridgeInstance->ResAllocNode[TypeBus].Base    = BusStart;
      RootBridgeInstance->ResAllocNode[TypeBus].Length  = BusLen;
      RootBridgeInstance->ResAllocNode[TypeBus].Status  = ResAllocated;
      RootBridgeInstance->BusScanCount++;
      if (RootBridgeInstance->BusScanCount > 0) {
        //
        // Only care about the 2nd PCI bus scanning
        //
        RootBridgeInstance->BusNumberAssigned = TRUE;
      }

      return EFI_SUCCESS;
    }

    List = List->ForwardLink;
  }

  return EFI_INVALID_PARAMETER;
}

EFI_STATUS
EFIAPI
SubmitResources (
  IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
  IN EFI_HANDLE                                       RootBridgeHandle,
  IN VOID                                             *Configuration
  )
/*++

Routine Description:

  Submits the I/O and memory resource requirements for the specified PCI Root Bridge.

Arguments:
  This              -  The EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_ PROTOCOL instance.
  RootBridgeHandle  -  The PCI Root Bridge whose I/O and memory resource requirements.
                       are being submitted.
  Configuration     -  The pointer to the PCI I/O and PCI memory resource descriptor.

Returns:

  EFI_SUCCESS            -  Succeed.
  EFI_INVALID_PARAMETER  -  Wrong parameters passed in.

--*/
{
  EFI_LIST_ENTRY                    *List;
  PCI_HOST_BRIDGE_INSTANCE          *HostBridgeInstance;
  PCI_ROOT_BRIDGE_INSTANCE          *RootBridgeInstance;
  UINT8                             *Temp;
  EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *ptr;
  UINT64                            AddrLen;
  UINT64                            Alignment;
  UINT64                            Value;

  //
  // Check the input parameter: Configuration
  //
  if (Configuration == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  HostBridgeInstance  = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
  List                = HostBridgeInstance->Head.ForwardLink;

  Temp = (UINT8 *) Configuration;
  while (List != &HostBridgeInstance->Head) {
    RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
    if (RootBridgeHandle == RootBridgeInstance->Handle) {
      //
      // Check the resource descriptors.
      // If the Configuration includes one or more invalid resource descriptors, all the resource
      // descriptors are ignored and the function returns EFI_INVALID_PARAMETER.
      //
      while (*Temp == ACPI_ADDRESS_SPACE_DESCRIPTOR) {
        ptr = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp;
        DEBUG ((EFI_D_INFO, " ptr->ResType:%x \n",ptr->ResType));
        DEBUG ((EFI_D_INFO, "  ptr->AddrLen:0x%lx AddrRangeMin:0x%lx AddrRangeMax:0x%lx\n\n",ptr->AddrLen,ptr->AddrRangeMin,ptr->AddrRangeMax));

        switch (ptr->ResType) {
          case ACPI_ADDRESS_SPACE_TYPE_MEM:
            if (ptr->AddrSpaceGranularity != 32 && ptr->AddrSpaceGranularity != 64) {
              return EFI_INVALID_PARAMETER;
            }
            if (ptr->AddrSpaceGranularity == 32 && ptr->AddrLen > 0xffffffff) {
              return EFI_INVALID_PARAMETER;
            }
            //
            // If the PCI root bridge does not support separate windows for nonprefetchable and
            // prefetchable memory, then the PCI bus driver needs to include requests for
            // prefetchable memory in the nonprefetchable memory pool.
            //
            if ((RootBridgeInstance->RootBridgeAllocAttrib & EFI_PCI_HOST_BRIDGE_COMBINE_MEM_PMEM) != 0 &&
                ((ptr->SpecificFlag & (BIT2 | BIT1)) != 0)) {
              return EFI_INVALID_PARAMETER;
            }
          case ACPI_ADDRESS_SPACE_TYPE_IO:
            //
            // Check aligment, it should be of the form 2^n-1
            //
            Value = Power2MaxMemory (ptr->AddrRangeMax + 1);
            if (Value != (ptr->AddrRangeMax + 1)) {
              CpuDeadLoop();
              return EFI_INVALID_PARAMETER;
            }
            break;
          case ACPI_ADDRESS_SPACE_TYPE_BUS:
          default:
            return EFI_INVALID_PARAMETER;
        }
        Temp += sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) ;
      }
      if (*Temp != ACPI_END_TAG_DESCRIPTOR) {
        return EFI_INVALID_PARAMETER;
      }

      Temp = (UINT8 *) Configuration;
      while (*Temp == ACPI_ADDRESS_SPACE_DESCRIPTOR) {
        ptr = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp;

        switch (ptr->ResType) {
        case ACPI_ADDRESS_SPACE_TYPE_MEM:
          AddrLen   = (UINT64) ptr->AddrLen;
          Alignment = (UINT64) ptr->AddrRangeMax;
          if (ptr->AddrSpaceGranularity == 32) {
            if (ptr->SpecificFlag == 0x06) {
              //
              // Apply from GCD
              //
              RootBridgeInstance->ResAllocNode[TypePMem32].Status = ResSubmitted;
            } else {
              RootBridgeInstance->ResAllocNode[TypeMem32].Length    = AddrLen;
              RootBridgeInstance->ResAllocNode[TypeMem32].Alignment = Alignment;
              RootBridgeInstance->ResAllocNode[TypeMem32].Status    = ResRequested;
              HostBridgeInstance->ResourceSubmited                  = TRUE;
            }
          }

          if (ptr->AddrSpaceGranularity == 64) {
            if (ptr->SpecificFlag == 0x06) {
              RootBridgeInstance->ResAllocNode[TypePMem64].Status = ResSubmitted;
            } else {
              RootBridgeInstance->ResAllocNode[TypeMem64].Length    = AddrLen;
              RootBridgeInstance->ResAllocNode[TypeMem64].Alignment = Alignment;
              RootBridgeInstance->ResAllocNode[TypeMem64].Status    = ResSubmitted;
              HostBridgeInstance->ResourceSubmited                  = TRUE;
            }
          }
          break;

        case ACPI_ADDRESS_SPACE_TYPE_IO:
          AddrLen   = (UINT64) ptr->AddrLen;
          Alignment = (UINT64) ptr->AddrRangeMax;
          RootBridgeInstance->ResAllocNode[TypeIo].Length     = AddrLen;
          RootBridgeInstance->ResAllocNode[TypeIo].Alignment  = Alignment;
          RootBridgeInstance->ResAllocNode[TypeIo].Status     = ResRequested;
          HostBridgeInstance->ResourceSubmited                = TRUE;
          break;

        default:
          break;
        }

        Temp += sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR);
      }

      return EFI_SUCCESS;
    }

    List = List->ForwardLink;
  }

  return EFI_INVALID_PARAMETER;
}

EFI_STATUS
EFIAPI
GetProposedResources (
  IN  EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This,
  IN  EFI_HANDLE                                       RootBridgeHandle,
  OUT VOID                                             **Configuration
  )
/*++

Routine Description:
  This function returns the proposed resource settings for the specified
  PCI Root Bridge.

Arguments:

  This              -  The EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_ PROTOCOL instance.
  RootBridgeHandle  -  The PCI Root Bridge handle.
  Configuration     -  The pointer to the pointer to the PCI I/O
                       and memory resource descriptor.

Returns:

  EFI_SUCCESS            -  Succeed.
  EFI_OUT_OF_RESOURCES   -  Not enough pool to be allocated.
  EFI_INVALID_PARAMETER  -  RootBridgeHandle is not a valid handle.

--*/
{
  EFI_LIST_ENTRY                    *List;
  PCI_HOST_BRIDGE_INSTANCE          *HostBridgeInstance;
  PCI_ROOT_BRIDGE_INSTANCE          *RootBridgeInstance;
  UINTN                             Index;
  UINTN                             Number;
  VOID                              *Buffer;
  UINT8                             *Temp;
  EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *ptr;
  EFI_STATUS                        Status;
  UINT64                            ResStatus;

  Buffer  = NULL;
  Number  = 0;
  //
  // Get the Host Bridge Instance from the resource allocation protocol
  //
  HostBridgeInstance  = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
  List                = HostBridgeInstance->Head.ForwardLink;

  //
  // Enumerate the root bridges in this host bridge
  //
  while (List != &HostBridgeInstance->Head) {
    RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);
    if (RootBridgeHandle == RootBridgeInstance->Handle) {
      for (Index = 0; Index < TypeBus; Index++) {
        if (RootBridgeInstance->ResAllocNode[Index].Status != ResNone) {
          Number++;
        }
      }

      if (Number > 0) {
        Status = gBS->AllocatePool (
                        EfiBootServicesData,
                        Number * sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) + sizeof (EFI_ACPI_END_TAG_DESCRIPTOR),
                        &Buffer
                        );

        if (EFI_ERROR (Status)) {
          return EFI_OUT_OF_RESOURCES;
        }

        ZeroMem (Buffer, sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) * Number + sizeof (EFI_ACPI_END_TAG_DESCRIPTOR));
      }

      ASSERT (Buffer != NULL);
      Temp = Buffer;
      for (Index = 0; Index < TypeBus; Index++) {
        if (RootBridgeInstance->ResAllocNode[Index].Status != ResNone) {
          ptr       = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp;
          ResStatus = RootBridgeInstance->ResAllocNode[Index].Status;

          switch (Index) {

          case TypeIo:
            //
            // Io
            //
            ptr->Desc                   = 0x8A;
            ptr->Len                    = 0x2B;
            ptr->ResType                = 1;
            ptr->GenFlag                = 0;
            ptr->SpecificFlag           = 0;
            ptr->AddrRangeMin           = RootBridgeInstance->ResAllocNode[Index].Base;
            ptr->AddrRangeMax           = 0;
            ptr->AddrTranslationOffset  = (ResStatus == ResAllocated) ? EFI_RESOURCE_SATISFIED : EFI_RESOURCE_LESS;
            ptr->AddrLen                = RootBridgeInstance->ResAllocNode[Index].Length;
            break;

          case TypeMem32:
            //
            // Memory 32
            //
            ptr->Desc                   = 0x8A;
            ptr->Len                    = 0x2B;
            ptr->ResType                = 0;
            ptr->GenFlag                = 0;
            ptr->SpecificFlag           = 0;
            ptr->AddrSpaceGranularity   = 32;
            ptr->AddrRangeMin           = RootBridgeInstance->ResAllocNode[Index].Base;
            ptr->AddrRangeMax           = 0;
            ptr->AddrTranslationOffset  = (ResStatus == ResAllocated) ? EFI_RESOURCE_SATISFIED : EFI_RESOURCE_LESS;
            ptr->AddrLen                = RootBridgeInstance->ResAllocNode[Index].Length;
            break;

          case TypePMem32:
            //
            // Prefetch memory 32
            //
            ptr->Desc                   = 0x8A;
            ptr->Len                    = 0x2B;
            ptr->ResType                = 0;
            ptr->GenFlag                = 0;
            ptr->SpecificFlag           = 6;
            ptr->AddrSpaceGranularity   = 32;
            ptr->AddrRangeMin           = 0;
            ptr->AddrRangeMax           = 0;
            ptr->AddrTranslationOffset  = EFI_RESOURCE_NONEXISTENT;
            ptr->AddrLen                = 0;
            break;

          case TypeMem64:
            //
            // Memory 64
            //
            ptr->Desc                   = 0x8A;
            ptr->Len                    = 0x2B;
            ptr->ResType                = 0;
            ptr->GenFlag                = 0;
            ptr->SpecificFlag           = 0;
            ptr->AddrSpaceGranularity   = 64;
            ptr->AddrRangeMin           = RootBridgeInstance->ResAllocNode[Index].Base;
            ptr->AddrRangeMax           = 0;
            ptr->AddrTranslationOffset  = (ResStatus == ResAllocated) ? EFI_RESOURCE_SATISFIED : EFI_RESOURCE_LESS;
            ptr->AddrLen                = RootBridgeInstance->ResAllocNode[Index].Length;
            break;

          case TypePMem64:
            //
            // Prefetch memory 64
            //
            ptr->Desc                   = 0x8A;
            ptr->Len                    = 0x2B;
            ptr->ResType                = 0;
            ptr->GenFlag                = 0;
            ptr->SpecificFlag           = 6;
            ptr->AddrSpaceGranularity   = 64;
            ptr->AddrRangeMin           = 0;
            ptr->AddrRangeMax           = 0;
            ptr->AddrTranslationOffset  = EFI_RESOURCE_NONEXISTENT;
            ptr->AddrLen                = 0;
            break;
          }

          Temp += sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR);
        }
      }

      ((EFI_ACPI_END_TAG_DESCRIPTOR *) Temp)->Desc      = 0x79;
      ((EFI_ACPI_END_TAG_DESCRIPTOR *) Temp)->Checksum  = 0x0;

      *Configuration = Buffer;

      return EFI_SUCCESS;
    }

    List = List->ForwardLink;
  }

  return EFI_INVALID_PARAMETER;
}

EFI_STATUS
EFIAPI
PreprocessController (
  IN  EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL          *This,
  IN  EFI_HANDLE                                                RootBridgeHandle,
  IN  EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_PCI_ADDRESS               PciAddress,
  IN  EFI_PCI_CONTROLLER_RESOURCE_ALLOCATION_PHASE              Phase
  )
/*++

Routine Description:
  This function is called for all the PCI controllers that the PCI
  bus driver finds. Can be used to Preprogram the controller.

Arguments:

  This              -  The EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_ PROTOCOL instance.
  RootBridgeHandle  -  The PCI Root Bridge handle.
  PciAddress        -  Address of the controller on the PCI bus.
  Phase             -  The Phase during resource allocation.

Returns:

  EFI_SUCCESS            -  Succeed.
  EFI_INVALID_PARAMETER  -  RootBridgeHandle is not a valid handle.

--*/
{
  BOOLEAN                   RootBridgeFound;
  EFI_LIST_ENTRY            *List;
  PCI_HOST_BRIDGE_INSTANCE  *HostBridgeInstance;
  PCI_ROOT_BRIDGE_INSTANCE  *RootBridgeInstance;

  if (RootBridgeHandle == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  RootBridgeFound     = FALSE;
  HostBridgeInstance  = INSTANCE_FROM_RESOURCE_ALLOCATION_THIS (This);
  List                = HostBridgeInstance->Head.ForwardLink;

  while (List != &HostBridgeInstance->Head) {
    RootBridgeInstance = DRIVER_INSTANCE_FROM_LIST_ENTRY (List);

    if (RootBridgeHandle == RootBridgeInstance->Handle) {
      RootBridgeFound = TRUE;
      break;
    }
    //
    // Get next if have
    //
    List = List->ForwardLink;
  }

  if (RootBridgeFound == FALSE) {
    return EFI_INVALID_PARAMETER;
  }

  return EFI_SUCCESS;
}

UINT64
Power2MaxMemory (
  IN UINT64                     MemoryLength
  )
/*++

Routine Description:

  Calculate maximum memory length that can be fit to a mtrr.

Arguments:

  MemoryLength  -  Input memory length.

Returns:

  Returned Maximum length.

--*/
{
  UINT64  Result;

  if (RShiftU64 (MemoryLength, 32)) {
    Result = LShiftU64 ((UINT64) GetPowerOfTwo64 ((UINT32) RShiftU64 (MemoryLength, 32)), 32);
  } else {
    Result = (UINT64) GetPowerOfTwo64 ((UINT32) MemoryLength);
  }

  return Result;
}


text:
[![Version     ](https://img.shields.io/gem/v/cloaca.svg?style=flat)](https://rubygems.org/gems/cloaca)
[![Build Status](https://img.shields.io/travis/mchadwick/cloaca/master.svg?style=flat)](https://travis-ci.org/mchadwick/cloaca)
[![Code Climate](https://img.shields.io/codeclimate/github/mchadwick/cloaca.svg?style=flat)](https://codeclimate.com/github/mchadwick/cloaca)

# Cloaca

This project is archived and is no actively maintained.

Cloaca provides a library of transformations for CSV files and other row structured data.

It does this by providing command-line operations for manipulating a data stream. Operations can be concatenated to perform more complex file transformations.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'cloaca'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install cloaca

## Usage

```bash
exe/cloaca

Cloaca commands:
  cloaca add-fixed-value-column --col-value=column cell value                    # adds a fixed value column to a stream of data
  cloaca add-integer-index-column                                                # adds a index column to a stream of data
  cloaca add-numeric-index-column                                                # adds a index column to a stream of data
  cloaca change-col-delimiter --new-col-delim=column delimiter                   # change the column delimiter for a stream of data
  cloaca check-headers-unique                                                    # checks that each column has a unique header value
  cloaca extract-unique-col-values --index-or-value=column index or header       # extract unique vlaues for a column, one per line
  cloaca generate-int N                                                          # generates N random integers, one per line
  cloaca help [COMMAND]                                                          # Describe available commands or one specific command
  cloaca remove-col-quotes --index-or-value=column index or header               # removes quotes from a column's values
  cloaca remove-column (index or value) --index-or-value=column index or header  # removes the column
  cloaca remove-header-row                                                       # removes the first N rows (default N = 1)
```

## What's in a Name?

cloaca [kloh-ey-kuh]

Definitions:
1. maw of voracious person
2. privy (medieval)
3. sewer, underground drain

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/mchadwick/cloaca. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
<?php
/**
 * Created by PhpStorm.
 * User: Arun Tamang
 * Date: 8/21/2016
 * Time: 7:10 PM
 */

require('../common/Common.php');
session_start();
$objCommon = new Common();

if(isset($_POST['mode'])){

    if($_POST['mode'] == 'farmerQuestion'){
        $fullName = $_POST['fullName'];
        $phoneNumber = $_POST['phoneNumber'];
        $email = $_POST['email'];
        $address = $_POST['address'];
        $query = $_POST['query'];

        $result = array();
        $result = $objCommon->createQuery($fullName,$phoneNumber,$email,$address,$query);

        if($result['message']=='success'){
            $_SESSION['farmerQuery']  = $result['message'];

            echo '<script>
                alert("तपाइको प्रश्न पेश गरिएको छ");
            </script>';
        }

        header("Location:../views/home.php");
    }

    if($_POST['mode']=='delete'){

        $id = $_POST['id'];

        $result = array();

        $result = $objCommon->deleteQuery($id);

        echo json_encode($result);

    }

    if($_POST['mode']=='reply'){

        $id = $_POST['query_id'];
        $reply= $_POST['reply'];

        $replyFrom = $_SESSION['email'];
        $result = array();

        $result = $objCommon->replyQuery($id,$reply,$replyFrom);

        if($result['message']=='success'){
            header('Location:../views/dashboard.php');
        }
    }

    if($_POST['mode']=='show'){

        $id = $_POST['id'];

        $result = array();

        $result = $objCommon->getReplyList($id);

        echo json_encode($result);
    }
}


text: The user level programming language that targets the VireoSDK.


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.4"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>OR-Tools: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="styleSheet.tmp.css" rel="stylesheet" type="text/css"/>

OR-Tools
    9.4

DiagonalTrustRegionProblem Member List

This is the complete list of members for DiagonalTrustRegionProblem, including all inherited members.

CenterPoint(int64_t index) const	DiagonalTrustRegionProblem	inline

DiagonalTrustRegionProblem(const VectorXd *objective_vector, const VectorXd *objective_matrix_diagonal, const VectorXd *lower_bounds, const VectorXd *upper_bounds, const VectorXd *center_point, const VectorXd *norm_weights)	DiagonalTrustRegionProblem	inline

LowerBound(int64_t index) const	DiagonalTrustRegionProblem	inline

NormWeight(int64_t index) const	DiagonalTrustRegionProblem	inline

Objective(int64_t index) const	DiagonalTrustRegionProblem	inline

ObjectiveMatrixDiagonalAt(int64_t index) const	DiagonalTrustRegionProblem	inline

UpperBound(int64_t index) const	DiagonalTrustRegionProblem	inline

Generated by

     1.9.4


text:
from django.contrib import admin
from django.utils.translation import ugettext_noop as _

from transurlvania.defaults import *

admin.autodiscover()

urlpatterns = lang_prefixed_patterns('garfield.views',
    url(r'^$', 'home'),
    url(r'^admin/', include(admin.site.urls)),
    (r'^garfield/', include('garfield.urls')),
    url(_(r'^about-us/$'), 'about_us', name='about_us'),
)

urlpatterns += patterns('transurlvania.views',
    (r'^$', 'detect_language_and_redirect'),
    )


text:
exports.ChallengeRunner = require('./challenge-runner').ChallengeRunner;
exports.start = require('./routes').start;
exports.User = require('./user').User;
exports.Challenge = require('./challenge').Challenge;
exports.data = {
	challenges: require('./data/challenges').challenges,
	user: require('./data/user').user,
	public: require('./data/public').public
};


text:
@implementation RMPath

@synthesize scaleLineWidth;
@synthesize projectedLocation;
@synthesize enableDragging;
@synthesize enableRotation;

#define kDefaultLineWidth 100

/// \bug default values for lineWidth, lineColor, fillColor are hardcoded
- (id) initWithContents: (RMMapContents*)aContents
{
	if (![super init])
		return nil;

	contents = aContents;

	path = CGPathCreateMutable();

	lineWidth = kDefaultLineWidth;
	drawingMode = kCGPathFillStroke;
	lineCap = kCGLineCapButt;
	lineJoin = kCGLineJoinMiter;
	lineColor = [UIColor blackColor];
	fillColor = [UIColor redColor];

	//self.masksToBounds = NO;
	self.masksToBounds = YES;

	scaleLineWidth = NO;
	enableDragging = YES;
	enableRotation = YES;
	isFirstPoint = YES;

	return self;
}

- (id) initForMap: (RMMapView*)map
{
	return [self initWithContents:[map contents]];
}

-(void) dealloc
{
	CGPathRelease(path);
    [self setLineColor:nil];
    [self setFillColor:nil];

	[super dealloc];
}

- (id<CAAction>)actionForKey:(NSString *)key
{
	return nil;
}

- (void) recalculateGeometry
{
	RMMercatorToScreenProjection *projection = [contents mercatorToScreenProjection];
	float scale = [projection metersPerPixel];
	float scaledLineWidth;
	CGPoint myPosition;
	CGRect pixelBounds, screenBounds;
	float offset;
	const float outset = 100.0f; // provides a buffer off screen edges for when path is scaled or moved

	// The bounds are actually in mercators...
	/// \bug if "bounds are actually in mercators", shouldn't be using a CGRect
	scaledLineWidth = lineWidth;
	if(!scaleLineWidth) {
		renderedScale = [contents metersPerPixel];
		scaledLineWidth *= renderedScale;
	}

	CGRect boundsInMercators = CGPathGetBoundingBox(path);
	boundsInMercators = CGRectInset(boundsInMercators, -scaledLineWidth, -scaledLineWidth);
	pixelBounds = CGRectInset(boundsInMercators, -scaledLineWidth, -scaledLineWidth);

	pixelBounds = RMScaleCGRectAboutPoint(pixelBounds, 1.0f / scale, CGPointZero);

	// Clip bound rect to screen bounds.
	// If bounds are not clipped, they won't display when you zoom in too much.
	myPosition = [projection projectXYPoint: projectedLocation];
	screenBounds = [contents screenBounds];

	// Clip top
	offset = myPosition.y + pixelBounds.origin.y - screenBounds.origin.y + outset;
	if(offset < 0.0f) {
		pixelBounds.origin.y -= offset;
		pixelBounds.size.height += offset;
	}
	// Clip left
	offset = myPosition.x + pixelBounds.origin.x - screenBounds.origin.x + outset;
	if(offset < 0.0f) {
		pixelBounds.origin.x -= offset;
		pixelBounds.size.width += offset;
	}
	// Clip bottom
	offset = myPosition.y + pixelBounds.origin.y + pixelBounds.size.height - screenBounds.origin.y - screenBounds.size.height - outset;
	if(offset > 0.0f) {
		pixelBounds.size.height -= offset;
	}
	// Clip right
	offset = myPosition.x + pixelBounds.origin.x + pixelBounds.size.width - screenBounds.origin.x - screenBounds.size.width - outset;
	if(offset > 0.0f) {
		pixelBounds.size.width -= offset;
	}

	[super setPosition:myPosition];
	self.bounds = pixelBounds;
	//RMLog(@"x:%f y:%f screen bounds: %f %f %f %f", myPosition.x, myPosition.y,  screenBounds.origin.x, screenBounds.origin.y, screenBounds.size.width, screenBounds.size.height);
	//RMLog(@"new bounds: %f %f %f %f", self.bounds.origin.x, self.bounds.origin.y, self.bounds.size.width, self.bounds.size.height);

	self.anchorPoint = CGPointMake(-pixelBounds.origin.x / pixelBounds.size.width,-pixelBounds.origin.y / pixelBounds.size.height);
	[self setNeedsDisplay];
}

- (void) addPointToXY: (RMProjectedPoint) point withDrawing: (BOOL)isDrawing
{
	//	RMLog(@"addLineToXY %f %f", point.x, point.y);

	if(isFirstPoint)
	{
		isFirstPoint = FALSE;
		projectedLocation = point;

		self.position = [[contents mercatorToScreenProjection] projectXYPoint: projectedLocation];
		//		RMLog(@"screen position set to %f %f", self.position.x, self.position.y);
		CGPathMoveToPoint(path, NULL, 0.0f, 0.0f);
	}
	else
	{
		point.easting = point.easting - projectedLocation.easting;
		point.northing = point.northing - projectedLocation.northing;

		if (isDrawing)
		{
			CGPathAddLineToPoint(path, NULL, point.easting, -point.northing);
		} else {
			CGPathMoveToPoint(path, NULL, point.easting, -point.northing);
		}

		[self recalculateGeometry];
	}
	[self setNeedsDisplay];
}

- (void) moveToXY: (RMProjectedPoint) point
{
	[self addPointToXY: point withDrawing: FALSE];
}

- (void) moveToScreenPoint: (CGPoint) point
{
	RMProjectedPoint mercator = [[contents mercatorToScreenProjection] projectScreenPointToXY: point];

	[self moveToXY: mercator];
}

- (void) moveToLatLong: (RMLatLong) point
{
	RMProjectedPoint mercator = [[contents projection] latLongToPoint:point];

	[self moveToXY:mercator];
}

- (void) addLineToXY: (RMProjectedPoint) point
{
	[self addPointToXY: point withDrawing: TRUE];
}

- (void) addLineToScreenPoint: (CGPoint) point
{
	RMProjectedPoint mercator = [[contents mercatorToScreenProjection] projectScreenPointToXY: point];

	[self addLineToXY: mercator];
}

- (void) addLineToLatLong: (RMLatLong) point
{
	RMProjectedPoint mercator = [[contents projection] latLongToPoint:point];

	[self addLineToXY:mercator];
}

- (void)drawInContext:(CGContextRef)theContext
{
	renderedScale = [contents metersPerPixel];

	float scale = 1.0f / [contents metersPerPixel];

	float scaledLineWidth = lineWidth;
	if(!scaleLineWidth) {
		scaledLineWidth *= renderedScale;
	}
	//NSLog(@"line width = %f, content scale = %f", scaledLineWidth, renderedScale);

	CGContextScaleCTM(theContext, scale, scale);

	CGContextBeginPath(theContext);
	CGContextAddPath(theContext, path);

	CGContextSetLineWidth(theContext, scaledLineWidth);
	CGContextSetLineCap(theContext, lineCap);
	CGContextSetLineJoin(theContext, lineJoin);
	CGContextSetStrokeColorWithColor(theContext, [lineColor CGColor]);
	CGContextSetFillColorWithColor(theContext, [fillColor CGColor]);

	// according to Apple's documentation, DrawPath closes the path if it's a filled style, so a call to ClosePath isn't necessary
	CGContextDrawPath(theContext, drawingMode);
}

- (void) closePath
{
	CGPathCloseSubpath(path);
}

- (float) lineWidth
{
	return lineWidth;
}

- (void) setLineWidth: (float) newLineWidth
{
	lineWidth = newLineWidth;
	[self recalculateGeometry];
}

- (CGPathDrawingMode) drawingMode
{
	return drawingMode;
}

- (void) setDrawingMode: (CGPathDrawingMode) newDrawingMode
{
	drawingMode = newDrawingMode;
	[self setNeedsDisplay];
}

- (CGLineCap) lineCap
{
	return lineCap;
}

- (void) setLineCap: (CGLineCap) newLineCap
{
	lineCap = newLineCap;
	[self setNeedsDisplay];
}

- (CGLineJoin) lineJoin
{
	return lineJoin;
}

- (void) setLineJoin: (CGLineJoin) newLineJoin
{
	lineJoin = newLineJoin;
	[self setNeedsDisplay];
}

- (UIColor *)lineColor
{
    return lineColor;
}
- (void)setLineColor:(UIColor *)aLineColor
{
    if (lineColor != aLineColor) {
        [lineColor release];
        lineColor = [aLineColor retain];
		[self setNeedsDisplay];
    }
}

- (UIColor *)fillColor
{
    return fillColor;
}
- (void)setFillColor:(UIColor *)aFillColor
{
    if (fillColor != aFillColor) {
        [fillColor release];
        fillColor = [aFillColor retain];
		[self setNeedsDisplay];
    }
}

- (void)moveBy: (CGSize) delta {
	if(enableDragging){
		[super moveBy:delta];
	}
}

- (void)setPosition:(CGPoint)value
{
	[self recalculateGeometry];
}

@end


text:
using System.Collections.Generic;
using System.Fabric;
using System.Threading.Tasks;

namespace Admin.Models
{
    public interface ISubscriberFabricProvider
    {
        Task<IEnumerable<SubscriberInfo>> GetSubscribers(string topic, string applicationName);
    }

    public class SubscriberInfo
    {
        public string ServiceName { get; set; }
        public string ServiceStatus { get; set; }
    }
}


text:
require 'spec_helper'

describe Graphlient::Query do
  describe '#initialize' do
    context 'query' do
      it 'returns expected query with block' do
        query = Graphlient::Query.new do
          query do
            invoice do
              line_items
            end
          end
        end
        expect(query.to_s).to eq "query{\n  invoice{\n    line_items\n    }\n  }"
      end

      it 'returns expected query with block and attributes' do
        query = Graphlient::Query.new do
          query do
            invoice(id: 10) do
              line_items
            end
          end
        end
        expect(query.to_s).to eq "query{\n  invoice(id: 10){\n    line_items\n    }\n  }"
      end

      it 'returns expected query with block and attributes' do
        query = Graphlient::Query.new do
          query do
            invoice(id: 10) do
              line_items(name: 'test')
            end
          end
        end
        expect(query.to_s).to eq "query{\n  invoice(id: 10){\n    line_items(name: \"test\")\n    }\n  }"
      end

      it 'returns expected query with block and local variables with proper type' do
        int_arg = 10
        float_arg = 10.3
        str_arg = 'new name'
        array_arg = ['str_item', 2]
        query = Graphlient::Query.new do
          query do
            invoice(id: int_arg, threshold: float_arg, item_list: array_arg) do
              line_items(name: str_arg)
            end
          end
        end
        expect(query.to_s).to eq "query{\n  invoice(id: 10, threshold: 10.3, item_list: [\"str_item\", 2]){\n    line_items(name: \"new name\")\n    }\n  }"
      end

      it 'returns proper query' do
        query = Graphlient::Query.new do
          query do
            invoice(id: 10) do
              line_items do
                line_item_type
              end
            end
          end
        end
        expect(query.to_s).to eq "query{\n  invoice(id: 10){\n    line_items{\n      line_item_type\n      }\n    }\n  }"
      end

      it 'returns proper query with query variables' do
        query = Graphlient::Query.new do
          query(invoice_id: :int, names: [:string!]) do
            invoice(id: :invoice_id, name: :names) do
              line_items do
                line_item_type
              end
            end
          end
        end
        expect(query.to_s).to eq "query($invoice_id: Int, $names: [String!]){\n  invoice(id: $invoice_id, name: $names){\n    line_items{\n      line_item_type\n      }\n    }\n  }"
      end
    end

    context 'mutation' do
      it 'returns proper mutation with arguments' do
        mutation = Graphlient::Query.new do
          mutation do
            invoice(type: 'test', fee_in_cents: 20_000, total_cents: 50_000, line_items: %w[li1 li2]) do
              id
            end
          end
        end
        expect(mutation.to_s).to eq "mutation{\n  invoice(type: \"test\", fee_in_cents: 20000, total_cents: 50000, line_items: [\"li1\", \"li2\"]){\n    id\n    }\n  }"
      end
    end

    it 'returns proper mutation for relay style mutation' do
      mutation = Graphlient::Query.new do
        mutation do
          invoice(input: { type: 'test', fee_in_cents: 20_000, total_cents: 50_000, line_items: %w[li1 li2] }) do
            id
          end
        end
      end
      expect(mutation.to_s).to eq "mutation{\n  invoice(input: { type: \"test\", fee_in_cents: 20000, total_cents: 50000, line_items: [\"li1\", \"li2\"] }){\n    id\n    }\n  }"
    end
  end
end


text:
package com.showka.web;

import java.io.Serializable;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class MeisaiFormBase implements Serializable {

	/**
	 * SID.
	 */
	private static final long serialVersionUID = -5376895824409763664L;

	/** ステータス. */
	@Getter(AccessLevel.NONE)
	private String _status;

	@AllArgsConstructor
	private enum MeisaiStatus {
		added("added"), notUpdated("notUpdated"), newRegistered("newRegistered"), updated("updated"), deleted(
				"deleted");
		@Getter(value = AccessLevel.PROTECTED)
		private String code;
	}

	public boolean isDeleted() {
		return MeisaiStatus.deleted.getCode().equals(_status);
	}

	/**
	 * 文字列化
	 */
	@Override
	public String toString() {
		return ReflectionToStringBuilder.toString(this);
	}

}


text:
import { writeFileSync, emptyDirSync } from 'fs-extra';
import { build, BuildOptions } from 'esbuild';
import yargs from 'yargs/yargs';
import { hideBin } from 'yargs/helpers';

const argv = yargs(hideBin(process.argv))
  .options({
    devMode: { type: 'boolean', default: false }
  })
  .parseSync();

const outDir = 'dist';

async function buildAll(devMode = false) {
  console.log(`DEV mode: ${devMode}`);

  emptyDirSync(outDir);

  const buildConf: BuildOptions = {
    logLevel: 'info',
    entryPoints: ['src/index.tsx'],
    entryNames: devMode ? '[name]' : '[name]-[hash]',
    bundle: true,
    outdir: outDir,
    metafile: !devMode,
    watch: devMode
  };

  if (devMode) {
    build(buildConf);
  } else {
    const result = await build(buildConf);
    writeFileSync('dist/meta.json', JSON.stringify(result.metafile));
  }
}

buildAll(argv.devMode);


text:
This is an elm version of the Gilded Rose Kata, found
[here](http://iamnotmyself.com/2011/02/13/refactor-this-the-gilded-rose-kata/).

This is a refactoring kata, so you will be starting with a legacy code base.
Clone this repository, read the description below for the rules and start hacking right away!

## Installation and running tests

Assuming you already installed [node.js](https://nodejs.org/en/download/package-manager/) and [npm](http://blog.npmjs.org/post/85484771375/how-to-install-npm) you have to install `elm` and `elm-test`:

```
# install prerequisites. depending on your setup, you may want to use `sudo`.
npm install -g elm elm-test

# run the tests
elm-test
```

If the tests pass, you are all set up to work the kata. After making familiar with the
[original description](#original-description-of-the-gilded-rose) you may start hacking at `src/GildedRose.elm`!

## Afterwards

Whenever you have a solution, please do not hesitate to make a PR. It will not be merged but may be an inspiration for the fellow elmish.
You also might want to have a look at my solution by checking out `solution1`.

## Changes from the original

This elm version follows the original code closely, but has the following changes:

* The original had no tests.  Since this is a refactoring kata, I feel
  the tests are important and provide a fairly complete test suite.
  Just delete the tests if you wish to "go it alone".

* The original used a hard coded set of "items", presumably for
  testing the code.  Since I added a test suite, the hard coded values
  were not of much use.  I also changed the interface to accept a list of
  items as a parameter rather than a hard coded constant.

# Original Description of the Gilded Rose

Hi and welcome to team Gilded Rose. As you know, we are a small inn
with a prime location in a prominent city run by a friendly innkeeper
named Allison. We also buy and sell only the finest
goods. Unfortunately, our goods are constantly degrading in quality as
they approach their sell by date. We have a system in place that
updates our inventory for us. It was developed by a no-nonsense type
named Leeroy, who has moved on to new adventures. Your task is to add
the new feature to our system so that we can begin selling a new
category of items. First an introduction to our system:

- All items have a SellIn value which denotes the number of days we
  have to sell the item
- All items have a Quality value which denotes how valuable the item
  is
- At the end of each day our system lowers both values for every item

Pretty simple, right? Well this is where it gets interesting:

  - Once the sell by date has passed, Quality degrades twice as fast
  - The Quality of an item is never negative
  - "Aged Brie" actually increases in Quality the older it gets
  - The Quality of an item is never more than 50
  - "Sulfuras", being a legendary item, never has to be sold or
    decreases in Quality
  - "Backstage passes", like aged brie, increases in Quality as it's
    SellIn value approaches; Quality increases by 2 when there are 10
    days or less and by 3 when there are 5 days or less but Quality
    drops to 0 after the concert

We have recently signed a supplier of conjured items. This requires an update to our system:

- "Conjured" items degrade in Quality twice as fast as normal items

Feel free to make any changes to the UpdateQuality method and add any
new code as long as everything still works correctly. However, do not
alter the Item class or Items property as those belong to the goblin
in the corner who will insta-rage and one-shot you as he doesn't
believe in shared code ownership (you can make the UpdateQuality
method and Items property static if you like, we'll cover for
you). Your work needs to be completed by Friday, February 18, 2011
08:00:00 AM PST.

Just for clarification, an item can never have its Quality increase
above 50, however "Sulfuras" is a legendary item and as such its
Quality is 80 and it never alters.

# Props

This README has mostly been copied from [Jim Weinrich's Ruby version](https://github.com/jimweirich/gilded_rose_kata).


text:
using SharpGL.SceneGraph;
using System;
using System.IO;

namespace SharpGL.Serialization.Caligari
{
    internal class CaligariString
    {
        public virtual void Read(BinaryReader stream)
        {
            short length = stream.ReadInt16();
            name = new string(stream.ReadChars(length));
        }

        public string name;
    }

    internal class CaligariName
    {
        public virtual void Read(BinaryReader stream)
        {
            dupecount = stream.ReadInt16();
            CaligariString str = new CaligariString();
            str.Read(stream);
            name = str.name;
        }

        public short dupecount;
        public string name;
    }

    internal class CaligariAxies
    {
        public virtual void Read(BinaryReader stream)
        {
            centre = new Vertex(stream.ReadSingle(), stream.ReadSingle(), stream.ReadSingle());
            directionX = new Vertex(stream.ReadSingle(), stream.ReadSingle(), stream.ReadSingle());
            directionY = new Vertex(stream.ReadSingle(), stream.ReadSingle(), stream.ReadSingle());
            directionZ = new Vertex(stream.ReadSingle(), stream.ReadSingle(), stream.ReadSingle());

            //	The X axis in SharpGL is always (1, 0, 0).

            xAxis = new Vertex(1, 0, 0);
            float angleX = xAxis.ScalarProduct(directionX);
            yAxis = new Vertex(0, 1, 0);
            float angleY = yAxis.ScalarProduct(directionY);
            zAxis = new Vertex(0, 0, 1);
            float angleZ = zAxis.ScalarProduct(directionZ);
            angleX = (float)System.Math.Asin(angleX);
            angleY = (float)System.Math.Asin(angleY);
            angleZ = (float)System.Math.Asin(angleZ);

            angleX = (180 * angleX) / (float)Math.PI;
            angleY = (180 * angleY) / (float)Math.PI;
            angleZ = (180 * angleZ) / (float)Math.PI;

            rotate = new Vertex(-angleX, -angleY, -angleZ);

            xAxis = xAxisGL = directionX;
            yAxis = zAxisGL = directionY;
            zAxis = yAxisGL = directionZ;
            xAxisGL.X = -xAxisGL.X;
        }

        public Vertex centre;
        public Vertex rotate;

        public Vertex directionX;
        public Vertex directionY;
        public Vertex directionZ;

        public Vertex xAxis;
        public Vertex yAxis;
        public Vertex zAxis;
        public Vertex xAxisGL;
        public Vertex yAxisGL;
        public Vertex zAxisGL;
    }

    internal class CaligariPosition
    {
        public virtual void Read(BinaryReader stream)
        {
            row1 = new float[] { stream.ReadSingle(), stream.ReadSingle(), stream.ReadSingle(), stream.ReadSingle() };
            row2 = new float[] { stream.ReadSingle(), stream.ReadSingle(), stream.ReadSingle(), stream.ReadSingle() };
            row3 = new float[] { stream.ReadSingle(), stream.ReadSingle(), stream.ReadSingle(), stream.ReadSingle() };

            //	Convert it to our own matrix.
            matrix[0, 0] = row1[0]; matrix[0, 1] = row1[1]; matrix[0, 2] = row1[2];
            matrix[1, 0] = row2[0]; matrix[1, 1] = row2[1]; matrix[1, 2] = row2[2];
            matrix[2, 0] = row3[0]; matrix[2, 1] = row3[1]; matrix[2, 2] = row3[2];

            matrix.Transpose();
        }

        public float[] row1;
        public float[] row2;
        public float[] row3;

        public Matrix matrix = new Matrix(3, 3);
    }
}


text:
<!doctype html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/helpers.js"></script>

<script>
promise_test(async t => {
  // Wait for after the load event so that the navigation doesn't get converted
  // into a replace navigation.
  await new Promise(resolve => window.onload = () => t.step_timeout(resolve, 0));

  location.href = "#1";

  assert_equals(navigation.entries().length, 2);
  const [entry0, entry1] = navigation.entries();
  assert_equals((new URL(entry0.url)).hash, "");
  assert_equals((new URL(entry1.url)).hash, "#1");

  await navigation.back().committed;

  const promise = Promise.resolve({ abc: "def" });
  navigation.onnavigate = e => e.intercept({ handler: () => promise });

  const result = navigation.forward();
  await assertBothFulfill(t, result, entry1);
  assert_equals(navigation.currentEntry, entry1);
}, "forward() and intercept() with a fulfilled promise");
</script>


text:
package com.canchitodev.awm.utils;

import org.springframework.stereotype.Component;

@Component
public class StrongUuidGenerator extends org.activiti.engine.impl.persistence.StrongUuidGenerator {

	public StrongUuidGenerator() {
		super();
	}

	public String getNextId() {
		return super.getNextId();
	}
}