text:
/*jshint unused: vars */
define([
    'angular',
    'controllers/add',
    'controllers/main',
    'controllers/list'
],
    /*deps*/
    function (angular, AddController, MainController, ListController)/*invoke*/ {
        'use strict';

        return angular.module('controllers', [])
            .controller('AddController', AddController)
            .controller('MainController', MainController)
            .controller('ListController', ListController);
    });


text:
// Copyright (C) 2003  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_SEQUENCE_KERNEl_2_
#define DLIB_SEQUENCE_KERNEl_2_

#include "sequence_kernel_abstract.h"
#include "../algs.h"
#include "../interfaces/enumerable.h"
#include "../interfaces/remover.h"
#include "../serialize.h"

namespace dlib
{

    template <
        typename T,
        typename mem_manager = default_memory_manager
        >
    class sequence_kernel_2 : public enumerable<T>,
                              public remover<T>
    {
        /*!
            INITIAL VALUE
                sequence_size   == 0
                at_start_       == true
                current_enumeration_node == 0

            CONVENTION
                sequence_size == the number of elements in the sequence

                at_start_ == at_start()
                (current_enumeration_node!=0) == current_element_valid()
                if (current_enumeration_node!=0) then
                    current_enumeration_node->item == element()
                    current_enumeration_pos == the position of the node pointed to by
                                               current_enumeration_node

                if ( sequence_size > 0 )
                {
                    current_node        == pointer to a node in the linked list and
                    current_node->right->right->... eventually == current_node and
                    current_node->left->left->... eventually == current_node and
                    current_pos         == the position in the sequence of
                                           current_node->item
                }

        !*/

        struct node {
            T item;
            node* right;
            node* left;
        };

        public:

            typedef T type;
            typedef mem_manager mem_manager_type;

            sequence_kernel_2 (
            ) :
                sequence_size(0),
                at_start_(true),
                current_enumeration_node(0)
            {}

            virtual ~sequence_kernel_2 (
            );

            inline void clear (
            );

            void add (
                unsigned long pos,
                T& item
            );

            void remove (
                unsigned long pos,
                T& item
            );

            void cat (
                sequence_kernel_2& item
            );

            const T& operator[] (
                unsigned long pos
            ) const;

            T& operator[] (
                unsigned long pos
            );

            void swap (
                sequence_kernel_2& item
            );

            // functions from the remover interface
            inline void remove_any (
                T& item
            );

            // functions from the enumerable interface
            inline unsigned long size (
            ) const;

            bool at_start (
            ) const;

            inline void reset (
            ) const;

            bool current_element_valid (
            ) const;

            const T& element (
            ) const;

            T& element (
            );

            bool move_next (
            ) const;

        private:

            void delete_nodes (
                node* current_node,
                unsigned long sequence_size
            );
            /*!
                requires
                    CONVENTION IS CORRECT
                ensures
                    all memory associated with the ring of nodes has been freed
            !*/

            void move_to_pos (
                node*& current_node,
                unsigned long& current_pos,
                unsigned long pos,
                unsigned long size
            ) const;
            /*!
                requires
                    everything in the CONVENTION is correct and
                    there is a node corresponding to pos in the CONVENTION and
                    0 <= pos < size
                ensures
                    current_pos == pos and
                    current_node->item is the item in the sequence associated with
                    position pos
            !*/

            // data members
            unsigned long sequence_size;
            mutable node* current_node;
            mutable unsigned long current_pos;
            mutable bool at_start_;
            mutable node* current_enumeration_node;
            mutable unsigned long current_enumeration_pos;

            // restricted functions
            sequence_kernel_2(sequence_kernel_2&);        // copy constructor
            sequence_kernel_2& operator=(sequence_kernel_2&); // assignment operator

    };

    template <
        typename T,
        typename mem_manager
        >
    inline void swap (
        sequence_kernel_2<T,mem_manager>& a,
        sequence_kernel_2<T,mem_manager>& b
    ) { a.swap(b); }

    template <
        typename T,
        typename mem_manager
        >
    void deserialize (
        sequence_kernel_2<T,mem_manager>& item,
        std::istream& in
    )
    {
        try
        {
            item.clear();
            unsigned long size;
            deserialize(size,in);
            T temp;
            for (unsigned long i = 0; i < size; ++i)
            {
                deserialize(temp,in);
                item.add(i,temp);
            }
        }
        catch (serialization_error e)
        {
            item.clear();
            throw serialization_error(e.info + "\n   while deserializing object of type sequence_kernel_2");
        }
    }

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
    // member function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <
        typename T,
        typename mem_manager
        >
    sequence_kernel_2<T,mem_manager>::
    ~sequence_kernel_2 (
    )
    {
        delete_nodes(current_node,sequence_size);
    }

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

    template <
        typename T,
        typename mem_manager
        >
    void sequence_kernel_2<T,mem_manager>::
    clear (
    )
    {
        if (sequence_size != 0)
        {
            delete_nodes(current_node,sequence_size);
            sequence_size = 0;
        }
        // reset the enumerator
        reset();
    }

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

    template <
        typename T,
        typename mem_manager
        >
    void sequence_kernel_2<T,mem_manager>::
    add (
        unsigned long pos,
        T& item
    )
    {
        // make new node and swap item into it
        node* new_node = new node;
        exchange(item,new_node->item);

        if (sequence_size > 0)
        {
            if (pos == sequence_size)
            {
                move_to_pos(current_node,current_pos,pos-1,sequence_size);

                node& n_node = *new_node;
                node& c_node = *current_node;

                // make new node point to the nodes to its left and right
                n_node.right = c_node.right;
                n_node.left  = current_node;

                // make the left node point back to new_node
                c_node.right->left = new_node;

                // make the right node point back to new_node
                c_node.right = new_node;
                current_pos = pos;

            }
            else
            {
                move_to_pos(current_node,current_pos,pos,sequence_size);

                node& n_node = *new_node;
                node& c_node = *current_node;

                // make new node point to the nodes to its left and right
                n_node.right = current_node;
                n_node.left  = c_node.left;

                // make the left node point back to new_node
                c_node.left->right = new_node;

                // make the right node point back to new_node
                c_node.left = new_node;
            }

        }
        else
        {
            current_pos = 0;
            new_node->left = new_node;
            new_node->right = new_node;
        }

        // make the new node the current node
        current_node = new_node;

        ++sequence_size;
        // reset the enumerator
        reset();
    }

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

    template <
        typename T,
        typename mem_manager
        >
    void sequence_kernel_2<T,mem_manager>::
    remove (
        unsigned long pos,
        T& item
    )
    {
        move_to_pos(current_node,current_pos,pos,sequence_size);
        node& c_node = *current_node;
        exchange(c_node.item,item);

        node* temp = current_node;

        // close up gap left by remove
        c_node.left->right = c_node.right;
        c_node.right->left = c_node.left;

        current_node = c_node.right;

        --sequence_size;

        delete temp;
        // reset the enumerator
        reset();
    }

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

    template <
        typename T,
        typename mem_manager
        >
    const T& sequence_kernel_2<T,mem_manager>::
    operator[] (
        unsigned long pos
    ) const
    {
        move_to_pos(current_node,current_pos,pos,sequence_size);
        return current_node->item;
    }

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

    template <
        typename T,
        typename mem_manager
        >
    void sequence_kernel_2<T,mem_manager>::
    cat (
        sequence_kernel_2<T,mem_manager>& item
    )
    {
        if (item.sequence_size > 0)
        {
            if (sequence_size > 0)
            {
                // move both sequences to a convenient location
                move_to_pos(current_node,current_pos,0,sequence_size);
                item.move_to_pos (
                    item.current_node,
                    item.current_pos,
                    item.sequence_size-1,
                    item.sequence_size
                );

                // make copies of poitners
                node& item_right = *item.current_node->right;
                node& left = *current_node->left;

                item.current_node->right = current_node;
                current_node->left = item.current_node;

                left.right = &item_right;
                item_right.left = &left;

                // set sizes
                sequence_size += item.sequence_size;
                item.sequence_size = 0;
            }
            else
            {
                // *this is empty so just swap
                item.swap(*this);
            }
        }
        item.clear();
        // reset the enumerator
        reset();
    }

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

    template <
        typename T,
        typename mem_manager
        >
    T& sequence_kernel_2<T,mem_manager>::
    operator[] (
        unsigned long pos
    )
    {
        move_to_pos(current_node,current_pos,pos,sequence_size);
        return current_node->item;
    }

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

    template <
        typename T,
        typename mem_manager
        >
    unsigned long sequence_kernel_2<T,mem_manager>::
    size (
    ) const
    {
        return sequence_size;
    }

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

    template <
        typename T,
        typename mem_manager
        >
    void sequence_kernel_2<T,mem_manager>::
    swap (
        sequence_kernel_2<T,mem_manager>& item
    )
    {
        unsigned long   sequence_size_temp         = item.sequence_size;
        node*           current_node_temp          = item.current_node;
        unsigned long   current_pos_temp           = item.current_pos;
        bool            at_start_temp              = item.at_start_;
        node*           current_enumeration_node_temp = item.current_enumeration_node;
        unsigned long   current_enumeration_pos_temp = item.current_enumeration_pos;

        item.sequence_size  = sequence_size;
        item.current_node   = current_node;
        item.current_pos    = current_pos;
        item.at_start_      = at_start_;
        item.current_enumeration_node = current_enumeration_node;
        item.current_enumeration_pos = current_enumeration_pos;

        sequence_size   = sequence_size_temp;
        current_node    = current_node_temp;
        current_pos     = current_pos_temp;
        at_start_       = at_start_temp;
        current_enumeration_node = current_enumeration_node_temp;
        current_enumeration_pos = current_enumeration_pos_temp;
    }

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
    // enumerable function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <
        typename T,
        typename mem_manager
        >
    bool sequence_kernel_2<T,mem_manager>::
    at_start (
    ) const
    {
        return at_start_;
    }

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

    template <
        typename T,
        typename mem_manager
        >
    void sequence_kernel_2<T,mem_manager>::
    reset (
    ) const
    {
        at_start_ = true;
        current_enumeration_node = 0;
    }

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

    template <
        typename T,
        typename mem_manager
        >
    bool sequence_kernel_2<T,mem_manager>::
    current_element_valid (
    ) const
    {
        return (current_enumeration_node!=0);
    }

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

    template <
        typename T,
        typename mem_manager
        >
    const T& sequence_kernel_2<T,mem_manager>::
    element (
    ) const
    {
        return current_enumeration_node->item;
    }

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

    template <
        typename T,
        typename mem_manager
        >
    T& sequence_kernel_2<T,mem_manager>::
    element (
    )
    {
        return current_enumeration_node->item;
    }

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

    template <
        typename T,
        typename mem_manager
        >
    bool sequence_kernel_2<T,mem_manager>::
    move_next (
    ) const
    {
        if (at_start_ && sequence_size>0)
        {
            move_to_pos(current_node,current_pos,0,sequence_size);
            current_enumeration_node = current_node;
            current_enumeration_pos = 0;
        }
        else if (current_enumeration_node!=0)
        {
            ++current_enumeration_pos;
            if (current_enumeration_pos<sequence_size)
            {
                current_enumeration_node = current_enumeration_node->right;
            }
            else
            {
                // we have reached the end of the sequence
                current_enumeration_node = 0;
            }
        }

        at_start_ = false;
        return (current_enumeration_node!=0);
    }

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
    // remover function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <
        typename T,
        typename mem_manager
        >
    void sequence_kernel_2<T,mem_manager>::
    remove_any (
        T& item
    )
    {
        remove(0,item);
    }

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
    // private member function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <
        typename T,
        typename mem_manager
        >
    void sequence_kernel_2<T,mem_manager>::
    delete_nodes (
        node* current_node,
        unsigned long sequence_size
    )
    {
        node* temp;
        while (sequence_size)
        {
            temp = current_node->right;
            delete current_node;
            current_node = temp;
            --sequence_size;
        }
    }

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

