<commit_before>
#include "RigidBodyManipulator.h"
#include <stdexcept>

using namespace std;

const int defaultRobotNum[1] = {0};
const set<int> RigidBody::defaultRobotNumSet(defaultRobotNum,defaultRobotNum+1);

RigidBody::RigidBody(void) :
    parent(nullptr),
    S(TWIST_SIZE, 0),
    dSdqi(0, 0),
    J(TWIST_SIZE, 0),
    dJdq(0, 0),
    qdot_to_v(0, 0),
    dqdot_to_v_dqi(0, 0),
    dqdot_to_v_dq(0, 0),
    v_to_qdot(0, 0),
    dv_to_qdot_dqi(0, 0),
    dv_to_qdot_dq(0, 0),
    T_new(Isometry3d::Identity()),
    dTdq_new(HOMOGENEOUS_TRANSFORM_SIZE, 0),
    twist(TWIST_SIZE, 1),
    dtwistdq(TWIST_SIZE, 0),
    SdotV(TWIST_SIZE, 1),
    dSdotVdqi(TWIST_SIZE, 0),
    dSdotVdvi(TWIST_SIZE, 0),
    JdotV(TWIST_SIZE, 1),
    dJdotVdq(TWIST_SIZE, 0),
    dJdotVdv(TWIST_SIZE, 0),
    collision_filter_group(DrakeCollision::DEFAULT_GROUP),
    collision_filter_mask(DrakeCollision::ALL_MASK)
{
  robotnum = 0;
	position_num_start = 0;
	velocity_num_start = 0;
	mass = 0.0;
	floating = 0;
	com << Vector3d::Zero(), 1;
	I << Matrix<double, TWIST_SIZE, TWIST_SIZE>::Zero();
	T = Matrix4d::Identity();
	Tdot = Matrix4d::Zero();
	Ttree = Matrix4d::Identity();
	T_body_to_joint = Matrix4d::Identity();
}

void RigidBody::setN(int nq, int nv) {
  dTdq = MatrixXd::Zero(3*nq,4);
  dTdqdot = MatrixXd::Zero(3*nq,4);
  ddTdqdq = MatrixXd::Zero(3*nq*nq,4);

  dJdq.resize(J.size(), nq);
  dTdq_new.resize(T.size(), nq);
  dtwistdq.resize(twist.size(), nq);

  dJdotVdq.resize(TWIST_SIZE, nq);
  dJdotVdv.resize(TWIST_SIZE, nv);

  dqdot_to_v_dq.resize(Eigen::NoChange, nq);
  dv_to_qdot_dq.resize(Eigen::NoChange, nq);
}

void RigidBody::setJoint(std::unique_ptr<DrakeJoint> new_joint)
{
  this->joint = move(new_joint);

  S.resize(TWIST_SIZE, joint->getNumVelocities());
  dSdqi.resize(S.size(), joint->getNumPositions());
  J.resize(TWIST_SIZE, joint->getNumVelocities());
  qdot_to_v.resize(joint->getNumVelocities(), joint->getNumPositions()),
  dqdot_to_v_dqi.resize(qdot_to_v.size(), joint->getNumPositions()),
  dqdot_to_v_dq.resize(qdot_to_v.size(), Eigen::NoChange);
  v_to_qdot.resize(joint->getNumPositions(), joint->getNumVelocities()),
  dv_to_qdot_dqi.resize(v_to_qdot.size(), joint->getNumPositions());
  dv_to_qdot_dq.resize(v_to_qdot.size(), Eigen::NoChange);
  dSdotVdqi.resize(TWIST_SIZE, joint->getNumPositions());
  dSdotVdvi.resize(TWIST_SIZE, joint->getNumVelocities());
}

const DrakeJoint& RigidBody::getJoint() const
{
  if (joint) {
    return (*joint);
  }
  else {
    throw runtime_error("Joint is not initialized");
  }
}

void RigidBody::computeAncestorDOFs(RigidBodyManipulator* model)
{
  if (position_num_start>=0) {
    int i,j;
    if (parent!=nullptr) {
      ancestor_dofs = parent->ancestor_dofs;
      ddTdqdq_nonzero_rows = parent->ddTdqdq_nonzero_rows;
    }

    if (floating==1) {
    	for (j=0; j<6; j++) {
    		ancestor_dofs.insert(position_num_start+j);
    		for (i=0; i<3*model->NB; i++) {
    			ddTdqdq_nonzero_rows.insert(i*model->NB + position_num_start + j);
    			ddTdqdq_nonzero_rows.insert(3*model->NB*position_num_start + i + j);
    		}
    	}
    } else if (floating==2) {
    	for (j=0; j<7; j++) {
    		ancestor_dofs.insert(position_num_start+j);
    		for (i=0; i<3*model->NB; i++) {
    			ddTdqdq_nonzero_rows.insert(i*model->NB + position_num_start + j);
    			ddTdqdq_nonzero_rows.insert(3*model->NB*position_num_start + i + j);
    		}
    	}
    }
    else {
    	ancestor_dofs.insert(position_num_start);
    	for (i=0; i<3*model->NB; i++) {
    		ddTdqdq_nonzero_rows.insert(i*model->NB + position_num_start);
    		ddTdqdq_nonzero_rows.insert(3*model->NB*position_num_start + i);
    	}
    }

    // compute matrix blocks
    IndexRange ind;  ind.start=-1; ind.length=0;
    for (i=0; i<3*model->NB*model->NB; i++) {
      if (ddTdqdq_nonzero_rows.find(i)!=ddTdqdq_nonzero_rows.end()) {
        if (ind.start<0) ind.start=i;
      } else {
        if (ind.start>=0) {
          ind.length = i-ind.start;
          ddTdqdq_nonzero_rows_grouped.insert(ind);
          ind.start = -1;
        }
      }
    }
    if (ind.start>=0) {
      ind.length = i-ind.start;
      ddTdqdq_nonzero_rows_grouped.insert(ind);
    }
  }
}

bool RigidBody::hasParent() const {
  return parent !=nullptr;
}

void RigidBody::setCollisionFilter(const DrakeCollision::bitmask& group,
                                   const DrakeCollision::bitmask& mask)
{
  setCollisionFilterGroup(group);
  setCollisionFilterMask(mask);
}

bool RigidBody::appendCollisionElementIdsFromThisBody(const string& group_name, vector<DrakeCollision::ElementId>& ids) const
{
  auto group_ids_iter = collision_element_groups.find(group_name);
  if (group_ids_iter != collision_element_groups.end()) {
    ids.reserve(ids.size() + distance(group_ids_iter->second.begin(), group_ids_iter->second.end()));
    ids.insert(ids.end(), group_ids_iter->second.begin(), group_ids_iter->second.end());
    return true;
  } else {
    return false;
  }
}

bool RigidBody::appendCollisionElementIdsFromThisBody(vector<DrakeCollision::ElementId>& ids) const
{
  ids.reserve(ids.size() + distance(collision_element_ids.begin(), collision_element_ids.end()));
  ids.insert(ids.end(), collision_element_ids.begin(), collision_element_ids.end());
  return true;
}

RigidBody::CollisionElement::
CollisionElement(std::unique_ptr<DrakeCollision::Geometry> geometry,
                 const Matrix4d& T_element_to_link, std::shared_ptr<RigidBody> body)
  : DrakeCollision::Element(move(geometry), T_element_to_link), body(body) {}

const std::shared_ptr<RigidBody>& RigidBody::CollisionElement:: getBody() const
{
  return this->body;
}

bool RigidBody::CollisionElement::collidesWith( const DrakeCollision::Element* other) const
{
  //DEBUG
  //cout << "RigidBody::CollisionElement::collidesWith: START" << endl;
  //END_DEBUG
  auto other_rb = dynamic_cast<const RigidBody::CollisionElement*>(other);
  bool collides = true;
  if (other_rb != nullptr) {
    collides = this->body->collidesWith(other_rb->body);
    //DEBUG
    //cout << "RigidBody::CollisionElement::collidesWith:" << endl;
    //cout << "  " << this->body->linkname << " & " << other_rb->body->linkname;
    //cout << ": collides = " << collides << endl;
    //END_DEBUG
  }
  return collides;
}

ostream &operator<<( ostream &out, const RigidBody &b)
{
	out << "RigidBody(" << b.linkname << "," << b.jointname << ")";
	return out;
}
<commit_msg>Replace distance with size when appending entire vector<commit_after>
#include "RigidBodyManipulator.h"
#include <stdexcept>

using namespace std;

const int defaultRobotNum[1] = {0};
const set<int> RigidBody::defaultRobotNumSet(defaultRobotNum,defaultRobotNum+1);

RigidBody::RigidBody(void) :
    parent(nullptr),
    S(TWIST_SIZE, 0),
    dSdqi(0, 0),
    J(TWIST_SIZE, 0),
    dJdq(0, 0),
    qdot_to_v(0, 0),
    dqdot_to_v_dqi(0, 0),
    dqdot_to_v_dq(0, 0),
    v_to_qdot(0, 0),
    dv_to_qdot_dqi(0, 0),
    dv_to_qdot_dq(0, 0),
    T_new(Isometry3d::Identity()),
    dTdq_new(HOMOGENEOUS_TRANSFORM_SIZE, 0),
    twist(TWIST_SIZE, 1),
    dtwistdq(TWIST_SIZE, 0),
    SdotV(TWIST_SIZE, 1),
    dSdotVdqi(TWIST_SIZE, 0),
    dSdotVdvi(TWIST_SIZE, 0),
    JdotV(TWIST_SIZE, 1),
    dJdotVdq(TWIST_SIZE, 0),
    dJdotVdv(TWIST_SIZE, 0),
    collision_filter_group(DrakeCollision::DEFAULT_GROUP),
    collision_filter_mask(DrakeCollision::ALL_MASK)
{
  robotnum = 0;
	position_num_start = 0;
	velocity_num_start = 0;
	mass = 0.0;
	floating = 0;
	com << Vector3d::Zero(), 1;
	I << Matrix<double, TWIST_SIZE, TWIST_SIZE>::Zero();
	T = Matrix4d::Identity();
	Tdot = Matrix4d::Zero();
	Ttree = Matrix4d::Identity();
	T_body_to_joint = Matrix4d::Identity();
}

void RigidBody::setN(int nq, int nv) {
  dTdq = MatrixXd::Zero(3*nq,4);
  dTdqdot = MatrixXd::Zero(3*nq,4);
  ddTdqdq = MatrixXd::Zero(3*nq*nq,4);

  dJdq.resize(J.size(), nq);
  dTdq_new.resize(T.size(), nq);
  dtwistdq.resize(twist.size(), nq);

  dJdotVdq.resize(TWIST_SIZE, nq);
  dJdotVdv.resize(TWIST_SIZE, nv);

  dqdot_to_v_dq.resize(Eigen::NoChange, nq);
  dv_to_qdot_dq.resize(Eigen::NoChange, nq);
}

void RigidBody::setJoint(std::unique_ptr<DrakeJoint> new_joint)
{
  this->joint = move(new_joint);

  S.resize(TWIST_SIZE, joint->getNumVelocities());
  dSdqi.resize(S.size(), joint->getNumPositions());
  J.resize(TWIST_SIZE, joint->getNumVelocities());
  qdot_to_v.resize(joint->getNumVelocities(), joint->getNumPositions()),
  dqdot_to_v_dqi.resize(qdot_to_v.size(), joint->getNumPositions()),
  dqdot_to_v_dq.resize(qdot_to_v.size(), Eigen::NoChange);
  v_to_qdot.resize(joint->getNumPositions(), joint->getNumVelocities()),
  dv_to_qdot_dqi.resize(v_to_qdot.size(), joint->getNumPositions());
  dv_to_qdot_dq.resize(v_to_qdot.size(), Eigen::NoChange);
  dSdotVdqi.resize(TWIST_SIZE, joint->getNumPositions());
  dSdotVdvi.resize(TWIST_SIZE, joint->getNumVelocities());
}

const DrakeJoint& RigidBody::getJoint() const
{
  if (joint) {
    return (*joint);
  }
  else {
    throw runtime_error("Joint is not initialized");
  }
}

void RigidBody::computeAncestorDOFs(RigidBodyManipulator* model)
{
  if (position_num_start>=0) {
    int i,j;
    if (parent!=nullptr) {
      ancestor_dofs = parent->ancestor_dofs;
      ddTdqdq_nonzero_rows = parent->ddTdqdq_nonzero_rows;
    }

    if (floating==1) {
    	for (j=0; j<6; j++) {
    		ancestor_dofs.insert(position_num_start+j);
    		for (i=0; i<3*model->NB; i++) {
    			ddTdqdq_nonzero_rows.insert(i*model->NB + position_num_start + j);
    			ddTdqdq_nonzero_rows.insert(3*model->NB*position_num_start + i + j);
    		}
    	}
    } else if (floating==2) {
    	for (j=0; j<7; j++) {
    		ancestor_dofs.insert(position_num_start+j);
    		for (i=0; i<3*model->NB; i++) {
    			ddTdqdq_nonzero_rows.insert(i*model->NB + position_num_start + j);
    			ddTdqdq_nonzero_rows.insert(3*model->NB*position_num_start + i + j);
    		}
    	}
    }
    else {
    	ancestor_dofs.insert(position_num_start);
    	for (i=0; i<3*model->NB; i++) {
    		ddTdqdq_nonzero_rows.insert(i*model->NB + position_num_start);
    		ddTdqdq_nonzero_rows.insert(3*model->NB*position_num_start + i);
    	}
    }

    // compute matrix blocks
    IndexRange ind;  ind.start=-1; ind.length=0;
    for (i=0; i<3*model->NB*model->NB; i++) {
      if (ddTdqdq_nonzero_rows.find(i)!=ddTdqdq_nonzero_rows.end()) {
        if (ind.start<0) ind.start=i;
      } else {
        if (ind.start>=0) {
          ind.length = i-ind.start;
          ddTdqdq_nonzero_rows_grouped.insert(ind);
          ind.start = -1;
        }
      }
    }
    if (ind.start>=0) {
      ind.length = i-ind.start;
      ddTdqdq_nonzero_rows_grouped.insert(ind);
    }
  }
}

bool RigidBody::hasParent() const {
  return parent !=nullptr;
}

void RigidBody::setCollisionFilter(const DrakeCollision::bitmask& group,
                                   const DrakeCollision::bitmask& mask)
{
  setCollisionFilterGroup(group);
  setCollisionFilterMask(mask);
}

bool RigidBody::appendCollisionElementIdsFromThisBody(const string& group_name, vector<DrakeCollision::ElementId>& ids) const
{
  auto group_ids_iter = collision_element_groups.find(group_name);
  if (group_ids_iter != collision_element_groups.end()) {
    ids.reserve(ids.size() + distance(group_ids_iter->second.begin(), group_ids_iter->second.end()));
    ids.insert(ids.end(), group_ids_iter->second.begin(), group_ids_iter->second.end());
    return true;
  } else {
    return false;
  }
}

bool RigidBody::appendCollisionElementIdsFromThisBody(vector<DrakeCollision::ElementId>& ids) const
{
  ids.reserve(ids.size() + collision_element_ids.size());
  ids.insert(ids.end(), collision_element_ids.begin(), collision_element_ids.end());
  return true;
}

RigidBody::CollisionElement::
CollisionElement(std::unique_ptr<DrakeCollision::Geometry> geometry,
                 const Matrix4d& T_element_to_link, std::shared_ptr<RigidBody> body)
  : DrakeCollision::Element(move(geometry), T_element_to_link), body(body) {}

const std::shared_ptr<RigidBody>& RigidBody::CollisionElement:: getBody() const
{
  return this->body;
}

bool RigidBody::CollisionElement::collidesWith( const DrakeCollision::Element* other) const
{
  //DEBUG
  //cout << "RigidBody::CollisionElement::collidesWith: START" << endl;
  //END_DEBUG
  auto other_rb = dynamic_cast<const RigidBody::CollisionElement*>(other);
  bool collides = true;
  if (other_rb != nullptr) {
    collides = this->body->collidesWith(other_rb->body);
    //DEBUG
    //cout << "RigidBody::CollisionElement::collidesWith:" << endl;
    //cout << "  " << this->body->linkname << " & " << other_rb->body->linkname;
    //cout << ": collides = " << collides << endl;
    //END_DEBUG
  }
  return collides;
}

ostream &operator<<( ostream &out, const RigidBody &b)
{
	out << "RigidBody(" << b.linkname << "," << b.jointname << ")";
	return out;
}
<|endoftext|>


<commit_before>// $Id$

/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
***********************************************************************/

#ifdef WIN32
#include <windows.h>
#else
#include <sys/times.h>
#include <sys/resource.h>
#endif

#include <cstring>
#include <cctype>
#include <algorithm>
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include "TypeDef.h"
#include "Util.h"
#include "Timer.h"
#include "util/exception.hh"
#include "util/file.hh"

using namespace std;

namespace Moses
{

//global variable
Timer g_timer;

string GetTempFolder()
{
#ifdef _WIN32
  char *tmpPath = getenv("TMP");
  string str(tmpPath);
  if (str.substr(str.size() - 1, 1) != "\\")
    str += "\\";
  return str;
#else
  return "/tmp/";
#endif
}

const std::string ToLower(const std::string& str)
{
  std::string lc(str);
  std::transform(lc.begin(), lc.end(), lc.begin(), (int(*)(int))std::tolower);
  return lc;
}

class BoolValueException : public util::Exception {};

template<>
bool Scan<bool>(const std::string &input)
{
  std::string lc = ToLower(input);
  if (lc == "yes" || lc == "y" || lc == "true" || lc == "1")
    return true;
  if (lc == "no" || lc == "n" || lc =="false" || lc == "0")
    return false;
  UTIL_THROW(BoolValueException, "Could not interpret " << input << " as a boolean.  After lowercasing, valid values are yes, y, true, 1, no, n, false, and 0.");
}

bool FileExists(const std::string& filePath)
{
  ifstream ifs(filePath.c_str());
  return !ifs.fail();
}

const std::string Trim(const std::string& str, const std::string dropChars)
{
  std::string res = str;
  res.erase(str.find_last_not_of(dropChars)+1);
  return res.erase(0, res.find_first_not_of(dropChars));
}

void ResetUserTime()
{
  g_timer.start();
};

void PrintUserTime(const std::string &message)
{
  g_timer.check(message.c_str());
}

double GetUserTime()
{
  return g_timer.get_elapsed_time();
}

std::vector< std::map<std::string, std::string> > ProcessAndStripDLT(std::string &line)
{
  std::vector< std::map<std::string, std::string> > meta;
  std::string lline = ToLower(line);
  bool check_dlt = true;

 std::cerr << "GLOBAL START" << endl;
  while (check_dlt) {
    size_t start = lline.find("<dlt");
    if (start == std::string::npos) {
      //no more dlt tags
      check_dlt = false;
      continue;
    }
    size_t close = lline.find("/>");
    if (close == std::string::npos) {
      // error: dlt tag is not ended
      check_dlt = false;
      continue;
    }
    std::string dlt = Trim(lline.substr(start+4, close-start-4));
//    std::cerr << "dlt:|" << dlt << "|" << endl;
    line.erase(start,close-start+2);
    lline.erase(start,close-start+2);

    if (dlt != ""){

    std::map<std::string, std::string> tmp_meta;
    for (size_t i = 1; i < dlt.size(); i++) {
      if (dlt[i] == '=') {
        std::string label = dlt.substr(0, i);
        std::string val = dlt.substr(i+1);
//        std::cerr << "label:|" << label << "|" << endl;
//        std::cerr << "val:|" << val << "|" << endl;
        if (val[0] == '"') {
          val = val.substr(1);
          // it admits any double quotation mark in the value of the attribute
          // it assumes that just one attribute is present in the tag,
          // it assumes that the value starts and ends with double quotation mark
          size_t close = val.rfind('"');
          if (close == std::string::npos) {
            TRACE_ERR("SGML parse error: missing \"\n");
            dlt = "";
            i = 0;
          } else {
            dlt = val.substr(close+1);
            val = val.substr(0, close);
            i = 0;
          }
        } else {
          size_t close = val.find(' ');
          if (close == std::string::npos) {
            dlt = "";
            i = 0;
          } else {
            dlt = val.substr(close+1);
            val = val.substr(0, close);
          }
        }
        label = Trim(label);
        dlt = Trim(dlt);

        tmp_meta[label] = val;
      }
    }

    meta.push_back(tmp_meta);
   }
  }
  std::cerr << "GLOBAL END" << endl;
  return meta;
}

std::map<std::string, std::string> ProcessAndStripSGML(std::string &line)
{
  std::map<std::string, std::string> meta;
  std::string lline = ToLower(line);
  if (lline.find("<seg")!=0) return meta;
  size_t close = lline.find(">");
  if (close == std::string::npos) return meta; // error
  size_t end = lline.find("</seg>");
  std::string seg = Trim(lline.substr(4, close-4));
  std::string text = line.substr(close+1, end - close - 1);
  for (size_t i = 1; i < seg.size(); i++) {
    if (seg[i] == '=' && seg[i-1] == ' ') {
      std::string less = seg.substr(0, i-1) + seg.substr(i);
      seg = less;
      i = 0;
      continue;
    }
    if (seg[i] == '=' && seg[i+1] == ' ') {
      std::string less = seg.substr(0, i+1);
      if (i+2 < seg.size()) less += seg.substr(i+2);
      seg = less;
      i = 0;
      continue;
    }
  }
  line = Trim(text);
  if (seg == "") return meta;
  for (size_t i = 1; i < seg.size(); i++) {
    if (seg[i] == '=') {
      std::string label = seg.substr(0, i);
      std::string val = seg.substr(i+1);
      if (val[0] == '"') {
        val = val.substr(1);
        size_t close = val.find('"');
        if (close == std::string::npos) {
          TRACE_ERR("SGML parse error: missing \"\n");
          seg = "";
          i = 0;
        } else {
          seg = val.substr(close+1);
          val = val.substr(0, close);
          i = 0;
        }
      } else {
        size_t close = val.find(' ');
        if (close == std::string::npos) {
          seg = "";
          i = 0;
        } else {
          seg = val.substr(close+1);
          val = val.substr(0, close);
        }
      }
      label = Trim(label);
      seg = Trim(seg);
      meta[label] = val;
    }
  }
  return meta;
}

std::string PassthroughSGML(std::string &line, const std::string tagName, const std::string& lbrackStr, const std::string& rbrackStr)
{
  string lbrack = lbrackStr; // = "<";
  string rbrack = rbrackStr; // = ">";

  std::string meta = "";

  std::string lline = ToLower(line);
  size_t open = lline.find(lbrack+tagName);
  //check whether the tag exists; if not return the empty string
  if (open == std::string::npos) return meta;

  size_t close = lline.find(rbrack, open);
  //check whether the tag is closed with '/>'; if not return the empty string
  if (close == std::string::npos) {
    TRACE_ERR("PassthroughSGML error: the <passthrough info/> tag does not end properly\n");
    return meta;
  }
  // extract the tag
  std::string tmp = line.substr(open, close - open + 1);
  meta = line.substr(open, close - open + 1);

  // strip the tag from the line
  line = line.substr(0, open) + line.substr(close + 1, std::string::npos);

  TRACE_ERR("The input contains a <passthrough info/> tag:" << meta << std::endl);

  lline = ToLower(line);
  open = lline.find(lbrack+tagName);
  if (open != std::string::npos) {
    TRACE_ERR("PassthroughSGML error: there are two <passthrough> tags\n");
  }
  return meta;
}

}

<commit_msg>code cleanup<commit_after>// $Id$

/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
***********************************************************************/

#ifdef WIN32
#include <windows.h>
#else
#include <sys/times.h>
#include <sys/resource.h>
#endif

#include <cstring>
#include <cctype>
#include <algorithm>
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include "TypeDef.h"
#include "Util.h"
#include "Timer.h"
#include "util/exception.hh"
#include "util/file.hh"

using namespace std;

namespace Moses
{

//global variable
Timer g_timer;

string GetTempFolder()
{
#ifdef _WIN32
  char *tmpPath = getenv("TMP");
  string str(tmpPath);
  if (str.substr(str.size() - 1, 1) != "\\")
    str += "\\";
  return str;
#else
  return "/tmp/";
#endif
}

const std::string ToLower(const std::string& str)
{
  std::string lc(str);
  std::transform(lc.begin(), lc.end(), lc.begin(), (int(*)(int))std::tolower);
  return lc;
}

class BoolValueException : public util::Exception {};

template<>
bool Scan<bool>(const std::string &input)
{
  std::string lc = ToLower(input);
  if (lc == "yes" || lc == "y" || lc == "true" || lc == "1")
    return true;
  if (lc == "no" || lc == "n" || lc =="false" || lc == "0")
    return false;
  UTIL_THROW(BoolValueException, "Could not interpret " << input << " as a boolean.  After lowercasing, valid values are yes, y, true, 1, no, n, false, and 0.");
}

bool FileExists(const std::string& filePath)
{
  ifstream ifs(filePath.c_str());
  return !ifs.fail();
}

const std::string Trim(const std::string& str, const std::string dropChars)
{
  std::string res = str;
  res.erase(str.find_last_not_of(dropChars)+1);
  return res.erase(0, res.find_first_not_of(dropChars));
}

void ResetUserTime()
{
  g_timer.start();
};

void PrintUserTime(const std::string &message)
{
  g_timer.check(message.c_str());
}

double GetUserTime()
{
  return g_timer.get_elapsed_time();
}

std::vector< std::map<std::string, std::string> > ProcessAndStripDLT(std::string &line)
{
  std::vector< std::map<std::string, std::string> > meta;
  std::string lline = ToLower(line);
  bool check_dlt = true;

 std::cerr << "GLOBAL START" << endl;
  while (check_dlt) {
    size_t start = lline.find("<dlt");
    if (start == std::string::npos) {
      //no more dlt tags
      check_dlt = false;
      continue;
    }
    size_t close = lline.find("/>");
    if (close == std::string::npos) {
      // error: dlt tag is not ended
      check_dlt = false;
      continue;
    }
    //std::string dlt = Trim(lline.substr(start+4, close-start-4));
    std::string dlt = Trim(line.substr(start+4, close-start-4));
    std::cerr << "dlt:|" << dlt << "|" << endl;
    line.erase(start,close-start+2);
    lline.erase(start,close-start+2);

    if (dlt != ""){

    std::map<std::string, std::string> tmp_meta;
    for (size_t i = 1; i < dlt.size(); i++) {
      if (dlt[i] == '=') {
        std::string label = dlt.substr(0, i);
        std::string val = dlt.substr(i+1);
        std::cerr << "label:|" << label << "|" << endl;
        std::cerr << "val:|" << val << "|" << endl;
        if (val[0] == '"') {
          val = val.substr(1);
          // it admits any double quotation mark in the value of the attribute
          // it assumes that just one attribute is present in the tag,
          // it assumes that the value starts and ends with double quotation mark
          size_t close = val.rfind('"');
          if (close == std::string::npos) {
            TRACE_ERR("SGML parse error: missing \"\n");
            dlt = "";
            i = 0;
          } else {
            dlt = val.substr(close+1);
            val = val.substr(0, close);
            i = 0;
          }
        } else {
          size_t close = val.find(' ');
          if (close == std::string::npos) {
            dlt = "";
            i = 0;
          } else {
            dlt = val.substr(close+1);
            val = val.substr(0, close);
          }
        }
        label = Trim(label);
        dlt = Trim(dlt);

        tmp_meta[label] = val;
    	std::cerr << "tmp_meta:|" << tmp_meta[label] << "|" << endl;
      }
    }

    meta.push_back(tmp_meta);
   }
  }
  std::cerr << "GLOBAL END" << endl;
  return meta;
}

std::map<std::string, std::string> ProcessAndStripSGML(std::string &line)
{
  std::map<std::string, std::string> meta;
  std::string lline = ToLower(line);
  if (lline.find("<seg")!=0) return meta;
  size_t close = lline.find(">");
  if (close == std::string::npos) return meta; // error
  size_t end = lline.find("</seg>");
  std::string seg = Trim(lline.substr(4, close-4));
  std::string text = line.substr(close+1, end - close - 1);
  for (size_t i = 1; i < seg.size(); i++) {
    if (seg[i] == '=' && seg[i-1] == ' ') {
      std::string less = seg.substr(0, i-1) + seg.substr(i);
      seg = less;
      i = 0;
      continue;
    }
    if (seg[i] == '=' && seg[i+1] == ' ') {
      std::string less = seg.substr(0, i+1);
      if (i+2 < seg.size()) less += seg.substr(i+2);
      seg = less;
      i = 0;
      continue;
    }
  }
  line = Trim(text);
  if (seg == "") return meta;
  for (size_t i = 1; i < seg.size(); i++) {
    if (seg[i] == '=') {
      std::string label = seg.substr(0, i);
      std::string val = seg.substr(i+1);
      if (val[0] == '"') {
        val = val.substr(1);
        size_t close = val.find('"');
        if (close == std::string::npos) {
          TRACE_ERR("SGML parse error: missing \"\n");
          seg = "";
          i = 0;
        } else {
          seg = val.substr(close+1);
          val = val.substr(0, close);
          i = 0;
        }
      } else {
        size_t close = val.find(' ');
        if (close == std::string::npos) {
          seg = "";
          i = 0;
        } else {
          seg = val.substr(close+1);
          val = val.substr(0, close);
        }
      }
      label = Trim(label);
      seg = Trim(seg);
      meta[label] = val;
    }
  }
  return meta;
}

std::string PassthroughSGML(std::string &line, const std::string tagName, const std::string& lbrackStr, const std::string& rbrackStr)
{
  string lbrack = lbrackStr; // = "<";
  string rbrack = rbrackStr; // = ">";

  std::string meta = "";

  std::string lline = ToLower(line);
  size_t open = lline.find(lbrack+tagName);
  //check whether the tag exists; if not return the empty string
  if (open == std::string::npos) return meta;

  size_t close = lline.find(rbrack, open);
  //check whether the tag is closed with '/>'; if not return the empty string
  if (close == std::string::npos) {
    TRACE_ERR("PassthroughSGML error: the <passthrough info/> tag does not end properly\n");
    return meta;
  }
  // extract the tag
  std::string tmp = line.substr(open, close - open + 1);
  meta = line.substr(open, close - open + 1);

  // strip the tag from the line
  line = line.substr(0, open) + line.substr(close + 1, std::string::npos);

  TRACE_ERR("The input contains a <passthrough info/> tag:" << meta << std::endl);

  lline = ToLower(line);
  open = lline.find(lbrack+tagName);
  if (open != std::string::npos) {
    TRACE_ERR("PassthroughSGML error: there are two <passthrough> tags\n");
  }
  return meta;
}

}

<|endoftext|>


<commit_before>/**
 * \file
 * \brief SignalsCatcherControlBlock class header
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-10-24
 */

#ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_

#include "distortos/SignalAction.hpp"

namespace distortos
{

namespace scheduler
{

class ThreadControlBlock;

}	// namespace scheduler

namespace synchronization
{

class SignalsReceiverControlBlock;

/// SignalsCatcherControlBlock class is a structure required by threads for "catching" and "handling" of signals
class SignalsCatcherControlBlock
{
public:

	/// association of signal numbers (as SignalSet) with SignalAction
	using Association = std::pair<SignalSet, SignalAction>;

	/// type of uninitialized storage for Association objects
	using Storage = std::aligned_storage<sizeof(Association), alignof(Association)>::type;

	/**
	 * \brief SignalsCatcherControlBlock's constructor
	 *
	 * \param [in] storage is a memory block for storage of Association objects, sufficiently large for \a storageSize
	 * elements
	 * \param [in] storageSize is the number of elements in \a storage array
	 */

	constexpr SignalsCatcherControlBlock(Storage* const storage, const size_t storageSize) :
			signalMask_{SignalSet::empty},
			associationsBegin_{reinterpret_cast<decltype(associationsBegin_)>(storage)},
			storageBegin_{storage},
			storageEnd_{storage + storageSize},
			deliveryIsPending_{}
	{

	}

	/**
	 * \brief SignalsCatcherControlBlock's destructor
	 */

	~SignalsCatcherControlBlock();

	/**
	 * \brief Hook function executed when delivery of signals is started.
	 *
	 * Clears "delivery pending" flag.
	 *
	 * \attention This function should be called only by SignalsReceiverControlBlock::deliveryOfSignalsFinishedHook().
	 */

	void deliveryOfSignalsStartedHook()
	{
		deliveryIsPending_ = false;
	}

	/**
	 * \brief Gets SignalAction associated with given signal number.
	 *
	 * \param [in] signalNumber is the signal for which the association is requested, [0; 31]
	 *
	 * \return pair with return code (0 on success, error code otherwise) and SignalAction that is associated with
	 * \a signalNumber, default-constructed object if no association was found;
	 * error codes:
	 * - EINVAL - \a signalNumber value is invalid;
	 */

	std::pair<int, SignalAction> getAssociation(uint8_t signalNumber) const;

	/**
	 * \return SignalSet with signal mask for associated thread
	 */

	SignalSet getSignalMask() const
	{
		return signalMask_;
	}

	/**
	 * \brief Part of SignalsReceiverControlBlock::postGenerate() specific to catching unmasked signals.
	 *
	 * Requests delivery of signals to associated thread if there is some non-default signal handler for the signal.
	 *
	 * \param [in] signalNumber is the unmasked signal that was generated, [0; 31]
	 * \param [in] threadControlBlock is a reference to associated ThreadControlBlock
	 *
	 * \return 0 on success, error code otherwise:
	 * - EINVAL - \a signalNumber value is invalid;
	 */

	int postGenerate(uint8_t signalNumber, scheduler::ThreadControlBlock& threadControlBlock);

	/**
	 * \brief Sets association for given signal number.
	 *
	 * \param [in] signalNumber is the signal for which the association will be set, [0; 31]
	 * \param [in] signalAction is a reference to SignalAction that will be associated with given signal number, object
	 * in internal storage is copy-constructed
	 *
	 * \return pair with return code (0 on success, error code otherwise) and SignalAction that was associated with
	 * \a signalNumber, default-constructed object if no association was found;
	 * error codes:
	 * - EAGAIN - no resources are available to associate \a signalNumber with \a signalAction;
	 * - EINVAL - \a signalNumber value is invalid;
	 */

	std::pair<int, SignalAction> setAssociation(uint8_t signalNumber, const SignalAction& signalAction);

	/**
	 * \brief Sets signal mask for associated thread.
	 *
	 * If any pending signal is unblocked and \a owner doesn't equal nullptr, then delivery of signals to associated
	 * thread will be requested.
	 *
	 * \param [in] signalMask is the SignalSet with new signal mask for associated thread
	 * \param [in] owner selects whether delivery of signals will be requested if any pending signal is unblocked
	 * (pointer to owner SignalsReceiverControlBlock object) or not (nullptr)
	 */

	void setSignalMask(SignalSet signalMask, const SignalsReceiverControlBlock* owner);

private:

	/**
	 * \brief Clears association for given signal number.
	 *
	 * \param [in] signalNumber is the signal for which the association will be cleared, [0; 31]
	 *
	 * \return SignalAction that was associated with \a signalNumber, default-constructed object if no association was
	 * found
	 */

	SignalAction clearAssociation(uint8_t signalNumber);

	/**
	 * \brief Clears given association for given signal number.
	 *
	 * \param [in] signalNumber is the signal for which the association will be cleared, [0; 31]
	 * \param [in] association is a reference to Association object from [associationsBegin_; associationsEnd_)
	 * range that will be removed
	 *
	 * \return SignalAction from \a association
	 */

	SignalAction clearAssociation(uint8_t signalNumber, Association& association);

	/**
	 * \brief Requests delivery of signals to associated thread.
	 *
	 * Delivery of signals (via special function executed in the associated thread) is requested only if it's not
	 * already pending. The thread is unblocked if it was blocked.
	 *
	 * \param [in] threadControlBlock is a reference to associated ThreadControlBlock
	 */

	void requestDeliveryOfSignals(scheduler::ThreadControlBlock& threadControlBlock);

	/// SignalSet with signal mask for associated thread
	SignalSet signalMask_;

	/// pointer to first element of range of Association objects
	Association* associationsBegin_;

	/// union binds \a associationsEnd_ and \a storageBegin_ - these point to the same address
	union
	{
		/// pointer to "one past the last" element of range of Association objects
		Association* associationsEnd_;

		/// pointer to first element of range of Storage objects
		Storage* storageBegin_;
	};

	/// pointer to "one past the last" element of range of Storage objects
	Storage* storageEnd_;

	/// true if signal delivery is pending, false otherwise
	bool deliveryIsPending_;
};

}	// namespace synchronization

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_
<commit_msg>SignalsCatcherControlBlock: add StorageUniquePointer type alias<commit_after>/**
 * \file
 * \brief SignalsCatcherControlBlock class header
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-10-24
 */

#ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_

#include "distortos/SignalAction.hpp"

#include <memory>

namespace distortos
{

namespace scheduler
{

class ThreadControlBlock;

}	// namespace scheduler

namespace synchronization
{

class SignalsReceiverControlBlock;

/// SignalsCatcherControlBlock class is a structure required by threads for "catching" and "handling" of signals
class SignalsCatcherControlBlock
{
public:

	/// association of signal numbers (as SignalSet) with SignalAction
	using Association = std::pair<SignalSet, SignalAction>;

	/// type of uninitialized storage for Association objects
	using Storage = std::aligned_storage<sizeof(Association), alignof(Association)>::type;

	/// unique_ptr (with deleter) to Storage[]
	using StorageUniquePointer = std::unique_ptr<Storage[], void(&)(Storage*)>;

	/**
	 * \brief SignalsCatcherControlBlock's constructor
	 *
	 * \param [in] storage is a memory block for storage of Association objects, sufficiently large for \a storageSize
	 * elements
	 * \param [in] storageSize is the number of elements in \a storage array
	 */

	constexpr SignalsCatcherControlBlock(Storage* const storage, const size_t storageSize) :
			signalMask_{SignalSet::empty},
			associationsBegin_{reinterpret_cast<decltype(associationsBegin_)>(storage)},
			storageBegin_{storage},
			storageEnd_{storage + storageSize},
			deliveryIsPending_{}
	{

	}

	/**
	 * \brief SignalsCatcherControlBlock's destructor
	 */

	~SignalsCatcherControlBlock();

	/**
	 * \brief Hook function executed when delivery of signals is started.
	 *
	 * Clears "delivery pending" flag.
	 *
	 * \attention This function should be called only by SignalsReceiverControlBlock::deliveryOfSignalsFinishedHook().
	 */

	void deliveryOfSignalsStartedHook()
	{
		deliveryIsPending_ = false;
	}

	/**
	 * \brief Gets SignalAction associated with given signal number.
	 *
	 * \param [in] signalNumber is the signal for which the association is requested, [0; 31]
	 *
	 * \return pair with return code (0 on success, error code otherwise) and SignalAction that is associated with
	 * \a signalNumber, default-constructed object if no association was found;
	 * error codes:
	 * - EINVAL - \a signalNumber value is invalid;
	 */

	std::pair<int, SignalAction> getAssociation(uint8_t signalNumber) const;

	/**
	 * \return SignalSet with signal mask for associated thread
	 */

	SignalSet getSignalMask() const
	{
		return signalMask_;
	}

	/**
	 * \brief Part of SignalsReceiverControlBlock::postGenerate() specific to catching unmasked signals.
	 *
	 * Requests delivery of signals to associated thread if there is some non-default signal handler for the signal.
	 *
	 * \param [in] signalNumber is the unmasked signal that was generated, [0; 31]
	 * \param [in] threadControlBlock is a reference to associated ThreadControlBlock
	 *
	 * \return 0 on success, error code otherwise:
	 * - EINVAL - \a signalNumber value is invalid;
	 */

	int postGenerate(uint8_t signalNumber, scheduler::ThreadControlBlock& threadControlBlock);

	/**
	 * \brief Sets association for given signal number.
	 *
	 * \param [in] signalNumber is the signal for which the association will be set, [0; 31]
	 * \param [in] signalAction is a reference to SignalAction that will be associated with given signal number, object
	 * in internal storage is copy-constructed
	 *
	 * \return pair with return code (0 on success, error code otherwise) and SignalAction that was associated with
	 * \a signalNumber, default-constructed object if no association was found;
	 * error codes:
	 * - EAGAIN - no resources are available to associate \a signalNumber with \a signalAction;
	 * - EINVAL - \a signalNumber value is invalid;
	 */

	std::pair<int, SignalAction> setAssociation(uint8_t signalNumber, const SignalAction& signalAction);

	/**
	 * \brief Sets signal mask for associated thread.
	 *
	 * If any pending signal is unblocked and \a owner doesn't equal nullptr, then delivery of signals to associated
	 * thread will be requested.
	 *
	 * \param [in] signalMask is the SignalSet with new signal mask for associated thread
	 * \param [in] owner selects whether delivery of signals will be requested if any pending signal is unblocked
	 * (pointer to owner SignalsReceiverControlBlock object) or not (nullptr)
	 */

	void setSignalMask(SignalSet signalMask, const SignalsReceiverControlBlock* owner);

private:

	/**
	 * \brief Clears association for given signal number.
	 *
	 * \param [in] signalNumber is the signal for which the association will be cleared, [0; 31]
	 *
	 * \return SignalAction that was associated with \a signalNumber, default-constructed object if no association was
	 * found
	 */

	SignalAction clearAssociation(uint8_t signalNumber);

	/**
	 * \brief Clears given association for given signal number.
	 *
	 * \param [in] signalNumber is the signal for which the association will be cleared, [0; 31]
	 * \param [in] association is a reference to Association object from [associationsBegin_; associationsEnd_)
	 * range that will be removed
	 *
	 * \return SignalAction from \a association
	 */

	SignalAction clearAssociation(uint8_t signalNumber, Association& association);

	/**
	 * \brief Requests delivery of signals to associated thread.
	 *
	 * Delivery of signals (via special function executed in the associated thread) is requested only if it's not
	 * already pending. The thread is unblocked if it was blocked.
	 *
	 * \param [in] threadControlBlock is a reference to associated ThreadControlBlock
	 */

	void requestDeliveryOfSignals(scheduler::ThreadControlBlock& threadControlBlock);

	/// SignalSet with signal mask for associated thread
	SignalSet signalMask_;

	/// pointer to first element of range of Association objects
	Association* associationsBegin_;

	/// union binds \a associationsEnd_ and \a storageBegin_ - these point to the same address
	union
	{
		/// pointer to "one past the last" element of range of Association objects
		Association* associationsEnd_;

		/// pointer to first element of range of Storage objects
		Storage* storageBegin_;
	};

	/// pointer to "one past the last" element of range of Storage objects
	Storage* storageEnd_;

	/// true if signal delivery is pending, false otherwise
	bool deliveryIsPending_;
};

}	// namespace synchronization

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_
<|endoftext|>


<commit_before>#include "rtkTestConfiguration.h"
#include "rtkProjectionsReader.h"
#include "rtkMacro.h"
#include "rtkDigisensGeometryReader.h"
#include "rtkThreeDCircularProjectionGeometryXMLFile.h"

#include <itkRegularExpressionSeriesFileNames.h>

typedef rtk::ThreeDCircularProjectionGeometry GeometryType;

template<class TImage>
void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref)
{
#if !(FAST_TESTS_NO_CHECKS)
  typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType;
  ImageIteratorType itTest( recon, recon->GetBufferedRegion() );
  ImageIteratorType itRef( ref, ref->GetBufferedRegion() );

  typedef double ErrorType;
  ErrorType TestError = 0.;
  ErrorType EnerError = 0.;

  itTest.GoToBegin();
  itRef.GoToBegin();

  while( !itRef.IsAtEnd() )
    {
    typename TImage::PixelType TestVal = itTest.Get();
    typename TImage::PixelType RefVal = itRef.Get();

    if( TestVal != RefVal )
      {
      TestError += vcl_abs(RefVal - TestVal);
      EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
      }
    ++itTest;
    ++itRef;
    }
  // Error per Pixel
  ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
  // MSE
  ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "MSE = " << MSE << std::endl;
  // PSNR
  ErrorType PSNR = 20*log10(255.0) - 10*log10(MSE);
  std::cout << "PSNR = " << PSNR << "dB" << std::endl;
  // QI
  ErrorType QI = (255.0-ErrorPerPixel)/255.0;
  std::cout << "QI = " << QI << std::endl;

  // Checking results
  if (ErrorPerPixel > 1.6e-7)
    {
    std::cerr << "Test Failed, Error per pixel not valid! "
              << ErrorPerPixel << " instead of 1.6e-7" << std::endl;
    exit( EXIT_FAILURE);
    }
  if (PSNR < 100.)
    {
    std::cerr << "Test Failed, PSNR not valid! "
              << PSNR << " instead of 100" << std::endl;
    exit( EXIT_FAILURE);
    }
#endif
}

void CheckGeometries(GeometryType *g1, GeometryType *g2)
{
  const double e           = 1e-10;
  const unsigned int nproj = g1->GetGantryAngles().size();
  if(g2->GetGantryAngles().size() != nproj)
    {
    std::cerr << "Unequal number of projections in the two geometries"
              << std::endl;
    exit(EXIT_FAILURE);
    }

  for(unsigned int i=0; i<nproj; i++)
    {
    if( e < rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetween0And360Degrees(
              std::fabs(g1->GetGantryAngles()[i] -
                        g2->GetGantryAngles()[i])) ||
        e < rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetween0And360Degrees(
              std::fabs(g1->GetOutOfPlaneAngles()[i] -
                        g2->GetOutOfPlaneAngles()[i])) ||
        e < rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetween0And360Degrees(
              std::fabs(g1->GetInPlaneAngles()[i] -
                        g2->GetInPlaneAngles()[i])) ||
        e < std::fabs(g1->GetSourceToIsocenterDistances()[i] -
                      g2->GetSourceToIsocenterDistances()[i]) ||
        e < std::fabs(g1->GetSourceOffsetsX()[i] -
                      g2->GetSourceOffsetsX()[i]) ||
        e < std::fabs(g1->GetSourceOffsetsY()[i] -
                      g2->GetSourceOffsetsY()[i]) ||
        e < std::fabs(g1->GetSourceToDetectorDistances()[i] -
                      g2->GetSourceToDetectorDistances()[i]) ||
        e < std::fabs(g1->GetProjectionOffsetsX()[i] -
                      g2->GetProjectionOffsetsX()[i]) ||
        e < std::fabs(g1->GetProjectionOffsetsY()[i] -
                      g2->GetProjectionOffsetsY()[i]) )
      {
      std::cerr << "Geometry of projection #" << i << " is unvalid."
                << std::endl;
      exit(EXIT_FAILURE);
      }

    }
}

int main(int, char** )
{
  // Elekta geometry
  rtk::DigisensGeometryReader::Pointer geoTargReader;
  geoTargReader = rtk::DigisensGeometryReader::New();
  geoTargReader->SetXMLFileName( std::string(RTK_DATA_ROOT) +
                                 std::string("/Input/Digisens/calibration.cal") );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( geoTargReader->UpdateOutputData() );

  // Reference geometry
  rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geoRefReader;
  geoRefReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New();
  geoRefReader->SetFilename( std::string(RTK_DATA_ROOT) +
                             std::string("/Baseline/Digisens/geometry.xml") );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( geoRefReader->GenerateOutputInformation() )

  // 1. Check geometries
  CheckGeometries(geoTargReader->GetGeometry(), geoRefReader->GetOutputObject() );

  // ******* COMPARING projections *******
  typedef float OutputPixelType;
  const unsigned int Dimension = 3;
  typedef itk::Image< OutputPixelType, Dimension > ImageType;

  // Tif projections reader
  typedef rtk::ProjectionsReader< ImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  std::vector<std::string> fileNames;
  fileNames.push_back( std::string(RTK_DATA_ROOT) +
                       std::string("/Input/Digisens/ima0010.tif") );
  reader->SetFileNames( fileNames );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() );

  // Reference projections reader
  ReaderType::Pointer readerRef = ReaderType::New();
  fileNames.clear();
  fileNames.push_back( std::string(RTK_DATA_ROOT) +
                       std::string("/Baseline/Digisens/attenuation.mha") );
  readerRef->SetFileNames( fileNames );
  TRY_AND_EXIT_ON_ITK_EXCEPTION(readerRef->Update());

  // 2. Compare read projections
  CheckImageQuality< ImageType >(reader->GetOutput(), readerRef->GetOutput());

  // If both succeed
  std::cout << "\n\nTest PASSED! " << std::endl;
  return EXIT_SUCCESS;
}
<commit_msg>TEST: New threshold in order to Pass the test<commit_after>#include "rtkTestConfiguration.h"
#include "rtkProjectionsReader.h"
#include "rtkMacro.h"
#include "rtkDigisensGeometryReader.h"
#include "rtkThreeDCircularProjectionGeometryXMLFile.h"

#include <itkRegularExpressionSeriesFileNames.h>

typedef rtk::ThreeDCircularProjectionGeometry GeometryType;

template<class TImage>
void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref)
{
#if !(FAST_TESTS_NO_CHECKS)
  typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType;
  ImageIteratorType itTest( recon, recon->GetBufferedRegion() );
  ImageIteratorType itRef( ref, ref->GetBufferedRegion() );

  typedef double ErrorType;
  ErrorType TestError = 0.;
  ErrorType EnerError = 0.;

  itTest.GoToBegin();
  itRef.GoToBegin();

  while( !itRef.IsAtEnd() )
    {
    typename TImage::PixelType TestVal = itTest.Get();
    typename TImage::PixelType RefVal = itRef.Get();

    if( TestVal != RefVal )
      {
      TestError += vcl_abs(RefVal - TestVal);
      EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
      }
    ++itTest;
    ++itRef;
    }
  // Error per Pixel
  ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
  // MSE
  ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "MSE = " << MSE << std::endl;
  // PSNR
  ErrorType PSNR = 20*log10(255.0) - 10*log10(MSE);
  std::cout << "PSNR = " << PSNR << "dB" << std::endl;
  // QI
  ErrorType QI = (255.0-ErrorPerPixel)/255.0;
  std::cout << "QI = " << QI << std::endl;

  // Checking results
  if (ErrorPerPixel > 2.31e-7)
    {
    std::cerr << "Test Failed, Error per pixel not valid! "
              << ErrorPerPixel << " instead of 1.31e-7" << std::endl;
    exit( EXIT_FAILURE);
    }
  if (PSNR < 100.)
    {
    std::cerr << "Test Failed, PSNR not valid! "
              << PSNR << " instead of 100" << std::endl;
    exit( EXIT_FAILURE);
    }
#endif
}

void CheckGeometries(GeometryType *g1, GeometryType *g2)
{
  const double e           = 1e-10;
  const unsigned int nproj = g1->GetGantryAngles().size();
  if(g2->GetGantryAngles().size() != nproj)
    {
    std::cerr << "Unequal number of projections in the two geometries"
              << std::endl;
    exit(EXIT_FAILURE);
    }

  for(unsigned int i=0; i<nproj; i++)
    {
    if( e < rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetween0And360Degrees(
              std::fabs(g1->GetGantryAngles()[i] -
                        g2->GetGantryAngles()[i])) ||
        e < rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetween0And360Degrees(
              std::fabs(g1->GetOutOfPlaneAngles()[i] -
                        g2->GetOutOfPlaneAngles()[i])) ||
        e < rtk::ThreeDCircularProjectionGeometry::ConvertAngleBetween0And360Degrees(
              std::fabs(g1->GetInPlaneAngles()[i] -
                        g2->GetInPlaneAngles()[i])) ||
        e < std::fabs(g1->GetSourceToIsocenterDistances()[i] -
                      g2->GetSourceToIsocenterDistances()[i]) ||
        e < std::fabs(g1->GetSourceOffsetsX()[i] -
                      g2->GetSourceOffsetsX()[i]) ||
        e < std::fabs(g1->GetSourceOffsetsY()[i] -
                      g2->GetSourceOffsetsY()[i]) ||
        e < std::fabs(g1->GetSourceToDetectorDistances()[i] -
                      g2->GetSourceToDetectorDistances()[i]) ||
        e < std::fabs(g1->GetProjectionOffsetsX()[i] -
                      g2->GetProjectionOffsetsX()[i]) ||
        e < std::fabs(g1->GetProjectionOffsetsY()[i] -
                      g2->GetProjectionOffsetsY()[i]) )
      {
      std::cerr << "Geometry of projection #" << i << " is unvalid."
                << std::endl;
      exit(EXIT_FAILURE);
      }

    }
}

int main(int, char** )
{
  // Elekta geometry
  rtk::DigisensGeometryReader::Pointer geoTargReader;
  geoTargReader = rtk::DigisensGeometryReader::New();
  geoTargReader->SetXMLFileName( std::string(RTK_DATA_ROOT) +
                                 std::string("/Input/Digisens/calibration.cal") );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( geoTargReader->UpdateOutputData() );

  // Reference geometry
  rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geoRefReader;
  geoRefReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New();
  geoRefReader->SetFilename( std::string(RTK_DATA_ROOT) +
                             std::string("/Baseline/Digisens/geometry.xml") );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( geoRefReader->GenerateOutputInformation() )

  // 1. Check geometries
  CheckGeometries(geoTargReader->GetGeometry(), geoRefReader->GetOutputObject() );

  // ******* COMPARING projections *******
  typedef float OutputPixelType;
  const unsigned int Dimension = 3;
  typedef itk::Image< OutputPixelType, Dimension > ImageType;

  // Tif projections reader
  typedef rtk::ProjectionsReader< ImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  std::vector<std::string> fileNames;
  fileNames.push_back( std::string(RTK_DATA_ROOT) +
                       std::string("/Input/Digisens/ima0010.tif") );
  reader->SetFileNames( fileNames );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() );

  // Reference projections reader
  ReaderType::Pointer readerRef = ReaderType::New();
  fileNames.clear();
  fileNames.push_back( std::string(RTK_DATA_ROOT) +
                       std::string("/Baseline/Digisens/attenuation.mha") );
  readerRef->SetFileNames( fileNames );
  TRY_AND_EXIT_ON_ITK_EXCEPTION(readerRef->Update());

  // 2. Compare read projections
  CheckImageQuality< ImageType >(reader->GetOutput(), readerRef->GetOutput());

  // If both succeed
  std::cout << "\n\nTest PASSED! " << std::endl;
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "common.h"
#include "World.h"
#include "Species.h"
#include <algorithm>

static long idGen = 0;

Species::Species(Species* originalSpecies){
  id = idGen++;

  if (originalSpecies == NULL){
    // completely new species
    while (!generateDna()) ;
  }else{
    // evolution of an existing species
    vector<DNA*>::iterator itDNA;
    for (itDNA = originalSpecies->dna.begin(); itDNA != originalSpecies->dna.end(); ++itDNA) {
      DNA* from = (*itDNA);
      this->dna.push_back(new DNA(from));
    }
    // mutation:
    int randIdx = randInt(dna.size());
    delete this->dna[randIdx];
    this->dna[randIdx] = new DNA(NULL);
  }

  HSVtoRGB( &(this->r), &(this->g), &(this->b), randDouble(), 1, .65 );
}

// Don't allow species with impossible shape (z<1 or collision with self)
bool Species::generateDna(){
  clearDna();

  DNA* d = new DNA(NULL);
  d->growthDirection = 4; // first cell has to go up
  this->dna.push_back(d);

  int pos[MAX_CELLS][3];
  pos[0][0] = pos[0][1] = pos[0][2] = 0;
  pos[1][0] = pos[1][1] = 0;
  pos[1][2] = 1;

  vector<int> takenDirs;
  for (int i=2; i<world.maxCells; ++i){
    int x = pos[i-1][0], y = pos[i-1][1], z = pos[i-1][2];

    takenDirs.clear();

    for (int j=0; j<i-1; ++j){
      int prevX = pos[j][0], prevY = pos[j][1], prevZ = pos[j][2];
      if (prevX == x+1 && prevY == y   && prevZ == z)   takenDirs.push_back(0);
      if (prevX == x-1 && prevY == y   && prevZ == z)   takenDirs.push_back(1);
      if (prevX == x   && prevY == y+1 && prevZ == z)   takenDirs.push_back(2);
      if (prevX == x   && prevY == y-1 && prevZ == z)   takenDirs.push_back(3);
      if (prevX == x   && prevY == y   && prevZ == z+1) takenDirs.push_back(4);
      if (prevX == x   && prevY == y   && prevZ == z-1) takenDirs.push_back(5);
    }

    // all positions around are already taken:
    if (takenDirs.size() == 6) return false;

    bool canGoDown = find(takenDirs.begin(), takenDirs.end(), 5) == takenDirs.end();

    // the only position available is downwards but Z=0 is disallowed:
    if (canGoDown && takenDirs.size() == 5 && z<=1) return false;

    // don't allow Z=0
    if (canGoDown && z == 1) takenDirs.push_back(5);

    int direction = randInt(6 - takenDirs.size());
    for (unsigned int k=0; k<takenDirs.size(); ++k){
      if (direction >= takenDirs[k]){
        ++direction;
      }
    }
    DNA* d = new DNA(NULL);
    d->growthDirection = direction;
    this->dna.push_back(d);

    pos[i][0] = x;
    pos[i][1] = y;
    pos[i][2] = z;

    if      (direction == 0) pos[i][0] = x+1;
    else if (direction == 1) pos[i][0] = x-1;
    else if (direction == 2) pos[i][1] = y+1;
    else if (direction == 3) pos[i][1] = y-1;
    else if (direction == 4) pos[i][2] = z+1;
    else if (direction == 5) pos[i][2] = z-1;
  }

  return true;
}

void Species::setColor(float r, float g, float b){
  this->r=r; this->g=g; this->b=b;
}

void Species::kill(Creature* c){
  list<Creature*>::iterator it = find(creatures.begin(), creatures.end(), c);
  if (it == creatures.end()){
    cout<<"Cannot kill creature: not found!"<<endl;
  }else{
    delete *it;
    creatures.erase(it);
  }
}

int Species::killOldAndWeakCreatures(){
  std::list<Creature*>::iterator itCreature = creatures.begin();

  int deathCount = 0;
  while (itCreature != creatures.end()){
    Creature* c = (*itCreature);
    if (c->cells.size() >= world.maxCells
        || world.cycle - c->creationCycle >= world.maxCells
        || !c->hasEnoughEnergy()){
      if (DEBUG) cout << "Creature dies." <<endl;
      delete c;
      itCreature = creatures.erase(itCreature);
      ++deathCount;
    }else{
      ++itCreature;
    }
  }

  return deathCount;
}

Creature* Species::reproduce(int x, int y){
  Creature* c = new Creature( (*this), x, y );
  creatures.push_back(c);
  return c;
}

void Species::clearDna(){
  vector<DNA*>::iterator itDNA;
  for (itDNA = dna.begin(); itDNA != dna.end(); ++itDNA) {
    delete (*itDNA);
  }
  this->dna.clear();
}

Species::~Species(){
  list<Creature*>::iterator itCreature;
  for (itCreature = creatures.begin(); itCreature != creatures.end(); ++itCreature) {
    delete (*itCreature);
  }

  clearDna();
}

DNA::DNA(DNA* from){
  for (int i=0;i<6;i++) {
    this->probas[i] = (from!=NULL) ? from->probas[i] : randDouble();
  }
  growthDirection = from!=NULL ? from->growthDirection:randInt(6);
}
<commit_msg>Compiler warning<commit_after>#include "common.h"
#include "World.h"
#include "Species.h"
#include <algorithm>

static long idGen = 0;

Species::Species(Species* originalSpecies){
  id = idGen++;

  if (originalSpecies == NULL){
    // completely new species
    while (!generateDna()) ;
  }else{
    // evolution of an existing species
    vector<DNA*>::iterator itDNA;
    for (itDNA = originalSpecies->dna.begin(); itDNA != originalSpecies->dna.end(); ++itDNA) {
      DNA* from = (*itDNA);
      this->dna.push_back(new DNA(from));
    }
    // mutation:
    int randIdx = randInt(dna.size());
    delete this->dna[randIdx];
    this->dna[randIdx] = new DNA(NULL);
  }

  HSVtoRGB( &(this->r), &(this->g), &(this->b), randDouble(), 1, .65 );
}

// Don't allow species with impossible shape (z<1 or collision with self)
bool Species::generateDna(){
  clearDna();

  DNA* d = new DNA(NULL);
  d->growthDirection = 4; // first cell has to go up
  this->dna.push_back(d);

  int pos[MAX_CELLS][3];
  pos[0][0] = pos[0][1] = pos[0][2] = 0;
  pos[1][0] = pos[1][1] = 0;
  pos[1][2] = 1;

  vector<int> takenDirs;
  for (int i=2; i<world.maxCells; ++i){
    int x = pos[i-1][0], y = pos[i-1][1], z = pos[i-1][2];

    takenDirs.clear();

    for (int j=0; j<i-1; ++j){
      int prevX = pos[j][0], prevY = pos[j][1], prevZ = pos[j][2];
      if (prevX == x+1 && prevY == y   && prevZ == z)   takenDirs.push_back(0);
      if (prevX == x-1 && prevY == y   && prevZ == z)   takenDirs.push_back(1);
      if (prevX == x   && prevY == y+1 && prevZ == z)   takenDirs.push_back(2);
      if (prevX == x   && prevY == y-1 && prevZ == z)   takenDirs.push_back(3);
      if (prevX == x   && prevY == y   && prevZ == z+1) takenDirs.push_back(4);
      if (prevX == x   && prevY == y   && prevZ == z-1) takenDirs.push_back(5);
    }

    // all positions around are already taken:
    if (takenDirs.size() == 6) return false;

    bool canGoDown = find(takenDirs.begin(), takenDirs.end(), 5) == takenDirs.end();

    // the only position available is downwards but Z=0 is disallowed:
    if (canGoDown && takenDirs.size() == 5 && z<=1) return false;

    // don't allow Z=0
    if (canGoDown && z == 1) takenDirs.push_back(5);

    int direction = randInt(6 - takenDirs.size());
    for (unsigned int k=0; k<takenDirs.size(); ++k){
      if (direction >= takenDirs[k]){
        ++direction;
      }
    }
    DNA* d = new DNA(NULL);
    d->growthDirection = direction;
    this->dna.push_back(d);

    pos[i][0] = x;
    pos[i][1] = y;
    pos[i][2] = z;

    if      (direction == 0) pos[i][0] = x+1;
    else if (direction == 1) pos[i][0] = x-1;
    else if (direction == 2) pos[i][1] = y+1;
    else if (direction == 3) pos[i][1] = y-1;
    else if (direction == 4) pos[i][2] = z+1;
    else if (direction == 5) pos[i][2] = z-1;
  }

  return true;
}

void Species::setColor(float r, float g, float b){
  this->r=r; this->g=g; this->b=b;
}

void Species::kill(Creature* c){
  list<Creature*>::iterator it = find(creatures.begin(), creatures.end(), c);
  if (it == creatures.end()){
    cout<<"Cannot kill creature: not found!"<<endl;
  }else{
    delete *it;
    creatures.erase(it);
  }
}

int Species::killOldAndWeakCreatures(){
  std::list<Creature*>::iterator itCreature = creatures.begin();

  int deathCount = 0;
  while (itCreature != creatures.end()){
    Creature* c = (*itCreature);
    if (c->cells.size() >= (unsigned int)world.maxCells
        || world.cycle - c->creationCycle >= world.maxCells
        || !c->hasEnoughEnergy()){
      if (DEBUG) cout << "Creature dies." <<endl;
      delete c;
      itCreature = creatures.erase(itCreature);
      ++deathCount;
    }else{
      ++itCreature;
    }
  }

  return deathCount;
}

Creature* Species::reproduce(int x, int y){
  Creature* c = new Creature( (*this), x, y );
  creatures.push_back(c);
  return c;
}

void Species::clearDna(){
  vector<DNA*>::iterator itDNA;
  for (itDNA = dna.begin(); itDNA != dna.end(); ++itDNA) {
    delete (*itDNA);
  }
  this->dna.clear();
}

Species::~Species(){
  list<Creature*>::iterator itCreature;
  for (itCreature = creatures.begin(); itCreature != creatures.end(); ++itCreature) {
    delete (*itCreature);
  }

  clearDna();
}

DNA::DNA(DNA* from){
  for (int i=0;i<6;i++) {
    this->probas[i] = (from!=NULL) ? from->probas[i] : randDouble();
  }
  growthDirection = from!=NULL ? from->growthDirection:randInt(6);
}
<|endoftext|>


<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "JsrtPch.h"
#include "jsrtHelper.h"
#include "JsrtExternalObject.h"
#include "Types/PathTypeHandler.h"

#ifdef _CHAKRACOREBUILD
JsrtExternalType::JsrtExternalType(Js::ScriptContext* scriptContext, JsTraceCallback traceCallback, JsFinalizeCallback finalizeCallback, Js::RecyclableObject * prototype)
    : Js::DynamicType(
        scriptContext,
        Js::TypeIds_Object,
        prototype,
        nullptr,
        Js::PathTypeHandlerNoAttr::New(scriptContext, scriptContext->GetLibrary()->GetRootPath(), 0, 0, 0, true, true),
        true,
        true)
    , jsTraceCallback(traceCallback)
    , jsFinalizeCallback(finalizeCallback)
{
    this->flags |= TypeFlagMask_JsrtExternal;
}
#endif
JsrtExternalType::JsrtExternalType(Js::ScriptContext* scriptContext, JsFinalizeCallback finalizeCallback, Js::RecyclableObject * prototype)
    : Js::DynamicType(
        scriptContext,
        Js::TypeIds_Object,
        prototype,
        nullptr,
        Js::PathTypeHandlerNoAttr::New(scriptContext, scriptContext->GetLibrary()->GetRootPath(), 0, 0, 0, true, true),
        true,
        true)
#ifdef _CHAKRACOREBUILD
    , jsTraceCallback(nullptr)
#endif
    , jsFinalizeCallback(finalizeCallback)
{
    this->flags |= TypeFlagMask_JsrtExternal;
}

JsrtExternalObject::JsrtExternalObject(JsrtExternalType * type, void *data, uint inlineSlotSize) :
    Js::DynamicObject(type, true /* initSlots*/)
{
    if (inlineSlotSize != 0)
    {
        this->slotType = SlotType::Inline;
        this->u.inlineSlotSize = inlineSlotSize;
        if (data)
        {
            memcpy_s(this->GetInlineSlots(), inlineSlotSize, data, inlineSlotSize);
        }
    }
    else
    {
        this->slotType = SlotType::External;
        this->u.slot = data;
    }
}

JsrtExternalObject::JsrtExternalObject(JsrtExternalObject* instance, bool deepCopy) :
    Js::DynamicObject(instance, deepCopy)
{
    if (instance->GetInlineSlotSize() != 0)
    {
        this->slotType = SlotType::Inline;
        this->u.inlineSlotSize = instance->GetInlineSlotSize();
        if (instance->GetInlineSlots())
        {
            memcpy_s(this->GetInlineSlots(), this->GetInlineSlotSize(), instance->GetInlineSlots(), instance->GetInlineSlotSize());
        }
    }
    else
    {
        this->slotType = SlotType::External;
        this->u.slot = instance->GetInlineSlots();
    }
}

#ifdef _CHAKRACOREBUILD
/* static */
JsrtExternalObject* JsrtExternalObject::Create(void *data, uint inlineSlotSize, JsTraceCallback traceCallback, JsFinalizeCallback finalizeCallback, Js::RecyclableObject * prototype, Js::ScriptContext *scriptContext, JsrtExternalType * type)
{
    if (prototype == nullptr)
    {
        prototype = scriptContext->GetLibrary()->GetObjectPrototype();
    }
    if (type == nullptr)
    {
        type = scriptContext->GetLibrary()->GetCachedJsrtExternalType(reinterpret_cast<uintptr_t>(traceCallback), reinterpret_cast<uintptr_t>(finalizeCallback), reinterpret_cast<uintptr_t>(prototype));

        if (type == nullptr)
        {
            type = RecyclerNew(scriptContext->GetRecycler(), JsrtExternalType, scriptContext, traceCallback, finalizeCallback, prototype);
            scriptContext->GetLibrary()->CacheJsrtExternalType(reinterpret_cast<uintptr_t>(traceCallback), reinterpret_cast<uintptr_t>(finalizeCallback), reinterpret_cast<uintptr_t>(prototype), type);
        }
    }

    Assert(type->IsJsrtExternal());

    JsrtExternalObject * externalObject;
    if (traceCallback != nullptr)
    {
        externalObject = RecyclerNewTrackedPlus(scriptContext->GetRecycler(), inlineSlotSize, JsrtExternalObject, static_cast<JsrtExternalType*>(type), data, inlineSlotSize);
    }
    else if (finalizeCallback != nullptr)
    {
        externalObject = RecyclerNewFinalizedPlus(scriptContext->GetRecycler(), inlineSlotSize, JsrtExternalObject, static_cast<JsrtExternalType*>(type), data, inlineSlotSize);
    }
    else
    {
        externalObject = RecyclerNewPlus(scriptContext->GetRecycler(), inlineSlotSize, JsrtExternalObject, static_cast<JsrtExternalType*>(type), data, inlineSlotSize);
    }

    return externalObject;
}
#endif
/* static */
JsrtExternalObject* JsrtExternalObject::Create(void *data, uint inlineSlotSize, JsFinalizeCallback finalizeCallback, Js::RecyclableObject * prototype, Js::ScriptContext *scriptContext, JsrtExternalType * type)
{
    if (prototype == nullptr)
    {
        prototype = scriptContext->GetLibrary()->GetObjectPrototype();
    }
    if (type == nullptr)
    {
#ifdef _CHAKRACOREBUILD
        type = scriptContext->GetLibrary()->GetCachedJsrtExternalType(0, reinterpret_cast<uintptr_t>(finalizeCallback), reinterpret_cast<uintptr_t>(prototype));
#else
        type = scriptContext->GetLibrary()->GetCachedJsrtExternalType(reinterpret_cast<uintptr_t>(finalizeCallback), reinterpret_cast<uintptr_t>(prototype));
#endif

        if (type == nullptr)
        {
            type = RecyclerNew(scriptContext->GetRecycler(), JsrtExternalType, scriptContext, finalizeCallback, prototype);
#ifdef _CHAKRACOREBUILD
            scriptContext->GetLibrary()->CacheJsrtExternalType(0, reinterpret_cast<uintptr_t>(finalizeCallback), reinterpret_cast<uintptr_t>(prototype), type);
#else
            scriptContext->GetLibrary()->CacheJsrtExternalType(reinterpret_cast<uintptr_t>(finalizeCallback), reinterpret_cast<uintptr_t>(prototype), type);
#endif
        }
    }

    Assert(type->IsJsrtExternal());

    JsrtExternalObject * externalObject;
    if (finalizeCallback != nullptr)
    {
        externalObject = RecyclerNewFinalizedPlus(scriptContext->GetRecycler(), inlineSlotSize, JsrtExternalObject, static_cast<JsrtExternalType*>(type), data, inlineSlotSize);
    }
    else
    {
        externalObject = RecyclerNewPlus(scriptContext->GetRecycler(), inlineSlotSize, JsrtExternalObject, static_cast<JsrtExternalType*>(type), data, inlineSlotSize);
    }

    return externalObject;
}

JsrtExternalObject* JsrtExternalObject::Copy(bool deepCopy)
{
    Recycler* recycler = this->GetRecycler();
    JsrtExternalType* type = this->GetExternalType();
    int inlineSlotSize = this->GetInlineSlotSize();

    if (type->GetJsTraceCallback() != nullptr)
    {
        return RecyclerNewTrackedPlus(recycler, inlineSlotSize, JsrtExternalObject, this, deepCopy);
    }
    else if (type->GetJsFinalizeCallback() != nullptr)
    {
        return RecyclerNewFinalizedPlus(recycler, inlineSlotSize, JsrtExternalObject, this, deepCopy);
    }
    else
    {
        return RecyclerNewPlus(recycler, inlineSlotSize, JsrtExternalObject, this, deepCopy);
    }
}

void JsrtExternalObject::Mark(Recycler * recycler)
{
#ifdef _CHAKRACOREBUILD
    recycler->SetNeedExternalWrapperTracing();
    JsTraceCallback traceCallback = this->GetExternalType()->GetJsTraceCallback();
    Assert(nullptr != traceCallback);
    JsrtCallbackState scope(nullptr);
    traceCallback(this->GetSlotData());
#else
    Assert(UNREACHED);
#endif
}

void JsrtExternalObject::Finalize(bool isShutdown)
{
    JsFinalizeCallback finalizeCallback = this->GetExternalType()->GetJsFinalizeCallback();
#ifdef _CHAKRACOREBUILD
    Assert(this->GetExternalType()->GetJsTraceCallback() != nullptr || finalizeCallback != nullptr);
#else
    Assert(finalizeCallback != nullptr);
#endif
    if (nullptr != finalizeCallback)
    {
        JsrtCallbackState scope(nullptr);
        finalizeCallback(this->GetSlotData());
    }
}

void JsrtExternalObject::Dispose(bool isShutdown)
{
}

void * JsrtExternalObject::GetSlotData() const
{
    return this->slotType == SlotType::External
        ? unsafe_write_barrier_cast<void *>(this->u.slot)
        : GetInlineSlots();
}

void JsrtExternalObject::SetSlotData(void * data)
{
    this->slotType = SlotType::External;
    this->u.slot = data;
}

int JsrtExternalObject::GetInlineSlotSize() const
{
    return this->slotType == SlotType::External
        ? 0
        : this->u.inlineSlotSize;
}

void * JsrtExternalObject::GetInlineSlots() const
{
    return this->slotType == SlotType::External
        ? nullptr
        : (void *)((uintptr_t)this + sizeof(JsrtExternalObject));
}

Js::DynamicType* JsrtExternalObject::DuplicateType()
{
    return RecyclerNew(this->GetScriptContext()->GetRecycler(), JsrtExternalType,
        this->GetExternalType());
}

#if ENABLE_TTD
TTD::NSSnapObjects::SnapObjectType JsrtExternalObject::GetSnapTag_TTD() const
{
    return TTD::NSSnapObjects::SnapObjectType::SnapExternalObject;
}

void JsrtExternalObject::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
{
    TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<void*, TTD::NSSnapObjects::SnapObjectType::SnapExternalObject>(objData, nullptr);
}
#endif
<commit_msg>remove reference to trace callback not defined in chakrafull<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "JsrtPch.h"
#include "jsrtHelper.h"
#include "JsrtExternalObject.h"
#include "Types/PathTypeHandler.h"

#ifdef _CHAKRACOREBUILD
JsrtExternalType::JsrtExternalType(Js::ScriptContext* scriptContext, JsTraceCallback traceCallback, JsFinalizeCallback finalizeCallback, Js::RecyclableObject * prototype)
    : Js::DynamicType(
        scriptContext,
        Js::TypeIds_Object,
        prototype,
        nullptr,
        Js::PathTypeHandlerNoAttr::New(scriptContext, scriptContext->GetLibrary()->GetRootPath(), 0, 0, 0, true, true),
        true,
        true)
    , jsTraceCallback(traceCallback)
    , jsFinalizeCallback(finalizeCallback)
{
    this->flags |= TypeFlagMask_JsrtExternal;
}
#endif
JsrtExternalType::JsrtExternalType(Js::ScriptContext* scriptContext, JsFinalizeCallback finalizeCallback, Js::RecyclableObject * prototype)
    : Js::DynamicType(
        scriptContext,
        Js::TypeIds_Object,
        prototype,
        nullptr,
        Js::PathTypeHandlerNoAttr::New(scriptContext, scriptContext->GetLibrary()->GetRootPath(), 0, 0, 0, true, true),
        true,
        true)
#ifdef _CHAKRACOREBUILD
    , jsTraceCallback(nullptr)
#endif
    , jsFinalizeCallback(finalizeCallback)
{
    this->flags |= TypeFlagMask_JsrtExternal;
}

JsrtExternalObject::JsrtExternalObject(JsrtExternalType * type, void *data, uint inlineSlotSize) :
    Js::DynamicObject(type, true /* initSlots*/)
{
    if (inlineSlotSize != 0)
    {
        this->slotType = SlotType::Inline;
        this->u.inlineSlotSize = inlineSlotSize;
        if (data)
        {
            memcpy_s(this->GetInlineSlots(), inlineSlotSize, data, inlineSlotSize);
        }
    }
    else
    {
        this->slotType = SlotType::External;
        this->u.slot = data;
    }
}

JsrtExternalObject::JsrtExternalObject(JsrtExternalObject* instance, bool deepCopy) :
    Js::DynamicObject(instance, deepCopy)
{
    if (instance->GetInlineSlotSize() != 0)
    {
        this->slotType = SlotType::Inline;
        this->u.inlineSlotSize = instance->GetInlineSlotSize();
        if (instance->GetInlineSlots())
        {
            memcpy_s(this->GetInlineSlots(), this->GetInlineSlotSize(), instance->GetInlineSlots(), instance->GetInlineSlotSize());
        }
    }
    else
    {
        this->slotType = SlotType::External;
        this->u.slot = instance->GetInlineSlots();
    }
}

#ifdef _CHAKRACOREBUILD
/* static */
JsrtExternalObject* JsrtExternalObject::Create(void *data, uint inlineSlotSize, JsTraceCallback traceCallback, JsFinalizeCallback finalizeCallback, Js::RecyclableObject * prototype, Js::ScriptContext *scriptContext, JsrtExternalType * type)
{
    if (prototype == nullptr)
    {
        prototype = scriptContext->GetLibrary()->GetObjectPrototype();
    }
    if (type == nullptr)
    {
        type = scriptContext->GetLibrary()->GetCachedJsrtExternalType(reinterpret_cast<uintptr_t>(traceCallback), reinterpret_cast<uintptr_t>(finalizeCallback), reinterpret_cast<uintptr_t>(prototype));

        if (type == nullptr)
        {
            type = RecyclerNew(scriptContext->GetRecycler(), JsrtExternalType, scriptContext, traceCallback, finalizeCallback, prototype);
            scriptContext->GetLibrary()->CacheJsrtExternalType(reinterpret_cast<uintptr_t>(traceCallback), reinterpret_cast<uintptr_t>(finalizeCallback), reinterpret_cast<uintptr_t>(prototype), type);
        }
    }

    Assert(type->IsJsrtExternal());

    JsrtExternalObject * externalObject;
    if (traceCallback != nullptr)
    {
        externalObject = RecyclerNewTrackedPlus(scriptContext->GetRecycler(), inlineSlotSize, JsrtExternalObject, static_cast<JsrtExternalType*>(type), data, inlineSlotSize);
    }
    else if (finalizeCallback != nullptr)
    {
        externalObject = RecyclerNewFinalizedPlus(scriptContext->GetRecycler(), inlineSlotSize, JsrtExternalObject, static_cast<JsrtExternalType*>(type), data, inlineSlotSize);
    }
    else
    {
        externalObject = RecyclerNewPlus(scriptContext->GetRecycler(), inlineSlotSize, JsrtExternalObject, static_cast<JsrtExternalType*>(type), data, inlineSlotSize);
    }

    return externalObject;
}
#endif
/* static */
JsrtExternalObject* JsrtExternalObject::Create(void *data, uint inlineSlotSize, JsFinalizeCallback finalizeCallback, Js::RecyclableObject * prototype, Js::ScriptContext *scriptContext, JsrtExternalType * type)
{
    if (prototype == nullptr)
    {
        prototype = scriptContext->GetLibrary()->GetObjectPrototype();
    }
    if (type == nullptr)
    {
#ifdef _CHAKRACOREBUILD
        type = scriptContext->GetLibrary()->GetCachedJsrtExternalType(0, reinterpret_cast<uintptr_t>(finalizeCallback), reinterpret_cast<uintptr_t>(prototype));
#else
        type = scriptContext->GetLibrary()->GetCachedJsrtExternalType(reinterpret_cast<uintptr_t>(finalizeCallback), reinterpret_cast<uintptr_t>(prototype));
#endif

        if (type == nullptr)
        {
            type = RecyclerNew(scriptContext->GetRecycler(), JsrtExternalType, scriptContext, finalizeCallback, prototype);
#ifdef _CHAKRACOREBUILD
            scriptContext->GetLibrary()->CacheJsrtExternalType(0, reinterpret_cast<uintptr_t>(finalizeCallback), reinterpret_cast<uintptr_t>(prototype), type);
#else
            scriptContext->GetLibrary()->CacheJsrtExternalType(reinterpret_cast<uintptr_t>(finalizeCallback), reinterpret_cast<uintptr_t>(prototype), type);
#endif
        }
    }

    Assert(type->IsJsrtExternal());

    JsrtExternalObject * externalObject;
    if (finalizeCallback != nullptr)
    {
        externalObject = RecyclerNewFinalizedPlus(scriptContext->GetRecycler(), inlineSlotSize, JsrtExternalObject, static_cast<JsrtExternalType*>(type), data, inlineSlotSize);
    }
    else
    {
        externalObject = RecyclerNewPlus(scriptContext->GetRecycler(), inlineSlotSize, JsrtExternalObject, static_cast<JsrtExternalType*>(type), data, inlineSlotSize);
    }

    return externalObject;
}

JsrtExternalObject* JsrtExternalObject::Copy(bool deepCopy)
{
    Recycler* recycler = this->GetRecycler();
    JsrtExternalType* type = this->GetExternalType();
    int inlineSlotSize = this->GetInlineSlotSize();

#ifdef _CHAKRACOREBUILD
    if (type->GetJsTraceCallback() != nullptr)
    {
        return RecyclerNewTrackedPlus(recycler, inlineSlotSize, JsrtExternalObject, this, deepCopy);
    }
#endif

    if (type->GetJsFinalizeCallback() != nullptr)
    {
        return RecyclerNewFinalizedPlus(recycler, inlineSlotSize, JsrtExternalObject, this, deepCopy);
    }

    return RecyclerNewPlus(recycler, inlineSlotSize, JsrtExternalObject, this, deepCopy);
}

void JsrtExternalObject::Mark(Recycler * recycler)
{
#ifdef _CHAKRACOREBUILD
    recycler->SetNeedExternalWrapperTracing();
    JsTraceCallback traceCallback = this->GetExternalType()->GetJsTraceCallback();
    Assert(nullptr != traceCallback);
    JsrtCallbackState scope(nullptr);
    traceCallback(this->GetSlotData());
#else
    Assert(UNREACHED);
#endif
}

void JsrtExternalObject::Finalize(bool isShutdown)
{
    JsFinalizeCallback finalizeCallback = this->GetExternalType()->GetJsFinalizeCallback();
#ifdef _CHAKRACOREBUILD
    Assert(this->GetExternalType()->GetJsTraceCallback() != nullptr || finalizeCallback != nullptr);
#else
    Assert(finalizeCallback != nullptr);
#endif
    if (nullptr != finalizeCallback)
    {
        JsrtCallbackState scope(nullptr);
        finalizeCallback(this->GetSlotData());
    }
}

void JsrtExternalObject::Dispose(bool isShutdown)
{
}

void * JsrtExternalObject::GetSlotData() const
{
    return this->slotType == SlotType::External
        ? unsafe_write_barrier_cast<void *>(this->u.slot)
        : GetInlineSlots();
}

void JsrtExternalObject::SetSlotData(void * data)
{
    this->slotType = SlotType::External;
    this->u.slot = data;
}

int JsrtExternalObject::GetInlineSlotSize() const
{
    return this->slotType == SlotType::External
        ? 0
        : this->u.inlineSlotSize;
}

void * JsrtExternalObject::GetInlineSlots() const
{
    return this->slotType == SlotType::External
        ? nullptr
        : (void *)((uintptr_t)this + sizeof(JsrtExternalObject));
}

Js::DynamicType* JsrtExternalObject::DuplicateType()
{
    return RecyclerNew(this->GetScriptContext()->GetRecycler(), JsrtExternalType,
        this->GetExternalType());
}

#if ENABLE_TTD
TTD::NSSnapObjects::SnapObjectType JsrtExternalObject::GetSnapTag_TTD() const
{
    return TTD::NSSnapObjects::SnapObjectType::SnapExternalObject;
}

void JsrtExternalObject::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
{
    TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<void*, TTD::NSSnapObjects::SnapObjectType::SnapExternalObject>(objData, nullptr);
}
#endif
<|endoftext|>


<commit_before>#include "dg/PointerAnalysis/Pointer.h"
#include "dg/PointerAnalysis/PSNode.h"

#ifndef NDEBUG
#include <iostream>

namespace dg {
namespace pta {

void Pointer::dump() const {
    target->dump();
    std::cout << " + ";
    offset.dump();
}

void Pointer::print() const {
    dump();
    std::cout << "\n";
}

size_t Pointer::hash() const {
    static_assert (sizeof(size_t) == 8, "We relay on 64-bit size_t");

    // we relay on the fact the offsets are usually small. Therefore,
    // cropping them to 4 bytes and putting them together with ID (which is 4 byte)
    // into one uint64_t should not have much collisions... we'll see.
    constexpr unsigned mask = 0xffffffff;
    constexpr unsigned short shift = 32;
    return (static_cast<uint64_t>(target->getID()) << shift) | (*offset && mask);
}

} // namespace pta
} // namespace dg

#endif // not NDEBUG

<commit_msg>Pointer.cpp: fix operation && -> &<commit_after>#include "dg/PointerAnalysis/Pointer.h"
#include "dg/PointerAnalysis/PSNode.h"

#ifndef NDEBUG
#include <iostream>

namespace dg {
namespace pta {

void Pointer::dump() const {
    target->dump();
    std::cout << " + ";
    offset.dump();
}

void Pointer::print() const {
    dump();
    std::cout << "\n";
}

size_t Pointer::hash() const {
    static_assert (sizeof(size_t) == 8, "We relay on 64-bit size_t");

    // we relay on the fact the offsets are usually small. Therefore,
    // cropping them to 4 bytes and putting them together with ID (which is 4 byte)
    // into one uint64_t should not have much collisions... we'll see.
    constexpr unsigned mask = 0xffffffff;
    constexpr unsigned short shift = 32;
    return (static_cast<uint64_t>(target->getID()) << shift) | (*offset & mask);
}

} // namespace pta
} // namespace dg

#endif // not NDEBUG

<|endoftext|>


<commit_before>#ifndef ARABICA_DOM_CONF_TEST_HPP
#define ARABICA_DOM_CONF_TEST_HPP

#include "../CppUnit/framework/TestCase.h"
#include "../CppUnit/framework/TestSuite.h"
#include "../CppUnit/framework/TestCaller.h"

#include <DOM/Simple/DOMImplementation.hpp>

#ifdef ARABICA_WINDOWS
const std::string PATH_PREFIX="../tests/DOM/conformance/files/";
#else
#include "test_path.hpp"
const std::string PATH_PREFIX=test_path;
#endif

template<class string_type, class string_adaptor>
class DOMTestCase : public TestCase
{
public:
  typedef typename Arabica::DOM::Document<string_type, string_adaptor> Document;
  typedef typename Arabica::DOM::Node<string_type, string_adaptor> Node;
  typedef typename Arabica::DOM::NodeList<string_type, string_adaptor> NodeList;
  typedef typename Arabica::DOM::NamedNodeMap<string_type, string_adaptor> NamedNodeMap;

  typedef string_adaptor SA;

  DOMTestCase(std::string name) : TestCase(name)
  {
  } // DOMTestCase

  virtual void runTest() = 0;
  virtual std::string getTargetURI() const = 0;

protected:

  std::string getContentType() const
  {
    return "";
  } // getContentType

  void preload(const std::string& /*contentType*/, const std::string& /*docURI*/, bool /*willBeModified*/) const
  {
  } // preload

  template<class T>
  bool equals(const T& lhs, const T& rhs) const { return lhs == rhs; }

  Document load(const std::string& docURI, bool /*willBeModified*/)
  {
    std::string filename = PATH_PREFIX + docURI + ".xml";

    Arabica::SAX::InputSource<string_type, string_adaptor> is(SA::construct_from_utf8(filename.c_str()));
    Arabica::SAX2DOM::Parser<string_type, string_adaptor> parser;
    parser.parse(is);

    Document d = parser.getDocument();
    if(d == 0)
      assertImplementation(false, "Could not load", -1, filename);

    d.normalize();
    return d;
  } // load

  void assertEquals(int expected, int actual, int lineNo, const char* fileName)
  {
    TestCase::assertEquals((long)expected, (long)actual, lineNo, fileName);
  } // assertEquals
  void assertEquals(const char* expected, const string_type& actual, int lineNo, const char* fileName)
  {
    if(SA::construct_from_utf8(expected) != actual)
      assertImplementation (false, notEqualsMessage(expected, SA::asStdString(actual)), lineNo, fileName);
  } // assertEquals
  void assertEquals(const string_type& expected, const string_type& actual, int lineNo, const char* fileName)
  {
    if(expected != actual)
      assertImplementation (false, notEqualsMessage(SA::asStdString(expected), SA::asStdString(actual)), lineNo, fileName);
  } // assertEquals
  void assertEquals(const std::vector<string_type>& expected, const std::vector<string_type>& actual, int lineNo, const char* fileName)
  {
    std::string e = serialise_vector(expected);
    std::string a = serialise_vector(actual);
    if(e != a)
      assertImplementation (false, notEqualsMessage(e, a), lineNo, fileName);
  } // assertEquals
  void assertSame(const Node& lhs, const Node& rhs, int lineNo, const char* fileName)
  {
    if(lhs != rhs)
      assertImplementation(false, "Nodes should be the same", lineNo, fileName);
  } // assertSame

  void assertSize(int size, const NodeList& l, int lineNo, const char* fileName)
  {
    assertEquals(size, l.getLength(), lineNo, fileName);
  } // assertSize
  void assertSize(int size, const NamedNodeMap& l, int lineNo, const char* fileName)
  {
    assertEquals(size, l.getLength(), lineNo, fileName);
  } // assertSize

  bool isNull(const string_type& actual) { return SA::empty(actual); }
  bool isNull(const Node& actual) { return (actual == 0); }
  bool notNull(const string_type& actual) { return !isNull(actual); }
  bool notNull(const Node& actual) { return !isNull(actual); }

  void assertNull(const string_type& actual, int lineNo, const char* fileName)
  {
    if(!SA::empty(actual))
      assertImplementation(false, "String should be empty", lineNo, fileName);
  } // assertNull
  void assertNull(const Node& actual, int lineNo, const char* fileName)
  {
    if(actual != 0)
      assertImplementation(false, "Node should be null", lineNo, fileName);
  } // assertNull
  void assertNull(const NamedNodeMap& actual, int lineNo, const char* fileName)
  {
    if(actual != 0)
      assertImplementation(false, "NamedNodeMap should be empty", lineNo, fileName);
  } // assertNotNull
  void assertNotNull(const Node& actual, int lineNo, const char* fileName)
  {
    if(actual == 0)
      assertImplementation(false, "Node should not be null", lineNo, fileName);
  } // assertNull
  void assertNotNull(const NamedNodeMap& actual, int lineNo, const char* fileName)
  {
    if(actual == 0)
      assertImplementation(false, "NamedNodeMap should not be empty", lineNo, fileName);
  } // assertNotNull
  void skipIfNull(const Node& actual)
  {
    if(actual == 0)
      throw SkipException(getTargetURI());
  } // skipIfNull
  template<typename T>
  void skipIfNot(const Node& actual)
  {
     bool ok = false;
     try {
       T t = (T)actual;
       ok = true;
     }
     catch(const std::bad_cast&) {
     }
     if(!ok)
       throw SkipException(getTargetURI());
  } // skipIfNot
  void assertURIEquals(const char* /*dummy*/,
                       const char* /*scheme*/,
                       const char* /*path*/,
                       const char* /*host*/,
                       const char* /*file*/,
                       const char* /*name*/,
                       const char* /*query*/,
                       const char* /*fragment*/,
                       bool /*isAbsolute*/,
                       const string_type& /*actual*/)
  {
    assertImplementation(false, "Haven't implemented assertURIEquals yet", -1, getTargetURI());
  } // assertURIEquals

  bool equals(const char* expected, const string_type& actual)
  {
    return (SA::construct_from_utf8(expected) == actual);
  } // equals

  void fail(const char* msg, int lineNo, const char* fileName)
  {
    assertImplementation(false, msg, lineNo, fileName);
  } // fail

private:
  std::string serialise_vector(std::vector<string_type> v)
  {
    std::sort(v.begin(), v.end());
    std::string s;
    typedef typename std::vector<string_type>::const_iterator const_iterator;
    for(const_iterator a = v.begin(), e = v.end(); a != e; ++a)
      s += SA::asStdString(*a);
    return s;
  } // serialise_vector
};

#endif
<commit_msg>Don't normalize after loading the test document.  (OTOH it's gratifying to know that normalization worked properly :) )<commit_after>#ifndef ARABICA_DOM_CONF_TEST_HPP
#define ARABICA_DOM_CONF_TEST_HPP

#include "../CppUnit/framework/TestCase.h"
#include "../CppUnit/framework/TestSuite.h"
#include "../CppUnit/framework/TestCaller.h"

#include <DOM/Simple/DOMImplementation.hpp>

#ifdef ARABICA_WINDOWS
const std::string PATH_PREFIX="../tests/DOM/conformance/files/";
#else
#include "test_path.hpp"
const std::string PATH_PREFIX=test_path;
#endif

template<class string_type, class string_adaptor>
class DOMTestCase : public TestCase
{
public:
  typedef typename Arabica::DOM::Document<string_type, string_adaptor> Document;
  typedef typename Arabica::DOM::Node<string_type, string_adaptor> Node;
  typedef typename Arabica::DOM::NodeList<string_type, string_adaptor> NodeList;
  typedef typename Arabica::DOM::NamedNodeMap<string_type, string_adaptor> NamedNodeMap;

  typedef string_adaptor SA;

  DOMTestCase(std::string name) : TestCase(name)
  {
  } // DOMTestCase

  virtual void runTest() = 0;
  virtual std::string getTargetURI() const = 0;

protected:

  std::string getContentType() const
  {
    return "";
  } // getContentType

  void preload(const std::string& /*contentType*/, const std::string& /*docURI*/, bool /*willBeModified*/) const
  {
  } // preload

  template<class T>
  bool equals(const T& lhs, const T& rhs) const { return lhs == rhs; }

  Document load(const std::string& docURI, bool /*willBeModified*/)
  {
    std::string filename = PATH_PREFIX + docURI + ".xml";

    Arabica::SAX::InputSource<string_type, string_adaptor> is(SA::construct_from_utf8(filename.c_str()));
    Arabica::SAX2DOM::Parser<string_type, string_adaptor> parser;
    parser.parse(is);

    Document d = parser.getDocument();
    if(d == 0)
      assertImplementation(false, "Could not load", -1, filename);

    //d.normalize();
    return d;
  } // load

  void assertEquals(int expected, int actual, int lineNo, const char* fileName)
  {
    TestCase::assertEquals((long)expected, (long)actual, lineNo, fileName);
  } // assertEquals
  void assertEquals(const char* expected, const string_type& actual, int lineNo, const char* fileName)
  {
    if(SA::construct_from_utf8(expected) != actual)
      assertImplementation (false, notEqualsMessage(expected, SA::asStdString(actual)), lineNo, fileName);
  } // assertEquals
  void assertEquals(const string_type& expected, const string_type& actual, int lineNo, const char* fileName)
  {
    if(expected != actual)
      assertImplementation (false, notEqualsMessage(SA::asStdString(expected), SA::asStdString(actual)), lineNo, fileName);
  } // assertEquals
  void assertEquals(const std::vector<string_type>& expected, const std::vector<string_type>& actual, int lineNo, const char* fileName)
  {
    std::string e = serialise_vector(expected);
    std::string a = serialise_vector(actual);
    if(e != a)
      assertImplementation (false, notEqualsMessage(e, a), lineNo, fileName);
  } // assertEquals
  void assertSame(const Node& lhs, const Node& rhs, int lineNo, const char* fileName)
  {
    if(lhs != rhs)
      assertImplementation(false, "Nodes should be the same", lineNo, fileName);
  } // assertSame

  void assertSize(int size, const NodeList& l, int lineNo, const char* fileName)
  {
    assertEquals(size, l.getLength(), lineNo, fileName);
  } // assertSize
  void assertSize(int size, const NamedNodeMap& l, int lineNo, const char* fileName)
  {
    assertEquals(size, l.getLength(), lineNo, fileName);
  } // assertSize

  bool isNull(const string_type& actual) { return SA::empty(actual); }
  bool isNull(const Node& actual) { return (actual == 0); }
  bool notNull(const string_type& actual) { return !isNull(actual); }
  bool notNull(const Node& actual) { return !isNull(actual); }

  void assertNull(const string_type& actual, int lineNo, const char* fileName)
  {
    if(!SA::empty(actual))
      assertImplementation(false, "String should be empty", lineNo, fileName);
  } // assertNull
  void assertNull(const Node& actual, int lineNo, const char* fileName)
  {
    if(actual != 0)
      assertImplementation(false, "Node should be null", lineNo, fileName);
  } // assertNull
  void assertNull(const NamedNodeMap& actual, int lineNo, const char* fileName)
  {
    if(actual != 0)
      assertImplementation(false, "NamedNodeMap should be empty", lineNo, fileName);
  } // assertNotNull
  void assertNotNull(const Node& actual, int lineNo, const char* fileName)
  {
    if(actual == 0)
      assertImplementation(false, "Node should not be null", lineNo, fileName);
  } // assertNull
  void assertNotNull(const NamedNodeMap& actual, int lineNo, const char* fileName)
  {
    if(actual == 0)
      assertImplementation(false, "NamedNodeMap should not be empty", lineNo, fileName);
  } // assertNotNull
  void skipIfNull(const Node& actual)
  {
    if(actual == 0)
      throw SkipException(getTargetURI());
  } // skipIfNull
  template<typename T>
  void skipIfNot(const Node& actual)
  {
     bool ok = false;
     try {
       T t = (T)actual;
       ok = true;
     }
     catch(const std::bad_cast&) {
     }
     if(!ok)
       throw SkipException(getTargetURI());
  } // skipIfNot
  void assertURIEquals(const char* /*dummy*/,
                       const char* /*scheme*/,
                       const char* /*path*/,
                       const char* /*host*/,
                       const char* /*file*/,
                       const char* /*name*/,
                       const char* /*query*/,
                       const char* /*fragment*/,
                       bool /*isAbsolute*/,
                       const string_type& /*actual*/)
  {
    assertImplementation(false, "Haven't implemented assertURIEquals yet", -1, getTargetURI());
  } // assertURIEquals

  bool equals(const char* expected, const string_type& actual)
  {
    return (SA::construct_from_utf8(expected) == actual);
  } // equals

  void fail(const char* msg, int lineNo, const char* fileName)
  {
    assertImplementation(false, msg, lineNo, fileName);
  } // fail

private:
  std::string serialise_vector(std::vector<string_type> v)
  {
    std::sort(v.begin(), v.end());
    std::string s;
    typedef typename std::vector<string_type>::const_iterator const_iterator;
    for(const_iterator a = v.begin(), e = v.end(); a != e; ++a)
      s += SA::asStdString(*a);
    return s;
  } // serialise_vector
};

#endif
<|endoftext|>