text:
using vespalib::make_string_short::fmt;

namespace vespalib::eval {

VESPA_IMPLEMENT_EXCEPTION(DecodeValueException, Exception);

namespace {

constexpr uint32_t DOUBLE_CELL_TYPE = 0;
constexpr uint32_t FLOAT_CELL_TYPE = 1;
constexpr uint32_t BFLOAT16_CELL_TYPE = 2;
constexpr uint32_t INT8_CELL_TYPE = 3;

inline uint32_t cell_type_to_id(CellType cell_type) {
    switch (cell_type) {
    case CellType::DOUBLE: return DOUBLE_CELL_TYPE;
    case CellType::FLOAT: return FLOAT_CELL_TYPE;
    case CellType::BFLOAT16: return BFLOAT16_CELL_TYPE;
    case CellType::INT8: return INT8_CELL_TYPE;
    }
    throw IllegalArgumentException(fmt("Unknown CellType=%u", (uint32_t)cell_type));
}

inline CellType id_to_cell_type(uint32_t id) {
    switch (id) {
    case DOUBLE_CELL_TYPE: return CellType::DOUBLE;
    case FLOAT_CELL_TYPE: return CellType::FLOAT;
    case BFLOAT16_CELL_TYPE: return CellType::BFLOAT16;
    case INT8_CELL_TYPE: return CellType::INT8;
    }
    throw IllegalArgumentException(fmt("Unknown CellType id=%u", id));
}

struct Format {
    bool     has_sparse;
    bool     has_dense;
    bool     with_cell_type;
    uint32_t tag;
    explicit Format(const ValueType &type)
        : has_sparse(type.count_mapped_dimensions() > 0),
          has_dense((type.count_indexed_dimensions() > 0) || !has_sparse),
          with_cell_type(type.cell_type() != CellType::DOUBLE),
          tag((has_sparse ? 0x1 : 0) | (has_dense ? 0x2 : 0) | (with_cell_type ? 0x4 : 0)) {}
    explicit Format(uint32_t tag_in)
        : has_sparse((tag_in & 0x1) != 0),
          has_dense((tag_in & 0x2) != 0),
          with_cell_type((tag_in & 0x4) != 0),
          tag(tag_in)
    {
        if (tag & ~7u) {
            throw IllegalArgumentException(fmt("Unknown tensor format tag=%u", tag));
        }
    }
    ~Format() {}
};

void maybe_encode_cell_type(nbostream &output, const Format &format, CellType cell_type) {
    if (format.with_cell_type) {
        output.putInt1_4Bytes(cell_type_to_id(cell_type));
    }
}

void encode_type(nbostream &output, const Format &format, const ValueType &type) {
    maybe_encode_cell_type(output, format, type.cell_type());
    if (format.has_sparse) {
        output.putInt1_4Bytes(type.count_mapped_dimensions());
        for (const auto & dim : type.dimensions()) {
            if (dim.is_mapped()) {
                output.writeSmallString(dim.name);
            }
        }
    }
    if (format.has_dense) {
        output.putInt1_4Bytes(type.count_indexed_dimensions());
        for (const auto & dim : type.dimensions()) {
            if (dim.is_indexed()) {
                output.writeSmallString(dim.name);
                output.putInt1_4Bytes(dim.size);
            }
        }
    }
}

void maybe_encode_num_blocks(nbostream &output, bool has_mapped_dims, size_t num_blocks) {
    if (has_mapped_dims) {
        output.putInt1_4Bytes(num_blocks);
    }
}

CellType maybe_decode_cell_type(nbostream &input, const Format &format) {
    if (format.with_cell_type) {
        return id_to_cell_type(input.getInt1_4Bytes());
    }
    return CellType::DOUBLE;
}

ValueType decode_type(nbostream &input, const Format &format) {
    CellType cell_type = maybe_decode_cell_type(input, format);
    std::vector<ValueType::Dimension> dim_list;
    if (format.has_sparse) {
        size_t cnt = input.getInt1_4Bytes();
        for (size_t i = 0; i < cnt; ++i) {
            vespalib::string name;
            input.readSmallString(name);
            dim_list.emplace_back(name);
        }
    }
    if (format.has_dense) {
        size_t cnt = input.getInt1_4Bytes();
        for (size_t i = 0; i < cnt; ++i) {
            vespalib::string name;
            input.readSmallString(name);
            dim_list.emplace_back(name, input.getInt1_4Bytes());
        }
    }
    auto result = ValueType::make_type(cell_type, std::move(dim_list));
    if (result.is_error()) {
        throw IllegalArgumentException(fmt("Invalid type (with %zu dimensions and cell type %u)",
                                           dim_list.size(), (uint32_t)cell_type));
    }
    return result;
}

size_t maybe_decode_num_blocks(nbostream &input, bool has_mapped_dims, const Format &format) {
    if (has_mapped_dims || !format.has_dense) {
        return input.getInt1_4Bytes();
    }
    return 1;
}

void encode_mapped_labels(nbostream &output, size_t num_mapped_dims, const SmallVector<string_id> &addr) {
    for (size_t i = 0; i < num_mapped_dims; ++i) {
        vespalib::string str = SharedStringRepo::Handle::string_from_id(addr[i]);
        output.writeSmallString(str);
    }
}

void decode_mapped_labels(nbostream &input, size_t num_mapped_dims, SmallVector<vespalib::stringref> &addr) {
    for (size_t i = 0; i < num_mapped_dims; ++i) {
        size_t strSize = input.getInt1_4Bytes();
        addr[i] = vespalib::stringref(input.peek(), strSize);
        input.adjustReadPos(strSize);
    }
}

template<typename T>
void decode_cells(nbostream &input, size_t num_cells, ArrayRef<T> dst)
{
    assert(num_cells == dst.size());
    for (size_t i = 0; i < num_cells; ++i) {
        dst[i] = input.readValue<T>();
    }
}

struct DecodeState {
    const ValueType &type;
    const size_t subspace_size;
    const size_t num_blocks;
    const size_t num_mapped_dims;
};

struct ContentDecoder {
    template<typename T>
    static std::unique_ptr<Value> invoke(nbostream &input, const DecodeState &state, const ValueBuilderFactory &factory) {
        SmallVector<vespalib::stringref> address(state.num_mapped_dims);
        if (state.num_blocks * state.subspace_size * sizeof(T) > input.size()) {
            auto err = fmt("serialized input claims %zu blocks of size %zu*%zu, but only %zu bytes available",
                           state.num_blocks, state.subspace_size, sizeof(T), input.size());
            throw IllegalStateException(err);
        }
        auto builder = factory.create_value_builder<T>(state.type, state.num_mapped_dims, state.subspace_size, state.num_blocks);
        for (size_t i = 0; i < state.num_blocks; ++i) {
            decode_mapped_labels(input, state.num_mapped_dims, address);
            auto block_cells = builder->add_subspace(address);
            decode_cells(input, state.subspace_size, block_cells);
        }
        // add implicit empty subspace
        if ((state.num_mapped_dims == 0) && (state.num_blocks == 0)) {
            for (T &cell: builder->add_subspace()) {
                cell = T{};
            }
        }
        return builder->build(std::move(builder));
    }
};

struct CreateValueFromTensorSpec {
    template <typename T> static std::unique_ptr<Value> invoke(const ValueType &type, const TensorSpec &spec, const ValueBuilderFactory &factory) {
        size_t dense_size = type.dense_subspace_size();
        ArrayArrayMap<vespalib::stringref,T> map(type.count_mapped_dimensions(), dense_size,
                                                 std::max(spec.cells().size() / dense_size, size_t(1)));
        SmallVector<vespalib::stringref> sparse_key;
        for (const auto &entry: spec.cells()) {
            sparse_key.clear();
            size_t dense_key = 0;
            auto dim = type.dimensions().begin();
            auto binding = entry.first.begin();
            for (; dim != type.dimensions().end(); ++dim, ++binding) {
                assert(binding != entry.first.end());
                assert(dim->name == binding->first);
                assert(dim->is_mapped() == binding->second.is_mapped());
                if (dim->is_mapped()) {
                    sparse_key.push_back(binding->second.name);
                } else {
                    assert(binding->second.index < dim->size);
                    dense_key = (dense_key * dim->size) + binding->second.index;
                }
            }
            assert(binding == entry.first.end());
            assert(dense_key < map.values_per_entry());
            auto [tag, ignore] = map.lookup_or_add_entry(ConstArrayRef<vespalib::stringref>(sparse_key));
            map.get_values(tag)[dense_key] = entry.second;
        }
        // if spec is missing the required dense space, add it here:
        if ((map.keys_per_entry() == 0) && (map.size() == 0)) {
            map.add_entry(ConstArrayRef<vespalib::stringref>());
        }
        auto builder = factory.create_value_builder<T>(type, map.keys_per_entry(), map.values_per_entry(), map.size());
        map.each_entry([&](const auto &keys, const auto &values)
                       {
                           memcpy(builder->add_subspace(keys).begin(), values.begin(), values.size() * sizeof(T));
                       });
        return builder->build(std::move(builder));
    }
};

struct CreateTensorSpecFromValue {
    template <typename T> static TensorSpec invoke(const Value &value) {
        auto cells = value.cells().typify<T>();
        TensorSpec spec(value.type().to_spec());
        size_t subspace_id = 0;
        size_t subspace_size = value.type().dense_subspace_size();
        SmallVector<string_id> labels(value.type().count_mapped_dimensions());
        SmallVector<string_id*> label_refs;
        for (auto &label: labels) {
            label_refs.push_back(&label);
        }
        auto view = value.index().create_view({});
        view->lookup({});
        while (view->next_result(label_refs, subspace_id)) {
            size_t label_idx = 0;
            TensorSpec::Address addr;
            for (const auto &dim: value.type().dimensions()) {
                if (dim.is_mapped()) {
                    addr.emplace(dim.name, SharedStringRepo::Handle::string_from_id(labels[label_idx++]));
                }
            }
            for (size_t i = 0; i < subspace_size; ++i) {
                size_t dense_key = i;
                for (auto dim = value.type().dimensions().rbegin();
                     dim != value.type().dimensions().rend(); ++dim)
                {
                    if (dim->is_indexed()) {
                        size_t label = dense_key % dim->size;
                        addr.emplace(dim->name, label).first->second = TensorSpec::Label(label);
                        dense_key /= dim->size;
                    }
                }
                spec.add(addr, cells[(subspace_size * subspace_id) + i]);
            }
        }
        return spec;
    }
};

struct EncodeState {
    size_t num_mapped_dims;
    size_t subspace_size;
};

struct ContentEncoder {
    template<typename T>
    static void invoke(const Value &value, const EncodeState &state, nbostream &output) {
        SmallVector<string_id> address(state.num_mapped_dims);
        SmallVector<string_id*> a_refs(state.num_mapped_dims);;
        for (size_t i = 0; i < state.num_mapped_dims; ++i) {
            a_refs[i] = &address[i];
        }
        auto view = value.index().create_view({});
        view->lookup({});
        size_t subspace;
        while (view->next_result(a_refs, subspace)) {
            encode_mapped_labels(output, state.num_mapped_dims, address);
            auto iter = value.cells().typify<T>().begin();
            iter += (subspace * state.subspace_size);
            for (size_t i = 0; i < state.subspace_size; ++i) {
                output << *iter++;
            }
        }
    }
};

} // namespace <unnamed>

void encode_value(const Value &value, nbostream &output) {
    size_t num_mapped_dims = value.type().count_mapped_dimensions();
    size_t dense_subspace_size = value.type().dense_subspace_size();
    Format format(value.type());
    output.putInt1_4Bytes(format.tag);
    encode_type(output, format, value.type());
    maybe_encode_num_blocks(output, (num_mapped_dims > 0), value.cells().size / dense_subspace_size);
    EncodeState state{num_mapped_dims, dense_subspace_size};
    typify_invoke<1,TypifyCellType,ContentEncoder>(value.type().cell_type(), value, state, output);
}

std::unique_ptr<Value> decode_value(nbostream &input, const ValueBuilderFactory &factory) {
    try {
        Format format(input.getInt1_4Bytes());
        ValueType type = decode_type(input, format);
        size_t num_mapped_dims = type.count_mapped_dimensions();
        size_t dense_subspace_size = type.dense_subspace_size();
        const size_t num_blocks = maybe_decode_num_blocks(input, (num_mapped_dims > 0), format);
        DecodeState state{type, dense_subspace_size, num_blocks, num_mapped_dims};
        return typify_invoke<1,TypifyCellType,ContentDecoder>(type.cell_type(), input, state, factory);
    } catch (const Exception &e) {
        rethrow_if_unsafe(e);
        throw DecodeValueException("failed to decode value", e);
    }
}

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

std::unique_ptr<Value> value_from_spec(const TensorSpec &spec, const ValueBuilderFactory &factory) {
    ValueType type = ValueType::from_spec(spec.type());
    assert(!type.is_error());
    return typify_invoke<1,TypifyCellType,CreateValueFromTensorSpec>(type.cell_type(), type, spec, factory);
}

TensorSpec spec_from_value(const Value &value) {
    return typify_invoke<1,TypifyCellType,CreateTensorSpecFromValue>(value.type().cell_type(), value);
}

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

} // namespace


