text:
import os
import pathlib
import tempfile
from unittest import mock

import pytest

from cumulusci.core.exceptions import TaskOptionsError, CumulusCIException
from cumulusci.tasks.metadata_etl import MetadataOperation
from cumulusci.tasks.salesforce.update_profile import ProfileGrantAllAccess
from cumulusci.utils import CUMULUSCI_PATH
from cumulusci.utils.xml import metadata_tree
from cumulusci.tests.util import DummyOrgConfig, create_project_config

from .util import create_task

ADMIN_PROFILE_BEFORE = b"""<?xml version='1.0' encoding='utf-8'?>
<Profile xmlns="http://soap.sforce.com/2006/04/metadata">
    <applicationVisibilities>
        <application>npsp__Nonprofit_CRM</application>
        <default>true</default>
        <visible>false</visible>
    </applicationVisibilities>
    <classAccesses>
        <apexClass>TestClass</apexClass>
        <enabled>false</enabled>
    </classAccesses>
    <fieldPermissions>
        <field>Account.TestField__c</field>
        <editable>false</editable>
        <readable>false</readable>
    </fieldPermissions>
    <pageAccesses>
        <apexPage>TestPage</apexPage>
        <enabled>false</enabled>
    </pageAccesses>
    <recordTypeVisibilities>
        <recordType>Account.Business_Account</recordType>
        <default>true</default>
        <personAccountDefault>true</personAccountDefault>
        <visible>true</visible>
    </recordTypeVisibilities>
    <recordTypeVisibilities>
        <recordType>Account.HH_Account</recordType>
        <default>false</default>
        <personAccountDefault>false</personAccountDefault>
        <visible>false</visible>
    </recordTypeVisibilities>
    <tabVisibilities>
        <tab>NPSP_Settings</tab>
        <visibility>Hidden</visibility>
    </tabVisibilities>
</Profile>"""

ADMIN_PROFILE_EXPECTED = """<?xml version="1.0" encoding="UTF-8"?>
<Profile xmlns="http://soap.sforce.com/2006/04/metadata">
    <applicationVisibilities>
        <application>npsp__Nonprofit_CRM</application>
        <default>true</default>
        <visible>true</visible>
    </applicationVisibilities>
    <classAccesses>
        <apexClass>TestClass</apexClass>
        <enabled>true</enabled>
    </classAccesses>
    <fieldPermissions>
        <field>Account.TestField__c</field>
        <editable>true</editable>
        <readable>true</readable>
    </fieldPermissions>
    <pageAccesses>
        <apexPage>TestPage</apexPage>
        <enabled>true</enabled>
    </pageAccesses>
    <recordTypeVisibilities>
        <recordType>Account.Business_Account</recordType>
        <default>false</default>
        <personAccountDefault>false</personAccountDefault>
        <visible>true</visible>
    </recordTypeVisibilities>
    <recordTypeVisibilities>
        <recordType>Account.HH_Account</recordType>
        <default>true</default>
        <personAccountDefault>true</personAccountDefault>
        <visible>true</visible>
    </recordTypeVisibilities>
    <tabVisibilities>
        <tab>NPSP_Settings</tab>
        <visibility>DefaultOn</visibility>
    </tabVisibilities>
</Profile>
"""

PACKAGE_XML_BEFORE = """<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>*</members>
        <members>Account</members>
        <members>Campaign</members>
        <members>CampaignMember</members>
        <members>Contact</members>
        <members>Lead</members>
        <members>Opportunity</members>
        <name>CustomObject</name>
    </types>
    <types>
        <name>Profile</name>
    </types>
    <version>39.0</version>
</Package>"""

PACKAGE_XML_BEFORE__PROFILES = """<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>*</members>
        <members>Account</members>
        <name>CustomObject</name>
    </types>
    <types>
        <name>Profile</name>
        <members>Admin</members>
        <members>Test</members>
    </types>
    <version>39.0</version>
</Package>"""

PACKAGE_XML_BEFORE__NO_PROFILES = """<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>*</members>
        <members>Account</members>
        <name>CustomObject</name>
    </types>
    <version>39.0</version>
</Package>"""

ADMIN_PROFILE_BEFORE__MULTI_OBJECT_RT = b"""<?xml version='1.0' encoding='utf-8'?>
<Profile xmlns="http://soap.sforce.com/2006/04/metadata">
    <recordTypeVisibilities>
        <recordType>Account.Business_Account</recordType>
        <default>false</default>
        <personAccountDefault>true</personAccountDefault>
        <visible>true</visible>
    </recordTypeVisibilities>
    <recordTypeVisibilities>
        <recordType>Opportunity.Donation</recordType>
        <default>true</default>
        <personAccountDefault>false</personAccountDefault>
        <visible>false</visible>
    </recordTypeVisibilities>
</Profile>"""

ADMIN_PROFILE_EXPECTED__MULTI_OBJECT_RT = """<?xml version="1.0" encoding="UTF-8"?>
<Profile xmlns="http://soap.sforce.com/2006/04/metadata">
    <recordTypeVisibilities>
        <recordType>Account.Business_Account</recordType>
        <default>true</default>
        <personAccountDefault>true</personAccountDefault>
        <visible>true</visible>
    </recordTypeVisibilities>
    <recordTypeVisibilities>
        <recordType>Opportunity.Donation</recordType>
        <default>true</default>
        <personAccountDefault>false</personAccountDefault>
        <visible>false</visible>
    </recordTypeVisibilities>
</Profile>
"""

def test_run_task():
    with tempfile.TemporaryDirectory() as tempdir:
        with open(
            os.path.join(CUMULUSCI_PATH, "cumulusci", "files", "admin_profile.xml"), "w"
        ) as f:
            f.write(PACKAGE_XML_BEFORE)

        retrieve_dir = pathlib.Path(tempdir, "retrieve")
        retrieve_dir.mkdir()
        target_dir = retrieve_dir / "profiles"
        target_dir.mkdir()

        with open(target_dir / "Admin.profile", "wb") as f:
            f.write(ADMIN_PROFILE_BEFORE)

        task = create_task(
            ProfileGrantAllAccess,
            {
                "record_types": [
                    {
                        "record_type": "Account.HH_Account",
                        "default": True,
                        "person_account_default": True,
                    }
                ],
                "include_packaged_objects": False,
            },
        )

        task._retrieve = mock.Mock()
        task._deploy = mock.Mock()
        task._create_directories = mock.Mock()
        task.retrieve_dir = retrieve_dir
        task.deploy_dir = pathlib.Path(tempdir, "deploy")
        task.deploy_dir.mkdir()

        task()

        dest_path = task.deploy_dir / "profiles" / "Admin.profile"
        assert dest_path.exists()

        assert dest_path.read_text() == ADMIN_PROFILE_EXPECTED

def test_transforms_profile():
    task = create_task(
        ProfileGrantAllAccess,
        {
            "record_types": [
                {
                    "record_type": "Account.HH_Account",
                    "default": True,
                    "person_account_default": True,
                }
            ],
        },
    )

    inbound = metadata_tree.fromstring(ADMIN_PROFILE_BEFORE)
    outbound = task._transform_entity(inbound, "Admin")

    xml_output = outbound.tostring(xml_declaration=True)

    assert xml_output == ADMIN_PROFILE_EXPECTED

def test_transforms_profile__multi_object_rt():
    task = create_task(
        ProfileGrantAllAccess,
        {
            "record_types": [
                {
                    "record_type": "Account.Business_Account",
                    "default": True,
                    "person_account_default": True,
                }
            ],
        },
    )

    inbound = metadata_tree.fromstring(ADMIN_PROFILE_BEFORE__MULTI_OBJECT_RT)
    outbound = task._transform_entity(inbound, "Admin")

    xml_output = outbound.tostring(xml_declaration=True)

    assert xml_output == ADMIN_PROFILE_EXPECTED__MULTI_OBJECT_RT

def test_throws_exception_record_type_not_found():
    task = create_task(
        ProfileGrantAllAccess,
        {
            "record_types": [{"record_type": "DOESNT_EXIST"}],
        },
    )

    with pytest.raises(TaskOptionsError):
        task._transform_entity(metadata_tree.fromstring(ADMIN_PROFILE_BEFORE), "Admin")

def test_expand_package_xml():
    task = create_task(ProfileGrantAllAccess, {"api_names": ["Admin"]})
    task.tooling = mock.Mock()
    task.tooling.query_all.return_value = {
        "totalSize": 2,
        "records": [
            {"DeveloperName": "Test", "NamespacePrefix": "ns"},
            {"DeveloperName": "Foo_Bar", "NamespacePrefix": "fb"},
        ],
    }

    package_xml = metadata_tree.fromstring(PACKAGE_XML_BEFORE)
    task._expand_package_xml(package_xml)
    types = package_xml.find("types", name="CustomObject")
    assert "ns__Test__c" in {elem.text for elem in types.findall("members")}
    assert "fb__Foo_Bar__c" in {elem.text for elem in types.findall("members")}

def test_expand_package_xml__broken_package():
    task = create_task(ProfileGrantAllAccess, {"api_names": ["Admin"]})
    task.tooling = mock.Mock()
    task.tooling.query_all.return_value = {
        "totalSize": 2,
        "records": [
            {"DeveloperName": "Test", "NamespacePrefix": "ns"},
            {"DeveloperName": "Foo_Bar", "NamespacePrefix": "fb"},
        ],
    }

    package_xml = metadata_tree.fromstring(PACKAGE_XML_BEFORE)
    types = package_xml.find("types", name="CustomObject")
    types.find("name").text = "NotCustomObject"
    with pytest.raises(CumulusCIException):
        task._expand_package_xml(package_xml)

def test_expand_profile_members():
    task = create_task(
        ProfileGrantAllAccess,
        {
            "api_names": ["Admin", "%%%NAMESPACE%%%Continuous Integration"],
            "namespace_inject": "ns",
            "managed": True,
        },
    )
    package_xml = metadata_tree.fromstring(PACKAGE_XML_BEFORE)

    task._expand_profile_members(package_xml)

    types = package_xml.find("types", name="Profile")
    assert {elem.text for elem in types.findall("members")} == {
        "Admin",
        "ns__Continuous Integration",
    }

def test_expand_profile_members__no_api_names():
    task = create_task(
        ProfileGrantAllAccess,
        {
            "namespace_inject": "ns",
            "managed": True,
        },
    )
    package_xml = metadata_tree.fromstring(PACKAGE_XML_BEFORE)

    task._expand_profile_members(package_xml)

    types = package_xml.find("types", name="Profile")
    assert {elem.text for elem in types.findall("members")} == {"Admin"}

def test_expand_profile_members__existing_entries():
    task = create_task(
        ProfileGrantAllAccess,
        {
            "api_names": ["Admin", "%%%NAMESPACE%%%Continuous Integration"],
            "namespace_inject": "ns",
            "managed": True,
        },
    )
    package_xml = metadata_tree.fromstring(PACKAGE_XML_BEFORE__PROFILES)

    task._expand_profile_members(package_xml)

    types = package_xml.find("types", name="Profile")

    assert {elem.text for elem in types.findall("members")} == {
        "Admin",
        "Test",
        "ns__Continuous Integration",
    }

    assert task.api_names == {"Admin", "ns__Continuous Integration", "Test"}

def test_expand_profile_members__no_profile_section():
    task = create_task(
        ProfileGrantAllAccess,
        {
            "api_names": ["Admin", "%%%NAMESPACE%%%Continuous Integration"],
            "namespace_inject": "ns",
            "managed": True,
        },
    )
    package_xml = metadata_tree.fromstring(PACKAGE_XML_BEFORE__NO_PROFILES)

    task._expand_profile_members(package_xml)

    types = package_xml.find("types", name="Profile")

    assert {elem.text for elem in types.findall("members")} == {
        "Admin",
        "ns__Continuous Integration",
    }

    assert task.api_names == {"Admin", "ns__Continuous Integration"}

