<commit_before>/*!
  \copyright (c) RDO-Team, 2011
  \file      rdo_random_distribution.cpp
  \author    Лущан Дмитрий (dluschan@rk9.bmstu.ru)
  \date      02.08.2011
  \brief     Датчики псевдослучайных чисел
  \indent    4T
*/

// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "rdo_random_distribution.h"
#include "simulator/runtime/rdo_value.h"
// --------------------------------------------------------------------------------

OPEN_RDO_RUNTIME_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- RandGenerator
// --------------------------------------------------------------------------------
RandGenerator::RandGenerator(long int seed)
	: m_seed(seed)
{}

RandGenerator::~RandGenerator()
{}

void RandGenerator::setSeed(long int seed)
{
	m_seed = seed;
}

double RandGenerator::u01()
{
#ifdef RDO_NATIVE_U01
	m_seed = m_seed * 69069 + 1;
	return m_seed / 4294967296.0;
#else
	const long int MODLUS = 2147483647;
	const long int MULT1  = 24112;
	const long int MULT2  = 26143;
	long int zi = m_seed;
	long int lowprd = (zi & 65535) * MULT1;
	long int hi31   = (zi >> 16) * MULT1 + (lowprd >> 16);
	zi = ((lowprd & 65535) - MODLUS) + ((hi31 & 32767) << 16) + (hi31 >> 15);
	if (zi < 0) zi += MODLUS;
	lowprd = (zi & 65535) * MULT2;
	hi31 = (zi >> 16) * MULT2 + (lowprd >> 16);
	zi = ((lowprd & 65535) - MODLUS) + ((hi31 & 32767) << 16) + (hi31 >> 15);
	if (zi < 0) zi += MODLUS;
	m_seed = zi;
	//return ((zi >> 7) + 1) / 16777216.0;     // Так в примере на FORTRAN imho
	return (((zi >> 7) | 1) + 1) / 16777216.0; // Так в примере на C
#endif
}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorUniform
// --------------------------------------------------------------------------------
RandGeneratorUniform::RandGeneratorUniform(long int seed)
	: RandGenerator(seed)
{}

double RandGeneratorUniform::next(double from, double to)
{
	return u01() * (to - from) + from;
}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorExponential
// --------------------------------------------------------------------------------
RandGeneratorExponential::RandGeneratorExponential(long int seed)
	: RandGenerator(seed)
{}

double RandGeneratorExponential::next(double math)
{
	return -log(u01()) * math;
}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorNormal
// --------------------------------------------------------------------------------
RandGeneratorNormal::RandGeneratorNormal(long int seed)
	: RandGenerator(seed)
{}

double RandGeneratorNormal::next(double av, double var)
{
	double ran = 0;
	for (int i = 0; i < 12; ++i)
	{
		ran += u01();
	}
	return var * (ran - 6) + av;
}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorTriangular
// --------------------------------------------------------------------------------
RandGeneratorTriangular::RandGeneratorTriangular(long int seed)
	: RandGenerator(seed)
{}

double RandGeneratorTriangular::next(double from, double top, double to)
{
	double result;
	if (u01() > (top-from)/(to-from))
	{
		result = -(to-top)*(sqrt(u01()) - 1);
	}
	else
	{
		result = (top-from)*(sqrt(u01()) - 1);
	}
	return result + top;
}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorCommonNext
// --------------------------------------------------------------------------------
RandGeneratorCommonNext::RandGeneratorCommonNext()
{}

RandGeneratorCommonNext::~RandGeneratorCommonNext()
{}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorByHist
// --------------------------------------------------------------------------------
RandGeneratorByHist::RandGeneratorByHist(long int seed)
	: RandGeneratorUniform   (seed)
	, RandGeneratorCommonNext(    )
	, summ                   (0   )
{}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorByHistReal
// --------------------------------------------------------------------------------
RandGeneratorByHistReal::RandGeneratorByHistReal(long int seed)
	: RandGeneratorByHist(seed)
{}

void RandGeneratorByHistReal::addValues(double from, double to, double freq)
{
	m_from.push_back(from);
	m_to.push_back  (to  );
	m_freq.push_back(freq);
	summ += freq;
}

RDOValue RandGeneratorByHistReal::next()
{
	double ran1 = RandGeneratorUniform::next(0, summ);
	double add = 0;
	std::vector<double>::size_type i;
	for (i = 0; i < m_freq.size() - 1; ++i)
	{
		if (ran1 < m_freq[i] + add) break;
		add += m_freq[i];
	}
	return RandGeneratorUniform::next(m_from[i], m_to[i]);
}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorByHistEnum
// --------------------------------------------------------------------------------
RandGeneratorByHistEnum::RandGeneratorByHistEnum(long int seed)
	: RandGeneratorByHist(seed)
{}

void RandGeneratorByHistEnum::addValues(RDOValue val, double freq)
{
	m_vals.push_back(val);
	m_freq.push_back(freq);
	summ += freq;
}

RDOValue RandGeneratorByHistEnum::next()
{
	double ran1 = RandGeneratorUniform::next(0, summ);
	double add = 0;
	std::vector<double>::size_type i;
	for (i = 0; i < m_freq.size() - 1; ++i)
	{
		if (ran1 < m_freq[i] + add) break;
		add += m_freq[i];
	}
	return m_vals[i];
}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorEnumerative
// --------------------------------------------------------------------------------
RandGeneratorEnumerative::RandGeneratorEnumerative()
	: RandGeneratorCommonNext( )
	, m_curr                 (0)
{}

RandGeneratorEnumerative::~RandGeneratorEnumerative()
{}

void RandGeneratorEnumerative::addValue(RDOValue val)
{
	m_vals.push_back(val);
}

RDOValue RandGeneratorEnumerative::next()
{
	RDOValue res = m_vals[m_curr++];
	if (m_curr >= m_vals.size()) m_curr = 0;
	return res;
}

