text:
#include "dart/utils/sdf/SdfParser.hpp"

#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <string>

#include <Eigen/Dense>
#include <Eigen/StdVector>
#include <tinyxml2.h>

#include "dart/common/Console.hpp"
#include "dart/common/LocalResourceRetriever.hpp"
#include "dart/common/ResourceRetriever.hpp"
#include "dart/common/Uri.hpp"
#include "dart/dynamics/BallJoint.hpp"
#include "dart/dynamics/BodyNode.hpp"
#include "dart/dynamics/BoxShape.hpp"
#include "dart/dynamics/CylinderShape.hpp"
#include "dart/dynamics/FreeJoint.hpp"
#include "dart/dynamics/MeshShape.hpp"
#include "dart/dynamics/PrismaticJoint.hpp"
#include "dart/dynamics/RevoluteJoint.hpp"
#include "dart/dynamics/ScrewJoint.hpp"
#include "dart/dynamics/Skeleton.hpp"
#include "dart/dynamics/SoftBodyNode.hpp"
#include "dart/dynamics/SphereShape.hpp"
#include "dart/dynamics/UniversalJoint.hpp"
#include "dart/dynamics/WeldJoint.hpp"
#include "dart/simulation/World.hpp"
#include "dart/utils/CompositeResourceRetriever.hpp"
#include "dart/utils/DartResourceRetriever.hpp"
#include "dart/utils/SkelParser.hpp"
#include "dart/utils/XmlHelpers.hpp"

