text:
<?xml version="1.0" encoding="UTF-8"?>
<book xmlns:ci="http://apache.org/cocoon/include/1.0">
    <bookinfo>
        <graphic fileref="logo.jpg"/>
        <productname>Open Source Native XML Database</productname>
        <title>Developer's Guide</title>
        <author>
            <firstname>Wolfgang M.</firstname>
            <surname>Meier</surname>
            <affiliation>
                <address format="linespecific">
                    <email>wolfgang at exist-db.org</email>
                </address>
            </affiliation>
        </author>
    </bookinfo>
    <ci:include src="sidebar.xml"/>
    <chapter id="ch01">
        <title>Developer's Guide</title>

            <title>Writing Java Applications with the XML:DB API</title>

            <para>The preferred way to work with eXist when developing Java applications is to use
                the XML:DB API. This API provides a common interface to native or XML-enabled
                databases and supports the development of portable, reusable applications. eXist's
                implementation of the XML:DB standards follows the Xindice implementation, and
                conforms to the latest working drafts put forth by the <ulink
                    url="http://xmldb-org.sourceforge.net/xapi/">XML:DB Initiative</ulink>. For more
                information, refer to the <ulink url="api/index.html">Javadocs for this API</ulink>.</para>

            <para>The basic components employed by the XML:DB API are <emphasis>drivers</emphasis>,
                    <emphasis>collections</emphasis>, <emphasis>resources</emphasis> and
                    <emphasis>services</emphasis>.</para>

            <para><emphasis>Drivers</emphasis> are implementations of the database interface that
                encapsulate the database access logic for specific XML database products. They are
                provided by the product vendor and must be registered with the database manager.</para>

            <para>A <emphasis>collection</emphasis> is a hierarchical container for
                    <emphasis>resources</emphasis> and further sub-collections. Currently two
                different resources are defined by the API: <classname>XMLResource</classname> and
                    <classname>BinaryResource</classname>. An <classname>XMLResource</classname>
                represents an XML document or a document fragment, selected by a previously executed
                XPath query.</para>
            <para>Finally, <emphasis>services</emphasis> are requested for special tasks such as
                querying a collection with XPath, or managing a collection.</para>
            <note>
                <para>There are several XML:DB examples provided in eXist's
                    <filename>samples</filename> directory . To start an example, use the <filename
                        moreinfo="none">start.jar</filename> jar file and pass the name of the
                    example class as the first parameter, for instance:</para>
                <synopsis format="linespecific">java -jar start.jar
					org.exist.examples.xmldb.Retrieve [- other options]</synopsis>
            </note>
            <para>Programming with the XML:DB API is straightforward. You will find some code
                examples in the <filename>samples/org/exist/examples/xmldb</filename> directory. In
                the following simple example, a document can be retrieved from the eXist server and
                printed to standard output.</para>
            <example>
                <title>Retrieving a Document with XML:DB</title>

                <programlisting format="linespecific" language="java"><![CDATA[
import org.xmldb.api.base.*;
import org.xmldb.api.modules.*;
import org.xmldb.api.*;
import javax.xml.transform.OutputKeys;

public class RetrieveExample {
    protected static String URI = "xmldb:exist://localhost:8080/exist/xmlrpc";

    public static void main(String args[]) throws Exception {
        String driver = "org.exist.xmldb.DatabaseImpl";

        // initialize database driver
        Class cl = Class.forName(driver);
        Database database = (Database) cl.newInstance();
        DatabaseManager.registerDatabase(database);

        // get the collection
        Collection col = DatabaseManager.getCollection(URI + args[0]);
        col.setProperty(OutputKeys.INDENT, "no");
        XMLResource res = (XMLResource)col.getResource(args[1]);
        if(res == null)
            System.out.println("document not found!");
        else
            System.out.println(res.getContent());   }
}
        ]]></programlisting>
            </example>
            <para>With this example, the database driver class for eXist
                    (<classname>org.exist.xmldb.DatabaseImpl</classname>) is first registered with
                the <classname>DatabaseManager</classname>. Next we obtain a
                <classname>Collection</classname> object from the database manager by calling the
                static method <methodname>DatabaseManger.getCollection()</methodname>. The method
                expects a fully qualified URI for its parameter value, which identifies the desired
                collection. The format of this URI should look like the following:</para>
            <synopsis format="linespecific">xmldb:[DATABASE-ID]://[HOST-ADDRESS]/db/collection</synopsis>
            <para>Because more than one database driver can be registered with the database manager,
                the first part of the URI (<option>xmldb:exist</option>) is required to determine
                which driver class to use. The <emphasis>database-id</emphasis> is used by the
                database manager to select the correct driver from its list of available drivers. To
                use eXist, this ID should always be "exist" (unless you have set up multiple
                database instances; additional instances may have other names).</para>
            <para>The final part of the URI identifies the collection path, and optionally the host
                address of the database server on the network. Internally, eXist uses two different
                driver implementations: The first talks to a remote database engine using XML-RPC
                calls, the second has direct access to a local instance of eXist. The root
                collection is always identified by <option>/db</option>. For example, the URI</para>
            <synopsis format="linespecific">xmldb:exist://localhost:8080/exist/xmlrpc/db/shakespeare/plays</synopsis>
            <para>references the Shakespeare collection on a remote server running the XML-RPC
                interface as a servlet at <option>localhost:8080/exist/xmlrpc</option>. If we leave
                out the host address, the XML:DB driver will try to connect to a locally attached
                database instance, e.g.:</para>
            <synopsis format="linespecific">xmldb:exist:///db/shakespeare/plays</synopsis>
            <para>In this case, we have to tell the XML:DB driver that it should create a new
                database instance if none has been started. This is done by setting the
                    <option>create-database</option> property of class
                <classname>Database</classname> to "true" (more information on embedded use of eXist
                can be found in the <ulink url="deployment.xml">deployment guide</ulink>.</para>
            <para>The <methodname>setProperty</methodname> calls are used to set database-specific
                parameters. In this case, pretty-printing of XML output is turned on for the
                collection. eXist uses the property keys defined in the standard Java package
                    <filename>javax.xml.transform</filename>. Thus, in Java you can simply use class
                    <classname>OutputKeys</classname> to get the correct keys.</para>
            <para>Calling <methodname>col.getResource()</methodname> finally retrieves the document,
                which is returned as an <classname>XMLResource</classname>. All resources have a
                method <methodname>getContent()</methodname>, which returns the resource's content,
                depending on it's type. In this case we retrieve the content as type
                    <classname>String</classname>.</para>
            <para>To query the repository, we may either use the standard
                    <classname>XPathQueryService</classname> or eXist's
                <classname>XQueryService</classname> class. The XML:DB API defines different kinds
                of services, which may or may not be provided by the database. The
                    <methodname>getService</methodname> method of class
                <classname>Collection</classname> calls a service if it is available. The method
                expects the service name as the first parameter, and the version (as a string) as
                the second, which is used to distinguish between different versions of the service
                defined by the XML:DB API.</para>
            <para>The following is an example of using the XML:DB API to execute a database query:</para>

            <example>
                <title>Querying the Database (XML:DB API)</title>

                <programlisting format="linespecific" language="java"><![CDATA[import org.xmldb.api.base.*;
import org.xmldb.api.modules.*;
import org.xmldb.api.*;

public class QueryExample {
    public static void main(String args[]) throws Exception {
        String driver = "org.exist.xmldb.DatabaseImpl";
        Class cl = Class.forName(driver);
        Database database = (Database)cl.newInstance();
        DatabaseManager.registerDatabase(database);

        Collection col =
            DatabaseManager.getCollection(
                "xmldb:exist://localhost:8080/exist/xmlrpc/db"
            );
        XPathQueryService service =
            (XPathQueryService) col.getService("XPathQueryService", "1.0");
        service.setProperty("indent", "yes");

        ResourceSet result = service.query(args[0]);
        ResourceIterator i = result.getIterator();
        while(i.hasMoreResources()) {
            Resource r = i.nextResource();
            System.out.println((String)r.getContent());
        }
    }
}
        ]]></programlisting>
            </example>
            <para>To execute the query, method <methodname>service.query(xpath)</methodname> is
                called. This method returns a <classname>ResourceSet</classname>, containing the
                Resources found by the query. <methodname>ResourceSet.getIterator()</methodname>
                gives us an iterator over these resources. Every Resource contains a single document
                fragment or value selected by the XPath expression.</para>
            <para>Internally, eXist does not distinguish between XPath and XQuery expressions.
                    <classname>XQueryService</classname> thus maps to the same implementation class
                as <classname>XPathQueryService</classname>. However, it provides a few additional
                methods. Most important, when talking to an embedded database,
                    <classname>XQueryService</classname> allows for the XQuery expression to be
                compiled as an internal representation, which can then be reused. With compilation,
                the previous example code would look as follows:</para>
            <example>
                <title>Compiling a Query (XML:DB API)</title>

                <programlisting format="linespecific" language="java"><![CDATA[import org.xmldb.api.base.*;
import org.xmldb.api.modules.*;
import org.xmldb.api.*;
import org.exist.xmldb.XQueryService;

public class QueryExample {
    public static void main(String args[]) throws Exception {
        String driver = "org.exist.xmldb.DatabaseImpl";
        Class cl = Class.forName(driver);
        Database database = (Database)cl.newInstance();
        database.setProperty("create-database", "true");
        DatabaseManager.registerDatabase(database);

        Collection col =
            DatabaseManager.getCollection("xmldb:exist:///db");
        XQueryService service =
            (XQueryService) col.getService("XQueryService", "1.0");
        service.setProperty("indent", "yes");

        CompiledExpression compiled = service.compile(args[0]);
        ResourceSet result = service.execute(compiled);
        ResourceIterator i = result.getIterator();
        while(i.hasMoreResources()) {
            Resource r = i.nextResource();
            System.out.println((String)r.getContent());
        }
    }
}
        ]]></programlisting>
            </example>
            <para>The XML-RPC server automatically caches compiled expressions, and so calling
                    <methodname>compile</methodname> through the remote driver produces no effect if
                the expression is already cached.</para>
            <para>Next, we would like to store a new document into the repository. This is done by
                creating a new <classname>XMLResource</classname>, assigning it the content of the
                new document, and calling the <methodname>storeResource</methodname> method of class
                    <classname>Collection</classname>. First, a new Resource is created by method
                    <methodname>Collection.createResource()</methodname>, and expects two
                parameters: the id and type of resource being created. If the id-parameter is null,
                a unique resource-id will be automatically generated .</para>
            <para>In some cases, the collection may not yet exist, and so we must create it. To
                create a new collection, call the <methodname>createCollection</methodname> method
                of the <classname>CollectionManagementService</classname> service. In the following
                example, we simply start at the root-collection object to get the
                    <classname>CollectionManagementService</classname> service.</para>
            <example>
                <title>Adding a File (XML:DB API)</title>

                <programlisting format="linespecific" language="java"><![CDATA[public class StoreExample {
    public final static String URI = "xmldb:exist://localhost:8080/exist/xmlrpc";

    public static void main(String args[]) throws Exception {
        if(args.length < 2) {
            System.out.println("usage: StoreExample collection-path document");
            System.exit(1);
        }

        String collection = args[0], file = args[1];

        // initialize driver
        String driver = "org.exist.xmldb.DatabaseImpl";
        Class cl = Class.forName(driver);
        Database database = (Database)cl.newInstance();
        DatabaseManager.registerDatabase(database);

        // try to get collection
        Collection col =
            DatabaseManager.getCollection(URI + collection);
        if(col == null) {
            // collection does not exist: get root collection and create
            // for simplicity, we assume that the new collection is a
            // direct child of the root collection, e.g. /db/test.
            // the example will fail otherwise.
            Collection root = DatabaseManager.getCollection(URI + "/db");
            CollectionManagementService mgtService = (CollectionManagementService)
                root.getService("CollectionManagementService", "1.0");
            col = mgtService.createCollection(collection.substring("/db".length()));
        }
        // create new XMLResource; an id will be assigned to the new resource
        XMLResource document = (XMLResource)col.createResource(null, "XMLResource");
        File f = new File(file);
        if(!f.canRead()) {
            System.out.println("cannot read file " + file);
            return;
        }
        document.setContent(f);
        System.out.print("storing document " + document.getId() + "...");
        col.storeResource(document);
        System.out.println("ok.");
    }
}]]></programlisting>
            </example>
            <para>Please note that the <classname>XMLResource.setContent()</classname> method takes
                a Java object as its parameter. The eXist driver checks if the object is a File.
                Otherwise, the object is transformed into a String by calling the object's
                    <methodname>toString()</methodname> method. Passing a File has one big
                advantage: If the database is running in the embedded mode, the file will be
                directly passed to the indexer. Thus, the file's content does not have to be loaded
                into the main memory. This is handy if your files are very large.</para>

            <title>Extensions to XML:DB</title>

                <title>Additional Services</title>
                <para>eXist provides several services in addition to those defined by the XML:DB
                    specification:</para>
                <para>The <ulink url="api/org/exist/xmldb/UserManagementService.html"
                        >UserManagementService</ulink> service contains methods to manage users and
                    handle permissions. These methods resemble common Unix commands such as
                        <methodname>chown</methodname> or <methodname>chmod</methodname>. As with
                    other services, <classname>UserManagementService</classname> can be retrieved
                    from a collection object, as in:</para>
                <synopsis format="linespecific">UserManagementService service =
                    (UserManagementService)collection.getService("UserManagementService", "1.0");</synopsis>
                <para>Another service called <ulink
                        url="api/org/exist/xmldb/DatabaseInstanceManager.html"
                        >DatabaseInstanceManager</ulink>, provides a single method to shut down the
                    database instance accessed by the driver. You have to be a member of the
                        <option>dba</option> user group to use this method or an exception will be
                    thrown. See the <ulink url="deployment.xml#embedded">Deployment Guide</ulink>
                    for an example.</para>
                <para>Finally, interface <ulink url="api/org/exist/xmldb/IndexQueryService.html"
                        >IndexQueryService</ulink> supports access to the terms and elements
                    contained in eXist's internal index. Method getIndexedElements() returns a list
                    of element occurrences for the current collection. For each occurring element,
                    the element's name and a frequency count is returned.</para>
                <para>Method scanIndexTerms() allows for a retrieval of the list of occurring words
                    for the current collection. This might be useful, for example, to provide users
                    a list of searchable terms together with their frequency.</para>

                <title>Multiple Database Instances</title>
                <para>As explained above, passing a local XML:DB URI to the
                        <classname>DatabaseManager</classname> means that the driver will try to
                    start or access an embedded database instance. You can configure more than one
                    database instance by setting the location of the central configuration file. The
                    configuration file is set through the <option>configuration</option> property of
                    the <classname>DatabaseImpl</classname> driver class. If you would like to use
                    different drivers for different database instances, specify a name for the
                    created instance through the <option>database-id</option> property. You may
                    later use this name in the URI to refer to a database instance. The following
                    fragment sets up two instances:</para>
                <example>
                    <title>Multiple Database Instances</title>
                    <programlisting format="linespecific" language="java"><![CDATA[
// initialize driver
String driver = "org.exist.xmldb.DatabaseImpl";
Class cl = Class.forName(driver);
Database database1 = (Database)cl.newInstance();
database1.setProperty("create-database", "true");
database1.setProperty("configuration", "/home/exist/test/conf.xml");
database1.setProperty("database-id", "test");
DatabaseManager.registerDatabase(database1);

Database database2 = (Database)cl.newInstance();
database2.setProperty("create-database", "true");
database2.setProperty("configuration", "/home/exist/production/conf.xml");
database2.setProperty("database-id", "exist");
DatabaseManager.registerDatabase(database1);
]]></programlisting>
                </example>
                <para>With the above example, the URI</para>
                <synopsis format="linespecific">xmldb:test:///db</synopsis>
                <para>selects the test database instance. Both instances should have their own data
                    and log directory as specified in the configuration files.</para>

            <title>XMLDBTransformer for Cocoon (Deprecated)</title>

            <important>
                <para>The XMLDBTransformer is no longer actively developed since all its
                functionality can be replaced with simple XQuery.</para>
            </important>

            <para>eXist offers several ways to access the database from Cocoon-based applications.
                This includes access via the XMLDB pseudo-protocol, through XSP pages, and through
                the XMLDBTransformer. The XMLDBTransformer provides a simple way to query the
                database, and works in a similar way to other transformers supplied with Cocoon.
                Consult the <ulink url="cocoon.apache.org/">Cocoon documentation</ulink> for more on
                using Transformers and about their basic concepts.</para>
            <para>As with other transformers, the XMLDBTransformer listens for a limited set of tags
                that belong to the namespace <filename moreinfo="none"
                    >http://exist-db/transformer/1.0</filename>. These are
                <sgmltag>collection</sgmltag>, <sgmltag>for-each</sgmltag>,
                <sgmltag>select-node</sgmltag>, <sgmltag>current-node</sgmltag>. To examine how they
                are used, let's consider the following example (Note that the complete version of
                this example can be found at <filename moreinfo="none"
                >webapp/examples/simple2.xml</filename>):</para>
            <example>
                <title>XMLDBTransformer Example</title>
                <programlisting format="linespecific" language="java"><![CDATA[
<xdb:collection xmlns:xdb="http://exist-db.org/transformer/1.0"
	uri="xdb:exist:///db">

	<xdb:for-each query="//rdf:Description[dc:title &= 'computer']"
		from="0" to="9" sort-by="/dc:title">

		<book>

			<title><xdb:select-node query="dc:title/text()"/></title>

			<xdb:for-each query="dc:creator/text()">
				<creator><xdb:current-node/></creator>
			</xdb:for-each>
		</book>
	</xdb:for-each>
</xdb:collection>
]]></programlisting>
            </example>
            <para>As we can see above, before you can start to query the database, you must specify
                a collection in the <sgmltag>collection</sgmltag> element, which accepts a standard
                XMLDB URI in its <option>uri</option> attribute. To process a query, you may either
                use the <sgmltag>for-each</sgmltag>, or the <sgmltag>select-node</sgmltag> tag. The
                difference is the following:</para>
            <itemizedlist>
                <listitem>
                    <para><sgmltag>for-each</sgmltag> iterates over all the results it finds for the
                        given query. The body of the statement will therefore be evaluated for each
                        query result.</para>
                </listitem>
                <listitem>
                    <para><sgmltag>select-node</sgmltag> selects the first result it finds. If the
                        result set contains more than one match, the remaining matches will be
                        ignored.</para>
                </listitem>
            </itemizedlist>
            <para>The <sgmltag>current-node</sgmltag> element is used to return the current node
                being processed in a for-each iteration to the output document. You can restrict the
                number of for-each iterations by specifying the bounds set by the
                <option>from</option> and <option>to</option> attributes. The
                <option>sort-by</option> attribute is still experimental: the query results will be
                sorted by an XPath expression. For each of the results, the XPath expression is
                evaluated and the resulting string value is used to sort the query results in
                ascending order.</para>
            <para>As shown above, it is possible to nest multiple for-each or select-node tags. The
                nested tag will be evaluated relative to the current result node. In the example
                above, the main for-each statement selects all <sgmltag>rdf:Description</sgmltag>
                fragments whose title contains the term "computer". During each iteration, we
                further process the current result fragment by using nested
                <sgmltag>for-each</sgmltag> and <sgmltag>select-node</sgmltag> tags to select the
                title and creators.</para>
            <para>Notice that the same result could be achieved by an XSLT stylesheet. However, if
                the selected fragments are rather large, post-processing with XSLT can be much
                slower, since each fragment has to be serialized and then parsed by the XSLT
                processor.</para>
            <para>The results of the XMLDBTransformer query are enclosed in the element
                    <sgmltag>result-set</sgmltag>. Attributes for this tag include the number of
                hits for the query, the XPath query processed, the query time (in milliseconds), and
                the start and end position of the retrieved records in the result set. The output of
                the XMLDBTransformer for the above fragment is shown below:</para>
            <example>
                <title>XMLDBTransformer Output</title>