text:
namespace System.Data.Services.Client
{
    #region Namespaces.

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Reflection;
    using System.Xml;
    using System.Xml.Linq;
    using System.Text;

    #endregion Namespaces.

    [DebuggerDisplay("AtomParser {kind} {reader}")]
    internal class AtomParser
    {
        #region Private fields.

        private readonly Func<XmlReader, KeyValuePair<XmlReader, object>> entryCallback;

        private readonly Stack<XmlReader> readers;

        private readonly string typeScheme;

        private AtomEntry entry;

        private AtomFeed feed;

        private AtomDataKind kind;

        private XmlReader reader;

        private string currentDataNamespace;

        #endregion Private fields.

        #region Constructors.

        internal AtomParser(XmlReader reader, Func<XmlReader, KeyValuePair<XmlReader, object>> entryCallback, string typeScheme, string currentDataNamespace)
        {
            Debug.Assert(reader != null, "reader != null");
            Debug.Assert(typeScheme != null, "typeScheme != null");
            Debug.Assert(entryCallback != null, "entryCallback != null");
            Debug.Assert(!String.IsNullOrEmpty(currentDataNamespace), "currentDataNamespace is empty or null");

            this.reader = reader;
            this.readers = new Stack<XmlReader>();
            this.entryCallback = entryCallback;
            this.typeScheme = typeScheme;
            this.currentDataNamespace = currentDataNamespace;

            Debug.Assert(this.kind == AtomDataKind.None, "this.kind == AtomDataKind.None -- otherwise not initialized correctly");
        }

        #endregion Constructors.

        #region Internal properties.

        internal AtomEntry CurrentEntry
        {
            get
            {
                return this.entry;
            }
        }

        internal AtomFeed CurrentFeed
        {
            get
            {
                return this.feed;
            }
        }

        internal AtomDataKind DataKind
        {
            get
            {
                return this.kind;
            }
        }

        internal bool IsDataWebElement
        {
            get { return this.reader.NamespaceURI == this.currentDataNamespace; }
        }

        #endregion Internal properties.

        #region Internal methods.

        internal static KeyValuePair<XmlReader, object> XElementBuilderCallback(XmlReader reader)
        {
            Debug.Assert(reader != null, "reader != null");
            Debug.Assert(reader is Xml.XmlWrappingReader, "reader must be a instance of XmlWrappingReader");

            string readerBaseUri = reader.BaseURI;
            XElement element = XElement.Load(reader.ReadSubtree(), LoadOptions.None);
            return new KeyValuePair<XmlReader, object>(Xml.XmlWrappingReader.CreateReader(readerBaseUri, element.CreateReader()), element);
        }

        #endregion Internal methods.

        #region Internal methods.

        internal bool Read()
        {
            if (this.DataKind == AtomDataKind.Finished)
            {
                return false;
            }

            while (this.reader.Read())
            {
                if (ShouldIgnoreNode(this.reader))
                {
                    continue;
                }

                Debug.Assert(
                    this.reader.NodeType == XmlNodeType.Element || this.reader.NodeType == XmlNodeType.EndElement,
                    "this.reader.NodeType == XmlNodeType.Element || this.reader.NodeType == XmlNodeType.EndElement -- otherwise we should have ignored or thrown");

                AtomDataKind readerData = ParseStateForReader(this.reader);

                if (this.reader.NodeType == XmlNodeType.EndElement)
                {
                    break;
                }

                switch (readerData)
                {
                    case AtomDataKind.Custom:
                        if (this.DataKind == AtomDataKind.None)
                        {
                            this.kind = AtomDataKind.Custom;
                            return true;
                        }
                        else
                        {
                            MaterializeAtom.SkipToEnd(this.reader);
                            continue;
                        }

                    case AtomDataKind.Entry:
                        this.kind = AtomDataKind.Entry;
                        this.ParseCurrentEntry(out this.entry);
                        return true;

                    case AtomDataKind.Feed:
                        if (this.DataKind == AtomDataKind.None)
                        {
                            this.feed = new AtomFeed();
                            this.kind = AtomDataKind.Feed;
                            return true;
                        }

                        throw new InvalidOperationException(Strings.AtomParser_FeedUnexpected);

                    case AtomDataKind.FeedCount:
                        this.ParseCurrentFeedCount();
                        break;

                    case AtomDataKind.PagingLinks:
                        if (this.feed == null)
                        {
                            throw new InvalidOperationException(Strings.AtomParser_PagingLinkOutsideOfFeed);
                        }

                        this.kind = AtomDataKind.PagingLinks;
                        this.ParseCurrentFeedPagingLinks();
                        return true;

                    default:
                        Debug.Assert(false, "Atom Parser is in a wrong state...Did you add a new AtomDataKind?");
                        break;
                }
            }

            this.kind = AtomDataKind.Finished;
            this.entry = null;
            return false;
        }

        internal AtomContentProperty ReadCurrentPropertyValue()
        {
            Debug.Assert(
                this.kind == AtomDataKind.Custom,
                "this.kind == AtomDataKind.Custom -- otherwise caller shouldn't invoke ReadCurrentPropertyValue");
            return this.ReadPropertyValue();
        }

        internal string ReadCustomElementString()
        {
            Debug.Assert(
                this.kind == AtomDataKind.Custom,
                "this.kind == AtomDataKind.Custom -- otherwise caller shouldn't invoke ReadCustomElementString");
            return MaterializeAtom.ReadElementString(this.reader, true);
        }

        internal void ReplaceReader(XmlReader newReader)
        {
            Debug.Assert(newReader != null, "newReader != null");
            this.reader = newReader;
        }

        #endregion Internal methods.

        #region Private methods.

        private static AtomDataKind ParseStateForReader(XmlReader reader)
        {
            Debug.Assert(reader != null, "reader != null");
            Debug.Assert(
                reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.EndElement,
                "reader.NodeType == XmlNodeType.Element || EndElement -- otherwise can't determine");

            AtomDataKind result = AtomDataKind.Custom;
            string elementName = reader.LocalName;
            string namespaceURI = reader.NamespaceURI;
            if (Util.AreSame(XmlConstants.AtomNamespace, namespaceURI))
            {
                if (Util.AreSame(XmlConstants.AtomEntryElementName, elementName))
                {
                    result = AtomDataKind.Entry;
                }
                else if (Util.AreSame(XmlConstants.AtomFeedElementName, elementName))
                {
                    result = AtomDataKind.Feed;
                }
                else if (Util.AreSame(XmlConstants.AtomLinkElementName, elementName) &&
                    Util.AreSame(XmlConstants.AtomLinkNextAttributeString, reader.GetAttribute(XmlConstants.AtomLinkRelationAttributeName)))
                {
                    result = AtomDataKind.PagingLinks;
                }
            }
            else if (Util.AreSame(XmlConstants.DataWebMetadataNamespace, namespaceURI))
            {
                if (Util.AreSame(XmlConstants.RowCountElement, elementName))
                {
                    result = AtomDataKind.FeedCount;
                }
            }

            return result;
        }

        private static bool ReadChildElement(XmlReader reader, string localName, string namespaceUri)
        {
            Debug.Assert(localName != null, "localName != null");
            Debug.Assert(namespaceUri != null, "namespaceUri != null");
            Debug.Assert(!reader.IsEmptyElement, "!reader.IsEmptyElement");
            Debug.Assert(reader.NodeType != XmlNodeType.EndElement, "reader.NodeType != XmlNodeType.EndElement");

            return reader.Read() && reader.IsStartElement(localName, namespaceUri);
        }

        private static void SkipToEndAtDepth(XmlReader reader, int depth)
        {
            Debug.Assert(reader != null, "reader != null");
            Debug.Assert(reader.Depth >= depth, "reader.Depth >= depth");

            while (!(reader.Depth == depth &&
                     (reader.NodeType == XmlNodeType.EndElement ||
                      (reader.NodeType == XmlNodeType.Element && reader.IsEmptyElement))))
            {
                reader.Read();
            }
        }

        private static string ReadElementStringForText(XmlReader reader)
        {
            Debug.Assert(reader != null, "reader != null");
            if (reader.IsEmptyElement)
            {
                return String.Empty;
            }

            StringBuilder result = new StringBuilder();
            int depth = reader.Depth;
            while (reader.Read())
            {
                if (reader.Depth == depth)
                {
                    Debug.Assert(
                        reader.NodeType == XmlNodeType.EndElement,
                        "reader.NodeType == XmlNodeType.EndElement -- otherwise XmlReader is acting odd");
                    break;
                }

                if (reader.NodeType == XmlNodeType.SignificantWhitespace ||
                    reader.NodeType == XmlNodeType.Text)
                {
                    result.Append(reader.Value);
                }
            }

            return result.ToString();
        }

        private static bool ShouldIgnoreNode(XmlReader reader)
        {
            Debug.Assert(reader != null, "reader != null");

            switch (reader.NodeType)
            {
                case XmlNodeType.CDATA:
                case XmlNodeType.EntityReference:
                case XmlNodeType.EndEntity:
                    Error.ThrowInternalError(InternalError.UnexpectedXmlNodeTypeWhenReading);
                    break;
                case XmlNodeType.Text:
                case XmlNodeType.SignificantWhitespace:
                    Error.ThrowInternalError(InternalError.UnexpectedXmlNodeTypeWhenReading);
                    break;
                case XmlNodeType.Element:
                case XmlNodeType.EndElement:
                    return false;
                default:
                    break;
            }

            return true;
        }

        private static bool IsAllowedContentType(string contentType)
        {
            return (String.Equals(XmlConstants.MimeApplicationXml, contentType, StringComparison.OrdinalIgnoreCase) ||
                    String.Equals(XmlConstants.MimeApplicationAtom, contentType, StringComparison.OrdinalIgnoreCase));
        }

        private static bool IsAllowedLinkType(string linkType, out bool isFeed)
        {
            isFeed = String.Equals(XmlConstants.LinkMimeTypeFeed, linkType, StringComparison.OrdinalIgnoreCase);
            return isFeed ? true : String.Equals(XmlConstants.LinkMimeTypeEntry, linkType, StringComparison.OrdinalIgnoreCase);
        }