    template <
        typename T,
        typename mem_manager
        >
    void sequence_kernel_2<T,mem_manager>::
    move_to_pos (
        node*& current_node,
        unsigned long& current_pos,
        unsigned long pos,
        unsigned long size
    ) const
    {
        if ( current_pos > pos)
        {
            // number of hops in each direction needed to reach pos
            unsigned long right = size + pos - current_pos;
            unsigned long left = current_pos - pos;
            current_pos = pos;

            if (left < right)
            {
                // move left to position pos
                for (; left > 0; --left)
                    current_node = current_node->left;
            }
            else
            {
                // move left to position pos
                for (; right > 0; --right)
                    current_node = current_node->right;
            }
        }
        else if (current_pos != pos)
        {
            // number of hops in each direction needed to reach pos
            unsigned long right = pos - current_pos;
            unsigned long left = size - pos + current_pos;
            current_pos = pos;

            if (left < right)
            {
                // move left to position pos
                for (; left > 0; --left)
                    current_node = current_node->left;
            }
            else
            {
                // move left to position pos
                for (; right > 0; --right)
                    current_node = current_node->right;
            }
        }
    }

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

}

#endif // DLIB_SEQUENCE_KERNEl_2_

redpajama_set_name: RedPajamaGithub


text:
export { createDiscoveryClient } from './discovery-client'
export * from './constants'

export type * from './types'


text:
class DataApiModel {

  constructor(DataDetailSchema) {
    this.DataDetailSchema = DataDetailSchema;
  }

    /**
     * Get all objectId equal id of data
     * @param {string} id , this id is mongodb objectId
     * @returns {promise}
     */
  get(id) {
    const query = {
      dataId: id
    };
    return this.DataDetailSchema.find(query)
            .then((datas) => {
              const result = [];
              const datasLength = datas.length || 0;

              for (let i = 0; i < datasLength; i++) {
                result.push(datas[i].data);
              }
              return Promise.resolve(result);
            }).catch((err) => {
              throw (err);
            });
  }

    /**
     * Get data by id
     * @param {string} id , this id is mongodb objectId
     * @param {string} selectId , this id is restful api get id
     * @returns {promise}
     */
  getById(id, selectId) {
    const query = {
      dataId: id,
      keyId: selectId
    };
    return new Promise((resolve, reject) => {
      this.DataDetailSchema.find(query, (err, datas) => {
        if (err) {
          reject(err);
        } else {
          resolve(datas[0].data);
        }
      });
    });
  }
  getDataKey(id) {

  }
}
module.exports = DataApiModel;


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
  xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
  xmlns:camunda="http://camunda.org/schema/1.0/bpmn"
  targetNamespace="Examples">

  <process id="parentProcess" isExecutable="true">

    <startEvent id="theStart1" />

    <sequenceFlow id="flow1" sourceRef="theStart1" targetRef="callActivity1" />

    <callActivity id="callActivity1" name="Call Activity" calledElement="childProcess" />

    <sequenceFlow id="flow2" sourceRef="callActivity1" targetRef="theEnd1" />

    <endEvent id="theEnd1" />

  </process>

  <process id="childProcess" isExecutable="true">
    <startEvent id="theStart2" />

    <sequenceFlow id="flow3" sourceRef="theStart2" targetRef="waitState1" />

    <receiveTask id="waitState1" name="Wait State 1" />

    <sequenceFlow id="flow4" sourceRef="waitState1" targetRef="theEnd2" />

    <endEvent id="theEnd2" />
  </process>

</definitions>


text:
package rdfxml

import (
	"bytes"
	"encoding/xml"
	"fmt"
	"io"
	"regexp"
	"sort"
	"strings"

	"github.com/google/xtoproto/rdf/iri"
	"github.com/google/xtoproto/rdf/ntriples"
)

const (
	// RDF if the base IRI for RDF terms.
	RDF ntriples.IRI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
)

// IRIs for terms defined in https://www.w3.org/TR/rdf-schema/.
const (
	RDFRoot        ntriples.IRI = RDF + "RDF"
	RDFDescription ntriples.IRI = RDF + "Description"
	RDFLangString  ntriples.IRI = RDF + "langString"
	RDFHTML        ntriples.IRI = RDF + "HTML"
	RDFXMLLiteral  ntriples.IRI = RDF + "XMLLiteral"
	RDFXMLProperty ntriples.IRI = RDF + "XMLProperty"
	RDFID          ntriples.IRI = RDF + "ID"
	RDFNodeID      ntriples.IRI = RDF + "nodeID"
	RDFLI          ntriples.IRI = RDF + "li"
	RDFAbout       ntriples.IRI = RDF + "about"
	RDFType        ntriples.IRI = RDF + "type"
	RDFParseType   ntriples.IRI = RDF + "parseType"
	RDFProperty    ntriples.IRI = RDF + "Property"
	RDFDatatype    ntriples.IRI = RDF + "datatype"
	RDFResource    ntriples.IRI = RDF + "resource"
	RDFSubject     ntriples.IRI = RDF + "subject"
	RDFPredicate   ntriples.IRI = RDF + "predicate"
	RDFObject      ntriples.IRI = RDF + "object"
	RDFStatement   ntriples.IRI = RDF + "Statement"
	RDFNil         ntriples.IRI = RDF + "nil"
	RDFRest        ntriples.IRI = RDF + "rest"
	RDFFirst       ntriples.IRI = RDF + "first"

	xmlNS string = "http://www.w3.org/XML/1998/namespace"
)

// IterationDecision indicates whether an iterating function should stop
// iterating.
type IterationDecision int

// Valid IterationDecision values.
const (
	Stop IterationDecision = iota
	Continue
)

// readTriples decodes triples from an XML token stream.
func readTriples(p *Parser, receiver func(t *ntriples.Triple) (IterationDecision, error)) error {
	p.tripleCallback = receiver
	return readRootOrNodeElem(p)
}

func readRootOrNodeElem(p *Parser) error {
	started, finished := false, false
	for {
		tok, err := p.reader.Token()
		if err == io.EOF {
			if finished {
				return nil
			}
			return fmt.Errorf("unexpected end of file while parsing RDF xml")
		}
		if err != nil {
			return fmt.Errorf("XML error: %v", err)
		}
		switch t := tok.(type) {
		case xml.StartElement:
			if started {
				return p.errorf("internal error? got second start element at root level %+v", t)
			}
			started = true

			if xmlNameToIRI(t.Name) == RDFRoot {
				_, err := p.handleGenericStartElem(t)
				if err != nil {
					return err
				}
				return readNodeElemsAndEndRootElement(p)
			}
			// Otherwise, treat this like reading a regular node element.
			// See https://www.w3.org/TR/rdf-syntax-grammar/#nodeElement.
			_, err := readNodeElem(p, t)
			return err
		case xml.EndElement:
			if xmlNameToIRI(t.Name) != RDFRoot {
				return p.errorf("internal parsing error - only expect an end element when handlng rdf:Root; probably forgot to consume an EndElement elsewhere: %+v", t)
			}
			finished = true
			// end elements should be consumed
		case xml.CharData:
			str := string(t)
			if strings.TrimSpace(str) != "" {
				return p.errorf("unexpected non-whitespace element text %q", str)
			}
		case xml.Comment: // ignore
		case xml.ProcInst: // ignore
		case xml.Directive: // ignore
		}
	}
}

func readNodeElemsAndEndRootElement(p *Parser) error {
	_, err := readNodeElemsAndEndElement(p, RDFRoot)
	return err
}

func readNodeElemsAndEndElement(p *Parser, wantEnd ntriples.IRI) ([]*ntriples.Subject, error) {
	var subjects []*ntriples.Subject
	for {
		tok, err := p.reader.Token()
		if err == io.EOF {
			return nil, fmt.Errorf("unexpected end of file while parsing rdf:Root")
		}
		if err != nil {
			return nil, fmt.Errorf("XML error while parsing rdf:Root: %v", err)
		}
		switch t := tok.(type) {
		case xml.StartElement:
			// Otherwise, treat this like reading a regular node element.
			// See https://www.w3.org/TR/rdf-syntax-grammar/#nodeElement.
			sub, err := readNodeElem(p, t)
			if err != nil {
				return nil, err
			}
			subjects = append(subjects, sub)
		case xml.EndElement:
			if got := xmlNameToIRI(t.Name); got != wantEnd {
				return nil, p.errorf("internal parsing error - got end element %s, want %q; probably forgot to consume an EndElement elsewhere: %+v", got, wantEnd, t)
			}
			return subjects, nil
		case xml.CharData:
			str := string(t)
			if strings.TrimSpace(str) != "" {
				return nil, p.errorf("unexpected non-whitespace element text %q", str)
			}
		case xml.Comment: // ignore
		case xml.ProcInst: // ignore
		case xml.Directive: // ignore
		}
	}
}

// ParserOptions configures a Parser.
type ParserOptions struct {
	// BaseURL to use for the document being parsed.
	BaseURL ntriples.IRI
}

type baseStackEntry struct {
	iri         ntriples.IRI
	declaredIDs map[ntriples.IRI]bool
}

// Parser is an RDF/XML document parser.
type Parser struct {
	reader         xml.TokenReader
	tripleCallback func(t *ntriples.Triple) (IterationDecision, error)
	// TODO(reddaly): Update the way xml:base is treated to respect rules of 2.14:
	// The rdf:ID attribute on a node element (not property element, that has
	// another meaning) can be used instead of rdf:about and gives a relative IRI
	// equivalent to # concatenated with the rdf:ID attribute value. So for
	// example if rdf:ID="name", that would be equivalent to rdf:about="#name".
	// rdf:ID provides an additional check since the same name can only appear
	// once in the scope of an xml:base value (or document, if none is given), so
	// is useful for defining a set of distinct, related terms relative to the
	// same IRI.
	xmlBaseStack       []*baseStackEntry
	langStack          []string
	nextBlankNodeID    int
	observedBlankNodes map[ntriples.BlankNodeID]bool
}

// NewParser returns a new RDF/XML parser that reads from the given xml document
// tr.
func NewParser(tr xml.TokenReader, opts *ParserOptions) *Parser {
	p := &Parser{tr, nil, nil, nil, 0, map[ntriples.BlankNodeID]bool{}}
	if opts != nil && opts.BaseURL != "" {
		p.pushBaseURI(opts.BaseURL)
	}
	return p
}

// ReadAllTriples returns a slice of triples based on all the XML contents of
// the input reader.
func (p *Parser) ReadAllTriples() ([]*ntriples.Triple, error) {
	all := []*ntriples.Triple{}
	err := readTriples(p, func(t *ntriples.Triple) (IterationDecision, error) {
		all = append(all, t)
		return Continue, nil
	})
	return all, err
}

func (p *Parser) errorf(format string, args ...interface{}) error {
	// TODO(reddaly): Add position within xml to error output.
	return fmt.Errorf(format, args...)
}

func (p *Parser) pushBaseURI(baseURI ntriples.IRI) {
	// https://www.ietf.org/rfc/rfc3986.html#section-5.2
	//
	// RDF/XML spec: An empty same document reference "" resolves against the URI
	// part of the base URI; any fragment part is ignored. See Uniform Resource
	// Identifiers (URI) [RFC3986].
	entry := &baseStackEntry{
		iri:         removeFragment(baseURI),
		declaredIDs: map[ntriples.IRI]bool{},
	}
	p.xmlBaseStack = append(p.xmlBaseStack, entry)
}

func removeFragment(baseURI ntriples.IRI) ntriples.IRI {
	s := string(baseURI)
	if idx := strings.IndexRune(s, '#'); idx != -1 {
		return ntriples.IRI(s[0:idx])
	}
	return baseURI
}

func (p *Parser) popBaseURI() {
	p.xmlBaseStack = p.xmlBaseStack[0 : len(p.xmlBaseStack)-1]
}

func (p *Parser) pushLang(lang string) {
	p.langStack = append(p.langStack, lang)
}

func (p *Parser) popLang() {
	p.langStack = p.langStack[0 : len(p.langStack)-1]
}

func (p *Parser) baseURI() ntriples.IRI {
	if len(p.xmlBaseStack) == 0 {
		return ""
	}
	return p.xmlBaseStack[len(p.xmlBaseStack)-1].iri
}

// declareID declares that a nodeElement with the given ID has been encountered
// in the scope of the current xml:base element. If such an ID has already been
// registered in the current scope, an error is returned.
func (p *Parser) declareID(id ntriples.IRI) error {
	if len(p.xmlBaseStack) == 0 {
		return p.errorf("internal error - empty base stack")
	}
	entry := p.xmlBaseStack[len(p.xmlBaseStack)-1]
	if entry.declaredIDs[id] {
		return p.errorf("duplicate node element id within same xml:base scope; see section 2.14 of the RDF/XML spec <https://www.w3.org/TR/rdf-syntax-grammar/#nodeElementURIs>; offending id = %s", id)
	}
	return nil
}