<programlisting format="linespecific"><markup><![CDATA[<xdb:result-set count="72" xpath="//rdf:Description[dc:title &= 'computer']"
	query-time="370" from="0" to="9">
	<book xdb:document-id="zit.rdf" xdb:collection="/db/library">
		<title> A Centennial History of the American Society of Mechanical Engineers 1880-1980 </title>
		<creator xdb:document-id="zit.rdf" xdb:collection="/db/library"> Sinclair, Bruce </creator>
	</book>

</xdb:result-set>]]></markup></programlisting>
            </example>

            <title>XML:DB Logicsheet for Cocoon</title>
            <important>
                <para>The XMLDB logicsheet is no longer actively developed. The XQueryGenerator
                provides a much easier way to generate web page contents.</para>
            </important>

            <para>Cocoon offers a powerful mechanism called XSP (eXtensible Server Pages) to write
                dynamic XML-based web pages. Similar to JSP, XSP embeds Java code in the XML pages.
                However, embedding large sections of Java code in an XML document is usually
                considered poor programming form. To support the separation of content and
                programming logic, XSP allows us to put reusable code into "logicsheets", which
                correspond to the tag libraries found in JSP. A logicsheet helps to minimize the
                amount of Java code used inside an XSP page.</para>
            <para>Version 0.8 of eXist includes a logicsheet based on the XML:DB API, which defines
                tags for all important tasks. While it is possible to write all of the XML:DB
                related code by hand, these predefined tags make the XML file more readable and
                helps users without Java experience to understand the process involved.</para>
            <para>An overview of the available XSP tags is available with the <ulink
                    url="xmldb/xsl.html">stylesheet documentation</ulink> (generated using <ulink
                    url="www.xsldoc.org">xsldoc</ulink>). In the following simple XSP example, a
                document is retrieved and displayed:</para>
            <example>
                <title>Simple XSP Page (example1.xsp)</title>
                <programlisting format="linespecific">