def test_expand_profile_members__namespaced_org():
    project_config = create_project_config(namespace="ns")
    task = create_task(
        ProfileGrantAllAccess,
        {
            "api_names": ["Admin", "%%%NAMESPACED_ORG%%%Continuous Integration"],
            "namespace_inject": "ns",
            "namespaced_org": True,
            "managed": False,
        },
        project_config,
    )
    package_xml = metadata_tree.fromstring(PACKAGE_XML_BEFORE)

    task._expand_profile_members(package_xml)

    types = package_xml.find("types", name="Profile")
    assert {elem.text for elem in types.findall("members")} == {
        "Admin",
        "ns__Continuous Integration",
    }

def test_init_options__general():
    project_config = create_project_config(namespace="ns")
    task = create_task(
        ProfileGrantAllAccess, {"managed": "true"}, project_config=project_config
    )
    assert task.options["managed"]
    assert not task.options["namespaced_org"]
    assert task.options["namespace_inject"] == "ns"
    assert task.namespace_prefixes == {"managed": "ns__", "namespaced_org": ""}

    task = create_task(
        ProfileGrantAllAccess,
        {"namespaced_org": "true", "managed": False},
        project_config=project_config,
    )
    assert not task.options["managed"]
    assert task.options["namespaced_org"]
    assert task.options["namespace_inject"] == "ns"
    assert task.namespace_prefixes == {"managed": "", "namespaced_org": "ns__"}

    task = create_task(ProfileGrantAllAccess, {})
    assert not task.options["managed"]
    assert not task.options["namespaced_org"]
    assert task.options["namespace_inject"] is None
    assert task.namespace_prefixes == {"managed": "", "namespaced_org": ""}

def test_init_options__api_names():
    task = create_task(
        ProfileGrantAllAccess,
        {
            "api_names": ["Admin", "%%%NAMESPACE%%%Continuous Integration"],
            "namespace_inject": "ns",
            "managed": True,
        },
    )
    assert task.api_names == {"Admin", "ns__Continuous Integration"}

    task = create_task(
        ProfileGrantAllAccess,
        {
            "api_names": ["Admin", "%%%NAMESPACE%%%Continuous Integration"],
            "namespace_inject": "ns",
            "managed": False,
        },
    )
    assert task.api_names == {"Admin", "Continuous Integration"}

    task = create_task(
        ProfileGrantAllAccess, {"profile_name": "Continuous Integration"}
    )
    assert task.api_names == {"Continuous Integration"}

    task = create_task(ProfileGrantAllAccess, {})
    assert task.api_names == {"Admin"}

    task = create_task(ProfileGrantAllAccess, {"package_xml": "lib/admin_profile.xml"})
    assert task.api_names == set()

def test_init_options__include_packaged_objects():
    pc = create_project_config()
    pc.minimum_cumulusci_version = "4.0.0"
    task = create_task(
        ProfileGrantAllAccess,
        {"package_xml": "lib/admin_profile.xml"},
        project_config=pc,
    )
    assert task.package_xml_path == "lib/admin_profile.xml"
    assert not task.options["include_packaged_objects"]

    task = create_task(ProfileGrantAllAccess, {}, project_config=pc)
    assert task.options["include_packaged_objects"]
    assert task.package_xml_path == os.path.join(
        CUMULUSCI_PATH, "cumulusci", "files", "admin_profile.xml"
    )

    pc.minimum_cumulusci_version = "2.0.0"
    task = create_task(ProfileGrantAllAccess, {}, project_config=pc)
    assert not task.options["include_packaged_objects"]

    task = create_task(
        ProfileGrantAllAccess, {"include_packaged_objects": True}, project_config=pc
    )
    assert task.options["include_packaged_objects"]

def test_init_options__namespace_injection():
    pc = create_project_config(namespace="ns")
    org_config = DummyOrgConfig({"namespace": "ns"})
    org_config._installed_packages = {"ns": None}
    task = create_task(
        ProfileGrantAllAccess, {}, project_config=pc, org_config=org_config
    )
    assert task.options["namespace_inject"] == "ns"
    assert task.options["namespaced_org"]
    assert task.options["managed"]

def test_generate_package_xml__retrieve():
    with tempfile.TemporaryDirectory() as tmp_dir:
        admin_profile = os.path.join(tmp_dir, "admin_profile.xml")
        with open(admin_profile, "w") as f:
            f.write(PACKAGE_XML_BEFORE)
        with open(
            os.path.join(CUMULUSCI_PATH, "cumulusci", "files", "admin_profile.xml"), "w"
        ) as f:
            f.write(PACKAGE_XML_BEFORE)

        task = create_task(
            ProfileGrantAllAccess,
            {"package_xml": admin_profile, "include_packaged_objects": False},
        )

        task._expand_profile_members = mock.Mock()
        task._expand_package_xml = mock.Mock()
        task._generate_package_xml(MetadataOperation.RETRIEVE)
        task._expand_package_xml.assert_not_called()

        task = create_task(
            ProfileGrantAllAccess,
            {"package_xml": admin_profile, "include_packaged_objects": True},
        )

        task._expand_profile_members = mock.Mock()
        task._expand_package_xml = mock.Mock()
        task._generate_package_xml(MetadataOperation.RETRIEVE)
        task._expand_package_xml.assert_called_once()

        task = create_task(ProfileGrantAllAccess, {"include_packaged_objects": True})

        task._expand_profile_members = mock.Mock()
        task._expand_package_xml = mock.Mock()
        task._generate_package_xml(MetadataOperation.RETRIEVE)
        task._expand_package_xml.assert_called_once()

        task = create_task(ProfileGrantAllAccess, {"include_packaged_objects": False})

        task._expand_profile_members = mock.Mock()
        task._expand_package_xml = mock.Mock()
        task._generate_package_xml(MetadataOperation.RETRIEVE)
        task._expand_package_xml.assert_not_called()


text:
package nom.bdezonia.zorbage.type.complex.highprec;

import java.math.BigDecimal;
import java.math.BigInteger;

import nom.bdezonia.zorbage.algebra.*;
import nom.bdezonia.zorbage.sampling.IntegerIndex;
import nom.bdezonia.zorbage.storage.coder.BigDecimalCoder;
import nom.bdezonia.zorbage.misc.Hasher;
import nom.bdezonia.zorbage.type.real.highprec.HighPrecisionMember;
import nom.bdezonia.zorbage.type.universal.OctonionRepresentation;
import nom.bdezonia.zorbage.type.universal.PrimitiveConversion;
import nom.bdezonia.zorbage.type.universal.PrimitiveRepresentation;
import nom.bdezonia.zorbage.type.universal.TensorOctonionRepresentation;
import nom.bdezonia.zorbage.type.universal.TensorStringRepresentation;
import nom.bdezonia.zorbage.type.universal.UniversalRepresentation;

/**
 *
 * @author Barry DeZonia
 *
 */