        private void ParseCurrentContent(AtomEntry targetEntry)
        {
            Debug.Assert(targetEntry != null, "targetEntry != null");
            Debug.Assert(this.reader.NodeType == XmlNodeType.Element, "this.reader.NodeType == XmlNodeType.Element");

            string propertyValue = this.reader.GetAttributeEx(XmlConstants.AtomContentSrcAttributeName, XmlConstants.AtomNamespace);
            if (propertyValue != null)
            {
                if (!this.reader.IsEmptyElement)
                {
                    throw Error.InvalidOperation(Strings.Deserialize_ExpectedEmptyMediaLinkEntryContent);
                }

                targetEntry.MediaLinkEntry = true;
                targetEntry.MediaContentUri = new Uri(propertyValue, UriKind.RelativeOrAbsolute);
            }
            else
            {
                if (targetEntry.MediaLinkEntry.HasValue && targetEntry.MediaLinkEntry.Value)
                {
                    throw Error.InvalidOperation(Strings.Deserialize_ContentPlusPropertiesNotAllowed);
                }

                targetEntry.MediaLinkEntry = false;

                propertyValue = this.reader.GetAttributeEx(XmlConstants.AtomTypeAttributeName, XmlConstants.AtomNamespace);
                if (AtomParser.IsAllowedContentType(propertyValue))
                {
                    if (this.reader.IsEmptyElement)
                    {
                        return;
                    }

                    if (ReadChildElement(this.reader, XmlConstants.AtomPropertiesElementName, XmlConstants.DataWebMetadataNamespace))
                    {
                        this.ReadCurrentProperties(targetEntry.DataValues);
                    }
                    else
                    if (this.reader.NodeType != XmlNodeType.EndElement)
                    {
                        throw Error.InvalidOperation(Strings.Deserialize_NotApplicationXml);
                    }
                }
            }
        }

        private void ParseCurrentLink(AtomEntry targetEntry)
        {
            Debug.Assert(targetEntry != null, "targetEntry != null");
            Debug.Assert(
                this.reader.NodeType == XmlNodeType.Element,
                "this.reader.NodeType == XmlNodeType.Element -- otherwise we shouldn't try to parse a link");
            Debug.Assert(
                this.reader.LocalName == "link",
                "this.reader.LocalName == 'link' -- otherwise we shouldn't try to parse a link");

            string relation = this.reader.GetAttribute(XmlConstants.AtomLinkRelationAttributeName);
            if (relation == null)
            {
                return;
            }

            if (relation == XmlConstants.AtomEditRelationAttributeValue && targetEntry.EditLink == null)
            {
                string href = this.reader.GetAttribute(XmlConstants.AtomHRefAttributeName);
                if (String.IsNullOrEmpty(href))
                {
                    throw Error.InvalidOperation(Strings.Context_MissingEditLinkInResponseBody);
                }

                targetEntry.EditLink = this.ConvertHRefAttributeValueIntoURI(href);
            }
            else if (relation == XmlConstants.AtomSelfRelationAttributeValue && targetEntry.QueryLink == null)
            {
                string href = this.reader.GetAttribute(XmlConstants.AtomHRefAttributeName);
                if (String.IsNullOrEmpty(href))
                {
                    throw Error.InvalidOperation(Strings.Context_MissingSelfLinkInResponseBody);
                }

                targetEntry.QueryLink = this.ConvertHRefAttributeValueIntoURI(href);
            }
            else if (relation == XmlConstants.AtomEditMediaRelationAttributeValue && targetEntry.MediaEditUri == null)
            {
                string href = this.reader.GetAttribute(XmlConstants.AtomHRefAttributeName);
                if (String.IsNullOrEmpty(href))
                {
                    throw Error.InvalidOperation(Strings.Context_MissingEditMediaLinkInResponseBody);
                }

                targetEntry.MediaEditUri = this.ConvertHRefAttributeValueIntoURI(href);
                targetEntry.StreamETagText = this.reader.GetAttribute(XmlConstants.AtomETagAttributeName, XmlConstants.DataWebMetadataNamespace);
            }

            if (!this.reader.IsEmptyElement)
            {
                string propertyName = UriUtil.GetNameFromAtomLinkRelationAttribute(relation);
                if (propertyName == null)
                {
                    return;
                }

                string propertyValueText = this.reader.GetAttribute(XmlConstants.AtomTypeAttributeName);
                bool isFeed;

                if (!IsAllowedLinkType(propertyValueText, out isFeed))
                {
                    return;
                }

                if (!ReadChildElement(this.reader, XmlConstants.AtomInlineElementName, XmlConstants.DataWebMetadataNamespace))
                {
                    return;
                }

                bool emptyInlineCollection = this.reader.IsEmptyElement;
                object propertyValue = null;

                if (!emptyInlineCollection)
                {
                    AtomFeed nestedFeed = null;
                    AtomEntry nestedEntry = null;
                    List<AtomEntry> feedEntries = null;

                    Debug.Assert(this.reader is Xml.XmlWrappingReader, "reader must be a instance of XmlWrappingReader");
                    string readerBaseUri = this.reader.BaseURI;
                    XmlReader nestedReader = Xml.XmlWrappingReader.CreateReader(readerBaseUri, this.reader.ReadSubtree());
                    nestedReader.Read();
                    Debug.Assert(nestedReader.LocalName == "inline", "nestedReader.LocalName == 'inline'");

                    AtomParser nested = new AtomParser(nestedReader, this.entryCallback, this.typeScheme, this.currentDataNamespace);
                    while (nested.Read())
                    {
                        switch (nested.DataKind)
                        {
                            case AtomDataKind.Feed:
                                feedEntries = new List<AtomEntry>();
                                nestedFeed = nested.CurrentFeed;
                                propertyValue = nestedFeed;
                                break;
                            case AtomDataKind.Entry:
                                nestedEntry = nested.CurrentEntry;
                                if (feedEntries != null)
                                {
                                    feedEntries.Add(nestedEntry);
                                }
                                else
                                {
                                    propertyValue = nestedEntry;
                                }

                                break;
                            case AtomDataKind.PagingLinks:
                                break;
                            default:
                                throw new InvalidOperationException(Strings.AtomParser_UnexpectedContentUnderExpandedLink);
                        }
                    }

                    if (nestedFeed != null)
                    {
                        Debug.Assert(
                            nestedFeed.Entries == null,
                            "nestedFeed.Entries == null -- otherwise someone initialized this for us");
                        nestedFeed.Entries = feedEntries;
                    }
                }

                AtomContentProperty property = new AtomContentProperty();
                property.Name = propertyName;

                if (emptyInlineCollection || propertyValue == null)
                {
                    property.IsNull = true;
                    if (isFeed)
                    {
                        property.Feed = new AtomFeed();
                        property.Feed.Entries = Enumerable.Empty<AtomEntry>();
                    }
                    else
                    {
                        property.Entry = new AtomEntry();
                        property.Entry.IsNull = true;
                    }
                }
                else
                {
                    property.Feed = propertyValue as AtomFeed;
                    property.Entry = propertyValue as AtomEntry;
                }

                targetEntry.DataValues.Add(property);
            }
        }

        private void ReadPropertyValueIntoResult(AtomContentProperty property)
        {
            Debug.Assert(this.reader != null, "reader != null");
            Debug.Assert(property != null, "property != null");

            switch (this.reader.NodeType)
            {
                case XmlNodeType.CDATA:
                case XmlNodeType.SignificantWhitespace:
                case XmlNodeType.Text:
                    if (!String.IsNullOrEmpty(property.Text))
                    {
                        throw Error.InvalidOperation(Strings.Deserialize_MixedTextWithComment);
                    }

                    property.Text = this.reader.Value;
                    break;

                case XmlNodeType.Comment:
                case XmlNodeType.Whitespace:
                case XmlNodeType.ProcessingInstruction:
                case XmlNodeType.EndElement:
                    break;

                case XmlNodeType.Element:
                    if (!String.IsNullOrEmpty(property.Text))
                    {
                        throw Error.InvalidOperation(Strings.Deserialize_ExpectingSimpleValue);
                    }

                    property.EnsureProperties();
                    AtomContentProperty prop = this.ReadPropertyValue();

                    if (prop != null)
                    {
                        property.Properties.Add(prop);
                    }

                    break;

                default:
                    throw Error.InvalidOperation(Strings.Deserialize_ExpectingSimpleValue);
            }
        }

        private AtomContentProperty ReadPropertyValue()
        {
            Debug.Assert(this.reader != null, "reader != null");
            Debug.Assert(
                this.reader.NodeType == XmlNodeType.Element,
                "reader.NodeType == XmlNodeType.Element -- otherwise caller is confused as to where the reader is");

            if (!this.IsDataWebElement)
            {
                SkipToEndAtDepth(this.reader, this.reader.Depth);
                return null;
            }

            AtomContentProperty result = new AtomContentProperty();
            result.Name = this.reader.LocalName;
            result.TypeName = this.reader.GetAttributeEx(XmlConstants.AtomTypeAttributeName, XmlConstants.DataWebMetadataNamespace);
            result.IsNull = Util.DoesNullAttributeSayTrue(this.reader);
            result.Text = result.IsNull ? null : String.Empty;

            if (!this.reader.IsEmptyElement)
            {
                int depth = this.reader.Depth;
                while (this.reader.Read())
                {
                    this.ReadPropertyValueIntoResult(result);
                    if (this.reader.Depth == depth)
                    {
                        break;
                    }
                }
            }

            return result;
        }

        private void ReadCurrentProperties(List<AtomContentProperty> values)
        {
            Debug.Assert(values != null, "values != null");
            Debug.Assert(this.reader.NodeType == XmlNodeType.Element, "this.reader.NodeType == XmlNodeType.Element");

            while (this.reader.Read())
            {
                if (ShouldIgnoreNode(this.reader))
                {
                    continue;
                }

                if (this.reader.NodeType == XmlNodeType.EndElement)
                {
                    return;
                }

                if (this.reader.NodeType == XmlNodeType.Element)
                {
                    AtomContentProperty prop = this.ReadPropertyValue();

                    if (prop != null)
                    {
                        values.Add(prop);
                    }
                }
            }
        }