<markup><![CDATA[<xsp:page xmlns:xsp="http://apache.org/xsp"
          xmlns:xdb="http://exist-db.org/xmldb/1.0"
>
<document>

Retrieving document <xsp:expr>request.getParameter("doc")</xsp:expr>

        <xdb:collection uri="xdb:exist:///db/shakespeare/plays">
            <xml-source>
                <xdb:get-document encoding="ISO-8859-1" as="xml">
                     <xdb:name>request.getParameter("doc")</xdb:name>
                </xdb:get-document>
            </xml-source>
        </xdb:collection>

</document>
</xsp:page>]]></markup></programlisting>
            </example>
            <para>The Cocoon version included with eXist is already configured to recognize the
                    <filename>xmldb</filename> namespace and associate it with the XML:DB
                logicsheet. The logicsheet is defined in <filename moreinfo="none"
                    >src/org/exist/xmldb.xsl</filename>. To use the logicsheet from our page we just
                declare the xmldb namespace (i.e. xmlns:xdb="http://exist-db.org/xmldb/1.0").</para>
            <para>The above sample code retrieves a document from the collection <filename
                    moreinfo="none">/db/shakespeare/plays</filename>. The name of the document is
                passed in the HTTP request parameter <parameter>doc</parameter>.</para>
            <para>To post-process the retrieved XML data, we set the attribute
                <parameter>as</parameter> to "xml". This indicates that the resource should be fed
                into the current Cocoon processing stream. To include the data as a string value,
                you may specify <parameter moreinfo="none">as="string"</parameter>. As a result, all
                XML markup characters will be escaped.</para>
            <para>Please note that the parameters of the logicsheet tags may be specified either as
                an attribute of an element or as a child element. If you specify a parameter as a
                child element, its content will be interpreted as a Java expression. Literal values
                should be set via an attribute. For example, the <parameter moreinfo="none"
                >xpath</parameter> parameter is specified as a Java expression, it is thus embedded
                in an <sgmltag>xdb:xpath</sgmltag> element.</para>
            <para>Finally, in order to tell Cocoon how to process this page, we have to add a new
                    <sgmltag>map:match</sgmltag>pattern to the sitemap - for example:</para>
            <example>
                <title>Cocoon Sitemap Snippet (XSP)</title>
                <programlisting format="linespecific"><markup><![CDATA[
<map:match pattern="test.xsp">
    <map:generate type="serverpages" src="test.xsp"/>
    <map:transform src="stylesheets/doc2html-2.xsl"/>
    <map:serialize type="xhtml"/>
</map:match>
]]></markup></programlisting>
            </example>
            <para>The next example shows how to query the database:</para>
            <example>
                <title>Querying the Database (example2.xsp)</title>
                <programlisting format="linespecific"><markup><![CDATA[
<xsp:page xmlns:xsp="http://apache.org/xsp"
          xmlns:xdb="http://exist-db.org/xmldb/1.0"
>

Find books by title

            <xdb:collection uri="xdb:exist:///db">
                <xdb:execute>
                    <xdb:xpath>
                        "xmldb:document()//rdf:Description[dc:title" +
                        "&='" + request.getParameter("title") + "']"
                    </xdb:xpath>

Found <xdb:get-hit-count/> hits.

                    <xdb:results>

                            <xdb:get-xml as="string"/>

                    </xdb:results>
                </xdb:execute>
            </xdb:collection>

</xsp:page>
]]></markup></programlisting>
            </example>
            <para>This XSP example page takes the HTTP request parameter
                <parameter>title</parameter> as its input and creates an XPath expression that finds
                all <sgmltag>df:Description</sgmltag> elements having a <sgmltag>dc:title</sgmltag>
                element containing the keywords entered by the user. As required by the XML:DB API,
                any action has to be enclosed in an <sgmltag>xdb:collection</sgmltag> element. The
                query is specified in the <sgmltag>xdb:xpath</sgmltag> element using a Java
                expression, which inserts the value of the request parameter
                <parameter>title</parameter> into the XPath query string.</para>
            <para>The <sgmltag>xdb:results</sgmltag> element will iterate through the generated
                result set, inserting each resource into the page by calling
                <sgmltag>xdb:get-xml</sgmltag>. In this case, <sgmltag>xdb:get-xml</sgmltag> inserts
                the resource contents as a string, which means that all XML markup is
            escaped.</para>

    </chapter>