func (p *Parser) language() string {
	if len(p.langStack) == 0 {
		return "" // according to 6.1, language is set to the empty string.
	}
	return p.langStack[len(p.langStack)-1]
}

func (p *Parser) generateBlankNodeID() ntriples.BlankNodeID {
	for {
		p.nextBlankNodeID++
		candidate := ntriples.BlankNodeID(fmt.Sprintf("gen-%d", p.nextBlankNodeID))
		if p.observedBlankNodes[candidate] {
			continue
		}
		return candidate
	}
}

func (p *Parser) generateBlankNodeIDWithHint(hint string) ntriples.BlankNodeID {
	for {
		p.nextBlankNodeID++
		candidate := ntriples.BlankNodeID(fmt.Sprintf("gen-%d-%s", p.nextBlankNodeID, hint))
		if p.observedBlankNodes[candidate] {
			continue
		}
		return candidate
	}
}

// handleGenericStartElem updaters the parser's state based on generic
// attributes of the start element, like "xml:base" and returns a function that
// handles the closing of the element.
func (p *Parser) handleGenericStartElem(elem xml.StartElement) (func() error, error) {
	var base, lang *string
	for _, attr := range elem.Attr {
		if attr.Name.Space == xmlNS && attr.Name.Local == "base" {
			v := attr.Value
			base = &v
		}
		if attr.Name.Space == xmlNS && attr.Name.Local == "lang" {
			v := attr.Value
			lang = &v
		}
	}
	if base != nil {
		baseIRI, err := parseIRI(*base)
		if err != nil {
			return nil, p.errorf("xml:base value invalid: %w", err)
		}
		p.pushBaseURI(baseIRI)
	}
	if lang != nil {
		p.pushLang(*lang)
	}
	return func() error {
		if base != nil {
			p.popBaseURI()
		}
		if lang != nil {
			p.popLang()
		}
		return nil
	}, nil
}

func readNodeElem(p *Parser, start xml.StartElement) (*ntriples.Subject, error) {
	return readNodeElemUsingSubject(p, start, nil)
}

// readNodeElemUsingSubject decodes triples from an XML token stream.
//
// The forceSubject argument may be nil, in which case the subject is
// determined based on the element and its attributes.
func readNodeElemUsingSubject(p *Parser, start xml.StartElement, forcedSubject *ntriples.Subject) (*ntriples.Subject, error) {
	handleCloseElem, err := p.handleGenericStartElem(start)
	if err != nil {
		return nil, err
	}
	// From the spec:
	//
	// If there is an attribute a with a.URI == rdf:ID, then e.subject :=
	// uri(identifier := resolve(e, concat("#", a.string-value))).
	//
	// If there is an attribute a with a.URI == rdf:nodeID, then e.subject :=
	// bnodeid(identifier:=a.string-value).
	//
	// If there is an attribute a with a.URI == rdf:about then e.subject :=
	// uri(identifier := resolve(e, a.string-value)).
	//
	// If e.subject is empty, then e.subject := bnodeid(identifier :=
	// generated-blank-node-id()).

	subject := forcedSubject

	if forcedSubject == nil {
		if err := checkNodeElementURI(xmlNameToIRI(start.Name)); err != nil {
			return nil, err
		}
	}

	propAttrs, _, idAttrs, err := parsePropertyAttributes(start.Attr)
	if err != nil {
		return nil, p.errorf("bad attributes while parsing %+v: %w", start, err)
	}
	for _, attr := range idAttrs {
		switch xmlNameToIRI(attr.Name) {
		case RDFID:
			subIRI, err := resolve(p, "#"+attr.Value)
			if err != nil {
				return nil, p.errorf("bad IRI for rdf:Description's rdf:ID attribute: %w", err)
			}
			if err := p.declareID(subIRI); err != nil {
				return nil, err
			}
			newSubject := ntriples.NewSubjectIRI(subIRI)
			if subject != nil {
				return nil, p.errorf("ambiguous subject: %s and %s", subject, newSubject)
			}
			subject = ntriples.NewSubjectIRI(subIRI)
		case RDFNodeID:
			if err := checkXMLNCName(attr.Value); err != nil {
				return nil, p.errorf("invalid rdf:nodeID parameter: %w", err)
			}
			blankID, err := parseBlankNodeID(attr.Value)
			if err != nil {
				return nil, p.errorf("bad IRI for rdf:Description's rdf:NodeID attribute: %w", err)
			}
			newSubject := ntriples.NewSubjectBlankNodeID(blankID)
			if subject != nil {
				return nil, p.errorf("ambiguous subject: %s and %s", subject, newSubject)
			}
			subject = newSubject
		case RDFAbout:
			subIRI, err := resolve(p, attr.Value)
			if err != nil {
				return nil, p.errorf("bad IRI for rdf:Description's rdf:about attribute: %w", err)
			}
			newSubject := ntriples.NewSubjectIRI(subIRI)
			if subject != nil {
				return nil, p.errorf("ambiguous subject: %s and %s", subject, newSubject)
			}
			subject = newSubject
		default:
			// ignore
		}
	}
	if subject == nil {
		subject = ntriples.NewSubjectBlankNodeID(p.generateBlankNodeID())
	}

	eURI := xmlNameToIRI(start.Name)
	if forcedSubject != nil {
		eURI = RDFDescription
	}
	// If e.URI != rdf:Description then the following statement is added to the graph:
	//
	// e.subject.string-value <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> e.URI-string-value .
	if eURI != RDFDescription {
		triple := ntriples.NewTriple(subject, RDFType, ntriples.NewObjectIRI(eURI))
		ind, err := p.tripleCallback(triple)
		if err != nil {
			return nil, p.errorf("triple callback error: %w", err)
		}
		if ind == Stop {
			return subject, nil
		}
	}

	// For each attribute a matching propertyAttr (and not rdf:type), the Unicode
	// string a.string-value should be in Normal Form C [NFC], o :=
	// literal(literal-value := a.string-value, literal-language := e.language)
	// and the following statement is added to the graph:
	for _, attr := range propAttrs {
		switch attrIRI := xmlNameToIRI(attr.Name); attrIRI {
		case RDFType:
			objectIRI, err := resolve(p, attr.Value)
			if err != nil {
				return nil, p.errorf("error parsing rdf:type attribute value: %w", err)
			}
			triple := ntriples.NewTriple(subject, RDFType, ntriples.NewObjectIRI(objectIRI))
			ind, err := p.tripleCallback(triple)
			if err != nil {
				return nil, p.errorf("triple callback error: %w", err)
			}
			if ind == Stop {
				return subject, nil
			}
		default:
			objectLiteral, err := parseLiteral(p, attr.Value)
			if err != nil {
				return nil, p.errorf("bad literal for attribute %+v: %w", attr, err)
			}
			triple := ntriples.NewTriple(subject, attrIRI, ntriples.NewObjectLiteral(objectLiteral))
			ind, err := p.tripleCallback(triple)
			if err != nil {
				return nil, p.errorf("triple callback error: %w", err)
			}
			if ind == Stop {
				return subject, nil
			}
		}
	}
	if err := readPropertyElems(p, start.Name, subject); err != nil {
		return nil, err
	}
	if err := handleCloseElem(); err != nil {
		return nil, err
	}
	return subject, nil
}

// readPropertyElems parses the property elements of a nodeElem per
// https://www.w3.org/TR/rdf-syntax-grammar/#propertyElt.
func readPropertyElems(p *Parser, startElemName xml.Name, subject *ntriples.Subject) error {
	liCounter := 1
	for {
		tok, err := p.reader.Token()
		if err == io.EOF {
			return p.errorf("unexpected EOF while reading property elem")
		}
		if err != nil {
			return p.errorf("XML error: %w", err)
		}
		switch t := tok.(type) {
		case xml.StartElement:
			err := readPropertyElem(p, &liCounter, subject, t)
			if err != nil {
				return err
			}
		case xml.EndElement:
			if t.Name != startElemName {
				return p.errorf("unexpected end element while reading property elements of %+v (%s): got unexpected end element %+v", startElemName, subject, t.Name)
			}
			return nil
		case xml.CharData:
		case xml.Comment: // ignore
		case xml.ProcInst: // ignore
		case xml.Directive: // ignore aside from the usual handling
		}
	}
}