namespace dart {
namespace utils {

namespace SdfParser {

namespace {

using BodyPropPtr = std::shared_ptr<dynamics::BodyNode::Properties>;

struct SDFBodyNode
{
  BodyPropPtr properties;
  Eigen::Isometry3d initTransform;
  std::string type;
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};

using JointPropPtr = std::shared_ptr<dynamics::Joint::Properties>;

struct SDFJoint
{
  JointPropPtr properties;
  std::string parentName;
  std::string childName;
  std::string type;
};

// Maps the name of a BodyNode to its properties
using BodyMap = common::aligned_map<std::string, SDFBodyNode>;

// Maps a child BodyNode to the properties of its parent Joint
using JointMap = std::map<std::string, SDFJoint>;

simulation::WorldPtr readWorld(
    tinyxml2::XMLElement* worldElement,
    const common::Uri& baseUri,
    const Options& options);

void readPhysics(
    tinyxml2::XMLElement* physicsElement, simulation::WorldPtr world);

dynamics::SkeletonPtr readSkeleton(
    tinyxml2::XMLElement* skeletonElement,
    const common::Uri& baseUri,
    const Options& options);

bool createPair(
    dynamics::SkeletonPtr skeleton,
    dynamics::BodyNode* parent,
    const SDFJoint& newJoint,
    const SDFBodyNode& newBody);

enum NextResult
{
  VALID,
  CONTINUE,
  BREAK,
  CREATE_ROOT_JOINT
};

NextResult getNextJointAndNodePair(
    BodyMap::iterator& body,
    JointMap::const_iterator& parentJoint,
    dynamics::BodyNode*& parentBody,
    const dynamics::SkeletonPtr skeleton,
    BodyMap& sdfBodyNodes,
    const JointMap& sdfJoints);

dynamics::SkeletonPtr makeSkeleton(
    tinyxml2::XMLElement* skeletonElement, Eigen::Isometry3d& skeletonFrame);

template <class NodeType>
std::pair<dynamics::Joint*, dynamics::BodyNode*> createJointAndNodePair(
    dynamics::SkeletonPtr skeleton,
    dynamics::BodyNode* parent,
    const SDFJoint& joint,
    const SDFBodyNode& node);

BodyMap readAllBodyNodes(
    tinyxml2::XMLElement* skeletonElement,
    const common::Uri& baseUri,
    const common::ResourceRetrieverPtr& retriever,
    const Eigen::Isometry3d& skeletonFrame);

SDFBodyNode readBodyNode(
    tinyxml2::XMLElement* bodyNodeElement,
    const Eigen::Isometry3d& skeletonFrame,
    const common::Uri& baseUri,
    const common::ResourceRetrieverPtr& retriever);

dynamics::SoftBodyNode::UniqueProperties readSoftBodyProperties(
    tinyxml2::XMLElement* softBodyNodeElement);

dynamics::ShapePtr readShape(
    tinyxml2::XMLElement* shapelement,
    const common::Uri& baseUri,
    const common::ResourceRetrieverPtr& retriever);

dynamics::ShapeNode* readShapeNode(
    dynamics::BodyNode* bodyNode,
    tinyxml2::XMLElement* shapeNodeEle,
    const std::string& shapeNodeName,
    const common::Uri& baseUri,
    const common::ResourceRetrieverPtr& retriever);

void readMaterial(
    tinyxml2::XMLElement* materialEle, dynamics::ShapeNode* shapeNode);

void readVisualizationShapeNode(
    dynamics::BodyNode* bodyNode,
    tinyxml2::XMLElement* vizShapeNodeEle,
    const common::Uri& baseUri,
    const common::ResourceRetrieverPtr& retriever);

void readCollisionShapeNode(
    dynamics::BodyNode* bodyNode,
    tinyxml2::XMLElement* collShapeNodeEle,
    const common::Uri& baseUri,
    const common::ResourceRetrieverPtr& retriever);

void readAspects(
    const dynamics::SkeletonPtr& skeleton,
    tinyxml2::XMLElement* skeletonElement,
    const common::Uri& baseUri,
    const common::ResourceRetrieverPtr& retriever);

JointMap readAllJoints(
    tinyxml2::XMLElement* skeletonElement,
    const Eigen::Isometry3d& skeletonFrame,
    const BodyMap& sdfBodyNodes);

SDFJoint readJoint(
    tinyxml2::XMLElement* jointElement,
    const BodyMap& bodies,
    const Eigen::Isometry3d& skeletonFrame);

dart::dynamics::WeldJoint::Properties readWeldJoint(
    tinyxml2::XMLElement* jointElement,
    const Eigen::Isometry3d& parentModelFrame,
    const std::string& name);

dynamics::RevoluteJoint::Properties readRevoluteJoint(
    tinyxml2::XMLElement* revoluteJointElement,
    const Eigen::Isometry3d& parentModelFrame,
    const std::string& name);

dynamics::PrismaticJoint::Properties readPrismaticJoint(
    tinyxml2::XMLElement* jointElement,
    const Eigen::Isometry3d& parentModelFrame,
    const std::string& name);

dynamics::ScrewJoint::Properties readScrewJoint(
    tinyxml2::XMLElement* jointElement,
    const Eigen::Isometry3d& parentModelFrame,
    const std::string& name);

dynamics::UniversalJoint::Properties readUniversalJoint(
    tinyxml2::XMLElement* jointElement,
    const Eigen::Isometry3d& parentModelFrame,
    const std::string& name);

dynamics::BallJoint::Properties readBallJoint(
    tinyxml2::XMLElement* jointElement,
    const Eigen::Isometry3d& parentModelFrame,
    const std::string& name);

common::ResourceRetrieverPtr getRetriever(
    const common::ResourceRetrieverPtr& retriever);

} // anonymous namespace

//==============================================================================
Options::Options(
    common::ResourceRetrieverPtr resourceRetriever,
    RootJointType defaultRootJointType)
  : mResourceRetriever(std::move(resourceRetriever)),
    mDefaultRootJointType(defaultRootJointType)
{
  // Do nothing
}

//==============================================================================
simulation::WorldPtr readSdfFile(
    const common::Uri& uri, const common::ResourceRetrieverPtr& nullOrRetriever)
{
  Options options;
  options.mResourceRetriever = nullOrRetriever;
  return readWorld(uri, options);
}

//==============================================================================
bool checkVersion(
    const tinyxml2::XMLElement& sdfElement, const common::Uri& uri)
{
  const std::string version = getAttributeString(&sdfElement, "version");
  // TODO: We need version aware SDF parser (see #264)
  // We support 1.4 ~ 1.6.
  if (version != "1.4" && version != "1.5" && version != "1.6")
  {
    dtwarn << "[SdfParser] The file format of [" << uri.toString()
           << "] was found to be [" << version << "], but we only support SDF "
           << "1.4, 1.5, and 1.6!\n";
    return false;
  }

  return true;
}

//==============================================================================
simulation::WorldPtr readWorld(const common::Uri& uri, const Options& options)
{
  const auto retriever = getRetriever(options.mResourceRetriever);

  //--------------------------------------------------------------------------
  // Load xml and create Document
  tinyxml2::XMLDocument sdfFile;
  try
  {
    openXMLFile(sdfFile, uri, retriever);
  }
  catch (std::exception const& e)
  {
    dtwarn << "[SdfParser::readSdfFile] Loading file [" << uri.toString()
           << "] failed: " << e.what() << "\n";
    return nullptr;
  }

  //--------------------------------------------------------------------------
  // Load DART
  tinyxml2::XMLElement* sdfElement = nullptr;
  sdfElement = sdfFile.FirstChildElement("sdf");
  if (sdfElement == nullptr)
    return nullptr;

  //--------------------------------------------------------------------------
  // version attribute
  if (!checkVersion(*sdfElement, uri))
    return nullptr;

  //--------------------------------------------------------------------------
  // Load World
  tinyxml2::XMLElement* worldElement = nullptr;
  worldElement = sdfElement->FirstChildElement("world");
  if (worldElement == nullptr)
    return nullptr;

  return readWorld(worldElement, uri, options);
}

//==============================================================================
simulation::WorldPtr readWorld(
    const common::Uri& uri, const common::ResourceRetrieverPtr& nullOrRetriever)
{
  Options options;
  options.mResourceRetriever = nullOrRetriever;
  return readWorld(uri, options);
}

//==============================================================================
dynamics::SkeletonPtr readSkeleton(
    const common::Uri& uri, const Options& options)
{
  const auto retriever = getRetriever(options.mResourceRetriever);

  //--------------------------------------------------------------------------
  // Load xml and create Document
  tinyxml2::XMLDocument _dartFile;
  try
  {
    openXMLFile(_dartFile, uri, retriever);
  }
  catch (std::exception const& e)
  {
    dtwarn << "[SdfParser::readSkeleton] Loading file [" << uri.toString()
           << "] failed: " << e.what() << "\n";
    return nullptr;
  }

  //--------------------------------------------------------------------------
  // Load sdf
  tinyxml2::XMLElement* sdfElement = nullptr;
  sdfElement = _dartFile.FirstChildElement("sdf");
  if (sdfElement == nullptr)
    return nullptr;

  //--------------------------------------------------------------------------
  // version attribute
  if (!checkVersion(*sdfElement, uri))
    return nullptr;

  //--------------------------------------------------------------------------
  // Load skeleton
  tinyxml2::XMLElement* skelElement = nullptr;
  skelElement = sdfElement->FirstChildElement("model");
  if (skelElement == nullptr)
    return nullptr;

  dynamics::SkeletonPtr newSkeleton = readSkeleton(skelElement, uri, retriever);

  return newSkeleton;
}

//==============================================================================
dynamics::SkeletonPtr readSkeleton(
    const common::Uri& uri, const common::ResourceRetrieverPtr& nullOrRetriever)
{
  Options options;
  options.mResourceRetriever = nullOrRetriever;
  return readSkeleton(uri, options);
}

namespace {

//==============================================================================
simulation::WorldPtr readWorld(
    tinyxml2::XMLElement* worldElement,
    const common::Uri& baseUri,
    const Options& options)
{
  assert(worldElement != nullptr);

  // Create a world
  simulation::WorldPtr newWorld = simulation::World::create();

  //--------------------------------------------------------------------------
  // Name attribute
  std::string name = getAttributeString(worldElement, "name");
  newWorld->setName(name);

  //--------------------------------------------------------------------------
  // Load physics
  if (hasElement(worldElement, "physics"))
  {
    tinyxml2::XMLElement* physicsElement
        = worldElement->FirstChildElement("physics");
    readPhysics(physicsElement, newWorld);
  }

  //--------------------------------------------------------------------------
  // Load skeletons
  ElementEnumerator skeletonElements(worldElement, "model");
  while (skeletonElements.next())
  {
    dynamics::SkeletonPtr newSkeleton
        = readSkeleton(skeletonElements.get(), baseUri, options);

    newWorld->addSkeleton(newSkeleton);
  }

  return newWorld;
}

//==============================================================================
void readPhysics(
    tinyxml2::XMLElement* physicsElement, simulation::WorldPtr world)
{
  // Type attribute
  // std::string physicsEngineName = getAttribute(_physicsElement, "type");

  // Time step
  if (hasElement(physicsElement, "max_step_size"))
  {
    double timeStep = getValueDouble(physicsElement, "max_step_size");
    world->setTimeStep(timeStep);
  }

  // Number of max contacts
  // if (hasElement(_physicsElement, "max_contacts"))
  // {
  //   int timeStep = getValueInt(_physicsElement, "max_contacts");
  //   _world->setMaxNumContacts(timeStep);
  // }

  // Gravity
  if (hasElement(physicsElement, "gravity"))
  {
    Eigen::Vector3d gravity = getValueVector3d(physicsElement, "gravity");
    world->setGravity(gravity);
  }
}

//==============================================================================
dynamics::SkeletonPtr readSkeleton(
    tinyxml2::XMLElement* skeletonElement,
    const common::Uri& baseUri,
    const Options& options)
{
  assert(skeletonElement != nullptr);

  Eigen::Isometry3d skeletonFrame = Eigen::Isometry3d::Identity();
  dynamics::SkeletonPtr newSkeleton
      = makeSkeleton(skeletonElement, skeletonFrame);

  //--------------------------------------------------------------------------
  // Bodies
  BodyMap sdfBodyNodes = readAllBodyNodes(
      skeletonElement, baseUri, options.mResourceRetriever, skeletonFrame);

  //--------------------------------------------------------------------------
  // Joints
  JointMap sdfJoints
      = readAllJoints(skeletonElement, skeletonFrame, sdfBodyNodes);

  // Iterate through the collected properties and construct the Skeleton from
  // the root nodes downward
  BodyMap::iterator body = sdfBodyNodes.begin();
  JointMap::const_iterator parentJoint;
  dynamics::BodyNode* parentBody{nullptr};
  while (body != sdfBodyNodes.end())
  {
    NextResult result = getNextJointAndNodePair(
        body, parentJoint, parentBody, newSkeleton, sdfBodyNodes, sdfJoints);

    if (BREAK == result)
      break;
    else if (CONTINUE == result)
      continue;
    else if (CREATE_ROOT_JOINT == result)
    {
      SDFJoint rootJoint;
      if (options.mDefaultRootJointType == RootJointType::FLOATING)
      {
        // If a root FreeJoint is needed for the parent of the current joint,
        // then create it
        rootJoint.properties = dynamics::FreeJoint::Properties::createShared(
            dynamics::Joint::Properties("root", body->second.initTransform));
        rootJoint.type = "free";
      }
      else if (options.mDefaultRootJointType == RootJointType::FIXED)
      {
        // If a root WeldJoint is needed for the parent of the current joint,
        // then create it
        rootJoint.properties = dynamics::WeldJoint::Properties::createShared(
            dynamics::Joint::Properties("root", body->second.initTransform));
        rootJoint.type = "fixed";
      }
      else
      {
        dtwarn << "Unsupported root joint type ["
               << static_cast<int>(options.mDefaultRootJointType)
               << "]. Using FLOATING by default.\n";
      }

      if (!createPair(newSkeleton, nullptr, rootJoint, body->second))
        break;

      sdfBodyNodes.erase(body);
      body = sdfBodyNodes.begin();

      continue;
    }

    if (!createPair(newSkeleton, parentBody, parentJoint->second, body->second))
      break;

    sdfBodyNodes.erase(body);
    body = sdfBodyNodes.begin();
  }

  // Read aspects here since aspects cannot be added if the BodyNodes haven't
  // created yet.
  readAspects(
      newSkeleton, skeletonElement, baseUri, options.mResourceRetriever);

  // Set positions to their initial values
  newSkeleton->resetPositions();

  return newSkeleton;
}

//==============================================================================
bool createPair(
    dynamics::SkeletonPtr skeleton,
    dynamics::BodyNode* parent,
    const SDFJoint& newJoint,
    const SDFBodyNode& newBody)
{
  std::pair<dynamics::Joint*, dynamics::BodyNode*> pair;

  if (newBody.type.empty())
  {
    pair = createJointAndNodePair<dynamics::BodyNode>(
        skeleton, parent, newJoint, newBody);
  }
  else if (std::string("soft") == newBody.type)
  {
    pair = createJointAndNodePair<dynamics::SoftBodyNode>(
        skeleton, parent, newJoint, newBody);
  }
  else
  {
    dterr << "[SdfParser::createPair] Unsupported Link type: " << newBody.type
          << "\n";
    return false;
  }

  if (!pair.first || !pair.second)
    return false;

  return true;
}

//==============================================================================
NextResult getNextJointAndNodePair(
    BodyMap::iterator& body,
    JointMap::const_iterator& parentJoint,
    dynamics::BodyNode*& parentBody,
    const dynamics::SkeletonPtr skeleton,
    BodyMap& sdfBodyNodes,
    const JointMap& sdfJoints)
{
  parentJoint = sdfJoints.find(body->first);
  if (parentJoint == sdfJoints.end())
  {
    return CREATE_ROOT_JOINT;
  }

  const std::string& parentBodyName = parentJoint->second.parentName;
  const std::string& parentJointName = parentJoint->second.properties->mName;

  // Check if the parent Body is created yet
  parentBody = skeleton->getBodyNode(parentBodyName);
  if (nullptr == parentBody && parentBodyName != "world"
      && !parentBodyName.empty())
  {
    // Find the properties of the parent Joint of the current Joint, because it
    // does not seem to be created yet.
    BodyMap::iterator check_parent_body = sdfBodyNodes.find(parentBodyName);

    if (check_parent_body == sdfBodyNodes.end())
    {
      // The Body does not exist in the file
      dterr << "[SdfParser::getNextJointAndNodePair] Could not find Link "
            << "named [" << parentBodyName << "] requested as parent of "
            << "Joint [" << parentJointName << "]. We will now quit "
            << "parsing.\n";
      return BREAK;
    }
    else
    {
      body = check_parent_body;
      return CONTINUE; // Create the parent before creating the current Joint
    }
  }

  return VALID;
}

dynamics::SkeletonPtr makeSkeleton(
    tinyxml2::XMLElement* _skeletonElement, Eigen::Isometry3d& skeletonFrame)
{
  assert(_skeletonElement != nullptr);

  dynamics::SkeletonPtr newSkeleton = dynamics::Skeleton::create();

  //--------------------------------------------------------------------------
  // Name attribute
  std::string name = getAttributeString(_skeletonElement, "name");
  newSkeleton->setName(name);

  //--------------------------------------------------------------------------
  // immobile attribute
  if (hasElement(_skeletonElement, "static"))
  {
    bool isStatic = getValueBool(_skeletonElement, "static");
    newSkeleton->setMobile(!isStatic);
  }

  //--------------------------------------------------------------------------
  // transformation
  if (hasElement(_skeletonElement, "pose"))
  {
    Eigen::Isometry3d W
        = getValueIsometry3dWithExtrinsicRotation(_skeletonElement, "pose");
    skeletonFrame = W;
  }

  return newSkeleton;
}

//==============================================================================
template <class NodeType>
std::pair<dynamics::Joint*, dynamics::BodyNode*> createJointAndNodePair(
    dynamics::SkeletonPtr skeleton,
    dynamics::BodyNode* parent,
    const SDFJoint& joint,
    const SDFBodyNode& node)
{
  const std::string& type = joint.type;

  if (std::string("prismatic") == type)
    return skeleton->createJointAndBodyNodePair<dynamics::PrismaticJoint>(
        parent,
        static_cast<const dynamics::PrismaticJoint::Properties&>(
            *joint.properties),
        static_cast<const typename NodeType::Properties&>(*node.properties));
  else if (std::string("revolute") == type)
    return skeleton->createJointAndBodyNodePair<dynamics::RevoluteJoint>(
        parent,
        static_cast<const dynamics::RevoluteJoint::Properties&>(
            *joint.properties),
        static_cast<const typename NodeType::Properties&>(*node.properties));
  else if (std::string("screw") == type)
    return skeleton->createJointAndBodyNodePair<dynamics::ScrewJoint>(
        parent,
        static_cast<const dynamics::ScrewJoint::Properties&>(*joint.properties),
        static_cast<const typename NodeType::Properties&>(*node.properties));
  else if (std::string("revolute2") == type || std::string("universal") == type)
    return skeleton->createJointAndBodyNodePair<dynamics::UniversalJoint>(
        parent,
        static_cast<const dynamics::UniversalJoint::Properties&>(
            *joint.properties),
        static_cast<const typename NodeType::Properties&>(*node.properties));
  else if (std::string("ball") == type)
    return skeleton->createJointAndBodyNodePair<dynamics::BallJoint>(
        parent,
        static_cast<const dynamics::BallJoint::Properties&>(*joint.properties),
        static_cast<const typename NodeType::Properties&>(*node.properties));
  else if (std::string("fixed") == type)
    return skeleton->createJointAndBodyNodePair<dynamics::WeldJoint>(
        parent,
        static_cast<const dynamics::WeldJoint::Properties&>(*joint.properties),
        static_cast<const typename NodeType::Properties&>(*node.properties));
  else if (std::string("free") == type)
    return skeleton->createJointAndBodyNodePair<dynamics::FreeJoint>(
        parent,
        static_cast<const dynamics::FreeJoint::Properties&>(*joint.properties),
        static_cast<const typename NodeType::Properties&>(*node.properties));

  dterr << "[SdfParser::createJointAndNodePair] Unsupported Joint type "
           "encountered: "
        << type << ". Please report this as a bug! We will now quit parsing.\n";
  return std::pair<dynamics::Joint*, dynamics::BodyNode*>(nullptr, nullptr);
}

//==============================================================================
BodyMap readAllBodyNodes(
    tinyxml2::XMLElement* skeletonElement,
    const common::Uri& baseUri,
    const common::ResourceRetrieverPtr& retriever,
    const Eigen::Isometry3d& skeletonFrame)
{
  ElementEnumerator bodies(skeletonElement, "link");
  BodyMap sdfBodyNodes;
  while (bodies.next())
  {
    SDFBodyNode body
        = readBodyNode(bodies.get(), skeletonFrame, baseUri, retriever);

    BodyMap::iterator it = sdfBodyNodes.find(body.properties->mName);
    if (it != sdfBodyNodes.end())
    {
      dtwarn << "[SdfParser::readAllBodyNodes] Duplicate name in file: "
             << body.properties->mName << "\n"
             << "Every Link must have a unique name!\n";
      continue;
    }

    sdfBodyNodes[body.properties->mName] = body;
  }

  return sdfBodyNodes;
}

//===============================================================================
SDFBodyNode readBodyNode(
    tinyxml2::XMLElement* bodyNodeElement,
    const Eigen::Isometry3d& skeletonFrame,
    const common::Uri& /*baseUri*/,
    const common::ResourceRetrieverPtr& /*retriever*/)
{
  assert(bodyNodeElement != nullptr);

  dynamics::BodyNode::Properties properties;
  Eigen::Isometry3d initTransform = Eigen::Isometry3d::Identity();

  // Name attribute
  std::string name = getAttributeString(bodyNodeElement, "name");
  properties.mName = name;

  //--------------------------------------------------------------------------
  // gravity
  if (hasElement(bodyNodeElement, "gravity"))
  {
    bool gravityMode = getValueBool(bodyNodeElement, "gravity");
    properties.mGravityMode = gravityMode;
  }

  //--------------------------------------------------------------------------
  // self_collide
  //    if (hasElement(_bodyElement, "self_collide"))
  //    {
  //        bool gravityMode = getValueBool(_bodyElement, "self_collide");
  //    }

  //--------------------------------------------------------------------------
  // transformation
  if (hasElement(bodyNodeElement, "pose"))
  {
    Eigen::Isometry3d W
        = getValueIsometry3dWithExtrinsicRotation(bodyNodeElement, "pose");
    initTransform = skeletonFrame * W;
  }
  else
  {
    initTransform = skeletonFrame;
  }

  //--------------------------------------------------------------------------
  // inertia
  if (hasElement(bodyNodeElement, "inertial"))
  {
    tinyxml2::XMLElement* inertiaElement
        = getElement(bodyNodeElement, "inertial");

    // mass
    if (hasElement(inertiaElement, "mass"))
    {
      double mass = getValueDouble(inertiaElement, "mass");
      properties.mInertia.setMass(mass);
    }

    // offset
    if (hasElement(inertiaElement, "pose"))
    {
      Eigen::Isometry3d T
          = getValueIsometry3dWithExtrinsicRotation(inertiaElement, "pose");
      properties.mInertia.setLocalCOM(T.translation());
    }

    // inertia
    if (hasElement(inertiaElement, "inertia"))
    {
      tinyxml2::XMLElement* moiElement = getElement(inertiaElement, "inertia");

      double ixx = getValueDouble(moiElement, "ixx");
      double iyy = getValueDouble(moiElement, "iyy");
      double izz = getValueDouble(moiElement, "izz");

      double ixy = getValueDouble(moiElement, "ixy");
      double ixz = getValueDouble(moiElement, "ixz");
      double iyz = getValueDouble(moiElement, "iyz");

      properties.mInertia.setMoment(ixx, iyy, izz, ixy, ixz, iyz);
    }
  }

  SDFBodyNode sdfBodyNode;
  sdfBodyNode.initTransform = initTransform;
  if (hasElement(bodyNodeElement, "soft_shape"))
  {
    auto softProperties = readSoftBodyProperties(bodyNodeElement);

    sdfBodyNode.properties = dynamics::SoftBodyNode::Properties::createShared(
        properties, softProperties);
    sdfBodyNode.type = "soft";
  }
  else
  {
    sdfBodyNode.properties
        = dynamics::BodyNode::Properties::createShared(properties);
    sdfBodyNode.type = "";
  }

  return sdfBodyNode;
}

//==============================================================================
dynamics::SoftBodyNode::UniqueProperties readSoftBodyProperties(
    tinyxml2::XMLElement* softBodyNodeElement)
{
  //---------------------------------- Note ------------------------------------
  // SoftBodyNode is created if _softBodyNodeElement has <soft_shape>.
  // Otherwise, BodyNode is created.

  //----------------------------------------------------------------------------
  assert(softBodyNodeElement != nullptr);

  dynamics::SoftBodyNode::UniqueProperties softProperties;

  //----------------------------------------------------------------------------
  // Soft properties
  if (hasElement(softBodyNodeElement, "soft_shape"))
  {
    tinyxml2::XMLElement* softShapeEle
        = getElement(softBodyNodeElement, "soft_shape");

    // mass
    double totalMass = getValueDouble(softShapeEle, "total_mass");

    // pose
    Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
    if (hasElement(softShapeEle, "pose"))
      T = getValueIsometry3dWithExtrinsicRotation(softShapeEle, "pose");

    // geometry
    tinyxml2::XMLElement* geometryEle = getElement(softShapeEle, "geometry");
    if (hasElement(geometryEle, "sphere"))
    {
      tinyxml2::XMLElement* sphereEle = getElement(geometryEle, "sphere");
      const auto radius = getValueDouble(sphereEle, "radius");
      const auto nSlices = getValueUInt(sphereEle, "num_slices");
      const auto nStacks = getValueUInt(sphereEle, "num_stacks");
      softProperties = dynamics::SoftBodyNodeHelper::makeSphereProperties(
          radius, nSlices, nStacks, totalMass);
    }
    else if (hasElement(geometryEle, "box"))
    {
      tinyxml2::XMLElement* boxEle = getElement(geometryEle, "box");
      Eigen::Vector3d size = getValueVector3d(boxEle, "size");
      Eigen::Vector3i frags = getValueVector3i(boxEle, "frags");
      softProperties = dynamics::SoftBodyNodeHelper::makeBoxProperties(
          size, T, frags, totalMass);
    }
    else if (hasElement(geometryEle, "ellipsoid"))
    {
      tinyxml2::XMLElement* ellipsoidEle = getElement(geometryEle, "ellipsoid");
      Eigen::Vector3d size = getValueVector3d(ellipsoidEle, "size");
      const auto nSlices = getValueUInt(ellipsoidEle, "num_slices");
      const auto nStacks = getValueUInt(ellipsoidEle, "num_stacks");
      softProperties = dynamics::SoftBodyNodeHelper::makeEllipsoidProperties(
          size, nSlices, nStacks, totalMass);
    }
    else if (hasElement(geometryEle, "cylinder"))
    {
      tinyxml2::XMLElement* ellipsoidEle = getElement(geometryEle, "cylinder");
      double radius = getValueDouble(ellipsoidEle, "radius");
      double height = getValueDouble(ellipsoidEle, "height");
      double nSlices = getValueDouble(ellipsoidEle, "num_slices");
      double nStacks = getValueDouble(ellipsoidEle, "num_stacks");
      double nRings = getValueDouble(ellipsoidEle, "num_rings");
      softProperties = dynamics::SoftBodyNodeHelper::makeCylinderProperties(
          radius, height, nSlices, nStacks, nRings, totalMass);
    }
    else
    {
      dterr << "Unknown soft shape.\n";
    }

    // kv
    if (hasElement(softShapeEle, "kv"))
    {
      softProperties.mKv = getValueDouble(softShapeEle, "kv");
    }

    // ke
    if (hasElement(softShapeEle, "ke"))
    {
      softProperties.mKe = getValueDouble(softShapeEle, "ke");
    }

    // damp
    if (hasElement(softShapeEle, "damp"))
    {
      softProperties.mDampCoeff = getValueDouble(softShapeEle, "damp");
    }
  }

  return softProperties;
}

//==============================================================================
dynamics::ShapePtr readShape(
    tinyxml2::XMLElement* _shapelement,
    const common::Uri& baseUri,
    const common::ResourceRetrieverPtr& _retriever)
{
  dynamics::ShapePtr newShape;

  // type
  assert(hasElement(_shapelement, "geometry"));
  tinyxml2::XMLElement* geometryElement = getElement(_shapelement, "geometry");

  if (hasElement(geometryElement, "sphere"))
  {
    tinyxml2::XMLElement* sphereElement = getElement(geometryElement, "sphere");

    const auto radius = getValueDouble(sphereElement, "radius");

    newShape = dynamics::ShapePtr(new dynamics::SphereShape(radius));
  }
  else if (hasElement(geometryElement, "box"))
  {
    tinyxml2::XMLElement* boxElement = getElement(geometryElement, "box");

    Eigen::Vector3d size = getValueVector3d(boxElement, "size");

    newShape = dynamics::ShapePtr(new dynamics::BoxShape(size));
  }
  else if (hasElement(geometryElement, "cylinder"))
  {
    tinyxml2::XMLElement* cylinderElement
        = getElement(geometryElement, "cylinder");

    double radius = getValueDouble(cylinderElement, "radius");
    double height = getValueDouble(cylinderElement, "length");

    newShape = dynamics::ShapePtr(new dynamics::CylinderShape(radius, height));
  }
  else if (hasElement(geometryElement, "plane"))
  {
    // TODO: Don't support plane shape yet.
    tinyxml2::XMLElement* planeElement = getElement(geometryElement, "plane");

    Eigen::Vector2d visSize = getValueVector2d(planeElement, "size");
    // TODO: Need to use normal for correct orientation of the plane
    // Eigen::Vector3d normal = getValueVector3d(planeElement, "normal");

    Eigen::Vector3d size(visSize(0), visSize(1), 0.001);

    newShape = dynamics::ShapePtr(new dynamics::BoxShape(size));
  }
  else if (hasElement(geometryElement, "mesh"))
  {
    tinyxml2::XMLElement* meshEle = getElement(geometryElement, "mesh");
    // TODO(JS): We assume that uri is just file name for the mesh
    if (!hasElement(meshEle, "uri"))
    {
      // TODO(MXG): Figure out how to report the file name and line number of
      dtwarn << "[SdfParser::readShape] Mesh is missing a URI, which is "
             << "required in order to load it\n";
      return nullptr;
    }
    std::string uri = getValueString(meshEle, "uri");

    Eigen::Vector3d scale = hasElement(meshEle, "scale")
                                ? getValueVector3d(meshEle, "scale")
                                : Eigen::Vector3d::Ones();

    const std::string meshUri = common::Uri::getRelativeUri(baseUri, uri);
    const aiScene* model = dynamics::MeshShape::loadMesh(meshUri, _retriever);

    if (model)
      newShape = std::make_shared<dynamics::MeshShape>(
          scale, model, meshUri, _retriever);
    else
    {
      dtwarn << "[SdfParser::readShape] Failed to load mesh model [" << meshUri
             << "].\n";
      return nullptr;
    }
  }
  else
  {
    std::cout << "Invalid shape type." << std::endl;
    return nullptr;
  }

  return newShape;
}

//==============================================================================
dynamics::ShapeNode* readShapeNode(
    dynamics::BodyNode* bodyNode,
    tinyxml2::XMLElement* shapeNodeEle,
    const std::string& shapeNodeName,
    const common::Uri& baseUri,
    const common::ResourceRetrieverPtr& retriever)
{
  assert(bodyNode);

  auto shape = readShape(shapeNodeEle, baseUri, retriever);
  auto shapeNode = bodyNode->createShapeNode(shape, shapeNodeName);

  // Transformation
  if (hasElement(shapeNodeEle, "pose"))
  {
    const Eigen::Isometry3d W
        = getValueIsometry3dWithExtrinsicRotation(shapeNodeEle, "pose");
    shapeNode->setRelativeTransform(W);
  }

  return shapeNode;
}

//==============================================================================
void readMaterial(
    tinyxml2::XMLElement* materialEle, dynamics::ShapeNode* shapeNode)
{
  auto visualAspect = shapeNode->getVisualAspect();
  if (hasElement(materialEle, "diffuse"))
  {
    Eigen::VectorXd color = getValueVectorXd(materialEle, "diffuse");
    if (color.size() == 3)
    {
      Eigen::Vector3d color3d = color;
      visualAspect->setColor(color3d);
    }
    else if (color.size() == 4)
    {
      Eigen::Vector4d color4d = color;
      visualAspect->setColor(color4d);
    }
    else
    {
      dterr << "[SdfParse::readMaterial] Unsupported color vector size: "
            << color.size() << "\n";
    }
  }
}

//==============================================================================
void readVisualizationShapeNode(
    dynamics::BodyNode* bodyNode,
    tinyxml2::XMLElement* vizShapeNodeEle,
    const common::Uri& baseUri,
    const common::ResourceRetrieverPtr& retriever)
{
  std::string visualName = "visual shape";
  if (hasAttribute(vizShapeNodeEle, "name"))
  {
    visualName = getAttributeString(vizShapeNodeEle, "name");
  }
  else
  {
    dtwarn << "Missing required attribute [name] in <visual> element of "
           << "<link name = " << bodyNode->getName() << ">.\n";
  }

  dynamics::ShapeNode* newShapeNode = readShapeNode(
      bodyNode,
      vizShapeNodeEle,
      bodyNode->getName() + " - " + visualName,
      baseUri,
      retriever);

  newShapeNode->createVisualAspect();

  // Material
  if (hasElement(vizShapeNodeEle, "material"))
  {
    tinyxml2::XMLElement* materialEle = getElement(vizShapeNodeEle, "material");
    readMaterial(materialEle, newShapeNode);
  }
}

//==============================================================================
void readCollisionShapeNode(
    dynamics::BodyNode* bodyNode,
    tinyxml2::XMLElement* collShapeNodeEle,
    const common::Uri& baseUri,
    const common::ResourceRetrieverPtr& retriever)
{
  std::string collName = "collision shape";
  if (hasAttribute(collShapeNodeEle, "name"))
  {
    collName = getAttributeString(collShapeNodeEle, "name");
  }
  else
  {
    dtwarn << "Missing required attribute [name] in <collision> element of "
           << "<link name = " << bodyNode->getName() << ">.\n";
  }

  dynamics::ShapeNode* newShapeNode = readShapeNode(
      bodyNode,
      collShapeNodeEle,
      bodyNode->getName() + " - " + collName,
      baseUri,
      retriever);

  newShapeNode->createCollisionAspect();
  newShapeNode->createDynamicsAspect();
}

//==============================================================================
void readAspects(
    const dynamics::SkeletonPtr& skeleton,
    tinyxml2::XMLElement* skeletonElement,
    const common::Uri& baseUri,
    const common::ResourceRetrieverPtr& retriever)
{
  ElementEnumerator xmlBodies(skeletonElement, "link");
  while (xmlBodies.next())
  {
    auto bodyElement = xmlBodies.get();
    auto bodyNodeName = getAttributeString(bodyElement, "name");
    auto bodyNode = skeleton->getBodyNode(bodyNodeName);

    // visualization_shape
    ElementEnumerator vizShapes(bodyElement, "visual");
    while (vizShapes.next())
    {
      readVisualizationShapeNode(bodyNode, vizShapes.get(), baseUri, retriever);
    }

    // collision_shape
    ElementEnumerator collShapes(bodyElement, "collision");
    while (collShapes.next())
      readCollisionShapeNode(bodyNode, collShapes.get(), baseUri, retriever);
  }
}

//==============================================================================
JointMap readAllJoints(
    tinyxml2::XMLElement* _skeletonElement,
    const Eigen::Isometry3d& skeletonFrame,
    const BodyMap& sdfBodyNodes)
{
  JointMap sdfJoints;
  ElementEnumerator joints(_skeletonElement, "joint");
  while (joints.next())
  {
    SDFJoint joint = readJoint(joints.get(), sdfBodyNodes, skeletonFrame);

    if (joint.childName.empty())
    {
      dterr << "[SdfParser::readAllJoints] Joint named ["
            << joint.properties->mName << "] does not have a valid child "
            << "Link, so it will not be added to the Skeleton\n";
      continue;
    }

    JointMap::iterator it = sdfJoints.find(joint.childName);
    if (it != sdfJoints.end())
    {
      dterr << "[SdfParser::readAllJoints] Joint named ["
            << joint.properties->mName << "] is claiming Link ["
            << joint.childName << "] as its child, but that is already "
            << "claimed by Joint [" << it->second.properties->mName
            << "]. Joint [" << joint.properties->mName
            << "] will be discarded\n";
      continue;
    }

    sdfJoints[joint.childName] = joint;
  }

  return sdfJoints;
}

SDFJoint readJoint(
    tinyxml2::XMLElement* _jointElement,
    const BodyMap& _sdfBodyNodes,
    const Eigen::Isometry3d& _skeletonFrame)
{
  assert(_jointElement != nullptr);

  //--------------------------------------------------------------------------
  // Type attribute
  std::string type = getAttributeString(_jointElement, "type");
  assert(!type.empty());

  //--------------------------------------------------------------------------
  // Name attribute
  std::string name = getAttributeString(_jointElement, "name");

  //--------------------------------------------------------------------------
  // parent
  BodyMap::const_iterator parent_it = _sdfBodyNodes.end();

  if (hasElement(_jointElement, "parent"))
  {
    std::string strParent = getValueString(_jointElement, "parent");

    if (strParent != std::string("world"))
    {
      parent_it = _sdfBodyNodes.find(strParent);

      if (parent_it == _sdfBodyNodes.end())
      {
        dterr << "[SdfParser::readJoint] Cannot find a Link named ["
              << strParent << "] requested as the parent of the Joint named ["
              << name << "]\n";
        assert(0);
      }
    }
  }
  else
  {
    dterr << "[SdfParser::readJoint] You must set parent link for "
          << "the Joint [" << name << "]!\n";
    assert(0);
  }

  //--------------------------------------------------------------------------
  // child
  BodyMap::const_iterator child_it = _sdfBodyNodes.end();

  if (hasElement(_jointElement, "child"))
  {
    std::string strChild = getValueString(_jointElement, "child");

    child_it = _sdfBodyNodes.find(strChild);

    if (child_it == _sdfBodyNodes.end())
    {
      dterr << "[SdfParser::readJoint] Cannot find a Link named [" << strChild
            << "] requested as the child of the Joint named [" << name << "]\n";
      assert(0);
    }
  }
  else
  {
    dterr << "[SdfParser::readJoint] You must set the child link for the Joint "
          << "[" << name << "]!\n";
    assert(0);
  }

  SDFJoint newJoint;
  newJoint.parentName
      = (parent_it == _sdfBodyNodes.end()) ? "" : parent_it->first;
  newJoint.childName = (child_it == _sdfBodyNodes.end()) ? "" : child_it->first;

  //--------------------------------------------------------------------------
  // transformation
  Eigen::Isometry3d parentWorld = Eigen::Isometry3d::Identity();
  Eigen::Isometry3d childToJoint = Eigen::Isometry3d::Identity();
  Eigen::Isometry3d childWorld = Eigen::Isometry3d::Identity();

  if (parent_it != _sdfBodyNodes.end())
    parentWorld = parent_it->second.initTransform;
  if (child_it != _sdfBodyNodes.end())
    childWorld = child_it->second.initTransform;
  if (hasElement(_jointElement, "pose"))
    childToJoint
        = getValueIsometry3dWithExtrinsicRotation(_jointElement, "pose");

  Eigen::Isometry3d parentToJoint
      = parentWorld.inverse() * childWorld * childToJoint;

  // TODO: Workaround!!
  Eigen::Isometry3d parentModelFrame
      = (childWorld * childToJoint).inverse() * _skeletonFrame;

  if (type == std::string("fixed"))
  {
    newJoint.properties = dynamics::WeldJoint::Properties::createShared(
        readWeldJoint(_jointElement, parentModelFrame, name));
  }
  else if (type == std::string("prismatic"))
  {
    newJoint.properties = dynamics::PrismaticJoint::Properties::createShared(
        readPrismaticJoint(_jointElement, parentModelFrame, name));
  }
  else if (type == std::string("revolute"))
  {
    newJoint.properties = dynamics::RevoluteJoint::Properties::createShared(
        readRevoluteJoint(_jointElement, parentModelFrame, name));
  }
  else if (type == std::string("screw"))
  {
    newJoint.properties = dynamics::ScrewJoint::Properties::createShared(
        readScrewJoint(_jointElement, parentModelFrame, name));
  }
  else if (type == std::string("revolute2") || type == std::string("universal"))
  {
    newJoint.properties = dynamics::UniversalJoint::Properties::createShared(
        readUniversalJoint(_jointElement, parentModelFrame, name));
  }
  else if (type == std::string("ball"))
  {
    newJoint.properties = dynamics::BallJoint::Properties::createShared(
        readBallJoint(_jointElement, parentModelFrame, name));
  }
  else
  {
    dterr << "Unsupported joint type [" << type
          << "]. Using [fixed] joint type instead.\n";
    newJoint.properties = dynamics::WeldJoint::Properties::createShared(
        readWeldJoint(_jointElement, parentModelFrame, name));
  }

  newJoint.type = type;

  newJoint.properties->mName = name;

  newJoint.properties->mT_ChildBodyToJoint = childToJoint;
  newJoint.properties->mT_ParentBodyToJoint = parentToJoint;

  return newJoint;
}

static void reportMissingElement(
    const std::string& functionName,
    const std::string& elementName,
    const std::string& objectType,
    const std::string& objectName)
{
  dterr << "[SdfParser::" << functionName << "] Missing element " << elementName
        << " for " << objectType << " named " << objectName << "\n";
  assert(0);
}

static void readAxisElement(
    tinyxml2::XMLElement* axisElement,
    const Eigen::Isometry3d& _parentModelFrame,
    Eigen::Vector3d& axis,
    double& lower,
    double& upper,
    double& initial,
    double& rest,
    double& damping,
    double& friction,
    double& spring_stiffness)
{
  // use_parent_model_frame
  bool useParentModelFrame = false;
  if (hasElement(axisElement, "use_parent_model_frame"))
    useParentModelFrame = getValueBool(axisElement, "use_parent_model_frame");

  // xyz
  Eigen::Vector3d xyz = getValueVector3d(axisElement, "xyz");
  if (useParentModelFrame)
  {
    xyz = _parentModelFrame.rotation() * xyz;
  }
  axis = xyz;

  // dynamics
  if (hasElement(axisElement, "dynamics"))
  {
    tinyxml2::XMLElement* dynamicsElement = getElement(axisElement, "dynamics");

    // damping
    if (hasElement(dynamicsElement, "damping"))
    {
      damping = getValueDouble(dynamicsElement, "damping");
    }

    // friction
    if (hasElement(dynamicsElement, "friction"))
    {
      friction = getValueDouble(dynamicsElement, "friction");
    }

    // spring reference
    if (hasElement(dynamicsElement, "spring_reference"))
    {
      rest = getValueDouble(dynamicsElement, "spring_reference");
    }

    // spring stiffness
    if (hasElement(dynamicsElement, "spring_stiffness"))
    {
      spring_stiffness = getValueDouble(dynamicsElement, "spring_stiffness");
    }
  }

  // limit
  if (hasElement(axisElement, "limit"))
  {
    tinyxml2::XMLElement* limitElement = getElement(axisElement, "limit");

    // lower
    if (hasElement(limitElement, "lower"))
    {
      lower = getValueDouble(limitElement, "lower");
    }

    // upper
    if (hasElement(limitElement, "upper"))
    {
      upper = getValueDouble(limitElement, "upper");
    }
  }

  // If the zero position is out of our limits, we should change the initial
  // position instead of assuming zero
  if (0.0 < lower || upper < 0.0)
  {
    if (std::isfinite(lower) && std::isfinite(upper))
      initial = (lower + upper) / 2.0;
    else if (std::isfinite(lower))
      initial = lower;
    else if (std::isfinite(upper))
      initial = upper;

    // Any other case means the limits are both +inf, both -inf, or one is a NaN

    // Apply the same logic to the rest position.
    rest = initial;
  }
}

dart::dynamics::WeldJoint::Properties readWeldJoint(
    tinyxml2::XMLElement* /*_jointElement*/,
    const Eigen::Isometry3d&,
    const std::string&)
{
  return dynamics::WeldJoint::Properties();
}

dynamics::RevoluteJoint::Properties readRevoluteJoint(
    tinyxml2::XMLElement* _revoluteJointElement,
    const Eigen::Isometry3d& _parentModelFrame,
    const std::string& _name)
{
  assert(_revoluteJointElement != nullptr);

  dynamics::RevoluteJoint::Properties newRevoluteJoint;

  //--------------------------------------------------------------------------
  // axis
  if (hasElement(_revoluteJointElement, "axis"))
  {
    tinyxml2::XMLElement* axisElement
        = getElement(_revoluteJointElement, "axis");

    readAxisElement(
        axisElement,
        _parentModelFrame,
        newRevoluteJoint.mAxis,
        newRevoluteJoint.mPositionLowerLimits[0],
        newRevoluteJoint.mPositionUpperLimits[0],
        newRevoluteJoint.mInitialPositions[0],
        newRevoluteJoint.mRestPositions[0],
        newRevoluteJoint.mDampingCoefficients[0],
        newRevoluteJoint.mFrictions[0],
        newRevoluteJoint.mSpringStiffnesses[0]);
  }
  else
  {
    reportMissingElement("readRevoluteJoint", "axis", "joint", _name);
  }

  return newRevoluteJoint;
}

dynamics::PrismaticJoint::Properties readPrismaticJoint(
    tinyxml2::XMLElement* _jointElement,
    const Eigen::Isometry3d& _parentModelFrame,
    const std::string& _name)
{
  assert(_jointElement != nullptr);

  dynamics::PrismaticJoint::Properties newPrismaticJoint;

  //--------------------------------------------------------------------------
  // axis
  if (hasElement(_jointElement, "axis"))
  {
    tinyxml2::XMLElement* axisElement = getElement(_jointElement, "axis");

    readAxisElement(
        axisElement,
        _parentModelFrame,
        newPrismaticJoint.mAxis,
        newPrismaticJoint.mPositionLowerLimits[0],
        newPrismaticJoint.mPositionUpperLimits[0],
        newPrismaticJoint.mInitialPositions[0],
        newPrismaticJoint.mRestPositions[0],
        newPrismaticJoint.mDampingCoefficients[0],
        newPrismaticJoint.mFrictions[0],
        newPrismaticJoint.mSpringStiffnesses[0]);
  }
  else
  {
    reportMissingElement("readPrismaticJoint", "axis", "joint", _name);
  }

  return newPrismaticJoint;
}

dynamics::ScrewJoint::Properties readScrewJoint(
    tinyxml2::XMLElement* _jointElement,
    const Eigen::Isometry3d& _parentModelFrame,
    const std::string& _name)
{
  assert(_jointElement != nullptr);

  dynamics::ScrewJoint::Properties newScrewJoint;

  //--------------------------------------------------------------------------
  // axis
  if (hasElement(_jointElement, "axis"))
  {
    tinyxml2::XMLElement* axisElement = getElement(_jointElement, "axis");

    readAxisElement(
        axisElement,
        _parentModelFrame,
        newScrewJoint.mAxis,
        newScrewJoint.mPositionLowerLimits[0],
        newScrewJoint.mPositionUpperLimits[0],
        newScrewJoint.mInitialPositions[0],
        newScrewJoint.mRestPositions[0],
        newScrewJoint.mDampingCoefficients[0],
        newScrewJoint.mFrictions[0],
        newScrewJoint.mSpringStiffnesses[0]);
  }
  else
  {
    reportMissingElement("readScrewJoint", "axis", "joint", _name);
  }

  // pitch
  if (hasElement(_jointElement, "thread_pitch"))
  {
    double pitch = getValueDouble(_jointElement, "thread_pitch");
    newScrewJoint.mPitch = pitch;
  }

  return newScrewJoint;
}

dynamics::UniversalJoint::Properties readUniversalJoint(
    tinyxml2::XMLElement* _jointElement,
    const Eigen::Isometry3d& _parentModelFrame,
    const std::string& _name)
{
  assert(_jointElement != nullptr);

  dynamics::UniversalJoint::Properties newUniversalJoint;

  //--------------------------------------------------------------------------
  // axis
  if (hasElement(_jointElement, "axis"))
  {
    tinyxml2::XMLElement* axisElement = getElement(_jointElement, "axis");

    readAxisElement(
        axisElement,
        _parentModelFrame,
        newUniversalJoint.mAxis[0],
        newUniversalJoint.mPositionLowerLimits[0],
        newUniversalJoint.mPositionUpperLimits[0],
        newUniversalJoint.mInitialPositions[0],
        newUniversalJoint.mRestPositions[0],
        newUniversalJoint.mDampingCoefficients[0],
        newUniversalJoint.mFrictions[0],
        newUniversalJoint.mSpringStiffnesses[0]);
  }
  else
  {
    reportMissingElement("readUniversalJoint", "axis", "joint", _name);
  }

  //--------------------------------------------------------------------------
  // axis2
  if (hasElement(_jointElement, "axis2"))
  {
    tinyxml2::XMLElement* axis2Element = getElement(_jointElement, "axis2");

    readAxisElement(
        axis2Element,
        _parentModelFrame,
        newUniversalJoint.mAxis[1],
        newUniversalJoint.mPositionLowerLimits[1],
        newUniversalJoint.mPositionUpperLimits[1],
        newUniversalJoint.mInitialPositions[1],
        newUniversalJoint.mRestPositions[1],
        newUniversalJoint.mDampingCoefficients[1],
        newUniversalJoint.mFrictions[1],
        newUniversalJoint.mSpringStiffnesses[1]);
  }
  else
  {
    reportMissingElement("readUniversalJoint", "axis2", "joint", _name);
  }

  return newUniversalJoint;
}

dynamics::BallJoint::Properties readBallJoint(
    tinyxml2::XMLElement* /*_jointElement*/,
    const Eigen::Isometry3d&,
    const std::string&)
{
  return dynamics::BallJoint::Properties();
}

//==============================================================================
common::ResourceRetrieverPtr getRetriever(
    const common::ResourceRetrieverPtr& retriever)
{
  if (retriever)
  {
    return retriever;
  }
  else
  {
    auto newRetriever = std::make_shared<utils::CompositeResourceRetriever>();
    newRetriever->addSchemaRetriever(
        "file", std::make_shared<common::LocalResourceRetriever>());
    newRetriever->addSchemaRetriever("dart", DartResourceRetriever::create());

    return newRetriever;
  }
}

} // anonymous namespace

} // namespace SdfParser

} // namespace utils
} // namespace dart