public final class ComplexHighPrecisionMember
	implements
		BigDecimalCoder,
		Allocatable<ComplexHighPrecisionMember>, Duplicatable<ComplexHighPrecisionMember>,
		Settable<ComplexHighPrecisionMember>, Gettable<ComplexHighPrecisionMember>,
		NumberMember<ComplexHighPrecisionMember>, PrimitiveConversion,
		UniversalRepresentation, SetComplex<HighPrecisionMember>, GetComplex<HighPrecisionMember>,
		SetFromBigDecimal, SetFromBigInteger, SetFromDouble, SetFromLong,
		GetAsBigDecimalArray
{
	private BigDecimal r, i;

	public ComplexHighPrecisionMember() {
		primitiveInit();
	}

	public ComplexHighPrecisionMember(ComplexHighPrecisionMember value) {
		set(value);
	}

	public ComplexHighPrecisionMember(String value) {
		TensorStringRepresentation rep = new TensorStringRepresentation(value);
		OctonionRepresentation val = rep.firstValue();
		setR(val.r());
		setI(val.i());
	}

	public ComplexHighPrecisionMember(BigDecimal... vals) {
		setFromBigDecimal(vals);
	}

	public ComplexHighPrecisionMember(BigInteger... vals) {
		setFromBigInteger(vals);
	}

	public ComplexHighPrecisionMember(double... vals) {
		setFromDouble(vals);
	}

	public ComplexHighPrecisionMember(long... vals) {
		setFromLong(vals);
	}

	public BigDecimal r() { return r; }

	public BigDecimal i() { return i; }

	public void setR(BigDecimal val) { r = val; }

	public void setI(BigDecimal val) { i = val; }

	@Override
	public void get(ComplexHighPrecisionMember other) {
		other.r = r;
		other.i = i;
	}

	@Override
	public void set(ComplexHighPrecisionMember other) {
		r = other.r;
		i = other.i;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append('{');
		builder.append(r());
		builder.append(',');
		builder.append(i());
		builder.append('}');
		return builder.toString();
	}

	@Override
	public int bigDecimalCount() {
		return 2;
	}

	@Override
	public void fromBigDecimalArray(BigDecimal[] arr, int index) {
		r = arr[index];
		i = arr[index+1];
	}

	@Override
	public void toBigDecimalArray(BigDecimal[] arr, int index) {
		arr[index] = r;
		arr[index+1] = i;
	}

	@Override
	public ComplexHighPrecisionMember allocate() {
		return new ComplexHighPrecisionMember();
	}

	@Override
	public ComplexHighPrecisionMember duplicate() {
		return new ComplexHighPrecisionMember(this);
	}

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

	@Override
	public void getV(ComplexHighPrecisionMember value) {
		get(value);
	}

	@Override
	public void setV(ComplexHighPrecisionMember value) {
		set(value);
	}

	@Override
	public void toRep(TensorOctonionRepresentation rep) {
		rep.setValue(
			new OctonionRepresentation(
				r(),
				i()
			)
		);
	}

	@Override
	public void fromRep(TensorOctonionRepresentation rep) {
		OctonionRepresentation v = rep.getValue();
		setR(v.r());
		setI(v.i());
	}

	@Override
	public PrimitiveRepresentation preferredRepresentation() {
		return PrimitiveRepresentation.BIGDECIMAL;
	}

	@Override
	public long dimension(int i) {
		return 0;
	}

	@Override
	public int componentCount() {
		return 2;
	}

	@Override
	public void primComponentSetByte(IntegerIndex index, int component, byte v) {
		if (component == 0)
			this.setR(BigDecimal.valueOf(v));
		else
			this.setI(BigDecimal.valueOf(v));
	}

	@Override
	public void primComponentSetShort(IntegerIndex index, int component, short v) {
		if (component == 0)
			this.setR(BigDecimal.valueOf(v));
		else
			this.setI(BigDecimal.valueOf(v));
	}

	@Override
	public void primComponentSetInt(IntegerIndex index, int component, int v) {
		if (component == 0)
			this.setR(BigDecimal.valueOf(v));
		else
			this.setI(BigDecimal.valueOf(v));
	}

	@Override
	public void primComponentSetLong(IntegerIndex index, int component, long v) {
		if (component == 0)
			this.setR(BigDecimal.valueOf(v));
		else
			this.setI(BigDecimal.valueOf(v));
	}

	@Override
	public void primComponentSetFloat(IntegerIndex index, int component, float v) {
		if (component == 0)
			this.setR(BigDecimal.valueOf(v));
		else
			this.setI(BigDecimal.valueOf(v));
	}

	@Override
	public void primComponentSetDouble(IntegerIndex index, int component, double v) {
		if (component == 0)
			this.setR(BigDecimal.valueOf(v));
		else
			this.setI(BigDecimal.valueOf(v));
	}

	@Override
	public void primComponentSetBigInteger(IntegerIndex index, int component, BigInteger v) {
		if (component == 0)
			this.setR(new BigDecimal(v));
		else
			this.setI(new BigDecimal(v));
	}

	@Override
	public void primComponentSetBigDecimal(IntegerIndex index, int component, BigDecimal v) {
		if (component == 0)
			this.setR(v);
		else
			this.setI(v);
	}

	@Override
	public void primComponentSetByteSafe(IntegerIndex index, int component, byte v) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			if (v != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			if (component == 0)
				this.setR(BigDecimal.valueOf(v));
			else
				this.setI(BigDecimal.valueOf(v));
		}
	}

	@Override
	public void primComponentSetShortSafe(IntegerIndex index, int component, short v) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			if (v != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			if (component == 0)
				this.setR(BigDecimal.valueOf(v));
			else
				this.setI(BigDecimal.valueOf(v));
		}
	}

	@Override
	public void primComponentSetIntSafe(IntegerIndex index, int component, int v) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			if (v != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			if (component == 0)
				this.setR(BigDecimal.valueOf(v));
			else
				this.setI(BigDecimal.valueOf(v));
		}
	}

	@Override
	public void primComponentSetLongSafe(IntegerIndex index, int component, long v) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			if (v != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			if (component == 0)
				this.setR(BigDecimal.valueOf(v));
			else
				this.setI(BigDecimal.valueOf(v));
		}
	}

	@Override
	public void primComponentSetFloatSafe(IntegerIndex index, int component, float v) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			if (v != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			if (component == 0)
				this.setR(BigDecimal.valueOf(v));
			else
				this.setI(BigDecimal.valueOf(v));
		}
	}

	@Override
	public void primComponentSetDoubleSafe(IntegerIndex index, int component, double v) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			if (v != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			if (component == 0)
				this.setR(BigDecimal.valueOf(v));
			else
				this.setI(BigDecimal.valueOf(v));
		}
	}

	@Override
	public void primComponentSetBigIntegerSafe(IntegerIndex index, int component, BigInteger v) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			if (v.signum() != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			if (component == 0)
				this.setR(new BigDecimal(v));
			else
				this.setI(new BigDecimal(v));
		}
	}

	@Override
	public void primComponentSetBigDecimalSafe(IntegerIndex index, int component, BigDecimal v) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			if (v.signum() != 0)
				throw new IllegalArgumentException(
						"cannot set nonzero value outside extents");
		}
		else {
			if (component == 0)
				this.setR(v);
			else
				this.setI(v);
		}
	}

	@Override
	public byte primComponentGetAsByte(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		if (component == 0) return r().byteValue();
		if (component == 1) return i().byteValue();
		return 0;
	}

	@Override
	public short primComponentGetAsShort(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		if (component == 0) return r().shortValue();
		if (component == 1) return i().shortValue();
		return 0;
	}

	@Override
	public int primComponentGetAsInt(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		if (component == 0) return r().intValue();
		if (component == 1) return i().intValue();
		return 0;
	}

	@Override
	public long primComponentGetAsLong(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		if (component == 0) return r().longValue();
		if (component == 1) return i().longValue();
		return 0;
	}

	@Override
	public float primComponentGetAsFloat(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		if (component == 0) return r().floatValue();
		if (component == 1) return i().floatValue();
		return 0;
	}

	@Override
	public double primComponentGetAsDouble(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		if (component == 0) return r().doubleValue();
		if (component == 1) return i().doubleValue();
		return 0;
	}

	@Override
	public BigInteger primComponentGetAsBigInteger(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		if (component == 0) return r().toBigInteger();
		if (component == 1) return i().toBigInteger();
		return BigInteger.ZERO;
	}

	@Override
	public BigDecimal primComponentGetAsBigDecimal(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		if (component == 0) return r();
		if (component == 1) return i();
		return BigDecimal.ZERO;
	}

	@Override
	public byte primComponentGetAsByteSafe(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			return 0;
		}
		else {
			if (component == 0) return r().byteValue();
			else return i().byteValue();
		}
	}

	@Override
	public short primComponentGetAsShortSafe(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			return 0;
		}
		else {
			if (component == 0) return r().shortValue();
			else return i().shortValue();
		}
	}

	@Override
	public int primComponentGetAsIntSafe(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			return 0;
		}
		else {
			if (component == 0) return r().intValue();
			else return i().intValue();
		}
	}

	@Override
	public long primComponentGetAsLongSafe(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			return 0;
		}
		else {
			if (component == 0) return r().longValue();
			else return i().longValue();
		}
	}

	@Override
	public float primComponentGetAsFloatSafe(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			return 0;
		}
		else {
			if (component == 0) return r().floatValue();
			else return i().floatValue();
		}
	}

	@Override
	public double primComponentGetAsDoubleSafe(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			return 0;
		}
		else {
			if (component == 0) return r().doubleValue();
			else return i().doubleValue();
		}
	}

	@Override
	public BigInteger primComponentGetAsBigIntegerSafe(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			return BigInteger.ZERO;
		}
		else {
			if (component == 0) return r().toBigInteger();
			else return i().toBigInteger();
		}
	}

	@Override
	public BigDecimal primComponentGetAsBigDecimalSafe(IntegerIndex index, int component) {
		if (component < 0)
			throw new IllegalArgumentException(
					"negative component index error");
		boolean oob = component > 1;
		if (!oob) {
			for (int i = 0; i < numDimensions(); i++) {
				if (index.get(i) != 0) {
					oob = true;
					break;
				}
			}
		}
		if (oob) {
			return BigDecimal.ZERO;
		}
		else {
			if (component == 0) return r();
			else return i();
		}
	}

	@Override
	public void primitiveInit() {
		r = i = BigDecimal.ZERO;
	}

	@Override
	public void setR(HighPrecisionMember val) {
		setR(val.v());
	}

	@Override
	public void setI(HighPrecisionMember val) {
		setI(val.v());
	}

	@Override
	public void getR(HighPrecisionMember v) {
		v.setV(r);
	}

	@Override
	public void getI(HighPrecisionMember v) {
		v.setV(i);
	}

	@Override
	public int hashCode() {
		int v = 1;
		v = Hasher.PRIME * v + Hasher.hashCode(r);
		v = Hasher.PRIME * v + Hasher.hashCode(i);
		return v;
	}

	@Override
	public boolean equals(Object o) {
		if (o instanceof ComplexHighPrecisionMember) {
			return G.CHP.isEqual().call(this, (ComplexHighPrecisionMember) o);
		}
		return false;
	}

	@Override
	public void setFromDouble(double... vals) {
		setR(BigDecimal.valueOf(vals[0]));
		setI(BigDecimal.valueOf(vals[1]));
	}

	@Override
	public void setFromLong(long... vals) {
		setR(BigDecimal.valueOf(vals[0]));
		setI(BigDecimal.valueOf(vals[1]));
	}

	@Override
	public void setFromBigInteger(BigInteger... vals) {
		setR(new BigDecimal(vals[0]));
		setI(new BigDecimal(vals[1]));
	}

	@Override
	public void setFromBigDecimal(BigDecimal... vals) {
		setR(vals[0]);
		setI(vals[1]);
	}

	@Override
	public BigDecimal[] getAsBigDecimalArray() {
		return new BigDecimal[] {r(), i()};
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.zen.android.zz.ui.news;

import com.zen.android.brite.dbflow.DbflowBrite;
import com.zen.android.zz.common.lifecycle.RxLifecyclePresenter;
import com.zen.android.zz.sdk.ZhiHu;
import com.zen.android.zz.sdk.model.Story;

import java.util.List;

import rx.android.schedulers.AndroidSchedulers;

/**
 * @author zen yang - 2016/12/8
 */
class NewsPresenter extends RxLifecyclePresenter<NewsView> {

    @Override
    public void onViewAttached(NewsView view) {
        super.onViewAttached(view);

        DbflowBrite.Query.from(Story.class)
                .queryModels()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::updateNews);
    }

    void fetchNews() {
        ZhiHu.get().service()
                .getNewsLatest()
                .compose(async())
                .subscribe(result -> {
                    DbflowBrite.save(Story.class, result.getStories());
                });
    }

    private void updateNews(List<Story> news) {
        NewsView v = getView();
        if (v != null) {
            v.showNews(news);
        }
    }

}


text:
title: Tools
aliases:
    - influxdb/v1.2/clients/
    - influxdb/v1.2/write_protocols/json/
---

This section covers the available tools for interacting with InfluxDB.

## [CLI/Shell](/influxdb/v1.2/tools/shell/)

InfluxDB's Command Line Interface (`influx`) is an interactive shell for the
HTTP API that comes with every InfluxDB package.
Use `influx` to write data (manually or from a file), query data interactively,
and view query output in different formats:

![CLI GIF](/img/influxdb/cli-1.0-beta.gif)

Go straight to the documentation on:

* [Launching `influx`](/influxdb/v1.2/tools/shell/#launch-influx)
* [Writing data with `influx`](/influxdb/v1.2/tools/shell/#write-data-to-influxdb-with-insert)

## [API Reference](/influxdb/v1.2/tools/api/)

Reference documentation for InfluxDB's HTTP API.

Go straight to the reference documentation on:

* [Writing data with the HTTP API](/influxdb/v1.2/tools/api/#write)
* [Querying data with the HTTP API](/influxdb/v1.2/tools/api/#query)

For friendlier documentation, see the guides on
[writing data](/influxdb/v1.2/guides/writing_data/) and
[querying data](/influxdb/v1.2/guides/querying_data/) with the HTTP API.

## [API Client Libraries](/influxdb/v1.2/tools/api_client_libraries/)

The list of client libraries for interacting with InfluxDB.

## [Web Admin Interface](/influxdb/v1.2/tools/web_admin/)

InfluxDB's built-in web administration GUI.
The built-in web administration GUI is deprecated in InfluxDB 1.2 and is disabled by default. We recommend using the [HTTP API](/influxdb/v1.2/tools/api/) or the [Command Line Interface](/influxdb/v1.2/tools/shell/) to interact with InfluxDB.

## [Influx Inspect](/influxdb/v1.2/tools/influx_inspect/)

Influx Inspect is a tool designed to view detailed information about on disk shards, as well as export data from a shard to line protocol that can be inserted back into the database.

## [Grafana Graphs and Dashboards](https://grafana.com/docs/grafana/latest/features/datasources/influxdb/)

Grafana is a convenient dashboard tool for visualizing time series data.
It was originally built for Graphite, modeled after Kibana, and since been updated to support InfluxDB.

{{% warn %}} Because of the [changes](/influxdb/v0.11/concepts/010_vs_011/#breaking-api-changes) to the `SHOW SERIES` and `SHOW TAG VALUES` formats in InfluxDB 0.11, InfluxDB 1.2 will not work with the Query Editor in Grafana 2.6.
This issue does not affect existing queries and dashboards or users working with Grafana 3.0. {{% /warn %}}

## Service Plugins

InfluxDB accepts writes over
[UDP](https://github.com/influxdata/influxdb/blob/master/services/udp/README.md)
and provides an easy way to set up
[Graphite](https://github.com/influxdata/influxdb/blob/master/services/graphite/README.md),
[CollectD](https://github.com/influxdata/influxdb/blob/master/services/collectd/README.md),
and [OpenTSDB](https://github.com/influxdb/influxdb/blob/1.2/services/opentsdb/README.md) as input sources.


text:
{% load embed_video_tags sekizai_tags %}

<div class="oembed-video" {% if max_width %} style="max-width: {{max_width}}px" {% endif %}>
	{% video item 'small' %}
</div>

{% addtoblock "css" %}<link rel="stylesheet" href="{{ STATIC_URL }}cmsplugin_oembed/css/style.css">{% endaddtoblock "css" %}

{% addtoblock "js" %}<script src="{{ STATIC_URL }}bower_components/fitvids/jquery.fitvids.js"></script>{% endaddtoblock "js" %}
{% addtoblock "js" %}
<script>
	$(document).ready(function(){
			// Target your .container, .wrapper, .post, etc.
					$(".oembed-video").fitVids();
});
</script>
{% endaddtoblock "js" %}


text:
package org.seasar.dao.pager;

/**
 * @author jundu
 *
 */
public class NullPagingSqlRewriter implements PagingSqlRewriter {

    private boolean countSqlCompatibility = true;

    public String rewrite(String sql, Object[] args, Class[] argTypes) {
        return sql;
    }

    public void setCount(String baseSQL, Object[] args, Object[] bindVariables,
            Class[] bindVariableTypes) {
        // 何もしない
    }

    public boolean isCountSqlCompatibility() {
        return countSqlCompatibility;
    }

}


text:
/**************************************************\
README: JEFFSTRAP.CSS Sinatra Stylesheet
Developed by Jeff George
DBC Copperheads/Island Foxes 2016
Designed for use in projects based on
the Dev Bootcamp Sinatra Skeleton

This stylesheet is designed to rely on element tags
as css selectors, so it can be dropped on DBC Sinatra
Skeleton projects to provide bare-bones styling without
adding classes to the HTML file. Ordinarily, avoiding
classes when styling would be bad practice; in this case,
we use tags instead so that the stylesheet can be applied
with minimal time invested in CSS styling.

TO INCLUDE THIS STYLESHEET in your project,
add the following link to the <head> of layout.erb,
*between* the links to normalize.css and application.css:
  <link rel="stylesheet" href="/css/jeffstrap.css">

FOR SPECIFIED GOOGLE FONTS,
add the following link to layout.erb, before the links to
local css stylesheets:
  <link href='https://fonts.googleapis.com/css?family=Bangers|Open+Sans:400,700,400italic,700italic' rel='stylesheet' type='text/css'>

These fonts are only referenced in two css rules, both in the
GENERAL STYLES section of this sheet. Open Sans, which is used
for everything except major headings, is declared in the style
for the <body> tag; Bangers, a decorative font, is assigned in
a single rule for h1, h2, and h3 headings. If you change these
fonts, just add the link to the Google fonts, and declare the
fonts in those two rules.

* Thanks(?) to DBC Copperhead Jon Chen
for coining the name "jeffstrap".
\************************************************/

/* GENERAL STYLES */

html {
  box-sizing: border-box;
  background-color: #888;
  color: #ddd;
  font-size: 12px;
  line-height: 1.4;
}

*, *:before, *:after {
  box-sizing: inherit;
  margin: 0;
  padding: 0;
}

body {
  min-width: 320px;
  max-width: 400px;
  margin: 0 auto;
  font-family: 'Open Sans', sans-serif;
  background-color: #222;
}

h1, h2, h3, h4, h5, h6 {
  margin-bottom: 0;
  margin-top: 0;
}

h1, h2, h3 {
  font-family: Bangers, sans-serif;
  letter-spacing: 0.075rem;
}

h1 {
  font-size: 2.5rem;
}

h2 {
  font-size: 2rem;
}

h3 {
  font-size: 1.75rem;
}

p {
  margin: 0.5rem 0;
}

a:link,
a:visited {
  color: #cc0000;
  font-weight: bold;
  text-decoration: none;
}

a:hover,
a:active {
  color: #ff2222;
  font-weight: bold;
  text-decoration: none;
}

/* HEADER STYLES */

header {
  padding: 1rem;
}

header h1 {
  margin-bottom: 1rem;
  font-size: 2.75rem;
}

header ul {
}

header ul li {
  display: inline-block;
  padding-left: 1rem;
}

header ul li {
  padding: 0 0.5rem;
  border-left: 2px solid #444;
}

header ul li:first-child {
  border-left: 0;
}

header ul li input[type="submit"] {
  overflow: visible;
  text-align: center;
  width: auto;
  border: none;
  background-color: #222;
  color: #c00;
  font-weight: bold;
}

header ul li input[type="submit"]:hover,
header ul li input[type="submit"]:active {
  color: #f22;
}

/* MAIN STYLES - within YIELD block */

main {
  color: #222;
  clear: both;
  padding: 1rem;
  background-color: #ddd;
}

main li {
  font-size: 1.25rem;
}

main ol li {
  position: relative;
  left: 1.5rem;
  margin: 0;
}

main ul li {
  margin: 0.5rem 0;
  list-style: none;
}

main input {
  display: block;
  margin-bottom: 0.75rem;
  width: 100%;
}

main input[type="text"] {
  padding: 0 0.5rem;
}

main input[type="submit"] {
  width: 20rem;
}

main textarea {
  width: 100%;
  height: 5rem;
  margin-bottom: 1rem;
  padding: 0.5rem;
}

main table {
  margin-bottom: 1rem;
  border: 1px #222 solid;
  background-color: #fff;
  width: 100%;
}

main tr:first-child {
  background-color: #aaa;
  color: #222;
}

main th,
main td {
  padding: 0.25rem 0;
  width: 25%;
  text-align: center;
  border: 1px solid #222;
}

.error {
  color: #d00;
  font-weight: bold;
  text-align: center;
}

/* FOOTER STYLES */

footer {
  text-align: center;
  font-size: 0.8rem;
  padding: 1rem;
}

footer p {
  margin: 0;
  padding: 0;
}

/* MEDIA QUERIES for screens larger than phones */

/* TABLET - 680px */

@media only screen and (min-width: 680px) {

  html {
    font-size: 14px;
  }

  body {
    width: 680px;
    max-width: 680px;
  }

  header h1 {
    float: left;
  }

  header ul {
    float: right;
  }
}

/* COMPUTER (small monitor) - 960px */

@media only screen and (min-width: 960px) {

  html {
    font-size: 16px;
  }

  body {
    width: 960px;
    max-width: 960px;
  }
}

/* COMPUTER (desktop) - 1120px */

@media only screen and (min-width: 1200px) {

  html {
    font-size: 19px;
  }

  body {
    width: 1200px;
    max-width: 1200px;
  }
}


text:
class UserMailer < ActionMailer::Base
  default from: "admin@fuinneamh.com"

  def welcome_email(user)
    @user = user
    @url = 'http://fuinneamh.com/login'
    mail(to: @user.email, subject: 'Welcome to Fuinneamh!')
  end
end


text:
package com.twitter.zipkin.common

import java.nio.ByteBuffer
import com.twitter.io.Charsets.Utf8

case class BinaryAnnotation(
  key: String,
  value: ByteBuffer,
  annotationType: AnnotationType,
  host: Option[Endpoint]
)

object BinaryAnnotation {
  def apply[V](key: String, value: BinaryAnnotationValue[V], host: Option[Endpoint]): BinaryAnnotation =
    BinaryAnnotation(key, value.encode, value.annotationType, host)
  def apply[V](key: String, value: V, host: Option[Endpoint])(implicit enc: BinaryAnnotationValueEncoder[V]): BinaryAnnotation =
    BinaryAnnotation(key, BinaryAnnotationValue(value), host)
}

case class BinaryAnnotationValue[V](self: V)(implicit  enc: BinaryAnnotationValueEncoder[V]) extends Proxy {
  val annotationType = enc.typ
  def encode: ByteBuffer = enc.encode(self)
}

case class BinaryAnnotationValueEncoder[V](typ: AnnotationType, encode: V => ByteBuffer)

object BinaryAnnotationValueEncoder {
  private def intoBuffer[V](z: Int, f: ByteBuffer => V => ByteBuffer): V => ByteBuffer = {v =>
    f(ByteBuffer.allocate(z))(v).rewind.asInstanceOf[ByteBuffer]
  }

  implicit val StringEncoder =
    BinaryAnnotationValueEncoder[String](AnnotationType.String, {v => ByteBuffer.wrap(v.getBytes(Utf8))})

  implicit  val BooleanEncoder =
    BinaryAnnotationValueEncoder[Boolean](AnnotationType.Bool, {v => ByteBuffer.wrap(Array((if (v) 1 else 0).toByte))})

  implicit val ShortEncoder =
    BinaryAnnotationValueEncoder[Short](AnnotationType.I16, intoBuffer(2, _.putShort))

  implicit val IntEncoder =
    BinaryAnnotationValueEncoder[Int](AnnotationType.I32, intoBuffer(4, _.putInt))

  implicit val LongEncoder =
    BinaryAnnotationValueEncoder[Long](AnnotationType.I64, intoBuffer(8, _.putLong))

  implicit val DoubleEncoder =
    BinaryAnnotationValueEncoder[Double](AnnotationType.Double, intoBuffer(8, _.putDouble))
}


text:
@interface GHCAppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate>
@end


text:
<?php

/**
 * @defgroup oai
 */

/**
 * @file classes/oai/OAI.inc.php
 *
 * Copyright (c) 2000-2012 John Willinsky
 * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
 *
 * @class OAI
 * @ingroup oai
 * @see OAIDAO
 *
 * @brief Class to process and respond to OAI requests.
 */

// $Id$

import('oai.OAIStruct');
import('oai.OAIUtils');

class OAI {
	/** @var $config OAIConfig configuration parameters */
	var $config;

	/** @var $params array list of request parameters */
	var $params;

	/** @var $protocolVersion string version of the OAI protocol supported by this class */
	var $protocolVersion = '2.0';

	/**
	 * Constructor.
	 * Initializes object and parses user input.
	 * @param $config OAIConfig repository configuration
	 */
	function OAI(&$config) {
		$this->config = $config;

		// Initialize parameters from GET or POST variables
		$this->params = array();

		if (isset($GLOBALS['HTTP_RAW_POST_DATA']) && !empty($GLOBALS['HTTP_RAW_POST_DATA'])) {
			OAIUtils::parseStr($GLOBALS['HTTP_RAW_POST_DATA'], $this->params);

		} else if (!empty($_SERVER['QUERY_STRING'])) {
			OAIUtils::parseStr($_SERVER['QUERY_STRING'], $this->params);

		} else {
			$this->params = array_merge($_GET, $_POST);
		}

		// Clean input variables
		OAIUtils::prepInput($this->params);

		// Encode data with gzip, deflate, or none, depending on browser support
		ob_start('ob_gzhandler');
	}

	/**
	 * Execute the requested OAI protocol request
	 * and output the response.
	 */
	function execute() {
		switch ($this->getParam('verb')) {
			case 'GetRecord':
				$this->GetRecord();
				break;
			case 'Identify':
				$this->Identify();
				break;
			case 'ListIdentifiers':
				$this->ListIdentifiers();
				break;
			case 'ListMetadataFormats':
				$this->ListMetadataFormats();
				break;
			case 'ListRecords':
				$this->ListRecords();
				break;
			case 'ListSets':
				$this->ListSets();
				break;
			default:
				$this->error('badVerb', 'Illegal OAI verb');
				break;
		}
	}

	//
	// Abstract implementation-specific functions
	// (to be overridden in subclass)
	//

	/**
	 * Return information about the repository.
	 * @return OAIRepository
	 */
	function &repositoryInfo() {
		$info = false;
		return $info;
	}

	/**
	 * Check if identifier is in the valid format.
	 * @param $identifier string
	 * @return boolean
	 */
	function validIdentifier($identifier) {
		return false;
	}

	/**
	 * Check if identifier exists.
	 * @param $identifier string
	 * @return boolean
	 */
	function identifierExists($identifier) {
		return false;
	}

	/**
	 * Return OAI record for specified identifier.
	 * @param $identifier string
	 * @return OAIRecord (or false, if identifier is invalid)
	 */
	function &record($identifier) {
		$record = false;
		return $record;
	}

	/**
	 * Return set of OAI records.
	 * @param $metadataPrefix string specified metadata prefix
	 * @param $from int minimum timestamp
	 * @param $until int maximum timestamp
	 * @param $set string specified set
	 * @param $offset int current record offset
	 * @param $limit int maximum number of records to return
	 * @param $total int output parameter, set to total number of records
	 * @return array OAIRecord
	 */
	function &records($metadataPrefix, $from, $until, $set, $offset, $limit, &$total) {
		$records = array();
		return $records;
	}

	/**
	 * Return set of OAI identifiers.
	 * @see getRecords
	 * @return array OAIIdentifier
	 */
	function &identifiers($metadataPrefix, $from, $until, $set, $offset, $limit, &$total) {
		$identifiers = array();
		return $identifiers;
	}

	/**
	 * Return set of OAI sets.
	 * @param $offset int current set offset
	 * @param $total int output parameter, set to total number of sets
	 */
	function &sets($offset, &$total) {
		$sets = array();
		return $sets;
	}

	/**
	 * Retrieve a resumption token.
	 * @param $tokenId string
	 * @return OAIResumptionToken (or false, if token invalid)
	 */
	function &resumptionToken($tokenId) {
		$token = false;
		return $token;
	}

	/**
	 * Save a resumption token.
	 * @param $offset int current offset
	 * @param $params array request parameters
	 * @return OAIResumptionToken the saved token
	 */
	function &saveResumptionToken($offset, $params) {
		$token = null;
		return $token;
	}

	/**
	 * Return array of supported metadata formats.
	 * @param $namesOnly boolean return array of format prefix names only
	 * @param $identifier string return formats for specific identifier
	 * @return array
	 */
	function &metadataFormats($namesOnly = false, $identifier = null) {
		$formats = array();
		HookRegistry::call('OAI::metadataFormats', array($namesOnly, $identifier, &$formats));

		return $formats;
	}

	//
	// Protocol request handlers
	//

	/**
	 * Handle OAI GetRecord request.
	 * Retrieves an individual record from the repository.
	 */
	function GetRecord() {
		// Validate parameters
		if (!$this->checkParams(array('identifier', 'metadataPrefix'))) {
			return;
		}

		$identifier = $this->getParam('identifier');
		$metadataPrefix = $this->getParam('metadataPrefix');

		// Check that identifier is in valid format
		if ($this->validIdentifier($identifier) === false) {
			$this->error('badArgument', 'Identifier is not in a valid format');
			return;
		}

		// Get metadata for requested identifier
		if (($record =& $this->record($identifier)) === false) {
			$this->error('idDoesNotExist', 'No matching identifier in this repository');
			return;
		}

		// Check that the requested metadata format is supported for this identifier
		if (!in_array($metadataPrefix, $this->metadataFormats(true, $identifier))) {
			$this->error('cannotDisseminateFormat', 'The requested metadataPrefix is not supported by this repository');
			return;
		}

		// Display response
		$response = "\t<GetRecord>\n" .
			"\t\t<record>\n" .
			"\t\t\t\n" .
			"\t\t\t\t<identifier>" . $record->identifier ."</identifier>\n" .
			"\t\t\t\t<datestamp>" . $record->datestamp . "</datestamp>\n";
		// Output set memberships
		foreach ($record->sets as $setSpec) {
			$response .= "\t\t\t\t<setSpec>$setSpec</setSpec>\n";
		}
		$response .= "\t\t\t\n" .
			"\t\t\t<metadata>\n";
		// Output metadata
		$response .= $this->formatMetadata($metadataPrefix, $record);
		$response .= "\t\t\t</metadata>\n" .
			"\t\t</record>\n" .
			"\t</GetRecord>\n";

		$this->response($response);
	}

	/**
	 * Handle OAI Identify request.
	 * Retrieves information about a repository.
	 */
	function Identify() {
		// Validate parameters
		if (!$this->checkParams()) {
			return;
		}

		$info =& $this->repositoryInfo();

		// Format body of response
		$response = "\t<Identify>\n" .
			"\t\t<repositoryName>" . OAIUtils::prepOutput($info->repositoryName) . "</repositoryName>\n" .
			"\t\t<baseURL>" . $this->config->baseUrl . "</baseURL>\n" .
			"\t\t<protocolVersion>" . $this->protocolVersion . "</protocolVersion>\n" .
			"\t\t<adminEmail>" . $info->adminEmail . "</adminEmail>\n" .
			"\t\t<earliestDatestamp>" . OAIUtils::UTCDate($info->earliestDatestamp) . "</earliestDatestamp>\n" .
			"\t\t<deletedRecord>no</deletedRecord>\n" . // FIXME Support deleted records?
			"\t\t<granularity>" . $this->config->granularity . "</granularity>\n";
		if (extension_loaded('zlib')) {
			// Show compression options if server supports Zlib
			$response .= "\t\t<compression>gzip</compression>\n" .
				"\t\t<compression>deflate</compression>\n";
		}
		$response .= "\t\t<description>\n" .
			"\t\t\t<oai-identifier\n" .
			"\t\t\t\txmlns=\"http://www.openarchives.org/OAI/2.0/oai-identifier\"\n" .
			"\t\t\t\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" .
			"\t\t\t\txsi:schemaLocation=\"http://www.openarchives.org/OAI/2.0/oai-identifier\n" .
			"\t\t\t\t\thttp://www.openarchives.org/OAI/2.0/oai-identifier.xsd\">\n" .
			"\t\t\t\t<scheme>oai</scheme>\n" .
			"\t\t\t\t<repositoryIdentifier>" . $this->config->repositoryId . "</repositoryIdentifier>\n" .
			"\t\t\t\t<delimiter>" . $info->delimiter . "</delimiter>\n" .
			"\t\t\t\t<sampleIdentifier>" . $info->sampleIdentifier . "</sampleIdentifier>\n" .
			"\t\t\t</oai-identifier>\n" .
			"\t\t</description>\n" .
			"\t</Identify>\n";

		$this->response($response);
	}

	/**
	 * Handle OAI ListIdentifiers request.
	 * Retrieves headers of records from the repository.
	 */
	function ListIdentifiers() {
		$offset = 0;

		// Check for resumption token
		if ($this->paramExists('resumptionToken')) {
			// Validate parameters
			if (!$this->checkParams(array('resumptionToken'))) {
				return;
			}

			// Get parameters from resumption token
			if (($token =& $this->resumptionToken($this->getParam('resumptionToken'))) === false) {
				$this->error('badResumptionToken', 'The requested resumptionToken is invalid or has expired');
				return;
			}

			$this->setParams($token->params);
			$offset = $token->offset;
		}

		// Validate parameters
		if (!$this->checkParams(array('metadataPrefix'), array('from', 'until', 'set'))) {
			return;
		}

		$metadataPrefix = $this->getParam('metadataPrefix');
		$set = $this->getParam('set');

		// Check that the requested metadata format is supported
		if (!in_array($metadataPrefix, $this->metadataFormats(true))) {
			$this->error('cannotDisseminateFormat', 'The requested metadataPrefix is not supported by this repository');
			return;
		}

		// If a set was passed in check if repository supports sets
		if (isset($set) && $this->config->maxSets == 0) {
			$this->error('noSetHierarchy', 'This repository does not support sets');
			return;
		}

		// Get UNIX timestamps for from and until dates, if applicable
		if (!$this->extractDateParams($this->getParams(), $from, $until)) {
			return;
		}

		// Store current offset and total records for resumption token, if needed
		$cursor = $offset;
		$total = 0;

		// Get list of matching identifiers
		$records =& $this->identifiers($metadataPrefix, $from, $until, $set, $offset, $this->config->maxIdentifiers, $total);
		if (empty($records)) {
			$this->error('noRecordsMatch', 'No matching records in this repository');
			return;
		}

		// Format body of response
		$response = "\t<ListIdentifiers>\n";

		// Output identifiers
		for ($i = 0, $num = count($records); $i < $num; $i++) {
			$record = $records[$i];
			$response .= "\t\t\n" .
				"\t\t\t<identifier>" . $record->identifier . "</identifier>\n" .
				"\t\t\t<datestamp>" . $record->datestamp . "</datestamp>\n";
			// Output set memberships
			foreach ($record->sets as $setSpec) {
				$response .= "\t\t\t<setSpec>" . OAIUtils::prepOutput($setSpec) . "</setSpec>\n";
			}
			$response .= "\t\t\n";
		}
		$offset += $num;

		if ($offset != 0 && $offset < $total) {
			// Partial result, save resumption token
			$token =& $this->saveResumptionToken($offset, $this->getParams());

			$response .= "\t\t<resumptionToken expirationDate=\"" . OAIUtils::UTCDate($token->expire) . "\"\n" .
				"\t\t\tcompleteListSize=\"$total\"\n" .
				"\t\t\tcursor=\"$cursor\">" . $token->id . "</resumptionToken>\n";

		} else if (isset($token)) {
			// Current request completes a previous incomplete list, add empty resumption token
			$response .= "\t\t<resumptionToken completeListSize=\"$total\" cursor=\"$cursor\" />\n";
		}

		$response .= "\t</ListIdentifiers>\n";

		$this->response($response);
	}

	/**
	 * Handle OAI ListMetadataFormats request.
	 * Retrieves metadata formats supported by the repository.
	 */
	function ListMetadataFormats() {
		// Validate parameters
		if (!$this->checkParams(array(), array('identifier'))) {
			return;
		}

		// Get list of metadata formats for selected identifier, or all formats if no identifier was passed
		if ($this->paramExists('identifier')) {
			if (!$this->identifierExists($this->getParam('identifier'))) {
				$this->error('idDoesNotExist', 'No matching identifier in this repository');
				return;

			} else {
				$formats =& $this->metadataFormats(false, $this->getParam('identifier'));
			}

		} else {
			$formats =& $this->metadataFormats();
		}

		if (empty($formats) || !is_array($formats)) {
			$this->error('noMetadataFormats', 'No metadata formats are available');
			return;
		}

		// Format body of response
		$response = "\t<ListMetadataFormats>\n";

		// output metadata formats
		foreach ($formats as $prefix => $format) {
			$response .= "\t\t<metadataFormat>\n" .
				"\t\t\t<metadataPrefix>" . $format->prefix . "</metadataPrefix>\n" .
				"\t\t\t<schema>" . $format->schema . "</schema>\n" .
				"\t\t\t<metadataNamespace>" . $format->namespace . "</metadataNamespace>\n" .
				"\t\t</metadataFormat>\n";
		}

		$response .= "\t</ListMetadataFormats>\n";

		$this->response($response);
	}

	/**
	 * Handle OAI ListRecords request.
	 * Retrieves records from the repository.
	 */
	function ListRecords() {
		$offset = 0;

		// Check for resumption token
		if ($this->paramExists('resumptionToken')) {
			// Validate parameters
			if (!$this->checkParams(array('resumptionToken'))) {
				return;
			}

			// get parameters from resumption token
			if (($token =& $this->resumptionToken($this->getParam('resumptionToken'))) === false) {
				$this->error('badResumptionToken', 'The requested resumptionToken is invalid or has expired');
				return;
			}

			$this->setParams($token->params);
			$offset = $token->offset;

		}

		// Validate parameters
		if (!$this->checkParams(array('metadataPrefix'), array('from', 'until', 'set'))) {
			return;
		}

		$metadataPrefix = $this->getParam('metadataPrefix');
		$set = $this->getParam('set');

		// Check that the requested metadata format is supported
		if (!in_array($metadataPrefix, $this->metadataFormats(true))) {
			$this->error('cannotDisseminateFormat', 'The requested metadataPrefix is not supported by this repository');
			return;
		}

		// If a set was passed check if repository supports sets
		if (isset($set) && $this->config->maxSets == 0) {
			$this->error('noSetHierarchy', 'This repository does not support sets');
			return;
		}

		// Get UNIX timestamps for from and until dates, if applicable
		if (!$this->extractDateParams($this->getParams(), $from, $until)) {
			return;
		}

		// Store current offset and total records for resumption token, if needed
		$cursor = $offset;
		$total = 0;

		// Get list of matching records
		$records =& $this->records($metadataPrefix, $from, $until, $set, $offset, $this->config->maxRecords, $total);
		if (empty($records)) {
			$this->error('noRecordsMatch', 'No matching records in this repository');
			return;
		}

		// Format body of response
		$response = "\t<ListRecords>\n";

		// Output records
		for ($i = 0, $num = count($records); $i < $num; $i++) {
			$record = $records[$i];
			$response .= "\t\t<record>\n" .
				"\t\t\t\n" .
				"\t\t\t\t<identifier>" . $record->identifier . "</identifier>\n" .
				"\t\t\t\t<datestamp>" . $record->datestamp . "</datestamp>\n";
			// Output set memberships
			foreach ($record->sets as $setSpec) {
				$response .= "\t\t\t\t<setSpec>" . OAIUtils::prepOutput($setSpec) . "</setSpec>\n";
			}
			$response .=	"\t\t\t\n" .
					"\t\t\t<metadata>\n";
			// Output metadata
			$response .= $this->formatMetadata($this->getParam('metadataPrefix'), $record);
			$response .=	"\t\t\t</metadata>\n" .
					"\t\t</record>\n";
		}
		$offset += $num;

		if ($offset != 0 && $offset < $total) {
			// Partial result, save resumption token
			$token =& $this->saveResumptionToken($offset, $this->getParams());

			$response .=	"\t\t<resumptionToken expirationDate=\"" . OAIUtils::UTCDate($token->expire) . "\"\n" .
					"\t\t\tcompleteListSize=\"$total\"\n" .
					"\t\t\tcursor=\"$cursor\">" . $token->id . "</resumptionToken>\n";

		} else if(isset($token)) {
			// Current request completes a previous incomplete list, add empty resumption token
			$response .= "\t\t<resumptionToken completeListSize=\"$total\" cursor=\"$cursor\" />\n";
		}

		$response .= "\t</ListRecords>\n";

		$this->response($response);
	}

	/**
	 * Handle OAI ListSets request.
	 * Retrieves sets from a repository.
	 */
	function ListSets() {
		$offset = 0;

		// Check for resumption token
		if ($this->paramExists('resumptionToken')) {
			// Validate parameters
			if (!$this->checkParams(array('resumptionToken'))) {
				return;
			}

			// Get parameters from resumption token
			if (($token =& $this->resumptionToken($this->getParam('resumptionToken'))) === false) {
				$this->error('badResumptionToken', 'The requested resumptionToken is invalid or has expired');
				return;
			}

			$this->setParams($token->params);
			$offset = $token->offset;

		}

		// Validate parameters
		if (!$this->checkParams()) {
			return;
		}

		// Store current offset and total sets for resumption token, if needed
		$cursor = $offset;
		$total = 0;

		// Get list of matching sets
		$sets =& $this->sets($offset, $total);
		if (empty($sets)) {
			$this->error('noSetHierarchy', 'This repository does not support sets');
			return;
		}

		// Format body of response
		$response = "\t<ListSets>\n";

		// Output sets
		for ($i = 0, $num = count($sets); $i < $num; $i++) {
			$set = $sets[$i];
			$response .=	"\t\t<set>\n" .
					"\t\t\t<setSpec>" . OAIUtils::prepOutput($set->spec) . "</setSpec>\n" .
					"\t\t\t<setName>" . OAIUtils::prepOutput($set->name) . "</setName>\n";
			// output set description, if applicable
			if (isset($set->description)) {
				$response .=	"\t\t\t<setDescription>\n" .
						"\t\t\t\t<oai_dc:dc\n" .
						"\t\t\t\t\txmlns:oai_dc=\"http://www.openarchives.org/OAI/2.0/oai_dc/\"\n" .
						"\t\t\t\t\txmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n" .
						"\t\t\t\t\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" .
						"\t\t\t\t\txsi:schemaLocation=\"http://www.openarchives.org/OAI/2.0/oai_dc/\n" .
						"\t\t\t\t\t\thttp://www.openarchives.org/OAI/2.0/oai_dc.xsd\">\n" .
						"\t\t\t\t\t<dc:description>" . OAIUtils::prepOutput($set->description) . "</dc:description>\n" .
						"\t\t\t\t</oai_dc:dc>\n" .
						"\t\t\t</setDescription>\n";

			}
			$response .= "\t\t</set>\n";
		}

		if ($offset != 0 && $offset < $total) {
			// Partial result, set resumption token
			$token =& $this->saveResumptionToken($offset, $this->getParams());

			$response .=	"\t\t<resumptionToken expirationDate=\"" . OAIUtils::UTCDate($token->expire) . "\"\n" .
					"\t\t\tcompleteListSize=\"$total\"\n" .
					"\t\t\tcursor=\"$cursor\">" . $token->id . "</resumptionToken>\n";

		} else if (isset($token)) {
			// current request completes a previous incomplete list, add empty resumption token
			$response .= "\t\t<resumptionToken completeListSize=\"$total\" cursor=\"$cursor\" />\n";
		}

		$response .= "\t</ListSets>\n";

		$this->response($response);
	}

	//
	// Private helper functions
	//

	/**
	 * Display OAI error response.
	 */
	function error($code, $message) {
		if (in_array($code, array('badVerb', 'badArgument'))) {
			$printParams = false;

		} else {
			$printParams = true;
		}

		$this->response("\t<error code=\"$code\">$message</error>", $printParams);
	}

	/**
	 * Output OAI response.
	 * @param $response string text of response message.
	 * @param $printParams boolean display request parameters
	 */
	function response($response, $printParams = true) {
		header('Content-Type: text/xml');

		echo	"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" .
			"<?xml-stylesheet type=\"text/xsl\" href=\"" . PKPRequest::getBaseUrl() . "/lib/pkp/xml/oai2.xsl\" ?>\n" .
			"<OAI-PMH xmlns=\"http://www.openarchives.org/OAI/2.0/\"\n" .
			"\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" .
			"\txsi:schemaLocation=\"http://www.openarchives.org/OAI/2.0/\n" .
			"\t\thttp://www.openarchives.org/OAI/2.0/OAI-PMH.xsd\">\n" .
			"\t<responseDate>" . OAIUtils::UTCDate() . "</responseDate>\n" .
			"\t<request";

		// print request params, if applicable
		if($printParams) {
			foreach($this->params as $k => $v) {
				echo " $k=\"" . OAIUtils::prepOutput($v) . "\"";
			}
		}

		echo	">" . OAIUtils::prepOutput($this->config->baseUrl) . "</request>\n" .
			$response .
			"</OAI-PMH>\n";
	}

	/**
	 * Returns the value of the specified parameter.
	 * @param $name string
	 * @return string
	 */
	function getParam($name) {
		return isset($this->params[$name]) ? $this->params[$name] : null;
	}

	/**
	 * Returns an associative array of all request parameters.
	 * @return array
	 */
	function getParams() {
		return $this->params;
	}

	/**
	 * Set the request parameters.
	 * @param $params array
	 */
	function setParams(&$params) {
		$this->params = $params;
	}

	/**
	 * Returns true if the requested parameter is set, false if it is not set.
	 * @param $name string
	 * @return boolean
	 */
	function paramExists($name) {
		return isset($this->params[$name]);
	}

	/**
	 * Return a list of ignorable GET parameters.
	 * @return array
	 */
	function getNonPathInfoParams() {
		return array();
	}

	/**
	 * Check request parameters.
	 * Outputs error response if an invalid parameter is found.
	 * @param $required array required parameters for the current request
	 * @param $optional array optional parameters for the current request
	 * @return boolean
	 */
	function checkParams($required = array(), $optional = array()) {
		// Get allowed parameters for current request
		$requiredParams = array_merge(array('verb'), $required);
		$validParams = array_merge($requiredParams, $optional);

		// Check for missing or duplicate required parameters
		foreach ($requiredParams as $k) {
			if(!$this->paramExists($k)) {
				$this->error('badArgument', "Missing $k parameter");
				return false;

			} else if (is_array($this->getParam($k))) {
				$this->error('badArgument', "Multiple values are not allowed for the $k parameter");
				return false;
			}
		}

		// Check for duplicate optional parameters
		foreach ($optional as $k) {
			if ($this->paramExists($k) && is_array($this->getParam($k))) {
				$this->error('badArgument', "Multiple values are not allowed for the $k parameter");
				return false;
			}
		}

		// Check for illegal parameters
		foreach ($this->params as $k => $v) {
			if (!in_array($k, $validParams)) {
				// Ignore the "path" and "context" parameters if path_info is disabled.
				if (Request::isPathInfoEnabled() || !in_array($k, $this->getNonPathInfoParams())) {
					$this->error('badArgument', "$k is an illegal parameter");
					return false;
				}
			}
		}

		return true;
	}

	/**
	 * Returns formatted metadata response in specified format.
	 * @param $format string
	 * @param $metadata OAIMetadata
	 * @return string
	 */
	function &formatMetadata($format, $record) {
		$formats =& $this->metadataFormats();
		$metadata = $formats[$format]->toXml($record);
		return $metadata;
	}

	/**
	 * Checks if from and until parameters have been passed.
	 * If passed, validate and convert to UNIX timestamps.
	 * @param $params array request parameters
	 * @param $from int from timestamp (output parameter)
	 * @param $until int until timestamp (output parameter)
	 * @return boolean
	 */
	function extractDateParams($params, &$from, &$until) {
		if (isset($params['from'])) {
			$from = OAIUtils::UTCtoTimestamp($params['from']);

			if ($from == 'invalid') {
				$this->error('badArgument', 'Illegal from parameter');
				return false;

			} else if($from == 'invalid_granularity') {
				$this->error('badArgument', 'Illegal granularity for from parameter');
				return false;
			}
		}

		if(isset($params['until'])) {
			$until = OAIUtils::UTCtoTimestamp($params['until']);

			if($until == 'invalid') {
				$this->error('badArgument', 'Illegal until parameter');
				return false;

			} else if($until == 'invalid_granularity') {
				$this->error('badArgument', 'Illegal granularity for until parameter');
				return false;
			}

			// Check that until value is greater than or equal to from value
			if (isset($from) && $from > $until) {
				$this->error('badArgument', 'until parameter must be greater than or equal to from parameter');
				return false;
			}

			// Check that granularities are equal
			if (isset($from) && strlen($params['from']) != strlen($params['until'])) {
				$this->error('badArgument', 'until and from parameters must be of the same granularity');
				return false;
			}

			if (strlen($params['until']) == 10) {
				// Until date is inclusive
				$until += 86399;
			}
		}

		return true;
	}
}

?>


text:
from .version import __version__
from .macau import macau, bpmf, MacauResult
from .macau import blockcg, make_train_test, make_train_test_df


text:
//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements.  Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////

UNIX_WiFiEndpoint::UNIX_WiFiEndpoint(void)
{
}

UNIX_WiFiEndpoint::~UNIX_WiFiEndpoint(void)
{
}

Boolean UNIX_WiFiEndpoint::getInstanceID(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID());
	return true;
}

String UNIX_WiFiEndpoint::getInstanceID() const
{
	return String ("");
}

Boolean UNIX_WiFiEndpoint::getCaption(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_CAPTION, getCaption());
	return true;
}

String UNIX_WiFiEndpoint::getCaption() const
{
	return String ("");
}

Boolean UNIX_WiFiEndpoint::getDescription(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_DESCRIPTION, getDescription());
	return true;
}

String UNIX_WiFiEndpoint::getDescription() const
{
	return String ("");
}

Boolean UNIX_WiFiEndpoint::getElementName(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName());
	return true;
}

String UNIX_WiFiEndpoint::getElementName() const
{
	return String("WiFiEndpoint");
}

Boolean UNIX_WiFiEndpoint::getInstallDate(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_INSTALL_DATE, getInstallDate());
	return true;
}

CIMDateTime UNIX_WiFiEndpoint::getInstallDate() const
{
	struct tm* clock;			// create a time structure
	time_t val = time(NULL);
	clock = gmtime(&(val));	// Get the last modified time and put it into the time structure
	return CIMDateTime(
		clock->tm_year + 1900,
		clock->tm_mon + 1,
		clock->tm_mday,
		clock->tm_hour,
		clock->tm_min,
		clock->tm_sec,
		0,0,
		clock->tm_gmtoff);
}

Boolean UNIX_WiFiEndpoint::getName(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_NAME, getName());
	return true;
}

String UNIX_WiFiEndpoint::getName() const
{
	return String ("");
}

Boolean UNIX_WiFiEndpoint::getOperationalStatus(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_OPERATIONAL_STATUS, getOperationalStatus());
	return true;
}

Array<Uint16> UNIX_WiFiEndpoint::getOperationalStatus() const
{
	Array<Uint16> as;

	return as;

}

Boolean UNIX_WiFiEndpoint::getStatusDescriptions(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_STATUS_DESCRIPTIONS, getStatusDescriptions());
	return true;
}

Array<String> UNIX_WiFiEndpoint::getStatusDescriptions() const
{
	Array<String> as;

	return as;

}

Boolean UNIX_WiFiEndpoint::getStatus(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_STATUS, getStatus());
	return true;
}