// readPropertyElems parses the property elements of a nodeElem per
// https://www.w3.org/TR/rdf-syntax-grammar/#propertyElt.
func readPropertyElemInternal(p *Parser, liCounter *int, subject *ntriples.Subject, propElem xml.StartElement) error {
	elemURI := xmlNameToIRI(propElem.Name)
	if err := checkPropertyElementURI(elemURI); err != nil {
		return p.errorf("bad property element %+v: %w", propElem, err)
	}
	switch elemURI {
	case RDFLI:
		elemURI = ntriples.IRI(fmt.Sprintf("%s_%d", string(RDF), *liCounter))
		*liCounter++
	}
	parseType, hasParseType, err := processParseTypeAttr(propElem)
	if err != nil {
		return p.errorf("bad property element %+v: %w", propElem.Name, err)
	}
	if hasParseType {
		switch parseType {
		case "Resource":
			// Section 7.2.18: https://www.w3.org/TR/rdf-syntax-grammar/#parseTypeResourcePropertyElt
			// n := bnodeid(identifier := generated-blank-node-id()).
			// Add the following statement to the graph:
			// e.parent.subject.string-value e.URI-string-value n.string-value .
			n := p.generateBlankNodeID()
			triple := ntriples.NewTriple(subject, elemURI, ntriples.NewObjectBlankNodeID(n))
			ind, err := p.tripleCallback(triple)
			if err != nil {
				return p.errorf("triple callback error: %w", err)
			}
			if ind == Stop {
				return nil
			}
			if attr := findAttr(propElem, RDFID); attr != nil {
				i, err := resolve(p, "#"+attr.Value)
				if err != nil {
					return err
				}
				ind, err := emitReifiedTriple(p, triple, ntriples.NewSubjectIRI(i))
				if err != nil {
					return p.errorf("triple callback error: %w", err)
				}
				if ind == Stop {
					return nil
				}
			}
			var badAttributes []string
			for _, attr := range rdfAttributes(propElem.Attr) {
				attrIRI := xmlNameToIRI(attr.Name)
				if attrIRI == RDFID || attrIRI == RDFParseType {
					continue
				}
				badAttributes = append(badAttributes, attr.Name.Local)
			}
			if len(badAttributes) != 0 {
				sort.Strings(badAttributes)
				return fmt.Errorf("unexpected attributes for rdf:parseType='Resource': only allowed to have an rdf:id and rdf:parseType attribute, got %d extras: %s", len(badAttributes), strings.Join(badAttributes, ","))
			}
			propElemNoAttrs := propElem.Copy()
			propElemNoAttrs.Attr = nil

			if _, err := readNodeElemUsingSubject(p, propElemNoAttrs, ntriples.NewSubjectBlankNodeID(n)); err != nil {
				return p.errorf("failed while processing parseTypeResourcePropertyElt: of %s: %w", subject, err)
			}

			return nil
		case "Collection":
			return readSequencePropertyElem(p, subject, propElem, elemURI)
		case "Literal":
			fallthrough
		default: // unrecognized parseType is treated as a "Literal" per spec
			contents, err := readElementContents(p)
			if err != nil {
				return p.errorf("failed to get literal contents from parseType=%q: %w", parseType, err)
			}
			literal := ntriples.NewLiteral(string(contents), RDFXMLLiteral, "")
			triple := ntriples.NewTriple(subject, elemURI, ntriples.NewObjectLiteral(literal))
			ind, err := p.tripleCallback(triple)
			if err != nil {
				return p.errorf("triple callback error: %w", err)
			}
			if ind == Stop {
				return nil
			}
			if attr := findAttr(propElem, RDFID); attr != nil {
				i, err := resolve(p, "#"+attr.Value)
				if err != nil {
					return err
				}
				ind, err := emitReifiedTriple(p, triple, ntriples.NewSubjectIRI(i))
				if err != nil {
					return p.errorf("triple callback error: %w", err)
				}
				if ind == Stop {
					return nil
				}
			}
		}
		return nil
	}
	childInfo, err := readNextChildOfPropertyElement(p)
	if err != nil {
		return err
	}
	if childInfo.nodeElemStart != nil {
		// 7.2.15: Production resourcePropertyElt
		valueSubject, err := readNodeElem(p, *childInfo.nodeElemStart)
		if err != nil {
			return p.errorf("failed to parse resourcePropertyElt %s property of %s: %w", xmlNameToIRI(childInfo.nodeElemStart.Name), subject, err)
		}
		if err := readWhitespaceUntilEndElem(p, &propElem); err != nil {
			return p.errorf("failed to parse resourcePropertyElt %s property of %s: %w", xmlNameToIRI(childInfo.nodeElemStart.Name), subject, err)
		}
		// e.parent.subject.string-value e.URI-string-value n.subject.string-value .

		triple := ntriples.NewTriple(subject, elemURI, ntriples.NewObjectFromSubject(valueSubject))
		ind, err := p.tripleCallback(triple)
		if err != nil {
			return p.errorf("triple callback error: %w", err)
		}
		if ind == Stop {
			return nil
		}

		// 7.2.15: If the rdf:ID attribute a is given, the above statement is
		// reified with i := uri(identifier := resolve(e, concat("#",
		// a.string-value))) using the reification rules in section 7.3 and
		// e.subject := i.
		if attr := findAttr(propElem, RDFID); attr != nil {
			i, err := resolve(p, "#"+attr.Value)
			if err != nil {
				return err
			}
			ind, err := emitReifiedTriple(p, triple, ntriples.NewSubjectIRI(i))
			if err != nil {
				return p.errorf("triple callback error: %w", err)
			}
			if ind == Stop {
				return nil
			}
		}
		return nil
	}

	if childInfo.isEmptyProperty {
		// 7.2.21 Production emptyPropertyElt
		idAttr, _, _, _, propAttrs, attrCount, err := parseEmptyPropertyElementAttributes(propElem.Attr)
		if err != nil {
			return p.errorf("error processing attributs of empty literal property: %w", err)
		}

		if attrCount == 0 || (attrCount == 1 && idAttr != nil) {
			// If there are no attributes or only the optional rdf:ID attribute i then
			// o := literal(literal-value:="", literal-language := e.language) and the
			// following statement is added to the graph:
			// e.parent.subject.string-value e.URI-string-value o.string-value .
			literal, err := parseLiteral(p, "")
			if err != nil {
				return p.errorf("error emitting empty literal property: %w", err)
			}
			triple := ntriples.NewTriple(subject, elemURI, ntriples.NewObjectLiteral(literal))
			ind, err := p.tripleCallback(triple)
			if err != nil {
				return p.errorf("triple callback error: %w", err)
			}
			if ind == Stop {
				return nil
			}
			// 7.2.21: f rdf:ID attribute i is given, the above statement is reified
			// with uri(identifier := resolve(e, concat("#", i.string-value))) using
			// the reification rules in section 7.3.
			if idAttr != nil {
				i, err := resolve(p, "#"+idAttr.Value)
				if err != nil {
					return err
				}
				ind, err := emitReifiedTriple(p, triple, ntriples.NewSubjectIRI(i))
				if err != nil {
					return p.errorf("triple callback error: %w", err)
				}
				if ind == Stop {
					return nil
				}
			}
		} else {
			// If rdf:resource attribute i is present, then r := uri(identifier := resolve(e, i.string-value))
			// If rdf:nodeID attribute i is present, then r := bnodeid(identifier := i.string-value)
			// If neither, r := bnodeid(identifier := generated-blank-node-id())
			attrs := rdfAttributes(propElem.Attr)
			r, err := parseEmptyPropertyResource(p, attrs)
			if err != nil {
				return err
			}
			for _, propAttr := range propAttrs {
				var triple1 *ntriples.Triple
				propAsIRI := xmlNameToIRI(propAttr.Name)
				if propAsIRI == RDFType {
					typeIRI, err := resolve(p, propAttr.Value)
					if err != nil {
						return err
					}
					triple1 = ntriples.NewTriple(r, RDFType, ntriples.NewObjectIRI(typeIRI))
				} else {
					lit, err := parseLiteral(p, propAttr.Value)
					if err != nil {
						return err
					}
					triple1 = ntriples.NewTriple(r, propAsIRI, ntriples.NewObjectLiteral(lit))
				}
				ind, err := p.tripleCallback(triple1)
				if err != nil {
					return p.errorf("triple callback error: %w", err)
				}
				if ind == Stop {
					return nil
				}
			}

			triple := ntriples.NewTriple(subject, elemURI, ntriples.NewObjectFromSubject(r))
			ind, err := p.tripleCallback(triple)
			if err != nil {
				return p.errorf("triple callback error: %w", err)
			}
			if ind == Stop {
				return nil
			}
			// Reification. 7.2.21: If rdf:ID attribute i is given, the
			// above statement is reified with uri(identifier := resolve(e,
			// concat("#", i.string-value))) using the reification rules in section
			// 7.3.

			if idAttr != nil {
				i, err := resolve(p, "#"+idAttr.Value)
				if err != nil {
					return err
				}
				ind, err := emitReifiedTriple(p, triple, ntriples.NewSubjectIRI(i))
				if err != nil {
					return p.errorf("triple callback error: %w", err)
				}
				if ind == Stop {
					return nil
				}
			}
		}
		return nil
	}

	// 7.2.16 Production literalPropertyElt
	var literal ntriples.Literal
	idAttr, dtAttr, err := parseLiteralPropertyElementAttributes(propElem.Attr)
	if err != nil {
		return p.errorf("bad literalPropertyElt: %w", err)
	}
	if dtAttr != nil {
		datatype, err := parseIRI(dtAttr.Value)
		if err != nil {
			return err
		}
		literal = ntriples.NewLiteral(childInfo.text, datatype, "")
	} else {
		literal, err = parseLiteral(p, childInfo.text)
		if err != nil {
			return err
		}
	}
	triple := ntriples.NewTriple(subject, elemURI, ntriples.NewObjectLiteral(literal))
	ind, err := p.tripleCallback(triple)
	if err != nil {
		return p.errorf("triple callback error: %w", err)
	}
	if ind == Stop {
		return nil
	}
	if idAttr != nil {
		i, err := resolve(p, "#"+idAttr.Value)
		if err != nil {
			return err
		}
		ind, err := emitReifiedTriple(p, triple, ntriples.NewSubjectIRI(i))
		if err != nil {
			return p.errorf("triple callback error: %w", err)
		}
		if ind == Stop {
			return nil
		}
	}
	// The end element was read

	return nil
}

func readSequencePropertyElem(p *Parser, subject *ntriples.Subject, propElem xml.StartElement, propElemURI ntriples.IRI) error {
	// Section 7.2.19
	emittedSubjects, err := readNodeElemsAndEndElement(p, xmlNameToIRI(propElem.Name))
	if err != nil {
		return err
	}
	if len(emittedSubjects) == 0 {
		triple := ntriples.NewTriple(subject, propElemURI, ntriples.NewObjectIRI(RDFNil))
		ind, err := p.tripleCallback(triple)
		if err != nil || ind == Stop {
			return err
		}
		if attr := findAttr(propElem, RDFID); attr != nil {
			i, err := resolve(p, "#"+attr.Value)
			if err != nil {
				return err
			}
			if ind, err := emitReifiedTriple(p, triple, ntriples.NewSubjectIRI(i)); err != nil || ind == Stop {
				return err
			}
		}
		return nil
	}
	seqID := p.generateBlankNodeIDWithHint("first-in-seq")
	{
		triple := ntriples.NewTriple(subject, propElemURI, ntriples.NewObjectBlankNodeID(seqID))
		ind, err := p.tripleCallback(triple)
		if err != nil || ind == Stop {
			return err
		}
		if attr := findAttr(propElem, RDFID); attr != nil {
			i, err := resolve(p, "#"+attr.Value)
			if err != nil {
				return err
			}
			if ind, err := emitReifiedTriple(p, triple, ntriples.NewSubjectIRI(i)); err != nil || ind == Stop {
				return err
			}
		}
	}

	isFirst := true
	for i, emittedSub := range emittedSubjects {
		nextSeqID := p.generateBlankNodeIDWithHint(fmt.Sprintf("cons-%d", i))
		if !isFirst {
			triple := ntriples.NewTriple(ntriples.NewSubjectBlankNodeID(seqID), RDFRest, ntriples.NewObjectBlankNodeID(nextSeqID))
			ind, err := p.tripleCallback(triple)
			if err != nil || ind == Stop {
				return err
			}
		}
		isFirst = false
		seqID = nextSeqID
		triple := ntriples.NewTriple(ntriples.NewSubjectBlankNodeID(seqID), RDFFirst, ntriples.NewObjectFromSubject(emittedSub))
		ind, err := p.tripleCallback(triple)
		if err != nil || ind == Stop {
			return err
		}
	}

	triple := ntriples.NewTriple(ntriples.NewSubjectBlankNodeID(seqID), RDFRest, ntriples.NewObjectIRI(RDFNil))
	_, err = p.tripleCallback(triple)
	return err
}

// readPropertyElems parses the property elements of a nodeElem per
// https://www.w3.org/TR/rdf-syntax-grammar/#propertyElt.
func readPropertyElem(p *Parser, liCounter *int, subject *ntriples.Subject, propElem xml.StartElement) error {
	handleCloseElem, err := p.handleGenericStartElem(propElem)
	if err != nil {
		return err
	}
	if err := readPropertyElemInternal(p, liCounter, subject, propElem); err != nil {
		return err
	}
	if err := handleCloseElem(); err != nil {
		return err
	}

	return nil
}

// readPropertyElems parses the property elements of a nodeElem per
// https://www.w3.org/TR/rdf-syntax-grammar/#propertyElt.
func emitReifiedTriple(p *Parser, tr *ntriples.Triple, tripleID *ntriples.Subject) (IterationDecision, error) {
	reifiedTriples := []*ntriples.Triple{
		// r.string-value <http://www.w3.org/1999/02/22-rdf-syntax-ns#subject> s .
		ntriples.NewTriple(tripleID, RDFSubject, ntriples.NewObjectFromSubject(tr.Subject())),
		// r.string-value <http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate> p .
		ntriples.NewTriple(tripleID, RDFPredicate, ntriples.NewObjectIRI(tr.Predicate())),
		// r.string-value <http://www.w3.org/1999/02/22-rdf-syntax-ns#object> o .
		ntriples.NewTriple(tripleID, RDFObject, tr.Object()),
		// r.string-value <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement> .
		ntriples.NewTriple(tripleID, RDFType, ntriples.NewObjectIRI(RDFStatement)),
	}
	for _, x := range reifiedTriples {
		ind, err := p.tripleCallback(x)
		if err != nil {
			return Stop, p.errorf("triple callback error: %w", err)
		}
		if ind == Stop {
			return ind, nil
		}
	}
	return Continue, nil
}

func parseEmptyPropertyResource(p *Parser, attrs []xml.Attr) (*ntriples.Subject, error) {
	// From the spec:
	//
	// If rdf:resource attribute i is present, then r := uri(identifier := resolve(e, i.string-value))
	// If rdf:nodeID attribute i is present, then r := bnodeid(identifier := i.string-value)
	// If neither, r := bnodeid(identifier := generated-blank-node-id())
	var subject *ntriples.Subject

	for _, attr := range rdfAttributes(attrs) {
		switch xmlNameToIRI(attr.Name) {
		case RDFResource:
			subIRI, err := resolve(p, attr.Value)
			if err != nil {
				return nil, p.errorf("bad IRI for rdf:Description's rdf:ID attribute: %w", err)
			}
			newSubject := ntriples.NewSubjectIRI(subIRI)
			if subject != nil {
				return nil, p.errorf("ambiguous subject: %s and %s", subject, newSubject)
			}
			subject = ntriples.NewSubjectIRI(subIRI)
		case RDFNodeID:
			if err := checkXMLNCName(attr.Value); err != nil {
				return nil, p.errorf("invalid rdf:nodeID parameter: %w", err)
			}
			blankID, err := parseBlankNodeID(attr.Value)
			if err != nil {
				return nil, p.errorf("bad IRI for rdf:Description's rdf:NodeID attribute: %w", err)
			}
			newSubject := ntriples.NewSubjectBlankNodeID(blankID)
			if subject != nil {
				return nil, p.errorf("ambiguous subject: %s and %s", subject, newSubject)
			}
			subject = newSubject
		default:
			// ignore
		}
	}
	if subject == nil {
		subject = ntriples.NewSubjectBlankNodeID(p.generateBlankNodeID())
	}
	return subject, nil
}