        private void ParseCurrentEntry(out AtomEntry targetEntry)
        {
            Debug.Assert(this.reader.NodeType == XmlNodeType.Element, "this.reader.NodeType == XmlNodeType.Element");

            var callbackResult = this.entryCallback(this.reader);
            Debug.Assert(callbackResult.Key != null, "callbackResult.Key != null");
            this.readers.Push(this.reader);
            this.reader = callbackResult.Key;

            this.reader.Read();
            Debug.Assert(this.reader.LocalName == "entry", "this.reader.LocalName == 'entry' - otherwise we're not reading the subtree");

            bool hasContent = false;
            targetEntry = new AtomEntry();
            targetEntry.DataValues = new List<AtomContentProperty>();
            targetEntry.Tag = callbackResult.Value;
            targetEntry.ETagText = this.reader.GetAttribute(XmlConstants.AtomETagAttributeName, XmlConstants.DataWebMetadataNamespace);

            while (this.reader.Read())
            {
                if (ShouldIgnoreNode(this.reader))
                {
                    continue;
                }

                if (this.reader.NodeType == XmlNodeType.Element)
                {
                    int depth = this.reader.Depth;
                    string elementName = this.reader.LocalName;
                    string namespaceURI = this.reader.NamespaceURI;
                    if (namespaceURI == XmlConstants.AtomNamespace)
                    {
                        if (elementName == XmlConstants.AtomCategoryElementName && targetEntry.TypeName == null)
                        {
                            string text = this.reader.GetAttributeEx(XmlConstants.AtomCategorySchemeAttributeName, XmlConstants.AtomNamespace);
                            if (text == this.typeScheme)
                            {
                                targetEntry.TypeName = this.reader.GetAttributeEx(XmlConstants.AtomCategoryTermAttributeName, XmlConstants.AtomNamespace);
                            }
                        }
                        else if (elementName == XmlConstants.AtomContentElementName)
                        {
                            hasContent = true;
                            this.ParseCurrentContent(targetEntry);
                        }
                        else if (elementName == XmlConstants.AtomIdElementName && targetEntry.Identity == null)
                        {
                            string idText = ReadElementStringForText(this.reader);
                            idText = Util.ReferenceIdentity(idText);

                            Uri idUri = Util.CreateUri(idText, UriKind.RelativeOrAbsolute);
                            if (!idUri.IsAbsoluteUri)
                            {
                                throw Error.InvalidOperation(Strings.Context_TrackingExpectsAbsoluteUri);
                            }

                            targetEntry.Identity = idText;
                        }
                        else if (elementName == XmlConstants.AtomLinkElementName)
                        {
                            this.ParseCurrentLink(targetEntry);
                        }
                    }
                    else if (namespaceURI == XmlConstants.DataWebMetadataNamespace)
                    {
                        if (elementName == XmlConstants.AtomPropertiesElementName)
                        {
                            if (targetEntry.MediaLinkEntry.HasValue && !targetEntry.MediaLinkEntry.Value)
                            {
                                throw Error.InvalidOperation(Strings.Deserialize_ContentPlusPropertiesNotAllowed);
                            }

                            targetEntry.MediaLinkEntry = true;

                            if (!this.reader.IsEmptyElement)
                            {
                                this.ReadCurrentProperties(targetEntry.DataValues);
                            }
                        }
                    }

                    SkipToEndAtDepth(this.reader, depth);
                }
            }

            if (targetEntry.Identity == null)
            {
                throw Error.InvalidOperation(Strings.Deserialize_MissingIdElement);
            }

            if (!hasContent)
            {
                throw Error.BatchStreamContentExpected(BatchStreamState.GetResponse);
            }

            this.reader = this.readers.Pop();
        }

        private void ParseCurrentFeedCount()
        {
            if (this.feed == null)
            {
                throw new InvalidOperationException(Strings.AtomParser_FeedCountNotUnderFeed);
            }

            if (this.feed.Count.HasValue)
            {
                throw new InvalidOperationException(Strings.AtomParser_ManyFeedCounts);
            }

            long countValue;
            if (!long.TryParse(MaterializeAtom.ReadElementString(this.reader, true), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out countValue))
            {
                throw new FormatException(Strings.MaterializeFromAtom_CountFormatError);
            }

            if (countValue < 0)
            {
                throw new FormatException(Strings.MaterializeFromAtom_CountFormatError);
            }

            this.feed.Count = countValue;
        }

        private void ParseCurrentFeedPagingLinks()
        {
            Debug.Assert(this.feed != null, "Trying to parser paging links but feed is null.");

            if (this.feed.NextLink != null)
            {
                throw new InvalidOperationException(Strings.AtomMaterializer_DuplicatedNextLink);
            }

            string nextLink = this.reader.GetAttribute(XmlConstants.AtomHRefAttributeName);

            if (nextLink == null)
            {
                throw new InvalidOperationException(Strings.AtomMaterializer_LinksMissingHref);
            }
            else
            {
                this.feed.NextLink = this.ConvertHRefAttributeValueIntoURI(nextLink);
            }
        }

        private Uri ConvertHRefAttributeValueIntoURI(string href)
        {
            Uri uri = Util.CreateUri(href, UriKind.RelativeOrAbsolute);
            if (!uri.IsAbsoluteUri && !String.IsNullOrEmpty(this.reader.BaseURI))
            {
                Uri baseUri = Util.CreateUri(this.reader.BaseURI, UriKind.RelativeOrAbsolute);

                uri = new Uri(baseUri, uri);
            }

            return uri;
        }

        #endregion Private methods.
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.openksavi.sponge.remoteapi.model.response;

import java.util.Map;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import org.openksavi.sponge.remoteapi.model.response.GetFeaturesResponse.GetFeaturesResult;

@ApiModel(value = "GetFeaturesResponse", description = "A get features response")
public class GetFeaturesResponse extends BaseResponse<GetFeaturesResult> {

    public GetFeaturesResponse(GetFeaturesResult result) {
        super(result);
    }

    public GetFeaturesResponse() {
        this(null);
    }

    @ApiModel(value = "GetFeaturesResult", description = "A get features response result")
    public static class GetFeaturesResult extends BaseResponseResult<Map<String, Object>> {

        public GetFeaturesResult() {
        }

        public GetFeaturesResult(Map<String, Object> features) {
            super(features);
        }

        @Override
        @ApiModelProperty(value = "The API features", required = true)
        public Map<String, Object> getValue() {
            return super.getValue();
        }
    }
}


text:
package com.ami.gui2go.tree;

import android.util.Log;

/**
 * Allows to build tree easily in sequential mode (you have to know levels of
 * all the tree elements upfront). You should rather use this class rather than
 * manager if you build initial tree from some external data source.
 *
 * @param <T>
 */
public class TreeBuilder<T> {
    private static final String TAG = TreeBuilder.class.getSimpleName();

    private final TreeStateManager<T> manager;

    private T lastAddedId = null;
    private int lastLevel = -1;

    public TreeBuilder(final TreeStateManager<T> manager) {
        this.manager = manager;
    }

    public void clear() {
        manager.clear();
    }

    /**
     * Adds new relation to existing tree. Child is set as the last child of the
     * parent node. Parent has to already exist in the tree, child cannot yet
     * exist. This method is mostly useful in case you add entries layer by
     * layer - i.e. first top level entries, then children for all parents, then
     * grand-children and so on.
     *
     * @param parent
     *            parent id
     * @param child
     *            child id
     */
    public synchronized void addRelation(final T parent, final T child) {
        Log.d(TAG, "Adding relation parent:" + parent + " -> child: " + child);
        manager.addAfterChild(parent, child, null);
        lastAddedId = child;
        lastLevel = manager.getLevel(child);
    }

    /**
     * Adds sequentially new node. Using this method is the simplest way of
     * building tree - if you have all the elements in the sequence as they
     * should be displayed in fully-expanded tree. You can combine it with add
     * relation - for example you can add information about few levels using
     * {@link addRelation} and then after the right level is added as parent,
     * you can continue adding them using sequential operation.
     *
     * @param id
     *            id of the node
     * @param level
     *            its level
     */
    public synchronized void sequentiallyAddNextNode(final T id, final int level) {
        Log.d(TAG, "Adding sequentiall node " + id + " at level " + level);
        if (lastAddedId == null) {
            addNodeToParentOneLevelDown(null, id, level);
        } else {
            if (level <= lastLevel) {
                final T parent = findParentAtLevel(lastAddedId, level - 1);
                addNodeToParentOneLevelDown(parent, id, level);
            } else {
                addNodeToParentOneLevelDown(lastAddedId, id, level);
            }
        }
    }

    /**
     * Find parent of the node at the level specified.
     *
     * @param node
     *            node from which we start
     * @param levelToFind
     *            level which we are looking for
     * @return the node found (null if it is topmost node).
     */
    private T findParentAtLevel(final T node, final int levelToFind) {
        T parent = manager.getParent(node);
        while (parent != null) {
            if (manager.getLevel(parent) == levelToFind) {
                break;
            }
            parent = manager.getParent(parent);
        }
        return parent;
    }

    /**
     * Adds note to parent at the level specified. But it verifies that the
     * level is one level down than the parent!
     *
     * @param parent
     *            parent parent
     * @param id
     *            new node id
     * @param level
     *            should always be parent's level + 1
     */
    private void addNodeToParentOneLevelDown(final T parent, final T id,
            final int level) {
        if (parent == null && level != 0) {
            throw new TreeConfigurationException("Trying to add new id " + id
                    + " to top level with level != 0 (" + level + ")");
        }
        if (parent != null && manager.getLevel(parent) != level - 1) {
            throw new TreeConfigurationException("Trying to add new id " + id
                    + " <" + level + "> to " + parent + " <"
                    + manager.getLevel(parent)
                    + ">. The difference in levels up is bigger than 1.");
        }
        manager.addAfterChild(parent, id, null);
        setLastAdded(id, level);
    }

    private void setLastAdded(final T id, final int level) {
        lastAddedId = id;
        lastLevel = level;
    }

}


text:
// coding: utf-8

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

/**
 * \file	tcs3414.hpp
 * \date	02 Mar 2013
 * \author	David Hebbeker
 */

#ifndef XPCC_TCS3414_HPP
#define XPCC_TCS3414_HPP

#include <stdint.h>

#include <xpcc/ui/color.hpp>
#include <xpcc/processing/protothread.hpp>
#include <xpcc/processing/resumable.hpp>
#include <xpcc/architecture/interface/i2c_device.hpp>

namespace xpcc
{
/**
 * \brief 	Settings to configure the digital color sensor TCS3414 / TCS3413 / TCS3415 / TCS3416.
 * \see		Tcs3414
 * \ingroup	driver_other
 *
 * Device   Address
 * TCS3413  0x29
 *       4  0x39
 *       5  0x49
 *       6  0x59
 *
 */
struct tcs3414
{
	/** @name Gain_Register
	 * @{
	 */

	//! \brief 	Analog gain control
	enum class Gain : uint8_t
	{
		X1	= 0b000000,	//!< x1 gain
		X4	= 0b010000,	//!< x4 gain
		X16	= 0b100000,	//!< x16 gain
		X64	= 0b110000,	//!< x64 gain
		DEFAULT = 0		//!< default value on chip reset
	};

	//! \brief 	Prescaler mode
	enum class Prescaler : uint8_t
	{
		D1	= 0b000,	//!< divide by 1
		D2	= 0b001,	//!< divide by 2
		D4	= 0b010,	//!< divide by 4
		D8	= 0b011,	//!< divide by 8
		D16	= 0b100,	//!< divide by 16
		D32	= 0b101,	//!< divide by 32
		D64	= 0b110,	//!< divide by 64
		DEFAULT = 0		//!< default value on chip reset
	};
	//! @}

	/** @name Timing register
	 * @{
	 */

	//! \brief 	Select mode how to choose the integration time
	enum class IntegrationMode : uint8_t
	{
		INTERNAL	= 0b000000,	//!< integrates with the free-running mode
		ADC_CTR		= 0b010000,	//!< use the ADC enable bit field in the control register to start and stop integration
		SYNC_NOM	= 0b100000,	//!< use synchronize signal to integrate over nominal integration time
		SYNC_COUNT	= 0b110000,	//!< integrate over pulse count pulses of the sync pin
		DEFAULT = 0				//!< default value on chip reset
	};

	//! \brief 	Integration for a fixed time
	enum class NominalIntegrationTime : uint8_t
	{
		MSEC_12		= 0b0000,	//!< integrate over 12 ms
		MSEC_100	= 0b0001,	//!< integrate over 100 ms
		MSEC_400	= 0b0010,	//!< integrate over 400 ms
		DEFAULT = 0				//!< default value on chip reset
	};

	//! \brief 	The number of pulses on sync pin to integrate over
	enum class SyncPulseCount : uint8_t
	{
		PULSES_1	= 0b0000,	//!< integrate over 1 pulses of sync pin
		PULSES_2	= 0b0001,	//!< integrate over 2 pulses of sync pin
		PULSES_4	= 0b0010,	//!< integrate over 4 pulses of sync pin
		PULSES_8	= 0b0011,	//!< integrate over 8 pulses of sync pin
		PULSES_16	= 0b0100,	//!< integrate over 16 pulses of sync pin
		PULSES_32	= 0b0101,	//!< integrate over 32 pulses of sync pin
		PULSES_64	= 0b0110,	//!< integrate over 64 pulses of sync pin
		PULSES_128	= 0b0111,	//!< integrate over 128 pulses of sync pin
		PULSES_256	= 0b1000,	//!< integrate over 256 pulses of sync pin
		DEFAULT = 0		//!< default value on chip reset
	};
	//! @}

	//! \brief 	Register addresses
	enum class RegisterAddress : uint8_t
	{
		CONTROL					= 0x00,	//!< Control of basic functions
		TIMING					= 0x01,	//!< Integration time control  @see Tcs3414::setIntegrationTime
		INTERRUPT				= 0x02,	//!< Interrupt settings
		INT_SOURCE				= 0x03,	//!< Interrupt source
		ID						= 0x04,	//!< Part number
		GAIN					= 0x07,	//!< Sensitivity settings @see Tcs3414::setGain
		LOW_THRESH_LOW_BYTE		= 0x08,	//!< Low byte of low interrupt threshold
		LOW_THRESH_HIGH_BYTE	= 0x09,	//!< High byte of low interrupt threshold
		HIGH_THRESH_LOW_BYTE	= 0x0A,	//!< Low byte of high interrupt threshold
		HIGH_THRESH_HIGH_BYTE	= 0x0B,	//!< High byte of high interrupt threshold
		// Data registers
		DATA1LOW				= 0x10,	//!< Low byte of ADC green channel
		DATA1HIGH				= 0x11,	//!< High byte of ADC green channel
		DATA2LOW				= 0x12,	//!< Low byte of ADC green channel
		DATA2HIGH				= 0x13,	//!< High byte of ADC green channel
		DATA3LOW				= 0x14,	//!< Low byte of ADC green channel
		DATA3HIGH				= 0x15,	//!< High byte of ADC green channel
		DATA4LOW				= 0x16,	//!< Low byte of ADC green channel
		DATA5HIGH				= 0x17	//!< High byte of ADC green channel
	};

	typedef uint16_t	UnderlyingType;		//!< datatype of color values
	typedef color::RgbT<UnderlyingType> Rgb;

};

/**
 * \brief	TCS3414 Digital Color Sensors
 *
 * \todo	Not all features of the sensors are implemented in this driver
 * 			yet.
 *
 * \tparam	I2CMaster	I2C interface which needs an \em initialized
 * 						xpcc::i2c::Master
 * \see		tcs3414
 * \author	David Hebbeker
 * \ingroup	driver_other
 */
template < typename I2cMaster >
class Tcs3414 : public tcs3414, public xpcc::I2cDevice< I2cMaster, 2 >
{
public:
	Tcs3414(uint8_t address = 0x39);

	//! \brief 	Power up sensor and start conversions
	// Blocking
	bool inline
	initializeBlocking()
	{
		return RF_CALL_BLOCKING(initialize());
	}

	//! \brief 	Configures some of the most important settings for the sensor.
	static inline bool
	configure(
			const Gain                   gain      = Gain::DEFAULT,
			const Prescaler              prescaler = Prescaler::DEFAULT,
			const IntegrationMode        mode      = IntegrationMode::DEFAULT,
			const NominalIntegrationTime time      = NominalIntegrationTime::DEFAULT)
	{
		return configure(gain, prescaler, mode, static_cast<uint8_t>(time));
	}

	//! \brief	Configures some of the most important settings for the sensor.
	static inline bool
	configure(
			const Gain            gain      = Gain::DEFAULT,
			const Prescaler       prescaler = Prescaler::DEFAULT,
			const IntegrationMode mode      = IntegrationMode::DEFAULT,
			const SyncPulseCount  time      = SyncPulseCount::DEFAULT)
	{
		return configure(gain, prescaler, mode, static_cast<uint8_t>(time));
	}

	//! \brief	The gain can be used to adjust the sensitivity of all ADC output channels.
	xpcc::ResumableResult<bool>
	setGain(
			const Gain      gain      = Gain::DEFAULT,
			const Prescaler prescaler = Prescaler::DEFAULT)
	{
		return writeRegister(RegisterAddress::GAIN,
				static_cast<uint8_t>(gain) | static_cast<uint8_t>(prescaler));
	}

	//! \brief Sets the integration time for the ADCs.
	xpcc::ResumableResult<bool>
	setIntegrationTime(
			const IntegrationMode        mode = IntegrationMode::DEFAULT,
			const NominalIntegrationTime time = NominalIntegrationTime::DEFAULT)
	{
		return setIntegrationTime(mode, static_cast<uint8_t>(time));
	}

	//! \brief Sets the integration time for the ADCs.
	xpcc::ResumableResult<bool>
	setIntegrationTime(
			const IntegrationMode mode = IntegrationMode::DEFAULT,
			const SyncPulseCount  time = SyncPulseCount::DEFAULT)
	{
		return setIntegrationTime(mode, static_cast<uint8_t>(time));
	}

	/**
	 * @name Return already sampled color
	 * @{
	 */
	inline static tcs3414::Rgb
	getOldColors()
	{
		return color;
	};

	//!@}

	/**
	 * @name Sample and return fresh color values
	 * @{
	 */
	inline static tcs3414::Rgb
	getNewColors()
	{
		refreshAllColors();
		return getOldColors();
	};

	//!@}

	//! \brief	Read current samples of ADC conversions for all channels.
	// Non-blocking
	xpcc::ResumableResult<bool>
	refreshAllColors();

	// MARK: - TASKS
	xpcc::ResumableResult<bool>
	initialize()
	{
		return writeRegister(RegisterAddress::CONTROL, 0b11);	// control to power up and start conversion
	};

	xpcc::ResumableResult<bool>
	configure(
			const Gain            gain      = Gain::DEFAULT,
			const Prescaler       prescaler = Prescaler::DEFAULT,
			const IntegrationMode mode      = IntegrationMode::DEFAULT,
			const uint8_t time = 0);

private:
	//! \brief Sets the integration time for the ADCs.
	xpcc::ResumableResult<bool>
	setIntegrationTime(
			const IntegrationMode mode = IntegrationMode::DEFAULT,
			const uint8_t         time = 0)
	{
		return writeRegister(
				RegisterAddress::TIMING,
				static_cast<uint8_t>(mode) | time );
	}

private:
	uint8_t commandBuffer[4];
	bool success;

private:
	//! \brief	Read value of specific register.
	xpcc::ResumableResult<bool>
	readRegisters(
			const RegisterAddress address,
			uint8_t * const values,
			const uint8_t count = 1);

	xpcc::ResumableResult<bool>
	writeRegister(
			const RegisterAddress address,
			const uint8_t value);

private:
	class uint16_t_LOW_HIGH
	{
	private:
		uint8_t low;
		uint8_t high;
	public:
		uint16_t
		get() const
		{
			uint16_t value = low;
			value |= high << 8;
			return value;
		}
		inline uint8_t getLSB()	const { return low; }
		inline uint8_t getMSB()	const { return high; }
	} xpcc_packed;

	static union Data
	{
		uint8_t dataBytes[2*4];
		struct
		{
			uint16_t_LOW_HIGH green;
			uint16_t_LOW_HIGH red;
			uint16_t_LOW_HIGH blue;
			uint16_t_LOW_HIGH clear;
		} xpcc_packed;
	} data;

	static Rgb	color;
};
}

#include "tcs3414_impl.hpp"

#endif // XPCC_TCS3414_HPP


text:
var fs = require('fs-extra');
var argv = require('minimist')(process.argv.slice(2));
var inquirer = require('inquirer');
var clone = require('git-clone');
var path = require('path');
var userHome = require('user-home');
var colors = require('colors');
var starterKitsDirectory = path.join(userHome, '.propel');
var starterKitsFile = path.join(starterKitsDirectory, 'starterKits.json');
fs.ensureDirSync(starterKitsDirectory);
fs.ensureFileSync(starterKitsFile);

var starterKits = fs.readJsonSync(starterKitsFile, { throws: false });
if (starterKits === null) {
    starterKits = {
        kits: []
    };
    fs.writeFileSync(starterKitsFile, JSON.stringify(starterKits));
}

if (argv.a) {
    addStartKit();
} else if (argv.r) {
    removeStarterKit();
} else if(argv.i) {
    if (typeof argv.i === "string") {
        importStarterKits(path.join(process.cwd(), argv.i));
    } else {
        console.log('Provide the name of the file to import which is in the current working directory.'.yellow)
    }
} else if(argv.e) {
    exportStarterKits();
} else {
    if (starterKits.kits.length === 0) {
        console.log("No starter kit available. Use the --a option to add a new one.".blue)
    } else {
        cloneStarterKit();
    }
}

function addStartKit() {
    inquirer.prompt([{
        type: 'input',
        name: 'kit_name',
        message: 'Name of the starter kit?'
    }, {
        type: 'input',
        name: 'kit_url',
        message: 'Git url of the starter kit?'
    }]).then(function (answers) {
        if (getKitName(answers.kit_name) !== null) {
            console.log('There is already a starter kit with the same name. Shall we try a differnt name?'.red)
        } else {
            starterKits.kits.push({
                name: answers.kit_name,
                url: answers.kit_url
            })
            fs.writeFileSync(starterKitsFile, JSON.stringify(starterKits));
        }
    });
}

function removeStarterKit() {
    var kit_choices_to_remove = [];
    starterKits.kits.forEach(function (item) {
        kit_choices_to_remove.push({
            name: item.name
        });
    })

    inquirer.prompt([{
        type: 'checkbox',
        name: 'kits_to_remove',
        message: 'Select the starter kits to remove.',
        choices: kit_choices_to_remove
    }]).then(function (answers) {
        removeKitsByName(answers.kits_to_remove);
        fs.writeFileSync(starterKitsFile, JSON.stringify(starterKits));
    });
}

function cloneStarterKit() {
    var kit_choices = [];
    starterKits.kits.forEach(function (item) {
        kit_choices.push(item.name);
    })
    inquirer.prompt([{
        type: 'list',
        name: 'kit_to_clone',
        message: 'Choose a starter kit to clone.',
        choices: kit_choices
    }]).then(function (answers) {
        var gitUrl = getKitName(answers.kit_to_clone).url;
        console.log(colors.blue('Cloning starter kit ' + answers.kit_to_clone + ' (' + gitUrl + ')'));
        clone(gitUrl, process.cwd(), function(err) {
            if (err) {
                console.log(colors.red('Something is wrong. ' + err));
            } else {
                console.log("Successfully cloned. Let's get to work.".green);
            }
        });
    });
}

function importStarterKits(filePath) {
    var importedStarterKits = fs.readJsonSync(filePath, { throws: false });
    fs.writeFileSync(starterKitsFile, JSON.stringify(importedStarterKits));
    console.log("Successfully imported.".green);
}

function exportStarterKits() {
    var exportFilePath = path.join(process.cwd(), 'StaterKits.json');
    fs.writeFileSync(exportFilePath, JSON.stringify(starterKits));
    console.log(colors.green('Successfully exported to ' + exportFilePath + '.'));
}

function getKitName(kitName) {
    for (var i = 0; i < starterKits.kits.length; i++) {
        if (starterKits.kits[i].name === kitName) {
            return starterKits.kits[i];
        }
    }

    return null;
}

function removeKitsByName(toBeRemoved) {
    for (var i = 0; i < starterKits.kits.length; i++) {
        if (toBeRemoved.indexOf(starterKits.kits[i].name) > -1) {
            starterKits.kits.splice(i, 1);
            break;
        }
    }
}


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

#include "common.h"

//#include "ClassFactory3.h"
#include "winwrap.h"
#include "comcallablewrapper.h"
#include "frames.h"
#include "excep.h"
#include "registration.h"
#ifdef FEATURE_REMOTING
#include "remoting.h"
#endif
#include "typeparse.h"
#include "mdaassistants.h"

#ifdef FEATURE_COMINTEROP_MANAGED_ACTIVATION

// Allocate a managed object given the method table pointer.
HRESULT STDMETHODCALLTYPE EEAllocateInstance(LPUNKNOWN pOuter, MethodTable* pMT, BOOL fHasLicensing, REFIID riid, BOOL fDesignTime, BSTR bstrKey, void** ppv);
extern BOOL g_fEEComActivatedStartup;
extern BOOL g_fEEHostedStartup;
extern GUID g_EEComObjectGuid;

// ---------------------------------------------------------------------------
// %%Class EEClassFactory
// IClassFactory implementation for COM+ objects
// ---------------------------------------------------------------------------
class EEClassFactory : public IClassFactory2
{
public:
    EEClassFactory(CLSID* pClsId, MethodTable* pTable)
    {
        CONTRACTL
        {
            THROWS;
            GC_TRIGGERS;
            MODE_ANY;
            PRECONDITION(CheckPointer(pTable));
            PRECONDITION(CheckPointer(pClsId));
        }
        CONTRACTL_END;

        LOG((LF_INTEROP, LL_INFO100, "EEClassFactory::EEClassFactory for class %s\n", pTable->GetDebugClassName()));
        m_pMethodTable = pTable;
        m_cbRefCount = 0;
        memcpy(&m_ClsId, pClsId, sizeof(GUID));
        m_hasLicensing = FALSE;

        while (pTable != NULL && pTable != g_pObjectClass)
        {
            if (pTable->GetMDImport()->GetCustomAttributeByName(pTable->GetCl(), "System.ComponentModel.LicenseProviderAttribute", 0,0) == S_OK)
            {
                m_hasLicensing = TRUE;
                break;
            }
            pTable = pTable->GetParentMethodTable();
        }
    }

    ~EEClassFactory()
    {
        WRAPPER_NO_CONTRACT;

        LOG((LF_INTEROP, LL_INFO100, "EEClassFactory::~ for class %s\n", m_pMethodTable->GetDebugClassName()));
    }

    STDMETHODIMP QueryInterface( REFIID iid, void **ppv)
    {
        SetupForComCallDWORDNoHostNotif();

        CONTRACTL
        {
            NOTHROW;
            GC_TRIGGERS;
            MODE_PREEMPTIVE;
            SO_TOLERANT;
            PRECONDITION(CheckPointer(ppv, NULL_OK));
        }
        CONTRACTL_END;

        if (ppv == NULL)
            return E_POINTER;

        *ppv = NULL;

        if (iid == IID_IClassFactory || ((iid == IID_IClassFactory2) && m_hasLicensing ) || iid == IID_IUnknown)
        {
            *ppv = (IClassFactory2 *)this;
            AddRef();
        }

        return (*ppv != NULL) ? S_OK : E_NOINTERFACE;
    }

    STDMETHODIMP_(ULONG) AddRef()
{
        SetupForComCallDWORDNoHostNotif();

        CONTRACTL
        {
            NOTHROW;
            GC_TRIGGERS;
            MODE_PREEMPTIVE;
            SO_TOLERANT;
        }
        CONTRACTL_END;

        ULONG l = FastInterlockIncrement(&m_cbRefCount);
        return l;
    }

    STDMETHODIMP_(ULONG) Release()
    {
        SetupForComCallDWORD();

        CONTRACTL
        {
            NOTHROW;
            GC_TRIGGERS;
            MODE_PREEMPTIVE;
            SO_TOLERANT;
            PRECONDITION(m_cbRefCount > 0);
        }
        CONTRACTL_END;

        HRESULT hr = S_OK;
        ULONG l = -1;

        BEGIN_EXTERNAL_ENTRYPOINT(&hr)
        {
            l = FastInterlockDecrement(&m_cbRefCount);
            if (l == 0)
                delete this;
        }
        END_EXTERNAL_ENTRYPOINT;

        return l;
    }

    STDMETHODIMP CreateInstance(LPUNKNOWN punkOuter, REFIID riid, void** ppv)
    {
        HRESULT hr = S_OK;
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
        // SetupForComCallHR uses "SO_INTOLERANT_CODE_NOTHROW" to setup the SO-Intolerant transition
        // for COM Interop. However, "SO_INTOLERANT_CODE_NOTHROW" expects that no exception can escape
        // through this boundary but all it does is (in addition to checking that no exception has escaped it)
        // do stack probing.
        //
        // However, Corrupting Exceptions [CE] can escape the COM Interop boundary. Thus, to address that scenario,
        // we use the macro below that uses BEGIN_SO_INTOLERANT_CODE_NOTHROW to do the equivalent of
        // SO_INTOLERANT_CODE_NOTHROW and yet allow for CEs to escape through. Since there will be a corresponding
        // END_SO_INTOLERANT_CODE, the call is splitted into two parts: the Begin and End (see below).
        BeginSetupForComCallHRWithEscapingCorruptingExceptions();
#else // !FEATURE_CORRUPTING_EXCEPTIONS
        SetupForComCallHR();
#endif // FEATURE_CORRUPTING_EXCEPTIONS

        CONTRACTL
        {
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
            THROWS; // CSE can escape out of this function
#else // !FEATURE_CORRUPTING_EXCEPTIONS
            NOTHROW;
#endif // FEATURE_CORRUPTING_EXCEPTIONS
            GC_TRIGGERS;
            MODE_PREEMPTIVE;
            SO_TOLERANT;
        }
        CONTRACTL_END;

        hr = UpdateMethodTable();

        // allocate a com+ object
        // this will allocate the object in the correct context
        // we might end up with a tear-off on our COM+ context proxy
        if (SUCCEEDED(hr))
        {
            hr = EEAllocateInstance(punkOuter, m_pMethodTable, m_hasLicensing, riid, TRUE, NULL, ppv);
        }

#ifdef FEATURE_CORRUPTING_EXCEPTIONS
        EndSetupForComCallHRWithEscapingCorruptingExceptions();
#endif // FEATURE_CORRUPTING_EXCEPTIONS

        return hr;
    }

    STDMETHODIMP LockServer(BOOL fLock)
    {
        SetupForComCallHR();

        CONTRACTL
        {
            NOTHROW;
            GC_TRIGGERS;
            MODE_PREEMPTIVE;
            SO_TOLERANT;
        }
        CONTRACTL_END;

        return S_OK;
    }

    // The implementation of these two functions is provided below. Prefast chocks if their implementation is here.
    STDMETHODIMP GetLicInfo(LPLICINFO pLicInfo);
    STDMETHODIMP RequestLicKey(DWORD dwReserved, BSTR * pbstrKey);

    STDMETHODIMP CreateInstanceLic(IUnknown *punkOuter, IUnknown* pUnkReserved, REFIID riid, BSTR bstrKey, void **ppUnk)
    {
        HRESULT hr = S_OK;

#ifdef FEATURE_CORRUPTING_EXCEPTIONS
        // SetupForComCallHR uses "SO_INTOLERANT_CODE_NOTHROW" to setup the SO-Intolerant transition
        // for COM Interop. However, "SO_INTOLERANT_CODE_NOTHROW" expects that no exception can escape
        // through this boundary but all it does is (in addition to checking that no exception has escaped it)
        // do stack probing.
        //
        // However, Corrupting Exceptions [CE] can escape the COM Interop boundary. Thus, to address that scenario,
        // we use the macro below that uses BEGIN_SO_INTOLERANT_CODE_NOTHROW to do the equivalent of
        // SO_INTOLERANT_CODE_NOTHROW and yet allow for CEs to escape through. Since there will be a corresponding
        // END_SO_INTOLERANT_CODE, the call is splitted into two parts: the Begin and End (see below).
        BeginSetupForComCallHRWithEscapingCorruptingExceptions();
#else // !FEATURE_CORRUPTING_EXCEPTIONS
        SetupForComCallHR();
#endif // FEATURE_CORRUPTING_EXCEPTIONS

        CONTRACTL
        {
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
            THROWS; // CSE can escape out of this function
#else // !FEATURE_CORRUPTING_EXCEPTIONS
            NOTHROW;
#endif // FEATURE_CORRUPTING_EXCEPTIONS

            GC_TRIGGERS;
            MODE_PREEMPTIVE;
            SO_TOLERANT;
        }
        CONTRACTL_END;

        if (!ppUnk)
        {
            hr = E_POINTER;
            goto done;
        }

        *ppUnk = NULL;

        if (pUnkReserved != NULL)
        {
            hr = E_INVALIDARG;
            goto done;
        }

        if (bstrKey == NULL)
        {
            hr = E_POINTER;
            goto done;
        }

        hr = UpdateMethodTable();

        // allocate a com+ object
        // this will allocate the object in the correct context
        // we might end up with a tear-off on our COM+ context proxy
        if (SUCCEEDED(hr))
        {
            hr = EEAllocateInstance(punkOuter, m_pMethodTable, m_hasLicensing, riid, /*fDesignTime=*/FALSE, bstrKey, ppUnk);
        }

done: ;
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
        EndSetupForComCallHRWithEscapingCorruptingExceptions();
#endif // FEATURE_CORRUPTING_EXCEPTIONS

        return hr;
    }

    STDMETHODIMP CreateInstanceWithContext(LPUNKNOWN punkContext, LPUNKNOWN punkOuter, REFIID riid, void** ppv)
    {
        HRESULT hr = S_OK;

#ifdef FEATURE_CORRUPTING_EXCEPTIONS
        // SetupForComCallHR uses "SO_INTOLERANT_CODE_NOTHROW" to setup the SO-Intolerant transition
        // for COM Interop. However, "SO_INTOLERANT_CODE_NOTHROW" expects that no exception can escape
        // through this boundary but all it does is (in addition to checking that no exception has escaped it)
        // do stack probing.
        //
        // However, Corrupting Exceptions [CE] can escape the COM Interop boundary. Thus, to address that scenario,
        // we use the macro below that uses BEGIN_SO_INTOLERANT_CODE_NOTHROW to do the equivalent of
        // SO_INTOLERANT_CODE_NOTHROW and yet allow for CEs to escape through. Since there will be a corresponding
        // END_SO_INTOLERANT_CODE, the call is splitted into two parts: the Begin and End (see below).
        BeginSetupForComCallHRWithEscapingCorruptingExceptions();
#else // !FEATURE_CORRUPTING_EXCEPTIONS
        SetupForComCallHR();
#endif // FEATURE_CORRUPTING_EXCEPTIONS

        CONTRACTL
        {
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
            THROWS; // CSE can escape out of this function
#else // !FEATURE_CORRUPTING_EXCEPTIONS
            NOTHROW;
#endif // FEATURE_CORRUPTING_EXCEPTIONS
            GC_TRIGGERS;
            MODE_PREEMPTIVE;
            SO_TOLERANT;
        }
        CONTRACTL_END;

        hr = UpdateMethodTable();

        if (SUCCEEDED(hr))
        {
            hr = EEAllocateInstance(punkOuter, m_pMethodTable, m_hasLicensing, riid, TRUE, NULL, ppv);
        }

#ifdef FEATURE_CORRUPTING_EXCEPTIONS
        EndSetupForComCallHRWithEscapingCorruptingExceptions();
#endif // FEATURE_CORRUPTING_EXCEPTIONS

        return hr;
    }

private:
    // If we happen to be called from the same AD last time, we can use a cached MT
    // If not, we need to use the CLSID to find the correct MT for the current domain.
    CLSID                   m_ClsId;
    MethodTable*            m_pMethodTable;  // most recently used MT
    ADID                    m_dwDomainId;    // the AD we were in when this ClassFact was last used
    LONG                    m_cbRefCount;
    BOOL                    m_hasLicensing;

    // Ensure that m_pMethodTable and m_dwDomainId are valid for the current AppDomain.  If we're
    // not in the AD m_dwDomainId use the CLSID to get the MT.
    STDMETHODIMP UpdateMethodTable()
    {
        CONTRACTL
        {
            NOTHROW;
            GC_TRIGGERS;
            MODE_ANY;
            INJECT_FAULT(COMPlusThrowOM(););
            SO_TOLERANT;
        }
        CONTRACTL_END;

        HRESULT hr = S_OK;
        Thread *pThread = GetThread();
        ADID adid = pThread->GetDomain()->GetId();
        if (adid != m_dwDomainId)
        {
            MethodTable* tempMT = NULL;
            EX_TRY
            {
                BEGIN_SO_INTOLERANT_CODE(pThread);
                GCX_COOP();
                tempMT = GetTypeForCLSID(m_ClsId);
                END_SO_INTOLERANT_CODE;
            }
            EX_CATCH
            {
                hr = E_FAIL;
            }
            EX_END_CATCH(SwallowAllExceptions);

            if (tempMT != NULL && SUCCEEDED(hr))
            {
                m_pMethodTable = tempMT;
                m_dwDomainId = adid;
            }
        }
        return hr;
    }

};

STDMETHODIMP EEClassFactory::GetLicInfo(LPLICINFO pLicInfo)
{
    SetupForComCallHR();

    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;
    if (!pLicInfo)
        return E_POINTER;

    BEGIN_EXTERNAL_ENTRYPOINT(&hr)
    {
        GCX_COOP_THREAD_EXISTS(GET_THREAD());

        Thread *pThread = GET_THREAD();
        hr = UpdateMethodTable();
        if (SUCCEEDED(hr))
        {
            MethodTable *pHelperMT = pThread->GetDomain()->GetLicenseInteropHelperMethodTable();
            MethodDesc *pMD = MemberLoader::FindMethod(pHelperMT, "GetLicInfo", &gsig_IM_LicenseInteropHelper_GetLicInfo);
            MethodDescCallSite getLicInfo(pMD);

            struct _gc {
                OBJECTREF pHelper;
                OBJECTREF pType;
            } gc;
            gc.pHelper = NULL; // LicenseInteropHelper
            gc.pType   = NULL;

            GCPROTECT_BEGIN(gc);

            gc.pHelper = pHelperMT->Allocate();
            gc.pType = m_pMethodTable->GetManagedClassObject();

            {
                INT32 fRuntimeKeyAvail = 0;
                INT32 fLicVerified     = 0;

                ARG_SLOT args[4];
                args[0] = ObjToArgSlot(gc.pHelper);
                args[1] = ObjToArgSlot(gc.pType);
                args[2] = (ARG_SLOT)&fRuntimeKeyAvail;
                args[3] = (ARG_SLOT)&fLicVerified;
                getLicInfo.Call(args);

                pLicInfo->cbLicInfo = sizeof(LICINFO);
                pLicInfo->fRuntimeKeyAvail = fRuntimeKeyAvail;
                pLicInfo->fLicVerified     = fLicVerified;
            }
            GCPROTECT_END();
        }
    }
    END_EXTERNAL_ENTRYPOINT;

    return hr;
}

STDMETHODIMP EEClassFactory::RequestLicKey(DWORD dwReserved, BSTR * pbstrKey)
{
    SetupForComCallHR();

    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;

    if (dwReserved != 0)
        return E_INVALIDARG;

    if (!pbstrKey)
        return E_POINTER;

    *pbstrKey = NULL;

    BEGIN_EXTERNAL_ENTRYPOINT(&hr)
    {
        GCX_COOP_THREAD_EXISTS(GET_THREAD());

        Thread *pThread = GET_THREAD();
        hr = UpdateMethodTable();
        if (SUCCEEDED(hr))
        {
            MethodTable *pHelperMT = pThread->GetDomain()->GetLicenseInteropHelperMethodTable();
            MethodDesc *pMD = MemberLoader::FindMethod(pHelperMT, "RequestLicKey", &gsig_SM_LicenseInteropHelper_RequestLicKey);
            MethodDescCallSite requestLicKey(pMD);

            OBJECTREF pType = NULL;

            GCPROTECT_BEGIN(pType);

            pType = m_pMethodTable->GetManagedClassObject();
            ARG_SLOT args[2];
            args[0] = ObjToArgSlot(pType);
            args[1] = (ARG_SLOT)pbstrKey;
            hr = requestLicKey.Call_RetHR(args);
            GCPROTECT_END();
        }
    }
    END_EXTERNAL_ENTRYPOINT;

    return hr;
}

void EEAllocateInstanceWorker(LPUNKNOWN pOuter, MethodTable* pMT, BOOL fHasLicensing, REFIID riid, BOOL fDesignTime, BSTR bstrKey, void** ppv)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        INJECT_FAULT(COMPlusThrowOM());
        PRECONDITION(CheckPointer(pMT));
        PRECONDITION(!pMT->IsComImport());
    }
    CONTRACTL_END;

    *ppv                            = NULL;
    OBJECTREF   newobj;
    CCWHolder   pWrap               = NULL;
    BOOL        fCtorAlreadyCalled  = FALSE;
    Thread*     pThread             = GetThread();

    // classes that extend COM Imported class are special
    if (ExtendsComImport(pMT))
    {
        pMT->EnsureInstanceActive();
        newobj = AllocateObject(pMT);
    }
    else if (CRemotingServices::RequiresManagedActivation(pMT) != NoManagedActivation)
    {
        fCtorAlreadyCalled = TRUE;
        newobj = CRemotingServices::CreateProxyOrObject(pMT, TRUE);
    }
    else
    {
        // If the class doesn't have a LicenseProviderAttribute, let's not
        // pull in the LicenseManager class and friends.
        if (!fHasLicensing)
        {
            pMT->EnsureInstanceActive();
            newobj = AllocateObject( pMT, false );
        }
        else
        {
            MethodTable *pHelperMT = pThread->GetDomain()->GetLicenseInteropHelperMethodTable();
            MethodDesc *pMD = MemberLoader::FindMethod(pHelperMT, "AllocateAndValidateLicense", &gsig_SM_LicenseInteropHelper_AllocateAndValidateLicense);
            MethodDescCallSite allocateAndValidateLicense(pMD);

            pHelperMT->EnsureInstanceActive();

            OBJECTREF pType = NULL;

            GCPROTECT_BEGIN(pType);

            pType = pMT->GetManagedClassObject();

            ARG_SLOT args[3];
            args[0] = ObjToArgSlot(pType);
            args[1] = (ARG_SLOT)bstrKey;
            args[2] = fDesignTime ? 1 : 0;
            newobj = allocateAndValidateLicense.Call_RetOBJECTREF(args);
            fCtorAlreadyCalled = TRUE;

            GCPROTECT_END();
        }
    }

    GCPROTECT_BEGIN(newobj);
    {
        //get wrapper for the object, this could enable GC
        pWrap =  ComCallWrapper::InlineGetWrapper(&newobj);

        // don't call any constructors if we already have called them
        if (!fCtorAlreadyCalled && !pMT->IsValueType())
            CallDefaultConstructor(newobj);
    }
    GCPROTECT_END();

    if (pOuter == NULL)
    {
        // Return the tear-off
        *ppv = ComCallWrapper::GetComIPFromCCW(pWrap, riid, NULL, GetComIPFromCCW::CheckVisibility);
        if (!*ppv)
            COMPlusThrowHR(E_NOINTERFACE);
    }
    else
    {
        // Aggregation support,
        pWrap->InitializeOuter(pOuter);
        IfFailThrow(pWrap->GetInnerUnknown(ppv));
    }
}

// Allocate a managed object given the method table pointer
HRESULT STDMETHODCALLTYPE EEAllocateInstance(LPUNKNOWN pOuter, MethodTable* pMT, BOOL fHasLicensing, REFIID riid, BOOL fDesignTime, BSTR bstrKey, void** ppv)
{
    CONTRACTL
    {
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
        THROWS; // CSE can escape out of this function
#else // !FEATURE_CORRUPTING_EXCEPTIONS
        NOTHROW;
#endif // FEATURE_CORRUPTING_EXCEPTIONS
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
        PRECONDITION(CheckPointer(pMT));
        PRECONDITION(CheckPointer(ppv, NULL_OK));
    }
    CONTRACTL_END;

    if (ppv == NULL)
        return E_POINTER;
    *ppv = NULL;

    if ((!fDesignTime) && bstrKey == NULL)
        return E_POINTER;

    // aggregating objects should QI for IUnknown
    if (pOuter != NULL && !IsEqualIID(riid, IID_IUnknown))
        return E_INVALIDARG;

    HRESULT hr = S_OK;

#ifdef FEATURE_CORRUPTING_EXCEPTIONS
    // Get the MethodDesc of the type being instantiated. Based upon it,
    // we will decide whether to rethrow a CSE or not in
    // END_EXTERNAL_ENTRYPOINT_RETHROW_CORRUPTING_EXCEPTIONS_EX below.
    PTR_MethodDesc pMDDefConst = NULL;
    BOOL fHasConstructor = FALSE;
#endif // FEATURE_CORRUPTING_EXCEPTIONS

    BEGIN_EXTERNAL_ENTRYPOINT(&hr)
    {
        GCX_COOP_THREAD_EXISTS(GET_THREAD());

#ifdef FEATURE_CORRUPTING_EXCEPTIONS
        // Get the MethodDesc of the type being instantiated. Based upon it,
        // we will decide whether to rethrow a CSE or not in
        // END_EXTERNAL_ENTRYPOINT_RETHROW_CORRUPTING_EXCEPTIONS_EX below.
        if (pMT->HasDefaultConstructor())
        {
            pMDDefConst = pMT->GetDefaultConstructor();
            fHasConstructor = (pMDDefConst != NULL);
        }
#endif // FEATURE_CORRUPTING_EXCEPTIONS

        EEAllocateInstanceWorker(pOuter, pMT, fHasLicensing, riid, fDesignTime, bstrKey, ppv);
    }
    END_EXTERNAL_ENTRYPOINT_RETHROW_CORRUPTING_EXCEPTIONS_EX((fHasConstructor && (!CEHelper::CanMethodHandleException(UseLast,pMDDefConst))) ||
                                                             (!fHasConstructor));

    LOG((LF_INTEROP, LL_INFO100, "EEAllocateInstance for class %s object %8.8x\n", pMT->GetDebugClassName(), *ppv));

    return hr;
}

IUnknown *AllocateEEClassFactoryHelper(CLSID *pClsId, MethodTable *pMT)
{
    CONTRACT (IUnknown*)
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM());
        PRECONDITION(CheckPointer(pMT));
        PRECONDITION(CheckPointer(pClsId));
        POSTCONDITION(CheckPointer(RETVAL));
    }
    CONTRACT_END;

    RETURN ((IUnknown*)new EEClassFactory(pClsId, pMT));
}

void InitializeClass(TypeHandle th)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION(!th.IsNull());
    }
    CONTRACTL_END;

    // Make sure the type isn't an interface or an abstract class.
    if (th.IsAbstract() || th.IsInterface())
        COMPlusThrowHR(COR_E_MEMBERACCESS);

    // Unless we are dealing with a value class, the type must have a public
    // default constructor.
    if (!th.GetMethodTable()->HasExplicitOrImplicitPublicDefaultConstructor())
    {
        COMPlusThrowHR(COR_E_MEMBERACCESS);
    }

    // Call class init if necessary
    th.GetMethodTable()->EnsureInstanceActive();
    th.GetMethodTable()->CheckRunClassInitThrowing();
}