String UNIX_WiFiEndpoint::getStatus() const
{
	return String(DEFAULT_STATUS);
}

Boolean UNIX_WiFiEndpoint::getHealthState(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_HEALTH_STATE, getHealthState());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getHealthState() const
{
	return Uint16(DEFAULT_HEALTH_STATE);
}

Boolean UNIX_WiFiEndpoint::getCommunicationStatus(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_COMMUNICATION_STATUS, getCommunicationStatus());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getCommunicationStatus() const
{
	return Uint16(0);
}

Boolean UNIX_WiFiEndpoint::getDetailedStatus(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_DETAILED_STATUS, getDetailedStatus());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getDetailedStatus() const
{
	return Uint16(0);
}

Boolean UNIX_WiFiEndpoint::getOperatingStatus(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_OPERATING_STATUS, getOperatingStatus());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getOperatingStatus() const
{
	return Uint16(DEFAULT_OPERATING_STATUS);
}

Boolean UNIX_WiFiEndpoint::getPrimaryStatus(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_PRIMARY_STATUS, getPrimaryStatus());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getPrimaryStatus() const
{
	return Uint16(DEFAULT_PRIMARY_STATUS);
}

Boolean UNIX_WiFiEndpoint::getEnabledState(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_ENABLED_STATE, getEnabledState());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getEnabledState() const
{
	return Uint16(DEFAULT_ENABLED_STATE);
}