</book>


text:
"""
server.py

Created by Thomas Mangin on 2011-11-30.
Copyright (c) 2011-2013  Exa Networks. All rights reserved.
"""

# http://code.google.com/speed/articles/web-metrics.html

import errno

errno_block = set((
	errno.EINPROGRESS, errno.EALREADY,
	errno.EAGAIN, errno.EWOULDBLOCK,
	errno.EINTR, errno.EDEADLK,
	errno.EBUSY, errno.ENOBUFS,
	errno.ENOMEM,
))

errno_fatal = set((
	errno.ECONNABORTED, errno.EPIPE,
	errno.ECONNREFUSED, errno.EBADF,
	errno.ESHUTDOWN, errno.ENOTCONN,
	errno.ECONNRESET, errno.ETIMEDOUT,
	errno.EINVAL,
))

errno_unavailable = set((
	errno.ECONNREFUSED, errno.EHOSTUNREACH,
))

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Novuso\Common\Adapter\Config\Directory;

use Novuso\Common\Application\Config\ConfigContainer;
use Novuso\Common\Application\Config\ConfigLoader;
use Novuso\Common\Application\Config\Exception\ConfigLoaderException;
use Novuso\Common\Application\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\Yaml\Yaml;
use Throwable;

/**
 * Class YamlConfigEnvLoader
 */
final class YamlConfigEnvLoader implements ConfigLoader
{
    /**
     * Constructs YamlConfigEnvLoader
     */
    public function __construct(
        protected Filesystem $filesystem,
        protected string $environment
    ) {
    }

    /**
     * @inheritDoc
     */
    public function load(mixed $resource, ?string $type = null): ConfigContainer
    {
        $config = $this->loadConfig($resource);

        $envDirectory = sprintf('%s/%s', $resource, $this->environment);
        if ($this->filesystem->isDir($envDirectory)) {
            $envConfig = $this->loadConfig($envDirectory);
            $config = $config->merge($envConfig);
        }

        $config->freeze();

        return $config;
    }

    /**
     * @inheritDoc
     */
    public function supports(mixed $resource, ?string $type = null): bool
    {
        return $this->filesystem->isDir($resource)
            && $type !== null
            && in_array(strtolower($type), ['yml', 'yaml']);
    }

    /**
     * Loads configuration from a directory
     *
     * @throws ConfigLoaderException
     */
    protected function loadConfig(string $directory): ConfigContainer
    {
        try {
            $config = new ConfigContainer();

            $files = Finder::create()
                ->files()
                ->name('*.yml')
                ->in($directory)
                ->depth('== 0');

            /** @var SplFileInfo $file */
            foreach ($files as $file) {
                $name = $file->getBasename('.yml');
                $data = Yaml::parse($this->filesystem->get(sprintf(
                    '%s/%s',
                    $file->getPath(),
                    $file->getFilename()
                )));
                if (!is_array($data)) {
                    $message = sprintf(
                        'YAML config must be an array; received (%s) from %s',
                        gettype($data),
                        sprintf('%s/%s', $file->getPath(), $file->getFilename())
                    );
                    throw new ConfigLoaderException($message);
                }
                $config->set($name, $data);
            }

            return $config;
        } catch (Throwable $e) {
            throw new ConfigLoaderException(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
    }
}


text:
'''

    Payment Gateway Transaction

    :copyright: (c) 2013 by Openlabs Technologies & Consulting (P) Ltd.
    :license: BSD, see LICENSE for more details

'''
import authorize
from authorize.exceptions import AuthorizeInvalidError, \
    AuthorizeResponseError
from trytond.pool import PoolMeta, Pool
from trytond.pyson import Eval
from trytond.model import fields
from trytond import backend
from trytond.transaction import Transaction

__all__ = [
    'PaymentGatewayAuthorize', 'AddPaymentProfileView', 'AddPaymentProfile',
    'AuthorizeNetTransaction', 'Party', 'Address', 'PaymentProfile'
]
__metaclass__ = PoolMeta

class PaymentGatewayAuthorize:
    "Authorize.net Gateway Implementation"
    __name__ = 'payment_gateway.gateway'

    authorize_net_login = fields.Char(
        'API Login', states={
            'required': Eval('provider') == 'authorize_net',
            'invisible': Eval('provider') != 'authorize_net',
            'readonly': ~Eval('active', True),
        }, depends=['provider', 'active']
    )
    authorize_net_transaction_key = fields.Char(
        'Transaction Key', states={
            'required': Eval('provider') == 'authorize_net',
            'invisible': Eval('provider') != 'authorize_net',
            'readonly': ~Eval('active', True),
        }, depends=['provider', 'active']
    )

    @classmethod
    def get_providers(cls, values=None):
        """
        Downstream modules can add to the list
        """
        rv = super(PaymentGatewayAuthorize, cls).get_providers()
        authorize_record = ('authorize_net', 'Authorize.net')
        if authorize_record not in rv:
            rv.append(authorize_record)
        return rv

    def get_methods(self):
        if self.provider == 'authorize_net':
            return [
                ('credit_card', 'Credit Card - Authorize.net'),
            ]
        return super(PaymentGatewayAuthorize, self).get_methods()

    def get_authorize_client(self):
        """
        Return an authenticated authorize.net client.
        """
        assert self.provider == 'authorize_net', 'Invalid provider'
        authorize.Configuration.configure(
            authorize.Environment.TEST if self.test else authorize.Environment.PRODUCTION,  # noqa
            self.authorize_net_login,
            self.authorize_net_transaction_key,
        )

class AuthorizeNetTransaction:
    """
    Implement the authorize and capture methods
    """
    __name__ = 'payment_gateway.transaction'

    @classmethod
    def __setup__(cls):
        super(AuthorizeNetTransaction, cls).__setup__()

        cls._error_messages.update({
            'cancel_only_authorized': 'Only authorized transactions can be' + (
                ' cancelled.'),
        })

    def authorize_authorize_net(self, card_info=None):
        """
        Authorize using authorize.net for the specific transaction.
        """
        TransactionLog = Pool().get('payment_gateway.transaction.log')

        # Initialize authorize client
        self.gateway.get_authorize_client()

        auth_data = self.get_authorize_net_request_data()
        if card_info:
            billing_address = self.address.get_authorize_address(
                card_info.owner)
            shipping_address = {}
            if self.shipping_address:
                shipping_address = self.shipping_address.get_authorize_address(
                    card_info.owner)

            auth_data.update({
                'email': self.party.email,
                'credit_card': {
                    'card_number': card_info.number,
                    'card_code': str(card_info.csc),
                    'expiration_date': "%s/%s" % (
                        card_info.expiry_month, card_info.expiry_year
                    ),
                },
                'billing': billing_address,
                'shipping': shipping_address,
            })

        elif self.payment_profile:
            if self.shipping_address:
                if self.shipping_address.authorize_id:
                    address_id = self.shipping_address.authorize_id
                else:
                    address_id = self.shipping_address.send_to_authorize(
                        self.payment_profile.authorize_profile_id)
            else:
                if self.address.authorize_id:
                    address_id = self.address.authorize_id
                else:
                    address_id = self.address.send_to_authorize(
                        self.payment_profile.authorize_profile_id)
            auth_data.update({
                'customer_id': self.payment_profile.authorize_profile_id,
                'payment_id': self.payment_profile.provider_reference,
                'address_id': address_id,
            })
        else:
            self.raise_user_error('no_card_or_profile')

        try:
            result = authorize.Transaction.auth(auth_data)
        except AuthorizeResponseError, exc:
            self.state = 'failed'
            self.save()
            TransactionLog.serialize_and_create(self, exc.full_response)
        else:
            self.state = 'authorized'
            self.provider_reference = str(result.transaction_response.trans_id)
            self.save()
            TransactionLog.serialize_and_create(self, result)

    def settle_authorize_net(self):
        """
        Settles this transaction if it is a previous authorization.
        """
        TransactionLog = Pool().get('payment_gateway.transaction.log')

        # Initialize authorize.net client
        self.gateway.get_authorize_client()

        try:
            result = authorize.Transaction.settle(
                self.provider_reference, self.amount
            )
        except AuthorizeResponseError, exc:
            self.state = 'failed'
            self.save()
            TransactionLog.serialize_and_create(self, exc.full_response)
        else:
            self.state = 'completed'
            self.provider_reference = str(result.transaction_response.trans_id)
            self.save()
            TransactionLog.serialize_and_create(self, result)
            self.safe_post()

    def capture_authorize_net(self, card_info=None):
        """
        Capture using authorize.net for the specific transaction.
        """
        TransactionLog = Pool().get('payment_gateway.transaction.log')

        # Initialize authorize client
        self.gateway.get_authorize_client()

        capture_data = self.get_authorize_net_request_data()
        if card_info:
            billing_address = self.address.get_authorize_address(
                card_info.owner)
            shipping_address = {}
            if self.shipping_address:
                shipping_address = self.shipping_address.get_authorize_address(
                    card_info.owner)

            capture_data.update({
                'email': self.party.email,
                'credit_card': {
                    'card_number': card_info.number,
                    'card_code': str(card_info.csc),
                    'expiration_date': "%s/%s" % (
                        card_info.expiry_month, card_info.expiry_year
                    ),
                },
                'billing': billing_address,
                'shipping': shipping_address,
            })

        elif self.payment_profile:
            if self.shipping_address:
                if self.shipping_address.authorize_id:
                    address_id = self.shipping_address.authorize_id
                else:
                    address_id = self.shipping_address.send_to_authorize(
                        self.payment_profile.authorize_profile_id)
            else:
                if self.address.authorize_id:
                    address_id = self.address.authorize_id
                else:
                    address_id = self.address.send_to_authorize(
                        self.payment_profile.authorize_profile_id)
            capture_data.update({
                'customer_id': self.payment_profile.authorize_profile_id,
                'payment_id': self.payment_profile.provider_reference,
                'address_id': address_id,
            })
        else:
            self.raise_user_error('no_card_or_profile')

        try:
            result = authorize.Transaction.sale(capture_data)
        except AuthorizeResponseError, exc:
            self.state = 'failed'
            self.save()
            TransactionLog.serialize_and_create(self, exc.full_response)
        else:
            self.state = 'completed'
            self.provider_reference = str(result.transaction_response.trans_id)
            self.save()
            TransactionLog.serialize_and_create(self, result)
            self.safe_post()

    def retry_authorize_net(self, credit_card=None):  # pragma: no cover
        """
        Authorize using Authorize.net for the specific transaction.

        :param credit_card: An instance of CreditCardView
        """
        raise self.raise_user_error('feature_not_available')

    def update_authorize_net(self):  # pragma: no cover
        """
        Update the status of the transaction from Authorize.net
        """
        raise self.raise_user_error('feature_not_available')

    def cancel_authorize_net(self):
        """
        Cancel this authorization or request
        """
        TransactionLog = Pool().get('payment_gateway.transaction.log')

        if self.state != 'authorized':
            self.raise_user_error('cancel_only_authorized')

        # Initialize authurize.net client
        self.gateway.get_authorize_client()

        # Try to void the transaction
        try:
            result = authorize.Transaction.void(self.provider_reference)
        except AuthorizeResponseError, exc:
            TransactionLog.serialize_and_create(self, exc.full_response)
        else:
            self.state = 'cancel'
            self.save()
            TransactionLog.serialize_and_create(self, result)

    def get_authorize_net_request_data(self):
        """
        Downstream modules can modify this method to send extra data to
        authorize.net

        Ref: http://vcatalano.github.io/py-authorize/transaction.html
        """
        return {
            'amount': self.amount
        }

class AddPaymentProfileView:
    __name__ = 'party.payment_profile.add_view'

    @classmethod
    def get_providers(cls):
        """
        Return the list of providers who support credit card profiles.
        """
        res = super(AddPaymentProfileView, cls).get_providers()
        res.append(('authorize_net', 'Authorize.net'))
        return res

class AddPaymentProfile:
    """
    Add a payment profile
    """
    __name__ = 'party.party.payment_profile.add'

    def transition_add_authorize_net(self):
        """
        Handle the case if the profile should be added for authorize.net
        """
        card_info = self.card_info

        # Initialize authorize.net client
        card_info.gateway.get_authorize_client()

        customer_id = card_info.party._get_authorize_net_customer_id(
            card_info.gateway.id
        )
        # Create new customer profile if no old profile is there
        if not customer_id:
            customer_id = self.create_auth_customer_profile()

        # Now create new credit card and associate it with the above
        # created customer
        credit_card_data = {
            'card_number': card_info.number,
            'card_code': str(card_info.csc),
            'expiration_date': "%s/%s" % (
                card_info.expiry_month, card_info.expiry_year
            ),
            'billing': card_info.address.get_authorize_address(card_info.owner)
        }
        for try_count in range(2):
            try:
                credit_card = authorize.CreditCard.create(
                    customer_id, credit_card_data
                )
                # Validate newly created credit card
                authorize.CreditCard.validate(
                    customer_id, credit_card.payment_id, {
                        'card_code': credit_card_data['card_code'],
                        'validationMode': 'testMode' if card_info.gateway.test
                        else 'liveMode'
                    }
                )
                break
            except AuthorizeInvalidError, exc:
                self.raise_user_error(unicode(exc))
            except AuthorizeResponseError, exc:
                if try_count == 0 and 'E00039' in unicode(exc):
                    # Delete all unused payment profiles on authorize.net
                    customer_details = authorize.Customer.details(customer_id)
                    auth_payment_ids = set([
                        p.payment_id for p in customer_details.profile.payments
                    ])
                    if card_info.party.payment_profiles:
                        local_payment_ids = set([
                            p.provider_reference for p in card_info.party.payment_profiles  # noqa
                        ])
                        ids_to_delete = auth_payment_ids.difference(
                            local_payment_ids
                        )
                    else:
                        ids_to_delete = auth_payment_ids

                    if ids_to_delete:
                        for payment_id in ids_to_delete:
                            authorize.CreditCard.delete(customer_id, payment_id)
                    continue
                self.raise_user_error(unicode(exc.message))

        return self.create_profile(
            credit_card.payment_id,
            authorize_profile_id=customer_id
        )

    def create_auth_customer_profile(self):
        """
        Creates a customer profile on authorize.net and returns
        created profile's ID
        """
        customer_party = self.card_info.party
        try:
            customer = authorize.Customer.create({
                'description': customer_party.name,
                'email': customer_party.email,
            })
        except AuthorizeInvalidError, exc:
            self.raise_user_error(unicode(exc))

        return customer.customer_id

class Party:
    __name__ = 'party.party'

    @classmethod
    def __register__(cls, module_name):
        super(Party, cls).__register__(module_name)

        PaymentProfile = Pool().get('party.payment_profile')

        TableHandler = backend.get('TableHandler')
        cursor = Transaction().cursor
        table = TableHandler(cursor, cls, module_name)
        party = cls.__table__()
        payment_profile = PaymentProfile.__table__()

        # Migration
        # Move the content of authorize_profile_id from party to
        # payment profiles and drop authorize_profile_id from party table
        if table.column_exist('authorize_profile_id'):
            update = payment_profile.update(
                columns=[payment_profile.authorize_profile_id],
                values=[party.authorize_profile_id],
                from_=[party],
                where=(payment_profile.party == party.id)
            )
            cursor.execute(*update)

            table.drop_column('authorize_profile_id')

    def _get_authorize_net_customer_id(self, gateway_id):
        """
        Extracts and returns customer id from party's payment profile
        Return None if no customer id is found.

        :param gateway_id: The gateway ID to which the customer id is associated
        """
        PaymentProfile = Pool().get('party.payment_profile')

        payment_profiles = PaymentProfile.search([
            ('party', '=', self.id),
            ('authorize_profile_id', '!=', None),
            ('gateway', '=', gateway_id),
        ])
        if payment_profiles:
            return payment_profiles[0].authorize_profile_id
        return None

class Address:
    __name__ = 'party.address'

    authorize_id = fields.Char(
        'Authorize.net ID', readonly=True
    )

    def send_to_authorize(self, profile_id):
        """
        Helpler method which creates a new address record on
        authorize.net servers and returns it's ID.

        :param profile_id: The profile_id of customer profile for
            which you want to create address. Required if create=True
        """
        Address = Pool().get('party.address')

        for try_count in range(2):
            try:
                address = authorize.Address.create(
                    profile_id, self.get_authorize_address()
                )
                break
            except AuthorizeResponseError, exc:
                if try_count == 0 and 'E00039' in unicode(exc):
                    # Delete all addresses on authorize.net
                    self.delete_authorize_addresses(profile_id)
                    continue
                self.raise_user_error(unicode(exc.message))
            except AuthorizeInvalidError, exc:
                self.raise_user_error(unicode(exc))

        address_id = address.address_id

        Address.write([self], {
            'authorize_id': address_id,
        })
        return address_id

    def get_authorize_address(self, name=None):
        """
        Returns address as a dictionary to send to authorize.net

        :param name: Name to send as first name in address.
            Default is party's name.
        """
        return {
            'first_name': name or self.name or self.party.name,
            'last_name': '',
            'company': '',
            'address': '\n'.join(filter(None, [self.street, self.streetbis])),
            'city': self.city,
            'state': self.subdivision and self.subdivision.code,
            'zip': self.zip,
            'country': self.country and self.country.code,
            'phone_number': self.party.phone,
            'fax_number': self.party.fax,
        }

    def delete_authorize_addresses(self, profile_id):
        """
        Delete all shipping addresses for customer on authorize.net
        """
        Address = Pool().get('party.address')

        customer_details = authorize.Customer.details(profile_id)
        address_ids = [
            a.address_id for a in customer_details.profile.addresses
        ]
        for address_id in address_ids:
            authorize.Address.delete(profile_id, address_id)

        # Set authorize_id none for all party addresses
        Address.write(list(self.party.addresses), {
            'authorize_id': None,
        })

class PaymentProfile:
    __name__ = 'party.payment_profile'

    authorize_profile_id = fields.Char(
        'Authorize.net Profile ID', readonly=True
    )


text:
<?php
namespace sim\modules\admin\components;

use yii\helpers\VarDumper;

class Controller extends \yii\web\Controller
{

    public function __construct($id, $module, $config = [])
    {
        parent::__construct($id, $module, $config);

        $this->view->params['menu'] = [
            ['label' => \Yii::t('admin', 'Manage Modules'), 'url' => ['/admin/module/index']],
            ['label' => \Yii::t('admin', 'Create Module'), 'url' => ['/admin/module/create']],
            ['label'=>''],
            ['label' => \Yii::t('admin', 'Manage Posts'), 'url' => ['/post/admin/default/index']],
            ['label' => \Yii::t('admin', 'Create Post'), 'url' => ['/post/admin/default/create']]
        ];
        $this->layout = "admin";
    }

}


text:
/* DO NOT EDIT! This file is generated. */

var require;
if (!require) require = {config: function (x) {require = x;}};
require.config({
  "paths": {
    "typeahead": "bower_components/typeahead.js/dist/typeahead.jquery",
    "helios/showdown": "bower_components/showdown/src/showdown",
    "requireJS": "node_modules/requirejs/require",
    "require-css": "bower_components/require-css",
    "jquery": "bower_components/jquery/dist/jquery",
    "jquery-ui": "bower_components/jquery-ui/jquery-ui",
    "codemirror": "bower_components/codemirror",
    "bootstrap": "bower_components/bootstrap/dist",
    "mousetrap": "bower_components/mousetrap/mousetrap",
    "jquery.blockUI": "bower_components/blockui/jquery.blockUI",
    "socket.io": "bower_components/socket.io-client/socket.io",
    "linda-client": "node_modules/linda/lib/linda-client",
    "knockout": "bower_components/knockout/dist/knockout",
    "silk": "bower_components/silk/src",
    "helios": "bower_components/helios/src",
    "helios/resources": "bower_components/helios/resources",
    "helios/index": "bower_components/helios/index",
    "amber-ide-starter-dialog": "bower_components/amber-ide-starter-dialog/lib/idestarter",
    "amber/web": "bower_components/amber-contrib-web/src",
    "amber/legacy": "bower_components/amber-contrib-legacy/src",
    "amber/legacy/resources": "bower_components/amber-contrib-legacy/resources",
    "amber/jquery": "bower_components/amber-contrib-jquery/src",
    "amber/domite": "bower_components/amber-contrib-domite/src",
    "amber": "bower_components/amber/support",
    "amber_core": "bower_components/amber/src",
    "amber-lindaclient": "src"
  },
  "shim": {
    "typeahead": {
      "deps": [
        "jquery"
      ],
      "exports": "jQuery.fn.typeahead"
    },
    "jquery-ui": {
      "deps": [
        "jquery",
        "jquery"
      ]
    },
    "codemirror/lib/codemirror": {
      "deps": [
        "css!codemirror/lib/codemirror",
        "css!codemirror/lib/codemirror"
      ]
    },
    "bootstrap/js/bootstrap": {
      "deps": [
        "jquery",
        "css!bootstrap/css/bootstrap"
      ]
    },
    "linda-client": {
      "deps": [
        "socket.io"
      ]
    },
    "ensure-console": {
      "exports": "console"
    }
  },
  "map": {
    "*": {
      "css": "require-css/css",
      "00comment": "These are backward compatibility pointers.",
      "amber-contrib-web/Web": "amber/web/Web",
      "amber_core/Web": "amber/web/Web",
      "amber_core/Canvas": "amber/web/Web",
      "amber-attic/Benchfib": "amber/legacy/Benchfib",
      "amber-attic/Examples": "amber/legacy/Examples",
      "amber-attic/IDE": "amber/legacy/IDE",
      "amber-contrib-jquery/Wrappers-JQuery": "amber/jquery/Wrappers-JQuery",
      "domite/DOMite": "amber/domite/DOMite",
      "domite/DOMite-Tests": "amber/domite/DOMite-Tests",
      "amber_core/Kernel-ImportExport": "amber_core/Platform-ImportExport"
    }
  }
});


text:
require_relative 'base_cocca2'

module Whois
  class Parsers

    # Parser for the whois.nic.tc server.
    #
    # @see Whois::Parsers::Example
    #   The Example parser for the list of all available methods.
    #
    class WhoisNicTc < BaseCocca2
    end

  end
end


text:
#ifndef RESONANCE_AUDIO_UTILS_BUFFER_UNPARTITIONER_H_
#define RESONANCE_AUDIO_UTILS_BUFFER_UNPARTITIONER_H_

#include <functional>
#include <memory>

#include "base/audio_buffer.h"
#include "base/logging.h"

namespace vraudio {

// Unpackages |AudioBuffer| into output buffers of arbitrary sizes.
class BufferUnpartitioner {
 public:
  // Callback to obtain input |AudioBuffer|s. Returns a nullptr if no buffers
  // are available.
  typedef std::function<const AudioBuffer*()> GetBufferCallback;

  // Constructor.
  //
  // @param num_channels Number of audio channels in input and output buffers.
  // @param frames_per_buffer Number of frames per input buffer.
  // @param buffer_callback Callback to receive output |AudioBuffer|s.
  BufferUnpartitioner(size_t num_channels, size_t frames_per_buffer,
                      GetBufferCallback buffer_callback);

  // Returns the number of input buffers required for a given number of output
  // frames and based on the current fill state of the internal |temp_buffer_|.
  //
  // @param num_output_frames Number of output frames.
  // @return Number of required input |AudioBuffer|s.
  size_t GetNumBuffersRequestedForNumInputFrames(
      size_t num_output_frames) const;

  // Returns the number of buffered frames in internal |temp_buffer_|.
  size_t GetNumBufferedFrames() const;

  // Requests an interleaved int16 output buffer. This method triggers
  // |GetBufferCallback|.
  //
  // @param output_buffer Interleaved output buffer to write to.
  // @param num_channels Number of channels in output buffer.
  // @param num_frames Number of frames in output buffer.
  // @return Number of frames actually written.
  size_t GetBuffer(int16* output_buffer, size_t num_channels,
                   size_t num_frames);

  // Requests an interleaved float output buffer. This method triggers
  // |GetBufferCallback|.
  //
  // @param output_buffer Interleaved output buffer to write to.
  // @param num_channels Number of channels in output buffer.
  // @param num_frames Number of frames in output buffer.
  // @return Number of frames actually written.
  size_t GetBuffer(float* output_buffer, size_t num_channels,
                   size_t num_frames);

  // Requests a planar int16 output buffer. This method triggers
  // |GetBufferCallback|.
  //
  // @param output_buffer Planar output buffer to write to.
  // @param num_channels Number of channels in output buffer.
  // @param num_frames Number of frames in output buffer.
  // @return Number of frames actually written.
  size_t GetBuffer(int16** output_buffer, size_t num_channels,
                   size_t num_frames);

  // Requests a planar float output buffer. This method triggers
  // |GetBufferCallback|.
  //
  // @param output_buffer Planar output buffer to write to.
  // @param num_channels Number of channels in output buffer.
  // @param num_frames Number of frames in output buffer.
  // @return Number of frames actually written.
  size_t GetBuffer(float** output_buffer, size_t num_channels,
                   size_t num_frames);

  // Clears internal temporary buffer that holds remaining audio frames.
  void Clear();

 private:
  // Returns the number of frames that are buffered in |current_input_buffer_|.
  //
  // @return Number of frames in |current_input_buffer_|. If
  //     |current_input_buffer_| is undefined, it returns 0.
  size_t GetNumFramesAvailableInBuffer() const;

  // Writes output buffer into target buffer. Supported buffer types are planar
  // and interleaved floating point abd interleaved int16 output. This method
  // triggers |GetBufferCallback|.
  //
  // @tparam BufferType Output buffer type.
  // @param buffer Output buffer to write to.
  // @param num_channels Number of channels in output buffer.
  // @param num_frames Number of frames in output buffer.
  // @return Number of frames actually written.
  template <typename BufferType>
  size_t GetBufferTemplated(BufferType buffer, size_t num_channels,
                            size_t num_frames);

  // Number of channels in output buffers.
  const size_t num_channels_;

  // Number of frames per buffer in output buffers.
  const size_t frames_per_buffer_;

  // Callback to request input |AudioBuffer|s.
  const GetBufferCallback buffer_callback_;

  // Temporary buffer containing remaining audio frames.
  const AudioBuffer* current_input_buffer_;  // Not owned.

  // Current read position in |current_input_buffer_|.
  size_t current_buffer_read_offset_frames_;
};

}  // namespace vraudio

#endif  // RESONANCE_AUDIO_UTILS_BUFFER_UNPARTITIONER_H_


text:
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;

namespace Thinktecture.IdentityModel.Tokens.Http
{
    class HttpsSecurityTokenHandler : X509SecurityTokenHandler
    {
        public HttpsSecurityTokenHandler()
            : base(X509CertificateValidator.None)
        {
            Configuration = new SecurityTokenHandlerConfiguration
            {
                IssuerNameRegistry = new HttpsIssuerNameRegistry()
            };
        }
    }
}


text:
package org.apache.eagle.metric.reportor;

import com.google.common.util.concurrent.AtomicDouble;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public abstract class EagleMetric implements IEagleMetric {

    public long latestUserTimeClock;
    public AtomicDouble value;
    public String name;
    public long granularity;
    public List<EagleMetricListener> metricListeners = new ArrayList<>();
    private static final Logger LOG = LoggerFactory.getLogger(EagleCounterMetric.class);

    public EagleMetric(EagleMetric metric) {
        this.latestUserTimeClock = metric.latestUserTimeClock;
        this.name = metric.name;
        this.value = new AtomicDouble(metric.value.doubleValue());
        this.granularity = metric.granularity;
    }

    public EagleMetric(long latestUserTimeClock, String name, double value, long granularity) {
        this.latestUserTimeClock = latestUserTimeClock;
        this.name = name;
        this.value = new AtomicDouble(value);
        this.granularity = granularity;
    }

    public EagleMetric(long latestUserTimeClock, String metricName, double value) {
        this(latestUserTimeClock, metricName, value, 5 * DateUtils.MILLIS_PER_MINUTE);
    }

    public void registerListener(EagleMetricListener listener) {
        metricListeners.add(listener);
    }

    public Double getValue() {
        return value.doubleValue();
    }
}


text:
from django.template.loader import get_template
from django.views.generic import TemplateView

from pygments import highlight
from pygments.lexers import DjangoLexer
from pygments.formatters import HtmlFormatter

class TemplateWithContextView(TemplateView):
    context = None
    config = None
    usage_name = None

    def get_template_names(self):
        if self.request.GET.get("source"):
            return "source.html"
        return super().get_template_names()

    def get_context_data(self, *args, **kwargs):
        ctx = super(TemplateWithContextView, self).get_context_data(*args, **kwargs)

        if self.config and self.config.template_source:
            # Explicit template source(s) takes priority
            if isinstance(self.config.template_source, str):
                # single template source file path
                template_sources = [self.config.template_source]
                if self.template_name and self.template_name != self.config.template_source:
                    self.usage_name = self.template_name
            else:
                # expecting an iterable of template source file paths
                template_sources = self.config.template_source
                self.usage_name = self.template_name
        elif self.template_name:
            # Default template
            template_sources = [self.template_name]

        templates = []
        for source in template_sources:
            # Add dictionary with name and source
            template = get_template(source)
            template_source = highlight(template.template.source, DjangoLexer(), HtmlFormatter())
            templates.append(dict(name=source, source=template_source))
        ctx.update({"templates": templates})

        # Display snippet usage
        if self.usage_name:
            usage = get_template(self.usage_name)
            usage_source = highlight(usage.template.source, DjangoLexer(), HtmlFormatter())
            ctx.update({"usage_source": usage_source})

        if self.context is not None:
            ctx.update(self.context)
        return ctx

def as_view(template, config, **kwargs):
    return TemplateWithContextView.as_view(template_name=template, config=config, context=kwargs)