// Try to load a managed class and give out an IClassFactory
void EEDllGetClassObjectHelper(REFCLSID rclsid, MethodTable* pMT, REFIID riid, LPVOID FAR *ppv)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pMT));
        PRECONDITION(CheckPointer(ppv));
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;
    CLSID clsId;
    SafeComHolder<IUnknown> pUnk = NULL;

    memcpy(&clsId, &rclsid, sizeof(GUID));
    pUnk = AllocateEEClassFactoryHelper(&clsId, pMT);

    // Bump up the count to protect the object
    ULONG cbRef = SafeAddRef(pUnk);
    LogInteropAddRef(pUnk, cbRef, "EEDllGetClassObjectHelper: Bump up refcount to protect object during call");

    // Query for the requested interface.
    hr = SafeQueryInterface(pUnk, riid, (IUnknown**)ppv);
    LogInteropQI(pUnk, riid, hr, "EDllGetClassObjectHelper: QI for requested interface");
    IfFailThrow(hr);
}

HRESULT STDMETHODCALLTYPE EEDllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID FAR *ppv)
{
    HRESULT hr = S_OK;
    g_fEEComActivatedStartup = TRUE;
    g_EEComObjectGuid = rclsid;

    // The EE must be started before SetupForComCallHR is called and the contract is set up.
    if (FAILED(hr = EnsureEEStarted(COINITEE_DEFAULT)))
        return hr;

    SetupForComCallHR();

    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
        PRECONDITION(CheckPointer(ppv, NULL_OK));
    }
    CONTRACTL_END;

    if (ppv == NULL)
        return  E_POINTER;

    BEGIN_EXTERNAL_ENTRYPOINT(&hr);
    {
        GCX_COOP_THREAD_EXISTS(GET_THREAD());

        // We are about to use COM IPs so make sure COM is started up.
        EnsureComStarted();

        MethodTable *pMT;

        {
            Thread *pThread = GetThread();
            BEGIN_SO_INTOLERANT_CODE(pThread);
            GCX_COOP();
            pMT = GetTypeForCLSID(rclsid);
            END_SO_INTOLERANT_CODE;
        }

        // If we can't find the class based on the CLSID or if the registered managed
        // class is ComImport class then fail the call. Also, if the type is a generic
        // type (either opened or closed) then fail the call.
        if (!pMT || pMT->IsComImport() || (pMT->GetNumGenericArgs() != 0))
        {
            COMPlusThrowHR(REGDB_E_CLASSNOTREG);
        }

        // Verify that the class is indeed creatable and run it's .cctor if it
        // hasn't been run yet.
        InitializeClass(TypeHandle(pMT));

        // Allocate the IClassFactory for the type.
        EEDllGetClassObjectHelper(rclsid, pMT, riid, ppv);
    }
    END_EXTERNAL_ENTRYPOINT;

    return hr;
} //EEDllGetClassObject

// Helper Functions to get a object based on a name
void ClrCreateManagedInstanceHelper(MethodTable* pMT, REFIID riid, LPVOID FAR *ppv)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pMT));
        PRECONDITION(CheckPointer(ppv));
    }
    CONTRACTL_END;

    GCX_PREEMP();

    HRESULT hr = S_OK;
    SafeComHolderPreemp<IUnknown> pUnk = NULL;
    SafeComHolderPreemp<IClassFactory> pFactory = NULL;

    GUID guid;
    pMT->GetGuid(&guid, TRUE);
    pUnk = AllocateEEClassFactoryHelper(&guid, pMT);

    // Bump up the count to protect the object for the duration of this function
    ULONG cbRef = SafeAddRef(pUnk);
    LogInteropAddRef(pUnk, cbRef, "ClrCreateManagedInstanceHelper: Bumping refcount to protect object during call");

    // Query the factory for the IClassFactory interface.
    hr = SafeQueryInterface(pUnk, IID_IClassFactory, (IUnknown**) &pFactory);
    LogInteropQI(pUnk, IID_IClassFactory, hr, "ClrCreateManagedInstanceHelper: QI for IID_IClassFactory");
    IfFailThrow(hr);

    // Create an instance of the type.
    IfFailThrow(pFactory->CreateInstance(NULL, riid, ppv));
}

STDAPI ClrCreateManagedInstance(LPCWSTR typeName, REFIID riid, LPVOID FAR *ppv)
{
    HRESULT hr = S_OK;

    // The EE must be started before SetupForComCallHR is called and the contract is set up.
    g_fEEHostedStartup = TRUE;
    if (FAILED(hr = EnsureEEStarted(COINITEE_DEFAULT)))
        return hr;

    SetupForComCallHR();

    CONTRACTL
    {
        DISABLED(NOTHROW);
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        SO_TOLERANT;
        PRECONDITION(CheckPointer(typeName, NULL_OK));
        PRECONDITION(CheckPointer(ppv, NULL_OK));
    }
    CONTRACTL_END;

    if (ppv == NULL)
        return  E_POINTER;

    if (typeName == NULL)
        return E_INVALIDARG;

    BEGIN_EXTERNAL_ENTRYPOINT(&hr);
    {
        GCX_COOP_THREAD_EXISTS(GET_THREAD());

        // We are about to use COM IPs so make sure COM is started up.
        EnsureComStarted();

        MAKE_UTF8PTR_FROMWIDE(pName, typeName);

        AppDomain* pDomain = SystemDomain::GetCurrentDomain();
        MethodTable *pMT = TypeName::GetTypeUsingCASearchRules(pName, NULL).GetMethodTable();
        if (!pMT || pMT->IsComImport())
            COMPlusThrowHR(REGDB_E_CLASSNOTREG);

        // Verify that the class is indeed creatable and run it's .cctor if it
        // hasn't been run yet.
        InitializeClass(TypeHandle(pMT));

        // Allocate the instance of the type.
        ClrCreateManagedInstanceHelper(pMT, riid, ppv);
    }
    END_EXTERNAL_ENTRYPOINT;

    return hr;
}

DWORD RegisterTypeForComClientsHelper(MethodTable *pMT, GUID *pGuid, CLSCTX clsContext, REGCLS flags)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION(pMT != NULL);
        PRECONDITION(pGuid != NULL);
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;
    DWORD dwCookie = 0;
    SafeComHolder<IUnknown> pUnk = NULL;

    // We are about to perform COM operations so ensure COM is started up.
    EnsureComStarted();

    // Allocate an EE class factory for the type.
    pUnk = AllocateEEClassFactoryHelper(pGuid, pMT);

    // bump up the count to protect the object
    ULONG cbRef = SafeAddRef(pUnk);
    LogInteropAddRef(pUnk, cbRef, "RegisterTypeForComClientsNative: Bumping refcount to protect class factory");

    {
        // Enable GC
        GCX_PREEMP();

        // Call CoRegisterClassObject.
        IfFailThrow(CoRegisterClassObject(*(pGuid), pUnk, clsContext, flags, &dwCookie));
    }

    // CoRegisterClassObject will bump up the ref count so we must release
    // the extra ref count we added above.
    return dwCookie;
}

//+----------------------------------------------------------------------------
//
//  Method:     RegisterTypeForComClientsNative
//
//  Synopsis:   Registers a class factory with COM classic for a given type
//              and CLSID. Later we can receive activations on this factory
//              and we return a CCW.
//

//
//+----------------------------------------------------------------------------
FCIMPL2(VOID, RegisterTypeForComClientsNative, ReflectClassBaseObject* pTypeUNSAFE, GUID* pGuid)
{
    CONTRACTL
    {
        FCALL_CHECK;
        PRECONDITION(pTypeUNSAFE != NULL);
        PRECONDITION(pGuid != NULL);
    }
    CONTRACTL_END;

    REFLECTCLASSBASEREF pType = (REFLECTCLASSBASEREF) pTypeUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_1(pType);

    // Retrieve the method table from the type.
    MethodTable *pMT = pType->GetType().GetMethodTable();

    // Call the helper to perform the registration.
    RegisterTypeForComClientsHelper(pMT, pGuid, (CLSCTX)(CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER), REGCLS_MULTIPLEUSE);

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

//+----------------------------------------------------------------------------
//
//  Method:     RegisterTypeForComClientsExNative
//
//  Synopsis:   Registers a class factory with COM classic for a given type.
//
//+----------------------------------------------------------------------------
FCIMPL3(DWORD, RegisterTypeForComClientsExNative, ReflectClassBaseObject* pTypeUNSAFE, CLSCTX clsContext, REGCLS flags)
{
    CONTRACTL
    {
        FCALL_CHECK;
        PRECONDITION(pTypeUNSAFE != NULL);
    }
    CONTRACTL_END;

    DWORD dwCookie = 0;
    GUID clsid;

    REFLECTCLASSBASEREF pType = (REFLECTCLASSBASEREF) pTypeUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_RET_1(pType);

    // Retrieve the method table from the type.
    MethodTable *pMT = pType->GetType().GetMethodTable();

    // Retrieve the CLSID from the type.
    pMT->GetGuid(&clsid, TRUE);

    // Call the helper to perform the registration.
    dwCookie = RegisterTypeForComClientsHelper(pMT, &clsid, clsContext, flags);

    HELPER_METHOD_FRAME_END();

    return dwCookie;
}
FCIMPLEND

#else // FEATURE_COMINTEROP_MANAGED_ACTIVATION

STDAPI ClrCreateManagedInstance(LPCWSTR typeName, REFIID riid, LPVOID FAR *ppv)
{

    return E_NOTIMPL; // @TODO: CoreCLR_REMOVED: completely remove this function
}

#endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\models */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'user_id') ?>

    <?= $form->field($model, 'firstname') ?>

    <?= $form->field($model, 'lastname') ?>

    <?= $form->field($model, 'user_email') ?>

    <?= $form->field($model, 'password') ?>

    <?php // echo $form->field($model, 'user_type_id') ?>

    <?php // echo $form->field($model, 'access_token') ?>

    <?php // echo $form->field($model, 'status') ?>

    <?php // echo $form->field($model, 'created_on') ?>

    <?php // echo $form->field($model, 'expiry_date') ?>

    <?php // echo $form->field($model, 'language_id') ?>

    <?php // echo $form->field($model, 'amount') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
package com.github.gcauchis.scalablepress4j;

import com.github.gcauchis.scalablepress4j.model.ErrorResponse;

/**
 * The Class ScalablePressBadRequestException.
 */
public class ScalablePressBadRequestException extends RuntimeException {

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = 5250945263556128109L;

    /** the error response. */
    private final ErrorResponse errorResponse;

    /**
     * Instantiates a new scalable press bad request exception.
     *
     * @param errorResponse the error response
     */
    public ScalablePressBadRequestException(ErrorResponse errorResponse) {
        super(errorResponse.getStatusCode());
        this.errorResponse = errorResponse;
    }

    /**
     * Instantiates a new scalable press bad request exception.
     *
     * @param errorResponse the error response
     * @param throwable the throwable
     */
    public ScalablePressBadRequestException(ErrorResponse errorResponse, Throwable throwable) {
        super(errorResponse.getStatusCode(), throwable);
        this.errorResponse = errorResponse;
    }

    /**
     * Gets the error response.
     *
     * @return the error response
     */
    public ErrorResponse getErrorResponse() {
        return errorResponse;
    }

    @Override
    public String toString() {
        return "ScalablePressBadRequestException [errorResponse="
                + errorResponse + "]";
    }

}