Boolean UNIX_WiFiEndpoint::getOtherEnabledState(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_OTHER_ENABLED_STATE, getOtherEnabledState());
	return true;
}

String UNIX_WiFiEndpoint::getOtherEnabledState() const
{
	return String ("");
}

Boolean UNIX_WiFiEndpoint::getRequestedState(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_REQUESTED_STATE, getRequestedState());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getRequestedState() const
{
	return Uint16(0);
}

Boolean UNIX_WiFiEndpoint::getEnabledDefault(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_ENABLED_DEFAULT, getEnabledDefault());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getEnabledDefault() const
{
	return Uint16(0);
}

Boolean UNIX_WiFiEndpoint::getTimeOfLastStateChange(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_TIME_OF_LAST_STATE_CHANGE, getTimeOfLastStateChange());
	return true;
}

CIMDateTime UNIX_WiFiEndpoint::getTimeOfLastStateChange() const
{
	struct tm* clock;			// create a time structure
	time_t val = time(NULL);
	clock = gmtime(&(val));	// Get the last modified time and put it into the time structure
	return CIMDateTime(
		clock->tm_year + 1900,
		clock->tm_mon + 1,
		clock->tm_mday,
		clock->tm_hour,
		clock->tm_min,
		clock->tm_sec,
		0,0,
		clock->tm_gmtoff);
}