text:
<?php

require_once __DIR__ . '/../vendor/autoload.php';

use Filchos\Imago\Source\Value;
use Filchos\Imago\Transformer\HtmlToDom;

class HtmlToDomTest extends PHPUnit_Framework_TestCase
{

    public function testGetWellFormed()
    {
        $xml   = '
Malmberget
';
        $imago = new Value($xml);
        $imago = new HtmlToDom($imago);
        $doc   = $imago->get();

        $this->assertInstanceOf('DomDocument', $doc);
        $this->assertEquals('Malmberget', $doc->getElementsByTagName('h1')->item(0)->nodeValue);
    }

    public function testUgly()
    {
        $xml   = '

Koskullskulle';
        $imago = new Value($xml);
        $imago = new HtmlToDom($imago);
        $doc   = $imago->get();

        $this->assertInstanceOf('DomDocument', $doc);
        $this->assertEquals('Koskullskulle', $doc->getElementsByTagName('h2')->item(0)->nodeValue);
    }

    /**
     * @expectedException Filchos\Imago\Exception\DomException
     * @expectedExceptionCode 81
     */
    public function testWrongIso()
    {
        $xml   = '
G' . chr(228) . 'llivare
';
        $imago = new Value($xml);
        $imago = new HtmlToDom($imago);
        $doc   = $imago->get();
    }

