<commit_before>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2019 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#include <DO/Sara/Core/EigenExtension.hpp>

#include <fstream>
#include <string>

namespace DO::Sara {

inline auto read_internal_camera_parameters(const std::string& filepath)
    -> Eigen::Matrix3d
{
  std::ifstream file{filepath};
  if (!file)
    throw std::runtime_error{"File " + filepath + "does not exist!"};

  Eigen::Matrix3d K;
  file >> K;

  return K;
}

} /* namespace DO::Sara */
<commit_msg>MAINT: fix compile errors.<commit_after>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2019 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#pragma once

#include <DO/Sara/Core/EigenExtension.hpp>

#include <fstream>
#include <string>

namespace DO::Sara {

inline auto read_internal_camera_parameters(const std::string& filepath)
    -> Eigen::Matrix3d
{
  std::ifstream file{filepath};
  if (!file)
    throw std::runtime_error{"File " + filepath + "does not exist!"};

  Eigen::Matrix3d K;
  file >> K;

  return K;
}

} /* namespace DO::Sara */
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

Copyright (c) 2000-2013 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "SamplePlugin.h"
#include "VolumeTerrain.h"

#include "OgreRay.h"

using namespace Ogre;
using namespace OgreBites;
using namespace Ogre::Volume;

void Sample_VolumeTerrain::setupContent(void)
{
    setupControls();

    // Skydome
    mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8);

    // Light
    Light* directionalLight0 = mSceneMgr->createLight("directionalLight0");
    directionalLight0->setType(Light::LT_DIRECTIONAL);
    directionalLight0->setDirection(Vector3((Real)1, (Real)-1, (Real)1));
    directionalLight0->setDiffuseColour((Real)1, (Real)0.98, (Real)0.73);
    directionalLight0->setSpecularColour((Real)0.1, (Real)0.1, (Real)0.1);

    // Volume
    mVolumeRoot = OGRE_NEW Chunk();
    SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("VolumeParent");
    mVolumeRoot->load(volumeRootNode, mSceneMgr, "volumeTerrain.cfg", &mSource);

    // Camera
    mCamera->setPosition((Real)(2560 - 384), (Real)2000, (Real)(2560 - 384));
    mCamera->lookAt((Real)0, (Real)100, (Real)0);
    mCamera->setNearClipDistance((Real)0.5);

}

//-----------------------------------------------------------------------

void Sample_VolumeTerrain::setupControls(void)
{
    mTrayMgr->showCursor();
#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS
        setDragLook(true);
#endif
    mCameraMan->setTopSpeed((Real)100.0);
    // make room for the volume
    mTrayMgr->showLogo(TL_TOPRIGHT);
    mTrayMgr->showFrameStats(TL_TOPRIGHT);
    mTrayMgr->toggleAdvancedFrameStats();

    mTrayMgr->createTextBox(TL_TOPLEFT, "VolumeTerrainHelp", "Usage:\n\nHold the left mouse button,\n press wasd for movement\nand move the mouse for\n the direction.\nYou can place white spheres\nwith the middle mouse\nbutton like in an ego-shooter.", 265, 160);
}

//-----------------------------------------------------------------------

void Sample_VolumeTerrain::cleanupContent(void)
{
    OGRE_DELETE mVolumeRoot;
    delete mSource;
    mVolumeRoot = 0;
}

//-----------------------------------------------------------------------

Sample_VolumeTerrain::Sample_VolumeTerrain(void) : mVolumeRoot(0), mHideAll(false)
{
    mInfo["Title"] = "Volume Terrain";
    mInfo["Description"] = "Demonstrates a volumetric terrain defined by an 3D texture and ray intersection with a volume.";
    mInfo["Thumbnail"] = "thumb_volumeterrain.png";
    mInfo["Category"] = "Geometry";
}

//-----------------------------------------------------------------------

bool Sample_VolumeTerrain::keyPressed(const OIS::KeyEvent& evt)
{
    if (evt.key == OIS::KC_F10)
    {
        mVolumeRoot->setVolumeVisible(!mVolumeRoot->getVolumeVisible());
    }
    if (evt.key == OIS::KC_F11)
    {
        mVolumeRoot->setOctreeVisible(!mVolumeRoot->getOctreeVisible());
    }
    if (evt.key == OIS::KC_F12)
    {
        mVolumeRoot->setDualGridVisible(!mVolumeRoot->getDualGridVisible());
    }
    if (evt.key == OIS::KC_H)
    {
        if (mHideAll)
        {
            mTrayMgr->showAll();
        }
        else
        {
            mTrayMgr->hideAll();
        }
        mHideAll = !mHideAll;
    }
    return SdkSample::keyPressed(evt);
}

//-----------------------------------------------------------------------

void Sample_VolumeTerrain::shootRay(Ray ray)
{
        Vector3 intersection;
        bool intersects = mSource->getFirstRayIntersection(ray, intersection);
        static int intersectionName = 0;
        if (intersects)
        {
            intersectionName++;
            SceneNode *n = mSceneMgr->getRootSceneNode()->createChildSceneNode();
            n->translate(intersection * mVolumeRoot->getScale());
            n->scale(Vector3((Real)0.05));
            Entity * mcSphere = mSceneMgr->createEntity("intersection" + StringConverter::toString(intersectionName), "sphere.mesh");
            n->attachObject(mcSphere);
        }
}

//-----------------------------------------------------------------------

bool Sample_VolumeTerrain::mousePressed(const OIS::MouseEvent& evt, OIS::MouseButtonID id)
{

    if (id == OIS::MB_Middle)
    {
            LogManager::getSingleton().stream() << "SCALE: " << mVolumeRoot->getScale();
        Ray ray(mCamera->getPosition() / mVolumeRoot->getScale(), -mCamera->getOrientation().zAxis());
        shootRay(ray);
    }

    return SdkSample::mousePressed(evt, id);
}

//-----------------------------------------------------------------------

#ifndef OGRE_STATIC_LIB

SamplePlugin* sp;
Sample* s;

//-----------------------------------------------------------------------

extern "C" _OgreSampleExport void dllStartPlugin()
{
    s = new Sample_VolumeTerrain();
    sp = OGRE_NEW SamplePlugin(s->getInfo()["Title"] + " Sample");
    sp->addSample(s);
    Root::getSingleton().installPlugin(sp);
}

//-----------------------------------------------------------------------

extern "C" _OgreSampleExport void dllStopPlugin()
{
    Root::getSingleton().uninstallPlugin(sp);
    OGRE_DELETE sp;
    delete s;
}

#endif
<commit_msg>Volume Rendering: removed debug log<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

Copyright (c) 2000-2013 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "SamplePlugin.h"
#include "VolumeTerrain.h"

#include "OgreRay.h"

using namespace Ogre;
using namespace OgreBites;
using namespace Ogre::Volume;

void Sample_VolumeTerrain::setupContent(void)
{
    setupControls();

    // Skydome
    mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8);

    // Light
    Light* directionalLight0 = mSceneMgr->createLight("directionalLight0");
    directionalLight0->setType(Light::LT_DIRECTIONAL);
    directionalLight0->setDirection(Vector3((Real)1, (Real)-1, (Real)1));
    directionalLight0->setDiffuseColour((Real)1, (Real)0.98, (Real)0.73);
    directionalLight0->setSpecularColour((Real)0.1, (Real)0.1, (Real)0.1);

    // Volume
    mVolumeRoot = OGRE_NEW Chunk();
    SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("VolumeParent");
    mVolumeRoot->load(volumeRootNode, mSceneMgr, "volumeTerrain.cfg", &mSource);

    // Camera
    mCamera->setPosition((Real)(2560 - 384), (Real)2000, (Real)(2560 - 384));
    mCamera->lookAt((Real)0, (Real)100, (Real)0);
    mCamera->setNearClipDistance((Real)0.5);

}

//-----------------------------------------------------------------------

void Sample_VolumeTerrain::setupControls(void)
{
    mTrayMgr->showCursor();
#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS
        setDragLook(true);
#endif
    mCameraMan->setTopSpeed((Real)100.0);
    // make room for the volume
    mTrayMgr->showLogo(TL_TOPRIGHT);
    mTrayMgr->showFrameStats(TL_TOPRIGHT);
    mTrayMgr->toggleAdvancedFrameStats();

    mTrayMgr->createTextBox(TL_TOPLEFT, "VolumeTerrainHelp", "Usage:\n\nHold the left mouse button,\n press wasd for movement\nand move the mouse for\n the direction.\nYou can place white spheres\nwith the middle mouse\nbutton like in an ego-shooter.", 265, 160);
}

//-----------------------------------------------------------------------

void Sample_VolumeTerrain::cleanupContent(void)
{
    OGRE_DELETE mVolumeRoot;
    delete mSource;
    mVolumeRoot = 0;
}

//-----------------------------------------------------------------------

Sample_VolumeTerrain::Sample_VolumeTerrain(void) : mVolumeRoot(0), mHideAll(false)
{
    mInfo["Title"] = "Volume Terrain";
    mInfo["Description"] = "Demonstrates a volumetric terrain defined by an 3D texture and ray intersection with a volume.";
    mInfo["Thumbnail"] = "thumb_volumeterrain.png";
    mInfo["Category"] = "Geometry";
}

//-----------------------------------------------------------------------

bool Sample_VolumeTerrain::keyPressed(const OIS::KeyEvent& evt)
{
    if (evt.key == OIS::KC_F10)
    {
        mVolumeRoot->setVolumeVisible(!mVolumeRoot->getVolumeVisible());
    }
    if (evt.key == OIS::KC_F11)
    {
        mVolumeRoot->setOctreeVisible(!mVolumeRoot->getOctreeVisible());
    }
    if (evt.key == OIS::KC_F12)
    {
        mVolumeRoot->setDualGridVisible(!mVolumeRoot->getDualGridVisible());
    }
    if (evt.key == OIS::KC_H)
    {
        if (mHideAll)
        {
            mTrayMgr->showAll();
        }
        else
        {
            mTrayMgr->hideAll();
        }
        mHideAll = !mHideAll;
    }
    return SdkSample::keyPressed(evt);
}

//-----------------------------------------------------------------------

void Sample_VolumeTerrain::shootRay(Ray ray)
{
        Vector3 intersection;
        bool intersects = mSource->getFirstRayIntersection(ray, intersection);
        static int intersectionName = 0;
        if (intersects)
        {
            intersectionName++;
            SceneNode *n = mSceneMgr->getRootSceneNode()->createChildSceneNode();
            n->translate(intersection * mVolumeRoot->getScale());
            n->scale(Vector3((Real)0.05));
            Entity * mcSphere = mSceneMgr->createEntity("intersection" + StringConverter::toString(intersectionName), "sphere.mesh");
            n->attachObject(mcSphere);
        }
}

//-----------------------------------------------------------------------

bool Sample_VolumeTerrain::mousePressed(const OIS::MouseEvent& evt, OIS::MouseButtonID id)
{

    if (id == OIS::MB_Middle)
    {
        Ray ray(mCamera->getPosition() / mVolumeRoot->getScale(), -mCamera->getOrientation().zAxis());
        shootRay(ray);
    }

    return SdkSample::mousePressed(evt, id);
}

//-----------------------------------------------------------------------

#ifndef OGRE_STATIC_LIB

SamplePlugin* sp;
Sample* s;

//-----------------------------------------------------------------------

extern "C" _OgreSampleExport void dllStartPlugin()
{
    s = new Sample_VolumeTerrain();
    sp = OGRE_NEW SamplePlugin(s->getInfo()["Title"] + " Sample");
    sp->addSample(s);
    Root::getSingleton().installPlugin(sp);
}

//-----------------------------------------------------------------------

extern "C" _OgreSampleExport void dllStopPlugin()
{
    Root::getSingleton().uninstallPlugin(sp);
    OGRE_DELETE sp;
    delete s;
}

#endif
<|endoftext|>


<commit_before>
#include "font.h"
#include <stdexcept>
#include <cairo-ft.h>

namespace cairo
{

////////////////////////////////////////

font::font( cairo_font_face_t *face, std::string fam, std::string sty, double sz )
	: draw::font( std::move(fam), std::move(sty), sz )
{
	auto opts = cairo_font_options_create();
	cairo_font_options_set_antialias( opts, CAIRO_ANTIALIAS_SUBPIXEL );
	cairo_font_options_set_subpixel_order( opts, CAIRO_SUBPIXEL_ORDER_DEFAULT );
	cairo_font_options_set_hint_style( opts, CAIRO_HINT_STYLE_FULL );
	cairo_font_options_set_hint_metrics( opts, CAIRO_HINT_METRICS_ON );

	cairo_matrix_t mat, ctm;
	cairo_matrix_init_identity( &ctm );
	cairo_matrix_init_scale( &mat, sz, sz );

	_font = cairo_scaled_font_create( face, &mat, &ctm, opts );

	cairo_font_options_destroy( opts );

	cairo_font_extents_t ex;
	cairo_scaled_font_extents( _font, &ex );

	cairo_text_extents_t tex;
	cairo_scaled_font_text_extents( _font, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", &tex );

	_extents = { -tex.y_bearing, ex.descent, ex.height, ex.max_x_advance, ex.max_y_advance };
}

////////////////////////////////////////

font::~font( void )
{
	cairo_scaled_font_destroy( _font );
}

////////////////////////////////////////

draw::font_extents font::extents( void )
{
	return _extents;
}

////////////////////////////////////////

draw::text_extents font::extents( const std::string &utf8 )
{
	cairo_text_extents_t ex;
	cairo_scaled_font_text_extents( _font, utf8.c_str(), &ex );
	return { ex.x_bearing, ex.y_bearing, ex.width, ex.height, ex.x_advance, ex.y_advance };
}

////////////////////////////////////////

}

<commit_msg>Removed unused header file.<commit_after>
#include "font.h"
#include <stdexcept>

namespace cairo
{

////////////////////////////////////////

font::font( cairo_font_face_t *face, std::string fam, std::string sty, double sz )
	: draw::font( std::move(fam), std::move(sty), sz )
{
	auto opts = cairo_font_options_create();
	cairo_font_options_set_antialias( opts, CAIRO_ANTIALIAS_SUBPIXEL );
	cairo_font_options_set_subpixel_order( opts, CAIRO_SUBPIXEL_ORDER_DEFAULT );
	cairo_font_options_set_hint_style( opts, CAIRO_HINT_STYLE_FULL );
	cairo_font_options_set_hint_metrics( opts, CAIRO_HINT_METRICS_ON );

	cairo_matrix_t mat, ctm;
	cairo_matrix_init_identity( &ctm );
	cairo_matrix_init_scale( &mat, sz, sz );

	_font = cairo_scaled_font_create( face, &mat, &ctm, opts );

	cairo_font_options_destroy( opts );

	cairo_font_extents_t ex;
	cairo_scaled_font_extents( _font, &ex );

	cairo_text_extents_t tex;
	cairo_scaled_font_text_extents( _font, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", &tex );

	_extents = { -tex.y_bearing, ex.descent, ex.height, ex.max_x_advance, ex.max_y_advance };
}

////////////////////////////////////////

font::~font( void )
{
	cairo_scaled_font_destroy( _font );
}

////////////////////////////////////////

draw::font_extents font::extents( void )
{
	return _extents;
}

////////////////////////////////////////

draw::text_extents font::extents( const std::string &utf8 )
{
	cairo_text_extents_t ex;
	cairo_scaled_font_text_extents( _font, utf8.c_str(), &ex );
	return { ex.x_bearing, ex.y_bearing, ex.width, ex.height, ex.x_advance, ex.y_advance };
}

////////////////////////////////////////

}

<|endoftext|>


<commit_before>#include <stdio.h>
#include <io.h>
#include <conio.h>
#include <iostream>
#include <cstdio>
using namespace std;
void file_copy(char* source, char* dest);
void reculsive_search(char* SCpath, char* DTpath);

void main()
{
	char* source_path[1000];
	char* destination_path[1000];

	scanf("%c", &source_path);
	scanf("%c", &destination_path);

	reculsive_search(*source_path, *destination_path);
	system("pause");
	return;
}

void file_copy(char* source, char* dest) {

	char buf[BUFSIZ];
	size_t size;

	FILE* fsource;
	FILE* fdest;
	fopen_s(&fsource, source, "rb");
	fopen_s(&fdest, dest, "wb");

	while (size = fread(buf, 1, BUFSIZ, fsource)) {
		fwrite(buf, 1, size, fdest);
	}

	fclose(fsource);
	fclose(fdest);

	return ;
}

void reculsive_search(char* SCpath, char* DTpath) {
	_finddata64i32_t fd;                             // ϻ ϴ ̸ ҽ path ¸ ϸ .  ٲ ǹ ״
	char SC_real_path[1000];

	sprintf(SC_real_path, "%s%s", SCpath, "\\*.*");     //  path  ϵ SC_real_path

	long handle = _findfirst(SC_real_path, &fd);      //    path   ְ? long ٲپ handle
	int result = 1;

	if (handle == -1) {
		printf("There were no files.\n");
		return;
	}

	result = _findnext(handle, &fd);					//  丮,  丮 ͵ ʱ ؼ next ι
	result = _findnext(handle, &fd);

	while (result != -1)                                        // ϸ  ٴٸ ʴ´ٸ
	{
		char source_path[1000];
		char destination_path[1000];

		printf("File: %s\n", fd.name);
		sprintf(source_path, "%s%s%s", SCpath, "\\",fd.name);
		sprintf(destination_path, "%s%s%s", DTpath, "\\", fd.name);

		file_copy(source_path, destination_path);              //  īѴ

		if (fd.attrib == 16) {                                 //  ߰ϸ Լ ȣѴ.
			char SC_next_path[1000];
			char DT_next_path[1000];
			sprintf(SC_next_path, "%s%s%s", SCpath, "\\", fd.name);
			sprintf(DT_next_path, "%s%s%s", DTpath, "\\", fd.name);

			printf("GOING INTO---->\n");
			reculsive_search(SC_next_path, DT_next_path);
		}
		result = _findnext(handle, &fd);                       // ī  path ϸ  ٴٶ ȮѴ.
	}
	_findclose(handle);
}

<commit_msg>Delete usb_backup.cpp<commit_after><|endoftext|>


<commit_before>/*************************************************************************
> File Name: ModifyHealth.cpp
> Project Name: Hearthstonepp
> Author: Young-Joong Kim
> Purpose: Implement ModifyHealthTask
> Created Time: 2018/07/21
> Copyright (c) 2018, Young-Joong Kim
*************************************************************************/
#include <Tasks/BasicTasks/ModifyHealthTask.h>

#include <algorithm>

namespace Hearthstonepp::BasicTasks
{
ModifyHealthTask::ModifyHealthTask(Character* character, BYTE damage)
    : m_character(character), m_damage(damage)
{
    // Do Nothing
}

TaskID ModifyHealthTask::GetTaskID() const
{
    return TaskID::MODIFY_HEALTH;
}

MetaData ModifyHealthTask::Impl(Player& user, Player&)
{
    int remainHealth = static_cast<int>(m_character->health) - m_damage;

    // if minion is exhausted
    if (remainHealth <= 0)
    {
        remainHealth = 0;
        user.usedMinion.emplace_back(m_character);

        // find minion and remove it from field
        auto& field = user.field;
        auto ptr = std::find(field.begin(), field.end(), m_character);
        if (ptr != field.end())
        {
            *ptr = nullptr;
            field.erase(ptr);
        }
    }

    // adjust health
    m_character->health = static_cast<size_t>(remainHealth);

    return MetaData::MODIFY_HEALTH_SUCCESS;
}
}  // namespace Hearthstonepp::BasicTasks<commit_msg>Update ModifyHealthTask - Move minion erasing routine to combat task<commit_after>/*************************************************************************
> File Name: ModifyHealth.cpp
> Project Name: Hearthstonepp
> Author: Young-Joong Kim
> Purpose: Implement ModifyHealthTask
> Created Time: 2018/07/21
> Copyright (c) 2018, Young-Joong Kim
*************************************************************************/
#include <Tasks/BasicTasks/ModifyHealthTask.h>

#include <algorithm>

namespace Hearthstonepp::BasicTasks
{
ModifyHealthTask::ModifyHealthTask(Character* character, BYTE damage)
    : m_character(character), m_damage(damage)
{
    // Do Nothing
}

TaskID ModifyHealthTask::GetTaskID() const
{
    return TaskID::MODIFY_HEALTH;
}

MetaData ModifyHealthTask::Impl(Player&, Player&)
{
    int remainHealth = static_cast<int>(m_character->health) - m_damage;

    // if minion is exhausted
    if (remainHealth <= 0)
    {
        remainHealth = 0;
    }

    // adjust health
    m_character->health = static_cast<size_t>(remainHealth);

    return MetaData::MODIFY_HEALTH_SUCCESS;
}
}  // namespace Hearthstonepp::BasicTasks<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This program 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 program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#define SOFA_HELPER_VECTOR_CPP
#include <sofa/helper/vector.h>
#include <sofa/helper/vector_device.h>
#include <sofa/helper/integer_id.h>
#include <sofa/helper/Factory.h>
#include <sofa/helper/BackTrace.h>
#include <cassert>
#include <iostream>

namespace sofa
{

namespace helper
{

#ifdef DEBUG_OUT_VECTOR
int cptid = 0;
#endif

void SOFA_HELPER_API vector_access_failure(const void* vec, unsigned size, unsigned i, const std::type_info& type)
{
    msg_error("vector") << "in vector<"<<gettypename(type)<<"> " << std::hex << (long)vec << std::dec << " size " << size << " : invalid index " << (int)i;
    BackTrace::dump();
    assert(i < size);
}

void SOFA_HELPER_API vector_access_failure(const void* vec, unsigned size, unsigned i, const std::type_info& type, const char* tindex)
{
    msg_error("vector") << "in vector<"<<gettypename(type)<<", integer_id<"<<tindex<<"> > " << std::hex << (long)vec << std::dec << " size " << size << " : invalid index " << (int)i;
    BackTrace::dump();
    assert(i < size);
}

/// Convert the string 's' into an unsigned int. The error are reported in msg & numErrors
/// is incremented.
int SOFA_HELPER_API getInteger(const std::string& s, std::stringstream& msg, unsigned int& numErrors)
{
    const char* attrstr=s.c_str();
    char* end=nullptr;
    int retval = strtol(attrstr, &end, 10);

    /// It is important to check that the string was totally parsed to report
    /// message to users because a silent error is the worse thing that can happen in UX.
    if(end !=  attrstr+strlen(attrstr))
    {
        if(numErrors<5)
            msg << "    - problem while parsing '" << s <<"' as Integer'. Replaced by 0 instead." << msgendl ;
        if(numErrors==5)
            msg << "   - ... " << msgendl;
        numErrors++ ;
        return 0 ;
    }
    return retval ;
}

/// Convert the string 's' into an unsigned int. The error are reported in msg & numErrors
/// is incremented.
unsigned int SOFA_HELPER_API getUnsignedInteger(const std::string& s, std::stringstream& msg, unsigned int& numErrors)
{
    const char* attrstr=s.c_str();
    char* end=nullptr;

    long long tmp = strtoll(attrstr, &end, 10);

    /// If there is minus sign we exit.
    if( tmp<0 ){
        if(numErrors<5)
            msg << "   - problem while parsing '" << s <<"' as Unsigned Integer because the minus sign is not allowed'. Replaced by 0 instead." << msgendl ;
        if(numErrors==5)
            msg << "   - ... " << msgendl;
        numErrors++ ;
        return 0 ;
    }

    /// It is important to check that the string was totally parsed to report
    /// message to users because a silent error is the worse thing that can happen in UX.
    if(end !=  attrstr+strlen(attrstr))
    {
        if(numErrors<5)
            msg << "   - problem while parsing '" << s <<"' as Unsigned Integer'. Replaced by 0 instead." << msgendl ;
        if(numErrors==5)
            msg << "   - ... " << msgendl;
        numErrors++ ;
        return 0 ;
    }

    return (unsigned int)tmp ;
}

} // namespace helper
} // namespace sofa
<commit_msg>[helper/vector.cpp] reorganize the code to simplify it a bit.<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This program 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 program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#define SOFA_HELPER_VECTOR_CPP
#include <sofa/helper/vector.h>
#include <sofa/helper/vector_device.h>
#include <sofa/helper/integer_id.h>
#include <sofa/helper/Factory.h>
#include <sofa/helper/BackTrace.h>
#include <cassert>
#include <iostream>

namespace sofa
{

namespace helper
{

#ifdef DEBUG_OUT_VECTOR
int cptid = 0;
#endif

void SOFA_HELPER_API vector_access_failure(const void* vec, unsigned size, unsigned i, const std::type_info& type)
{
    msg_error("vector") << "in vector<"<<gettypename(type)<<"> " << std::hex << (long)vec << std::dec << " size " << size << " : invalid index " << (int)i;
    BackTrace::dump();
    assert(i < size);
}

void SOFA_HELPER_API vector_access_failure(const void* vec, unsigned size, unsigned i, const std::type_info& type, const char* tindex)
{
    msg_error("vector") << "in vector<"<<gettypename(type)<<", integer_id<"<<tindex<<"> > " << std::hex << (long)vec << std::dec << " size " << size << " : invalid index " << (int)i;
    BackTrace::dump();
    assert(i < size);
}

/// Convert the string 's' into an unsigned int. The error are reported in msg & numErrors
/// is incremented.
int SOFA_HELPER_API getInteger(const std::string& s, std::stringstream& msg, unsigned int& numErrors)
{
    const char* attrstr=s.c_str();
    char* end=nullptr;
    int retval = strtol(attrstr, &end, 10);

    /// It is important to check that the string was totally parsed to report
    /// message to users because a silent error is the worse thing that can happen in UX.
    if(end ==  attrstr+strlen(attrstr))
        return retval ;

    if(numErrors<5)
        msg << "    - problem while parsing '" << s <<"' as Integer'. Replaced by 0 instead." << msgendl ;
    if(numErrors==5)
        msg << "   - ... " << msgendl;
    numErrors++ ;
    return 0 ;
}

/// Convert the string 's' into an unsigned int. The error are reported in msg & numErrors
/// is incremented.
unsigned int SOFA_HELPER_API getUnsignedInteger(const std::string& s, std::stringstream& msg, unsigned int& numErrors)
{
    const char* attrstr=s.c_str();
    char* end=nullptr;

    long long tmp = strtoll(attrstr, &end, 10);

    /// If there is minus sign we exit.
    if( tmp<0 ){
        if(numErrors<5)
            msg << "   - problem while parsing '" << s <<"' as Unsigned Integer because the minus sign is not allowed'. Replaced by 0 instead." << msgendl ;
        if(numErrors==5)
            msg << "   - ... " << msgendl;
        numErrors++ ;
        return 0 ;
    }

    /// It is important to check that the string was totally parsed to report
    /// message to users because a silent error is the worse thing that can happen in UX.
    if(end !=  attrstr+strlen(attrstr))
    {
        if(numErrors<5)
            msg << "   - problem while parsing '" << s <<"' as Unsigned Integer'. Replaced by 0 instead." << msgendl ;
        if(numErrors==5)
            msg << "   - ... " << msgendl;
        numErrors++ ;
        return 0 ;
    }

    return (unsigned int)tmp ;
}

} // namespace helper
} // namespace sofa
<|endoftext|>


<commit_before>#include "graphics/render_target/render_graph.h"
#include "api/video_api.h"
#include "graphics/render_context.h"
#include "graphics/material/material.h"
#include "graphics/render_target/render_graph_definition.h"
#include "graphics/render_target/render_graph_node.h"
#include "graphics/render_target/render_target.h"
#include "graphics/sprite/sprite.h"

using namespace Halley;

RenderGraph::RenderGraph()
{
	addOutputNode();
}

RenderGraph::RenderGraph(std::shared_ptr<const RenderGraphDefinition> def)
{
	loadDefinition(std::move(def));
}

void RenderGraph::loadDefinition(std::shared_ptr<const RenderGraphDefinition> definition)
{
	nodes.clear();
	nodeMap.clear();

	graphDefinition = std::move(definition);
	lastDefinitionVersion = graphDefinition->getAssetVersion();

	addOutputNode();

	for (const auto& nodeDefinition: graphDefinition->getNodes()) {
		addNode(nodeDefinition.id, std::make_unique<RenderGraphNode>(nodeDefinition));
	}
	for (const auto& connectionDefinition: graphDefinition->getConnections()) {
		auto* from = getNode(connectionDefinition.fromId);
		auto* to = getNode(connectionDefinition.toId);

		to->connectInput(connectionDefinition.toPin, *from, connectionDefinition.fromPin);
	}
}

void RenderGraph::update()
{
	// Hot-reload
	if (graphDefinition && graphDefinition->getAssetVersion() != lastDefinitionVersion) {
		loadDefinition(graphDefinition);
	}
}

void RenderGraph::addNode(String id, std::unique_ptr<RenderGraphNode> node)
{
	if (nodeMap.find(id) != nodeMap.end()) {
		throw Exception("Duplicate id \"" + id + "\" in RenderGraph.", HalleyExceptions::Graphics);
	}

	nodes.emplace_back(std::move(node));
	nodeMap[std::move(id)] = nodes.back().get();
}

void RenderGraph::addOutputNode()
{
	RenderGraphDefinition::Node nodeDef;
	nodeDef.method = RenderGraphMethod::Output;
	addNode("output", std::make_unique<RenderGraphNode>(nodeDef));
}

RenderGraphNode* RenderGraph::getNode(const String& id)
{
	return nodeMap.at(id);
}

void RenderGraph::render(const RenderContext& rc, VideoAPI& video)
{
	update();

	for (auto& node: nodes) {
		node->startRender();
	}

	const auto renderSize = rc.getDefaultRenderTarget().getViewPort().getSize();
	auto* outputNode = getNode("output");
	outputNode->prepareDependencyGraph(video, renderSize);

	for (auto& node: nodes) {
		node->determineIfNeedsRenderTarget();
	}
	for (auto& node: nodes) {
		node->allocateVideoResources(video);
	}

	std::vector<RenderGraphNode*> renderQueue;
	renderQueue.reserve(nodes.size());
	for (auto& node: nodes) {
		if (node->activeInCurrentPass && node->depsLeft == 0) {
			renderQueue.push_back(node.get());
		}
	}

	for (size_t i = 0; i < renderQueue.size(); ++i) {
		renderQueue[i]->render(*this, rc, renderQueue);
	}
}

const Camera* RenderGraph::tryGetCamera(std::string_view id) const
{
	const auto iter = cameras.find(id);
	if (iter != cameras.end()) {
		return &iter->second;
	} else {
		return nullptr;
	}
}

void RenderGraph::setCamera(std::string_view id, const Camera& camera)
{
	cameras[id] = camera;
}

const RenderGraph::PaintMethod* RenderGraph::tryGetPaintMethod(std::string_view id) const
{
	const auto iter = paintMethods.find(id);
	if (iter != paintMethods.end()) {
		return &iter->second;
	} else {
		return nullptr;
	}
}

void RenderGraph::setPaintMethod(std::string_view id, PaintMethod method)
{
	paintMethods[id] = std::move(method);
}

void RenderGraph::applyVariable(Material& material, const String& name, const ConfigNode& value) const
{
	if (value.getType() == ConfigNodeType::String) {
		variables.at(value.asString()).apply(material, name);
	} else if (value.getType() == ConfigNodeType::Float || value.getType() == ConfigNodeType::Int) {
		material.set(name, value.asFloat());
	}
}

void RenderGraph::setVariable(std::string_view name, float value)
{
	variables[name] = value;
}

void RenderGraph::setVariable(std::string_view name, Vector2f value)
{
	variables[name] = value;
}

void RenderGraph::setVariable(std::string_view name, Vector3f value)
{
	variables[name] = value;
}

void RenderGraph::setVariable(std::string_view name, Vector4f value)
{
	variables[name] = value;
}

void RenderGraph::setVariable(std::string_view name, Colour4f value)
{
	variables[name] = value;
}

void RenderGraph::Variable::apply(Material& material, const String& name) const
{
	switch (type) {
	case VariableType::Float:
		material.set(name, var.x);
		break;
	case VariableType::Float2:
		material.set(name, var.xy());
		break;
	case VariableType::Float3:
		material.set(name, var.xyz());
		break;
	case VariableType::Float4:
		material.set(name, var);
		break;
	}
}

RenderGraph::Variable& RenderGraph::Variable::operator=(float v)
{
	var = Vector4f(v, 0, 0, 0);
	type = VariableType::Float;
	return *this;
}

RenderGraph::Variable& RenderGraph::Variable::operator=(Vector2f v)
{
	var = Vector4f(v.x, v.y, 0, 0);
	type = VariableType::Float2;
	return *this;
}

RenderGraph::Variable& RenderGraph::Variable::operator=(Vector3f v)
{
	var = Vector4f(v.x, v.y, v.z, 0);
	type = VariableType::Float3;
	return *this;
}

RenderGraph::Variable& RenderGraph::Variable::operator=(Vector4f v)
{
	var = v;
	type = VariableType::Float4;
	return *this;
}

RenderGraph::Variable& RenderGraph::Variable::operator=(Colour4f v)
{
	var = Vector4f(v.r, v.g, v.b, v.a);
	type = VariableType::Float4;
	return *this;
}
<commit_msg>Flush painter at the end of RenderGraph execution<commit_after>#include "graphics/render_target/render_graph.h"
#include "api/video_api.h"
#include "graphics/render_context.h"
#include "graphics/material/material.h"
#include "graphics/render_target/render_graph_definition.h"
#include "graphics/render_target/render_graph_node.h"
#include "graphics/render_target/render_target.h"
#include "graphics/sprite/sprite.h"

using namespace Halley;

RenderGraph::RenderGraph()
{
	addOutputNode();
}

RenderGraph::RenderGraph(std::shared_ptr<const RenderGraphDefinition> def)
{
	loadDefinition(std::move(def));
}

void RenderGraph::loadDefinition(std::shared_ptr<const RenderGraphDefinition> definition)
{
	nodes.clear();
	nodeMap.clear();

	graphDefinition = std::move(definition);
	lastDefinitionVersion = graphDefinition->getAssetVersion();

	addOutputNode();

	for (const auto& nodeDefinition: graphDefinition->getNodes()) {
		addNode(nodeDefinition.id, std::make_unique<RenderGraphNode>(nodeDefinition));
	}
	for (const auto& connectionDefinition: graphDefinition->getConnections()) {
		auto* from = getNode(connectionDefinition.fromId);
		auto* to = getNode(connectionDefinition.toId);

		to->connectInput(connectionDefinition.toPin, *from, connectionDefinition.fromPin);
	}
}

void RenderGraph::update()
{
	// Hot-reload
	if (graphDefinition && graphDefinition->getAssetVersion() != lastDefinitionVersion) {
		loadDefinition(graphDefinition);
	}
}

void RenderGraph::addNode(String id, std::unique_ptr<RenderGraphNode> node)
{
	if (nodeMap.find(id) != nodeMap.end()) {
		throw Exception("Duplicate id \"" + id + "\" in RenderGraph.", HalleyExceptions::Graphics);
	}

	nodes.emplace_back(std::move(node));
	nodeMap[std::move(id)] = nodes.back().get();
}

void RenderGraph::addOutputNode()
{
	RenderGraphDefinition::Node nodeDef;
	nodeDef.method = RenderGraphMethod::Output;
	addNode("output", std::make_unique<RenderGraphNode>(nodeDef));
}

RenderGraphNode* RenderGraph::getNode(const String& id)
{
	return nodeMap.at(id);
}

void RenderGraph::render(const RenderContext& rc, VideoAPI& video)
{
	update();

	for (auto& node: nodes) {
		node->startRender();
	}

	const auto renderSize = rc.getDefaultRenderTarget().getViewPort().getSize();
	auto* outputNode = getNode("output");
	outputNode->prepareDependencyGraph(video, renderSize);

	for (auto& node: nodes) {
		node->determineIfNeedsRenderTarget();
	}
	for (auto& node: nodes) {
		node->allocateVideoResources(video);
	}

	std::vector<RenderGraphNode*> renderQueue;
	renderQueue.reserve(nodes.size());
	for (auto& node: nodes) {
		if (node->activeInCurrentPass && node->depsLeft == 0) {
			renderQueue.push_back(node.get());
		}
	}

	for (size_t i = 0; i < renderQueue.size(); ++i) {
		renderQueue[i]->render(*this, rc, renderQueue);
	}

	RenderContext(rc).bind([] (Painter& painter)
	{
		painter.flush();
	});
}

const Camera* RenderGraph::tryGetCamera(std::string_view id) const
{
	const auto iter = cameras.find(id);
	if (iter != cameras.end()) {
		return &iter->second;
	} else {
		return nullptr;
	}
}

void RenderGraph::setCamera(std::string_view id, const Camera& camera)
{
	cameras[id] = camera;
}

const RenderGraph::PaintMethod* RenderGraph::tryGetPaintMethod(std::string_view id) const
{
	const auto iter = paintMethods.find(id);
	if (iter != paintMethods.end()) {
		return &iter->second;
	} else {
		return nullptr;
	}
}

void RenderGraph::setPaintMethod(std::string_view id, PaintMethod method)
{
	paintMethods[id] = std::move(method);
}

void RenderGraph::applyVariable(Material& material, const String& name, const ConfigNode& value) const
{
	if (value.getType() == ConfigNodeType::String) {
		variables.at(value.asString()).apply(material, name);
	} else if (value.getType() == ConfigNodeType::Float || value.getType() == ConfigNodeType::Int) {
		material.set(name, value.asFloat());
	}
}

void RenderGraph::setVariable(std::string_view name, float value)
{
	variables[name] = value;
}

void RenderGraph::setVariable(std::string_view name, Vector2f value)
{
	variables[name] = value;
}

void RenderGraph::setVariable(std::string_view name, Vector3f value)
{
	variables[name] = value;
}

void RenderGraph::setVariable(std::string_view name, Vector4f value)
{
	variables[name] = value;
}

void RenderGraph::setVariable(std::string_view name, Colour4f value)
{
	variables[name] = value;
}

void RenderGraph::Variable::apply(Material& material, const String& name) const
{
	switch (type) {
	case VariableType::Float:
		material.set(name, var.x);
		break;
	case VariableType::Float2:
		material.set(name, var.xy());
		break;
	case VariableType::Float3:
		material.set(name, var.xyz());
		break;
	case VariableType::Float4:
		material.set(name, var);
		break;
	}
}

RenderGraph::Variable& RenderGraph::Variable::operator=(float v)
{
	var = Vector4f(v, 0, 0, 0);
	type = VariableType::Float;
	return *this;
}

RenderGraph::Variable& RenderGraph::Variable::operator=(Vector2f v)
{
	var = Vector4f(v.x, v.y, 0, 0);
	type = VariableType::Float2;
	return *this;
}

RenderGraph::Variable& RenderGraph::Variable::operator=(Vector3f v)
{
	var = Vector4f(v.x, v.y, v.z, 0);
	type = VariableType::Float3;
	return *this;
}

RenderGraph::Variable& RenderGraph::Variable::operator=(Vector4f v)
{
	var = v;
	type = VariableType::Float4;
	return *this;
}

RenderGraph::Variable& RenderGraph::Variable::operator=(Colour4f v)
{
	var = Vector4f(v.r, v.g, v.b, v.a);
	type = VariableType::Float4;
	return *this;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include "sal/config.h"

#include <cstdlib>
#include <cstring>
#include <vector>

#include "codemaker/global.hxx"
#include "codemaker/typemanager.hxx"
#include "rtl/ref.hxx"
#include "rtl/ustring.hxx"
#include "unoidl/unoidl.hxx"

TypeManager::TypeManager(): manager_(new unoidl::Manager) {}

TypeManager::~TypeManager() {}

void TypeManager::loadProvider(OUString const & uri, bool primary) {
    rtl::Reference< unoidl::Provider > prov(
        unoidl::loadProvider(manager_, uri));
    manager_->addProvider(prov);
    if (primary) {
        primaryProviders_.push_back(prov);
    }
}

bool TypeManager::foundAtPrimaryProvider(OUString const & name) const {
    if (name.isEmpty()) {
        return !primaryProviders_.empty();
    }
    for (std::vector< rtl::Reference< unoidl::Provider > >::const_iterator i(
             primaryProviders_.begin());
         i != primaryProviders_.end(); ++i)
    {
        if ((*i)->findEntity(name).is()) {
            return true;
        }
    }
    return false;
}

codemaker::UnoType::Sort TypeManager::getSort(
    OUString const & name, rtl::Reference< unoidl::Entity > * entity,
    rtl::Reference< unoidl::MapCursor > * cursor) const
{
    if (name.isEmpty()) {
        if (cursor != 0) {
            *cursor = manager_->createCursor("");
        }
        return codemaker::UnoType::SORT_MODULE;
    }
    if (name == "void") {
        return codemaker::UnoType::SORT_VOID;
    }
    if (name == "boolean") {
        return codemaker::UnoType::SORT_BOOLEAN;
    }
    if (name == "byte") {
        return codemaker::UnoType::SORT_BYTE;
    }
    if (name == "short") {
        return codemaker::UnoType::SORT_SHORT;
    }
    if (name == "unsigned short") {
        return codemaker::UnoType::SORT_UNSIGNED_SHORT;
    }
    if (name == "long") {
        return codemaker::UnoType::SORT_LONG;
    }
    if (name == "unsigned long") {
        return codemaker::UnoType::SORT_UNSIGNED_LONG;
    }
    if (name == "hyper") {
        return codemaker::UnoType::SORT_HYPER;
    }
    if (name == "unsigned hyper") {
        return codemaker::UnoType::SORT_UNSIGNED_HYPER;
    }
    if (name == "float") {
        return codemaker::UnoType::SORT_FLOAT;
    }
    if (name == "double") {
        return codemaker::UnoType::SORT_DOUBLE;
    }
    if (name == "char") {
        return codemaker::UnoType::SORT_CHAR;
    }
    if (name == "string") {
        return codemaker::UnoType::SORT_STRING;
    }
    if (name == "type") {
        return codemaker::UnoType::SORT_TYPE;
    }
    if (name == "any") {
        return codemaker::UnoType::SORT_ANY;
    }
    if (name.startsWith("[")) {
        return codemaker::UnoType::SORT_SEQUENCE_TYPE;
    }
    if (name.indexOf('<') != -1) {
        return codemaker::UnoType::SORT_INSTANTIATED_POLYMORPHIC_STRUCT_TYPE;
    }
    rtl::Reference< unoidl::Entity > ent(manager_->findEntity(name));
    if (!ent.is()) {
        throw CannotDumpException("Unknown entity '" + name + "'");
    }
    if (entity != 0) {
        *entity = ent;
    }
    switch (ent->getSort()) {
    case unoidl::Entity::SORT_MODULE:
        if (cursor != 0) {
            *cursor = manager_->createCursor(name);
        }
        return codemaker::UnoType::SORT_MODULE;
    case unoidl::Entity::SORT_ENUM_TYPE:
        return codemaker::UnoType::SORT_ENUM_TYPE;
    case unoidl::Entity::SORT_PLAIN_STRUCT_TYPE:
        return codemaker::UnoType::SORT_PLAIN_STRUCT_TYPE;
    case unoidl::Entity::SORT_POLYMORPHIC_STRUCT_TYPE_TEMPLATE:
        return codemaker::UnoType::SORT_POLYMORPHIC_STRUCT_TYPE_TEMPLATE;
    case unoidl::Entity::SORT_EXCEPTION_TYPE:
        return codemaker::UnoType::SORT_EXCEPTION_TYPE;
    case unoidl::Entity::SORT_INTERFACE_TYPE:
        return codemaker::UnoType::SORT_INTERFACE_TYPE;
    case unoidl::Entity::SORT_TYPEDEF:
        return codemaker::UnoType::SORT_TYPEDEF;
    case unoidl::Entity::SORT_CONSTANT_GROUP:
        return codemaker::UnoType::SORT_CONSTANT_GROUP;
    case unoidl::Entity::SORT_SINGLE_INTERFACE_BASED_SERVICE:
        return codemaker::UnoType::SORT_SINGLE_INTERFACE_BASED_SERVICE;
    case unoidl::Entity::SORT_ACCUMULATION_BASED_SERVICE:
        return codemaker::UnoType::SORT_ACCUMULATION_BASED_SERVICE;
    case unoidl::Entity::SORT_INTERFACE_BASED_SINGLETON:
        return codemaker::UnoType::SORT_INTERFACE_BASED_SINGLETON;
    case unoidl::Entity::SORT_SERVICE_BASED_SINGLETON:
        return codemaker::UnoType::SORT_SERVICE_BASED_SINGLETON;
    default:
        for (;;) { std::abort(); } // this cannot happen
    }
}

codemaker::UnoType::Sort TypeManager::decompose(
    OUString const & name, bool resolveTypedefs, OUString * nucleus,
    sal_Int32 * rank, std::vector< OUString > * arguments,
    rtl::Reference< unoidl::Entity > * entity) const
{
    sal_Int32 k;
    std::vector< OString > args;
    OUString n = b2u(codemaker::UnoType::decompose(u2b(name), &k, &args));
    for (;;) {
        rtl::Reference< unoidl::Entity > ent;
        codemaker::UnoType::Sort s = getSort(n, &ent);
        if (args.empty()
            != (s != codemaker::UnoType::SORT_POLYMORPHIC_STRUCT_TYPE_TEMPLATE))
        {
            throw CannotDumpException(
                "template arguments mismatch for \"" + n
                + "\" resolved from \"" + name + "\"");
        }
        switch (s) {
        case codemaker::UnoType::SORT_TYPEDEF:
            if (resolveTypedefs) {
                n = dynamic_cast< unoidl::TypedefEntity * >(ent.get())->
                    getType();
                while (n.startsWith("[]")) {
                    ++k; //TODO: overflow
                    n = n.copy(std::strlen("[]"));
                }
                break;
            }
            // fall through
        case codemaker::UnoType::SORT_VOID:
        case codemaker::UnoType::SORT_BOOLEAN:
        case codemaker::UnoType::SORT_BYTE:
        case codemaker::UnoType::SORT_SHORT:
        case codemaker::UnoType::SORT_UNSIGNED_SHORT:
        case codemaker::UnoType::SORT_LONG:
        case codemaker::UnoType::SORT_UNSIGNED_LONG:
        case codemaker::UnoType::SORT_HYPER:
        case codemaker::UnoType::SORT_UNSIGNED_HYPER:
        case codemaker::UnoType::SORT_FLOAT:
        case codemaker::UnoType::SORT_DOUBLE:
        case codemaker::UnoType::SORT_CHAR:
        case codemaker::UnoType::SORT_STRING:
        case codemaker::UnoType::SORT_TYPE:
        case codemaker::UnoType::SORT_ANY:
        case codemaker::UnoType::SORT_ENUM_TYPE:
        case codemaker::UnoType::SORT_PLAIN_STRUCT_TYPE:
        case codemaker::UnoType::SORT_EXCEPTION_TYPE:
        case codemaker::UnoType::SORT_INTERFACE_TYPE:
            if (nucleus != 0) {
                *nucleus = n;
            }
            if (rank != 0) {
                *rank = k;
            }
            if (arguments != 0) {
                arguments->clear();
            }
            if (entity != 0) {
                *entity = ent;
            }
            return s;
        case codemaker::UnoType::SORT_POLYMORPHIC_STRUCT_TYPE_TEMPLATE:
            if (args.size()
                != (dynamic_cast<
                    unoidl::PolymorphicStructTypeTemplateEntity * >(ent.get())->
                    getTypeParameters().size()))
            {
                throw CannotDumpException(
                    "bad number of template arguments for \"" + n
                    + "\" resolved from \"" + name + "\"");
            }
            if (nucleus != 0) {
                *nucleus = n;
            }
            if (rank != 0) {
                *rank = k;
            }
            if (arguments != 0) {
                arguments->clear();
                for (std::vector< OString >::iterator i(args.begin());
                     i != args.end(); ++i)
                {
                    arguments->push_back(b2u(*i));
                }
            }
            if (entity != 0) {
                *entity = ent;
            }
            return
                codemaker::UnoType::SORT_INSTANTIATED_POLYMORPHIC_STRUCT_TYPE;
        case codemaker::UnoType::SORT_SEQUENCE_TYPE:
            assert(false); // this cannot happen
            // fall through
        default:
            throw CannotDumpException(
                "unexpected \"" + n + "\" resolved from \"" + name
                + ("\"in call to TypeManager::decompose"));
        }
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fail for unkonwn entities<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include "sal/config.h"

#include <cstdlib>
#include <cstring>
#include <vector>

#include "codemaker/global.hxx"
#include "codemaker/typemanager.hxx"
#include "rtl/ref.hxx"
#include "rtl/ustring.hxx"
#include "unoidl/unoidl.hxx"

TypeManager::TypeManager(): manager_(new unoidl::Manager) {}

TypeManager::~TypeManager() {}

void TypeManager::loadProvider(OUString const & uri, bool primary) {
    rtl::Reference< unoidl::Provider > prov(
        unoidl::loadProvider(manager_, uri));
    manager_->addProvider(prov);
    if (primary) {
        primaryProviders_.push_back(prov);
    }
}

bool TypeManager::foundAtPrimaryProvider(OUString const & name) const {
    if (name.isEmpty()) {
        return !primaryProviders_.empty();
    }
    for (std::vector< rtl::Reference< unoidl::Provider > >::const_iterator i(
             primaryProviders_.begin());
         i != primaryProviders_.end(); ++i)
    {
        if ((*i)->findEntity(name).is()) {
            return true;
        }
    }
    if (!manager_->findEntity(name).is()) {
        throw CannotDumpException("Unknown entity '" + name + "'");
    }
    return false;
}

codemaker::UnoType::Sort TypeManager::getSort(
    OUString const & name, rtl::Reference< unoidl::Entity > * entity,
    rtl::Reference< unoidl::MapCursor > * cursor) const
{
    if (name.isEmpty()) {
        if (cursor != 0) {
            *cursor = manager_->createCursor("");
        }
        return codemaker::UnoType::SORT_MODULE;
    }
    if (name == "void") {
        return codemaker::UnoType::SORT_VOID;
    }
    if (name == "boolean") {
        return codemaker::UnoType::SORT_BOOLEAN;
    }
    if (name == "byte") {
        return codemaker::UnoType::SORT_BYTE;
    }
    if (name == "short") {
        return codemaker::UnoType::SORT_SHORT;
    }
    if (name == "unsigned short") {
        return codemaker::UnoType::SORT_UNSIGNED_SHORT;
    }
    if (name == "long") {
        return codemaker::UnoType::SORT_LONG;
    }
    if (name == "unsigned long") {
        return codemaker::UnoType::SORT_UNSIGNED_LONG;
    }
    if (name == "hyper") {
        return codemaker::UnoType::SORT_HYPER;
    }
    if (name == "unsigned hyper") {
        return codemaker::UnoType::SORT_UNSIGNED_HYPER;
    }
    if (name == "float") {
        return codemaker::UnoType::SORT_FLOAT;
    }
    if (name == "double") {
        return codemaker::UnoType::SORT_DOUBLE;
    }
    if (name == "char") {
        return codemaker::UnoType::SORT_CHAR;
    }
    if (name == "string") {
        return codemaker::UnoType::SORT_STRING;
    }
    if (name == "type") {
        return codemaker::UnoType::SORT_TYPE;
    }
    if (name == "any") {
        return codemaker::UnoType::SORT_ANY;
    }
    if (name.startsWith("[")) {
        return codemaker::UnoType::SORT_SEQUENCE_TYPE;
    }
    if (name.indexOf('<') != -1) {
        return codemaker::UnoType::SORT_INSTANTIATED_POLYMORPHIC_STRUCT_TYPE;
    }
    rtl::Reference< unoidl::Entity > ent(manager_->findEntity(name));
    if (!ent.is()) {
        throw CannotDumpException("Unknown entity '" + name + "'");
    }
    if (entity != 0) {
        *entity = ent;
    }
    switch (ent->getSort()) {
    case unoidl::Entity::SORT_MODULE:
        if (cursor != 0) {
            *cursor = manager_->createCursor(name);
        }
        return codemaker::UnoType::SORT_MODULE;
    case unoidl::Entity::SORT_ENUM_TYPE:
        return codemaker::UnoType::SORT_ENUM_TYPE;
    case unoidl::Entity::SORT_PLAIN_STRUCT_TYPE:
        return codemaker::UnoType::SORT_PLAIN_STRUCT_TYPE;
    case unoidl::Entity::SORT_POLYMORPHIC_STRUCT_TYPE_TEMPLATE:
        return codemaker::UnoType::SORT_POLYMORPHIC_STRUCT_TYPE_TEMPLATE;
    case unoidl::Entity::SORT_EXCEPTION_TYPE:
        return codemaker::UnoType::SORT_EXCEPTION_TYPE;
    case unoidl::Entity::SORT_INTERFACE_TYPE:
        return codemaker::UnoType::SORT_INTERFACE_TYPE;
    case unoidl::Entity::SORT_TYPEDEF:
        return codemaker::UnoType::SORT_TYPEDEF;
    case unoidl::Entity::SORT_CONSTANT_GROUP:
        return codemaker::UnoType::SORT_CONSTANT_GROUP;
    case unoidl::Entity::SORT_SINGLE_INTERFACE_BASED_SERVICE:
        return codemaker::UnoType::SORT_SINGLE_INTERFACE_BASED_SERVICE;
    case unoidl::Entity::SORT_ACCUMULATION_BASED_SERVICE:
        return codemaker::UnoType::SORT_ACCUMULATION_BASED_SERVICE;
    case unoidl::Entity::SORT_INTERFACE_BASED_SINGLETON:
        return codemaker::UnoType::SORT_INTERFACE_BASED_SINGLETON;
    case unoidl::Entity::SORT_SERVICE_BASED_SINGLETON:
        return codemaker::UnoType::SORT_SERVICE_BASED_SINGLETON;
    default:
        for (;;) { std::abort(); } // this cannot happen
    }
}

codemaker::UnoType::Sort TypeManager::decompose(
    OUString const & name, bool resolveTypedefs, OUString * nucleus,
    sal_Int32 * rank, std::vector< OUString > * arguments,
    rtl::Reference< unoidl::Entity > * entity) const
{
    sal_Int32 k;
    std::vector< OString > args;
    OUString n = b2u(codemaker::UnoType::decompose(u2b(name), &k, &args));
    for (;;) {
        rtl::Reference< unoidl::Entity > ent;
        codemaker::UnoType::Sort s = getSort(n, &ent);
        if (args.empty()
            != (s != codemaker::UnoType::SORT_POLYMORPHIC_STRUCT_TYPE_TEMPLATE))
        {
            throw CannotDumpException(
                "template arguments mismatch for \"" + n
                + "\" resolved from \"" + name + "\"");
        }
        switch (s) {
        case codemaker::UnoType::SORT_TYPEDEF:
            if (resolveTypedefs) {
                n = dynamic_cast< unoidl::TypedefEntity * >(ent.get())->
                    getType();
                while (n.startsWith("[]")) {
                    ++k; //TODO: overflow
                    n = n.copy(std::strlen("[]"));
                }
                break;
            }
            // fall through
        case codemaker::UnoType::SORT_VOID:
        case codemaker::UnoType::SORT_BOOLEAN:
        case codemaker::UnoType::SORT_BYTE:
        case codemaker::UnoType::SORT_SHORT:
        case codemaker::UnoType::SORT_UNSIGNED_SHORT:
        case codemaker::UnoType::SORT_LONG:
        case codemaker::UnoType::SORT_UNSIGNED_LONG:
        case codemaker::UnoType::SORT_HYPER:
        case codemaker::UnoType::SORT_UNSIGNED_HYPER:
        case codemaker::UnoType::SORT_FLOAT:
        case codemaker::UnoType::SORT_DOUBLE:
        case codemaker::UnoType::SORT_CHAR:
        case codemaker::UnoType::SORT_STRING:
        case codemaker::UnoType::SORT_TYPE:
        case codemaker::UnoType::SORT_ANY:
        case codemaker::UnoType::SORT_ENUM_TYPE:
        case codemaker::UnoType::SORT_PLAIN_STRUCT_TYPE:
        case codemaker::UnoType::SORT_EXCEPTION_TYPE:
        case codemaker::UnoType::SORT_INTERFACE_TYPE:
            if (nucleus != 0) {
                *nucleus = n;
            }
            if (rank != 0) {
                *rank = k;
            }
            if (arguments != 0) {
                arguments->clear();
            }
            if (entity != 0) {
                *entity = ent;
            }
            return s;
        case codemaker::UnoType::SORT_POLYMORPHIC_STRUCT_TYPE_TEMPLATE:
            if (args.size()
                != (dynamic_cast<
                    unoidl::PolymorphicStructTypeTemplateEntity * >(ent.get())->
                    getTypeParameters().size()))
            {
                throw CannotDumpException(
                    "bad number of template arguments for \"" + n
                    + "\" resolved from \"" + name + "\"");
            }
            if (nucleus != 0) {
                *nucleus = n;
            }
            if (rank != 0) {
                *rank = k;
            }
            if (arguments != 0) {
                arguments->clear();
                for (std::vector< OString >::iterator i(args.begin());
                     i != args.end(); ++i)
                {
                    arguments->push_back(b2u(*i));
                }
            }
            if (entity != 0) {
                *entity = ent;
            }
            return
                codemaker::UnoType::SORT_INSTANTIATED_POLYMORPHIC_STRUCT_TYPE;
        case codemaker::UnoType::SORT_SEQUENCE_TYPE:
            assert(false); // this cannot happen
            // fall through
        default:
            throw CannotDumpException(
                "unexpected \"" + n + "\" resolved from \"" + name
                + ("\"in call to TypeManager::decompose"));
        }
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <stan/agrad/rev/operators/operator_multiplication.hpp>
#include <test/unit/agrad/util.hpp>
#include <gtest/gtest.h>

TEST(AgradRev,a_times_b) {
  AVAR a = 2.0;
  AVAR b = -3.0;
  AVAR f = a * b;
  EXPECT_FLOAT_EQ(-6.0,f.val());

  AVEC x = createAVEC(a,b);
  VEC grad_f;
  f.grad(x,grad_f);
  EXPECT_FLOAT_EQ(-3.0,grad_f[0]);
  EXPECT_FLOAT_EQ(2.0,grad_f[1]);
}

TEST(AgradRev,a_times_a) {
  AVAR a = 2.0;
  AVAR f = a * a;
  EXPECT_FLOAT_EQ(4.0,f.val());

  AVEC x = createAVEC(a);
  VEC grad_f;
  f.grad(x,grad_f);
  EXPECT_FLOAT_EQ(4.0,grad_f[0]);
}

TEST(AgradRev,a_times_y) {
  AVAR a = 2.0;
  double y = -3.0;
  AVAR f = a * y;
  EXPECT_FLOAT_EQ(-6.0,f.val());

  AVEC x = createAVEC(a);
  VEC g;
  f.grad(x,g);
  EXPECT_FLOAT_EQ(-3.0,g[0]);
}

TEST(AgradRev,x_times_b) {
  double x = 2.0;
  AVAR b = -3.0;
  AVAR f = x * b;
  EXPECT_FLOAT_EQ(-6.0,f.val());

  AVEC v = createAVEC(b);
  VEC g;
  f.grad(v,g);
  EXPECT_FLOAT_EQ(2.0,g[0]);
}
<commit_msg>added NaN test for operator_multiplication<commit_after>#include <stan/agrad/rev/operators/operator_multiplication.hpp>
#include <test/unit/agrad/util.hpp>
#include <gtest/gtest.h>
#include <test/unit-agrad-rev/nan_util.hpp>
#include <stan/meta/traits.hpp>

TEST(AgradRev,a_times_b) {
  AVAR a = 2.0;
  AVAR b = -3.0;
  AVAR f = a * b;
  EXPECT_FLOAT_EQ(-6.0,f.val());

  AVEC x = createAVEC(a,b);
  VEC grad_f;
  f.grad(x,grad_f);
  EXPECT_FLOAT_EQ(-3.0,grad_f[0]);
  EXPECT_FLOAT_EQ(2.0,grad_f[1]);
}

TEST(AgradRev,a_times_a) {
  AVAR a = 2.0;
  AVAR f = a * a;
  EXPECT_FLOAT_EQ(4.0,f.val());

  AVEC x = createAVEC(a);
  VEC grad_f;
  f.grad(x,grad_f);
  EXPECT_FLOAT_EQ(4.0,grad_f[0]);
}

TEST(AgradRev,a_times_y) {
  AVAR a = 2.0;
  double y = -3.0;
  AVAR f = a * y;
  EXPECT_FLOAT_EQ(-6.0,f.val());

  AVEC x = createAVEC(a);
  VEC g;
  f.grad(x,g);
  EXPECT_FLOAT_EQ(-3.0,g[0]);
}

TEST(AgradRev,x_times_b) {
  double x = 2.0;
  AVAR b = -3.0;
  AVAR f = x * b;
  EXPECT_FLOAT_EQ(-6.0,f.val());

  AVEC v = createAVEC(b);
  VEC g;
  f.grad(v,g);
  EXPECT_FLOAT_EQ(2.0,g[0]);
}

struct multiply_fun {
  template <typename T0, typename T1>
  inline
  typename stan::return_type<T0,T1>::type
  operator()(const T0& arg1,
             const T1& arg2) const {
    return arg1*arg2;
  }
};

TEST(AgradRev, multiply_nan) {
  multiply_fun multiply_;
  test_nan(multiply_,3.0,5.0,false, false);
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2003 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/>.
 */

/*
 * $Log$
 * Revision 1.7  2003/12/15 19:04:55  neilg
 * fix segfault when a writeAnnotation() method was called
 *
 * Revision 1.6  2003/11/27 21:29:05  neilg
 * implement writeAnnotation; thanks to Dave Cargill
 *
 * Revision 1.5  2003/11/14 22:47:53  neilg
 * fix bogus log message from previous commit...
 *
 * Revision 1.4  2003/11/14 22:33:30  neilg
 * Second phase of schema component model implementation.
 * Implement XSModel, XSNamespaceItem, and the plumbing necessary
 * to connect them to the other components.
 * Thanks to David Cargill.
 *
 * Revision 1.3  2003/11/11 22:48:13  knoaman
 * Serialization of XSAnnotation.
 *
 * Revision 1.2  2003/11/06 19:28:11  knoaman
 * PSVI support for annotations.
 *
 * Revision 1.1  2003/09/16 14:33:36  neilg
 * PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
 *
 */

#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/util/XMLString.hpp>

#include <xercesc/framework/MemBufInputSource.hpp>

#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/dom/DOMElement.hpp>

XERCES_CPP_NAMESPACE_BEGIN

XSAnnotation::XSAnnotation(const XMLCh* const content,
                           MemoryManager * const manager):
    XSObject(XSConstants::ANNOTATION, 0, manager)
    , fContents(XMLString::replicate(content, manager))
    , fNext(0)
{
}

XSAnnotation::XSAnnotation(MemoryManager * const manager):
    XSObject(XSConstants::ANNOTATION, 0, manager)
    , fContents(0)
    , fNext(0)
{
}

XSAnnotation::~XSAnnotation()
{
    fMemoryManager->deallocate(fContents);

    if (fNext)
        delete fNext;
}

// XSAnnotation methods
void XSAnnotation::writeAnnotation(DOMNode* node, ANNOTATION_TARGET targetType)
{
    XercesDOMParser *parser = new (fMemoryManager) XercesDOMParser(0, fMemoryManager);
    parser->setDoNamespaces(true);
    parser->setValidationScheme(XercesDOMParser::Val_Never);

    DOMDocument* futureOwner = (targetType == W3C_DOM_ELEMENT) ?
        ((DOMElement*)node)->getOwnerDocument() :
        (DOMDocument*)node;

    MemBufInputSource* memBufIS = new (fMemoryManager) MemBufInputSource
    (
        (const XMLByte*)fContents
        , XMLString::stringLen(fContents)*sizeof(XMLCh)
        , ""
        , false
        , fMemoryManager
    );
    memBufIS->setEncoding(XMLUni::fgXMLChEncodingString);

    try
    {
        parser->parse(*memBufIS);
    }
    catch (const XMLException&)
    {
        throw;
    }

    DOMNode* newElem = futureOwner->importNode((parser->getDocument())->getDocumentElement(), true);
    node->insertBefore(newElem, node->getFirstChild());

    delete parser;
    delete memBufIS;
}

void XSAnnotation::writeAnnotation(ContentHandler* handler)
{
    SAX2XMLReader* parser = XMLReaderFactory::createXMLReader(fMemoryManager);
    parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
    parser->setFeature(XMLUni::fgSAX2CoreValidation, false);
    parser->setContentHandler(handler);

    MemBufInputSource* memBufIS = new (fMemoryManager) MemBufInputSource
    (
        (const XMLByte*)fContents
        , XMLString::stringLen(fContents)*sizeof(XMLCh)
        , ""
        , false
        , fMemoryManager
    );
    memBufIS->setEncoding(XMLUni::fgXMLChEncodingString);

    try
    {
        parser->parse(*memBufIS);
    }
    catch (const XMLException&)
    {
    }

    delete parser;
    delete memBufIS;
}

void XSAnnotation::setNext(XSAnnotation* const nextAnnotation)
{
    if (fNext)
        fNext->setNext(nextAnnotation);
    else
        fNext = nextAnnotation;
}

XSAnnotation* XSAnnotation::getNext()
{
    return fNext;
}

/***
 * Support for Serialization/De-serialization
 ***/

IMPL_XSERIALIZABLE_TOCREATE(XSAnnotation)

void XSAnnotation::serialize(XSerializeEngine& serEng)
{
    /***
     * Since we are pretty sure that fIdMap and fHashTable is
     * not shared by any other object, therefore there is no owned/referenced
     * issue. Thus we can serialize the raw data only, rather than serializing
     * both fIdMap and fHashTable.
     *
     * And we can rebuild the fIdMap and fHashTable out of the raw data during
     * deserialization.
     *
    ***/
    if (serEng.isStoring())
    {
        serEng.writeString(fContents);
        serEng<<fNext;
    }
    else
    {
        serEng.readString(fContents);
        serEng>>fNext;
    }
}

XERCES_CPP_NAMESPACE_END

<commit_msg>remove a throw clause inserted during debugging (but should we really swallow this exception?)<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2003 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/>.
 */

/*
 * $Log$
 * Revision 1.8  2003/12/19 07:18:56  neilg
 * remove a throw clause inserted during debugging (but should we really swallow this exception?)
 *
 * Revision 1.7  2003/12/15 19:04:55  neilg
 * fix segfault when a writeAnnotation() method was called
 *
 * Revision 1.6  2003/11/27 21:29:05  neilg
 * implement writeAnnotation; thanks to Dave Cargill
 *
 * Revision 1.5  2003/11/14 22:47:53  neilg
 * fix bogus log message from previous commit...
 *
 * Revision 1.4  2003/11/14 22:33:30  neilg
 * Second phase of schema component model implementation.
 * Implement XSModel, XSNamespaceItem, and the plumbing necessary
 * to connect them to the other components.
 * Thanks to David Cargill.
 *
 * Revision 1.3  2003/11/11 22:48:13  knoaman
 * Serialization of XSAnnotation.
 *
 * Revision 1.2  2003/11/06 19:28:11  knoaman
 * PSVI support for annotations.
 *
 * Revision 1.1  2003/09/16 14:33:36  neilg
 * PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
 *
 */

#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/util/XMLString.hpp>

#include <xercesc/framework/MemBufInputSource.hpp>

#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/dom/DOMElement.hpp>

XERCES_CPP_NAMESPACE_BEGIN

XSAnnotation::XSAnnotation(const XMLCh* const content,
                           MemoryManager * const manager):
    XSObject(XSConstants::ANNOTATION, 0, manager)
    , fContents(XMLString::replicate(content, manager))
    , fNext(0)
{
}

XSAnnotation::XSAnnotation(MemoryManager * const manager):
    XSObject(XSConstants::ANNOTATION, 0, manager)
    , fContents(0)
    , fNext(0)
{
}

XSAnnotation::~XSAnnotation()
{
    fMemoryManager->deallocate(fContents);

    if (fNext)
        delete fNext;
}

// XSAnnotation methods
void XSAnnotation::writeAnnotation(DOMNode* node, ANNOTATION_TARGET targetType)
{
    XercesDOMParser *parser = new (fMemoryManager) XercesDOMParser(0, fMemoryManager);
    parser->setDoNamespaces(true);
    parser->setValidationScheme(XercesDOMParser::Val_Never);

    DOMDocument* futureOwner = (targetType == W3C_DOM_ELEMENT) ?
        ((DOMElement*)node)->getOwnerDocument() :
        (DOMDocument*)node;

    MemBufInputSource* memBufIS = new (fMemoryManager) MemBufInputSource
    (
        (const XMLByte*)fContents
        , XMLString::stringLen(fContents)*sizeof(XMLCh)
        , ""
        , false
        , fMemoryManager
    );
    memBufIS->setEncoding(XMLUni::fgXMLChEncodingString);

    try
    {
        parser->parse(*memBufIS);
    }
    catch (const XMLException&)
    {
        // REVISIT:  should we really eat this?
    }

    DOMNode* newElem = futureOwner->importNode((parser->getDocument())->getDocumentElement(), true);
    node->insertBefore(newElem, node->getFirstChild());

    delete parser;
    delete memBufIS;
}

void XSAnnotation::writeAnnotation(ContentHandler* handler)
{
    SAX2XMLReader* parser = XMLReaderFactory::createXMLReader(fMemoryManager);
    parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
    parser->setFeature(XMLUni::fgSAX2CoreValidation, false);
    parser->setContentHandler(handler);

    MemBufInputSource* memBufIS = new (fMemoryManager) MemBufInputSource
    (
        (const XMLByte*)fContents
        , XMLString::stringLen(fContents)*sizeof(XMLCh)
        , ""
        , false
        , fMemoryManager
    );
    memBufIS->setEncoding(XMLUni::fgXMLChEncodingString);

    try
    {
        parser->parse(*memBufIS);
    }
    catch (const XMLException&)
    {
    }

    delete parser;
    delete memBufIS;
}

void XSAnnotation::setNext(XSAnnotation* const nextAnnotation)
{
    if (fNext)
        fNext->setNext(nextAnnotation);
    else
        fNext = nextAnnotation;
}

XSAnnotation* XSAnnotation::getNext()
{
    return fNext;
}

/***
 * Support for Serialization/De-serialization
 ***/

IMPL_XSERIALIZABLE_TOCREATE(XSAnnotation)

void XSAnnotation::serialize(XSerializeEngine& serEng)
{
    /***
     * Since we are pretty sure that fIdMap and fHashTable is
     * not shared by any other object, therefore there is no owned/referenced
     * issue. Thus we can serialize the raw data only, rather than serializing
     * both fIdMap and fHashTable.
     *
     * And we can rebuild the fIdMap and fHashTable out of the raw data during
     * deserialization.
     *
    ***/
    if (serEng.isStoring())
    {
        serEng.writeString(fContents);
        serEng<<fNext;
    }
    else
    {
        serEng.readString(fContents);
        serEng>>fNext;
    }
}

XERCES_CPP_NAMESPACE_END

<|endoftext|>


<commit_before>#include "command.hh"
#include "shared.hh"
#include "store-api.hh"
#include "sync.hh"
#include "thread-pool.hh"

#include <atomic>

using namespace nix;

struct CmdCopy : StorePathsCommand
{
    std::string srcUri, dstUri;

    CheckSigsFlag checkSigs = CheckSigs;

    SubstituteFlag substitute = NoSubstitute;

    CmdCopy()
        : StorePathsCommand(true)
    {
        mkFlag()
            .longName("from")
            .labels({"store-uri"})
            .description("URI of the source Nix store")
            .dest(&srcUri);
        mkFlag()
            .longName("to")
            .labels({"store-uri"})
            .description("URI of the destination Nix store")
            .dest(&dstUri);

        mkFlag()
            .longName("no-check-sigs")
            .description("do not require that paths are signed by trusted keys")
            .set(&checkSigs, NoCheckSigs);

        mkFlag()
            .longName("substitute")
            .shortName('s')
            .description("whether to try substitutes on the destination store (only supported by SSH)")
            .set(&substitute, Substitute);
    }

    std::string name() override
    {
        return "copy";
    }

    std::string description() override
    {
        return "copy paths between Nix stores";
    }

    Examples examples() override
    {
        return {
            Example{
                "To copy Firefox from the local store to a binary cache in file:///tmp/cache:",
                "nix copy --to file:///tmp/cache -r $(type -p firefox)"
            },
            Example{
                "To copy the entire current NixOS system closure to another machine via SSH:",
                "nix copy --to ssh://server -r /run/current-system"
            },
            Example{
                "To copy a closure from another machine via SSH:",
                "nix copy --from ssh://server -r /nix/store/a6cnl93nk1wxnq84brbbwr6hxw9gp2w9-blender-2.79-rc2"
            },
        };
    }

    ref<Store> createStore() override
    {
        return srcUri.empty() ? StoreCommand::createStore() : openStore(srcUri);
    }

    void run(ref<Store> srcStore, Paths storePaths) override
    {
        if (srcUri.empty() && dstUri.empty())
            throw UsageError("you must pass '--from' and/or '--to'");

        ref<Store> dstStore = dstUri.empty() ? openStore() : openStore(dstUri);

        copyPaths(srcStore, dstStore, PathSet(storePaths.begin(), storePaths.end()),
            NoRepair, checkSigs, substitute);
    }
};

static RegisterCommand r1(make_ref<CmdCopy>());
<commit_msg>nix-copy: fix examples<commit_after>#include "command.hh"
#include "shared.hh"
#include "store-api.hh"
#include "sync.hh"
#include "thread-pool.hh"

#include <atomic>

using namespace nix;

struct CmdCopy : StorePathsCommand
{
    std::string srcUri, dstUri;

    CheckSigsFlag checkSigs = CheckSigs;

    SubstituteFlag substitute = NoSubstitute;

    CmdCopy()
        : StorePathsCommand(true)
    {
        mkFlag()
            .longName("from")
            .labels({"store-uri"})
            .description("URI of the source Nix store")
            .dest(&srcUri);
        mkFlag()
            .longName("to")
            .labels({"store-uri"})
            .description("URI of the destination Nix store")
            .dest(&dstUri);

        mkFlag()
            .longName("no-check-sigs")
            .description("do not require that paths are signed by trusted keys")
            .set(&checkSigs, NoCheckSigs);

        mkFlag()
            .longName("substitute")
            .shortName('s')
            .description("whether to try substitutes on the destination store (only supported by SSH)")
            .set(&substitute, Substitute);
    }

    std::string name() override
    {
        return "copy";
    }

    std::string description() override
    {
        return "copy paths between Nix stores";
    }

    Examples examples() override
    {
        return {
            Example{
                "To copy Firefox from the local store to a binary cache in file:///tmp/cache:",
                "nix copy --to file:///tmp/cache $(type -p firefox)"
            },
            Example{
                "To copy the entire current NixOS system closure to another machine via SSH:",
                "nix copy --to ssh://server /run/current-system"
            },
            Example{
                "To copy a closure from another machine via SSH:",
                "nix copy --from ssh://server /nix/store/a6cnl93nk1wxnq84brbbwr6hxw9gp2w9-blender-2.79-rc2"
            },
        };
    }

    ref<Store> createStore() override
    {
        return srcUri.empty() ? StoreCommand::createStore() : openStore(srcUri);
    }

    void run(ref<Store> srcStore, Paths storePaths) override
    {
        if (srcUri.empty() && dstUri.empty())
            throw UsageError("you must pass '--from' and/or '--to'");

        ref<Store> dstStore = dstUri.empty() ? openStore() : openStore(dstUri);

        copyPaths(srcStore, dstStore, PathSet(storePaths.begin(), storePaths.end()),
            NoRepair, checkSigs, substitute);
    }
};

static RegisterCommand r1(make_ref<CmdCopy>());
<|endoftext|>