Boolean UNIX_WiFiEndpoint::getAvailableRequestedStates(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_AVAILABLE_REQUESTED_STATES, getAvailableRequestedStates());
	return true;
}

Array<Uint16> UNIX_WiFiEndpoint::getAvailableRequestedStates() const
{
	Array<Uint16> as;

	return as;

}

Boolean UNIX_WiFiEndpoint::getTransitioningToState(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_TRANSITIONING_TO_STATE, getTransitioningToState());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getTransitioningToState() const
{
	return Uint16(0);
}

Boolean UNIX_WiFiEndpoint::getSystemCreationClassName(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_SYSTEM_CREATION_CLASS_NAME, getSystemCreationClassName());
	return true;
}

String UNIX_WiFiEndpoint::getSystemCreationClassName() const
{
	return String("UNIX_ComputerSystem");
}

Boolean UNIX_WiFiEndpoint::getSystemName(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_SYSTEM_NAME, getSystemName());
	return true;
}

String UNIX_WiFiEndpoint::getSystemName() const
{
	return CIMHelper::HostName;
}

Boolean UNIX_WiFiEndpoint::getCreationClassName(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_CREATION_CLASS_NAME, getCreationClassName());
	return true;
}

String UNIX_WiFiEndpoint::getCreationClassName() const
{
	return String("UNIX_WiFiEndpoint");
}

Boolean UNIX_WiFiEndpoint::getNameFormat(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_NAME_FORMAT, getNameFormat());
	return true;
}

String UNIX_WiFiEndpoint::getNameFormat() const
{
	return String ("");
}

Boolean UNIX_WiFiEndpoint::getProtocolType(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_PROTOCOL_TYPE, getProtocolType());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getProtocolType() const
{
	return Uint16(0);
}

Boolean UNIX_WiFiEndpoint::getProtocolIFType(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_PROTOCOL_I_F_TYPE, getProtocolIFType());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getProtocolIFType() const
{
	return Uint16(0);
}

Boolean UNIX_WiFiEndpoint::getOtherTypeDescription(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_OTHER_TYPE_DESCRIPTION, getOtherTypeDescription());
	return true;
}

String UNIX_WiFiEndpoint::getOtherTypeDescription() const
{
	return String ("");
}

Boolean UNIX_WiFiEndpoint::getLANID(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_L_A_N_ID, getLANID());
	return true;
}

String UNIX_WiFiEndpoint::getLANID() const
{
	return String ("");
}

Boolean UNIX_WiFiEndpoint::getLANType(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_L_A_N_TYPE, getLANType());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getLANType() const
{
	return Uint16(0);
}

Boolean UNIX_WiFiEndpoint::getOtherLANType(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_OTHER_L_A_N_TYPE, getOtherLANType());
	return true;
}

String UNIX_WiFiEndpoint::getOtherLANType() const
{
	return String ("");
}

Boolean UNIX_WiFiEndpoint::getMACAddress(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_M_A_C_ADDRESS, getMACAddress());
	return true;
}

String UNIX_WiFiEndpoint::getMACAddress() const
{
	return String ("");
}

Boolean UNIX_WiFiEndpoint::getAliasAddresses(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_ALIAS_ADDRESSES, getAliasAddresses());
	return true;
}

Array<String> UNIX_WiFiEndpoint::getAliasAddresses() const
{
	Array<String> as;

	return as;

}

Boolean UNIX_WiFiEndpoint::getGroupAddresses(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_GROUP_ADDRESSES, getGroupAddresses());
	return true;
}

Array<String> UNIX_WiFiEndpoint::getGroupAddresses() const
{
	Array<String> as;

	return as;

}

Boolean UNIX_WiFiEndpoint::getMaxDataSize(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_MAX_DATA_SIZE, getMaxDataSize());
	return true;
}

Uint32 UNIX_WiFiEndpoint::getMaxDataSize() const
{
	return Uint32(0);
}

Boolean UNIX_WiFiEndpoint::getEncryptionMethod(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_ENCRYPTION_METHOD, getEncryptionMethod());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getEncryptionMethod() const
{
	return Uint16(0);
}

Boolean UNIX_WiFiEndpoint::getOtherEncryptionMethod(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_OTHER_ENCRYPTION_METHOD, getOtherEncryptionMethod());
	return true;
}

String UNIX_WiFiEndpoint::getOtherEncryptionMethod() const
{
	return String ("");
}

Boolean UNIX_WiFiEndpoint::getAuthenticationMethod(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_AUTHENTICATION_METHOD, getAuthenticationMethod());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getAuthenticationMethod() const
{
	return Uint16(0);
}

Boolean UNIX_WiFiEndpoint::getOtherAuthenticationMethod(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_OTHER_AUTHENTICATION_METHOD, getOtherAuthenticationMethod());
	return true;
}

String UNIX_WiFiEndpoint::getOtherAuthenticationMethod() const
{
	return String ("");
}

Boolean UNIX_WiFiEndpoint::getIEEE8021xAuthenticationProtocol(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_I_E_E_E_8_0_2_1X_AUTHENTICATION_PROTOCOL, getIEEE8021xAuthenticationProtocol());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getIEEE8021xAuthenticationProtocol() const
{
	return Uint16(0);
}

Boolean UNIX_WiFiEndpoint::getAccessPointAddress(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_ACCESS_POINT_ADDRESS, getAccessPointAddress());
	return true;
}

String UNIX_WiFiEndpoint::getAccessPointAddress() const
{
	return String ("");
}

Boolean UNIX_WiFiEndpoint::getBSSType(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_B_S_S_TYPE, getBSSType());
	return true;
}

Uint16 UNIX_WiFiEndpoint::getBSSType() const
{
	return Uint16(0);
}

Boolean UNIX_WiFiEndpoint::getAssociated(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_ASSOCIATED, getAssociated());
	return true;
}

Boolean UNIX_WiFiEndpoint::getAssociated() const
{
	return Boolean(false);
}

Boolean UNIX_WiFiEndpoint::initialize()
{
	return false;
}

Boolean UNIX_WiFiEndpoint::load(int &pIndex)
{
	return false;
}

Boolean UNIX_WiFiEndpoint::finalize()
{
	return false;
}