    public function testCorrectedIso1()
    {
        $xml   = '
G' . chr(228) . 'llivare
';
        $imago = new Value($xml);
        $imago = new HtmlToDom($imago, ['encoding' => 'ISO-8859-15']);
        $doc   = $imago->get();

        $this->assertSame('ISO-8859-15', $imago->options()->get('encoding'));
        $this->assertEquals('Gällivare', $doc->getElementsByTagName('h3')->item(0)->nodeValue);
    }

    public function testCorrectedIso5()
    {
        $xml   = '
' . chr(191) . chr(208) . chr(239) . chr(219) . chr(208). '
';
        $imago = new Value($xml);
        $imago = new HtmlToDom($imago, ['encoding' => 'ISO-8859-5']);
        $doc   = $imago->get();

        $this->assertEquals('Паяла', $doc->getElementsByTagName('h4')->item(0)->nodeValue);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.kafka.streams.integration;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.IntegerSerializer;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.errors.StreamsNotStartedException;
import org.apache.kafka.streams.errors.StreamsStoppedException;
import org.apache.kafka.streams.errors.UnknownStateStoreException;
import org.apache.kafka.streams.integration.utils.EmbeddedKafkaCluster;
import org.apache.kafka.streams.integration.utils.IntegrationTestUtils;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.processor.ProcessorContext;
import org.apache.kafka.streams.processor.StateStore;
import org.apache.kafka.streams.processor.StateStoreContext;
import org.apache.kafka.streams.processor.internals.StreamThread;
import org.apache.kafka.streams.processor.internals.StreamThread.State;
import org.apache.kafka.streams.query.FailureReason;
import org.apache.kafka.streams.query.KeyQuery;
import org.apache.kafka.streams.query.Position;
import org.apache.kafka.streams.query.QueryResult;
import org.apache.kafka.streams.query.StateQueryRequest;
import org.apache.kafka.streams.query.StateQueryResult;
import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier;
import org.apache.kafka.streams.state.KeyValueIterator;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.ValueAndTimestamp;
import org.apache.kafka.streams.state.internals.StoreQueryUtils;
import org.apache.kafka.test.TestUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.api.Timeout;

import java.io.IOException;
import java.lang.reflect.Field;
import java.time.Duration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static java.util.Collections.singleton;
import static org.apache.kafka.common.utils.Utils.mkSet;
import static org.apache.kafka.streams.query.StateQueryRequest.inStore;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.jupiter.api.Assertions.assertThrows;

@Timeout(600)
@Tag("integration")
public class IQv2IntegrationTest {
    private static final int NUM_BROKERS = 1;
    public static final Duration WINDOW_SIZE = Duration.ofMinutes(5);
    private static int port = 0;
    private static final String INPUT_TOPIC_NAME = "input-topic";
    private static final Position INPUT_POSITION = Position.emptyPosition();
    private static final String STORE_NAME = "kv-store";

    public static final EmbeddedKafkaCluster CLUSTER = new EmbeddedKafkaCluster(NUM_BROKERS);

    private KafkaStreams kafkaStreams;

    @BeforeAll
    public static void before()
        throws InterruptedException, IOException, ExecutionException, TimeoutException {
        CLUSTER.start();
        final int partitions = 2;
        CLUSTER.createTopic(INPUT_TOPIC_NAME, partitions, 1);

        final Properties producerProps = new Properties();
        producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, CLUSTER.bootstrapServers());
        producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
        producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);

        final List<Future<RecordMetadata>> futures = new LinkedList<>();
        try (final Producer<Integer, Integer> producer = new KafkaProducer<>(producerProps)) {
            for (int i = 0; i < 3; i++) {
                final Future<RecordMetadata> send = producer.send(
                    new ProducerRecord<>(
                        INPUT_TOPIC_NAME,
                        i % partitions,
                        Time.SYSTEM.milliseconds(),
                        i,
                        i,
                        null
                    )
                );
                futures.add(send);
                Time.SYSTEM.sleep(1L);
            }
            producer.flush();

            for (final Future<RecordMetadata> future : futures) {
                final RecordMetadata recordMetadata = future.get(1, TimeUnit.MINUTES);
                assertThat(recordMetadata.hasOffset(), is(true));
                INPUT_POSITION.withComponent(
                    recordMetadata.topic(),
                    recordMetadata.partition(),
                    recordMetadata.offset()
                );
            }
        }

        assertThat(INPUT_POSITION, equalTo(
            Position
                .emptyPosition()
                .withComponent(INPUT_TOPIC_NAME, 0, 1L)
                .withComponent(INPUT_TOPIC_NAME, 1, 0L)
        ));
    }