CLOSE_RDO_RUNTIME_NAMESPACE
<commit_msg>pch added<commit_after>/*!
  \copyright (c) RDO-Team, 2011
  \file      rdo_random_distribution.cpp
  \author    Лущан Дмитрий (dluschan@rk9.bmstu.ru)
  \date      02.08.2011
  \brief     Датчики псевдослучайных чисел
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/runtime/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "rdo_random_distribution.h"
#include "simulator/runtime/rdo_value.h"
// --------------------------------------------------------------------------------

OPEN_RDO_RUNTIME_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- RandGenerator
// --------------------------------------------------------------------------------
RandGenerator::RandGenerator(long int seed)
	: m_seed(seed)
{}

RandGenerator::~RandGenerator()
{}

void RandGenerator::setSeed(long int seed)
{
	m_seed = seed;
}

double RandGenerator::u01()
{
#ifdef RDO_NATIVE_U01
	m_seed = m_seed * 69069 + 1;
	return m_seed / 4294967296.0;
#else
	const long int MODLUS = 2147483647;
	const long int MULT1  = 24112;
	const long int MULT2  = 26143;
	long int zi = m_seed;
	long int lowprd = (zi & 65535) * MULT1;
	long int hi31   = (zi >> 16) * MULT1 + (lowprd >> 16);
	zi = ((lowprd & 65535) - MODLUS) + ((hi31 & 32767) << 16) + (hi31 >> 15);
	if (zi < 0) zi += MODLUS;
	lowprd = (zi & 65535) * MULT2;
	hi31 = (zi >> 16) * MULT2 + (lowprd >> 16);
	zi = ((lowprd & 65535) - MODLUS) + ((hi31 & 32767) << 16) + (hi31 >> 15);
	if (zi < 0) zi += MODLUS;
	m_seed = zi;
	//return ((zi >> 7) + 1) / 16777216.0;     // Так в примере на FORTRAN imho
	return (((zi >> 7) | 1) + 1) / 16777216.0; // Так в примере на C
#endif
}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorUniform
// --------------------------------------------------------------------------------
RandGeneratorUniform::RandGeneratorUniform(long int seed)
	: RandGenerator(seed)
{}

double RandGeneratorUniform::next(double from, double to)
{
	return u01() * (to - from) + from;
}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorExponential
// --------------------------------------------------------------------------------
RandGeneratorExponential::RandGeneratorExponential(long int seed)
	: RandGenerator(seed)
{}

double RandGeneratorExponential::next(double math)
{
	return -log(u01()) * math;
}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorNormal
// --------------------------------------------------------------------------------
RandGeneratorNormal::RandGeneratorNormal(long int seed)
	: RandGenerator(seed)
{}

double RandGeneratorNormal::next(double av, double var)
{
	double ran = 0;
	for (int i = 0; i < 12; ++i)
	{
		ran += u01();
	}
	return var * (ran - 6) + av;
}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorTriangular
// --------------------------------------------------------------------------------
RandGeneratorTriangular::RandGeneratorTriangular(long int seed)
	: RandGenerator(seed)
{}

double RandGeneratorTriangular::next(double from, double top, double to)
{
	double result;
	if (u01() > (top-from)/(to-from))
	{
		result = -(to-top)*(sqrt(u01()) - 1);
	}
	else
	{
		result = (top-from)*(sqrt(u01()) - 1);
	}
	return result + top;
}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorCommonNext
// --------------------------------------------------------------------------------
RandGeneratorCommonNext::RandGeneratorCommonNext()
{}

RandGeneratorCommonNext::~RandGeneratorCommonNext()
{}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorByHist
// --------------------------------------------------------------------------------
RandGeneratorByHist::RandGeneratorByHist(long int seed)
	: RandGeneratorUniform   (seed)
	, RandGeneratorCommonNext(    )
	, summ                   (0   )
{}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorByHistReal
// --------------------------------------------------------------------------------
RandGeneratorByHistReal::RandGeneratorByHistReal(long int seed)
	: RandGeneratorByHist(seed)
{}

void RandGeneratorByHistReal::addValues(double from, double to, double freq)
{
	m_from.push_back(from);
	m_to.push_back  (to  );
	m_freq.push_back(freq);
	summ += freq;
}

RDOValue RandGeneratorByHistReal::next()
{
	double ran1 = RandGeneratorUniform::next(0, summ);
	double add = 0;
	std::vector<double>::size_type i;
	for (i = 0; i < m_freq.size() - 1; ++i)
	{
		if (ran1 < m_freq[i] + add) break;
		add += m_freq[i];
	}
	return RandGeneratorUniform::next(m_from[i], m_to[i]);
}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorByHistEnum
// --------------------------------------------------------------------------------
RandGeneratorByHistEnum::RandGeneratorByHistEnum(long int seed)
	: RandGeneratorByHist(seed)
{}

void RandGeneratorByHistEnum::addValues(RDOValue val, double freq)
{
	m_vals.push_back(val);
	m_freq.push_back(freq);
	summ += freq;
}

RDOValue RandGeneratorByHistEnum::next()
{
	double ran1 = RandGeneratorUniform::next(0, summ);
	double add = 0;
	std::vector<double>::size_type i;
	for (i = 0; i < m_freq.size() - 1; ++i)
	{
		if (ran1 < m_freq[i] + add) break;
		add += m_freq[i];
	}
	return m_vals[i];
}

// --------------------------------------------------------------------------------
// -------------------- RandGeneratorEnumerative
// --------------------------------------------------------------------------------
RandGeneratorEnumerative::RandGeneratorEnumerative()
	: RandGeneratorCommonNext( )
	, m_curr                 (0)
{}

RandGeneratorEnumerative::~RandGeneratorEnumerative()
{}

void RandGeneratorEnumerative::addValue(RDOValue val)
{
	m_vals.push_back(val);
}

RDOValue RandGeneratorEnumerative::next()
{
	RDOValue res = m_vals[m_curr++];
	if (m_curr >= m_vals.size()) m_curr = 0;
	return res;
}

CLOSE_RDO_RUNTIME_NAMESPACE
<|endoftext|>


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

// sg
#include "SceneGraph.h"
#include "sg/common/Texture2D.h"
#include "sg/geometry/TriangleMesh.h"
// xml lib
#include "ospcommon/xml/XML.h"
// std
#include <fstream>
#include <set>

namespace ospray {
  namespace sg {

    void warnIgnore(const std::string &nodeType)
    {
      static std::set<std::string> alreadyWarned;
      if (alreadyWarned.find(nodeType) != alreadyWarned.end())
        return;

      alreadyWarned.insert(nodeType);
      std::cout << "#importer::X3D: ignoring node type " << nodeType
                << " (more instances may follow)"
                << std::endl;

    }

    static const char *delim = "\n\t\r, ";

    vec3f parseVec3f(char * &tok)
    {
      vec3f v;
      v.x = atof(tok);

      tok = strtok(NULL,delim);
      if (!tok) return v;
      v.y = atof(tok);

      tok = strtok(NULL,delim);
      if (!tok) return v;
      v.z = atof(tok);

      tok = strtok(NULL,delim);
      return v;
    }

    void parseVectorOfVec3fas(std::vector<vec3fa> &vec, const std::string &str)
    {
      char *s = strdup(str.c_str());
      char *tok = strtok(s,delim);
      while (tok)
        vec.push_back(parseVec3f(tok));
      free(s);
    }

    void parseVectorOfVec3fs(std::vector<vec3f> &vec, const std::string &str)
    {
      char *s = strdup(str.c_str());
      char *tok = strtok(s,delim);
      while (tok)
        vec.push_back(parseVec3f(tok));
      free(s);
    }

    void parseVectorOfColors(std::vector<vec4f> &vec, const std::string &str)
    {
      char *s = strdup(str.c_str());
      char *tok = strtok(s,delim);
      while (tok)
        vec.push_back(vec4f(parseVec3f(tok), 1.f));
      free(s);
    }

    void parseIndexedFaceSet(const std::shared_ptr<Node> model,
                             const affine3f &xfm, const xml::Node &root)
    {
      std::string name = "x3d mesh";
      auto mesh = createNode(name, "TriangleMesh")->nodeAs<TriangleMesh>();
      auto v = createNode("vertex", "DataVector3f")->nodeAs<DataVector3f>();
      mesh->add(v);

      auto vi = createNode("index", "DataVector3i")->nodeAs<DataVector3i>();
      mesh->add(vi);

      // -------------------------------------------------------
      // parse coordinate indices
      // -------------------------------------------------------
      std::string coordIndex = root.getProp("coordIndex");
      assert(coordIndex != "");

      char *s = strdup(coordIndex.c_str()); coordIndex = "";
      char *tok = strtok(s,delim);
      std::vector<int> ID;
      while (tok) {
        long thisID = atol(tok);
        if (thisID == -1) {
          for (size_t i = 2; i < ID.size(); i++) {
            vec3i t;
            t.x = ID[0];
            t.y = ID[i-1];
            t.z = ID[i];
            vi->v.push_back(t);
          }
          ID.clear();
        } else {
          ID.push_back(thisID);
        }
        tok = strtok(NULL,delim);
      }
      free(s);

      // -------------------------------------------------------
      // now, parse children for vertex arrays
      // -------------------------------------------------------
      for (auto &node : root.child) {
        if (node.name == "Coordinate") {
          parseVectorOfVec3fs(v->v,node.getProp("point"));
        } else if (node.name == "Normal") {
          parseVectorOfVec3fs(v->v,node.getProp("vector"));
        } else if (node.name == "Color") {
          // parseVectorOfColors(mesh->color,node.getProp("color"));
        } else {
          std::cout << "importX3D: unknown child type '" << node.name
                    << "' to 'IndexedFaceSet' node\n";
        }
      }

      model->add(mesh);
    }

    void parseShape(const std::shared_ptr<Node> model,
                    const affine3f &xfm,
                    const xml::Node &root)
    {
      for (auto &node : root.child) {
        if (node.name == "Appearance") {
          /* ignore for now */
          warnIgnore("'Appearance' (in Shape)");
        } else if (node.name == "IndexedLineSet") {
          /* ignore for now */
          warnIgnore("'IndexedLineSet' (in Shape)");
        } else if (node.name == "IndexedFaceSet") {
          /* ignore for now */
          parseIndexedFaceSet(model,xfm,node);
        } else {
          throw std::runtime_error("importX3D: unknown child type '"
                                   + node.name + "' to 'Shape' node");
        }
      }
    }

    void parseGroup(const std::shared_ptr<Node> model,
                    const affine3f &xfm,
                    const xml::Node &root)
    {
      for (auto &node : root.child) {
        if (node.name == "Appearance") {
          /* ignore for now */
          warnIgnore("'Appearance' (in Shape)");
        } else if (node.name == "Shape") {
          parseShape(model,xfm,node);
        } else {
          throw std::runtime_error("importX3D: unknown child type '"+node.name+"' to 'Group' node");
        }
      }
    }

    void parseTransform(const std::shared_ptr<Node> model,
                        const affine3f &parentXFM, const xml::Node &root)
    {
      affine3f xfm = parentXFM;

      for (auto &node : root.child) {
        if (node.name == "DirectionalLight") {
          /* ignore */
          warnIgnore("'DirectionalLight' (in Transform node)");
        } else if (node.name == "Transform") {
          parseTransform(model,xfm,node);
        } else if (node.name == "Shape") {
          parseShape(model,xfm,node);
        } else if (node.name == "Group") {
          parseGroup(model,xfm,node);
        } else {
          throw std::runtime_error("importX3D: unknown 'transform' child type '"
                                   + node.name + "'");
        }
      }
    }

    void parseX3D(const std::shared_ptr<Node> model, const xml::Node &root)
    {
      for (auto &node : root.child) {
        if (node.name == "Background") {
          /* ignore */
          warnIgnore("'Background' (in root node)");
        } else if (node.name == "Viewpoint") {
          /* ignore */
          warnIgnore("'Viewpoint' (in root node)");
        } else if (node.name == "NavigationInfo") {
          /* ignore */
          warnIgnore("'NavigationInfo' (in root node)");
        } else if (node.name == "DirectionalLight") {
          /* ignore */
          warnIgnore("'DirectionalLight' (in root node)");
        } else if (node.name == "Transform") {
          affine3f xfm = ospcommon::one;
          parseTransform(model,xfm,node);
          /* ignore */
        } else {
          throw std::runtime_error("importX3D: unknown node type '"+node.name+"'");
        }
      }
    }

    /*! import an X3D model, as forexample a ParaView contour exported
      using ParaView's X3D exporter */
    OSPSG_INTERFACE void importX3D(const std::shared_ptr<Node> &world,
                                   const FileName &fileName)
    {
      std::shared_ptr<xml::XMLDoc> doc = xml::readXML(fileName);
      assert(doc);
      const xml::Node &root_element = doc->child[0];
      PRINT(root_element.name);
      for (auto &node : root_element.child) {
        if (node.name == "head") {
          /* ignore meta data for now */
        } else if (node.name == "Scene") {
          parseX3D(world,node);
        } else {
          throw std::runtime_error("unknown X3D root element "+node.name);
        }
      }
    }

    OSPSG_REGISTER_IMPORT_FUNCTION(importX3D, x3d);

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

// sg
#include "SceneGraph.h"
#include "sg/common/Texture2D.h"
#include "sg/geometry/TriangleMesh.h"
// xml lib
#include "ospcommon/xml/XML.h"
// std
#include <fstream>
#include <set>

namespace ospray {
  namespace sg {

    void warnIgnore(const std::string &nodeType)
    {
      static std::set<std::string> alreadyWarned;
      if (alreadyWarned.find(nodeType) != alreadyWarned.end())
        return;

      alreadyWarned.insert(nodeType);
      std::cout << "#importer::X3D: ignoring node type " << nodeType
                << " (more instances may follow)"
                << std::endl;

    }

    static const char *delim = "\n\t\r, ";

    vec3f parseVec3f(char * &tok)
    {
      vec3f v;
      v.x = atof(tok);

      tok = strtok(NULL,delim);
      if (!tok) return v;
      v.y = atof(tok);

      tok = strtok(NULL,delim);
      if (!tok) return v;
      v.z = atof(tok);

      tok = strtok(NULL,delim);
      return v;
    }

    void parseVectorOfVec3fas(std::vector<vec3fa> &vec, const std::string &str)
    {
      char *s = strdup(str.c_str());
      char *tok = strtok(s,delim);
      while (tok)
        vec.push_back(parseVec3f(tok));
      free(s);
    }

    void parseVectorOfVec3fs(std::vector<vec3f> &vec, const std::string &str)
    {
      char *s = strdup(str.c_str());
      char *tok = strtok(s,delim);
      while (tok)
        vec.push_back(parseVec3f(tok));
      free(s);
    }

    void parseVectorOfColors(std::vector<vec4f> &vec, const std::string &str)
    {
      char *s = strdup(str.c_str());
      char *tok = strtok(s,delim);
      while (tok)
        vec.push_back(vec4f(parseVec3f(tok), 1.f));
      free(s);
    }

    void parseIndexedFaceSet(const std::shared_ptr<Node> model,
                             const affine3f &/*xfm*/, const xml::Node &root)
    {
      std::string name = "x3d mesh";
      auto mesh = createNode(name, "TriangleMesh")->nodeAs<TriangleMesh>();
      auto v = createNode("vertex", "DataVector3f")->nodeAs<DataVector3f>();
      mesh->add(v);

      auto vi = createNode("index", "DataVector3i")->nodeAs<DataVector3i>();
      mesh->add(vi);

      // -------------------------------------------------------
      // parse coordinate indices
      // -------------------------------------------------------
      std::string coordIndex = root.getProp("coordIndex");
      assert(coordIndex != "");

      char *s = strdup(coordIndex.c_str()); coordIndex = "";
      char *tok = strtok(s,delim);
      std::vector<int> ID;
      while (tok) {
        long thisID = atol(tok);
        if (thisID == -1) {
          for (size_t i = 2; i < ID.size(); i++) {
            vec3i t;
            t.x = ID[0];
            t.y = ID[i-1];
            t.z = ID[i];
            vi->v.push_back(t);
          }
          ID.clear();
        } else {
          ID.push_back(thisID);
        }
        tok = strtok(NULL,delim);
      }
      free(s);

      // -------------------------------------------------------
      // now, parse children for vertex arrays
      // -------------------------------------------------------
      for (auto &node : root.child) {
        if (node.name == "Coordinate") {
          parseVectorOfVec3fs(v->v,node.getProp("point"));
        } else if (node.name == "Normal") {
          parseVectorOfVec3fs(v->v,node.getProp("vector"));
        } else if (node.name == "Color") {
          // parseVectorOfColors(mesh->color,node.getProp("color"));
        } else {
          std::cout << "importX3D: unknown child type '" << node.name
                    << "' to 'IndexedFaceSet' node\n";
        }
      }

      model->add(mesh);
    }

    void parseShape(const std::shared_ptr<Node> model,
                    const affine3f &xfm,
                    const xml::Node &root)
    {
      for (auto &node : root.child) {
        if (node.name == "Appearance") {
          /* ignore for now */
          warnIgnore("'Appearance' (in Shape)");
        } else if (node.name == "IndexedLineSet") {
          /* ignore for now */
          warnIgnore("'IndexedLineSet' (in Shape)");
        } else if (node.name == "IndexedFaceSet") {
          /* ignore for now */
          parseIndexedFaceSet(model,xfm,node);
        } else {
          throw std::runtime_error("importX3D: unknown child type '"
                                   + node.name + "' to 'Shape' node");
        }
      }
    }

    void parseGroup(const std::shared_ptr<Node> model,
                    const affine3f &xfm,
                    const xml::Node &root)
    {
      for (auto &node : root.child) {
        if (node.name == "Appearance") {
          /* ignore for now */
          warnIgnore("'Appearance' (in Shape)");
        } else if (node.name == "Shape") {
          parseShape(model,xfm,node);
        } else {
          throw std::runtime_error("importX3D: unknown child type '"+node.name+"' to 'Group' node");
        }
      }
    }

    void parseTransform(const std::shared_ptr<Node> model,
                        const affine3f &parentXFM, const xml::Node &root)
    {
      affine3f xfm = parentXFM;

      for (auto &node : root.child) {
        if (node.name == "DirectionalLight") {
          /* ignore */
          warnIgnore("'DirectionalLight' (in Transform node)");
        } else if (node.name == "Transform") {
          parseTransform(model,xfm,node);
        } else if (node.name == "Shape") {
          parseShape(model,xfm,node);
        } else if (node.name == "Group") {
          parseGroup(model,xfm,node);
        } else {
          throw std::runtime_error("importX3D: unknown 'transform' child type '"
                                   + node.name + "'");
        }
      }
    }

    void parseX3D(const std::shared_ptr<Node> model, const xml::Node &root)
    {
      for (auto &node : root.child) {
        if (node.name == "Background") {
          /* ignore */
          warnIgnore("'Background' (in root node)");
        } else if (node.name == "Viewpoint") {
          /* ignore */
          warnIgnore("'Viewpoint' (in root node)");
        } else if (node.name == "NavigationInfo") {
          /* ignore */
          warnIgnore("'NavigationInfo' (in root node)");
        } else if (node.name == "DirectionalLight") {
          /* ignore */
          warnIgnore("'DirectionalLight' (in root node)");
        } else if (node.name == "Transform") {
          affine3f xfm = ospcommon::one;
          parseTransform(model,xfm,node);
          /* ignore */
        } else {
          throw std::runtime_error("importX3D: unknown node type '"+node.name+"'");
        }
      }
    }

    /*! import an X3D model, as forexample a ParaView contour exported
      using ParaView's X3D exporter */
    OSPSG_INTERFACE void importX3D(const std::shared_ptr<Node> &world,
                                   const FileName &fileName)
    {
      std::shared_ptr<xml::XMLDoc> doc = xml::readXML(fileName);
      assert(doc);
      const xml::Node &root_element = doc->child[0];
      PRINT(root_element.name);
      for (auto &node : root_element.child) {
        if (node.name == "head") {
          /* ignore meta data for now */
        } else if (node.name == "Scene") {
          parseX3D(world,node);
        } else {
          throw std::runtime_error("unknown X3D root element "+node.name);
        }
      }
    }

    OSPSG_REGISTER_IMPORT_FUNCTION(importX3D, x3d);

  }  // ::ospray::sg
}  // ::ospray
<|endoftext|>


<commit_before>//
// Created by peter on 4/5/15.
//

#include "Solver.h"
#include "Logger.h"

Solver::Solver(const BoardPtr& board, const DictionaryPtr& dictionary, const std::vector<int>& wordLengths)
        : board_(board), dictionary_(dictionary), wordLengths_(wordLengths), queue_()
{ }

void Solver::solve() {
    Logger::instance().log("[Solver::solve] begin");

    initializeQueue();
    printQueue();

    int safetyCounter = 0;
    int MAX_LOOPS = 500;
    std::vector<std::string> finalWordsFound;

    while (!queue_.empty() && safetyCounter < MAX_LOOPS) {
        Logger::instance().log("----- BEGIN ONE ITERATION -----");
        const StatePtr& state = queue_.front();
        Logger::instance().log("### POPPED STATE ###");
        Logger::instance().log(*state);
        Logger::instance().log("### END POPPED STATE ###");

        std::string word = state->getCurrentWord();
        const BoardPtr& board = state->getBoard();
        std::vector<std::string> wordsCompleted(state->getWordsCompleted());
        int currX = state->getX();
        int currY = state->getY();
        int dim = board->dim();
        const Tile& tile = const_cast<const Board&>(*board).getTile(currX, currY);

        word += ::tolower(tile.getValue());
        Logger::instance().log("Checking word: ", word);
        bool foundWord = dictionary_->check(word);
        if (foundWord) {
            int counter = 0;
            for (int i = 0; i < dim; ++i) {
                for (int j = 0; j < dim; ++j) {
                    if (const_cast<const Board&>(*board).getTile(i, j).isActive()) { ++counter; }
                }
            }
            if (counter <= 1) {
                Logger::instance().log("Finished state: ", *state);
                finalWordsFound = wordsCompleted;
                finalWordsFound.push_back(word);
                break;
            }
            Logger::instance().log("Found word: ", word);
        }

        std::vector<std::pair<int, int> > nextMoves(std::move(generateMoves(currX, currY, dim)));

        {
            Logger::instance().log("...generated moves...");
            for (auto &it: nextMoves) {
                Logger::instance().log("(", it.first, ",", it.second, ")");
            }
            Logger::instance().log("...end generated moves...");
        }

        BoardPtr newBoard = BoardPtr(new Board(*board));
        newBoard->useTile(currX, currY);
        simplifyBoard(newBoard);

        Logger::instance().log("After simplify:\n", *newBoard);

        for (auto& move : nextMoves) {
            if (const_cast<const Board&>(*newBoard).getTile(move.first, move.second).isActive()) {
                StatePtr newState(new State(newBoard, wordsCompleted, word, move.first, move.second));
                Logger::instance().log("Adding state:\n", *newState);

                queue_.push_back(std::move(newState));
            } else {
                Logger::instance().log("Skipping square (", move.first, ",", move.second, ")");
            }
        }

        if (foundWord) {
            // create states using the word we found
            std::vector<std::string> wordsCompletedWithNew(wordsCompleted);
            wordsCompletedWithNew.push_back(word);
            for (int x = dim - 1; x >= 0; --x) {
                for (int y = 0; y < dim; ++y) {
                    if (const_cast<const Board&>(*newBoard).getTile(x, y).isUsed()) {
                        newBoard->setTileToEmpty(x, y);
                    }
                }
            }
            simplifyBoard(newBoard);
            std::string newWord;
            for (auto& move : nextMoves) {
                queue_.push_back(StatePtr(new State(newBoard, wordsCompletedWithNew, newWord, move.first, move.second)));
            }
        }

        queue_.pop_front();
        ++safetyCounter;
        Logger::instance().log("----- END ITERATION(", safetyCounter, ") -----");
    }

    if (queue_.empty()) {
        Logger::instance().log("Unable to find solution!");
    } else {
        Logger::instance().log("FINISHED");
        Logger::instance().log("words: ");
        for (auto& it : finalWordsFound) {
            Logger::instance().log(it);
        }
    }

    Logger::instance().log("[Solver::solve] end");
}

void Solver::simplifyBoard(BoardPtr& board) {
    int dim = board->dim();
    for (int x = (dim - 1); x >= 0; --x) {
        for (int y = (dim -1); y >= 0; --y) {
            if (const_cast<const Board&>(*board).getTile(x, y).isEmpty()) {
                char val = -1;
                // check if any tiles above to drop down
                for (int i = y; i >= 0; --i) {
                    if (!const_cast<const Board&>(*board).getTile(x, i).isEmpty()) {
                        val = const_cast<const Board&>(*board).getTile(x, i).getValue();
                        board->setTileToEmpty(x, i);
                        break;
                    }
                }

                if (val == -1) {
                    board->setTileToEmpty(x, y);
                } else {
                    board->setTile(x, y, val);
                }
            }
        }
    }
}

void Solver::initializeQueue() {
    // initialize with beginning states
    std::vector<std::string> blank;
    std::string blankWord;
    for (int x = 0; x < board_->dim(); ++x) {
        for (int y = 0; y < board_->dim(); ++y) {
            StatePtr state(new State(board_, blank, blankWord, x, y));
            queue_.push_back(std::move(state));
        }
    }
}

void Solver::printQueue() {
    std::cout << "=== QUEUE ===" << "\n\n";
    for (auto& it : queue_) {
        std::cout << *it << std::endl;
    }
    std::cout << "=== \\QUEUE\\ ===" << "\n\n";
}

std::vector<std::pair<int, int> > Solver::generateMoves(int currX, int currY, int dim) {
    std::vector<std::pair<int, int> > nextMoves;
    if (currX > 0) {
        if (currY > 0) {
            nextMoves.emplace_back(currX-1, currY-1);
        }
        if (currY < (dim - 1)) {
            nextMoves.emplace_back(currX-1, currY+1);
        }
        nextMoves.emplace_back(currX-1, currY);
    }
    if (currX < (dim - 1)) {
        if (currY > 0) {
            nextMoves.emplace_back(currX+1, currY-1);
        }
        if (currY < (dim - 1)) {
            nextMoves.emplace_back(currX+1, currY+1);
        }
        nextMoves.emplace_back(currX+1, currY);
    }
    if (currY > 0) {
        nextMoves.emplace_back(currX, currY-1);
    }
    if (currY < (dim - 1)) {
        nextMoves.emplace_back(currX, currY+1);
    }
    return nextMoves;
}
<commit_msg>Solves medium.board<commit_after>//
// Created by peter on 4/5/15.
//

#include "Solver.h"
#include "Logger.h"

Solver::Solver(const BoardPtr& board, const DictionaryPtr& dictionary, const std::vector<int>& wordLengths)
        : board_(board), dictionary_(dictionary), wordLengths_(wordLengths), queue_()
{ }

void Solver::solve() {
    Logger::instance().log("[Solver::solve] begin");

    initializeQueue();
    printQueue();

    int safetyCounter = 0;
    int MAX_LOOPS = 50000;
    std::vector<std::string> finalWordsFound;

    while (!queue_.empty() && safetyCounter < MAX_LOOPS) {
        Logger::instance().log("----- BEGIN ONE ITERATION -----");
        const StatePtr& state = queue_.front();
        Logger::instance().log("### POPPED STATE ###");
        Logger::instance().log(*state);
        Logger::instance().log("### END POPPED STATE ###");

        std::string word = state->getCurrentWord();
        const BoardPtr& board = state->getBoard();
        std::vector<std::string> wordsCompleted(state->getWordsCompleted());
        int currX = state->getX();
        int currY = state->getY();
        int dim = board->dim();
        const Tile& tile = const_cast<const Board&>(*board).getTile(currX, currY);

        word += ::tolower(tile.getValue());
        Logger::instance().log("Checking word: ", word);
        bool foundWord = dictionary_->check(word);
        if (foundWord) {
            int counter = 0;
            for (int i = 0; i < dim; ++i) {
                for (int j = 0; j < dim; ++j) {
                    if (const_cast<const Board&>(*board).getTile(i, j).isActive()) { ++counter; }
                }
            }
            if (counter <= 1) {
                Logger::instance().log("Finished state: ", *state);
                finalWordsFound = wordsCompleted;
                finalWordsFound.push_back(word);
                break;
            }
            Logger::instance().log("Found word: ", word);
        }

        std::vector<std::pair<int, int> > nextMoves(std::move(generateMoves(currX, currY, dim)));

        {
            Logger::instance().log("...generated moves...");
            for (auto &it: nextMoves) {
                Logger::instance().log("(", it.first, ",", it.second, ")");
            }
            Logger::instance().log("...end generated moves...");
        }

        BoardPtr newBoard = BoardPtr(new Board(*board));
        newBoard->useTile(currX, currY);
        simplifyBoard(newBoard);

        Logger::instance().log("After simplify:\n", *newBoard);

        for (auto& move : nextMoves) {
            if (const_cast<const Board&>(*newBoard).getTile(move.first, move.second).isActive()) {
                StatePtr newState(new State(newBoard, wordsCompleted, word, move.first, move.second));
                Logger::instance().log("Adding state:\n", *newState);

                queue_.push_back(std::move(newState));
            } else {
                Logger::instance().log("Skipping square (", move.first, ",", move.second, ")");
            }
        }

        if (foundWord) {
            // create states using the word we found
            std::vector<std::string> wordsCompletedWithNew(wordsCompleted);
            wordsCompletedWithNew.push_back(word);
            for (int x = dim - 1; x >= 0; --x) {
                for (int y = 0; y < dim; ++y) {
                    if (const_cast<const Board&>(*newBoard).getTile(x, y).isUsed()) {
                        newBoard->setTileToEmpty(x, y);
                    }
                }
            }
            simplifyBoard(newBoard);
            std::string newWord;
            for (auto& move : nextMoves) {
                queue_.push_back(StatePtr(new State(newBoard, wordsCompletedWithNew, newWord, move.first, move.second)));
            }
        }

        queue_.pop_front();
        ++safetyCounter;
        Logger::instance().log("----- END ITERATION(", safetyCounter, ") -----");
    }

    if (queue_.empty()) {
        Logger::instance().log("Unable to find solution!");
    } else if (safetyCounter > MAX_LOOPS) {
        Logger::instance().log("Not enough iterations");
    } else {
        Logger::instance().log("FINISHED");
        Logger::instance().log("words: ");
        for (auto& it : finalWordsFound) {
            Logger::instance().log(it);
        }
    }

    Logger::instance().log("[Solver::solve] end");
}

void Solver::simplifyBoard(BoardPtr& board) {
    int dim = board->dim();
    for (int x = (dim - 1); x >= 0; --x) {
        for (int y = (dim -1); y >= 0; --y) {
            if (const_cast<const Board&>(*board).getTile(x, y).isEmpty()) {
                char val = -1;
                // check if any tiles above to drop down
                for (int i = y; i >= 0; --i) {
                    if (!const_cast<const Board&>(*board).getTile(x, i).isEmpty()) {
                        val = const_cast<const Board&>(*board).getTile(x, i).getValue();
                        board->setTileToEmpty(x, i);
                        break;
                    }
                }

                if (val == -1) {
                    board->setTileToEmpty(x, y);
                } else {
                    board->setTile(x, y, val);
                }
            }
        }
    }
}

void Solver::initializeQueue() {
    // initialize with beginning states
    std::vector<std::string> blank;
    std::string blankWord;
    for (int x = 0; x < board_->dim(); ++x) {
        for (int y = 0; y < board_->dim(); ++y) {
            StatePtr state(new State(board_, blank, blankWord, x, y));
            queue_.push_back(std::move(state));
        }
    }
}

void Solver::printQueue() {
    std::cout << "=== QUEUE ===" << "\n\n";
    for (auto& it : queue_) {
        std::cout << *it << std::endl;
    }
    std::cout << "=== \\QUEUE\\ ===" << "\n\n";
}

std::vector<std::pair<int, int> > Solver::generateMoves(int currX, int currY, int dim) {
    std::vector<std::pair<int, int> > nextMoves;
    if (currX > 0) {
        if (currY > 0) {
            nextMoves.emplace_back(currX-1, currY-1);
        }
        if (currY < (dim - 1)) {
            nextMoves.emplace_back(currX-1, currY+1);
        }
        nextMoves.emplace_back(currX-1, currY);
    }
    if (currX < (dim - 1)) {
        if (currY > 0) {
            nextMoves.emplace_back(currX+1, currY-1);
        }
        if (currY < (dim - 1)) {
            nextMoves.emplace_back(currX+1, currY+1);
        }
        nextMoves.emplace_back(currX+1, currY);
    }
    if (currY > 0) {
        nextMoves.emplace_back(currX, currY-1);
    }
    if (currY < (dim - 1)) {
        nextMoves.emplace_back(currX, currY+1);
    }
    return nextMoves;
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include <terark/util/autoclose.hpp>
#include <terark/util/linebuf.hpp>
#include <terark/util/profiling.hpp>
#include <terark/db/db_table.hpp>
#include <getopt.h>

void usage(const char* prog) {
	fprintf(stderr, "usage: %s options db-dir input-data-files...\n", prog);
}

int main(int argc, char* argv[]) {
	int inputFormat = 't';
	int compressionThreadsNum = 1;
	size_t rowsLimit = 10000000;
	for (;;) {
		int opt = getopt(argc, argv, "tjL:T:");
		switch (opt) {
		case -1:
			goto GetoptDone;
		case 'j':
		case 't':
			inputFormat = opt;
			break;
		case 'L':
			rowsLimit = strtoull(optarg, NULL, 10);
			break;
		case 'T':
			compressionThreadsNum = std::min(atoi(optarg), 8);
			break;
		}
	}
GetoptDone:
	if (optind + 2 < argc) {
		usage(argv[0]);
		return 1;
	}
	const char* dbdir = argv[optind + 0];
	terark::db::DbTablePtr tab = terark::db::DbTable::open(dbdir);
	terark::db::DbContextPtr ctx = tab->createDbContext();
	ctx->syncIndex = false;
	terark::LineBuf line;
	terark::valvec<unsigned char> row;
	size_t existedRows = tab->numDataRows();
	size_t skippedRows = 0;
	size_t rows = 0;
	size_t lines = 0;
	size_t bytes = 0;
	size_t colnum = tab->rowSchema().columnNum();
	printf("skip existed %zd rows and import %zd rows\n", existedRows, rowsLimit);
	for (int argIdx = optind + 1; argIdx < argc; ++argIdx) {
		const char* fname = argv[argIdx];
		terark::Auto_fclose fp(fopen(fname, "r"));
		if (!fp) {
			fprintf(stderr, "ERROR: fopen(%s, r) = %s\n", fname, strerror(errno));
			continue;
		}
		while (skippedRows < existedRows && line.getline(fp) > 0) {
			skippedRows++;
			if (skippedRows % TERARK_IF_DEBUG(100000, 1000000) == 0) {
				fprintf(stderr, "skipped %zd rows\n", skippedRows);
			}
		}
		fprintf(stderr, "total skipped %zd rows\n", skippedRows);
		while (rows < rowsLimit && line.getline(fp) > 0) {
			bytes += line.size();
			line.chomp();
			size_t parsed = tab->rowSchema().parseDelimText('\t', line, &row);
			if (parsed == colnum) {
				ctx->insertRow(row);
				rows++;
				if (lines % TERARK_IF_DEBUG(10000, 1000000) == 0) {
					printf("lines=%zd rows=%zd bytes=%zd currRow: %s\n",
						lines, rows, bytes,
						tab->rowSchema().toJsonStr(row).c_str());
					if (tab->getWritableSegNum() > 3) {
						printf("Waiting 10 seconds for compact thread catching up...\n");
						std::this_thread::sleep_for(std::chrono::seconds(10));
					}
					else {
						TERARK_IF_DEBUG(std::this_thread::sleep_for(std::chrono::seconds(2)),;);
					}
				}
			}
			lines++;
		}
	}
	printf("waiting for compact thread complete...\n");
	tab->syncFinishWriting();
	terark::db::DbTable::safeStopAndWaitForCompress();
	printf("done!\n");
    return 0;
}

<commit_msg>terarkdb_import.cpp: remvoe useless code<commit_after>#include "stdafx.h"
#include <terark/util/autoclose.hpp>
#include <terark/util/linebuf.hpp>
#include <terark/util/profiling.hpp>
#include <terark/db/db_table.hpp>
#include <getopt.h>

void usage(const char* prog) {
	fprintf(stderr, "usage: %s options db-dir input-data-files...\n", prog);
}

int main(int argc, char* argv[]) {
	int inputFormat = 't';
	size_t rowsLimit = 10000000;
	terark::hash_strmap<const char*> colformat;
	for (;;) {
		int opt = getopt(argc, argv, "tjL:");
		switch (opt) {
		case -1:
			goto GetoptDone;
		case 'j':
		case 't':
			inputFormat = opt;
			break;
		case 'L':
			rowsLimit = strtoull(optarg, NULL, 10);
			break;
		}
	}
GetoptDone:
	if (optind + 2 < argc) {
		usage(argv[0]);
		return 1;
	}
	const char* dbdir = argv[optind + 0];
	terark::db::DbTablePtr tab = terark::db::DbTable::open(dbdir);
	terark::db::DbContextPtr ctx = tab->createDbContext();
	ctx->syncIndex = false;
	terark::LineBuf line;
	terark::valvec<unsigned char> row;
	size_t existedRows = tab->numDataRows();
	size_t skippedRows = 0;
	size_t rows = 0;
	size_t lines = 0;
	size_t bytes = 0;
	size_t colnum = tab->rowSchema().columnNum();
	printf("skip existed %zd rows and import %zd rows\n", existedRows, rowsLimit);
	for (int argIdx = optind + 1; argIdx < argc; ++argIdx) {
		const char* fname = argv[argIdx];
		terark::Auto_fclose fp(fopen(fname, "r"));
		if (!fp) {
			fprintf(stderr, "ERROR: fopen(%s, r) = %s\n", fname, strerror(errno));
			continue;
		}
		while (skippedRows < existedRows && line.getline(fp) > 0) {
			skippedRows++;
			if (skippedRows % TERARK_IF_DEBUG(100000, 1000000) == 0) {
				fprintf(stderr, "skipped %zd rows\n", skippedRows);
			}
		}
		fprintf(stderr, "total skipped %zd rows\n", skippedRows);
		while (rows < rowsLimit && line.getline(fp) > 0) {
			bytes += line.size();
			line.chomp();
			size_t parsed = tab->rowSchema().parseDelimText('\t', line, &row);
			if (parsed == colnum) {
				ctx->insertRow(row);
				rows++;
				if (lines % TERARK_IF_DEBUG(10000, 1000000) == 0) {
					printf("lines=%zd rows=%zd bytes=%zd currRow: %s\n",
						lines, rows, bytes,
						tab->rowSchema().toJsonStr(row).c_str());
					if (tab->getWritableSegNum() > 3) {
						printf("Waiting 10 seconds for compact thread catching up...\n");
						std::this_thread::sleep_for(std::chrono::seconds(10));
					}
					else {
						TERARK_IF_DEBUG(std::this_thread::sleep_for(std::chrono::seconds(2)),;);
					}
				}
			}
			lines++;
		}
	}
	printf("waiting for compact thread complete...\n");
	tab->syncFinishWriting();
	terark::db::DbTable::safeStopAndWaitForCompress();
	printf("done!\n");
    return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: structtypedescription.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 08:05:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef INCLUDED_stoc_source_registry_tdprovider_structtypedescription_hxx
#define INCLUDED_stoc_source_registry_tdprovider_structtypedescription_hxx

#include "com/sun/star/reflection/XPublished.hpp"
#include "com/sun/star/reflection/XStructTypeDescription.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Sequence.hxx"
#include "cppuhelper/implbase2.hxx"
#include "rtl/ref.hxx"
#include "sal/types.h"

namespace com { namespace sun { namespace star {
    namespace container { class XHierarchicalNameAccess; }
    namespace reflection { class XCompoundTypeDescription; }
} } }
namespace rtl { class OUString; }
namespace stoc_rdbtdp { class CompoundTypeDescriptionImpl; }

namespace stoc { namespace registry_tdprovider {

class StructTypeDescription:
    public cppu::WeakImplHelper2<
        com::sun::star::reflection::XStructTypeDescription,
        com::sun::star::reflection::XPublished >
{
public:
    StructTypeDescription(
        com::sun::star::uno::Reference<
            com::sun::star::container::XHierarchicalNameAccess > const &
            manager,
        rtl::OUString const & name, rtl::OUString const & baseTypeName,
        com::sun::star::uno::Sequence< sal_Int8 > const & data, bool published);

    virtual ~StructTypeDescription();

    virtual com::sun::star::uno::TypeClass SAL_CALL getTypeClass()
        throw (com::sun::star::uno::RuntimeException);

    virtual rtl::OUString SAL_CALL getName()
        throw (com::sun::star::uno::RuntimeException);

    virtual
    com::sun::star::uno::Reference<
        com::sun::star::reflection::XTypeDescription >
    SAL_CALL getBaseType() throw (com::sun::star::uno::RuntimeException);

    virtual
    com::sun::star::uno::Sequence<
        com::sun::star::uno::Reference<
            com::sun::star::reflection::XTypeDescription > >
    SAL_CALL getMemberTypes() throw (com::sun::star::uno::RuntimeException);

    virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL
    getMemberNames() throw (com::sun::star::uno::RuntimeException);

    virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL
    getTypeParameters() throw (com::sun::star::uno::RuntimeException);

    virtual
    com::sun::star::uno::Sequence<
        com::sun::star::uno::Reference<
            com::sun::star::reflection::XTypeDescription > >
    SAL_CALL getTypeArguments() throw (com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL isPublished()
        throw (com::sun::star::uno::RuntimeException);

private:
    StructTypeDescription(StructTypeDescription &); // not implemented
    void operator =(StructTypeDescription); // not implemented

    com::sun::star::uno::Sequence< sal_Int8 > m_data;
    rtl::Reference< stoc_rdbtdp::CompoundTypeDescriptionImpl > m_base;
};

} }

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.90); FILE MERGED 2008/03/31 07:26:11 rt 1.4.90.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: structtypedescription.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef INCLUDED_stoc_source_registry_tdprovider_structtypedescription_hxx
#define INCLUDED_stoc_source_registry_tdprovider_structtypedescription_hxx

#include "com/sun/star/reflection/XPublished.hpp"
#include "com/sun/star/reflection/XStructTypeDescription.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Sequence.hxx"
#include "cppuhelper/implbase2.hxx"
#include "rtl/ref.hxx"
#include "sal/types.h"

namespace com { namespace sun { namespace star {
    namespace container { class XHierarchicalNameAccess; }
    namespace reflection { class XCompoundTypeDescription; }
} } }
namespace rtl { class OUString; }
namespace stoc_rdbtdp { class CompoundTypeDescriptionImpl; }

namespace stoc { namespace registry_tdprovider {

class StructTypeDescription:
    public cppu::WeakImplHelper2<
        com::sun::star::reflection::XStructTypeDescription,
        com::sun::star::reflection::XPublished >
{
public:
    StructTypeDescription(
        com::sun::star::uno::Reference<
            com::sun::star::container::XHierarchicalNameAccess > const &
            manager,
        rtl::OUString const & name, rtl::OUString const & baseTypeName,
        com::sun::star::uno::Sequence< sal_Int8 > const & data, bool published);

    virtual ~StructTypeDescription();

    virtual com::sun::star::uno::TypeClass SAL_CALL getTypeClass()
        throw (com::sun::star::uno::RuntimeException);

    virtual rtl::OUString SAL_CALL getName()
        throw (com::sun::star::uno::RuntimeException);

    virtual
    com::sun::star::uno::Reference<
        com::sun::star::reflection::XTypeDescription >
    SAL_CALL getBaseType() throw (com::sun::star::uno::RuntimeException);

    virtual
    com::sun::star::uno::Sequence<
        com::sun::star::uno::Reference<
            com::sun::star::reflection::XTypeDescription > >
    SAL_CALL getMemberTypes() throw (com::sun::star::uno::RuntimeException);

    virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL
    getMemberNames() throw (com::sun::star::uno::RuntimeException);

    virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL
    getTypeParameters() throw (com::sun::star::uno::RuntimeException);

    virtual
    com::sun::star::uno::Sequence<
        com::sun::star::uno::Reference<
            com::sun::star::reflection::XTypeDescription > >
    SAL_CALL getTypeArguments() throw (com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL isPublished()
        throw (com::sun::star::uno::RuntimeException);

private:
    StructTypeDescription(StructTypeDescription &); // not implemented
    void operator =(StructTypeDescription); // not implemented

    com::sun::star::uno::Sequence< sal_Int8 > m_data;
    rtl::Reference< stoc_rdbtdp::CompoundTypeDescriptionImpl > m_base;
};

} }

#endif
<|endoftext|>


<commit_before>
#include <raytracer.h>

#include <iostream>

#include <cmath>
#include <cassert>

#define DBL_CMP(X,Y) (std::abs((X) - (Y)) < 0.000001)

using namespace raytracer;

static void test_random();
static void test_dot();
static void test_cross();
static void test_copy();
static void test_power();
static void test_normalize();
static void test_scale();
static void test_add();
static void test_subtract();
static void test_translate();
static void test_project();
static void test_unproject();
static void test_reflect();
static void test_refract();

int main() {

	RNG::init();

	test_random();
	test_dot();
	test_cross();
	test_copy();
	test_power();
	test_normalize();
	test_scale();
	test_add();
	test_subtract();
	test_translate();
	test_project();
	test_unproject();
	test_reflect();
	test_refract();

	std::cout << "raytracer::Vector passed all tests\n";

	return 0;
}

void test_refract() {}
void test_reflect() {}
void test_unproject() {}
void test_project() {}
void test_translate() {}
void test_subtract() {}
void test_add() {}
void test_scale() {}
void test_normalize() {}
void test_power() {}
void test_copy() {}
void test_cross() {}

void test_dot() {
	for (int i = 0; i < 10000; i++) {
		Vector v = Vector::random(1.0);
		Vector w = Vector::random(1.0);

		double vl = std::sqrt(v.dot()),
			   wl = std::sqrt(w.dot());

		assert(v.dot(w) < vl*wl);
		assert(w.dot(v) < vl*wl);
		assert(v.dot() < 1.0);
		assert(w.dot() < 1.0);
		assert(v.dot(v) < 1.0);
		assert(w.dot(w) < 1.0);
		assert(Vector::dot(v,v));
		assert(Vector::dot(w,w));

		assert(DBL_CMP(v.dot(w),w.dot(v)));
		assert(DBL_CMP(v.dot(w),Vector::dot(v,w)));
		assert(DBL_CMP(w.dot(v),Vector::dot(v,w)));
		assert(DBL_CMP(v.dot(w),Vector::dot(w,v)));
	}
}

void test_random() {

	int x = 0, y = 0, z = 0;

	for (int i = 0; i < 10000; i++) {
		Vector v = Vector::random(1.0);
		assert(v.dot() < 1.0);
		if (v.x < 0.0)
			x--;
		else
			x++;
		if (v.y < 0.0)
			y--;
		else
			y++;
		if (v.z < 0.0)
			z--;
		else
			z++;
	}

	assert(std::abs(x) < 1000);
	assert(std::abs(y) < 1000);
	assert(std::abs(z) < 1000);
}

<commit_msg>added tests for Vector::cross<commit_after>
#include <raytracer.h>

#include <iostream>

#include <cmath>
#include <cassert>

#define DBL_CMP(X,Y) (std::abs((X) - (Y)) < 0.000001)

using namespace raytracer;

static void test_random();
static void test_dot();
static void test_cross();
static void test_copy();
static void test_power();
static void test_normalize();
static void test_scale();
static void test_add();
static void test_subtract();
static void test_translate();
static void test_project();
static void test_unproject();
static void test_reflect();
static void test_refract();

int main() {

	RNG::init();

	test_random();
	test_dot();
	test_cross();
	test_copy();
	test_power();
	test_normalize();
	test_scale();
	test_add();
	test_subtract();
	test_translate();
	test_project();
	test_unproject();
	test_reflect();
	test_refract();

	std::cout << "raytracer::Vector passed all tests\n";

	return 0;
}

void test_refract() {}
void test_reflect() {}
void test_unproject() {}
void test_project() {}
void test_translate() {}
void test_subtract() {}
void test_add() {}
void test_scale() {}
void test_normalize() {}
void test_power() {}
void test_copy() {}

void test_cross() {
	for (int i = 0; i < 10000; i++) {
		Vector v = Vector::random(1.0),
			   w = Vector::random(1.0),
			   a = v.cross(w),
			   b = Vector::cross(v,w);

		assert(a.dot() < 1.0);
		assert(b.dot() < 1.0);
		assert(DBL_CMP(a.dot(),b.dot()));

		a.add(w.cross(v));
		assert(DBL_CMP(a.dot(),0.0));

		b.add(Vector::cross(w,v));
		assert(DBL_CMP(b.dot(),0.0));
	}
}

void test_dot() {
	for (int i = 0; i < 10000; i++) {
		Vector v = Vector::random(1.0);
		Vector w = Vector::random(1.0);

		double vl = std::sqrt(v.dot()),
			   wl = std::sqrt(w.dot());

		assert(v.dot(w) < vl*wl);
		assert(w.dot(v) < vl*wl);
		assert(v.dot() < 1.0);
		assert(w.dot() < 1.0);
		assert(v.dot(v) < 1.0);
		assert(w.dot(w) < 1.0);
		assert(Vector::dot(v,v));
		assert(Vector::dot(w,w));

		assert(DBL_CMP(v.dot(w),w.dot(v)));
		assert(DBL_CMP(v.dot(w),Vector::dot(v,w)));
		assert(DBL_CMP(w.dot(v),Vector::dot(v,w)));
		assert(DBL_CMP(v.dot(w),Vector::dot(w,v)));
	}
}

void test_random() {

	int x = 0, y = 0, z = 0;

	for (int i = 0; i < 10000; i++) {
		Vector v = Vector::random(1.0);
		assert(v.dot() < 1.0);
		if (v.x < 0.0)
			x--;
		else
			x++;
		if (v.y < 0.0)
			y--;
		else
			y++;
		if (v.z < 0.0)
			z--;
		else
			z++;
	}

	assert(std::abs(x) < 1000);
	assert(std::abs(y) < 1000);
	assert(std::abs(z) < 1000);
}

<|endoftext|>


<commit_before>/*
	Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions
	are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of Rasterbar Software nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <cassert>
#include <iostream>
#include <vector>
#include <utility>
#include <set>

#include "libtorrent/buffer.hpp"
#include "libtorrent/chained_buffer.hpp"
#include "libtorrent/socket.hpp"

#include "test.hpp"

using namespace libtorrent;

/*
template<class T>
T const& min_(T const& x, T const& y)
{
	return x < y ? x : y;
}

void test_speed()
{
	buffer b;

	char data[32];

	srand(0);

	boost::timer t;

	int const iterations = 5000000;
	int const step = iterations / 20;

	for (int i = 0; i < iterations; ++i)
	{
		int x = rand();

		if (i % step == 0) std::cerr << ".";

		std::size_t n = rand() % 32;
		n = 32;

		if (x % 2)
		{
			b.insert(data, data + n);
		}
		else
		{
			b.erase(min_(b.size(), n));
		}
	}

	float t1 = t.elapsed();
	std::cerr << "buffer elapsed: " << t.elapsed() << "\n";

	std::vector<char> v;

	srand(0);
	t.restart();

	for (int i = 0; i < iterations; ++i)
	{
		int x = rand();

		if (i % step == 0) std::cerr << ".";

		std::size_t n = rand() % 32;
		n = 32;

		if (x % 2)
		{
			v.insert(v.end(), data, data + n);
		}
		else
		{
			v.erase(v.begin(), v.begin() + min_(v.size(), n));
		}
	}

	float t2 = t.elapsed();
	std::cerr << "std::vector elapsed: " << t.elapsed() << "\n";

	assert(t1 < t2);
}
*/

// -- test buffer --

void test_buffer()
{
	char data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

	buffer b;

	TEST_CHECK(b.size() == 0);
	TEST_CHECK(b.capacity() == 0);
	TEST_CHECK(b.empty());

	b.resize(10);
	TEST_CHECK(b.size() == 10);
	TEST_CHECK(b.capacity() == 10);

	std::memcpy(b.begin(), data, 10);
	b.reserve(50);
	TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
	TEST_CHECK(b.capacity() == 50);

	b.erase(b.begin() + 6, b.end());
	TEST_CHECK(std::memcmp(b.begin(), data, 6) == 0);
	TEST_CHECK(b.capacity() == 50);
	TEST_CHECK(b.size() == 6);

	b.insert(b.begin(), data + 5, data + 10);
	TEST_CHECK(b.capacity() == 50);
	TEST_CHECK(b.size() == 11);
	TEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0);

	b.clear();
	TEST_CHECK(b.size() == 0);
	TEST_CHECK(b.capacity() == 50);

	b.insert(b.end(), data, data + 10);
	TEST_CHECK(b.size() == 10);
	TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);

	b.erase(b.begin(), b.end());
	TEST_CHECK(b.capacity() == 50);
	TEST_CHECK(b.size() == 0);

	buffer().swap(b);
	TEST_CHECK(b.capacity() == 0);

}

// -- test chained buffer --

std::set<char*> buffer_list;

void free_buffer(char* m)
{
	std::set<char*>::iterator i = buffer_list.find(m);
	TEST_CHECK(i != buffer_list.end());

	buffer_list.erase(i);
	std::free(m);
}

char* allocate_buffer(int size)
{
	char* mem = (char*)std::malloc(size);
	buffer_list.insert(mem);
	return mem;
}

template <class T>
int copy_buffers(T const& b, char* target)
{
	int copied = 0;
	for (typename T::const_iterator i = b.begin()
		, end(b.end()); i != end; ++i)
	{
		memcpy(target, libtorrent::asio::buffer_cast<char const*>(*i), libtorrent::asio::buffer_size(*i));
		target += libtorrent::asio::buffer_size(*i);
		copied += libtorrent::asio::buffer_size(*i);
	}
	return copied;
}

bool compare_chained_buffer(chained_buffer& b, char const* mem, int size)
{
	if (size == 0) return true;
	std::vector<char> flat(size);
	std::list<libtorrent::asio::const_buffer> const& iovec2 = b.build_iovec(size);
	int copied = copy_buffers(iovec2, &flat[0]);
	TEST_CHECK(copied == size);
	return std::memcmp(&flat[0], mem, size) == 0;
}

void test_chained_buffer()
{
	char data[] = "foobar";
	{
		chained_buffer b;

		TEST_CHECK(b.empty());
		TEST_CHECK(b.capacity() == 0);
		TEST_CHECK(b.size() == 0);
		TEST_CHECK(b.space_in_last_buffer() == 0);
		TEST_CHECK(buffer_list.empty());

		char* b1 = allocate_buffer(512);
		std::memcpy(b1, data, 6);
		b.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer);
		TEST_CHECK(buffer_list.size() == 1);

		TEST_CHECK(b.capacity() == 512);
		TEST_CHECK(b.size() == 6);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		b.pop_front(3);

		TEST_CHECK(b.capacity() == 512);
		TEST_CHECK(b.size() == 3);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		bool ret = b.append(data, 6);

		TEST_CHECK(ret == true);
		TEST_CHECK(b.capacity() == 512);
		TEST_CHECK(b.size() == 9);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 12);

		ret = b.append(data, 1024);

		TEST_CHECK(ret == false);

		char* b2 = allocate_buffer(512);
		std::memcpy(b2, data, 6);
		b.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer);
		TEST_CHECK(buffer_list.size() == 2);

		char* b3 = allocate_buffer(512);
		std::memcpy(b3, data, 6);
		b.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer);
		TEST_CHECK(buffer_list.size() == 3);

		TEST_CHECK(b.capacity() == 512 * 3);
		TEST_CHECK(b.size() == 21);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		TEST_CHECK(compare_chained_buffer(b, "barfoobar", 9));

		for (int i = 1; i < 21; ++i)
			TEST_CHECK(compare_chained_buffer(b, "barfoobarfoobarfoobar", i));

		b.pop_front(5 + 6);

		TEST_CHECK(buffer_list.size() == 2);
		TEST_CHECK(b.capacity() == 512 * 2);
		TEST_CHECK(b.size() == 10);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		char const* str = "obarfooba";
		TEST_CHECK(compare_chained_buffer(b, str, 9));

		for (int i = 0; i < 9; ++i)
		{
			b.pop_front(1);
			++str;
			TEST_CHECK(compare_chained_buffer(b, str, 8 - i));
			TEST_CHECK(b.size() == 9 - i);
		}

		char* b4 = allocate_buffer(20);
		std::memcpy(b4, data, 6);
		std::memcpy(b4 + 6, data, 6);
		b.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer);
		TEST_CHECK(b.space_in_last_buffer() == 8);

		ret = b.append(data, 6);
		TEST_CHECK(ret == true);
		TEST_CHECK(b.space_in_last_buffer() == 2);
		std::cout << b.space_in_last_buffer() << std::endl;
		ret = b.append(data, 2);
		TEST_CHECK(ret == true);
		TEST_CHECK(b.space_in_last_buffer() == 0);
		std::cout << b.space_in_last_buffer() << std::endl;

		char* b5 = allocate_buffer(20);
		std::memcpy(b4, data, 6);
		b.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer);

		b.pop_front(22);
		TEST_CHECK(b.size() == 5);
	}
	TEST_CHECK(buffer_list.empty());
}

int test_main()
{
	test_buffer();
	test_chained_buffer();
	return 0;
}

<commit_msg>fix potential buffer overrun in unit test<commit_after>/*
	Copyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions
	are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of Rasterbar Software nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <cassert>
#include <iostream>
#include <vector>
#include <utility>
#include <set>

#include "libtorrent/buffer.hpp"
#include "libtorrent/chained_buffer.hpp"
#include "libtorrent/socket.hpp"

#include "test.hpp"

using namespace libtorrent;

/*
template<class T>
T const& min_(T const& x, T const& y)
{
	return x < y ? x : y;
}

void test_speed()
{
	buffer b;

	char data[32];

	srand(0);

	boost::timer t;

	int const iterations = 5000000;
	int const step = iterations / 20;

	for (int i = 0; i < iterations; ++i)
	{
		int x = rand();

		if (i % step == 0) std::cerr << ".";

		std::size_t n = rand() % 32;
		n = 32;

		if (x % 2)
		{
			b.insert(data, data + n);
		}
		else
		{
			b.erase(min_(b.size(), n));
		}
	}

	float t1 = t.elapsed();
	std::cerr << "buffer elapsed: " << t.elapsed() << "\n";

	std::vector<char> v;

	srand(0);
	t.restart();

	for (int i = 0; i < iterations; ++i)
	{
		int x = rand();

		if (i % step == 0) std::cerr << ".";

		std::size_t n = rand() % 32;
		n = 32;

		if (x % 2)
		{
			v.insert(v.end(), data, data + n);
		}
		else
		{
			v.erase(v.begin(), v.begin() + min_(v.size(), n));
		}
	}

	float t2 = t.elapsed();
	std::cerr << "std::vector elapsed: " << t.elapsed() << "\n";

	assert(t1 < t2);
}
*/

// -- test buffer --

void test_buffer()
{
	char data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

	buffer b;

	TEST_CHECK(b.size() == 0);
	TEST_CHECK(b.capacity() == 0);
	TEST_CHECK(b.empty());

	b.resize(10);
	TEST_CHECK(b.size() == 10);
	TEST_CHECK(b.capacity() == 10);

	std::memcpy(b.begin(), data, 10);
	b.reserve(50);
	TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);
	TEST_CHECK(b.capacity() == 50);

	b.erase(b.begin() + 6, b.end());
	TEST_CHECK(std::memcmp(b.begin(), data, 6) == 0);
	TEST_CHECK(b.capacity() == 50);
	TEST_CHECK(b.size() == 6);

	b.insert(b.begin(), data + 5, data + 10);
	TEST_CHECK(b.capacity() == 50);
	TEST_CHECK(b.size() == 11);
	TEST_CHECK(std::memcmp(b.begin(), data + 5, 5) == 0);

	b.clear();
	TEST_CHECK(b.size() == 0);
	TEST_CHECK(b.capacity() == 50);

	b.insert(b.end(), data, data + 10);
	TEST_CHECK(b.size() == 10);
	TEST_CHECK(std::memcmp(b.begin(), data, 10) == 0);

	b.erase(b.begin(), b.end());
	TEST_CHECK(b.capacity() == 50);
	TEST_CHECK(b.size() == 0);

	buffer().swap(b);
	TEST_CHECK(b.capacity() == 0);

}

// -- test chained buffer --

std::set<char*> buffer_list;

void free_buffer(char* m)
{
	std::set<char*>::iterator i = buffer_list.find(m);
	TEST_CHECK(i != buffer_list.end());

	buffer_list.erase(i);
	std::free(m);
}

char* allocate_buffer(int size)
{
	char* mem = (char*)std::malloc(size);
	buffer_list.insert(mem);
	return mem;
}

template <class T>
int copy_buffers(T const& b, char* target)
{
	int copied = 0;
	for (typename T::const_iterator i = b.begin()
		, end(b.end()); i != end; ++i)
	{
		memcpy(target, libtorrent::asio::buffer_cast<char const*>(*i), libtorrent::asio::buffer_size(*i));
		target += libtorrent::asio::buffer_size(*i);
		copied += libtorrent::asio::buffer_size(*i);
	}
	return copied;
}

bool compare_chained_buffer(chained_buffer& b, char const* mem, int size)
{
	if (size == 0) return true;
	std::vector<char> flat(size);
	std::list<libtorrent::asio::const_buffer> const& iovec2 = b.build_iovec(size);
	int copied = copy_buffers(iovec2, &flat[0]);
	TEST_CHECK(copied == size);
	return std::memcmp(&flat[0], mem, size) == 0;
}

void test_chained_buffer()
{
	char data[] = "foobar";
	{
		chained_buffer b;

		TEST_CHECK(b.empty());
		TEST_CHECK(b.capacity() == 0);
		TEST_CHECK(b.size() == 0);
		TEST_CHECK(b.space_in_last_buffer() == 0);
		TEST_CHECK(buffer_list.empty());

		char* b1 = allocate_buffer(512);
		std::memcpy(b1, data, 6);
		b.append_buffer(b1, 512, 6, (void(*)(char*))&free_buffer);
		TEST_CHECK(buffer_list.size() == 1);

		TEST_CHECK(b.capacity() == 512);
		TEST_CHECK(b.size() == 6);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		b.pop_front(3);

		TEST_CHECK(b.capacity() == 512);
		TEST_CHECK(b.size() == 3);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		bool ret = b.append(data, 6);

		TEST_CHECK(ret == true);
		TEST_CHECK(b.capacity() == 512);
		TEST_CHECK(b.size() == 9);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 12);

		char data2[1024];
		ret = b.append(data2, 1024);

		TEST_CHECK(ret == false);

		char* b2 = allocate_buffer(512);
		std::memcpy(b2, data, 6);
		b.append_buffer(b2, 512, 6, (void(*)(char*))&free_buffer);
		TEST_CHECK(buffer_list.size() == 2);

		char* b3 = allocate_buffer(512);
		std::memcpy(b3, data, 6);
		b.append_buffer(b3, 512, 6, (void(*)(char*))&free_buffer);
		TEST_CHECK(buffer_list.size() == 3);

		TEST_CHECK(b.capacity() == 512 * 3);
		TEST_CHECK(b.size() == 21);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		TEST_CHECK(compare_chained_buffer(b, "barfoobar", 9));

		for (int i = 1; i < 21; ++i)
			TEST_CHECK(compare_chained_buffer(b, "barfoobarfoobarfoobar", i));

		b.pop_front(5 + 6);

		TEST_CHECK(buffer_list.size() == 2);
		TEST_CHECK(b.capacity() == 512 * 2);
		TEST_CHECK(b.size() == 10);
		TEST_CHECK(!b.empty());
		TEST_CHECK(b.space_in_last_buffer() == 512 - 6);

		char const* str = "obarfooba";
		TEST_CHECK(compare_chained_buffer(b, str, 9));

		for (int i = 0; i < 9; ++i)
		{
			b.pop_front(1);
			++str;
			TEST_CHECK(compare_chained_buffer(b, str, 8 - i));
			TEST_CHECK(b.size() == 9 - i);
		}

		char* b4 = allocate_buffer(20);
		std::memcpy(b4, data, 6);
		std::memcpy(b4 + 6, data, 6);
		b.append_buffer(b4, 20, 12, (void(*)(char*))&free_buffer);
		TEST_CHECK(b.space_in_last_buffer() == 8);

		ret = b.append(data, 6);
		TEST_CHECK(ret == true);
		TEST_CHECK(b.space_in_last_buffer() == 2);
		std::cout << b.space_in_last_buffer() << std::endl;
		ret = b.append(data, 2);
		TEST_CHECK(ret == true);
		TEST_CHECK(b.space_in_last_buffer() == 0);
		std::cout << b.space_in_last_buffer() << std::endl;

		char* b5 = allocate_buffer(20);
		std::memcpy(b4, data, 6);
		b.append_buffer(b5, 20, 6, (void(*)(char*))&free_buffer);

		b.pop_front(22);
		TEST_CHECK(b.size() == 5);
	}
	TEST_CHECK(buffer_list.empty());
}

int test_main()
{
	test_buffer();
	test_chained_buffer();
	return 0;
}

<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 * $Log$
 * Revision 1.1  2002/09/30 22:09:28  peiyongz
 * To generate icu resource file (in text) for error message.
 *
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include "Xlat.hpp"

// ---------------------------------------------------------------------------
//  ICUResBundFormatter: Constructors and Destructor
// ---------------------------------------------------------------------------
ICUResBundFormatter::ICUResBundFormatter()
:fOutFl(0)
,fTranscoder(0)
{
    //
    //  Try to create a transcoder for the format that we were told
    //  to output in.
    //
    //  <TBD> Right now we are just using an LCP transcoding, which is not
    //  really the right thing to do!
    //
    fTranscoder = XMLPlatformUtils::fgTransService->makeNewLCPTranscoder();
    if (!fTranscoder)
    {
        wprintf(L"Could not create LCP transcoder\n");
        throw ErrReturn_NoTranscoder;
    }
}

ICUResBundFormatter::~ICUResBundFormatter()
{
}

// ---------------------------------------------------------------------------
//  ICUResBundFormatter: Implementation of the formatter interface
// ---------------------------------------------------------------------------
void ICUResBundFormatter::endDomain(const   XMLCh*        const    domainName
                                  , const   unsigned int           msgCount)
{
    fwprintf(fOutFl, L"\t\t} \n\n");
}

void ICUResBundFormatter::endMsgType(const MsgTypes type)
{
#ifdef ICU_RESBUNDLE_IN_ARRAY_FORM
     fwprintf(fOutFl, L"\t\t\"%S End \" ,\n", typePrefixes[type]);
#endif
}

void ICUResBundFormatter::endOutput()
{
    // Close the output files
    fwprintf(fOutFl, L"} \n\n");
    fclose(fOutFl);
}

void
ICUResBundFormatter::nextMessage(const  XMLCh* const            msgText
                               , const  XMLCh* const            msgId
                               , const  unsigned int            messageId
                               , const  unsigned int            curId)
{
    //
    //  We have to transcode the message text to UTF-8 in order to be able
    //  to write it out to a message catalog (which is not Unicode enabled.)
    //  If the text is just US-ASCII, this won't have any effect, but don't
    //  bother checking, just do it simple and stupid.
    //

	char* outData = fTranscoder->transcode(msgText);

    //
	//  array_name {
	//               "xxx" ,
	//               "yyy" ,
	//  }
	//
	//
	//  table_name {
	//       AB { "xxx" }
	//       CD { "yyy" }
	//  }
	//

#ifdef ICU_RESBUNDLE_IN_ARRAY_FORM
    fwprintf(fOutFl, L"\t\t\"%S \" ,\n", outData);
	// need a space between the last character and the closing "
#else
    fwprintf(fOutFl, L"\t\t %3d { \"%S \" } \n", curId, outData);
	// need to print leading 0 if less than 100, not tested yet
#endif

    delete [] outData;
}

void ICUResBundFormatter::startDomain(const   XMLCh* const    domainName
                                    , const   XMLCh* const    nameSpace)
{
    //
    //  Output:
    //           // an array
    //           domainName {
	//
	int index = XMLString::lastIndexOf(domainName, chForwardSlash);
	char *tmpDomainName = fTranscoder->transcode(&(domainName[index+1]));

#ifdef ICU_RESBUNDLE_IN_ARRAY_FORM
    fwprintf(fOutFl, L"\n\t // an array \n");
#else
    fwprintf(fOutFl, L"\n\t // a table \n");
#endif

    fwprintf(fOutFl, L"\t%S { \n" , tmpDomainName);

	delete [] tmpDomainName;

}

void ICUResBundFormatter::startMsgType(const MsgTypes type)
{
#ifdef ICU_RESBUNDLE_IN_ARRAY_FORM
    fwprintf(fOutFl, L"\t\t\"%S Start \" , \n", typePrefixes[type]);
#endif
}

void ICUResBundFormatter::startOutput(const   XMLCh* const    locale
                                    , const   XMLCh* const    outPath)
{
    //
    //  Ok, lets try to open the the output file. All of the messages
    //  for all the domains are put into a single Msg file, which can be
    //  compiled into the program.
    //
    //  CppErrMsgs_xxxx.Msg
    //
    //  where xxx is the locale suffix passed in.
    //
    const unsigned int bufSize = 4095;
    XMLCh tmpBuf[bufSize + 1];

    swprintf(tmpBuf, L"%s/%s_%s.Msg", outPath, L"root", locale);
    fOutFl = _wfopen(tmpBuf, L"wt");
    if (!fOutFl)
    {
        wprintf(L"Could not open the output file: %s\n\n", tmpBuf);
        throw ErrReturn_OutFileOpenFailed;
    }

    // Set the message delimiter
    fwprintf(fOutFl, L"root { \n");

}
<commit_msg>generate correct <locale>.txt file<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 * $Log$
 * Revision 1.2  2002/11/05 21:15:16  peiyongz
 * generate correct <locale>.txt file
 *
 * Revision 1.1  2002/09/30 22:09:28  peiyongz
 * To generate icu resource file (in text) for error message.
 *
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include "Xlat.hpp"

// ---------------------------------------------------------------------------
//  ICUResBundFormatter: Constructors and Destructor
// ---------------------------------------------------------------------------
ICUResBundFormatter::ICUResBundFormatter()
:fOutFl(0)
,fTranscoder(0)
{
    //
    //  Try to create a transcoder for the format that we were told
    //  to output in.
    //
    //  <TBD> Right now we are just using an LCP transcoding, which is not
    //  really the right thing to do!
    //
    fTranscoder = XMLPlatformUtils::fgTransService->makeNewLCPTranscoder();
    if (!fTranscoder)
    {
        wprintf(L"Could not create LCP transcoder\n");
        throw ErrReturn_NoTranscoder;
    }
}

ICUResBundFormatter::~ICUResBundFormatter()
{
}

// ---------------------------------------------------------------------------
//  ICUResBundFormatter: Implementation of the formatter interface
// ---------------------------------------------------------------------------
void ICUResBundFormatter::endDomain(const   XMLCh*        const    domainName
                                  , const   unsigned int           msgCount)
{
    fwprintf(fOutFl, L"\t\t} \n\n");
}

void ICUResBundFormatter::endMsgType(const MsgTypes type)
{
#ifdef ICU_RESBUNDLE_IN_ARRAY_FORM
     fwprintf(fOutFl, L"\t\t\"%S End \" ,\n", typePrefixes[type]);
#endif
}

void ICUResBundFormatter::endOutput()
{
    // Close the output files
    fwprintf(fOutFl, L"} \n\n");
    fclose(fOutFl);
}

void
ICUResBundFormatter::nextMessage(const  XMLCh* const            msgText
                               , const  XMLCh* const            msgId
                               , const  unsigned int            messageId
                               , const  unsigned int            curId)
{
    //
    //  We have to transcode the message text to UTF-8 in order to be able
    //  to write it out to a message catalog (which is not Unicode enabled.)
    //  If the text is just US-ASCII, this won't have any effect, but don't
    //  bother checking, just do it simple and stupid.
    //

	char* outData = fTranscoder->transcode(msgText);

    //
	//  array_name {
	//               "xxx" ,
	//               "yyy" ,
	//  }
	//
	//
	//  table_name {
	//       AB { "xxx" }
	//       CD { "yyy" }
	//  }
	//

#ifdef ICU_RESBUNDLE_IN_ARRAY_FORM
    fwprintf(fOutFl, L"\t\t\"%S \" ,\n", outData);
	// need a space between the last character and the closing "
#else
    fwprintf(fOutFl, L"\t\t %3d { \"%S \" } \n", curId, outData);
	// need to print leading 0 if less than 100, not tested yet
#endif

    delete [] outData;
}

void ICUResBundFormatter::startDomain(const   XMLCh* const    domainName
                                    , const   XMLCh* const    nameSpace)
{
    //
    //  Output:
    //           // an array
    //           domainName {
	//
	int index = XMLString::lastIndexOf(domainName, chForwardSlash);
	char *tmpDomainName = fTranscoder->transcode(&(domainName[index+1]));

#ifdef ICU_RESBUNDLE_IN_ARRAY_FORM
    fwprintf(fOutFl, L"\n\t // an array \n");
#else
    fwprintf(fOutFl, L"\n\t // a table \n");
#endif

    fwprintf(fOutFl, L"\t%S { \n" , tmpDomainName);

	delete [] tmpDomainName;

}

void ICUResBundFormatter::startMsgType(const MsgTypes type)
{
#ifdef ICU_RESBUNDLE_IN_ARRAY_FORM
    fwprintf(fOutFl, L"\t\t\"%S Start \" , \n", typePrefixes[type]);
#endif
}

void ICUResBundFormatter::startOutput(const   XMLCh* const    locale
                                    , const   XMLCh* const    outPath)
{
    //
    //  Ok, lets try to open the the output file. All of the messages
    //  for all the domains are put into a single Msg file, which can be
    //  compiled into the program.
    //
    //  CppErrMsgs_xxxx.Msg
    //
    //  where xxx is the locale suffix passed in.
    //
    const unsigned int bufSize = 4095;
    XMLCh tmpBuf[bufSize + 1];

    //
    // we got to comform to locale specs
    // that is en_US
    //
    XMLCh tempLocale[bufSize+1];
    XMLCh tempLan[64];
    int lang_end = XMLString::indexOf(locale, chUnderscore);
    if (lang_end != -1)
    {
        XMLString::subString(tempLan, locale, 0, lang_end);
        tempLan[lang_end] = 0;
        XMLString::lowerCase(tempLan);
        XMLString::copyString(tempLocale, tempLan);
        tempLocale[lang_end] = 0;
        XMLString::catString(&(tempLocale[lang_end]), &(locale[lang_end]));
    }
    else
    {
        XMLString::copyString(tempLocale, locale);
    }

    swprintf(tmpBuf, L"%s/%s.txt", outPath, tempLocale);
    fOutFl = _wfopen(tmpBuf, L"wt");
    if (!fOutFl)
    {
        wprintf(L"Could not open the output file: %s\n\n", tmpBuf);
        throw ErrReturn_OutFileOpenFailed;
    }

    // Set the message delimiter
    fwprintf(fOutFl, L"%s { \n", tempLocale);

}
<|endoftext|>


<commit_before><commit_msg>Correcting the other wrong addition function saves lives.<commit_after><|endoftext|>