text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Audio Software Intern</title>
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="#Music. DSP. Electronics. A musician creating technology for music. Electronics nerd. Will wash dishes for DSP. Can run a 5k for C++.
">
    <meta name="author" content="Ravikumar Rithesh Kumar">
    <link rel="canonical" href="https://www.linkedin.com/in/ritheshkumar/c++,%20dsp/2014/07/15/Audio-Software-Intern/">
    <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">

    <link rel="stylesheet" href="/style.css">

    <link rel="stylesheet" href="/css/font-awesome/css/font-awesome.min.css">
    <link href="//fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="//fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Rithesh Kumar Ravikumar

                        Portfolio

                        About

                        Contact

                        Rithesh Kumar Ravikumar

                        Music. DSP. Electronics.

Portfolio

About

A musician creating technology for music. Electronics nerd. Has crossed continents for DSP. Can run a 5k for C++.

                         Download Resume

Contact Me

				<form  action="//formspree.io/ritheshrkumar@gmail.com" method="POST" name="sentMessage" id="contactForm" novalidate>

							Name
							<input type="text" name="name" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">

							Email Address
							<input type="email" name="_replyto" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">

						<input type="hidden"  name="_subject" value="New submission!">
						<input type="text" name="_gotcha" style="display:none" />

							Message
							<textarea rows="5" name="message" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>

							<button type="submit" class="btn btn-success btn-lg">Send</button>

				</form>

Location

                                Atlanta, GA 30318

Around the Web

Credits

Freelancer is a free to use, open source Bootstrap theme created by Start Bootstrap.

                        Copyright © R. Rithesh Kumar 2016

Vocopter

VoCopter is a voice controlled video game, written using the JUCE framework. It converts a raw MIDI file into obstacles. Player has to maneuver the copter through the obstacles by singing the right pitch.

Date:

                                    April 2016

Category:
                                    Realtime DSP

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Mono2stereo

A simple plugin to convert a mono track to stereo sound. Contains intuitive spatialization controls. Click  here for video.

Date:

                                    April 2016

Category:
                                    Audio Plugins, Realtime DSP

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Pseudo Shazam

Built a song recognition app in MATLAB using Audio Fingerprinting. This algorithm was a foundation for Shazam's core algorithm.

Date:

                                    December 2015

Category:
                                    Music Information Retrieval, DSP

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Monk Ensemble

A song composition, exploring the interaction between human and robotic musicians. Click here for video.

Date:

                                    April 2014

Category:
                                    Realtime DSP, Music Composition, Robotic Musicianship

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

The Mangler

Co-built a waveshaper synthesizer module. The schematic is based off Buchla Timbre Easel's waveshaper.

Date:

                                    April 2015

Category:
                                    Analog Electronics

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Moog Hackathon

Second runner up in Moog Hackathon held at Georgia Tech Centre for Music Technology. A 3D printed object with touch sensors and Inertial Measurement Unit controls a synthesizer based on Gesture Recognition. The synthesizer output runs through a glass plate reverb for acoustic effect.

Date:

                                    Spring 2015

Category:
                                    MCUs, Electronics, Synthesizers

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Euclidean Beatgen

An app to make Euclidean Rhythms based on Bjorklund's Algorithm. Written on Max/MSP using Javascript. Click here for video demo. Based on this paper.

Date:

                                    Spring 2015

Category:
                                    Max/MSP, JavaScript

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Electrical Engineer

Was an Electrical Engineer at Kickr Design LLC. Helped prototype engineering products for clients, and took care of electronics/electrical aspests.

Date:

                                    Spring 2016

Category:
                                    MCUs, Electrical Engineering, Prototyping

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Audio Software Intern

Wrote testcases for SunHouse Inc.'s core DSP algorithms in C++. Was a part of their Kickstarter campaign.

Date:

                                    Summer 2015

Category:
                                    C++, DSP

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

The Parai Machine

Used realtime onset detection on an Indian Percussion to augment an electronic music performance. Click here for video.

Date:

                                    April 2015

Category:
                                    Realtime DSP

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>


text:
"""
    :codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""

import pytest

import salt.states.boto_elasticache as boto_elasticache
from tests.support.mock import MagicMock, patch

@pytest.fixture
def configure_loader_modules():
    return {boto_elasticache: {}}

def test_present():
    """
    Test to ensure the cache cluster exists.
    """
    name = "myelasticache"
    engine = "redis"
    cache_node_type = "cache.t1.micro"

    ret = {"name": name, "result": None, "changes": {}, "comment": ""}

    mock = MagicMock(side_effect=[None, False, False, True])
    mock_bool = MagicMock(return_value=False)
    with patch.dict(
        boto_elasticache.__salt__,
        {"boto_elasticache.get_config": mock, "boto_elasticache.create": mock_bool},
    ):
        comt = "Failed to retrieve cache cluster info from AWS."
        ret.update({"comment": comt})
        assert boto_elasticache.present(name, engine, cache_node_type) == ret

        with patch.dict(boto_elasticache.__opts__, {"test": True}):
            comt = "Cache cluster {} is set to be created.".format(name)
            ret.update({"comment": comt})
            assert boto_elasticache.present(name, engine, cache_node_type) == ret

        with patch.dict(boto_elasticache.__opts__, {"test": False}):
            comt = "Failed to create {} cache cluster.".format(name)
            ret.update({"comment": comt, "result": False})
            assert boto_elasticache.present(name, engine, cache_node_type) == ret

            comt = "Cache cluster {} is present.".format(name)
            ret.update({"comment": comt, "result": True})
            assert boto_elasticache.present(name, engine, cache_node_type) == ret

def test_absent():
    """
    Test to ensure the named elasticache cluster is deleted.
    """
    name = "new_table"

    ret = {"name": name, "result": True, "changes": {}, "comment": ""}

    mock = MagicMock(side_effect=[False, True])
    with patch.dict(boto_elasticache.__salt__, {"boto_elasticache.exists": mock}):
        comt = "{} does not exist in None.".format(name)
        ret.update({"comment": comt})
        assert boto_elasticache.absent(name) == ret

        with patch.dict(boto_elasticache.__opts__, {"test": True}):
            comt = "Cache cluster {} is set to be removed.".format(name)
            ret.update({"comment": comt, "result": None})
            assert boto_elasticache.absent(name) == ret

def test_creategroup():
    """
    Test to ensure the replication group is created.
    """
    name = "new_table"
    primary_cluster_id = "A"
    replication_group_description = "my description"

    ret = {"name": name, "result": True, "changes": {}, "comment": ""}

    mock = MagicMock(return_value=True)
    with patch.dict(boto_elasticache.__salt__, {"boto_elasticache.group_exists": mock}):
        comt = "{} replication group exists .".format(name)
        ret.update({"comment": comt})
        assert (
            boto_elasticache.creategroup(
                name, primary_cluster_id, replication_group_description
            )
            == ret
        )

redpajama_set_name: RedPajamaGithub


text:
import os
import sys

import waliki

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

version = waliki.__version__

if sys.argv[-1] == 'publish':
    os.system('sudo python setup.py sdist bdist_wheel upload')
    os.system("git tag -a %s -m 'version %s'" % (version, version))
    os.system("git push --tags")
    sys.exit()

readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')

install_requires = ['django', 'Markups', 'sh', 'docutils', 'rst2html5', 'pyquery']

extras_require = {                                      # noqa
        'restructuredtext': ['micawber'],
        'markdown': ['markdown'],
        'attachments': ['django-sendfile'],
        'pdf': ['rst2pdf'],
        'slides': ['hovercraft']
    }

everything = set()
for deps in extras_require.copy().values():
    everything.update(deps)

extras_require['all'] = everything

setup(
    name='waliki',
    version=version,
    description="""An extensible wiki app for Django with a Git backend""",
    long_description=readme + '\n\n' + history,
    author=u'Martín Gaitán',
    author_email='gaitan@gmail.com',
    url='https://github.com/mgaitan/waliki',
    packages=[
        'waliki',
    ],
    include_package_data=True,
    install_requires=install_requires,
    extras_require=extras_require,
    license="BSD",
    zip_safe=False,
    keywords='django wiki git waliki restructuredtext markdown',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Operating System :: OS Independent',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Natural Language :: Spanish',
        'Framework :: Django',
        'Framework :: Django :: 1.6',
        'Framework :: Django :: 1.7',
        'Framework :: Django :: 1.8',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: Implementation :: PyPy',
        'Topic :: Text Editors :: Documentation',
        'Topic :: Documentation',
        'Topic :: Documentation :: Sphinx',
        'Topic :: Text Processing :: Markup',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content'
    ],
)


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

using System;
using System.Collections.Generic;
using System.Management.Automation;
using Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.Models;
using Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.ProviderModel;
using Microsoft.Azure.Commands.RecoveryServices.Backup.Properties;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Internal.Resources.Utilities.Models;

namespace Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets
{
    /// <summary>
    /// Enable protection of an item with the recovery services vault.
    /// Returns the corresponding job created in the service to track this operation.
    /// </summary>
    [Cmdlet("Enable", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "RecoveryServicesBackupProtection",DefaultParameterSetName = AzureVMComputeParameterSet, SupportsShouldProcess = true),OutputType(typeof(JobBase))]
    public class EnableAzureRmRecoveryServicesBackupProtection : RSBackupVaultCmdletBase
    {
        internal const string AzureVMClassicComputeParameterSet = "AzureVMClassicComputeEnableProtection";
        internal const string AzureVMComputeParameterSet = "AzureVMComputeEnableProtection";
        internal const string AzureFileShareParameterSet = "AzureFileShareEnableProtection";
        internal const string ModifyProtectionParameterSet = "ModifyProtection";

        /// <summary>
        /// Policy to be associated with this item as part of the protection operation.
        /// </summary>
        [Parameter(Position = 1, Mandatory = true, HelpMessage = ParamHelpMsgs.Policy.ProtectionPolicy)]
        [ValidateNotNullOrEmpty]
        public PolicyBase Policy { get; set; }

        /// <summary>
        /// Name of the Azure VM whose representative item needs to be protected.
        /// </summary>
        [Parameter(Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true,
            ParameterSetName = AzureVMClassicComputeParameterSet, HelpMessage = ParamHelpMsgs.Item.ItemName)]
        [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true,
            ParameterSetName = AzureVMComputeParameterSet, HelpMessage = ParamHelpMsgs.Item.ItemName)]
        [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true,
            ParameterSetName = AzureFileShareParameterSet, HelpMessage = ParamHelpMsgs.Item.ItemName)]
        public string Name { get; set; }

        /// <summary>
        /// Service name of the classic Azure VM whose representative item needs to be protected.
        /// </summary>
        [Parameter(Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = true,
            ParameterSetName = AzureVMClassicComputeParameterSet,
            HelpMessage = ParamHelpMsgs.Item.AzureVMServiceName)]
        public string ServiceName { get; set; }

        /// <summary>
        /// Resource group name of the compute Azure VM whose representative item needs to be protected.
        /// </summary>
        [Parameter(Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = true,
            ParameterSetName = AzureVMComputeParameterSet,
            HelpMessage = ParamHelpMsgs.Item.AzureVMResourceGroupName)]
        [ResourceGroupCompleter]
        public string ResourceGroupName { get; set; }

        /// <summary>
        /// Storage account name of the Azure Files whose representative item needs to be protected.
        /// </summary>
        [Parameter(Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = true,
            ParameterSetName = AzureFileShareParameterSet,
            HelpMessage = ParamHelpMsgs.Item.AzureFileStorageAccountName)]
        [ResourceGroupCompleter]
        public string StorageAccountName { get; set; }

        /// <summary>
        /// Item whose protection needs to be modified.
        /// </summary>
        [Parameter(Position = 4, Mandatory = true, ParameterSetName = ModifyProtectionParameterSet,
            HelpMessage = ParamHelpMsgs.Item.ProtectedItem, ValueFromPipeline = true)]
        [ValidateNotNullOrEmpty]
        public ItemBase Item { get; set; }

        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                base.ExecuteCmdlet();

                ResourceIdentifier resourceIdentifier = new ResourceIdentifier(VaultId);
                string vaultName = resourceIdentifier.ResourceName;
                string resourceGroupName = resourceIdentifier.ResourceGroupName;

                string shouldProcessName = Name;
                if (ParameterSetName == ModifyProtectionParameterSet)
                {
                    shouldProcessName = Item.Name;
                }

                if (ShouldProcess(shouldProcessName, VerbsLifecycle.Enable))
                {
                    PsBackupProviderManager providerManager =
                        new PsBackupProviderManager(new Dictionary<Enum, object>()
                        {
                            { VaultParams.VaultName, vaultName },
                            { VaultParams.ResourceGroupName, resourceGroupName },
                            { ItemParams.StorageAccountName, StorageAccountName },
                            { ItemParams.ItemName, Name },
                            { ItemParams.AzureVMCloudServiceName, ServiceName },
                            { ItemParams.AzureVMResourceGroupName, ResourceGroupName },
                            { ItemParams.Policy, Policy },
                            { ItemParams.Item, Item },
                            { ItemParams.ParameterSetName, this.ParameterSetName },
                        }, ServiceClientAdapter);

                    IPsBackupProvider psBackupProvider = (Item != null) ?
                        providerManager.GetProviderInstance(Item.WorkloadType, Item.BackupManagementType)
                        : providerManager.GetProviderInstance(Policy.WorkloadType);

                    var itemResponse = psBackupProvider.EnableProtection();

                    // Track Response and display job details
                    HandleCreatedJob(
                        itemResponse,
                        Resources.EnableProtectionOperation,
                        vaultName: vaultName,
                        resourceGroupName: resourceGroupName);
                }
            });
        }
    }
}


text:
package com.opengamma.financial.generator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import com.opengamma.master.security.ManageableSecurity;

/**
 * Source of security instances from a selection of underlying generators.
 *
 * @param <T> common security super-type.
 */
public class CombiningSecurityGenerator<T extends ManageableSecurity> extends SecurityGenerator<T> {

  private final List<SecurityGenerator<? extends T>> _generators;

  public CombiningSecurityGenerator(final SecurityGenerator<? extends T>... generators) {
    _generators = Arrays.asList(generators);
  }

  public CombiningSecurityGenerator(final Collection<SecurityGenerator<? extends T>> generators) {
    _generators = new ArrayList<>(generators);
  }

  protected List<SecurityGenerator<? extends T>> getGenerators() {
    return _generators;
  }

  @Override
  public T createSecurity() {
    return getGenerators().get(getRandom(getGenerators().size())).createSecurity();
  }

}


text:
class IDealPaymentInput{

    issuerId = null;
}

 export default IDealPaymentInput;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2011 JBoss Inc
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~       http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <name>Drools :: Shapes Reasoner</name>

  <parent>
    <groupId>org.drools</groupId>
    <artifactId>drools-shapes</artifactId>
    <version>0.5.6.Final</version>
  </parent>

  <groupId>org.drools</groupId>
  <artifactId>drools-shapes-reasoner</artifactId>

  <dependencies>
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-compiler</artifactId>
    </dependency>
    <dependency>
      <groupId>org.drools.planner</groupId>
      <artifactId>drools-planner-core</artifactId>
    </dependency>

    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-shapes-utilities</artifactId>
      <version>${chance.version}</version>
    </dependency>

    <!--dependency>
        <groupId>org.jscience</groupId>
        <artifactId>jscience</artifactId>
        <version>4.3.1</version>
    </dependency-->

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>net.sourceforge.owlapi</groupId>
      <artifactId>owlapi-api</artifactId>
    </dependency>
    <dependency>
      <groupId>net.sourceforge.owlapi</groupId>
      <artifactId>owlapi-apibinding</artifactId>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
    </dependency>

    <dependency>
      <groupId>choco</groupId>
      <artifactId>choco</artifactId>
      <version>2.1.5</version>
      <type>pom</type>
    </dependency>
    <dependency>
      <groupId>choco</groupId>
      <artifactId>choco-kernel</artifactId>
      <version>2.1.5</version>
    </dependency>
    <dependency>
      <groupId>choco</groupId>
      <artifactId>choco-cp</artifactId>
      <version>2.1.5</version>
    </dependency>
    <dependency>
      <groupId>choco</groupId>
      <artifactId>choco-solver</artifactId>
      <version>2.1.5</version>
    </dependency>

  </dependencies>

  <repositories>
    <repository>
      <id>choco-repository</id>
      <name>Choco Repository</name>
      <url>http://www.emn.fr/z-info/choco-repo/mvn/repository/</url>

      <releases>
        <enabled>true</enabled>
        <updatePolicy>always</updatePolicy>
      </releases>
      <snapshots>
        <enabled>true</enabled>
        <updatePolicy>never</updatePolicy>
      </snapshots>
    </repository>
  </repositories>

</project>


text:
package org.apache.derby.iapi.types;

import org.apache.derby.shared.common.error.StandardException;

import org.apache.derby.iapi.services.cache.ClassSize;
import org.apache.derby.iapi.services.io.ArrayInputStream;
import org.apache.derby.iapi.services.io.StoredFormatIds;
import org.apache.derby.iapi.services.io.StreamStorable;
import org.apache.derby.iapi.services.io.Storable;
import org.apache.derby.iapi.services.io.TypedFormat;
import org.apache.derby.shared.common.sanity.SanityManager;
import org.apache.derby.iapi.sql.conn.ConnectionUtil;

import org.apache.derby.shared.common.reference.SQLState;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.text.RuleBasedCollator;

import java.io.InputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectInput;

import java.util.List;

/**
 * This type implements the XMLDataValue interface and thus is
 * the type on which all XML related operations are executed.
 *
 * The first and simplest XML store implementation is a UTF-8
 * based one--all XML data is stored on disk as a UTF-8 string,
 * just like the other Derby string types.  In order to make
 * it possible for smarter XML implementations to exist in
 * the future, this class always writes an "XML implementation
 * id" to disk before writing the rest of its data.  When
 * reading the data, the impl id is read first and serves
 * as an indicator of how the rest of the data should be
 * read.
 *
 * So long as there's only one implementation (UTF-8)
 * the impl id can be ignored; but when smarter implementations
 * are written, the impl id will be the key to figuring out
 * how an XML value should be read, written, and processed.
 */
public class XML
    extends DataType implements XMLDataValue, StreamStorable
{
    // Id for this implementation.  Should be unique
    // across all XML type implementations.
    protected static final short UTF8_IMPL_ID = 0;

    // Guess at how much memory this type will take.
    private static final int BASE_MEMORY_USAGE =
        ClassSize.estimateBaseFromCatalog(XML.class);

    // Some syntax-related constants used to determine
    // operator behavior.
    public static final short XQ_PASS_BY_REF = 1;
    public static final short XQ_PASS_BY_VALUE = 2;
    public static final short XQ_RETURN_SEQUENCE = 3;
    public static final short XQ_RETURN_CONTENT = 4;
    public static final short XQ_EMPTY_ON_EMPTY = 5;
    public static final short XQ_NULL_ON_EMPTY = 6;

    /* Per SQL/XML[2006] 4.2.2, there are several different
     * XML "types" defined through use of primary and secondary
     * "type modifiers".  For Derby we only support two kinds:
     *
     * XML(DOCUMENT(ANY)) : A valid and well-formed XML
     *  document as defined by W3C, meaning that there is
     *  exactly one root element node.  This is the only
     *  type of XML that can be stored into a Derby XML
     *  column.  This is also the type returned by a call
     *  to XMLPARSE since we require the DOCUMENT keyword.
     *
     * XML(SEQUENCE): A sequence of items (could be nodes or
     *  atomic values).  This is the type returned from an
     *  XMLQUERY operation.  Any node that is XML(DOCUMENT(ANY))
     *  is also XML(SEQUENCE).  Note that an XML(SEQUENCE)
     *  value is *only* storable into a Derby XML column
     *  if it is also an XML(DOCUMENT(ANY)).  See the
     *  normalize method below for the code that enforces
     *  this.
     */
    public static final int XML_DOC_ANY = 0;
    public static final int XML_SEQUENCE = 1;

    // The fully-qualified type for this XML value.
    private int xType;

    // The actual XML data in this implementation is just a simple
    // string, so this class really just wraps a SQLChar and
    // defers most calls to the corresponding calls on that
    // SQLChar.  Note that, even though a SQLChar is the
    // underlying implementation, an XML value is nonetheless
    // NOT considered comparable nor compatible with any of
    // Derby string types.
    private SQLChar xmlStringValue;

    /*
     * Status variable used to verify that user's classpath contains
     * required classes for accessing/operating on XML data values.
     */
    private static String xmlReqCheck = null;

    /*
     * Whether or not this XML value corresponds to a sequence
     * that has one or more top-level ("parentless") attribute
     * nodes.  If so then we have to throw an error if the user
     * attempts to serialize this value, per XML serialization
     * rules.
     */
    private boolean containsTopLevelAttr;

    private SqlXmlUtil tmpUtil;

    /**
     * Default constructor.
     */
    public XML()
    {
        xmlStringValue = null;
        xType = -1;
        containsTopLevelAttr = false;
    }

    /**
     * Private constructor used for the {@code cloneValue} method.
     * Returns a new instance of XML whose fields are clones
     * of the values received.
     *
     * @param val A SQLChar instance to clone and use for
     *  this XML value.
     * @param xmlType Qualified XML type for "val"
     * @param seqWithAttr Whether or not "val" corresponds to
     *  sequence with one or more top-level attribute nodes.
     * @param materialize whether or not to force materialization of the
     *      underlying source data
     */
    private XML(SQLChar val, int xmlType, boolean seqWithAttr,
            boolean materialize) {
        xmlStringValue = (val == null ? null
                                      : (SQLChar)val.cloneValue(materialize));
        setXType(xmlType);
        if (seqWithAttr)
            markAsHavingTopLevelAttr();
    }

    /* ****
     * DataValueDescriptor interface.
     * */

    /**
     * @see DataValueDescriptor#cloneValue
     */
    public DataValueDescriptor cloneValue(boolean forceMaterialization) {
        return new XML(xmlStringValue, getXType(), hasTopLevelAttr(),
                forceMaterialization);
    }

    /**
     * @see DataValueDescriptor#getNewNull
     */
    public DataValueDescriptor getNewNull()
    {
        return new XML();
    }

    /**
     * @see DataValueDescriptor#getTypeName
     */
    public String getTypeName()
    {
        return TypeId.XML_NAME;
    }

    /**
     * @see DataValueDescriptor#typePrecedence
     */
    public int typePrecedence()
    {
        return TypeId.XML_PRECEDENCE;
    }

    /**
     * @see DataValueDescriptor#getString
     */
    public String getString() throws StandardException
    {
        return (xmlStringValue == null) ? null : xmlStringValue.getString();
    }

    /**
     * @see DataValueDescriptor#getLength
     */
    public int    getLength() throws StandardException
    {
        return ((xmlStringValue == null) ? 0 : xmlStringValue.getLength());
    }

    /**
     * @see DataValueDescriptor#estimateMemoryUsage
     */
    public int estimateMemoryUsage()
    {
        int sz = BASE_MEMORY_USAGE;
        if (xmlStringValue != null)
            sz += xmlStringValue.estimateMemoryUsage();
        return sz;
    }

    /**
     * @see DataValueDescriptor#readExternalFromArray
     */
    public void readExternalFromArray(ArrayInputStream in)
        throws IOException
    {
        if (xmlStringValue == null)
            xmlStringValue = new SQLChar();

        // Read the XML implementation id.  Right now there's
        // only one implementation (UTF-8 based), so we don't
        // use this value.  But if better implementations come
        // up in the future, we'll have to use this impl id to
        // figure out how to read the data.
        in.readShort();

        // Now just read the XML data as UTF-8.
        xmlStringValue.readExternalFromArray(in);

        // If we read it from disk then it must have type
        // XML_DOC_ANY because that's all we allow to be
        // written into an XML column.
        setXType(XML_DOC_ANY);
    }

    /**
     * @see DataType#setFrom
     */
    protected void setFrom(DataValueDescriptor theValue)
        throws StandardException
    {
        String strVal = theValue.getString();
        if (strVal == null)
        {
            xmlStringValue = null;

            // Null is a valid value for DOCUMENT(ANY)
            setXType(XML_DOC_ANY);
            return;
        }

        // Here we just store the received value locally.
        if (xmlStringValue == null)
            xmlStringValue = new SQLChar();
        xmlStringValue.setValue(strVal);

        /*
         * Assumption is that if theValue is not an XML
         * value then the caller is aware of whether or
         * not theValue constitutes a valid XML(DOCUMENT(ANY))
         * and will behave accordingly (see in particular the
         * XMLQuery method of this class, which calls the
         * setValue() method of XMLDataValue which in turn
         * brings us to this method).
         */
        if (theValue instanceof XMLDataValue)
        {
            setXType(((XMLDataValue)theValue).getXType());
            if (((XMLDataValue)theValue).hasTopLevelAttr())
                markAsHavingTopLevelAttr();
        }
    }

    /**
     * @see DataValueDescriptor#setValueFromResultSet
     */
    public final void setValueFromResultSet(
        ResultSet resultSet, int colNumber, boolean isNullable)
        throws SQLException
    {
        if (xmlStringValue == null)
            xmlStringValue = new SQLChar();

        String valAsStr = resultSet.getString(colNumber);

        /* As there is no guarantee that the specified column within
         * resultSet is well-formed XML (is there??), we have to try
         * to parse it in order to set the "xType" field correctly.
         * This is required to ensure that we only store well-formed
         * XML on disk (see "normalize()" method of this class).  So
         * create an instance of SqlXmlUtil and use that to see if the
         * text satisifies the requirements of a well-formed DOCUMENT.
         *
         * RESOLVE: If there is anyway to guarantee that the column
         * is in fact well-formed XML then we can skip all of this
         * logic and simply set xType to XML_DOC_ANY.  But do we
         * have such a guarantee...?
         */
        if (tmpUtil == null)
        {
            try {

                tmpUtil = new SqlXmlUtil();

            } catch (StandardException se) {

                if (SanityManager.DEBUG)
                {
                    SanityManager.THROWASSERT(
                        "Failed to instantiate SqlXmlUtil for XML parsing.");
                }

                /* If we failed to get a SqlXmlUtil then we can't parse
                 * the string, which means we don't know if it constitutes
                 * a well-formed XML document or not.  In this case we
                 * set the value, but intentionally leave xType as -1
                 * so that the resultant value canNOT be stored on disk.
                 */
                xmlStringValue.setValue(valAsStr);
                setXType(-1);
                return;

            }
        }

        try {

            /* The following call parses the string into a DOM and
             * then serializes it, which is exactly what we do for
             * normal insertion of XML values.  If the parse finishes
             * with no error then we know the type is XML_DOC_ANY,
             * so set it.
             */
            valAsStr = tmpUtil.serializeToString(valAsStr);
            xmlStringValue.setValue(valAsStr);
            setXType(XML_DOC_ANY);

        } catch (Throwable t) {

            /* It's possible that the string value was either 1) an
             * XML SEQUENCE or 2) not XML at all.  We don't know
             * which one it was, so make xType invalid to ensure this
             * field doesn't end up on disk.
             */
            xmlStringValue.setValue(valAsStr);
            setXType(-1);

        }
    }

    /**
     * Compare two XML DataValueDescriptors.  NOTE: This method
     * should only be used by the database store for the purpose of
     * index positioning--comparisons of XML type are not allowed
     * from the language side of things.  That said, all store
     * wants to do is order the NULLs, so we don't actually
     * have to do a full comparison.  Just return an order
     * value based on whether or not this XML value and the
     * other XML value are null.  As mentioned in the "compare"
     * method of DataValueDescriptor, nulls are considered
     * equal to other nulls and less than all other values.
     *
     * An example of when this method might be used is if the
     * user executed a query like:
     *
     * select i from x_table where x_col is not null
     *
     * @see DataValueDescriptor#compare
     */
    public int compare(DataValueDescriptor other)
        throws StandardException
    {
        if (SanityManager.DEBUG) {
            SanityManager.ASSERT(other instanceof XMLDataValue,
                "Store should NOT have tried to compare an XML value " +
                "with a non-XML value.");
        }

        if (isNull()) {
            if (other.isNull())
            // both null, so call them 'equal'.
                return 0;
            // This XML is 'less than' the other.
            return -1;
        }

        if (other.isNull())
        // This XML is 'greater than' the other.
            return 1;

        // Two non-null values: we shouldn't ever get here,
        // since that would necessitate a comparsion of XML
        // values, which isn't allowed.
        if (SanityManager.DEBUG) {
            SanityManager.THROWASSERT(
                "Store tried to compare two non-null XML values, " +
                "which isn't allowed.");
        }
        return 0;
    }

    /**
     * Normalization method - this method will always be called when
     * storing an XML value into an XML column, for example, when
     * inserting/updating.  We always force normalization in this
     * case because we need to make sure the qualified type of the
     * value we're trying to store is XML_DOC_ANY--we don't allow
     * anything else.
     *
     * @param desiredType   The type to normalize the source column to
     * @param source        The value to normalize
     *
     * @exception StandardException Thrown if source is not
     *  XML_DOC_ANY.
     */
    public void normalize(
                DataTypeDescriptor desiredType,
                DataValueDescriptor source)
                    throws StandardException
    {
        if (SanityManager.DEBUG) {
            SanityManager.ASSERT(source instanceof XMLDataValue,
                "Tried to store non-XML value into XML column; " +
                "should have thrown error at compile time.");
        }

        if (((XMLDataValue)source).getXType() != XML_DOC_ANY) {
            throw StandardException.newException(
                SQLState.LANG_NOT_AN_XML_DOCUMENT);
        }

        ((DataValueDescriptor) this).setValue(source);
        return;

    }

    /* ****
     * Storable interface, implies Externalizable, TypedFormat
     */

    /**
     * @see TypedFormat#getTypeFormatId
     *
     * From the engine's perspective, all XML implementations share
     * the same format id.
     */
    public int getTypeFormatId() {
        return StoredFormatIds.XML_ID;
    }

    /**
     * @see Storable#isNull
     */
    public boolean isNull()
    {
        return ((xmlStringValue == null) || xmlStringValue.isNull());
    }

    /**
     * @see Storable#restoreToNull
     */
    public void restoreToNull()
    {
        if (xmlStringValue != null)
            xmlStringValue.restoreToNull();
    }

    /**
     * Read an XML value from an input stream.
     * @param in The stream from which we're reading.
     */
    public void readExternal(ObjectInput in) throws IOException
    {
        if (xmlStringValue == null)
            xmlStringValue = new SQLChar();

        // Read the XML implementation id.  Right now there's
        // only one implementation (UTF-8 based), so we don't
        // use this value.  But if better implementations come
        // up in the future, we'll have to use this impl id to
        // figure out how to read the data.
        in.readShort();

        // Now just read the XML data as UTF-8.
        xmlStringValue.readExternal(in);

        // If we read it from disk then it must have type
        // XML_DOC_ANY because that's all we allow to be
        // written into an XML column.
        setXType(XML_DOC_ANY);
    }

    /**
     * Write an XML value.
     * @param out The stream to which we're writing.
     */
    public void writeExternal(ObjectOutput out) throws IOException
    {
        // never called when value is null
        if (SanityManager.DEBUG)
            SanityManager.ASSERT(!isNull());

        // Write out the XML store impl id.
        out.writeShort(UTF8_IMPL_ID);

        // Now write out the data.
        xmlStringValue.writeExternal(out);
    }

    /* ****
     * StreamStorable interface
     * */

    /**
     * @see StreamStorable#returnStream
     */
    public InputStream returnStream()
    {
        return
            (xmlStringValue == null) ? null : xmlStringValue.returnStream();
    }

    /**
     * @see StreamStorable#setStream
     */
    public void setStream(InputStream newStream)
    {
        if (xmlStringValue == null)
            xmlStringValue = new SQLChar();

        // The stream that we receive is for an XML data value,
        // which means it has an XML implementation id stored
        // at the front (we put it there when we wrote it out).
        // If we leave that there we'll get a failure when
        // our underlying SQLChar tries to read from the
        // stream, because the extra impl id will throw
        // off the UTF format.  So we need to read in (and
        // ignore) the impl id before using the stream.
        try {
            // 2 bytes equal a short, which is what an impl id is.
            newStream.read();
            newStream.read();
        } catch (Exception e) {
            if (SanityManager.DEBUG)
                SanityManager.THROWASSERT("Failed to read impl id" +
                    "bytes in setStream.");
        }

        // Now go ahead and use the stream.
        xmlStringValue.setStream(newStream);

        // If we read it from disk then it must have type
        // XML_DOC_ANY because that's all we allow to be
        // written into an XML column.
        setXType(XML_DOC_ANY);
    }

    /**
     * @see StreamStorable#loadStream
     */
    public void loadStream() throws StandardException
    {
        getString();
    }

    /* ****
     * XMLDataValue interface.
     * */

    /**
     * Method to parse an XML string and, if it's valid,
     * store the _serialized_ version locally and then return
     * this XMLDataValue.
     *
     * @param stringValue The string value to check.
     * @param preserveWS Whether or not to preserve
     *  ignorable whitespace.
     * @param sqlxUtil Contains SQL/XML objects and util
     *  methods that facilitate execution of XML-related
     *  operations
     * @return If 'text' constitutes a valid XML document,
     *  it has been stored in this XML value and this XML
     *  value is returned; otherwise, an exception is thrown.
     * @exception StandardException Thrown on error.
     */
    public XMLDataValue XMLParse(
            StringDataValue stringValue,
            boolean preserveWS,
            SqlXmlUtil sqlxUtil)
        throws StandardException
    {
        if (stringValue.isNull()) {
            setToNull();
            return this;
        }

        String text = stringValue.getString();
        try {

            if (preserveWS) {
            // Currently the only way a user can view the contents of
            // an XML value is by explicitly calling XMLSERIALIZE.
            // So do a serialization now and just store the result,
            // so that we don't have to re-serialize every time a
            // call is made to XMLSERIALIZE.
                text = sqlxUtil.serializeToString(text);
            }
            else {
            // We don't support this yet, so we shouldn't
            // get here.
                if (SanityManager.DEBUG)
                    SanityManager.THROWASSERT("Tried to STRIP whitespace " +
                        "but we shouldn't have made it this far");
            }

        } catch (Throwable t) {
        /* Couldn't parse the XML document.  Throw a StandardException
         * with the parse exception (or other error) nested in it.
         * Note: we catch "Throwable" here to catch as many external
         * errors as possible in order to minimize the chance of an
         * uncaught JAXP/Xalan error (such as a NullPointerException)
         * causing Derby to fail in a more serious way.  In particular,
         * an uncaught Java exception like NPE can result in Derby
         * throwing "ERROR 40XT0: An internal error was identified by
         * RawStore module" for all statements on the connection after
         * the failure--which we clearly don't want.  If we catch the
         * error and wrap it, though, the statement will fail but Derby
         * will continue to run as normal.
         */
            throw StandardException.newException(
                SQLState.LANG_INVALID_XML_DOCUMENT, t, t.getMessage());

        }

        // If we get here, the text is valid XML so go ahead
        // and load/store it.
        setXType(XML_DOC_ANY);
        if (xmlStringValue == null)
            xmlStringValue = new SQLChar();
        xmlStringValue.setValue(text);
        return this;
    }

    /**
     * The SQL/XML XMLSerialize operator.
     * Serializes this XML value into a string with a user-specified
     * character type, and returns that string via the received
     * StringDataValue (if the received StringDataValue is non-null
     * and of the correct type; else, a new StringDataValue is
     * returned).
     *
     * @param result The result of a previous call to this method,
     *    null if not called yet.
     * @param targetType The string type to which we want to serialize.
     * @param targetWidth The width of the target type.
     * @return A serialized (to string) version of this XML object,
     *  in the form of a StringDataValue object.
     * @exception StandardException    Thrown on error
     */
    public StringDataValue XMLSerialize(StringDataValue result,
        int targetType, int targetWidth, int targetCollationType)
    throws StandardException
    {
        if (result == null) {
            switch (targetType)
            {
                case Types.CHAR:        result = new SQLChar(); break;
                case Types.VARCHAR:     result = new SQLVarchar(); break;
                case Types.LONGVARCHAR: result = new SQLLongvarchar(); break;
                case Types.CLOB:        result = new SQLClob(); break;
                default:
                // Shouldn't ever get here, as this check was performed
                // at bind time.

                    if (SanityManager.DEBUG) {
                        SanityManager.THROWASSERT(
                            "Should NOT have made it to XMLSerialize " +
                            "with a non-string target type: " + targetType);
                    }
                    return null;
            }
            // If the collation type is territory based, then we should use
            // CollatorSQLxxx rather than SQLxxx types for StringDataValue.
            // eg
            // CREATE TABLE T_MAIN1 (ID INT  GENERATED ALWAYS AS IDENTITY
            //       PRIMARY KEY, V XML);
            // INSERT INTO T_MAIN1(V) VALUES NULL;
            // SELECT ID, XMLSERIALIZE(V AS CLOB), XMLSERIALIZE(V AS CLOB)
            //       FROM T_MAIN1 ORDER BY 1;
            // Following code is for (V AS CLOB) inside XMLSERIALIZE. The
            // StringDataValue returned for (V AS CLOB) should consider the
            // passed collation type in determining whether we should
            // generate SQLChar vs CollatorSQLChar for instance. Keep in mind
            // that collation applies only to character string types.
            try {
                RuleBasedCollator rbs = ConnectionUtil.getCurrentLCC().getDataValueFactory().
                getCharacterCollator(targetCollationType);
                result = ((StringDataValue)result).getValue(rbs);
            }
            catch( java.sql.SQLException sqle)
            {
                throw StandardException.plainWrapException( sqle);
            }
        }

        // Else we're reusing a StringDataValue.  We only reuse
        // the result if we're executing the _same_ XMLSERIALIZE
        // call on multiple rows.  That means that all rows
        // must have the same result type (targetType) and thus
        // we know that the StringDataValue already has the
        // correct type.  So we're set.

        if (this.isNull()) {
        // Attempts to serialize a null XML value lead to a null
        // result (SQL/XML[2003] section 10.13).
            result.setToNull();
            return result;
        }

        /* XML serialization rules say that sequence "normalization"
         * must occur before serialization, and normalization dictates
         * that a serialization error must be thrown if the XML value
         * is a sequence with a top-level attribute.  We normalized
         * (and serialized) this XML value when it was first created,
         * and at that time we took note of whether or not there is
         * a top-level attribute.  So throw the error here if needed.
         * See SqlXmlUtil.serializeToString() for more on sequence
         * normalization.
         */
        if (this.hasTopLevelAttr())
        {
            throw StandardException.newException(
                SQLState.LANG_XQUERY_SERIALIZATION_ERROR);
        }

        // Get the XML value as a string.  For this UTF-8 impl,
        // we already have it as a UTF-8 string, so just use
        // that.
        result.setValue(getString());

        // Seems wrong to trunc an XML document, as it then becomes non-
        // well-formed and thus useless.  So we throw an error (that's
        // what the "true" in the next line says).
        result.setWidth(targetWidth, 0, true);
        return result;
    }

    /**
     * The SQL/XML XMLExists operator.
     * Checks to see if evaluation of the query expression contained
     * within the received util object against this XML value returns
     * at least one item. NOTE: For now, the query expression must be
     * XPath only (XQuery not supported) because that's what Xalan
     * supports.
     *
     * @param sqlxUtil Contains SQL/XML objects and util
     *  methods that facilitate execution of XML-related
     *  operations
     * @return True if evaluation of the query expression stored
     *  in sqlxUtil returns at least one node for this XML value;
     *  unknown if the xml value is NULL; false otherwise.
     * @exception StandardException Thrown on error
     */
    public BooleanDataValue XMLExists(SqlXmlUtil sqlxUtil)
        throws StandardException
    {
        if (this.isNull()) {
        // if the user specified a context node and that context
        // is null, result of evaluating the query is null
        // (per SQL/XML 6.17:General Rules:1.a), which means that we
        // return "unknown" here (per SQL/XML 8.4:General Rules:2.a).
            return SQLBoolean.unknownTruthValue();
        }

        // Make sure we have a compiled query (and associated XML
        // objects) to evaluate.
        if (SanityManager.DEBUG) {
            SanityManager.ASSERT(
                sqlxUtil != null,
                "Tried to evaluate XML xquery, but no XML objects were loaded.");
        }

        try {

            return new SQLBoolean(null !=
                sqlxUtil.evalXQExpression(this, false, new int[1]));

        } catch (StandardException se) {

            // Just re-throw it.
            throw se;

        } catch (Throwable xe) {
        /* Failed somewhere during evaluation of the XML query expression;
         * turn error into a StandardException and throw it.  Note: we
         * catch "Throwable" here to catch as many Xalan-produced errors
         * as possible in order to minimize the chance of an uncaught Xalan
         * error (such as a NullPointerException) causing Derby to fail in
         * a more serious way.  In particular, an uncaught Java exception
         * like NPE can result in Derby throwing "ERROR 40XT0: An internal
         * error was identified by RawStore module" for all statements on
         * the connection after the failure--which we clearly don't want.
         * If we catch the error and wrap it, though, the statement will
         * fail but Derby will continue to run as normal.
         */
            throw StandardException.newException(
                SQLState.LANG_XML_QUERY_ERROR, xe,
                "XMLEXISTS", xe.getMessage());
        }
    }

    /**
     * Evaluate the XML query expression contained within the received
     * util object against this XML value and store the results into
     * the received XMLDataValue "result" param (assuming "result" is
     * non-null; else create a new XMLDataValue).
     *
     * @param sqlxUtil Contains SQL/XML objects and util methods that
     *  facilitate execution of XML-related operations
     * @param result The result of a previous call to this method; null
     *  if not called yet.
     * @return An XMLDataValue whose content corresponds to the serialized
     *  version of the results from evaluation of the query expression.
     *  Note: this XMLDataValue may not be storable into Derby XML
     *  columns.
     * @exception StandardException thrown on error
     */
    public XMLDataValue XMLQuery(SqlXmlUtil sqlxUtil, XMLDataValue result)
            throws StandardException
    {
        if (this.isNull()) {
        // if the context is null, we return null,
        // per SQL/XML[2006] 6.17:GR.1.a.ii.1.
            if (result == null)
                result = (XMLDataValue)getNewNull();
            else
                result.setToNull();
            return result;
        }

        try {

            // Return an XML data value whose contents are the
            // serialized version of the query results.
            int [] xType = new int[1];
            List itemRefs = sqlxUtil.evalXQExpression(
                this, true, xType);

            if (result == null)
                result = new XML();
            String strResult = sqlxUtil.serializeToString(itemRefs, result);
            result.setValue(new SQLChar(strResult));

            // Now that we've set the result value, make sure
            // to indicate what kind of XML value we have.
            result.setXType(xType[0]);

            // And finally we return the query result as an XML value.
            return result;

        } catch (StandardException se) {

            // Just re-throw it.
            throw se;

        } catch (Throwable xe) {
        /* Failed somewhere during evaluation of the XML query expression;
         * turn error into a StandardException and throw it.  Note: we
         * catch "Throwable" here to catch as many Xalan-produced errors
         * as possible in order to minimize the chance of an uncaught Xalan
         * error (such as a NullPointerException) causing Derby to fail in
         * a more serious way.  In particular, an uncaught Java exception
         * like NPE can result in Derby throwing "ERROR 40XT0: An internal
         * error was identified by RawStore module" for all statements on
         * the connection after the failure--which we clearly don't want.
         * If we catch the error and wrap it, though, the statement will
         * fail but Derby will continue to run as normal.
         */
            throw StandardException.newException(
                SQLState.LANG_XML_QUERY_ERROR, xe,
                "XMLQUERY", xe.getMessage());
        }
    }

    /* ****
     * Helper classes and methods.
     * */

    /**
     * Set this XML value's qualified type.
     */
    public void setXType(int xtype)
    {
        this.xType = xtype;

        /* If the target type is XML_DOC_ANY then this XML value
         * holds a single well-formed Document.  So we know that
         * we do NOT have any top-level attribute nodes.  Note: if
         * xtype is SEQUENCE we don't set "containsTopLevelAttr"
         * here; assumption is that the caller of this method will
         * then set the field as appropriate.  Ex. see "setFrom()"
         * in this class.
         */
        if (xtype == XML_DOC_ANY)
            containsTopLevelAttr = false;
    }

    /**
     * Retrieve this XML value's qualified type.
     */
    public int getXType()
    {
        return xType;
    }

    /**
     * Take note of the fact this XML value represents an XML
     * sequence that has one or more top-level attribute nodes.
     */
    public void markAsHavingTopLevelAttr()
    {
        this.containsTopLevelAttr = true;
    }

    /**
     * Return whether or not this XML value represents a sequence
     * that has one or more top-level attribute nodes.
     */
    public boolean hasTopLevelAttr()
    {
        return containsTopLevelAttr;
    }

    /**
     * See if the required JAXP and Xalan classes are in the
     * user's classpath.  Assumption is that we will always
     * call this method before instantiating an instance of
     * SqlXmlUtil, and thus we will never get a ClassNotFound
     * exception caused by missing JAXP/Xalan classes.  Instead,
     * if either is missing we should throw an informative
     * error indicating what the problem is.
     *
     * NOTE: This method only does the checks necessary to
     * allow successful instantiation of the SqlXmlUtil
     * class.  Further checks (esp. the presence of a JAXP
     * _implementation_ in addition to the JAXP _interfaces_)
     * are performed in the SqlXmlUtil constructor.
     *
     * @exception StandardException thrown if the required
     *  classes cannot be located in the classpath.
     */
    public static void checkXMLRequirements()
        throws StandardException
    {
        // Only check once; after that, just re-use the result.
        if (xmlReqCheck == null)
        {
            xmlReqCheck = "";

            /* If the DocumentBuilderFactory class exists, then we
             * assume a JAXP implementation is present in
             * the classpath.  If this assumption is incorrect
             * then we at least know that the JAXP *interface*
             * exists and thus we'll be able to instantiate
             * the SqlXmlUtil class.  We can then do a check
             * for an actual JAXP *implementation* from within
             * the SqlXmlUtil class (see the constructor of
             * that class).
             *
             * Note: The JAXP API and implementation are
             * provided as part the JVM if it is jdk 1.4 or
             * greater.
             */
            if (!checkJAXPRequirement()) {
                xmlReqCheck = "JAXP";
            }

            /* If the XPathFactory class exists, then we assume that
             * our XML query processor is present in the classpath.
             */
            else if (!checkXPathRequirement()) {
                xmlReqCheck = "XPath";
            }
        }

        if (xmlReqCheck.length() != 0)
        {
            throw StandardException.newException(
                SQLState.LANG_MISSING_XML_CLASSES, xmlReqCheck);
        }
    }

    /**
     * Check if we have a JAXP implementation installed.
     *
     * @return {@code true} if JAXP is installed, or {@code false} otherwise
     */
    private static boolean checkJAXPRequirement() {
        try {
            Class.forName("javax.xml.parsers.DocumentBuilderFactory");
            return true;
        } catch (Throwable t) {
            // Oops... Couldn't load the DocumentBuilderFactory class for
            // some reason. Assume we don't have JAXP.
            return false;
        }
    }

    /**
     * Check if XPath is supported on this platform.
     *
     * @return {@code true} if XPath is supported, or {@code false} otherwise
     */
    private static boolean checkXPathRequirement() {
        try {
            Class.forName("javax.xml.xpath.XPathFactory");
            return true;
        } catch (Throwable t) {
            // Oops... Something went wrong when checking for XPath
            // support. Assume we don't have it.
            return false;
        }
    }
}


text:
package com.blp.minotaurus.arena;

import com.blp.minotaurus.Minotaurus;
import com.blp.minotaurus.bukkit.Locales;
import com.blp.minotaurus.bukkit.MessageType;
import com.blp.minotaurus.utils.Utils;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.entity.Damageable;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

public class PlayerData {

    private final Player player;
    private final Arena a;
    private PlayerType type = PlayerType.TRIBUTE;
    private final ItemStack[] inventory, armor;
    private final int level;
    private final float xp, hunger;
    private final GameMode gm;
    private final double maxhealth, health;
    private final boolean flying;

    public PlayerData(Player p, Arena a) {
        this.player = p;
        this.a = a;

        inventory = p.getInventory().getContents();
        armor = p.getInventory().getArmorContents();
        gm = player.getGameMode();
        xp = p.getExp();
        level = p.getLevel();
        hunger = p.getExhaustion();
        maxhealth = ((Damageable) p).getMaxHealth();
        health = ((Damageable) p).getHealth();
        flying = p.getAllowFlight();

        player.setGameMode(GameMode.ADVENTURE);
        player.setAllowFlight(false);
        player.setFlying(false);
        player.setSleepingIgnored(true);
        player.setMaxHealth(20.0);
        player.setHealth(20.0);
        player.setExhaustion(20.0F);
        player.setExp(0F);
        player.setLevel(0);
        Utils.clearInventory(player);
        player.updateInventory();
    }

    public void restorePlayerData() {
        if (player == null) return;
        player.setAllowFlight(flying);
        player.setMaxHealth(maxhealth);
        player.setExhaustion(hunger);
        player.setHealth(health);
        player.setGameMode(gm);
        player.getInventory().setArmorContents(armor);
        player.getInventory().setContents(inventory);
        player.setExp(xp);
        player.setLevel(level);
        player.setSleepingIgnored(false);
    }

    public boolean isForPlayer(Player p) {
        return player.getUniqueId().equals(p.getUniqueId());
    }

    public void setType(PlayerType type) {
        this.type = type;
    }

    public PlayerType getType() {
        return type;
    }

    public boolean isMinotaur() {
        return type == PlayerType.MINOTAUR;
    }

    public Player getPlayer() {
        return player;
    }

    public boolean isSpectator() {
        return type == PlayerType.SPECTATOR;
    }

    public void startSpectating() {
        type = PlayerType.SPECTATOR;

        for (PlayerData alive : a.getAlives()) {
            alive.getPlayer().hidePlayer(player);
        }

        Utils.clearInventory(player);

        Bukkit.getScheduler().scheduleSyncDelayedTask(Minotaurus.getInstance(), new Runnable() {
            @Override
            public void run() {
                ItemStack compass = new ItemStack(Material.COMPASS);
                ItemMeta meta = compass.getItemMeta();
                meta.setDisplayName("§6Teleport");
                compass.setItemMeta(meta);

                ItemStack ball = new ItemStack(Material.SLIME_BALL);
                ItemMeta ballmeta = ball.getItemMeta();
                ballmeta.setDisplayName("§5Quit");
                ball.setItemMeta(ballmeta);

                player.getInventory().addItem(compass, ball);
                player.setAllowFlight(true);
                player.teleport(a.getSpectatorSpawn());

                Locales.SPECTATOR_INIT.sendMessage(MessageType.INFO, player, null);
            }
        }, 4);
    }

    public enum PlayerType {

        TRIBUTE,
        MINOTAUR,
        SPECTATOR;

    }
}


text:
package analyzer

import (
	"net/http"

	"github.com/skydive-project/skydive/common"
	"github.com/skydive-project/skydive/logging"
	"github.com/skydive-project/skydive/topology"
	"github.com/skydive-project/skydive/topology/graph"
	"github.com/skydive-project/skydive/topology/graph/traversal"
	ws "github.com/skydive-project/skydive/websocket"
)

// PersistencePolicy defines Persistent policy for publishers
type PersistencePolicy string

const (
	// Persistent means that the graph elements created will always remain
	Persistent PersistencePolicy = "Persistent"
	// DeleteOnDisconnect means the graph elements created will be deleted on client disconnect
	DeleteOnDisconnect PersistencePolicy = "DeleteOnDisconnect"
)

// TopologyPublisherEndpoint serves the graph for external publishers, for instance
// an external program that interacts with the Skydive graph.
type TopologyPublisherEndpoint struct {
	common.RWMutex
	ws.DefaultSpeakerEventHandler
	pool            ws.StructSpeakerPool
	Graph           *graph.Graph
	schemaValidator *topology.SchemaValidator
	gremlinParser   *traversal.GremlinTraversalParser
}

// OnDisconnected called when a publisher got disconnected.
func (t *TopologyPublisherEndpoint) OnDisconnected(c ws.Speaker) {
	policy := PersistencePolicy(c.GetHeaders().Get("X-Persistence-Policy"))
	if policy == Persistent {
		return
	}

	origin := string(c.GetServiceType())
	if len(c.GetRemoteHost()) > 0 {
		origin += "." + c.GetRemoteHost()
	}
	logging.GetLogger().Debugf("Authoritative client unregistered, delete resources %s", origin)

	t.Graph.Lock()
	t.Graph.DelOriginGraph(origin)
	t.Graph.Unlock()
}

// OnStructMessage is triggered by message coming from a publisher.
func (t *TopologyPublisherEndpoint) OnStructMessage(c ws.Speaker, msg *ws.StructMessage) {
	msgType, obj, err := graph.UnmarshalMessage(msg)
	if err != nil {
		logging.GetLogger().Errorf("Graph: Unable to parse the event %v: %s", msg, err)
		return
	}

	origin := string(c.GetServiceType())
	if len(c.GetRemoteHost()) > 0 {
		origin += "." + c.GetRemoteHost()
	}

	switch msgType {
	case graph.NodeAddedMsgType, graph.NodeUpdatedMsgType, graph.NodeDeletedMsgType:
		obj.(*graph.Node).SetOrigin(origin)
		err = t.schemaValidator.ValidateNode(obj.(*graph.Node))
	case graph.EdgeAddedMsgType, graph.EdgeUpdatedMsgType, graph.EdgeDeletedMsgType:
		obj.(*graph.Edge).SetOrigin(origin)
		err = t.schemaValidator.ValidateEdge(obj.(*graph.Edge))
	}

	if err != nil {
		logging.GetLogger().Error(err)
		return
	}

	t.Graph.Lock()
	defer t.Graph.Unlock()

	switch msgType {
	case graph.SyncRequestMsgType:
		reply := msg.Reply(t.Graph, graph.SyncReplyMsgType, http.StatusOK)
		c.SendMessage(reply)
	case graph.OriginGraphDeletedMsgType:
		// OriginGraphDeletedMsgType is handled specifically as we need to be sure to not use the
		// cache while deleting otherwise the delete mechanism is using the cache to walk through
		// the graph.
		logging.GetLogger().Debugf("Got %s message for origin %s", graph.OriginGraphDeletedMsgType, obj.(string))
		t.Graph.DelOriginGraph(obj.(string))
	case graph.SyncMsgType, graph.SyncReplyMsgType:
		r := obj.(*graph.SyncMsg)
		for _, n := range r.Nodes {
			if t.Graph.GetNode(n.ID) == nil {
				t.Graph.NodeAdded(n)
			}
		}
		for _, e := range r.Edges {
			if t.Graph.GetEdge(e.ID) == nil {
				t.Graph.EdgeAdded(e)
			}
		}
	case graph.NodeUpdatedMsgType:
		t.Graph.NodeUpdated(obj.(*graph.Node))
	case graph.NodeDeletedMsgType:
		t.Graph.NodeDeleted(obj.(*graph.Node))
	case graph.NodeAddedMsgType:
		t.Graph.NodeAdded(obj.(*graph.Node))
	case graph.EdgeUpdatedMsgType:
		t.Graph.EdgeUpdated(obj.(*graph.Edge))
	case graph.EdgeDeletedMsgType:
		t.Graph.EdgeDeleted(obj.(*graph.Edge))
	case graph.EdgeAddedMsgType:
		t.Graph.EdgeAdded(obj.(*graph.Edge))
	}
}

// NewTopologyPublisherEndpoint returns a new server for external publishers.
func NewTopologyPublisherEndpoint(pool ws.StructSpeakerPool, g *graph.Graph) (*TopologyPublisherEndpoint, error) {
	schemaValidator, err := topology.NewSchemaValidator()
	if err != nil {
		return nil, err
	}

	t := &TopologyPublisherEndpoint{
		Graph:           g,
		pool:            pool,
		schemaValidator: schemaValidator,
		gremlinParser:   traversal.NewGremlinTraversalParser(),
	}

	pool.AddEventHandler(t)

	// subscribe to the graph messages
	pool.AddStructMessageHandler(t, []string{graph.Namespace})

	return t, nil
}


text:
package org.ovirt.engine.ui.uicommonweb.models.hosts;

import org.ovirt.engine.core.common.action.ChangeVDSClusterParameters;
import org.ovirt.engine.core.common.action.StoragePoolManagementParameter;
import org.ovirt.engine.core.common.action.StoragePoolParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.action.VdsGroupParametersBase;
import org.ovirt.engine.core.common.businessentities.StoragePoolStatus;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.storage_pool;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.datacenters.DataCenterModel;
import org.ovirt.engine.ui.uicompat.Enlistment;
import org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult;
import org.ovirt.engine.ui.uicompat.IEnlistmentNotification;
import org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback;
import org.ovirt.engine.ui.uicompat.PreparingEnlistment;

@SuppressWarnings("unused")
public class AddDataCenterRM extends IEnlistmentNotification {

    public AddDataCenterRM(String correlationId) {
        super(correlationId);
    }

    @Override
    public void prepare(PreparingEnlistment enlistment) {

        context.enlistment = enlistment;

        // Fetch all necessary data to make code flat.
        prepare1();
    }

    private void prepare1() {

        EnlistmentContext enlistmentContext = (EnlistmentContext) context.enlistment.getContext();
        HostListModel model = enlistmentContext.getModel();
        ConfigureLocalStorageModel configureModel = (ConfigureLocalStorageModel) model.getWindow();

        DataCenterModel dataCenterModel = configureModel.getDataCenter();
        String dataCenterName = (String) dataCenterModel.getName().getEntity();

        if (!StringHelper.isNullOrEmpty(dataCenterName)) {

            AsyncDataProvider.GetDataCenterListByName(new AsyncQuery(this,
                    new INewAsyncCallback() {
                        @Override
                        public void OnSuccess(Object model, Object returnValue) {

                            context.dataCenterFoundByName = Linq.FirstOrDefault((Iterable<storage_pool>) returnValue);
                            prepare2();
                        }
                    }),
                    dataCenterName);
        } else {
            prepare2();
        }
    }

    private void prepare2() {

        PreparingEnlistment enlistment = (PreparingEnlistment) context.enlistment;
        EnlistmentContext enlistmentContext = (EnlistmentContext) enlistment.getContext();
        HostListModel model = enlistmentContext.getModel();
        ConfigureLocalStorageModel configureModel = (ConfigureLocalStorageModel) model.getWindow();

        storage_pool candidate = configureModel.getCandidateDataCenter();
        DataCenterModel dataCenterModel = configureModel.getDataCenter();
        String dataCenterName = (String) dataCenterModel.getName().getEntity();

        if (candidate == null || candidate.getname() != dataCenterName) {

            // Try to find existing data center with the specified name.
            storage_pool dataCenter = context.dataCenterFoundByName;

            if (dataCenter != null) {

                enlistmentContext.setDataCenterId(dataCenter.getId());

                context.enlistment = null;
                enlistment.Prepared();
            } else {

                dataCenter = new storage_pool();
                dataCenter.setname(dataCenterName);
                dataCenter.setdescription((String) dataCenterModel.getDescription().getEntity());
                dataCenter.setstorage_pool_type((StorageType) dataCenterModel.getStorageTypeList().getSelectedItem());
                dataCenter.setcompatibility_version((Version) dataCenterModel.getVersion().getSelectedItem());

                Frontend.RunAction(VdcActionType.AddEmptyStoragePool, new StoragePoolManagementParameter(dataCenter),
                        new IFrontendActionAsyncCallback() {
                            @Override
                            public void Executed(FrontendActionAsyncResult result) {

                                VdcReturnValueBase returnValue = result.getReturnValue();

                                context.addDataCenterReturnValue = returnValue;
                                prepare3();
                            }
                        });
            }
        } else {
            enlistmentContext.setDataCenterId(configureModel.getDataCenter().getDataCenterId().getValue());

            context.enlistment = null;
            enlistment.Prepared();
        }
    }

    private void prepare3() {

        PreparingEnlistment enlistment = (PreparingEnlistment) context.enlistment;
        EnlistmentContext enlistmentContext = (EnlistmentContext) enlistment.getContext();
        VdcReturnValueBase returnValue = context.addDataCenterReturnValue;

        context.enlistment = null;

        if (returnValue != null && returnValue.getSucceeded()) {

            enlistmentContext.setDataCenterId((Guid) returnValue.getActionReturnValue());
            enlistment.Prepared();

        } else {
            enlistment.ForceRollback();
        }
    }

    @Override
    public void commit(Enlistment enlistment) {
        enlistment.Done();
    }

    @Override
    public void rollback(Enlistment enlistment) {
        context.enlistment = enlistment;

        // Fetch all necessary data to make code flat.
        rollback1();
    }

    public void rollback1() {

        Enlistment enlistment = context.enlistment;
        EnlistmentContext enlistmentContext = (EnlistmentContext) enlistment.getContext();

        if (enlistmentContext.getDataCenterId() != null) {

            AsyncDataProvider.GetDataCenterById(new AsyncQuery(this,
                    new INewAsyncCallback() {
                        @Override
                        public void OnSuccess(Object model, Object returnValue) {

                            context.dataCenterFoundById = (storage_pool) returnValue;
                            rollback2();
                        }
                    }),
                    enlistmentContext.getDataCenterId());
        } else {
            rollback3();
        }
    }

    public void rollback2() {

        Enlistment enlistment = context.enlistment;
        EnlistmentContext enlistmentContext = (EnlistmentContext) enlistment.getContext();
        HostListModel model = enlistmentContext.getModel();

        VDS host = (VDS) model.getSelectedItem();

        // Retrieve host to make sure we have an updated status etc.
        AsyncDataProvider.GetHostById(new AsyncQuery(this,
                new INewAsyncCallback() {
                    @Override
                    public void OnSuccess(Object model, Object returnValue) {

                        context.hostFoundById = (VDS) returnValue;
                        rollback3();
                    }
                }),
                host.getId());
    }

    public void rollback3() {

        Enlistment enlistment = context.enlistment;
        EnlistmentContext enlistmentContext = (EnlistmentContext) enlistment.getContext();
        HostListModel model = enlistmentContext.getModel();
        ConfigureLocalStorageModel configureModel = (ConfigureLocalStorageModel) model.getWindow();

        VDS host = context.hostFoundById;

        boolean abort = false;
        if (model != null && model.getSelectedItem() != null) {

            // Perform rollback only when the host is in maintenance.
            if (host.getstatus() != VDSStatus.Maintenance) {
                abort = true;
            }
        } else {
            abort = true;
        }

        if (abort) {

            context.enlistment = null;
            enlistment.Done();
            return;
        }

        storage_pool dataCenter = context.dataCenterFoundById;

        // Perform rollback only when the Data Center is un uninitialized.
        if (dataCenter.getstatus() != StoragePoolStatus.Uninitialized) {

            context.enlistment = null;
            enlistment.Done();
            return;
        }

        if (enlistmentContext.getOldClusterId() != null) {

            // Switch host back to previous cluster.
            Frontend.RunAction(VdcActionType.ChangeVDSCluster,
                    new ChangeVDSClusterParameters(enlistmentContext.getOldClusterId(), host.getId()),
                    new IFrontendActionAsyncCallback() {
                        @Override
                        public void Executed(FrontendActionAsyncResult result) {

                            VdcReturnValueBase returnValue = result.getReturnValue();

                            context.changeVDSClusterReturnValue = returnValue;
                            rollback4();
                        }
                    });

        } else {
            context.enlistment = null;
            enlistment.Done();
        }
    }

    private void rollback4() {

        Enlistment enlistment = context.enlistment;
        EnlistmentContext enlistmentContext = (EnlistmentContext) enlistment.getContext();
        VdcReturnValueBase returnValue = context.changeVDSClusterReturnValue;

        if (returnValue != null && returnValue.getSucceeded()) {

            // Remove cluster.
            if (enlistmentContext.getClusterId() != null) {

                Frontend.RunAction(VdcActionType.RemoveVdsGroup,
                        new VdsGroupParametersBase(enlistmentContext.getClusterId()),
                        new IFrontendActionAsyncCallback() {
                            @Override
                            public void Executed(FrontendActionAsyncResult result) {

                                VdcReturnValueBase returnValue = result.getReturnValue();

                                context.removeVDSGroupReturnValue = returnValue;
                                rollback5();
                            }
                        });
            }
        } else {
            context.enlistment = null;
            enlistment.Done();
        }
    }

    private void rollback5() {

        Enlistment enlistment = context.enlistment;
        EnlistmentContext enlistmentContext = (EnlistmentContext) enlistment.getContext();
        VdcReturnValueBase returnValue = context.changeVDSClusterReturnValue;

        // Try to remove data center.
        if (enlistmentContext.getDataCenterId() != null) {
            Frontend.RunAction(VdcActionType.RemoveStoragePool,
                    new StoragePoolParametersBase(enlistmentContext.getDataCenterId()));
        }

        // Call done, no matter whether the data center deletion was successful.
        context.enlistment = null;
        enlistment.Done();
    }

    // @Override
    // public void Prepare(PreparingEnlistment enlistment)
    // {
    // ConfigureLocalStorageModel model = (ConfigureLocalStorageModel) getModel().getWindow();
    // if (!model.getDontCreateDataCenter())
    // {
    // DataCenterModel m = model.getDataCenter();
    // String name = (String) m.getName().getEntity();
    // // Try to find existing data center with the specified name.
    // storage_pool dataCenter = DataProvider.GetDataCenterByName(name);
    // if (dataCenter != null)
    // {
    // getData().setDataCenterId(dataCenter.getId());
    // enlistment.Prepared();
    // }
    //
    // else
    // {
    // dataCenter = new storage_pool();
    // dataCenter.setname(name);
    // dataCenter.setdescription((String) m.getDescription().getEntity());
    // dataCenter.setstorage_pool_type((StorageType) m.getStorageTypeList().getSelectedItem());
    // dataCenter.setcompatibility_version((Version) m.getVersion().getSelectedItem());
    //
    // VdcReturnValueBase returnValue =
    // Frontend.RunAction(VdcActionType.AddEmptyStoragePool,
    // new StoragePoolManagementParameter(dataCenter));
    //
    // if (returnValue != null && returnValue.getSucceeded())
    // {
    // getData().setDataCenterId((Guid) returnValue.getActionReturnValue());
    // enlistment.Prepared();
    // } else
    // {
    // enlistment.ForceRollback();
    // }
    // }
    // }
    // else
    // {
    // enlistment.Prepared();
    // }
    // }

    // @Override
    // public void Rollback(Enlistment enlistment)
    // {
    // if (getModel() == null || getModel().getSelectedItem() == null)
    // {
    // return;
    // }
    // VDS host = (VDS) getModel().getSelectedItem();
    // // perform rollback only when the host is in maintenance
    // if (host.getstatus() != VDSStatus.Maintenance)
    // {
    // return;
    // }
    //
    // storage_pool dataCenter = DataProvider.GetDataCenterById(getData().getDataCenterId());
    //
    // // perform rollback only when the Data Center is un uninitialized
    // if (dataCenter.getstatus() != StoragePoolStatus.Uninitialized)
    // {
    // return;
    // }
    //
    // if (getData().getOldClusterId() != null
    // && !host.getvds_group_id().getValue().equals(getData().getOldClusterId().getValue()))
    // {
    // // Switch host back to previous cluster.
    // VdcReturnValueBase returnValue =
    // Frontend.RunAction(VdcActionType.ChangeVDSCluster,
    // new ChangeVDSClusterParameters(getData().getOldClusterId(), host.getvds_id()));
    //
    // if (returnValue != null && returnValue.getSucceeded())
    // {
    // // Remove cluster.
    // if (getData().getClusterId() != null)
    // {
    // Frontend.RunAction(VdcActionType.RemoveVdsGroup,
    // new VdsGroupParametersBase(getData().getClusterId()));
    // }
    //
    // // Remove data center.
    // if (getData().getDataCenterId() != null)
    // {
    // Frontend.RunAction(VdcActionType.RemoveStoragePool,
    // new StoragePoolParametersBase(getData().getDataCenterId()));
    // }
    // }
    // }
    //
    // enlistment.Done();
    // }

    private final Context context = new Context();

    public final class Context {

        public Enlistment enlistment;
        public storage_pool dataCenterFoundByName;
        public storage_pool dataCenterFoundById;
        public VDS hostFoundById;
        public VdcReturnValueBase addDataCenterReturnValue;
        public VdcReturnValueBase changeVDSClusterReturnValue;
        public VdcReturnValueBase removeVDSGroupReturnValue;
    }
}


text:
define([
  'jquery',
  'lodash',
  'backbone',
  'app',
  'modules/solrita/views/option'
  ], function ($, _, Backbone, app, OptionView) {

    var SortView = Backbone.View.extend({

      tagName: "select",

      initialize: function (options) {
        _.bindAll(this, "sortFieldSelected");
      },

      events: {
        "change": "sortFieldSelected"
      },

      beforeRender: function () {
        var self = this;
        $(app.sortFieldArray).each(function (num, item) {
          self.insertView(new OptionView({
            name: item,
            value: item
          }));
        });
        this.$el.addClass("input-medium");
      },

      afterRender: function () {
        this.$el.val(this.collection.sortField);
      },

      sortFieldSelected: function (e) {
        e.preventDefault();
        var sortFieldSelected = $(e.target).val();
        this.collection.sortField = sortFieldSelected;

        Backbone.history.navigate("search/text#?" + this.collection.getCurrentParams(), true);
      }

    });

    return SortView;
  });


text:
"""
tests.component.media_player.test_universal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Tests universal media_player component.
"""
from copy import copy
import unittest

import homeassistant.core as ha
from homeassistant.const import (
    STATE_OFF, STATE_ON, STATE_UNKNOWN, STATE_PLAYING, STATE_PAUSED)
import homeassistant.components.switch as switch
import homeassistant.components.media_player as media_player
import homeassistant.components.media_player.universal as universal

class MockMediaPlayer(media_player.MediaPlayerDevice):
    """ Mock media player for testing """

    def __init__(self, hass, name):
        self.hass = hass
        self._name = name
        self.entity_id = media_player.ENTITY_ID_FORMAT.format(name)
        self._state = STATE_OFF
        self._volume_level = 0
        self._is_volume_muted = False
        self._media_title = None
        self._supported_media_commands = 0

    @property
    def name(self):
        """ name of player """
        return self._name

    @property
    def state(self):
        """ state of the player """
        return self._state

    @property
    def volume_level(self):
        """ volume level of player """
        return self._volume_level

    @property
    def is_volume_muted(self):
        """ if the media player is muted """
        return self._is_volume_muted

    @property
    def supported_media_commands(self):
        """ supported media commands flag """
        return self._supported_media_commands

    def turn_on(self):
        """ mock turn_on function """
        self._state = STATE_UNKNOWN

    def turn_off(self):
        """ mock turn_off function """
        self._state = STATE_OFF

    def mute_volume(self):
        """ mock mute function """
        self._is_volume_muted = ~self._is_volume_muted

    def set_volume_level(self, volume):
        """ mock set volume level """
        self._volume_level = volume

    def media_play(self):
        """ mock play """
        self._state = STATE_PLAYING

    def media_pause(self):
        """ mock pause """
        self._state = STATE_PAUSED

class TestMediaPlayer(unittest.TestCase):
    """ Test the media_player module. """

    def setUp(self):  # pylint: disable=invalid-name
        self.hass = ha.HomeAssistant()

        self.mock_mp_1 = MockMediaPlayer(self.hass, 'mock1')
        self.mock_mp_1.update_ha_state()

        self.mock_mp_2 = MockMediaPlayer(self.hass, 'mock2')
        self.mock_mp_2.update_ha_state()

        self.mock_mute_switch_id = switch.ENTITY_ID_FORMAT.format('mute')
        self.hass.states.set(self.mock_mute_switch_id, STATE_OFF)

        self.mock_state_switch_id = switch.ENTITY_ID_FORMAT.format('state')
        self.hass.states.set(self.mock_state_switch_id, STATE_OFF)

        self.config_children_only = \
            {'name': 'test', 'platform': 'universal',
             'children': [media_player.ENTITY_ID_FORMAT.format('mock1'),
                          media_player.ENTITY_ID_FORMAT.format('mock2')]}
        self.config_children_and_attr = \
            {'name': 'test', 'platform': 'universal',
             'children': [media_player.ENTITY_ID_FORMAT.format('mock1'),
                          media_player.ENTITY_ID_FORMAT.format('mock2')],
             'attributes': {
                 'is_volume_muted': self.mock_mute_switch_id,
                 'state': self.mock_state_switch_id}}

    def tearDown(self):  # pylint: disable=invalid-name
        """ Stop down stuff we started. """
        self.hass.stop()

    def test_check_config_children_only(self):
        """ Check config with only children """
        config_start = copy(self.config_children_only)
        del config_start['platform']
        config_start['commands'] = {}
        config_start['attributes'] = {}

        response = universal.validate_config(self.config_children_only)

        self.assertTrue(response)
        self.assertEqual(config_start, self.config_children_only)

    def test_check_config_children_and_attr(self):
        """ Check config with children and attributes """
        config_start = copy(self.config_children_and_attr)
        del config_start['platform']
        config_start['commands'] = {}

        response = universal.validate_config(self.config_children_and_attr)

        self.assertTrue(response)
        self.assertEqual(config_start, self.config_children_and_attr)

    def test_master_state(self):
        """ test master state property """
        config = self.config_children_only
        universal.validate_config(config)

        ump = universal.UniversalMediaPlayer(self.hass, **config)

        self.assertEqual(None, ump.master_state)

    def test_master_state_with_attrs(self):
        """ test master state property """
        config = self.config_children_and_attr
        universal.validate_config(config)

        ump = universal.UniversalMediaPlayer(self.hass, **config)

        self.assertEqual(STATE_OFF, ump.master_state)

        self.hass.states.set(self.mock_state_switch_id, STATE_ON)

        self.assertEqual(STATE_ON, ump.master_state)

    def test_master_state_with_bad_attrs(self):
        """ test master state property """
        config = self.config_children_and_attr
        config['attributes']['state'] = 'bad.entity_id'
        universal.validate_config(config)

        ump = universal.UniversalMediaPlayer(self.hass, **config)

        self.assertEqual(STATE_OFF, ump.master_state)

    def test_active_child_state(self):
        """ test active child state property """
        config = self.config_children_only
        universal.validate_config(config)

        ump = universal.UniversalMediaPlayer(self.hass, **config)
        ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name'])
        ump.update()

        self.assertEqual(None, ump._child_state)

        self.mock_mp_1._state = STATE_PLAYING
        self.mock_mp_1.update_ha_state()
        ump.update()
        self.assertEqual(self.mock_mp_1.entity_id,
                         ump._child_state.entity_id)

        self.mock_mp_2._state = STATE_PLAYING
        self.mock_mp_2.update_ha_state()
        ump.update()
        self.assertEqual(self.mock_mp_1.entity_id,
                         ump._child_state.entity_id)

        self.mock_mp_1._state = STATE_OFF
        self.mock_mp_1.update_ha_state()
        ump.update()
        self.assertEqual(self.mock_mp_2.entity_id,
                         ump._child_state.entity_id)

    def test_name(self):
        """ test name property """
        config = self.config_children_only
        universal.validate_config(config)

        ump = universal.UniversalMediaPlayer(self.hass, **config)

        self.assertEqual(config['name'], ump.name)

    def test_state_children_only(self):
        """ test media player state with only children """
        config = self.config_children_only
        universal.validate_config(config)

        ump = universal.UniversalMediaPlayer(self.hass, **config)
        ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name'])
        ump.update()

        self.assertTrue(ump.state, STATE_OFF)

        self.mock_mp_1._state = STATE_PLAYING
        self.mock_mp_1.update_ha_state()
        ump.update()
        self.assertEqual(STATE_PLAYING, ump.state)

    def test_state_with_children_and_attrs(self):
        """ test media player with children and master state """
        config = self.config_children_and_attr
        universal.validate_config(config)

        ump = universal.UniversalMediaPlayer(self.hass, **config)
        ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name'])
        ump.update()

        self.assertEqual(ump.state, STATE_OFF)

        self.hass.states.set(self.mock_state_switch_id, STATE_ON)
        ump.update()
        self.assertEqual(ump.state, STATE_ON)

        self.mock_mp_1._state = STATE_PLAYING
        self.mock_mp_1.update_ha_state()
        ump.update()
        self.assertEqual(ump.state, STATE_PLAYING)

        self.hass.states.set(self.mock_state_switch_id, STATE_OFF)
        ump.update()
        self.assertEqual(ump.state, STATE_OFF)

    def test_volume_level(self):
        """ test volume level property """
        config = self.config_children_only
        universal.validate_config(config)

        ump = universal.UniversalMediaPlayer(self.hass, **config)
        ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name'])
        ump.update()

        self.assertEqual(None, ump.volume_level)

        self.mock_mp_1._state = STATE_PLAYING
        self.mock_mp_1.update_ha_state()
        ump.update()
        self.assertEqual(0, ump.volume_level)

        self.mock_mp_1._volume_level = 1
        self.mock_mp_1.update_ha_state()
        ump.update()
        self.assertEqual(1, ump.volume_level)

    def test_is_volume_muted_children_only(self):
        """ test is volume muted property w/ children only """
        config = self.config_children_only
        universal.validate_config(config)

        ump = universal.UniversalMediaPlayer(self.hass, **config)
        ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name'])
        ump.update()

        self.assertFalse(ump.is_volume_muted)

        self.mock_mp_1._state = STATE_PLAYING
        self.mock_mp_1.update_ha_state()
        ump.update()
        self.assertFalse(ump.is_volume_muted)

        self.mock_mp_1._is_volume_muted = True
        self.mock_mp_1.update_ha_state()
        ump.update()
        self.assertTrue(ump.is_volume_muted)

    def test_is_volume_muted_children_and_attr(self):
        """ test is volume muted property w/ children and attrs """
        config = self.config_children_and_attr
        universal.validate_config(config)

        ump = universal.UniversalMediaPlayer(self.hass, **config)

        self.assertFalse(ump.is_volume_muted)

        self.hass.states.set(self.mock_mute_switch_id, STATE_ON)
        self.assertTrue(ump.is_volume_muted)

    def test_supported_media_commands_children_only(self):
        """ test supported media commands with only children """
        config = self.config_children_only
        universal.validate_config(config)

        ump = universal.UniversalMediaPlayer(self.hass, **config)
        ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name'])
        ump.update()

        self.assertEqual(0, ump.supported_media_commands)

        self.mock_mp_1._supported_media_commands = 512
        self.mock_mp_1._state = STATE_PLAYING
        self.mock_mp_1.update_ha_state()
        ump.update()
        self.assertEqual(512, ump.supported_media_commands)

    def test_supported_media_commands_children_and_cmds(self):
        """ test supported media commands with children and attrs """
        config = self.config_children_and_attr
        universal.validate_config(config)
        config['commands']['turn_on'] = 'test'
        config['commands']['turn_off'] = 'test'
        config['commands']['volume_up'] = 'test'
        config['commands']['volume_down'] = 'test'
        config['commands']['volume_mute'] = 'test'

        ump = universal.UniversalMediaPlayer(self.hass, **config)
        ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name'])
        ump.update()

        self.mock_mp_1._supported_media_commands = \
            universal.SUPPORT_VOLUME_SET
        self.mock_mp_1._state = STATE_PLAYING
        self.mock_mp_1.update_ha_state()
        ump.update()

        check_flags = universal.SUPPORT_TURN_ON | universal.SUPPORT_TURN_OFF \
            | universal.SUPPORT_VOLUME_STEP | universal.SUPPORT_VOLUME_MUTE

        self.assertEqual(check_flags, ump.supported_media_commands)