    @BeforeEach
    public void beforeTest(final TestInfo testInfo) {
        final StreamsBuilder builder = new StreamsBuilder();

        builder.table(
            INPUT_TOPIC_NAME,
            Consumed.with(Serdes.Integer(), Serdes.Integer()),
            Materialized.as(STORE_NAME)
        );

        kafkaStreams = new KafkaStreams(builder.build(), streamsConfiguration(testInfo));
        kafkaStreams.cleanUp();
    }

    @AfterEach
    public void afterTest() {
        kafkaStreams.close();
        kafkaStreams.cleanUp();
    }

    @AfterAll
    public static void after() {
        CLUSTER.stop();
    }

    @Test
    public void shouldFailUnknownStore() {
        final KeyQuery<Integer, ValueAndTimestamp<Integer>> query = KeyQuery.withKey(1);
        final StateQueryRequest<ValueAndTimestamp<Integer>> request =
            inStore("unknown-store").withQuery(query);

        assertThrows(UnknownStateStoreException.class, () -> kafkaStreams.query(request));
    }

    @Test
    public void shouldFailNotStarted() {
        final KeyQuery<Integer, ValueAndTimestamp<Integer>> query = KeyQuery.withKey(1);
        final StateQueryRequest<ValueAndTimestamp<Integer>> request =
            inStore(STORE_NAME).withQuery(query);

        assertThrows(StreamsNotStartedException.class, () -> kafkaStreams.query(request));
    }

    @Test
    public void shouldFailStopped() {
        final KeyQuery<Integer, ValueAndTimestamp<Integer>> query = KeyQuery.withKey(1);
        final StateQueryRequest<ValueAndTimestamp<Integer>> request =
            inStore(STORE_NAME).withQuery(query);

        kafkaStreams.start();
        kafkaStreams.close(Duration.ZERO);
        assertThrows(StreamsStoppedException.class, () -> kafkaStreams.query(request));
    }

    @Test
    public void shouldRejectNonRunningActive()
        throws NoSuchFieldException, IllegalAccessException {
        final KeyQuery<Integer, ValueAndTimestamp<Integer>> query = KeyQuery.withKey(1);
        final StateQueryRequest<ValueAndTimestamp<Integer>> request =
            inStore(STORE_NAME).withQuery(query).requireActive();
        final Set<Integer> partitions = mkSet(0, 1);

        kafkaStreams.start();

        final Field threadsField = KafkaStreams.class.getDeclaredField("threads");
        threadsField.setAccessible(true);
        @SuppressWarnings("unchecked") final List<StreamThread> threads =
            (List<StreamThread>) threadsField.get(kafkaStreams);
        final StreamThread streamThread = threads.get(0);

        final Field stateLock = StreamThread.class.getDeclaredField("stateLock");
        stateLock.setAccessible(true);
        final Object lock = stateLock.get(streamThread);

        // wait for the desired partitions to be assigned
        IntegrationTestUtils.iqv2WaitForPartitions(
            kafkaStreams,
            inStore(STORE_NAME).withQuery(query),
            partitions
        );

        // then lock the thread state, change it, and make our assertions.
        synchronized (lock) {
            final Field stateField = StreamThread.class.getDeclaredField("state");
            stateField.setAccessible(true);
            stateField.set(streamThread, State.PARTITIONS_ASSIGNED);

            final StateQueryResult<ValueAndTimestamp<Integer>> result =
                IntegrationTestUtils.iqv2WaitForPartitions(
                    kafkaStreams,
                    request,
                    partitions
                );

            assertThat(result.getPartitionResults().keySet(), is(partitions));
            for (final Integer partition : partitions) {
                assertThat(result.getPartitionResults().get(partition).isFailure(), is(true));
                assertThat(
                    result.getPartitionResults().get(partition).getFailureReason(),
                    is(FailureReason.NOT_ACTIVE)
                );
                assertThat(
                    result.getPartitionResults().get(partition).getFailureMessage(),
                    is("Query requires a running active task,"
                        + " but partition was in state PARTITIONS_ASSIGNED and was active.")
                );
            }
        }
    }

    @Test
    public void shouldFetchFromPartition() {
        final KeyQuery<Integer, ValueAndTimestamp<Integer>> query = KeyQuery.withKey(1);
        final int partition = 1;
        final Set<Integer> partitions = singleton(partition);
        final StateQueryRequest<ValueAndTimestamp<Integer>> request =
            inStore(STORE_NAME).withQuery(query).withPartitions(partitions);

        kafkaStreams.start();
        final StateQueryResult<ValueAndTimestamp<Integer>> result =
            IntegrationTestUtils.iqv2WaitForResult(kafkaStreams, request);

        assertThat(result.getPartitionResults().keySet(), equalTo(partitions));
    }

    @Test
    public void shouldFetchExplicitlyFromAllPartitions() {
        final KeyQuery<Integer, ValueAndTimestamp<Integer>> query = KeyQuery.withKey(1);
        final Set<Integer> partitions = mkSet(0, 1);
        final StateQueryRequest<ValueAndTimestamp<Integer>> request =
            inStore(STORE_NAME).withQuery(query).withAllPartitions();

        kafkaStreams.start();
        final StateQueryResult<ValueAndTimestamp<Integer>> result =
            IntegrationTestUtils.iqv2WaitForPartitions(kafkaStreams, request, partitions);

        assertThat(result.getPartitionResults().keySet(), equalTo(partitions));
    }

    @Test
    public void shouldNotRequireQueryHandler(final TestInfo testInfo) {
        final KeyQuery<Integer, ValueAndTimestamp<Integer>> query = KeyQuery.withKey(1);
        final int partition = 1;
        final Set<Integer> partitions = singleton(partition);
        final StateQueryRequest<ValueAndTimestamp<Integer>> request =
            inStore(STORE_NAME).withQuery(query).withPartitions(partitions);

        final StreamsBuilder builder = new StreamsBuilder();

        builder.table(
            INPUT_TOPIC_NAME,
            Consumed.with(Serdes.Integer(), Serdes.Integer()),
            Materialized.as(new KeyValueBytesStoreSupplier() {
                @Override
                public String name() {
                    return STORE_NAME;
                }

                @Override
                public KeyValueStore<Bytes, byte[]> get() {
                    return new KeyValueStore<Bytes, byte[]>() {
                        private boolean open = false;
                        private Map<Bytes, byte[]> map = new HashMap<>();
                        private Position position;
                        private StateStoreContext context;

                        @Override
                        public void put(final Bytes key, final byte[] value) {
                            map.put(key, value);
                            StoreQueryUtils.updatePosition(position,  context);
                        }

                        @Override
                        public byte[] putIfAbsent(final Bytes key, final byte[] value) {
                            StoreQueryUtils.updatePosition(position,  context);
                            return map.putIfAbsent(key, value);
                        }

                        @Override
                        public void putAll(final List<KeyValue<Bytes, byte[]>> entries) {
                            StoreQueryUtils.updatePosition(position,  context);
                            for (final KeyValue<Bytes, byte[]> entry : entries) {
                                map.put(entry.key, entry.value);
                            }
                        }

                        @Override
                        public byte[] delete(final Bytes key) {
                            StoreQueryUtils.updatePosition(position,  context);
                            return map.remove(key);
                        }

                        @Override
                        public String name() {
                            return STORE_NAME;
                        }

                        @Deprecated
                        @Override
                        public void init(final ProcessorContext context, final StateStore root) {
                            throw new UnsupportedOperationException();
                        }

                        @Override
                        public void init(final StateStoreContext context, final StateStore root) {
                            context.register(root, (key, value) -> put(Bytes.wrap(key), value));
                            this.open = true;
                            this.position = Position.emptyPosition();
                            this.context = context;
                        }

                        @Override
                        public void flush() {

                        }

                        @Override
                        public void close() {
                            this.open = false;
                            map.clear();
                        }

                        @Override
                        public boolean persistent() {
                            return false;
                        }

                        @Override
                        public boolean isOpen() {
                            return open;
                        }

                        @Override
                        public Position getPosition() {
                            return position;
                        }

                        @Override
                        public byte[] get(final Bytes key) {
                            return map.get(key);
                        }

                        @Override
                        public KeyValueIterator<Bytes, byte[]> range(
                            final Bytes from,
                            final Bytes to
                        ) {
                            throw new UnsupportedOperationException();
                        }

                        @Override
                        public KeyValueIterator<Bytes, byte[]> all() {
                            throw new UnsupportedOperationException();
                        }

                        @Override
                        public long approximateNumEntries() {
                            return map.size();
                        }
                    };
                }

                @Override
                public String metricsScope() {
                    return "nonquery";
                }
            })
        );

        kafkaStreams = new KafkaStreams(builder.build(), streamsConfiguration(testInfo));
        kafkaStreams.cleanUp();

        kafkaStreams.start();
        final StateQueryResult<ValueAndTimestamp<Integer>> result =
            IntegrationTestUtils.iqv2WaitForResult(kafkaStreams, request);

        final QueryResult<ValueAndTimestamp<Integer>> queryResult =
            result.getPartitionResults().get(partition);
        assertThat(queryResult.isFailure(), is(true));
        assertThat(queryResult.getFailureReason(), is(FailureReason.UNKNOWN_QUERY_TYPE));
        assertThat(queryResult.getFailureMessage(), matchesPattern(
            "This store (.*) doesn't know how to execute the given query (.*)."
                + " Contact the store maintainer if you need support for a new query type."
        ));
    }

    private Properties streamsConfiguration(final TestInfo testInfo) {
        final String safeTestName = IntegrationTestUtils.safeUniqueTestName(getClass(), testInfo);

        final Properties config = new Properties();
        config.put(StreamsConfig.TOPOLOGY_OPTIMIZATION_CONFIG, StreamsConfig.OPTIMIZE);
        config.put(StreamsConfig.APPLICATION_ID_CONFIG, "app-" + safeTestName);
        config.put(StreamsConfig.APPLICATION_SERVER_CONFIG, "localhost:" + (++port));
        config.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, CLUSTER.bootstrapServers());
        config.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getPath());
        config.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.Integer().getClass());
        config.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.Integer().getClass());
        config.put(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG, 1);
        config.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 100);
        config.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, 200);
        config.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 1000);
        config.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 100L);
        config.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, 1);
        return config;
    }
}


text:
require File.expand_path('../application', __FILE__)

# Initialize the rails application
ExceptionHandlerTestApp::Application.initialize!


text:
Searching
=========

.. automodule:: algorithms.searching.binary_search
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: algorithms.searching.bmh_search
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: algorithms.searching.depth_first_search
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: algorithms.searching.kmp_search
    :members:
    :undoc-members:
    :show-inheritance:

.. automodule:: algorithms.searching.rabinkarp_search
    :members:
    :undoc-members:
    :show-inheritance:


text: parent pom for shedhack components.


text:
package ua.org.gdg.devfest.droidconsched.io.model;

import ua.org.gdg.devfest.droidconsched.io.ServerResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

/**
 * SessionResponse as modelled in the Google Developers API.
 *
 * This is an implementation which replaces the generated version which shipped with IOsched and
 * makes the code human more human readable and removed the dependence on additional Google libraries.
 */
public class SessionResponse extends ServerResponse {

    private String description;

    private Double endTimestamp;

    private String iconUrl;

    private String id;

    private String location;

    private List<String> presenterIds;

    private Double startTimestamp;

    private String subtype;

    private String title;

    private String webLink;

    private int flags;

    public SessionResponse()
    {
    }

    public String getDescription()
    {
        return this.description;
    }

    public SessionResponse setDescription(String description)
    {
        this.description = description;
        return this;
    }

    public Double getEndTimestamp()
    {
        return this.endTimestamp;
    }

    public SessionResponse setEndTimestamp(Double endTimestamp)
    {
        this.endTimestamp = endTimestamp;
        return this;
    }

    public String getIconUrl()
    {
        return this.iconUrl;
    }

    public SessionResponse setIconUrl(String iconUrl)
    {
        this.iconUrl = iconUrl;
        return this;
    }

    public String getId()
    {
        return this.id;
    }

    public SessionResponse setId(String id)
    {
        this.id = id;
        return this;
    }

    public String getLocation()
    {
        return this.location;
    }

    public SessionResponse setLocation(String location)
    {
        this.location = location;
        return this;
    }

    public List<String> getPresenterIds()
    {
        return this.presenterIds;
    }

    public SessionResponse setPresenterIds(List<String> presenterIds)
    {
        this.presenterIds = presenterIds;
        return this;
    }

    public Double getStartTimestamp()
    {
        return this.startTimestamp;
    }

    public SessionResponse setStartTimestamp(Double startTimestamp)
    {
        this.startTimestamp = startTimestamp;
        return this;
    }

    public String getSubtype()
    {
        return this.subtype;
    }

    public SessionResponse setSubtype(String subtype)
    {
        this.subtype = subtype;
        return this;
    }

    public String getTitle()
    {
        return this.title;
    }

    public SessionResponse setTitle(String title)
    {
        this.title = title;
        return this;
    }

    public String getWebLink() {
        return webLink;
    }

    public void setWebLink(String webLink) {
        this.webLink = webLink;
    }

    public int getFlags() {
        return flags;
    }

    public void setFlags(Integer flags) {
        this.flags = flags;
    }

    @Override
    protected boolean useClassSpecificSetter(JSONObject jsonObject, final String key)
        throws JSONException {
        if(!"presenterIds".equals(key)) {
            return false;
        }

        JSONArray array = jsonObject.getJSONArray("presenterIds");
        List<String> presenterIdList = new ArrayList<String>(array.length());
        for(int i = 0 ; i < array.length() ; i++) {
            presenterIdList.add(array.getString(i));
        }
        setPresenterIds(presenterIdList);
        return true;
    }
}


text:
from enum import Enum

# Enum for group types in the groups table
class GroupTypes(Enum):
    HOUSE = 'house'
    COMMITTEE = 'committee'  # i.e IHC, BOC, CRC
    ASCIT = 'ascit'  # For all groups that are involved with ascit
    PUBLICATION = 'publication'  # i.e The Tech
    UGCURRENT = 'ugcurrent'  # current student groups i.e ug2020
    UGALUMN = 'ugalumn'  # alumn groups, i.e ug2010


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">MoarRam</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="enter_num">Enter a number</string>
    <string name="add_32">Add 32 bytes</string>
    <string name="free_32">Free 32 bytes</string>
    <string name="add_2m">Add 2M bytes</string>
    <string name="free_2m">Free 2M bytes</string>
    <string name="add_variable">Add 17 or 71 bytes</string>
    <string name="free_variable">Free 17 or 71 bytes</string>
    <string name="_17byte">17 bytes</string>
    <string name="_71byte">71 bytes</string>
</resources>


text:
<dicts>
  <dict owner="2.16.840.1.114059.1.1.6.1.50.1">
    <entry group="0029" element="29" vr="UN" vm="1" name="Private Tag Range">
<definition>Reserves the (0029,29xx) Range</definition>
</entry>
    <entry group="0029" element="20" vr="UN" vm="1" name="Description">
<definition>Environmental Description</definition>
</entry>
    <entry group="0029" element="21" vr="UN" vm="1" name="Orientation">
<definition>Computed Type and Orientation</definition>
</entry>
    <entry group="0029" element="22" vr="UN" vm="1" name="Parameter 1">
<definition>Various Parameters</definition>
</entry>
    <entry group="0029" element="23" vr="UN" vm="1" name="Parameter 2">
<definition>More Parameters</definition>
</entry>
    <entry group="0029" element="24" vr="UN" vm="1" name="Teeth">
<definition>ISO Tooth Descr.</definition>
</entry>
    <entry group="0029" element="25" vr="UN" vm="1" name="Jaw">
<definition>ISO Jaw Descr.</definition>
</entry>
    <entry group="0029" element="26" vr="UN" vm="1" name="Quadrant">
<definition>ISO Quadrant Descr.</definition>
</entry>
    <entry group="0029" element="27" vr="UN" vm="1" name="CRC">
<definition>CRC Check Sum</definition>
</entry>
</dict>
</dicts>


text:
/**
 * Dev time server for front-end
 */
import config = require('../webpack.config');

import path = require('path');
import fs = require('fs');
import express = require('express');
import * as utils from "../common/utils";
import {getPort} from './utils/getPort';

const devtimeDetectionFile = __dirname + '/devtime.txt';

let webpackDevServerPort = 0;
let devTimeProxy: (req: express.Request, res: express.Response, next: Function) => void = null;
const bundleDevTimeProxy = () => {
    if (devTimeProxy) return devTimeProxy;

    /**
     * Provide a proxy server that will pass your requests to webpack if a webpack port is found
     */
    const httpProxy = require('http-proxy');
    const proxyServer = httpProxy.createProxyServer();
    devTimeProxy = function(req: express.Request, res: express.Response, next) {
        if (!webpackDevServerPort) next();

        proxyServer.web(req, res, {
            target: `http://127.0.0.1:${webpackDevServerPort}`
        });
        proxyServer.on('error', (err) => {
            console.log('[WDS] Proxy ERROR', err);
        });
    }

    getPort(8888).then((port) => {

        // console.log('found port', port); // DEBUG

        webpackDevServerPort = port;

        const Webpack = require('webpack');
        const WebpackDevServer = require('webpack-dev-server');
        const notification = '[WDS]'; // Webpack dev server

        /**
         * Update the prod config for dev time ease
         */
        const devConfig = Object.create(config);
        // Makes sure errors in console map to the correct file and line number
        devConfig.devtool = 'eval';
        // Add aditional entry points
        devConfig.entry = [
            // For hot style updates
            require.resolve('webpack/hot/dev-server'),
            // The script refreshing the browser on hot updates
            `${require.resolve('webpack-dev-server/client')}?http://127.0.0.1:${webpackDevServerPort}`,
            // Also keep existing
        ].concat(config.entry);

        // Add the Hot Replacement plugin for hot style updates
        devConfig.plugins.push(new Webpack.HotModuleReplacementPlugin());

        /**
         * Standard webpack bundler stuff
         */
        const compiler = Webpack(devConfig);
        compiler.plugin('compile', function() {
            console.log(`${notification} Bundling ..... `)
        });
        compiler.plugin('done', function(result) {
            console.log(`${notification} Bundled in ${(result.endTime - result.startTime)} ms!`);
        });

        /**
         * Wrap up the bundler in a dev server
         */
        const bundler = new WebpackDevServer(compiler, {

            // We need to tell Webpack to serve our bundled application
            // from the build path. When proxying
            publicPath: '/build/',

            // Configure hot replacement
            hot: true,

            // The rest is terminal configurations
            quiet: true,
            noInfo: true,
            stats: {
                colors: true
            }
        });
        /** Listen on all local address. If we don't then our `getPort` breaks on a mac */
        bundler.listen(webpackDevServerPort, '0.0.0.0', function() {
            console.log(`${notification} Server listening on port: ${webpackDevServerPort}`);
        });

    });

    return devTimeProxy;
}

function bundleDeploy() {
    // build
    const Webpack = require('webpack');
    const compiler = Webpack(config);
    compiler.run((err, stats) => {
        if (err) {
            console.error('Failed to refresh bundle', err);
        }
        else {
            console.log('Refreshed bundle');
        }
    });
}

function addDevHeaders(res: express.Response) {
    res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
    res.setHeader('Pragma', 'no-cache');
    res.setHeader('Expires', '0');
}

export function setup(app: express.Express) {

    /**
     * We always refresh the build bundle if it isn't there.
     * This is to help *new repo clones* . NPM installs get this file by default.
     */
    const outFile = path.join(config.output.path, config.output.filename);
    if (!fs.existsSync(outFile)) {
        bundleDeploy();
    }

    /**
     * Check for devtime
     */
    let devTime = fs.existsSync(devtimeDetectionFile);
    if (devTime){
        // if started with dev mode start the bundling process immediately
        bundleDevTimeProxy();
    }

    /**
     * Proxies to dev server if devtime
     */
    app.all('/build/*', function(req, res, next) {
        if (devTime) {
            bundleDevTimeProxy()(req, res, next);
        }
        else {
            next();
        }
    });

    /**
     * Disables caching if devtime
     */
    app.use('/', function(req, res, next) {
        if (devTime) {
            addDevHeaders(res);
        }
        next();
    });

    /**
     * Dev time vs. prod time toggling
     */
    app.use('/dev', (req, res, next) => {
        addDevHeaders(res);
        devTime = true;
        fs.writeFileSync(devtimeDetectionFile, 'If this file exists the server will start in dev mode');
        res.send('Hot Reload setup!')
    });
    app.use('/prod', (req, res, next) => {
        bundleDeploy();
        addDevHeaders(res);
        if (devTime) {
            devTime = false;
            fs.unlinkSync(devtimeDetectionFile);
        }
        res.send('Using static bundled files')
    });
}


text:
import { SourceType } from 'coffee-lex';

import notNull from '../../../utils/notNull';
import ReturnPatcher from './ReturnPatcher';

export default class YieldReturnPatcher extends ReturnPatcher {
  initialize(): void {
    this.yields();
    super.initialize();
  }

  patchAsStatement(): void {
    let yieldTokenIndex = this.contentStartTokenIndex;
    let returnTokenIndex = notNull(yieldTokenIndex.next());
    let yieldToken = notNull(this.sourceTokenAtIndex(yieldTokenIndex));
    let returnToken = notNull(this.sourceTokenAtIndex(returnTokenIndex));
    if (yieldToken.type !== SourceType.YIELD || returnToken.type !== SourceType.RETURN) {
      throw this.error('Unexpected token types for `yield return`.');
    }
    this.remove(yieldToken.start, returnToken.start);
    super.patchAsStatement();
  }
}


text:
package org.anddev.andengine.util;

import org.anddev.andengine.util.constants.*;
import android.content.*;

public class SimplePreferences implements Constants
{
    private static SharedPreferences$Editor EDITORINSTANCE;
    private static SharedPreferences INSTANCE;
    private static final String PREFERENCES_NAME;

    static {
        PREFERENCES_NAME = null;
    }

    public static int getAccessCount(final Context context, final String s) {
        return getInstance(context).getInt(s, 0);
    }

    public static SharedPreferences$Editor getEditorInstance(final Context context) {
        if (SimplePreferences.EDITORINSTANCE == null) {
            SimplePreferences.EDITORINSTANCE = getInstance(context).edit();
        }
        return SimplePreferences.EDITORINSTANCE;
    }

    public static SharedPreferences getInstance(final Context context) {
        if (SimplePreferences.INSTANCE == null) {
            SimplePreferences.INSTANCE = context.getSharedPreferences(SimplePreferences.PREFERENCES_NAME, 0);
        }
        return SimplePreferences.INSTANCE;
    }

    public static int incrementAccessCount(final Context context, final String s) {
        return incrementAccessCount(context, s, 1);
    }

    public static int incrementAccessCount(final Context context, final String s, final int n) {
        final SharedPreferences instance = getInstance(context);
        final int n2 = n + instance.getInt(s, 0);
        instance.edit().putInt(s, n2).commit();
        return n2;
    }
}


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

package edu.wpi.first.wpilibj.templates;

import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SimpleRobot;
import edu.wpi.first.wpilibj.Victor;

public class RobotTemplate extends SimpleRobot {

    Joystick j1;
    Victor left;
    Victor right;
    RobotDrive dr;

    public void robotInit(){

        Joystick j1 = new Joystick(1);
        Victor left = new Victor(1);
        Victor right = new Victor(2);
        dr = new RobotDrive(right,left);
    }

    public void disabled(){
        System.out.println("Disabled");
    }

    public void autonomous() {
        System.out.println("Autonomus");
    }

    public void operatorControl() {
        System.out.println("Operator Control");
        while(isEnabled()){
            dr.arcadeDrive(j1);
        }
    }

    public void test() {
        System.out.println("Test mode???");
    }
}


text:
Js Factory
==========

The **Js** factory provides a collection of event objects which allow the introduction of client scripting with **JavaScript**. These objects are not to be confused with the **Js** helper available in *CakePHP*, for this check out the [Cake](https://github.com/jameswatts/cake-factory) factory.

To use the **Js** factory in a View include it in the *$factories* property of the CTK class, for example:

```php
public $factories = array('Ctk.Js');
```

Once the factory is available you can access the event objects it provides. To bind an event object from the factory simply call the factory, and then the desired event object, for example:

```php
$button->bind('click', $this->Js->Alert(array(
	'text' => __('Click me!')
)));
```

As shown in the example, an array can be passed to the object with parameters to configure the object's template.

Some event objects expose subsequent APIs, allowing additional configuration, for example:

```php
$button->bind('click', $this->Js->Element(array('node' => $div))->toggle()); // Element wraps the node, then toggle() appends the client code
```

The event objects available in the **Js** factory are the following:

* [Ajax](Js/Ajax.md) - Object interface to the *XmlRpcRequest* object.
* [Alert](Js/Alert.md) - Object representing alert dialogs.
* [Callback](Js/Callback.md) - Object for wrapping client code as a callback.
* [Code](Js/Code.md) - Object for wrapping raw client code.
* [Confirm](Js/Confirm.md) - Object representing confirm dialogs.
* [Cookie](Js/Cookie.md) - Object interface to browser *cookies*.
* [Document](Js/Document.md) - Object interface to the *document* object.
* [Element](Js/Element.md) - Object interface to *DOM* elements.
* [Event](Js/Event.md) - Base object for all *JavaScript* events.
* [History](Js/History.md) - Object interface to the *history* object.
* [Json](Js/Json.md) - Object representing *JSON* data.
* [Listener](Js/Listener.md) - Object representing an event listener.
* [Location](Js/Location.md) - Object interface to the *location* object.
* [Navigator](Js/Navigator.md) - Object interface to the *navigator* object.
* [Prompt](Js/Prompt.md) - Object representing prompt dialogs.
* [Redirect](Js/Redirect.md) - Object representing alert dialogs.
* [Window](Js/Window.md) - Object interface to the *window* object.

The **Js** factory provides a layout specific for *JavaScript*, which can be set from the *$layout* property of the CTK class, for example:

```php
public $layout = 'Ctk.Js/default';
```


text:
package car.domain.inventory;

import java.util.Collection;
import java.util.Map;

import car.infrastructure.exception.CarException;

public interface InVentoryFacade {

	public void createDemand(String registerId, String vehicleNumber,
			Map<String, Integer> demandParts);

	public PartSpecVO obtainPartSpec(String number);

	public void out(String registerId, String vehicleNumber,
			Map<String, Integer> demandParts, Collection<String> codes)
			throws CarException;

}


text:
<?php

namespace App;

use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\RouteCollectionBuilder;

class Kernel extends BaseKernel
{
    use MicroKernelTrait;

    const CONFIG_EXTS = '.{php,xml,yaml,yml}';

    public function registerBundles()
    {
        $contents = require $this->getProjectDir() . '/config/bundles.php';
        foreach ($contents as $class => $envs) {
            if ($envs[$this->environment] ?? $envs['all'] ?? false) {
                yield new $class();
            }
        }
    }

    protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader)
    {
        $container->addResource(new FileResource($this->getProjectDir() . '/config/bundles.php'));
        $container->setParameter('container.dumper.inline_class_loader', true);
        $confDir = $this->getProjectDir() . '/config';

        $loader->load($confDir . '/{packages}/*' . self::CONFIG_EXTS, 'glob');
        $loader->load($confDir . '/{packages}/' . $this->environment . '/**/*' . self::CONFIG_EXTS, 'glob');
        $loader->load($confDir . '/{services}' . self::CONFIG_EXTS, 'glob');
        $loader->load($confDir . '/{services}_' . $this->environment . self::CONFIG_EXTS, 'glob');
    }

    protected function configureRoutes(RouteCollectionBuilder $routes)
    {
        $confDir = $this->getProjectDir() . '/config';

        $routes->import($confDir . '/{routes}/*' . self::CONFIG_EXTS, '/', 'glob');
        $routes->import($confDir . '/{routes}/' . $this->environment . '/**/*' . self::CONFIG_EXTS, '/', 'glob');
        $routes->import($confDir . '/{routes}' . self::CONFIG_EXTS, '/', 'glob');
    }
}


text:
package aiplatform;

// [START aiplatform_predict_text_sentiment_analysis_sample]

import com.google.cloud.aiplatform.v1.EndpointName;
import com.google.cloud.aiplatform.v1.PredictResponse;
import com.google.cloud.aiplatform.v1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
import com.google.protobuf.Value;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PredictTextSentimentAnalysisSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "YOUR_PROJECT_ID";
    String content = "YOUR_TEXT_CONTENT";
    String endpointId = "YOUR_ENDPOINT_ID";

    predictTextSentimentAnalysis(project, content, endpointId);
  }

  static void predictTextSentimentAnalysis(String project, String content, String endpointId)
      throws IOException {
    PredictionServiceSettings predictionServiceSettings =
        PredictionServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PredictionServiceClient predictionServiceClient =
        PredictionServiceClient.create(predictionServiceSettings)) {
      String location = "us-central1";
      String jsonString = "{\"content\": \"" + content + "\"}";

      EndpointName endpointName = EndpointName.of(project, location, endpointId);

      Value parameter = Value.newBuilder().setNumberValue(0).setNumberValue(5).build();
      Value.Builder instance = Value.newBuilder();
      JsonFormat.parser().merge(jsonString, instance);

      List<Value> instances = new ArrayList<>();
      instances.add(instance.build());

      PredictResponse predictResponse =
          predictionServiceClient.predict(endpointName, instances, parameter);
      System.out.println("Predict Text Sentiment Analysis Response");
      System.out.format("\tDeployed Model Id: %s\n", predictResponse.getDeployedModelId());

      System.out.println("Predictions");
      for (Value prediction : predictResponse.getPredictionsList()) {
        System.out.format("\tPrediction: %s\n", prediction);
      }
    }
  }
}
// [END aiplatform_predict_text_sentiment_analysis_sample]


text:
'use strict';

// MODULES //

var tape = require( 'tape' );
var proxyquire = require( 'proxyquire' );
var FLOAT_WORD_ORDER = require( './../lib' );

// TESTS //

tape( 'main export is a string', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof FLOAT_WORD_ORDER, 'string', 'main export is a string' );
	t.end();
});

tape( 'if the platform is little-endian, the value should be `little-endian`', function test( t ) {
	var FLOAT_WORD_ORDER;

	FLOAT_WORD_ORDER = proxyquire( './../lib/main.js', {
		'@stdlib/os/byte-order': 'little-endian'
	});
	t.equal( FLOAT_WORD_ORDER, 'little-endian', 'returns expected value' );
	t.end();
});

tape( 'if the platform is big-endian, the value should be `big-endian`', function test( t ) {
	var FLOAT_WORD_ORDER;

	FLOAT_WORD_ORDER = proxyquire( './../lib/main.js', {
		'@stdlib/os/byte-order': 'big-endian'
	});
	t.equal( FLOAT_WORD_ORDER, 'big-endian', 'returns expected value' );
	t.end();
});

tape( 'if the platform is neither little-endian nor big-endian, the value should be `unknown`', function test( t ) {
	var FLOAT_WORD_ORDER;

	FLOAT_WORD_ORDER = proxyquire( './../lib/main.js', {
		'@stdlib/os/byte-order': 'beep-boop'
	});
	t.equal( FLOAT_WORD_ORDER, 'unknown', 'returns expected value' );
	t.end();
});