// propertyElemParseInfo is used to hold the results of parsing a
// propertyElem's
type propertyElemParseInfo struct {
	// set to the first StartElement if one is encountered. Indicates that the
	// property elem is a resourcePropertyElt.
	nodeElemStart *xml.StartElement
	// concatenation of all CharData within the element.
	text string
	// true for the production emptyPropertyElt
	isEmptyProperty bool
}

func readNextChildOfPropertyElement(p *Parser) (*propertyElemParseInfo, error) {
	textBuilder := &strings.Builder{}
	for {
		tok, err := p.reader.Token()
		if err != nil {
			return nil, p.errorf("XML read error: %w", err)
		}
		switch t := tok.(type) {
		case xml.EndElement:
			text := textBuilder.String()
			return &propertyElemParseInfo{
				text:            text,
				isEmptyProperty: len(text) == 0,
			}, nil

		case xml.CharData:
			if _, err := textBuilder.Write([]byte(t)); err != nil {
				return nil, err
			}
		case xml.StartElement:
			text := textBuilder.String()
			if strings.TrimSpace(text) != "" {
				return nil, p.errorf("got start element %s for property and also non-whitespace element text %q", xmlNameToIRI(t.Name), text)
			}
			return &propertyElemParseInfo{
				nodeElemStart: &t,
			}, nil
		default:
			// Skip comments and other types
		}
	}
}

// resolve returns "a string created by interpreting string s as a relative IRI
// to the ·base-uri· accessor of 6.1.2 Element Event e as defined in Section 5.3
// Resolving URIs. The resulting string represents an IRI."
//
// The spec also says:
//
// RDF/XML supports XML Base [XMLBASE] which defines a ·base-uri· accessor for
// each ·root event· and ·element event·. Relative IRIs are resolved into IRIs
// according to the algorithm specified in [XMLBASE] (and RFC 2396). These
// specifications do not specify an algorithm for resolving a fragment
// identifier alone, such as #foo, or the empty string "" into an IRI. In
// RDF/XML, a fragment identifier is transformed into an IRI by appending the
// fragment identifier to the in-scope base URI. The empty string is transformed
// into an IRI by substituting the in-scope base URI.
func resolve(p *Parser, s string) (ntriples.IRI, error) {
	if s == "" {
		return p.baseURI(), nil
	}
	sIRI, err := iri.Parse(s)
	if err != nil {
		return "", fmt.Errorf("error parsing %q as IRI: %w", s, err)
	}
	return p.baseURI().ResolveReference(sIRI).NormalizePercentEncoding(), nil
}

func parseLiteral(p *Parser, s string) (ntriples.Literal, error) {
	lang := p.language()
	if lang == "" {
		return ntriples.NewLiteral(s, ntriples.XMLSchemaString, ""), nil
	}
	return ntriples.NewLiteral(s, "", lang), nil
}

func parseIRI(s string) (ntriples.IRI, error) {
	unnormalized, err := iri.Parse(s)
	if err != nil {
		return "", err
	}
	return unnormalized.NormalizePercentEncoding(), err
}

func parseBlankNodeID(s string) (ntriples.BlankNodeID, error) {
	// TODO(reddaly): Check blank node id syntax.
	value := ntriples.BlankNodeID(s)
	return value, nil
}

func xmlNameToIRI(n xml.Name) ntriples.IRI {
	return ntriples.IRI(n.Space + n.Local)
}

func findAttr(elem xml.StartElement, iri ntriples.IRI) *xml.Attr {
	for i, attr := range elem.Attr {
		if xmlNameToIRI(attr.Name) == iri {
			return &elem.Attr[i]
		}
	}
	return nil
}

// readElementContents reads the text contents of the element until the
// end element is found.
func readElementContents(p *Parser) ([]byte, error) {
	buf := &bytes.Buffer{}
	enc := xml.NewEncoder(buf)
	depth := 0
	for {
		tok, err := p.reader.Token()
		if err != nil {
			return nil, p.errorf("XML read error: %w", err)
		}
		switch tok.(type) {
		case xml.EndElement:
			if depth == 0 {
				if err := enc.Flush(); err != nil {
					return nil, p.errorf("XML printing error: %w", err)
				}
				return buf.Bytes(), nil
			}
			depth--
		case xml.StartElement:
			depth++
		}
		if err := enc.EncodeToken(tok); err != nil {
			return nil, p.errorf("XML printing error: %w", err)
		}
	}
}

func readWhitespaceUntilEndElem(p *Parser, startElem *xml.StartElement) error {
	for {
		tok, err := p.reader.Token()
		if err != nil {
			return p.errorf("XML read error: %w", err)
		}
		switch t := tok.(type) {
		case xml.EndElement:
			if startElem != nil && t.Name != startElem.Name {
				return p.errorf("unexpected end elem %+v does not match start elem %+v", t.Name, startElem.Name)
			}
			return nil
		case xml.CharData:
			nonWS := strings.TrimSpace(string(t))
			if len(nonWS) != 0 {
				return p.errorf("expected only whitespace in contents, got %q", nonWS)
			}
		case xml.StartElement:
			return p.errorf("expected whitespace, got start of element %+v", t)
		default:
			// ignore
		}
	}
}

var startWithXMLRegexp = regexp.MustCompile(`^(?i)xml`)

// rdfAttributes returns all the attributes that should be considered as the
// attributes of an element according to the RDF/XML spec.
func rdfAttributes(attrs []xml.Attr) []xml.Attr {
	// Made from the value of element information item property [attributes] which
	// is a set of attribute information items.
	//
	// If this set contains an attribute information item xml:lang ( [namespace
	// name] property with the value "http://www.w3.org/XML/1998/namespace" and
	// [local name] property value "lang") it is removed from the set of attribute
	// information items and the ·language· accessor is set to the
	// [normalized-value] property of the attribute information item.
	//
	// All remaining reserved XML Names (see Name in XML 1.0) are now removed from
	// the set. These are, all attribute information items in the set with
	// property [prefix] beginning with xml (case independent comparison) and all
	// attribute information items with [prefix] property having no value and
	// which have [local name] beginning with xml (case independent comparison)
	// are removed. Note that the [base URI] accessor is computed by XML Base
	// before any xml:base attribute information item is deleted.
	//
	// The remaining set of attribute information items are then used to construct
	// a new set of Attribute Events which is assigned as the value of this
	// accessor.
	return filterAttrs(attrs, func(a xml.Attr) bool {
		return !isXMLAttr(a.Name)
	})
}

func parsePropertyAttributes(allAttrs []xml.Attr) (propAttrs, xmlAttrs, idAttrs []xml.Attr, err error) {
	var badTerms []string
	for _, a := range allAttrs {
		if isXMLAttr(a.Name) {
			xmlAttrs = append(xmlAttrs, a)
			continue
		}
		uri := xmlNameToIRI(a.Name)
		switch uri {
		case RDFID, RDFNodeID, RDFAbout:
			idAttrs = append(idAttrs, a)
			continue
		}
		if isPropertyAttr(a.Name) {
			propAttrs = append(propAttrs, a)
			continue
		}
		badTerms = append(badTerms, a.Name.Local)
	}
	if len(badTerms) != 0 {
		return nil, nil, nil, fmt.Errorf("got %d bad attributes: %s", len(badTerms), strings.Join(badTerms, ", "))
	}
	if len(idAttrs) > 1 {
		return nil, nil, nil, fmt.Errorf("can only have one of rdf:id, rdf:nodeID, rdf:about, got %v", idAttrs)
	}
	return
}

func processParseTypeAttr(propElem xml.StartElement) (string, bool, error) {
	parseTypeAttr := findAttr(propElem, RDFParseType)
	if parseTypeAttr == nil {
		return "", false, nil
	}
	// Otherwise, only tolerate the ID attribute and the parseType attribute.
	var badAttrs []string
	for _, a := range propElem.Attr {
		if isXMLAttr(a.Name) {
			continue
		}
		attrIRI := xmlNameToIRI(a.Name)
		switch attrIRI {
		case RDFID, RDFParseType:
			continue
		default:
			badAttrs = append(badAttrs, a.Name.Local)
		}
	}
	if len(badAttrs) != 0 {
		return "", false, fmt.Errorf("property element with parseType attribute cannot have these attributes - see section 7.2.17-7.2.19 of the spec: %s", strings.Join(badAttrs, ", "))
	}
	return parseTypeAttr.Value, true, nil
}

func parseLiteralPropertyElementAttributes(allAttrs []xml.Attr) (id, datatype *xml.Attr, err error) {
	var badTerms []string
	for _, a := range allAttrs {
		a := a
		if isXMLAttr(a.Name) {
			continue
		}
		uri := xmlNameToIRI(a.Name)
		switch uri {
		case RDFID:
			id = &a
		case RDFDatatype:
			datatype = &a
		default:
			badTerms = append(badTerms, a.Name.Local)
		}
	}
	if len(badTerms) != 0 {
		return nil, nil, fmt.Errorf("got %d extra attributes in literal property element: %s", len(badTerms), strings.Join(badTerms, ", "))
	}
	return
}

func parseEmptyPropertyElementAttributes(allAttrs []xml.Attr) (id, resource, nodeID, datatype *xml.Attr, propertyAttrs []xml.Attr, attrCount int, err error) {
	// 7.2.21 Production emptyPropertyElt
	var badTerms []string
	xorCount := 0
	for _, a := range allAttrs {
		a := a
		if isXMLAttr(a.Name) {
			continue
		}
		attrCount++
		uri := xmlNameToIRI(a.Name)
		switch uri {
		case RDFID:
			id = &a
		case RDFDatatype:
			datatype = &a
			xorCount++
		case RDFNodeID:
			if err := checkXMLNCName(a.Value); err != nil {
				return nil, nil, nil, nil, nil, 0, fmt.Errorf("invalid rdf:nodeID parameter: %w", err)
			}
			nodeID = &a
			xorCount++
		case RDFResource:
			resource = &a
			xorCount++
		default:
			if !isPropertyAttr(a.Name) {
				badTerms = append(badTerms, a.Name.Local)
				continue
			}
			propertyAttrs = append(propertyAttrs, a)
		}
	}
	if len(badTerms) != 0 {
		err = fmt.Errorf("got %d extra attributes in literal property element: %s", len(badTerms), strings.Join(badTerms, ", "))
		return
	}
	if xorCount > 1 {
		err = fmt.Errorf("got more than one of rdf:NodeID, rdf:Resource, rdf:datatype: %v", allAttrs)
		return
	}
	return
}

// filterAttrs returns all of the attributes that pass a predicate function
func filterAttrs(attrs []xml.Attr, pred func(xml.Attr) bool) []xml.Attr {
	var out []xml.Attr
	for _, a := range attrs {
		if !pred(a) {
			continue
		}
		out = append(out, a)
	}
	return out
}

var beginsWithXMLExpr = regexp.MustCompile(`^(?i)xml`)
var xmlnsRE = regexp.MustCompile(`^(?i)` + regexp.QuoteMeta(xmlNS))

func isXMLAttr(name xml.Name) bool {
	return xmlnsRE.MatchString(name.Space) || beginsWithXMLExpr.MatchString(name.Local) || beginsWithXMLExpr.MatchString(name.Space)
}

func isPropertyAttr(name xml.Name) bool {
	term := xmlNameToIRI(name)
	switch term {
	case RDFDescription, RDFLI:
		return false
	default:
		return !coreSyntaxTerms[term] && !oldTerms[term]
	}
}

func checkNodeElementURI(name ntriples.IRI) error {
	// 7.2.5 Production nodeElementURIs
	// https://www.w3.org/TR/rdf-syntax-grammar/#nodeElementURIs
	bad := false
	switch name {
	case RDFLI:
		bad = true
	default:
		bad = coreSyntaxTerms[name] || oldTerms[name]
	}
	if bad {
		return fmt.Errorf("invalid RDF node element name %s", name)
	}
	return nil
}

func checkPropertyElementURI(name ntriples.IRI) error {
	if coreSyntaxTerms[name] {
		return fmt.Errorf("a core rdf syntax term may not be used as a property element name: %s", name)
	}
	if oldTerms[name] {
		return fmt.Errorf("an old rdf syntax term may not be used as a property element name: %s", name)
	}
	if name == RDFDescription {
		return fmt.Errorf("rdf:Description may not be used as a property element name")
	}
	return nil
}

var coreSyntaxTerms = map[ntriples.IRI]bool{
	RDFRoot:      true,
	RDFID:        true,
	RDFAbout:     true,
	RDFParseType: true,
	RDFResource:  true,
	RDFNodeID:    true,
	RDFDatatype:  true,
}

var oldTerms = map[ntriples.IRI]bool{
	RDF + "aboutEach":       true,
	RDF + "aboutEachPrefix": true,
	RDF + "bagID":           true,
}


text:
package com.sksamuel.elastic4s.json4s

import com.sksamuel.elastic4s.{Hit, HitReader, Indexable, JsonFormat}
import org.json4s._

import scala.reflect.Manifest
import scala.util.control.NonFatal

object ElasticJson4s {
  object Implicits {

    implicit def format[T <: AnyRef](implicit json4s: Serialization,
                                     formats: Formats,
                                     mf: Manifest[T]): JsonFormat[T] = new JsonFormat[T] {
      override def fromJson(json: String): T = json4s.read[T](json)
    }

    implicit def Json4sHitReader[T](implicit json4s: Serialization,
                                    formats: Formats,
                                    mf: Manifest[T]): HitReader[T] = new HitReader[T] {
      override def read(hit: Hit): Either[Throwable, T] = try {
        Right(json4s.read[T](hit.sourceAsString))
      } catch {
        case NonFatal(e) => Left(e)
      }
    }

    implicit def Json4sIndexable[T <: AnyRef](implicit json4s: Serialization,
                                              formats: Formats): Indexable[T] = new Indexable[T] {
      override def json(t: T): String = json4s.write(t)
    }
  }
}


text:
================================================================================
TaskReasonSystem
================================================================================

.. describe:: Extends

    :py:class:`~pyvisdk.mo.task_reason.TaskReason`

.. class:: pyvisdk.do.task_reason_system.TaskReasonSystem


text:
/******************************************************************************
 * @File    Test_GameOfLife.h
 * @Brief   Unit Testing for GameOfLife.c
 ******************************************************************************/

#ifndef __TEST_GAME_OF_LIFE_H__
#define __TEST_GAME_OF_LIFE_H__

#ifdef __cplusplus
    extern "C" {
#endif

#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include "cmockery.h" /* <== A great && free UT framework given by Google. */

#define UT_CASES_GROUP_TEST_GAME_OF_LIFE                    \
    unit_test(Test_LifeNext_NotEnoughMemoryToCopyOldLife),  \
    unit_test(Test_LifeNext_Success),                       \

void Test_LifeNext_NotEnoughMemoryToCopyOldLife(void **state);
void Test_LifeNext_Success(void **state);

#ifdef __cplusplus
}
#endif

#endif /* __TEST_GAME_OF_LIFE_H__ */


text:
namespace AggregateMetrics.Tests.One
{
    using System;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.ApplicationInsights;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Microsoft.ApplicationInsights.Extensibility.AggregateMetrics;
    using Microsoft.ApplicationInsights.Extensibility.AggregateMetrics.One;
    [TestClass]
    public class CounterCollectionLimitsTests : AggregationTests
    {
        [TestMethod]
        public void CounterNameIsTruncatedToMaxLength()
        {
            var client = new TelemetryClient();
            client.TrackAggregateMetric("This name is longer than the maximum allowed length and will be truncated", 123.00);

            Assert.AreEqual(1, AggregateMetrics.aggregationSets.Count);

            AggregationSet aggregationSet;
            AggregateMetrics.aggregationSets.TryGetValue(AggregateMetrics.aggregationSets.Keys.First(), out aggregationSet);
            Assert.AreEqual("This name is longer ", aggregationSet.Name);
        }

        [TestMethod]
        public void PropertyValueIsTruncatedToMaxLength()
        {
            var client = new TelemetryClient();
            client.TrackAggregateMetric("MyCounter", 123.00, "1. This is a long property value", "2. This is a long property value", "3. This is a long property value");

            Assert.AreEqual(1, AggregateMetrics.aggregationSets.Count);

            AggregationSet aggregationSet;
            AggregateMetrics.aggregationSets.TryGetValue(AggregateMetrics.aggregationSets.Keys.First(), out aggregationSet);

            MetricsBag counterData = aggregationSet.RemoveAggregations().First().Value;

            Assert.AreEqual("1. This is a long pr", counterData.Property1);
            Assert.AreEqual("2. This is a long pr", counterData.Property2);
            Assert.AreEqual("3. This is a long pr", counterData.Property3);
        }
    }
}


text:
@interface SpdyTestCallback : NSObject <SpdyUrlConnectionCallback>
@property (nonatomic, assign) BOOL shouldUseSpdy;
@end

@implementation SpdyTestCallback
@synthesize shouldUseSpdy;

- (BOOL)shouldUseSpdyForUrl:(NSURL *)url {
    return shouldUseSpdy;
}

@end

@implementation SpdyUrlConnectionTest

- (void)setUp {
    [SpdyUrlConnection registerSpdy];
}

- (void)tearDown {
    [SpdyUrlConnection unregister];
}

- (void)testDisableUrl {
    NSURL *url = [NSURL URLWithString:@"https://ww.g.ca/"];
    NSURL *url443 = [NSURL URLWithString:@"https://ww.g.ca:443/"];
    NSURL *url444 = [NSURL URLWithString:@"https://ww.g.ca:444/"];
    STAssertTrue([SpdyUrlConnection canInitWithUrl:url], @"%@", url);
    STAssertTrue([SpdyUrlConnection canInitWithUrl:url443], @"%@", url443);
    STAssertTrue([SpdyUrlConnection canInitWithUrl:url444], @"%@", url444);

    [SpdyUrlConnection disableUrl:url];
    STAssertFalse([SpdyUrlConnection canInitWithUrl:url], @"%@", url);
    STAssertFalse([SpdyUrlConnection canInitWithUrl:url443], @"%@", url443);
    STAssertTrue([SpdyUrlConnection canInitWithUrl:url444], @"%@", url444);

    [SpdyUrlConnection disableUrl:url444];
    STAssertFalse([SpdyUrlConnection canInitWithUrl:url444], @"%@", url444);
}

- (void)testGzipHeader {
    NSURL *url = [NSURL URLWithString:@"https://t.ca"];
    CFHTTPMessageRef request = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), (CFURLRef)url, kCFHTTPVersion1_1);
    CFHTTPMessageSetHeaderFieldValue(request, CFSTR("content-EncodinG"), CFSTR("gzip"));
    CFHTTPMessageSetHeaderFieldValue(request, CFSTR("unKnown-heaDeR"), CFSTR("value"));

    NSHTTPURLResponse *response = [SpdyUrlResponse responseWithURL:url withResponse:request withRequestBytes:45];
    STAssertNotNil(response, @"Have response");
    STAssertNotNil([response allHeaderFields], @"Have headers");
    // In iOS 4.3 and below CFHTTPMessage uppercases the first letter of each word in the http header key.  In iOS 5 and up the headers
    // from CFHTTPMessage are case insenstive.
    STAssertEquals([[response allHeaderFields] objectForKey:@"Content-Encoding"], @"gzip", @"Has content-encoding %@", [response allHeaderFields]);
    STAssertEquals([[response allHeaderFields] objectForKey:@"Unknown-Header"], @"value", @"Case insensitive dictionary %@", [response allHeaderFields]);
}

- (void)testCheckCallbackCanInitWithUrl {
    [SpdyUrlConnection unregister];
    SpdyTestCallback *callback = [[[SpdyTestCallback alloc] init] autorelease];
    [SpdyUrlConnection registerSpdyWithCallback:callback];
    NSURL *url = [NSURL URLWithString:@"https://t.ca"];
    callback.shouldUseSpdy = YES;
    STAssertTrue([SpdyUrlConnection canInitWithUrl:url], @"%@", url);

    callback.shouldUseSpdy = NO;
    STAssertFalse([SpdyUrlConnection canInitWithUrl:url], @"%@", url);
}

@end


text:
using namespace SDKTemplate;

Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
{
    { "Low Latency Input", "SDKTemplate.Scenario1_LowLatencyInput" }
};


text:
/**
 * \file src/pt2pt/mpidi_callback_ssm.c
 * \brief The standard callback for a new short message
 */
#include "mpidimpl.h"

/**
 * \brief Callback for incoming SSM CTS message.
 * \note  Because this is a short message, the data is already received
 * \param[in]  clientdata Unused
 * \param[in]  msginfo    The 16-byte msginfo struct
 * \param[in]  count      The number of msginfo quads (1)
 * \param[in]  senderrank The sender's rank
 * \param[in]  sndlen     The length of the incoming data
 * \param[in]  sndbuf     Where the data is stored
 */
void MPIDI_BG2S_SsmCtsCB(void                     * clientdata,
                         const DCQuad             * msginfo,
                         unsigned                   count,
                         size_t                     senderrank,
                         const char               * sndbuf,
                         size_t                     sndlen)
{
  // const MPIDI_DCMF_MsgInfo *m = (const MPIDI_DCMF_MsgInfo *)msginfo;
  SSM_ABORT();
}

/**
 * \brief Callback for SSM Ack to indicate that the put is done.
 * \note  Because this is a short message, the data is already received
 * \param[in]  clientdata Unused
 * \param[in]  msginfo    The 16-byte msginfo struct
 * \param[in]  count      The number of msginfo quads (1)
 * \param[in]  senderrank The sender's rank
 * \param[in]  sndlen     The length of the incoming data
 * \param[in]  sndbuf     Where the data is stored
 */
void MPIDI_BG2S_SsmAckCB(void                     * clientdata,
                         const DCQuad             * msginfo,
                         unsigned                   count,
                         size_t                     senderrank,
                         const char               * sndbuf,
                         size_t                     sndlen)
{
  // const MPIDI_DCMF_MsgInfo *m = (const MPIDI_DCMF_MsgInfo *)msginfo;
  SSM_ABORT();
}

/**
 * \brief Message layer callback which is invoked on the origin node
 * when the message put is done
 *
 * \param[in,out] sreq MPI receive request object
 */
void MPIDI_DCMF_SsmPutDoneCB (void *clientdata, DCMF_Error_t *err)
{
  SSM_ABORT();
}


text:
package com.platypii.baseline.views.map;

import com.platypii.baseline.views.map.layers.HomeLayer;
import com.platypii.baseline.views.map.layers.LandingLayer;
import com.platypii.baseline.views.map.layers.MyPositionLayer;
import com.platypii.baseline.views.map.layers.PlacesLayer;

import androidx.annotation.NonNull;
import com.google.android.gms.maps.GoogleMap;

/**
 * Main map fragment
 */
public class MapFragment extends BaseMapFragment {
    private static final String TAG = "Map";

    public PlacesLayer placesLayer;

    @Override
    public void onMapReady(@NonNull GoogleMap map) {
        super.onMapReady(map);

        // Add map layers
        addLayer(placesLayer = new PlacesLayer(getLayoutInflater(), getContext()));
        addLayer(new HomeLayer());
        addLayer(new LandingLayer());
        addLayer(new MyPositionLayer());
        updateLayers();
    }

}


text:
package volume_test

import (
	"fmt"

	"github.com/IBM/ubiquity-k8s/volume"
	"github.com/IBM/ubiquity/fakes"
	"github.com/IBM/ubiquity/resources"
	"github.com/kubernetes-incubator/external-storage/lib/controller"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var _ = Describe("Provisioner", func() {
	var (
		fakeClient *fakes.FakeStorageClient
		// fakeKubeInterface *k8s_fake.FakeInterface
		provisioner    controller.Provisioner
		options        controller.VolumeOptions
		backends       []string
		ubiquityConfig resources.UbiquityPluginConfig
		err            error
	)

	BeforeEach(func() {
		fakeClient = new(fakes.FakeStorageClient)
		backends = []string{resources.SpectrumScale}
		ubiquityConfig = resources.UbiquityPluginConfig{Backends: backends}
		// fakeKubeInterface = new(k8s_fake.FakeInterface)
		provisioner, err = volume.NewFlexProvisioner(testLogger, fakeClient, ubiquityConfig)
	})

	Context(".Provision", func() {
		BeforeEach(func() {

			options = controller.VolumeOptions{PVName: "fakepv"}
		})
		It("fails when options does not contain pvc", func() {
			_, err = provisioner.Provision(options)
			Expect(err).To(HaveOccurred())
		})
		It("fails when options does not contain pvc", func() {
			_, err = provisioner.Provision(options)
			Expect(err).To(HaveOccurred())
		})

	})

	Context(".Delete", func() {

		It("fails when volume name is empty", func() {
			volume := v1.PersistentVolume{}
			err = provisioner.Delete(&volume)
			Expect(err).To(HaveOccurred())
			Expect(fakeClient.RemoveVolumeCallCount()).To(Equal(0))
		})

		It("fails when ubiquityClient returns an error", func() {
			fakeClient.RemoveVolumeReturns(fmt.Errorf("error removing volume"))
			objectMeta := metav1.ObjectMeta{Name: "vol1"}
			volume := v1.PersistentVolume{ObjectMeta: objectMeta}
			err = provisioner.Delete(&volume)
			Expect(err).To(HaveOccurred())
			Expect(fakeClient.RemoveVolumeCallCount()).To(Equal(1))
		})
		It("succeeds when volume  name exists and ubiquityClient does not return an error", func() {
			fakeClient.RemoveVolumeReturns(nil)
			objectMeta := metav1.ObjectMeta{Name: "vol1"}
			volume := v1.PersistentVolume{ObjectMeta: objectMeta}
			err = provisioner.Delete(&volume)
			Expect(err).ToNot(HaveOccurred())
			Expect(fakeClient.RemoveVolumeCallCount()).To(Equal(1))
		})
		It("succeeds when volume wasnot found in ubiquity DB", func() {
			fakeClient.GetVolumeReturns(resources.Volume{}, &resources.VolumeNotFoundError{"vol1"})
			objectMeta := metav1.ObjectMeta{Name: "vol1"}
			volume := v1.PersistentVolume{ObjectMeta: objectMeta}
			err = provisioner.Delete(&volume)
			Expect(err).ToNot(HaveOccurred())
			Expect(fakeClient.GetVolumeCallCount()).To(Equal(1))
			Expect(fakeClient.RemoveVolumeCallCount()).To(Equal(0))
		})

	})
})


text:
import { Component } from '@angular/core';
import { NavParams } from 'ionic-angular';

@Component({
  selector: 'app-popover',
  templateUrl: 'app-popover.html'
})
export class AppPopover {
  private saveLayoutCallback;
  private loadLayoutCallback;
  private clearLayoutCallback;

  constructor(private navParams: NavParams) {
    this.saveLayoutCallback = this.navParams.get('saveLayout')
    this.loadLayoutCallback = this.navParams.get('loadLayout')
    this.clearLayoutCallback = this.navParams.get('clearLayout')
  }

  saveLayout() {
    this.saveLayoutCallback();
  }

  loadLayout() {
    this.loadLayoutCallback();
  }

  clear() {
    this.clearLayoutCallback();
  }
}


text:
* Support for Visual Studio 2019 - #50 via @dennisroche

### New in 1.1.2 (Released 2016/06/06)
* Support for Visual Studio "15" Preview - #39 via @sklivvz

### New in 1.1.1 (Released 2015/05/08)
* Support for Visual Studio 2015 RC - #26 via @rprouse

### New in 1.1.0 (Released 2014/07/29)
* Added option to configure the set of encouragements - #27 via @haacked

### New in 1.0.6 (Released 2014/07/24)
* Added eight new encouragements - #23 via @philoushka
* Fixed bug so encouragements now show up in Razor files - #25 via @jaredpar

### New in 1.0.5 (Released 2014/07/18)
* Fixed bug where encouragements show up in the Immediate window - #20 via @jaredpar

### New in 1.0.4 (Released 2014/07/11)
* Fixed bug with encouragements scrambled in JavaScript editor - #17 via @jaredpar

### New in 1.0.3 (Released 2014/06/30)
* Support for Visual Studio 2012 - #10 via @jaredpar
* Fixed crash when caret is at the very end of the document - #11 via @jaredpar
* Added a couple more encouragements

### New in 1.0.1 (Released 2014/06/23)
* Fixed encouragements showing up in Intellisense signature help - #7 via @jaredpar
* Fixed bug that did not show full range of encouragments - #5 via @argsv

### New in 1.0.0 (Released 2014/06/20)
* Initial release


text:
export interface AsyncStore {

}


text:
package org.uberfire.security.authz;

import java.util.Collection;

public interface RuntimeFeatureResource extends RuntimeResource {

    Collection<String> getRoles();
}


text:
package voldemort.store.cachestore;

/**
 * Created by IntelliJ IDEA.
 * User: mhsieh
 * Date: 3/7/12
 * Time: 2:47 PM
 * To change this template use File | Settings | File Templates.
 */
public interface Reference<T> {
    //
    public T getData();
    public void setData(T data);
    public long getAccessTime();
    public void setAccessTime(long time);
    public Reference getNext();
    public void setNext(Reference ref);
    public Reference getPrev();
    public void setPrev(Reference ref);
    public boolean isDirty();

}


text:
<?php

namespace Encore\Error;

use Encore\Container\Proxy as BaseProxy;

class Proxy extends BaseProxy
{
    /**
     * Get the name of the concrete binding in the container.
     *
     * @return string
     */
    public static function getConcreteBinding()
    {
        return 'error';
    }
}


text:
class CheckAssignmentDecorator < BaseDecorator
  delegate :completion_date, :created_at, :id, :user_id, :project_check

  def checker
    object.user.name
  end

  # rubocop:disable Metrics/AbcSize
  def note_url
    if object.note_url.to_s =~ /http/
      h.link_to h.truncate(object.note_url.to_s, length: 40), object.note_url
    else
      object.note_url
    end
  end
  # rubocop:enable Metrics/AbcSize

  def row_class
    "active" if completion_date.present?
  end

  def days_till_reviewer_deadline
    (object.deadline - Time.current.to_date).to_i if object.deadline.present?
  end

  def assigned_days_ago_as_string
    "#{h.time_ago_in_words(object.created_at)} ago"
  end

  def completion_notification_text(checker)
    "#{checker.name} has completed #{object.project_check.reminder.name} " \
      "in #{object.project_check.project.name}: #{object.note_url}"
  end

  def project_name
    object.project_check.project.name
  end
end


text:
namespace media {

class VideoFrame;
class VideoFrameMapper;

namespace test {

// VideoFrameValidator validates the pixel content of each video frame.
// It maps a video frame by using VideoFrameMapper if needed. If the validation
// fails, the frame is processed by |corrupt_frame_processor_|.
// VideoFrameValidator is created by calling Create() of the child classes in
// below.
// Mapping and verification of a frame is a costly operation and will influence
// performance measurements.
class VideoFrameValidator : public VideoFrameProcessor {
 public:
  // Get the model frame from |frame_index|.
  using GetModelFrameCB =
      base::RepeatingCallback<scoped_refptr<const VideoFrame>(size_t)>;

  ~VideoFrameValidator() override;

  // Prints information of frames on which the validation failed. This function
  // is thread-safe.
  void PrintMismatchedFramesInfo() const;

  // Returns the number of frames on which the validation failed. This function
  // is thread-safe.
  size_t GetMismatchedFramesCount() const;

  // Interface VideoFrameProcessor
  void ProcessVideoFrame(scoped_refptr<const VideoFrame> video_frame,
                         size_t frame_index) final;
  // Wait until all currently scheduled frame validations are done. Returns true
  // if no corrupt frames were found. This function might take a long time to
  // complete, depending on the platform.
  bool WaitUntilDone() final;

 protected:
  struct MismatchedFrameInfo {
    MismatchedFrameInfo(size_t frame_index) : frame_index(frame_index) {}
    virtual ~MismatchedFrameInfo() = default;
    virtual void Print() const = 0;
    size_t frame_index;
  };

  VideoFrameValidator(
      std::unique_ptr<VideoFrameProcessor> corrupt_frame_processor);

  // Start the frame validation thread.
  bool Initialize();

  SEQUENCE_CHECKER(validator_thread_sequence_checker_);

 private:
  // Stop the frame validation thread.
  void Destroy();

  // Validate the |video_frame|'s content on the |frame_validator_thread_|.
  void ProcessVideoFrameTask(scoped_refptr<const VideoFrame> video_frame,
                             size_t frame_index);

  virtual std::unique_ptr<MismatchedFrameInfo> Validate(
      scoped_refptr<const VideoFrame> frame,
      size_t frame_index) = 0;

  std::unique_ptr<VideoFrameMapper> video_frame_mapper_;

  // An optional video frame processor that all corrupted frames will be
  // forwarded to. This can be used to e.g. write corrupted frames to disk.
  const std::unique_ptr<VideoFrameProcessor> corrupt_frame_processor_;

  // The number of frames currently queued for validation.
  size_t num_frames_validating_ GUARDED_BY(frame_validator_lock_);
  // The results of invalid frame data.
  std::vector<std::unique_ptr<MismatchedFrameInfo>> mismatched_frames_
      GUARDED_BY(frame_validator_lock_);

  // Thread on which video frame validation is done.
  base::Thread frame_validator_thread_;
  mutable base::Lock frame_validator_lock_;
  mutable base::ConditionVariable frame_validator_cv_;

  SEQUENCE_CHECKER(validator_sequence_checker_);

  DISALLOW_COPY_AND_ASSIGN(VideoFrameValidator);
};

// Validate by converting the frame to be validated to |validation_format| to
// resolve pixel format differences on different platforms. Thereafter, it
// compares md5 values of the mapped and converted buffer with golden md5
// values. The golden values are prepared in advance and must be identical on
// all platforms.
class MD5VideoFrameValidator : public VideoFrameValidator {
 public:
  static std::unique_ptr<MD5VideoFrameValidator> Create(
      const std::vector<std::string>& expected_frame_checksums,
      VideoPixelFormat validation_format = PIXEL_FORMAT_I420,
      std::unique_ptr<VideoFrameProcessor> corrupt_frame_processor = nullptr);
  ~MD5VideoFrameValidator() override;

 private:
  struct MD5MismatchedFrameInfo;

  MD5VideoFrameValidator(
      const std::vector<std::string>& expected_frame_checksums,
      VideoPixelFormat validation_format,
      std::unique_ptr<VideoFrameProcessor> corrupt_frame_processor);
  MD5VideoFrameValidator(const MD5VideoFrameValidator&) = delete;
  MD5VideoFrameValidator& operator=(const MD5VideoFrameValidator&) = delete;

  // VideoFrameValidator implementation.
  std::unique_ptr<MismatchedFrameInfo> Validate(
      scoped_refptr<const VideoFrame> frame,
      size_t frame_index) override;

  // Returns md5 values of video frame represented by |video_frame|.
  std::string ComputeMD5FromVideoFrame(const VideoFrame& video_frame) const;

  const std::vector<std::string> expected_frame_checksums_;
  const VideoPixelFormat validation_format_;
};

// Validate by comparing each byte of visible area of the frame to be validated.
// An absolute difference equal to or less than |torelance_| is allowed on
// the comparison.
class RawVideoFrameValidator : public VideoFrameValidator {
 public:
  constexpr static uint8_t kDefaultTolerance = 4;

  static std::unique_ptr<RawVideoFrameValidator> Create(
      const GetModelFrameCB& get_model_frame_cb,
      uint8_t tolerance = kDefaultTolerance,
      std::unique_ptr<VideoFrameProcessor> corrupt_frame_processor = nullptr);
  ~RawVideoFrameValidator() override;

 private:
  struct RawMismatchedFrameInfo;

  RawVideoFrameValidator(
      const GetModelFrameCB& get_model_frame_cb,
      uint8_t tolerance,
      std::unique_ptr<VideoFrameProcessor> corrupt_frame_processor);

  std::unique_ptr<MismatchedFrameInfo> Validate(
      scoped_refptr<const VideoFrame> frame,
      size_t frame_index) override;

  const GetModelFrameCB get_model_frame_cb_;
  const uint8_t tolerance_;
};

// Validate by computing PSNR from the frame to be validated and the model frame
// acquired by |get_model_frame_cb_|. If the PSNR value is equal to or less than
// |tolerance_|, the validation on the frame passes.
class PSNRVideoFrameValidator : public VideoFrameValidator {
 public:
  constexpr static double kDefaultTolerance = 20.0;

  static std::unique_ptr<PSNRVideoFrameValidator> Create(
      const GetModelFrameCB& get_model_frame_cb,
      double tolerance = kDefaultTolerance,
      std::unique_ptr<VideoFrameProcessor> corrupt_frame_processor = nullptr);
  ~PSNRVideoFrameValidator() override;

 private:
  struct PSNRMismatchedFrameInfo;

  PSNRVideoFrameValidator(
      const GetModelFrameCB& get_model_frame_cb,
      double tolerance,
      std::unique_ptr<VideoFrameProcessor> corrupt_frame_processor);

  std::unique_ptr<MismatchedFrameInfo> Validate(
      scoped_refptr<const VideoFrame> frame,
      size_t frame_index) override;

  const GetModelFrameCB get_model_frame_cb_;
  const double tolerance_;
};

// Validate by computing SSIM from the frame to be validated and the model frame
// acquired by |get_model_frame_cb_|. If the SSIM value is equal to or less than
// |tolerance_|, the validation on the frame passes.
class SSIMVideoFrameValidator : public VideoFrameValidator {
 public:
  constexpr static double kDefaultTolerance = 0.70;

  static std::unique_ptr<SSIMVideoFrameValidator> Create(
      const GetModelFrameCB& get_model_frame_cb,
      double tolerance = kDefaultTolerance,
      std::unique_ptr<VideoFrameProcessor> corrupt_frame_processor = nullptr);
  ~SSIMVideoFrameValidator() override;

 private:
  struct SSIMMismatchedFrameInfo;

  SSIMVideoFrameValidator(
      const GetModelFrameCB& get_model_frame_cb,
      double tolerance,
      std::unique_ptr<VideoFrameProcessor> corrupt_frame_processor);

  std::unique_ptr<MismatchedFrameInfo> Validate(
      scoped_refptr<const VideoFrame> frame,
      size_t frame_index) override;

  const GetModelFrameCB get_model_frame_cb_;
  const double tolerance_;
};
}  // namespace test
}  // namespace media

#endif  // MEDIA_GPU_TEST_VIDEO_FRAME_VALIDATOR_H_


text:
<?php

/**
 * Handles the settings of the plugin
 */
class Prism_Detached_Settings
{
    /**
     * The chosen theme id
     *
     * @var string
     */
    private $theme;

    /**
     * The list of active extensions
     *
     * @var array
     */
    private $activeExtensions;

    /**
     * The cache keys
     *
     * @var array
     */
    private $cacheKeys;

    /**
     * The extension loader
     *
     * @var Prism_Detached_Extension_Loader
     */
    private $extensionLoader;

    /**
     * The available themes
     *
     * @var array
     */
    private static $themes = array(
        'prism' => 'Default Theme',
        'prism-dark' => 'Dark',
        'prism-funky' => 'Funky',
        'prism-okaidia' => 'Okaidia',
        'prism-tomorrow' => 'Tomorrow',
        'prism-twilight' => 'Twilight',
    );

    /**
     * Constructs a new prism settings dialog
     */
    public function __construct ()
    {
        $this->theme            = get_option('prism_detached_theme')      ?: $this->getDefaultTheme();
        $this->activeExtensions = get_option('prism_detached_extensions') ?: array();
        $this->cacheKeys        = get_option('prism_detached_cache_keys') ?: array('js' => null, 'css' => null);
    }

    /**
     * @return string
     */
    public function getTheme ()
    {
        return $this->theme;
    }

    /**
     * @return array
     */
    public function getActiveExtensions ()
    {
        return $this->activeExtensions;
    }

    /**
     * Sets the cache keys
     *
     * @param array $cacheKeys
     */
    public function setCacheKeys (array $cacheKeys)
    {
        $this->cacheKeys = $cacheKeys;
        update_option('prism_detached_cache_keys', $cacheKeys);
    }

    /**
     * Returns the cache keys
     *
     * @return array
     */
    public function getCacheKeys ()
    {
        return $this->cacheKeys;
    }

    /**
     * Registers the settings
     */
    public function registerSettings ()
    {
        // add settings
        register_setting('prism_detached_extensions', 'prism_detached_extensions', array($this, 'validateExtensionsForm'));
        register_setting('prism_detached_theme',      'prism_detached_theme',      array($this, 'validateThemeForm'));
    }

    /**
     * Deletes the options
     */
    public function unregisterSettings ()
    {
        // remove legacy options (up to v1.2)
        delete_option('prism-detached-invisibles');
        delete_option('prism-detached-autolinker');

        // delete current options
        delete_option('prism_detached_cache_keys');

        // unregister settings
        unregister_setting('prism_detached_extensions', 'prism_detached_extensions');
        unregister_setting('prism_detached_theme',      'prism_detached_theme');
    }

    //region Admin Form Handler
    /**
     * Validates the theme form
     *
     * @param string $input
     *
     * @return mixed
     */
    public function validateThemeForm ($input)
    {
        return $this->themeExists($input) ? $input : $this->getDefaultTheme();
    }

    /**
     * Validates the extensions form
     *
     * @param array $input
     *
     * @return array
     */
    public function validateExtensionsForm ($input)
    {
        if (is_array($input))
        {
            $this->extensionLoader->markActiveExtensions($input);
            return $this->extensionLoader->getExtensionsStates();
        }

        return array();
    }
    //endregion

    //region Theme Lists and Defaults
    /**
     * @return array
     */
    public function getAllThemes ()
    {
        return self::$themes;
    }

    /**
     * Returns, whether the given theme exists
     *
     * @param string $themeId
     *
     * @return bool
     */
    public function themeExists ($themeId)
    {
        return array_key_exists($themeId, $this->getAllThemes());
    }

    /**
     * Returns the default theme
     *
     * @return mixed
     */
    public function getDefaultTheme ()
    {
        return current(array_keys($this->getAllThemes()));
    }
    //endregion

    //region Accessors Extension Loader
    /**
     * @param \Prism_Detached_Extension_Loader $extensionLoader
     */
    public function setExtensionLoader ($extensionLoader)
    {
        $this->extensionLoader = $extensionLoader;
    }

    /**
     * @return \Prism_Detached_Extension_Loader
     */
    public function getExtensionLoader ()
    {
        return $this->extensionLoader;
    }
    //endregion
}


text:
package net.liftweb
package json

import java.util.{Date, TimeZone}

/** Formats to use when converting JSON.
 * Formats are usually configured by using an implicit parameter:
 *

 * implicit val formats = net.liftweb.json.DefaultFormats
 *

 */
trait Formats { self: Formats =>
  val dateFormat: DateFormat
  val typeHints: TypeHints = NoTypeHints
  val customSerializers: List[Serializer[_]] = Nil

  /**
   * The name of the field in JSON where type hints are added (jsonClass by default)
   */
  val typeHintFieldName = "jsonClass"

  /**
   * Adds the specified type hints to this formats.
   */
  def + (extraHints: TypeHints): Formats = new Formats {
    val dateFormat = Formats.this.dateFormat
    override val typeHints = self.typeHints + extraHints
    override val customSerializers = self.customSerializers
  }

  /**
   * Adds the specified custom serializer to this formats.
   */
  def + (newSerializer: Serializer[_]): Formats = new Formats {
    val dateFormat = Formats.this.dateFormat
    override val typeHints = self.typeHints
    override val customSerializers = newSerializer :: self.customSerializers
  }

  /**
   * Adds the specified custom serializers to this formats.
   */
  def ++ (newSerializers: Traversable[Serializer[_]]): Formats =
    newSerializers.foldLeft(this)(_ + _)

  def customSerializer(implicit format: Formats) =
    customSerializers.foldLeft(Map(): PartialFunction[Any, JValue]) { (acc, x) =>
      acc.orElse(x.serialize)
    }

  def customDeserializer(implicit format: Formats) =
    customSerializers.foldLeft(Map(): PartialFunction[(TypeInfo, JValue), Any]) { (acc, x) =>
      acc.orElse(x.deserialize)
    }
}

/** Conversions between String and Date.
 */
trait DateFormat {
  def parse(s: String): Option[Date]
  def format(d: Date): String
}

trait Serializer[A] {
  def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), A]
  def serialize(implicit format: Formats): PartialFunction[Any, JValue]
}

/** Type hints can be used to alter the default conversion rules when converting
 * Scala instances into JSON and vice versa. Type hints must be used when converting
 * class which is not supported by default (for instance when class is not a case class).
 *

 * Example:

 * class DateTime(val time: Long)
 *
 * val hints = new ShortTypeHints(classOf[DateTime] :: Nil) {
 *   override def serialize: PartialFunction[Any, JObject] = {
 *     case t: DateTime => JObject(JField("t", JInt(t.time)) :: Nil)
 *   }
 *
 *   override def deserialize: PartialFunction[(String, JObject), Any] = {
 *     case ("DateTime", JObject(JField("t", JInt(t)) :: Nil)) => new DateTime(t.longValue)
 *   }
 * }
 * implicit val formats = DefaultFormats.withHints(hints)
 *

 */
trait TypeHints {
  val hints: List[Class[_]]

  /** Return hint for given type.
   */
  def hintFor(clazz: Class[_]): String

  /** Return type for given hint.
   */
  def classFor(hint: String): Option[Class[_]]

  def containsHint_?(clazz: Class[_]) = hints exists (_ isAssignableFrom clazz)
  def deserialize: PartialFunction[(String, JObject), Any] = Map()
  def serialize: PartialFunction[Any, JObject] = Map()

  def components: List[TypeHints] = List(this)

  /**
   * Adds the specified type hints to this type hints.
   */
  def + (hints: TypeHints): TypeHints = CompositeTypeHints(hints.components ::: components)

  private[TypeHints] case class CompositeTypeHints(override val components: List[TypeHints]) extends TypeHints {
    val hints: List[Class[_]] = components.flatMap(_.hints)

    /**
     * Chooses most specific class.
     */
    def hintFor(clazz: Class[_]): String = components.filter(_.containsHint_?(clazz))
      .map(th => (th.hintFor(clazz), th.classFor(th.hintFor(clazz)).getOrElse(error("hintFor/classFor not invertible for " + th))))
      .sort((x, y) => delta(x._2, clazz) - delta(y._2, clazz) < 0).head._1

    def classFor(hint: String): Option[Class[_]] = hints find (hintFor(_) == hint)

    override def deserialize: PartialFunction[(String, JObject), Any] = components.foldLeft[PartialFunction[(String, JObject),Any]](Map()) {
      (result, cur) => result.orElse(cur.deserialize)
    }

    override def serialize: PartialFunction[Any, JObject] = components.foldLeft[PartialFunction[Any, JObject]](Map()) {
      (result, cur) => result.orElse(cur.serialize)
    }

    private def delta(class1: Class[_], class2: Class[_]): Int = {
      if (class1 == class2) 0
      else if (class1.getInterfaces.contains(class2)) 0
      else if (class2.getInterfaces.contains(class1)) 0
      else if (class1.isAssignableFrom(class2)) {
        1 + delta(class1, class2.getSuperclass)
      }
      else if (class2.isAssignableFrom(class1)) {
        1 + delta(class1.getSuperclass, class2)
      }
      else error("Don't call delta unless one class is assignable from the other")
    }
  }
}

/** Do not use any type hints.
 */
case object NoTypeHints extends TypeHints {
  val hints = Nil
  def hintFor(clazz: Class[_]) = error("NoTypeHints does not provide any type hints.")
  def classFor(hint: String) = None
}

/** Use short class name as a type hint.
 */
case class ShortTypeHints(hints: List[Class[_]]) extends TypeHints {
  def hintFor(clazz: Class[_]) = clazz.getName.substring(clazz.getName.lastIndexOf(".")+1)
  def classFor(hint: String) = hints find (hintFor(_) == hint)
}

/** Use full class name as a type hint.
 */
case class FullTypeHints(hints: List[Class[_]]) extends TypeHints {
  def hintFor(clazz: Class[_]) = clazz.getName
  def classFor(hint: String) = Some(Thread.currentThread.getContextClassLoader.loadClass(hint))
}

/** Default date format is UTC time.
 */
object DefaultFormats extends DefaultFormats {
  val losslessDate = new ThreadLocal(new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"))
  val UTC = TimeZone.getTimeZone("UTC")
}

trait DefaultFormats extends Formats {
  import java.text.{ParseException, SimpleDateFormat}

  val dateFormat = new DateFormat {
    def parse(s: String) = try {
      Some(formatter.parse(s))
    } catch {
      case e: ParseException => None
    }

    def format(d: Date) = formatter.format(d)

    private def formatter = {
      val f = dateFormatter
      f.setTimeZone(DefaultFormats.UTC)
      f
    }
  }

  protected def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")

  /** Lossless date format includes milliseconds too.
   */
  def lossless = new DefaultFormats {
    override def dateFormatter = DefaultFormats.losslessDate()
  }

  /** Default formats with given TypeHints.
   */
  def withHints(hints: TypeHints) = new DefaultFormats {
    override val typeHints = hints
  }
}

private[json] class ThreadLocal[A](init: => A) extends java.lang.ThreadLocal[A] with (() => A) {
  override def initialValue = init
  def apply = get
}