Boolean UNIX_WiFiEndpoint::find(Array<CIMKeyBinding> &kbArray)
{
	CIMKeyBinding kb;
	String systemCreationClassNameKey;
	String systemNameKey;
	String creationClassNameKey;
	String nameKey;

	for(Uint32 i = 0; i < kbArray.size(); i++)
	{
		kb = kbArray[i];
		CIMName keyName = kb.getName();
		if (keyName.equal(PROPERTY_SYSTEM_CREATION_CLASS_NAME)) systemCreationClassNameKey = kb.getValue();
		else if (keyName.equal(PROPERTY_SYSTEM_NAME)) systemNameKey = kb.getValue();
		else if (keyName.equal(PROPERTY_CREATION_CLASS_NAME)) creationClassNameKey = kb.getValue();
		else if (keyName.equal(PROPERTY_NAME)) nameKey = kb.getValue();
	}

/* EXecute find with extracted keys */

	return false;
}


text:
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM;
using TTC2017.SmartGrids.CIM.IEC61970.ControlArea;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.MarketOperations;
using TTC2017.SmartGrids.CIM.IEC61970.Wires;

namespace TTC2017.SmartGrids.CIM.IEC61970.LoadModel
{

    /// <summary>
    /// The default implementation of the ConformLoadSchedule class
    /// </summary>
    [XmlNamespaceAttribute("http://iec.ch/TC57/2009/CIM-schema-cim14#LoadModel")]
    [XmlNamespacePrefixAttribute("cimLoadModel")]
    [ModelRepresentationClassAttribute("http://iec.ch/TC57/2009/CIM-schema-cim14#//IEC61970/LoadModel/ConformLoadSchedule" +
        "")]
    [DebuggerDisplayAttribute("ConformLoadSchedule {UUID}")]
    public partial class ConformLoadSchedule : SeasonDayTypeSchedule, IConformLoadSchedule, IModelElement
    {

        private static Lazy<ITypedElement> _conformLoadGroupReference = new Lazy<ITypedElement>(RetrieveConformLoadGroupReference);

        /// <summary>
        /// The backing field for the ConformLoadGroup property
        /// </summary>
        private IConformLoadGroup _conformLoadGroup;

        private static IClass _classInstance;

        /// <summary>
        /// The ConformLoadGroup property
        /// </summary>
        [XmlAttributeAttribute(true)]
        [XmlOppositeAttribute("ConformLoadSchedules")]
        public virtual IConformLoadGroup ConformLoadGroup
        {
            get
            {
                return this._conformLoadGroup;
            }
            set
            {
                if ((this._conformLoadGroup != value))
                {
                    IConformLoadGroup old = this._conformLoadGroup;
                    ValueChangedEventArgs e = new ValueChangedEventArgs(old, value);
                    this.OnConformLoadGroupChanging(e);
                    this.OnPropertyChanging("ConformLoadGroup", e, _conformLoadGroupReference);
                    this._conformLoadGroup = value;
                    if ((old != null))
                    {
                        old.ConformLoadSchedules.Remove(this);
                        old.Deleted -= this.OnResetConformLoadGroup;
                    }
                    if ((value != null))
                    {
                        value.ConformLoadSchedules.Add(this);
                        value.Deleted += this.OnResetConformLoadGroup;
                    }
                    this.OnConformLoadGroupChanged(e);
                    this.OnPropertyChanged("ConformLoadGroup", e, _conformLoadGroupReference);
                }
            }
        }

        /// <summary>
        /// Gets the referenced model elements of this model element
        /// </summary>
        public override IEnumerableExpression<IModelElement> ReferencedElements
        {
            get
            {
                return base.ReferencedElements.Concat(new ConformLoadScheduleReferencedElementsCollection(this));
            }
        }

        /// <summary>
        /// Gets the Class model for this type
        /// </summary>
        public new static IClass ClassInstance
        {
            get
            {
                if ((_classInstance == null))
                {
                    _classInstance = ((IClass)(MetaRepository.Instance.Resolve("http://iec.ch/TC57/2009/CIM-schema-cim14#//IEC61970/LoadModel/ConformLoadSchedule" +
                            "")));
                }
                return _classInstance;
            }
        }

        /// <summary>
        /// Gets fired before the ConformLoadGroup property changes its value
        /// </summary>
        public event System.EventHandler<ValueChangedEventArgs> ConformLoadGroupChanging;

        /// <summary>
        /// Gets fired when the ConformLoadGroup property changed its value
        /// </summary>
        public event System.EventHandler<ValueChangedEventArgs> ConformLoadGroupChanged;

        private static ITypedElement RetrieveConformLoadGroupReference()
        {
            return ((ITypedElement)(((ModelElement)(ConformLoadSchedule.ClassInstance)).Resolve("ConformLoadGroup")));
        }

        /// <summary>
        /// Raises the ConformLoadGroupChanging event
        /// </summary>
        /// <param name="eventArgs">The event data</param>
        protected virtual void OnConformLoadGroupChanging(ValueChangedEventArgs eventArgs)
        {
            System.EventHandler<ValueChangedEventArgs> handler = this.ConformLoadGroupChanging;
            if ((handler != null))
            {
                handler.Invoke(this, eventArgs);
            }
        }

        /// <summary>
        /// Raises the ConformLoadGroupChanged event
        /// </summary>
        /// <param name="eventArgs">The event data</param>
        protected virtual void OnConformLoadGroupChanged(ValueChangedEventArgs eventArgs)
        {
            System.EventHandler<ValueChangedEventArgs> handler = this.ConformLoadGroupChanged;
            if ((handler != null))
            {
                handler.Invoke(this, eventArgs);
            }
        }

        /// <summary>
        /// Handles the event that the ConformLoadGroup property must reset
        /// </summary>
        /// <param name="sender">The object that sent this reset request</param>
        /// <param name="eventArgs">The event data for the reset event</param>
        private void OnResetConformLoadGroup(object sender, System.EventArgs eventArgs)
        {
            this.ConformLoadGroup = null;
        }

        /// <summary>
        /// Sets a value to the given feature
        /// </summary>
        /// <param name="feature">The requested feature</param>
        /// <param name="value">The value that should be set to that feature</param>
        protected override void SetFeature(string feature, object value)
        {
            if ((feature == "CONFORMLOADGROUP"))
            {
                this.ConformLoadGroup = ((IConformLoadGroup)(value));
                return;
            }
            base.SetFeature(feature, value);
        }

        /// <summary>
        /// Gets the property expression for the given attribute
        /// </summary>
        /// <returns>An incremental property expression</returns>
        /// <param name="attribute">The requested attribute in upper case</param>
        protected override NMF.Expressions.INotifyExpression<object> GetExpressionForAttribute(string attribute)
        {
            if ((attribute == "ConformLoadGroup"))
            {
                return new ConformLoadGroupProxy(this);
            }
            return base.GetExpressionForAttribute(attribute);
        }

        /// <summary>
        /// Gets the property expression for the given reference
        /// </summary>
        /// <returns>An incremental property expression</returns>
        /// <param name="reference">The requested reference in upper case</param>
        protected override NMF.Expressions.INotifyExpression<NMF.Models.IModelElement> GetExpressionForReference(string reference)
        {
            if ((reference == "ConformLoadGroup"))
            {
                return new ConformLoadGroupProxy(this);
            }
            return base.GetExpressionForReference(reference);
        }

        /// <summary>
        /// Gets the Class for this model element
        /// </summary>
        public override IClass GetClass()
        {
            if ((_classInstance == null))
            {
                _classInstance = ((IClass)(MetaRepository.Instance.Resolve("http://iec.ch/TC57/2009/CIM-schema-cim14#//IEC61970/LoadModel/ConformLoadSchedule" +
                        "")));
            }
            return _classInstance;
        }

        /// <summary>
        /// The collection class to to represent the children of the ConformLoadSchedule class
        /// </summary>
        public class ConformLoadScheduleReferencedElementsCollection : ReferenceCollection, ICollectionExpression<IModelElement>, ICollection<IModelElement>
        {

            private ConformLoadSchedule _parent;

            /// <summary>
            /// Creates a new instance
            /// </summary>
            public ConformLoadScheduleReferencedElementsCollection(ConformLoadSchedule parent)
            {
                this._parent = parent;
            }

            /// <summary>
            /// Gets the amount of elements contained in this collection
            /// </summary>
            public override int Count
            {
                get
                {
                    int count = 0;
                    if ((this._parent.ConformLoadGroup != null))
                    {
                        count = (count + 1);
                    }
                    return count;
                }
            }

            protected override void AttachCore()
            {
                this._parent.ConformLoadGroupChanged += this.PropagateValueChanges;
            }

            protected override void DetachCore()
            {
                this._parent.ConformLoadGroupChanged -= this.PropagateValueChanges;
            }

            /// <summary>
            /// Adds the given element to the collection
            /// </summary>
            /// <param name="item">The item to add</param>
            public override void Add(IModelElement item)
            {
                if ((this._parent.ConformLoadGroup == null))
                {
                    IConformLoadGroup conformLoadGroupCasted = item.As<IConformLoadGroup>();
                    if ((conformLoadGroupCasted != null))
                    {
                        this._parent.ConformLoadGroup = conformLoadGroupCasted;
                        return;
                    }
                }
            }

            /// <summary>
            /// Clears the collection and resets all references that implement it.
            /// </summary>
            public override void Clear()
            {
                this._parent.ConformLoadGroup = null;
            }

            /// <summary>
            /// Gets a value indicating whether the given element is contained in the collection
            /// </summary>
            /// <returns>True, if it is contained, otherwise False</returns>
            /// <param name="item">The item that should be looked out for</param>
            public override bool Contains(IModelElement item)
            {
                if ((item == this._parent.ConformLoadGroup))
                {
                    return true;
                }
                return false;
            }

            /// <summary>
            /// Copies the contents of the collection to the given array starting from the given array index
            /// </summary>
            /// <param name="array">The array in which the elements should be copied</param>
            /// <param name="arrayIndex">The starting index</param>
            public override void CopyTo(IModelElement[] array, int arrayIndex)
            {
                if ((this._parent.ConformLoadGroup != null))
                {
                    array[arrayIndex] = this._parent.ConformLoadGroup;
                    arrayIndex = (arrayIndex + 1);
                }
            }

            /// <summary>
            /// Removes the given item from the collection
            /// </summary>
            /// <returns>True, if the item was removed, otherwise False</returns>
            /// <param name="item">The item that should be removed</param>
            public override bool Remove(IModelElement item)
            {
                if ((this._parent.ConformLoadGroup == item))
                {
                    this._parent.ConformLoadGroup = null;
                    return true;
                }
                return false;
            }

            /// <summary>
            /// Gets an enumerator that enumerates the collection
            /// </summary>
            /// <returns>A generic enumerator</returns>
            public override IEnumerator<IModelElement> GetEnumerator()
            {
                return Enumerable.Empty<IModelElement>().Concat(this._parent.ConformLoadGroup).GetEnumerator();
            }
        }

        /// <summary>
        /// Represents a proxy to represent an incremental access to the ConformLoadGroup property
        /// </summary>
        private sealed class ConformLoadGroupProxy : ModelPropertyChange<IConformLoadSchedule, IConformLoadGroup>
        {

            /// <summary>
            /// Creates a new observable property access proxy
            /// </summary>
            /// <param name="modelElement">The model instance element for which to create the property access proxy</param>
            public ConformLoadGroupProxy(IConformLoadSchedule modelElement) :
                    base(modelElement, "ConformLoadGroup")
            {
            }

            /// <summary>
            /// Gets or sets the value of this expression
            /// </summary>
            public override IConformLoadGroup Value
            {
                get
                {
                    return this.ModelElement.ConformLoadGroup;
                }
                set
                {
                    this.ModelElement.ConformLoadGroup = value;
                }
            }
        }
    }
}


text:
Test that you can't set a prefix for a node with null namespace.

Should say PASS: