<commit_before>//
// Name:     app.cpp
// Purpose:  The application class for a wxWindows application.
//
// Copyright (c) 2001-2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
#pragma implementation
#pragma interface
#endif

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "vtlib/vtlib.h"
#include "vtlib/core/NavEngines.h"
#include "vtlib/core/vtSOG.h"
#include "vtdata/vtLog.h"

#include "app.h"
#include "frame.h"

static void Args(int argc, wxChar **argv)
{
   return;
}

IMPLEMENT_APP(vtApp)

//
// Initialize the app object
//
bool vtApp::OnInit(void)
{
	Args(argc, argv);

	g_Log._StartLog("debug.txt");
	VTLOG("CManager\n");

	//
	// Create the main frame window
	//
	VTLOG("Creating frame\n");
	wxString title = _T("Content Manager");
	vtFrame *frame = new vtFrame(NULL, title,
		wxPoint(50, 50), wxSize(800, 600));

	VTLOG("Setup scene\n");
	vtScene *pScene = vtGetScene();
	pScene->Init();
	pScene->SetBgColor(RGBf(0.5f, 0.5f, 0.5f));

	VTLOG(" creating camera\n");
	vtCamera *pCamera = pScene->GetCamera();
	pCamera->SetName2("Default Camera");

	m_pRoot = new vtGroup();
	pScene->SetRoot(m_pRoot);

#if VTLIB_SGL
	CreateTestSGLScene();
#endif

	// make a simple directional light
	VTLOG(" creating light\n");
	vtLight *pLight = new vtLight();
	pLight->SetName2("Light");
	vtMovLight *pMovLight = new vtMovLight(pLight);
	pMovLight->SetName2("Movable Light");
	pLight->SetAmbient2(RGBf(1, 1, 1));
	pMovLight->SetTrans(FPoint3(0.0f, 0.0f, 5.0f));
	m_pRoot->AddChild(pMovLight);

#if 0
#if 0
	// make a yellow sphere
	vtMaterialArray *pMats = new vtMaterialArray();
	pMats->AddRGBMaterial(RGBf(1.0f, 1.0f, 0.0f), RGBf(0.0f, 0.0f, 1.0f));
	vtGeom *pGeom = CreateSphereGeom(pMats, 0, VT_Normals, 0.5, 16);
	pGeom->SetName2("Yellow Sphere");

	OutputSOG osog;

	FILE *fp = fopen("output.sog", "wb");
	osog.WriteHeader(fp);
	osog.WriteSingleGeometry(fp, pGeom);
	fclose(fp);
	m_pRoot->AddChild(pGeom);
#else
	InputSOG isog;

	FILE *fp = fopen("output.sog", "rb");
	vtGroup *pGroup = new vtGroup;
	bool success = isog.ReadContents(fp, pGroup);
	fclose(fp);
	m_pRoot->AddChild(pGroup);
#endif
#endif

	// make a trackball controller for the camera
	VTLOG(" creating trackball\n");
	m_pTrackball = new vtTrackball(3.0f);
	m_pTrackball->SetTarget(pScene->GetCamera());
	m_pTrackball->SetName2("Trackball");
	m_pTrackball->SetRotateButton(VT_LEFT, 0);
	m_pTrackball->SetZoomButton(VT_RIGHT, 0);
	m_pTrackball->SetZoomScale(3000.0f);
	pScene->AddEngine(m_pTrackball);

	VTLOG(" end of OnInit\n");
	return TRUE;
}

int vtApp::OnExit(void)
{
	m_pRoot->Release();
	return 0;
}

<commit_msg>enabled translate button for trackball, fixed memleak with camera<commit_after>//
// Name:     app.cpp
// Purpose:  The application class the CManager application.
//
// Copyright (c) 2001-2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
#pragma implementation
#pragma interface
#endif

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "vtlib/vtlib.h"
#include "vtlib/core/NavEngines.h"
#include "vtlib/core/vtSOG.h"
#include "vtdata/vtLog.h"

#include "app.h"
#include "frame.h"

static void Args(int argc, wxChar **argv)
{
   return;
}

IMPLEMENT_APP(vtApp)

//
// Initialize the app object
//
bool vtApp::OnInit(void)
{
	Args(argc, argv);

	g_Log._StartLog("debug.txt");
	VTLOG("CManager\n");

	//
	// Create the main frame window
	//
	VTLOG("Creating frame\n");
	wxString title = _T("Content Manager");
	vtFrame *frame = new vtFrame(NULL, title,
		wxPoint(50, 50), wxSize(800, 600));

	VTLOG("Setup scene\n");
	vtScene *pScene = vtGetScene();
	pScene->Init();
	pScene->SetBgColor(RGBf(0.5f, 0.5f, 0.5f));

	VTLOG(" creating camera\n");
	vtCamera *pCamera = pScene->GetCamera();
	pCamera->SetName2("Default Camera");

	m_pRoot = new vtGroup();
	pScene->SetRoot(m_pRoot);

#if VTLIB_SGL
	CreateTestSGLScene();
#endif

	// make a simple directional light
	VTLOG(" creating light\n");
	vtLight *pLight = new vtLight();
	pLight->SetName2("Light");
	vtMovLight *pMovLight = new vtMovLight(pLight);
	pMovLight->SetName2("Movable Light");
	pLight->SetAmbient(RGBf(1, 1, 1));
	pMovLight->SetTrans(FPoint3(0.0f, 0.0f, 5.0f));
	m_pRoot->AddChild(pMovLight);

	// SOG testing, currently disabled
#if 0
#if 0
	// make a yellow sphere
	vtMaterialArray *pMats = new vtMaterialArray();
	pMats->AddRGBMaterial(RGBf(1.0f, 1.0f, 0.0f), RGBf(0.0f, 0.0f, 1.0f));
	vtGeom *pGeom = CreateSphereGeom(pMats, 0, VT_Normals, 0.5, 16);
	pGeom->SetName2("Yellow Sphere");
	pMats->Release();

	OutputSOG osog;

	FILE *fp = fopen("output.sog", "wb");
	osog.WriteHeader(fp);
	osog.WriteSingleGeometry(fp, pGeom);
	fclose(fp);
	m_pRoot->AddChild(pGeom);
#else
	InputSOG isog;

	FILE *fp = fopen("output.sog", "rb");
	vtGroup *pGroup = new vtGroup;
	bool success = isog.ReadContents(fp, pGroup);
	fclose(fp);
	m_pRoot->AddChild(pGroup);
#endif
#endif

	// make a trackball controller for the camera
	VTLOG(" creating trackball\n");
	m_pTrackball = new vtTrackball(3.0f);
	m_pTrackball->SetTarget(pScene->GetCamera());
	m_pTrackball->SetName2("Trackball");
	m_pTrackball->SetRotateButton(VT_LEFT, 0);
	m_pTrackball->SetZoomButton(VT_LEFT|VT_RIGHT, 0);
	m_pTrackball->SetZoomScale(3000.0f);
	m_pTrackball->SetTranslateButton(VT_RIGHT, 0);
	pScene->AddEngine(m_pTrackball);

	// Memleak Testing
//	GetMainFrame()->AddModelFromFile("E:/3D/IDA Free Models/schoolbus.flt");
//	GetMainFrame()->AddNewItem();

	VTLOG(" end of OnInit\n");
	return TRUE;
}

int vtApp::OnExit(void)
{
	vtCamera *pCamera = vtGetScene()->GetCamera();
	pCamera->Release();

	m_pRoot->Release();
	return 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2014, Robert Escriva
// 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 libtreadstone 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.

// C
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// POSIX
#include <errno.h>

// e
#include <e/guard.h>

// Treadstone
#include <treadstone.h>

int
main(int argc, const char* argv[])
{
    while (true)
    {
        char* line = NULL;
        size_t line_sz = 0;
        ssize_t amt = getline(&line, &line_sz, stdin);

        if (amt < 0)
        {
            if (feof(stdin) != 0)
            {
                break;
            }

            fprintf(stderr, "could not read from stdin: %s\n", strerror(ferror(stdin)));
            return EXIT_FAILURE;
        }

        if (!line)
        {
            continue;
        }

        e::guard line_guard = e::makeguard(free, line);
        (void) line_guard;

        if (amt < 1)
        {
            continue;
        }

        line[amt - 1] = '\0';
        unsigned char* binary1 = NULL;
        size_t binary1_sz = 0;

        if (treadstone_json_to_binary(line, &binary1, &binary1_sz) < 0)
        {
            printf("failure on binary1 conversion\n");
            continue;
        }

        assert(binary1);
        e::guard binary1_guard = e::makeguard(free, binary1);
        char* json1 = NULL;

        if (treadstone_binary_to_json(binary1, binary1_sz, &json1) < 0)
        {
            printf("failure on json1 conversion\n");
            continue;
        }

        assert(json1);
        e::guard json1_guard = e::makeguard(free, json1);
        unsigned char* binary2 = NULL;
        size_t binary2_sz = 0;

        if (treadstone_json_to_binary(json1, &binary2, &binary2_sz) < 0)
        {
            printf("failure on binary2 conversion\n");
            continue;
        }

        assert(binary2);
        e::guard binary2_guard = e::makeguard(free, binary2);
        char* json2 = NULL;

        if (treadstone_binary_to_json(binary2, binary2_sz, &json2) < 0)
        {
            printf("failure on json2 conversion\n");
            continue;
        }

        assert(json2);
        e::guard json2_guard = e::makeguard(free, json2);
        unsigned char* binary3 = NULL;
        size_t binary3_sz = 0;

        if (treadstone_json_to_binary(json1, &binary3, &binary3_sz) < 0)
        {
            printf("failure on binary3 conversion\n");
            continue;
        }

        assert(binary3);
        e::guard binary3_guard = e::makeguard(free, binary3);
        char* json3 = NULL;

        if (treadstone_binary_to_json(binary3, binary3_sz, &json3) < 0)
        {
            printf("failure on json3 conversion\n");
            continue;
        }

        assert(json3);
        e::guard json3_guard = e::makeguard(free, json3);

        bool json_same = strcmp(json1, json2) == 0 &&
                         strcmp(json2, json3) == 0;
        bool binary_same = binary2_sz == binary3_sz &&
                           memcmp(binary2, binary3, binary2_sz) == 0;

        if (!json_same || !binary_same)
        {
            printf("json_same=%s binary_same=%s\n\t%s\n",
                   (json_same ? "yes" : "no"),
                   (binary_same ? "yes" : "no"),
                   line);
        }
    }

    (void) argc;
    (void) argv;
    return EXIT_SUCCESS;
}
<commit_msg>Compile on freebsd<commit_after>// Copyright (c) 2014, Robert Escriva
// 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 libtreadstone 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.

#define _WITH_GETLINE

// C
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// POSIX
#include <errno.h>

// e
#include <e/guard.h>

// Treadstone
#include <treadstone.h>

int
main(int argc, const char* argv[])
{
    while (true)
    {
        char* line = NULL;
        size_t line_sz = 0;
        ssize_t amt = getline(&line, &line_sz, stdin);

        if (amt < 0)
        {
            if (feof(stdin) != 0)
            {
                break;
            }

            fprintf(stderr, "could not read from stdin: %s\n", strerror(ferror(stdin)));
            return EXIT_FAILURE;
        }

        if (!line)
        {
            continue;
        }

        e::guard line_guard = e::makeguard(free, line);
        (void) line_guard;

        if (amt < 1)
        {
            continue;
        }

        line[amt - 1] = '\0';
        unsigned char* binary1 = NULL;
        size_t binary1_sz = 0;

        if (treadstone_json_to_binary(line, &binary1, &binary1_sz) < 0)
        {
            printf("failure on binary1 conversion\n");
            continue;
        }

        assert(binary1);
        e::guard binary1_guard = e::makeguard(free, binary1);
        char* json1 = NULL;

        if (treadstone_binary_to_json(binary1, binary1_sz, &json1) < 0)
        {
            printf("failure on json1 conversion\n");
            continue;
        }

        assert(json1);
        e::guard json1_guard = e::makeguard(free, json1);
        unsigned char* binary2 = NULL;
        size_t binary2_sz = 0;

        if (treadstone_json_to_binary(json1, &binary2, &binary2_sz) < 0)
        {
            printf("failure on binary2 conversion\n");
            continue;
        }

        assert(binary2);
        e::guard binary2_guard = e::makeguard(free, binary2);
        char* json2 = NULL;

        if (treadstone_binary_to_json(binary2, binary2_sz, &json2) < 0)
        {
            printf("failure on json2 conversion\n");
            continue;
        }

        assert(json2);
        e::guard json2_guard = e::makeguard(free, json2);
        unsigned char* binary3 = NULL;
        size_t binary3_sz = 0;

        if (treadstone_json_to_binary(json1, &binary3, &binary3_sz) < 0)
        {
            printf("failure on binary3 conversion\n");
            continue;
        }

        assert(binary3);
        e::guard binary3_guard = e::makeguard(free, binary3);
        char* json3 = NULL;

        if (treadstone_binary_to_json(binary3, binary3_sz, &json3) < 0)
        {
            printf("failure on json3 conversion\n");
            continue;
        }

        assert(json3);
        e::guard json3_guard = e::makeguard(free, json3);

        bool json_same = strcmp(json1, json2) == 0 &&
                         strcmp(json2, json3) == 0;
        bool binary_same = binary2_sz == binary3_sz &&
                           memcmp(binary2, binary3, binary2_sz) == 0;

        if (!json_same || !binary_same)
        {
            printf("json_same=%s binary_same=%s\n\t%s\n",
                   (json_same ? "yes" : "no"),
                   (binary_same ? "yes" : "no"),
                   line);
        }
    }

    (void) argc;
    (void) argv;
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <mitkImage.h>
#include <mitkDataTree.h>
#include <mitkRenderWindow.h>
#include <mitkImageMapper2D.h>
#include <mitkLevelWindow.h>
#include <mitkLevelWindowProperty.h>

#include <mitkNativeRenderWindowInteractor.h>

#include "itkTextOutput.h"

#include <fstream>
int mitkDataTreeTest(int argc, char* argv[])
{
  itk::OutputWindow::SetInstance(
       itk::TextOutput::New().GetPointer() );

  //Create Image out of nowhere
	mitk::Image::Pointer image;
	mitk::PixelType pt(typeid(int));
	unsigned int dim[]={100,100,20};

  std::cout << "Creating image: ";
	image=mitk::Image::New();
image->DebugOn();
	image->Initialize(mitk::PixelType(typeid(int)), 3, dim);
  int *p = (int*)image->GetData();

  int size = dim[0]*dim[1]*dim[2];
  int i;
  for(i=0; i<size; ++i, ++p)
    *p=i;
  std::cout<<"[PASSED]"<<std::endl;

  {
    std::cout << "Creating node: ";
    mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New();
    node->SetData(image);
    std::cout<<"[PASSED]"<<std::endl;
  }

  std::cout << "Creating node: ";
  mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New();
  node->SetData(image);
  std::cout<<"[PASSED]"<<std::endl;

  std::cout << "Creating tree: ";
  mitk::DataTree::Pointer tree;
  tree=mitk::DataTree::New(); //@FIXME: da DataTreeIteratorClone keinen Smartpointer auf DataTree hlt, wird tree sonst gelscht.
  std::cout<<"[PASSED]"<<std::endl;

  std::cout << "Creating iterator on tree: ";
  mitk::DataTreePreOrderIterator it(tree);
  std::cout<<"[PASSED]"<<std::endl;

  std::cout << "Adding node via iterator: ";
  it.Add(node);
  std::cout<<"[PASSED]"<<std::endl;

  std::cout << "Adding level-window property: ";
  mitk::LevelWindowProperty::Pointer levWinProp = new mitk::LevelWindowProperty();
  mitk::LevelWindow levelwindow;
  levelwindow.SetAuto( image );
  levWinProp->SetLevelWindow( levelwindow );
  node->GetPropertyList()->SetProperty( "levelwindow", levWinProp );
  std::cout<<"[PASSED]"<<std::endl;

  std::cout<<"[TEST DONE]"<<std::endl;
  return EXIT_SUCCESS;
}
<commit_msg>ENH: enable data tree test and test to remove node<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <mitkImage.h>
#include <mitkDataTree.h>
#include <mitkRenderWindow.h>
#include <mitkImageMapper2D.h>
#include <mitkLevelWindow.h>
#include <mitkLevelWindowProperty.h>

#include <mitkNativeRenderWindowInteractor.h>

#include "itkTextOutput.h"

#include <fstream>
int mitkDataTreeTest(int argc, char* argv[])
{
  itk::OutputWindow::SetInstance(
       itk::TextOutput::New().GetPointer() );

  //Create Image out of nowhere
	mitk::Image::Pointer image;
	mitk::PixelType pt(typeid(int));
	unsigned int dim[]={100,100,20};

  std::cout << "Creating image: ";
	image=mitk::Image::New();
  image->DebugOn();
	image->Initialize(mitk::PixelType(typeid(int)), 3, dim);
  int *p = (int*)image->GetData();

  int size = dim[0]*dim[1]*dim[2];
  int i;
  for(i=0; i<size; ++i, ++p)
    *p=i;
  std::cout<<"[PASSED]"<<std::endl;

  {
    std::cout << "Creating node: ";
    mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New();
    node->SetData(image);
    std::cout<<"[PASSED]"<<std::endl;
  }

  std::cout << "Creating node: ";
  mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New();
  node->SetData(image);
  std::cout<<"[PASSED]"<<std::endl;

  std::cout << "Creating tree: ";
  mitk::DataTree::Pointer tree;
  tree=mitk::DataTree::New(); //@FIXME: da DataTreeIteratorClone keinen Smartpointer auf DataTree hlt, wird tree sonst gelscht.
  std::cout<<"[PASSED]"<<std::endl;

  std::cout << "Creating iterator on tree: ";
  mitk::DataTreePreOrderIterator it(tree);
  std::cout<<"[PASSED]"<<std::endl;

  std::cout << "Adding node via iterator: ";
  it.Add(node);
  std::cout<<"[PASSED]"<<std::endl;

  std::cout << "Adding level-window property: ";
  mitk::LevelWindowProperty::Pointer levWinProp = new mitk::LevelWindowProperty();
  mitk::LevelWindow levelwindow;
  levelwindow.SetAuto( image );
  levWinProp->SetLevelWindow( levelwindow );
  node->GetPropertyList()->SetProperty( "levelwindow", levWinProp );
  std::cout<<"[PASSED]"<<std::endl;

  std::cout << "Remove node after incrementing iterator: ";
  it++;
  if (it.Remove()) std::cout<<"[PASSED]"<<std::endl;
  else std::cout<<"[FAILED]"<<std::endl;

  std::cout<<"[TEST DONE]"<<std::endl;
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/// @file
/// @author uentity
/// @date 22.11.2017
/// @brief BS tree-related functions impl
/// @copyright
/// 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 https://mozilla.org/MPL/2.0/

#include <bs/tree/tree.h>
#include "tree_impl.h"

#include <set>
#include <boost/uuid/uuid_io.hpp>
#include <boost/algorithm/string.hpp>

NAMESPACE_BEGIN(blue_sky) NAMESPACE_BEGIN(tree)

using Key = node::Key;
template<Key K> using Key_type = typename node::Key_type<K>;

/*-----------------------------------------------------------------------------
 *  impl details
 *-----------------------------------------------------------------------------*/
// hidden
namespace {

template<class Callback>
void walk_impl(
	const std::vector<sp_link>& nodes, const Callback& step_f,
	const bool topdown, const bool follow_symlinks,
	std::set<Key_type<Key::ID>> active_symlinks = {}
) {
	sp_node cur_node;
	std::vector<sp_link> next_nodes;
	std::vector<sp_link> next_leafs;
	// for each node
	for(const auto& N : nodes) {
		if(!N) continue;
		// remember symlink
		const auto is_symlink = N->type_id() == "sym_link";
		if(is_symlink) {
			if(follow_symlinks && active_symlinks.find(N->id()) == active_symlinks.end())
				active_symlinks.insert(N->id());
			else continue;
		}

		// obtain node from link honoring LazyLoad flag
		cur_node = ( !(N->flags() & link::LazyLoad) || N->req_status(link::Req::DataNode) == link::ReqStatus::OK ) ?
			N->data_node() : nullptr;

		next_nodes.clear();
		next_leafs.clear();

		if(cur_node) {
			// for each link in node
			for(const auto& l : *cur_node) {
				// collect nodes
				if(l->data_node()) {
					next_nodes.push_back(l);
				}
				else
					next_leafs.push_back(l);
			}
		}

		// if `topdown` == true, process this node BEFORE leafs processing
		if(topdown)
			step_f(N, next_nodes, next_leafs);
		// process list of next nodes
		if(!next_nodes.empty())
			walk_impl(next_nodes, step_f, topdown, follow_symlinks, active_symlinks);
		// if walking from most deep subdir, process current node after all subtree
		if(!topdown)
			step_f(N, next_nodes, next_leafs);

		// forget symlink
		if(is_symlink)
			active_symlinks.erase(N->id());
	}
}

inline std::string link2path_unit(const sp_clink& l, Key path_unit) {
	switch(path_unit) {
	default:
	case Key::ID : return boost::uuids::to_string(l->id());
	case Key::OID : return l->oid();
	case Key::Name : return l->name();
	case Key::Type : return l->type_id();
	}
}

} // hidden ns

// public
NAMESPACE_BEGIN(detail)

sp_link walk_down_tree(const std::string& cur_lid, const sp_node& level, node::Key path_unit) {
	if(cur_lid != "..") {
		const auto next = level->find(cur_lid, path_unit);
		if(next != level->end()) {
			return *next;
		}
	}
	return nullptr;
}

NAMESPACE_END(detail)

/*-----------------------------------------------------------------------------
 *  public API
 *-----------------------------------------------------------------------------*/
std::string abspath(sp_clink l, Key path_unit) {
	std::deque<std::string> res;
	while(l) {
		res.push_front(link2path_unit(l, path_unit));
		if(const auto parent = l->owner()) {
			l = parent->handle();
		}
		else return boost::join(res, "/");
	}
	// leadind slash is appended only if we have 'real' root node without self link
	return std::string("/") + boost::join(res, "/");

	// another possible implementation without multiple returns
	// just leave it here -)
	//sp_node parent;
	//do {
	//	if(l)
	//		res.push_front(human_readable ? l->name() : boost::uuids::to_string(l->id()));
	//	else {
	//		// for root node
	//		res.emplace_front("");
	//		break;
	//	}
	//	if((parent = l->owner())) {
	//		l = parent->handle();
	//	}
	//} while(parent);
	//return boost::join(res, "/");
}

std::string convert_path(
	std::string src_path, const sp_clink& start,
	Key src_path_unit, Key dst_path_unit
) {
	std::string res_path;
	// convert from ID-based path to human-readable
	const auto converter = [&res_path, src_path_unit, dst_path_unit](std::string part, const sp_node& level) {
		sp_link res;
		if(part != "..") {
			const auto next = level->find(part, src_path_unit);
			if(next != level->end()) {
				res = *next;
				part = link2path_unit(res, dst_path_unit);
			}
		}
		// append link ID to link's path
		if(res_path.size()) res_path += '/';
		res_path += std::move(part);
		return res;
	};

	// do conversion
	boost::trim(src_path);
	detail::deref_path(src_path, *start, converter);
	// if abs path given, return abs path
	if(src_path[0] == '/')
		res_path.insert(res_path.begin(), '/');
	return res_path;
}

sp_link deref_path(const std::string& path, const sp_link& start, node::Key path_unit) {
	if(!start) return nullptr;
	return detail::deref_path(path, *start, detail::gen_walk_down_tree(path_unit));
}

void walk(const sp_link& root, step_process_fp step_f, bool topdown, bool follow_symlinks) {
	walk_impl({root}, step_f, topdown, follow_symlinks);
}

void walk(const sp_link& root, const step_process_f& step_f,bool topdown, bool follow_symlinks) {
	walk_impl({root}, step_f, topdown, follow_symlinks);
}

auto make_root_link(
	const std::string& link_type, std::string name, sp_node root_node
) -> sp_link {
	if(!root_node) root_node = std::make_shared<node>();
	// create link depending on type
	if(link_type == "fusion_link")
		return link::make_root<fusion_link>(std::move(name), std::move(root_node));
	else
		return link::make_root<hard_link>(std::move(name), std::move(root_node));
}

NAMESPACE_END(tree) NAMESPACE_END(blue_sky)

<commit_msg>tree: fix `tree::walk()` honor `LazyLoad` flag<commit_after>/// @file
/// @author uentity
/// @date 22.11.2017
/// @brief BS tree-related functions impl
/// @copyright
/// 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 https://mozilla.org/MPL/2.0/

#include <bs/tree/tree.h>
#include "tree_impl.h"

#include <set>
#include <boost/uuid/uuid_io.hpp>
#include <boost/algorithm/string.hpp>

#define CAN_CALL_DNODE(L) \
( !(L->flags() & link::LazyLoad) || L->req_status(link::Req::DataNode) == link::ReqStatus::OK )

NAMESPACE_BEGIN(blue_sky) NAMESPACE_BEGIN(tree)

using Key = node::Key;
template<Key K> using Key_type = typename node::Key_type<K>;

/*-----------------------------------------------------------------------------
 *  impl details
 *-----------------------------------------------------------------------------*/
// hidden
namespace {

template<class Callback>
void walk_impl(
	const std::vector<sp_link>& nodes, const Callback& step_f,
	const bool topdown, const bool follow_symlinks,
	std::set<Key_type<Key::ID>> active_symlinks = {}
) {
	sp_node cur_node;
	std::vector<sp_link> next_nodes;
	std::vector<sp_link> next_leafs;
	// for each node
	for(const auto& N : nodes) {
		if(!N) continue;
		// remember symlink
		const auto is_symlink = N->type_id() == "sym_link";
		if(is_symlink) {
			if(follow_symlinks && active_symlinks.find(N->id()) == active_symlinks.end())
				active_symlinks.insert(N->id());
			else continue;
		}

		// obtain node from link honoring LazyLoad flag
		cur_node = CAN_CALL_DNODE(N) ? N->data_node() : nullptr;

		next_nodes.clear();
		next_leafs.clear();

		if(cur_node) {
			// for each link in node
			for(const auto& l : *cur_node) {
				// collect nodes
				if(CAN_CALL_DNODE(l) && l->data_node()) {
					next_nodes.push_back(l);
				}
				else
					next_leafs.push_back(l);
			}
		}

		// if `topdown` == true, process this node BEFORE leafs processing
		if(topdown)
			step_f(N, next_nodes, next_leafs);
		// process list of next nodes
		if(!next_nodes.empty())
			walk_impl(next_nodes, step_f, topdown, follow_symlinks, active_symlinks);
		// if walking from most deep subdir, process current node after all subtree
		if(!topdown)
			step_f(N, next_nodes, next_leafs);

		// forget symlink
		if(is_symlink)
			active_symlinks.erase(N->id());
	}
}

inline std::string link2path_unit(const sp_clink& l, Key path_unit) {
	switch(path_unit) {
	default:
	case Key::ID : return boost::uuids::to_string(l->id());
	case Key::OID : return l->oid();
	case Key::Name : return l->name();
	case Key::Type : return l->type_id();
	}
}

} // hidden ns

// public
NAMESPACE_BEGIN(detail)

sp_link walk_down_tree(const std::string& cur_lid, const sp_node& level, node::Key path_unit) {
	if(cur_lid != "..") {
		const auto next = level->find(cur_lid, path_unit);
		if(next != level->end()) {
			return *next;
		}
	}
	return nullptr;
}

NAMESPACE_END(detail)

/*-----------------------------------------------------------------------------
 *  public API
 *-----------------------------------------------------------------------------*/
std::string abspath(sp_clink l, Key path_unit) {
	std::deque<std::string> res;
	while(l) {
		res.push_front(link2path_unit(l, path_unit));
		if(const auto parent = l->owner()) {
			l = parent->handle();
		}
		else return boost::join(res, "/");
	}
	// leadind slash is appended only if we have 'real' root node without self link
	return std::string("/") + boost::join(res, "/");

	// another possible implementation without multiple returns
	// just leave it here -)
	//sp_node parent;
	//do {
	//	if(l)
	//		res.push_front(human_readable ? l->name() : boost::uuids::to_string(l->id()));
	//	else {
	//		// for root node
	//		res.emplace_front("");
	//		break;
	//	}
	//	if((parent = l->owner())) {
	//		l = parent->handle();
	//	}
	//} while(parent);
	//return boost::join(res, "/");
}

std::string convert_path(
	std::string src_path, const sp_clink& start,
	Key src_path_unit, Key dst_path_unit
) {
	std::string res_path;
	// convert from ID-based path to human-readable
	const auto converter = [&res_path, src_path_unit, dst_path_unit](std::string part, const sp_node& level) {
		sp_link res;
		if(part != "..") {
			const auto next = level->find(part, src_path_unit);
			if(next != level->end()) {
				res = *next;
				part = link2path_unit(res, dst_path_unit);
			}
		}
		// append link ID to link's path
		if(res_path.size()) res_path += '/';
		res_path += std::move(part);
		return res;
	};

	// do conversion
	boost::trim(src_path);
	detail::deref_path(src_path, *start, converter);
	// if abs path given, return abs path
	if(src_path[0] == '/')
		res_path.insert(res_path.begin(), '/');
	return res_path;
}

sp_link deref_path(const std::string& path, const sp_link& start, node::Key path_unit) {
	if(!start) return nullptr;
	return detail::deref_path(path, *start, detail::gen_walk_down_tree(path_unit));
}

void walk(const sp_link& root, step_process_fp step_f, bool topdown, bool follow_symlinks) {
	walk_impl({root}, step_f, topdown, follow_symlinks);
}

void walk(const sp_link& root, const step_process_f& step_f,bool topdown, bool follow_symlinks) {
	walk_impl({root}, step_f, topdown, follow_symlinks);
}

auto make_root_link(
	const std::string& link_type, std::string name, sp_node root_node
) -> sp_link {
	if(!root_node) root_node = std::make_shared<node>();
	// create link depending on type
	if(link_type == "fusion_link")
		return link::make_root<fusion_link>(std::move(name), std::move(root_node));
	else
		return link::make_root<hard_link>(std::move(name), std::move(root_node));
}

NAMESPACE_END(tree) NAMESPACE_END(blue_sky)

<|endoftext|>


<commit_before>#include <sstream>
#include <cstdint>
#include "xUnit++/xUnit++.h"

SUITE("ToString")
{

DATA_THEORY("ToString should not move parameters", (const std::string &s),
    []() -> std::vector<std::tuple<std::string>>
    {
        std::vector<std::tuple<std::string>> data;
        data.emplace_back("ABCD");
        return data;
    })
{
    Assert.Equal("ABCD", s);
}

FACT("ToString will print pointer addresses")
{
    int x;
    int y;

    auto result = Assert.Throws<xUnitpp::xUnitAssert>([&]() { Assert.Equal(&x, &y); });

    std::stringstream str;
    str << "int *: " << std::showbase << std::hex << reinterpret_cast<intptr_t>(&x);

    Assert.Equal(str.str(), result.Expected());
}

}
<commit_msg>fixes #23: tostring unittest failing<commit_after>#include <sstream>
#include <cstdint>
#include <typeinfo>
#include "xUnit++/xUnit++.h"

SUITE("ToString")
{

DATA_THEORY("ToString should not move parameters", (const std::string &s),
    []() -> std::vector<std::tuple<std::string>>
    {
        std::vector<std::tuple<std::string>> data;
        data.emplace_back("ABCD");
        return data;
    })
{
    Assert.Equal("ABCD", s);
}

FACT("ToString will print pointer addresses")
{
    int x;
    int y;

    auto result = Assert.Throws<xUnitpp::xUnitAssert>([&]() { Assert.Equal(&x, &y); });

    std::stringstream str;
    str << typeid(int).name() << " *: " << std::showbase << std::hex << reinterpret_cast<intptr_t>(&x);

    Assert.Equal(str.str(), result.Expected());
}

}
<|endoftext|>


<commit_before>// Probabilistic Question-Answering system
// @2017 Sarge Rogatch
// This software is distributed under GNU AGPLv3 license. See file LICENSE in repository root for details.

#include "stdafx.h"
#include "../PqaCore/PermanentIdManager.h"

using namespace SRPlat;

namespace ProbQA {

TPqaId PermanentIdManager::PermFromComp(const TPqaId compId) {
  if (compId >= TPqaId(_comp2perm.size())) {
    return cInvalidPqaId;
  }
  return _comp2perm[compId];
}

TPqaId PermanentIdManager::CompFromPerm(const TPqaId permId) {
  auto it = _perm2comp.find(permId);
  if (it == _perm2comp.end()) {
    return cInvalidPqaId;
  }
  return it->second;
}

bool PermanentIdManager::Save(FILE *fpout, const bool empty) {
  const TPqaId nComp = (empty ? 0 : _comp2perm.size());
  if (fwrite(&_nextPermId, sizeof(_nextPermId), 1, fpout) != 1) {
    return false;
  }
  if (fwrite(&nComp, sizeof(nComp), 1, fpout) != 1) {
    return false;
  }
  if (TPqaId(fwrite(_comp2perm.data(), sizeof(_comp2perm[0]), nComp, fpout)) != nComp) {
    return false;
  }
  return true;
}

bool PermanentIdManager::Load(FILE *fpin) {
  TPqaId nComp;
  if (fread(&_nextPermId, sizeof(_nextPermId), 1, fpin) != 1) {
    return false;
  }
  if (fread(&nComp, sizeof(nComp), 1, fpin) != 1) {
    return false;
  }
  _comp2perm.resize(nComp);
  _perm2comp.clear();
  if (TPqaId(fread(_comp2perm.data(), sizeof(_comp2perm[0]), nComp, fpin)) != nComp) {
    return false;
  }
  for (TPqaId i = 0; i < nComp; i++) {
    if (_comp2perm[i] == cInvalidPqaId) {
      continue;
    }
    _perm2comp.emplace(_comp2perm[i], i);
  }
  return true;
}

bool PermanentIdManager::EnsurePermIdGreater(const TPqaId bound) {
  if (_nextPermId <= bound) {
    _nextPermId = bound + 1;
    return true;
  }
  return false;
}

bool PermanentIdManager::RemoveComp(const TPqaId compId) {
  if (compId >= TPqaId(_comp2perm.size())) {
    SRUtils::RequestDebug();
    return false;
  }
  const TPqaId iPerm = _comp2perm[compId];
  if (iPerm == cInvalidPqaId) {
    SRUtils::RequestDebug();
    return false;
  }
  auto it = _perm2comp.find(iPerm);
  if (it == _perm2comp.end()) {
    //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception
    SRUtils::RequestDebug();
    return false;
  }
  _perm2comp.erase(it);
  _comp2perm[compId] = cInvalidPqaId;
  return true;
}

bool PermanentIdManager::RenewComp(const TPqaId compId) {
  if (compId >= TPqaId(_comp2perm.size())) {
    SRUtils::RequestDebug();
    return false; // out of range for compact IDs on record
  }
  if (_comp2perm[compId] != cInvalidPqaId) {
    // Compact ID is already mapped to a permanent ID. Use RemoveComp() first.
    SRUtils::RequestDebug();
    return false;
  }
  _comp2perm[compId] = _nextPermId;
  _perm2comp.emplace(_nextPermId, compId);
  _nextPermId++;
  return true;
}

bool PermanentIdManager::GrowTo(const TPqaId nComp) {
  if (nComp < TPqaId(_comp2perm.size())) {
    SRUtils::RequestDebug();
    return false;
  }
  for (TPqaId i = _comp2perm.size(); i < nComp; i++) {
    _comp2perm.push_back(_nextPermId);
    _perm2comp.emplace(_nextPermId, i);
    _nextPermId++;
  }
  return true;
}

bool PermanentIdManager::OnCompact(const TPqaId nNew, const TPqaId *pOldIds) {
  if (nNew > TPqaId(_comp2perm.size())) {
    SRUtils::RequestDebug();
    return false;
  }
  if (nNew != TPqaId(_perm2comp.size())) {
    SRUtils::RequestDebug();
    return false;
  }
  for (TPqaId i = 0; i < nNew; i++) {
    const TPqaId oldComp = pOldIds[i];
    if (oldComp < 0 || oldComp >= TPqaId(_comp2perm.size())) {
      SRUtils::RequestDebug();
      return false;
    }
    const TPqaId oldPerm = _comp2perm[oldComp];
    if (oldPerm == cInvalidPqaId) {
      //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception
      SRUtils::RequestDebug();
      return false;
    }
    auto it = _perm2comp.find(oldPerm);
    if (it == _perm2comp.end()) {
      //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception
      SRUtils::RequestDebug();
      return false;
    }
    it->second = i;
  }

  _comp2perm.clear();
  _comp2perm.resize(nNew, cInvalidPqaId);
  for (std::pair<TPqaId, TPqaId> m : _perm2comp) {
    if (m.second < 0 || m.second >= nNew) {
      //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception
      SRUtils::RequestDebug();
      return false;
    }
    _comp2perm[m.second] = m.first;
  }

  return true;
}

bool PermanentIdManager::RemapPermId(const TPqaId srcPermId, const TPqaId destPermId) {
  if (destPermId >= _nextPermId) {
    return false; // can't remap to future permId's
  }
  auto jt = _perm2comp.find(destPermId);
  if (jt != _perm2comp.end()) {
    return false; // there's already such permId on record
  }
  auto it = _perm2comp.find(srcPermId);
  if (it == _perm2comp.end()) {
    return false; // no such permId on record
  }
  const TPqaId compId = it->second;
  _perm2comp.erase(it);
  _perm2comp.emplace(destPermId, compId);
  _comp2perm[compId] = destPermId;
  return true;
}

} // namespace ProbQA
<commit_msg>Fixed a bug where compact ID was not checked if it's below 0<commit_after>// Probabilistic Question-Answering system
// @2017 Sarge Rogatch
// This software is distributed under GNU AGPLv3 license. See file LICENSE in repository root for details.

#include "stdafx.h"
#include "../PqaCore/PermanentIdManager.h"

using namespace SRPlat;

namespace ProbQA {

TPqaId PermanentIdManager::PermFromComp(const TPqaId compId) {
  if (compId < 0 || compId >= TPqaId(_comp2perm.size())) {
    return cInvalidPqaId;
  }
  return _comp2perm[compId];
}

TPqaId PermanentIdManager::CompFromPerm(const TPqaId permId) {
  auto it = _perm2comp.find(permId);
  if (it == _perm2comp.end()) {
    return cInvalidPqaId;
  }
  return it->second;
}

bool PermanentIdManager::Save(FILE *fpout, const bool empty) {
  const TPqaId nComp = (empty ? 0 : _comp2perm.size());
  if (fwrite(&_nextPermId, sizeof(_nextPermId), 1, fpout) != 1) {
    return false;
  }
  if (fwrite(&nComp, sizeof(nComp), 1, fpout) != 1) {
    return false;
  }
  if (TPqaId(fwrite(_comp2perm.data(), sizeof(_comp2perm[0]), nComp, fpout)) != nComp) {
    return false;
  }
  return true;
}

bool PermanentIdManager::Load(FILE *fpin) {
  TPqaId nComp;
  if (fread(&_nextPermId, sizeof(_nextPermId), 1, fpin) != 1) {
    return false;
  }
  if (fread(&nComp, sizeof(nComp), 1, fpin) != 1) {
    return false;
  }
  _comp2perm.resize(nComp);
  _perm2comp.clear();
  if (TPqaId(fread(_comp2perm.data(), sizeof(_comp2perm[0]), nComp, fpin)) != nComp) {
    return false;
  }
  for (TPqaId i = 0; i < nComp; i++) {
    if (_comp2perm[i] == cInvalidPqaId) {
      continue;
    }
    _perm2comp.emplace(_comp2perm[i], i);
  }
  return true;
}

bool PermanentIdManager::EnsurePermIdGreater(const TPqaId bound) {
  if (_nextPermId <= bound) {
    _nextPermId = bound + 1;
    return true;
  }
  return false;
}

bool PermanentIdManager::RemoveComp(const TPqaId compId) {
  if (compId >= TPqaId(_comp2perm.size())) {
    SRUtils::RequestDebug();
    return false;
  }
  const TPqaId iPerm = _comp2perm[compId];
  if (iPerm == cInvalidPqaId) {
    SRUtils::RequestDebug();
    return false;
  }
  auto it = _perm2comp.find(iPerm);
  if (it == _perm2comp.end()) {
    //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception
    SRUtils::RequestDebug();
    return false;
  }
  _perm2comp.erase(it);
  _comp2perm[compId] = cInvalidPqaId;
  return true;
}

bool PermanentIdManager::RenewComp(const TPqaId compId) {
  if (compId >= TPqaId(_comp2perm.size())) {
    SRUtils::RequestDebug();
    return false; // out of range for compact IDs on record
  }
  if (_comp2perm[compId] != cInvalidPqaId) {
    // Compact ID is already mapped to a permanent ID. Use RemoveComp() first.
    SRUtils::RequestDebug();
    return false;
  }
  _comp2perm[compId] = _nextPermId;
  _perm2comp.emplace(_nextPermId, compId);
  _nextPermId++;
  return true;
}

bool PermanentIdManager::GrowTo(const TPqaId nComp) {
  if (nComp < TPqaId(_comp2perm.size())) {
    SRUtils::RequestDebug();
    return false;
  }
  for (TPqaId i = _comp2perm.size(); i < nComp; i++) {
    _comp2perm.push_back(_nextPermId);
    _perm2comp.emplace(_nextPermId, i);
    _nextPermId++;
  }
  return true;
}

bool PermanentIdManager::OnCompact(const TPqaId nNew, const TPqaId *pOldIds) {
  if (nNew > TPqaId(_comp2perm.size())) {
    SRUtils::RequestDebug();
    return false;
  }
  if (nNew != TPqaId(_perm2comp.size())) {
    SRUtils::RequestDebug();
    return false;
  }
  for (TPqaId i = 0; i < nNew; i++) {
    const TPqaId oldComp = pOldIds[i];
    if (oldComp < 0 || oldComp >= TPqaId(_comp2perm.size())) {
      SRUtils::RequestDebug();
      return false;
    }
    const TPqaId oldPerm = _comp2perm[oldComp];
    if (oldPerm == cInvalidPqaId) {
      //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception
      SRUtils::RequestDebug();
      return false;
    }
    auto it = _perm2comp.find(oldPerm);
    if (it == _perm2comp.end()) {
      //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception
      SRUtils::RequestDebug();
      return false;
    }
    it->second = i;
  }

  _comp2perm.clear();
  _comp2perm.resize(nNew, cInvalidPqaId);
  for (std::pair<TPqaId, TPqaId> m : _perm2comp) {
    if (m.second < 0 || m.second >= nNew) {
      //TODO: actually, this is inconsistency in the manager itself - consider throwing an exception
      SRUtils::RequestDebug();
      return false;
    }
    _comp2perm[m.second] = m.first;
  }

  return true;
}

bool PermanentIdManager::RemapPermId(const TPqaId srcPermId, const TPqaId destPermId) {
  if (destPermId >= _nextPermId) {
    return false; // can't remap to future permId's
  }
  auto jt = _perm2comp.find(destPermId);
  if (jt != _perm2comp.end()) {
    return false; // there's already such permId on record
  }
  auto it = _perm2comp.find(srcPermId);
  if (it == _perm2comp.end()) {
    return false; // no such permId on record
  }
  const TPqaId compId = it->second;
  _perm2comp.erase(it);
  _perm2comp.emplace(destPermId, compId);
  _comp2perm[compId] = destPermId;
  return true;
}

} // namespace ProbQA
<|endoftext|>


<commit_before>// ROS
#include <ros/ros.h>

// for debugging
#include <iostream>

// predicator stuff
#include "predicator.h"
#include "planning_tool.h"

int main(int argc, char **argv) {

  ros::init(argc, argv, "predicator_planning_node");

  predicator_planning::PredicateContext pc(true);

  int max_iter = 5000u;
  double step = 0.10;
  double chance = 0.30;
  double skip_distance = 0.75;

  ros::NodeHandle nh("~");
  nh.param("max_iter", max_iter, int(5000));
  nh.param("step", step, double(0.10));
  nh.param("chance", chance, double(0.30));
  nh.param("skip_distance", skip_distance, double(0.75));

  predicator_planning::Planner planner(&pc, (unsigned int)max_iter, step, chance, skip_distance);

  // define spin rate
  ros::Rate rate(30);

  // start main loop
  while(ros::ok()) {
    ros::spinOnce();
    pc.tick();
    rate.sleep();
  }

  pc.cleanup();
}
<commit_msg>volume size parameter in main file; accessed as ros parameter<commit_after>// ROS
#include <ros/ros.h>

// for debugging
#include <iostream>

// predicator stuff
#include "predicator.h"
#include "planning_tool.h"

int main(int argc, char **argv) {

  ros::init(argc, argv, "predicator_planning_node");

  predicator_planning::PredicateContext pc(true);

  int max_iter = 5000u;
  double step = 0.10;
  double chance = 0.30;
  double skip_distance = 0.75;
  double search_volume = 0.50;

  ros::NodeHandle nh("~");
  nh.param("max_iter", max_iter, int(5000));
  nh.param("step", step, double(0.10));
  nh.param("chance", chance, double(0.30));
  nh.param("skip_distance", skip_distance, double(0.75));
  nh.param("search_volume", search_volume, double(0.50));

  predicator_planning::Planner planner(&pc, (unsigned int)max_iter, step, chance, skip_distance, search_volume);

  // define spin rate
  ros::Rate rate(30);

  // start main loop
  while(ros::ok()) {
    ros::spinOnce();
    pc.tick();
    rate.sleep();
  }

  pc.cleanup();
}
<|endoftext|>


<commit_before>//Author:        Anders Strand Vestbo
//Author:        Uli Frankenfeld
//Last Modified: 06.03.2001

//____________________________________
// AliL3Track
//
// Base track class for L3

//Changes:

//14.03.01: Moved fHitNumbers from protected to private.-ASV
//          Set memory to zero in ctor.
//          Moved fNHits 2 private. Protected data members not a good idea after all.
//19.03.01: Made the method void Set(AliL3Track) virtual.

#include "AliL3RootTypes.h"

#include "AliL3Logging.h"
#include "AliL3Track.h"
#include <math.h>

ClassImp(AliL3Track)

Float_t AliL3Track::BFACT = 0.0029980;
Float_t AliL3Track::bField = 0.2;
Double_t AliL3Track::pi=3.14159265358979323846;

AliL3Track::AliL3Track()
{
  //Constructor

  fNHits = 0;
  fMCid = -1;
  fKappa=0;
  fRadius=0;
  fCenterX=0;
  fCenterY=0;
  ComesFromMainVertex(false);
  fQ = 0;
  fPhi0=0;
  fPsi=0;
  fR0=0;
  fTanl=0;
  fZ0=0;
  fPt=0;
  fLength=0;
  fIsLocal=true;
  fRowRange[0]=0;
  fRowRange[1]=0;
  memset(fHitNumbers,0,174*sizeof(UInt_t));
}

void AliL3Track::Set(AliL3Track *tpt){

   SetRowRange(tpt->GetFirstRow(),tpt->GetLastRow());
   SetPhi0(tpt->GetPhi0());
   SetKappa(tpt->GetKappa());
   SetNHits(tpt->GetNHits());

   SetFirstPoint(tpt->GetFirstPointX(),tpt->GetFirstPointY(),tpt->GetFirstPointZ());

  SetLastPoint(tpt->GetLastPointX(),tpt->GetLastPointY(),tpt->GetLastPointZ());
    SetPt(tpt->GetPt());
   SetPsi(tpt->GetPsi());
     SetTgl(tpt->GetTgl());
     SetCharge(tpt->GetCharge());

    SetHits(tpt->GetNHits(),(UInt_t *)tpt->GetHitNumbers());

/*
  fPhi0 = track->GetPhi0();
  fKappa = track->GetKappa();

  fRowRange[0] = track->GetFirstRow();
  fRowRange[1] = track->GetLastRow();
  fQ = track->GetCharge();
  fFirstPoint[0] = track->GetFirstPointX();
  fFirstPoint[1] = track->GetFirstPointY();
  fFirstPoint[2] = track->GetFirstPointZ();
  fLastPoint[0] = track->GetLastPointX();
  fLastPoint[1] = track->GetLastPointY();
  fLastPoint[2] = track->GetLastPointZ();
  fPt = track->GetPt();
  fTanl = track->GetTgl();
  fPsi = track->GetPsi();
  fQ = track->GetCharge();
  fNHits = track->GetNHits();
  memcpy(fHitNumbers,track->GetHitNumbers(),fNHits*sizeof(UInt_t));
*/
}

AliL3Track::~AliL3Track()
{

}

Double_t AliL3Track::GetP() const
{
  // Returns total momentum.

  return fabs(GetPt())*sqrt(1. + GetTgl()*GetTgl());

}

Double_t AliL3Track::GetPseudoRapidity() const
{
  return 0.5 * log((GetP() + GetPz()) / (GetP() - GetPz()));
}

Double_t AliL3Track::GetEta() const
{
  return GetPseudoRapidity();
}

Double_t AliL3Track::GetRapidity() const
{
  Double_t m_pi = 0.13957;
  return 0.5 * log((m_pi + GetPz()) / (m_pi - GetPz()));
}

void AliL3Track::CalculateHelix(){
  //Calculate Radius, CenterX and Centery from Psi, X0, Y0
  //

  fRadius = fPt / (BFACT*bField);
  if(fRadius) fKappa = 1./fRadius;
  else fRadius = 999999;  //just zero
  Double_t trackPhi0 = fPsi + fQ *0.5 * pi;

  fCenterX = fFirstPoint[0] - fRadius *  cos(trackPhi0);
  fCenterY = fFirstPoint[1] - fRadius *  sin(trackPhi0);
}

Bool_t AliL3Track::CalculateReferencePoint(Double_t angle){
  // Global coordinate: crossing point with y = ax+ b; a=tan(angle-Pi/2);
  //
  const Double_t rr=132; //position of referece plane
  const Double_t xr = cos(angle) *rr;
  const Double_t yr = sin(angle) *rr;

  Double_t a = tan(angle-pi/2);
  Double_t b = yr - a * xr;

  Double_t pp=(fCenterX+a*fCenterY-a*b)/(1+pow(a,2));
  Double_t qq=(pow(fCenterX,2)+pow(fCenterY,2)-2*fCenterY*b+pow(b,2)-pow(fRadius,2))/(1+pow(a,2));

  Double_t racine = pp*pp-qq;
  if(racine<0) return IsPoint(kFALSE);      //no Point

  Double_t rootRacine = sqrt(racine);
  Double_t x0 = pp+rootRacine;
  Double_t x1 = pp-rootRacine;
  Double_t y0 = a*x0 + b;
  Double_t y1 = a*x1 + b;

  Double_t diff0 = sqrt(pow(x0-xr,2)+pow(y0-yr,2));
  Double_t diff1 = sqrt(pow(x1-xr,2)+pow(y1-yr,2));

  if(diff0<diff1){
    fPoint[0]=x0;
    fPoint[1]=y0;
  }
  else{
    fPoint[0]=x1;
    fPoint[1]=y1;
  }

  Double_t pointPhi0  = atan2(fPoint[1]-fCenterY,fPoint[0]-fCenterX);
  Double_t trackPhi0  = atan2(fFirstPoint[1]-fCenterY,fFirstPoint[0]-fCenterX);
  if(fabs(trackPhi0-pointPhi0)>pi){
    if(trackPhi0<pointPhi0) trackPhi0 += 2*pi;
    else                    pointPhi0 += 2*pi;
  }
  Double_t stot = -fQ * (pointPhi0-trackPhi0) * fRadius ;
  fPoint[2]   = fFirstPoint[2] + stot * fTanl;

  fPointPsi = pointPhi0 - fQ * 0.5 * pi;
  if(fPointPsi<0.)  fPointPsi+= 2*pi;
  fPointPsi = fmod(fPointPsi, 2*pi);

  return IsPoint(kTRUE);
}

Bool_t AliL3Track::CalculateEdgePoint(Double_t angle){
  // Global coordinate: crossing point with y = ax; a=tan(angle);
  //
  Double_t rmin=80;  //min Radius of TPC
  Double_t rmax=260; //max Radius of TPC

  Double_t a = tan(angle);
  Double_t pp=(fCenterX+a*fCenterY)/(1+pow(a,2));
  Double_t qq=(pow(fCenterX,2)+pow(fCenterY,2)-pow(fRadius,2))/(1+pow(a,2));
  Double_t racine = pp*pp-qq;
  if(racine<0) return IsPoint(kFALSE);     //no Point
  Double_t rootRacine = sqrt(racine);
  Double_t x0 = pp+rootRacine;
  Double_t x1 = pp-rootRacine;
  Double_t y0 = a*x0;
  Double_t y1 = a*x1;

  Double_t r0 = sqrt(pow(x0,2)+pow(y0,2));
  Double_t r1 = sqrt(pow(x1,2)+pow(y1,2));
  //find the right crossing point:
  //inside the TPC modules
  Bool_t ok0 = kFALSE;
  Bool_t ok1 = kFALSE;
  if(r0>rmin&&r0<rmax){
    Double_t da=atan2(y0,x0);
    if(da<0) da+=pi;
    if(fabs(da-angle)<0.5)
      ok0 = kTRUE;
  }
  if(r1>rmin&&r1<rmax){
    Double_t da=atan2(y1,y1);
    if(da<0) da+=pi;
    if(fabs(da-angle)<0.5)
      ok1 = kTRUE;
  }
  if(!(ok0||ok1)) return IsPoint(kFALSE);   //no Point

  if(ok0&&ok1){
    Double_t diff0 = sqrt(pow(fFirstPoint[0]-x0,2)+pow(fFirstPoint[1]-y0,2));
    Double_t diff1 = sqrt(pow(fFirstPoint[0]-x1,2)+pow(fFirstPoint[1]-y1,2));
    if(diff0<diff1) ok1 = kFALSE; //use ok0
    else ok0 = kFALSE;            //use ok1
  }
  if(ok0){fPoint[0]=x0; fPoint[1]=y0;}
  else   {fPoint[0]=x1; fPoint[1]=y1;}

  Double_t pointPhi0  = atan2(fPoint[1]-fCenterY,fPoint[0]-fCenterX);
  Double_t trackPhi0  = atan2(fFirstPoint[1]-fCenterY,fFirstPoint[0]-fCenterX);
  if(fabs(trackPhi0-pointPhi0)>pi){
    if(trackPhi0<pointPhi0) trackPhi0 += 2*pi;
    else                    pointPhi0 += 2*pi;
  }
  Double_t stot = -fQ * (pointPhi0-trackPhi0) * fRadius ;
  fPoint[2]   = fFirstPoint[2] + stot * fTanl;

  fPointPsi = pointPhi0 - fQ * 0.5 * pi;
  if(fPointPsi<0.)  fPointPsi+= 2*pi;
  fPointPsi = fmod(fPointPsi, 2*pi);

  return IsPoint(kTRUE);
}

Bool_t AliL3Track::CalculatePoint(Double_t xplane){
  // Local coordinate: crossing point with x plane
  //
  Double_t racine = pow(fRadius,2)-pow(xplane-fCenterX,2);
  if(racine<0) return IsPoint(kFALSE);
  Double_t rootRacine = sqrt(racine);

  Double_t y0 = fCenterY + rootRacine;
  Double_t y1 = fCenterY - rootRacine;
  //Double_t diff0 = sqrt(pow(fFirstPoint[0]-xplane)+pow(fFirstPoint[1]-y0));
  //Double_t diff1 = sqrt(pow(fFirstPoint[0]-xplane)+pow(fFirstPoint[1]-y1));
  Double_t diff0 = fabs(y0-fFirstPoint[1]);
  Double_t diff1 = fabs(y1-fFirstPoint[1]);

  fPoint[0]=xplane;
  if(diff0<diff1) fPoint[1]=y0;
  else            fPoint[1]=y1;

  Double_t pointPhi0  = atan2(fPoint[1]-fCenterY,fPoint[0]-fCenterX);
  Double_t trackPhi0  = atan2(fFirstPoint[1]-fCenterY,fFirstPoint[0]-fCenterX);
  if(fabs(trackPhi0-pointPhi0)>pi){
    if(trackPhi0<pointPhi0) trackPhi0 += 2*pi;
    else                    pointPhi0 += 2*pi;
  }
  Double_t stot = -fQ * (pointPhi0-trackPhi0) * fRadius ;
  fPoint[2]   = fFirstPoint[2] + stot * fTanl;

  fPointPsi = pointPhi0 - fQ * 0.5 * pi;
  if(fPointPsi<0.)  fPointPsi+= 2*pi;
  fPointPsi = fmod(fPointPsi, 2*pi);

  return IsPoint(kTRUE);
}

<commit_msg>Removed junk<commit_after>//Author:        Anders Strand Vestbo
//Author:        Uli Frankenfeld
//Last Modified: 06.03.2001

//____________________________________
// AliL3Track
//
// Base track class for L3

//Changes:

//14.03.01: Moved fHitNumbers from protected to private.-ASV
//          Set memory to zero in ctor.
//          Moved fNHits 2 private. Protected data members not a good idea after all.
//19.03.01: Made the method void Set(AliL3Track) virtual.

#include "AliL3RootTypes.h"

#include "AliL3Logging.h"
#include "AliL3Track.h"
#include <math.h>

ClassImp(AliL3Track)

Float_t AliL3Track::BFACT = 0.0029980;
Float_t AliL3Track::bField = 0.2;
Double_t AliL3Track::pi=3.14159265358979323846;

AliL3Track::AliL3Track()
{
  //Constructor

  fNHits = 0;
  fMCid = -1;
  fKappa=0;
  fRadius=0;
  fCenterX=0;
  fCenterY=0;
  ComesFromMainVertex(false);
  fQ = 0;
  fPhi0=0;
  fPsi=0;
  fR0=0;
  fTanl=0;
  fZ0=0;
  fPt=0;
  fLength=0;
  fIsLocal=true;
  fRowRange[0]=0;
  fRowRange[1]=0;
  memset(fHitNumbers,0,174*sizeof(UInt_t));
}

void AliL3Track::Set(AliL3Track *tpt){

  SetRowRange(tpt->GetFirstRow(),tpt->GetLastRow());
  SetPhi0(tpt->GetPhi0());
  SetKappa(tpt->GetKappa());
  SetNHits(tpt->GetNHits());
  SetFirstPoint(tpt->GetFirstPointX(),tpt->GetFirstPointY(),tpt->GetFirstPointZ());
  SetLastPoint(tpt->GetLastPointX(),tpt->GetLastPointY(),tpt->GetLastPointZ());
  SetPt(tpt->GetPt());
  SetPsi(tpt->GetPsi());
  SetTgl(tpt->GetTgl());
  SetCharge(tpt->GetCharge());
  SetHits(tpt->GetNHits(),(UInt_t *)tpt->GetHitNumbers());

}

AliL3Track::~AliL3Track()
{

}

Double_t AliL3Track::GetP() const
{
  // Returns total momentum.

  return fabs(GetPt())*sqrt(1. + GetTgl()*GetTgl());

}

Double_t AliL3Track::GetPseudoRapidity() const
{
  return 0.5 * log((GetP() + GetPz()) / (GetP() - GetPz()));
}

Double_t AliL3Track::GetEta() const
{
  return GetPseudoRapidity();
}

Double_t AliL3Track::GetRapidity() const
{
  Double_t m_pi = 0.13957;
  return 0.5 * log((m_pi + GetPz()) / (m_pi - GetPz()));
}

void AliL3Track::CalculateHelix(){
  //Calculate Radius, CenterX and Centery from Psi, X0, Y0
  //

  fRadius = fPt / (BFACT*bField);
  if(fRadius) fKappa = 1./fRadius;
  else fRadius = 999999;  //just zero
  Double_t trackPhi0 = fPsi + fQ *0.5 * pi;

  fCenterX = fFirstPoint[0] - fRadius *  cos(trackPhi0);
  fCenterY = fFirstPoint[1] - fRadius *  sin(trackPhi0);
}

Bool_t AliL3Track::CalculateReferencePoint(Double_t angle){
  // Global coordinate: crossing point with y = ax+ b; a=tan(angle-Pi/2);
  //
  const Double_t rr=132; //position of referece plane
  const Double_t xr = cos(angle) *rr;
  const Double_t yr = sin(angle) *rr;

  Double_t a = tan(angle-pi/2);
  Double_t b = yr - a * xr;

  Double_t pp=(fCenterX+a*fCenterY-a*b)/(1+pow(a,2));
  Double_t qq=(pow(fCenterX,2)+pow(fCenterY,2)-2*fCenterY*b+pow(b,2)-pow(fRadius,2))/(1+pow(a,2));

  Double_t racine = pp*pp-qq;
  if(racine<0) return IsPoint(kFALSE);      //no Point

  Double_t rootRacine = sqrt(racine);
  Double_t x0 = pp+rootRacine;
  Double_t x1 = pp-rootRacine;
  Double_t y0 = a*x0 + b;
  Double_t y1 = a*x1 + b;

  Double_t diff0 = sqrt(pow(x0-xr,2)+pow(y0-yr,2));
  Double_t diff1 = sqrt(pow(x1-xr,2)+pow(y1-yr,2));

  if(diff0<diff1){
    fPoint[0]=x0;
    fPoint[1]=y0;
  }
  else{
    fPoint[0]=x1;
    fPoint[1]=y1;
  }

  Double_t pointPhi0  = atan2(fPoint[1]-fCenterY,fPoint[0]-fCenterX);
  Double_t trackPhi0  = atan2(fFirstPoint[1]-fCenterY,fFirstPoint[0]-fCenterX);
  if(fabs(trackPhi0-pointPhi0)>pi){
    if(trackPhi0<pointPhi0) trackPhi0 += 2*pi;
    else                    pointPhi0 += 2*pi;
  }
  Double_t stot = -fQ * (pointPhi0-trackPhi0) * fRadius ;
  fPoint[2]   = fFirstPoint[2] + stot * fTanl;

  fPointPsi = pointPhi0 - fQ * 0.5 * pi;
  if(fPointPsi<0.)  fPointPsi+= 2*pi;
  fPointPsi = fmod(fPointPsi, 2*pi);

  return IsPoint(kTRUE);
}

Bool_t AliL3Track::CalculateEdgePoint(Double_t angle){
  // Global coordinate: crossing point with y = ax; a=tan(angle);
  //
  Double_t rmin=80;  //min Radius of TPC
  Double_t rmax=260; //max Radius of TPC

  Double_t a = tan(angle);
  Double_t pp=(fCenterX+a*fCenterY)/(1+pow(a,2));
  Double_t qq=(pow(fCenterX,2)+pow(fCenterY,2)-pow(fRadius,2))/(1+pow(a,2));
  Double_t racine = pp*pp-qq;
  if(racine<0) return IsPoint(kFALSE);     //no Point
  Double_t rootRacine = sqrt(racine);
  Double_t x0 = pp+rootRacine;
  Double_t x1 = pp-rootRacine;
  Double_t y0 = a*x0;
  Double_t y1 = a*x1;

  Double_t r0 = sqrt(pow(x0,2)+pow(y0,2));
  Double_t r1 = sqrt(pow(x1,2)+pow(y1,2));
  //find the right crossing point:
  //inside the TPC modules
  Bool_t ok0 = kFALSE;
  Bool_t ok1 = kFALSE;
  if(r0>rmin&&r0<rmax){
    Double_t da=atan2(y0,x0);
    if(da<0) da+=pi;
    if(fabs(da-angle)<0.5)
      ok0 = kTRUE;
  }
  if(r1>rmin&&r1<rmax){
    Double_t da=atan2(y1,y1);
    if(da<0) da+=pi;
    if(fabs(da-angle)<0.5)
      ok1 = kTRUE;
  }
  if(!(ok0||ok1)) return IsPoint(kFALSE);   //no Point

  if(ok0&&ok1){
    Double_t diff0 = sqrt(pow(fFirstPoint[0]-x0,2)+pow(fFirstPoint[1]-y0,2));
    Double_t diff1 = sqrt(pow(fFirstPoint[0]-x1,2)+pow(fFirstPoint[1]-y1,2));
    if(diff0<diff1) ok1 = kFALSE; //use ok0
    else ok0 = kFALSE;            //use ok1
  }
  if(ok0){fPoint[0]=x0; fPoint[1]=y0;}
  else   {fPoint[0]=x1; fPoint[1]=y1;}

  Double_t pointPhi0  = atan2(fPoint[1]-fCenterY,fPoint[0]-fCenterX);
  Double_t trackPhi0  = atan2(fFirstPoint[1]-fCenterY,fFirstPoint[0]-fCenterX);
  if(fabs(trackPhi0-pointPhi0)>pi){
    if(trackPhi0<pointPhi0) trackPhi0 += 2*pi;
    else                    pointPhi0 += 2*pi;
  }
  Double_t stot = -fQ * (pointPhi0-trackPhi0) * fRadius ;
  fPoint[2]   = fFirstPoint[2] + stot * fTanl;

  fPointPsi = pointPhi0 - fQ * 0.5 * pi;
  if(fPointPsi<0.)  fPointPsi+= 2*pi;
  fPointPsi = fmod(fPointPsi, 2*pi);

  return IsPoint(kTRUE);
}

Bool_t AliL3Track::CalculatePoint(Double_t xplane){
  // Local coordinate: crossing point with x plane
  //
  Double_t racine = pow(fRadius,2)-pow(xplane-fCenterX,2);
  if(racine<0) return IsPoint(kFALSE);
  Double_t rootRacine = sqrt(racine);

  Double_t y0 = fCenterY + rootRacine;
  Double_t y1 = fCenterY - rootRacine;
  //Double_t diff0 = sqrt(pow(fFirstPoint[0]-xplane)+pow(fFirstPoint[1]-y0));
  //Double_t diff1 = sqrt(pow(fFirstPoint[0]-xplane)+pow(fFirstPoint[1]-y1));
  Double_t diff0 = fabs(y0-fFirstPoint[1]);
  Double_t diff1 = fabs(y1-fFirstPoint[1]);

  fPoint[0]=xplane;
  if(diff0<diff1) fPoint[1]=y0;
  else            fPoint[1]=y1;

  Double_t pointPhi0  = atan2(fPoint[1]-fCenterY,fPoint[0]-fCenterX);
  Double_t trackPhi0  = atan2(fFirstPoint[1]-fCenterY,fFirstPoint[0]-fCenterX);
  if(fabs(trackPhi0-pointPhi0)>pi){
    if(trackPhi0<pointPhi0) trackPhi0 += 2*pi;
    else                    pointPhi0 += 2*pi;
  }
  Double_t stot = -fQ * (pointPhi0-trackPhi0) * fRadius ;
  fPoint[2]   = fFirstPoint[2] + stot * fTanl;

  fPointPsi = pointPhi0 - fQ * 0.5 * pi;
  if(fPointPsi<0.)  fPointPsi+= 2*pi;
  fPointPsi = fmod(fPointPsi, 2*pi);

  return IsPoint(kTRUE);
}

<|endoftext|>


<commit_before>/******************************************************************************\
* File:          svn.cpp
* Purpose:       Implementation of wxExSVN class
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/config.h>
#include <wx/extension/svn.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/log.h>
#include <wx/extension/stc.h>
#include <wx/extension/util.h>

wxExSVN* wxExSVN::m_Self = NULL;
#if wxUSE_GUI
wxExSTCEntryDialog* wxExSVN::m_STCEntryDialog = NULL;
#endif
wxString wxExSVN::m_UsageKey;

wxExSVN::wxExSVN()
  : m_Type(SVN_NONE)
  , m_FullPath(wxEmptyString)
{
  Initialize();
}

wxExSVN::wxExSVN(int command_id, const wxString& fullpath)
  : m_Type(GetType(command_id))
  , m_FullPath(fullpath)
{
  Initialize();
}

wxExSVN::wxExSVN(wxExSVNType type, const wxString& fullpath)
  : m_Type(type)
  , m_FullPath(fullpath)
{
  Initialize();
}

#if wxUSE_GUI
int wxExSVN::ConfigDialog(
  wxWindow* parent,
  const wxString& title) const
{
  std::vector<wxExConfigItem> v;
  v.push_back(wxExConfigItem()); // a spacer
  v.push_back(wxExConfigItem(m_UsageKey, CONFIG_CHECKBOX));
  v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL));

  return wxExConfigDialog(parent, v, title).ShowModal();
}
#endif

bool wxExSVN::DirExists(const wxFileName& filename) const
{
  wxFileName path(filename);
  path.AppendDir(".svn");
  return path.DirExists();
}

wxStandardID wxExSVN::Execute()
{
  wxASSERT(m_Type != SVN_NONE);

  const wxString cwd = wxGetCwd();

  wxString file;

  if (m_FullPath.empty())
  {
    if (!wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder"))))
    {
      m_Output = _("Cannot set working directory");
      m_ReturnCode = wxID_ABORT;
      return m_ReturnCode;
    }

    if (m_Type == SVN_ADD)
    {
      file = wxExConfigFirstOf(_("Path"));
    }
  }
  else
  {
    file = " \"" + m_FullPath + "\"";
  }

  wxString comment;

  if (m_Type == SVN_COMMIT)
  {
    comment =
      " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\"";
  }

  wxString flags;
  wxString subcommand;

  if (UseSubcommand())
  {
    subcommand = wxConfigBase::Get()->Read(_("Subcommand"));

    if (!subcommand.empty())
    {
      subcommand = " " + subcommand;
    }
  }

  if (UseFlags())
  {
    flags = wxConfigBase::Get()->Read(_("Flags"));

    if (!flags.empty())
    {
      flags = " " + flags;
    }
  }

  m_CommandWithFlags = m_Command + flags;

  const wxString commandline =
    "svn " + m_Command + subcommand + flags + comment + file;

  wxArrayString output;
  wxArrayString errors;
  m_Output.clear();

  if (wxExecute(
    commandline,
    output,
    errors) == -1)
  {
    if (m_Output.empty())
    {
      m_Output = "Could not execute: " + commandline;
    }

    m_ReturnCode = wxID_ABORT;
    return m_ReturnCode;
  }

  wxExLog::Get()->Log(commandline);

  if (m_FullPath.empty())
  {
    wxSetWorkingDirectory(cwd);
  }

  // First output the errors.
  for (size_t i = 0; i < errors.GetCount(); i++)
  {
    m_Output += errors[i] + "\n";
  }

  // Then the normal output, will be empty if there are errors.
  for (size_t j = 0; j < output.GetCount(); j++)
  {
    m_Output += output[j] + "\n";
  }

  m_ReturnCode = wxID_OK;
  return m_ReturnCode;
}

#if wxUSE_GUI
wxStandardID wxExSVN::Execute(wxWindow* parent)
{
  wxASSERT(parent != NULL);

  // Key SVN is already used, so use other name.
  const wxString svn_flags_name = wxString::Format("svnflags/name%d", m_Type);

  std::vector<wxExConfigItem> v;

  if (m_Type == SVN_COMMIT)
  {
    v.push_back(wxExConfigItem(
      _("Revision comment"),
      CONFIG_COMBOBOX,
      wxEmptyString,
      true)); // required
  }

  if (m_FullPath.empty() && m_Type != SVN_HELP)
  {
    v.push_back(wxExConfigItem(
      _("Base folder"),
      CONFIG_COMBOBOXDIR,
      wxEmptyString,
      true)); // required

    if (m_Type == SVN_ADD)
    {
      v.push_back(wxExConfigItem(
        _("Path"),
        CONFIG_COMBOBOX,
        wxEmptyString,
        true)); // required
    }
  }

  if (UseFlags())
  {
    wxConfigBase::Get()->Write(
      _("Flags"),
      wxConfigBase::Get()->Read(svn_flags_name));

    v.push_back(wxExConfigItem(_("Flags")));
  }

  if (UseSubcommand())
  {
    v.push_back(wxExConfigItem(_("Subcommand")));
  }

  m_ReturnCode = (wxStandardID)wxExConfigDialog(parent,
    v,
    m_Caption).ShowModal();

  if (m_ReturnCode == wxID_CANCEL)
  {
    return m_ReturnCode;
  }

  if (UseFlags())
  {
    wxConfigBase::Get()->Write(svn_flags_name,
      wxConfigBase::Get()->Read(svn_flags_name));
  }

  return Execute();
}
#endif

#if wxUSE_GUI
wxStandardID wxExSVN::ExecuteAndShowOutput(wxWindow* parent)
{
  // We must have a parent.
  wxASSERT(parent != NULL);

  // If an error occurred, already shown by wxExecute itself.
  if (Execute(parent) == wxID_OK)
  {
    ShowOutput(parent);
  }

  return m_ReturnCode;
}
#endif

wxExSVN* wxExSVN::Get(bool createOnDemand)
{
  if (m_Self == NULL && createOnDemand)
  {
    m_Self = new wxExSVN;

    if (!wxConfigBase::Get()->Exists(m_UsageKey))
    {
      if (!wxConfigBase::Get()->Write(m_UsageKey, true))
      {
        wxFAIL;
      }
    }
  }

  return m_Self;
}

wxExSVNType wxExSVN::GetType(int command_id) const
{
  switch (command_id)
  {
    case ID_EDIT_SVN_ADD: return SVN_ADD; break;
    case ID_EDIT_SVN_BLAME: return SVN_BLAME; break;
    case ID_EDIT_SVN_CAT: return SVN_CAT; break;
    case ID_EDIT_SVN_COMMIT: return SVN_COMMIT; break;
    case ID_EDIT_SVN_DIFF: return SVN_DIFF; break;
    case ID_EDIT_SVN_HELP: return SVN_HELP; break;
    case ID_EDIT_SVN_INFO: return SVN_INFO; break;
    case ID_EDIT_SVN_LOG: return SVN_LOG; break;
    case ID_EDIT_SVN_PROPLIST: return SVN_PROPLIST; break;
    case ID_EDIT_SVN_PROPSET: return SVN_PROPSET; break;
    case ID_EDIT_SVN_REVERT: return SVN_REVERT; break;
    case ID_EDIT_SVN_STAT: return SVN_STAT; break;
    case ID_EDIT_SVN_UPDATE: return SVN_UPDATE; break;
    default:
      wxFAIL;
      return SVN_NONE;
      break;
  }
}

void wxExSVN::Initialize()
{
  switch (m_Type)
  {
    case SVN_NONE:     m_Caption = ""; break;
    case SVN_ADD:      m_Caption = "SVN Add"; break;
    case SVN_BLAME:    m_Caption = "SVN Blame"; break;
    case SVN_CAT:      m_Caption = "SVN Cat"; break;
    case SVN_COMMIT:   m_Caption = "SVN Commit"; break;
    case SVN_DIFF:     m_Caption = "SVN Diff"; break;
    case SVN_HELP:     m_Caption = "SVN Help"; break;
    case SVN_INFO:     m_Caption = "SVN Info"; break;
    case SVN_LOG:      m_Caption = "SVN Log"; break;
    case SVN_LS:       m_Caption = "SVN Ls"; break;
    case SVN_PROPLIST: m_Caption = "SVN Proplist"; break;
    case SVN_PROPSET:  m_Caption = "SVN Propset"; break;
    case SVN_REVERT:   m_Caption = "SVN Revert"; break;
    case SVN_STAT:     m_Caption = "SVN Stat"; break;
    case SVN_UPDATE:   m_Caption = "SVN Update"; break;
    default:
      wxFAIL;
      break;
  }

  m_Command = m_Caption.AfterFirst(' ').Lower();

  // Currently no flags, as no command was executed.
  m_CommandWithFlags = m_Command;

  m_Output.clear();
  m_ReturnCode = wxID_NONE;
  m_UsageKey = _("Use SVN");
}

wxExSVN* wxExSVN::Set(wxExSVN* svn)
{
  wxExSVN* old = m_Self;
  m_Self = svn;
  return old;
}

#if wxUSE_GUI
void wxExSVN::ShowOutput(wxWindow* parent) const
{
  switch (m_ReturnCode)
  {
    case wxID_CANCEL:
      break;

    case wxID_ABORT:
      wxMessageBox(m_Output);
      break;

    case wxID_OK:
    {
      wxString caption = m_Caption;

      if (m_Type != SVN_HELP)
      {
        caption += " " + (!m_FullPath.empty() ?
          wxFileName(m_FullPath).GetFullName():
          wxExConfigFirstOf(_("Base folder")));
      }

      // Create a dialog for contents.
      if (m_STCEntryDialog == NULL)
      {
        m_STCEntryDialog = new wxExSTCEntryDialog(
          parent,
          caption,
          m_Output,
          wxEmptyString,
          wxOK,
          wxID_ANY,
          wxDefaultPosition, wxSize(575, 250));
      }
      else
      {
        m_STCEntryDialog->SetText(m_Output);
        m_STCEntryDialog->SetTitle(caption);

        // Reset a previous lexer.
        if (!m_STCEntryDialog->GetLexer().empty())
        {
          m_STCEntryDialog->SetLexer(wxEmptyString);
        }
      }

      // Add a lexer if we specified a path, asked for cat or blame
      // and there is a lexer.
      if (
        !m_FullPath.empty() &&
        (m_Type == SVN_CAT || m_Type == SVN_BLAME))
      {
        const wxExFileName fn(m_FullPath);

        if (!fn.GetLexer().GetScintillaLexer().empty())
        {
          m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer());
        }
      }

      m_STCEntryDialog->Show();
    }
    break;

    default:
      wxFAIL;
      break;
  }
}
#endif

bool wxExSVN::Use() const
{
  return wxConfigBase::Get()->ReadBool(m_UsageKey, true);
}

bool wxExSVN::UseFlags() const
{
  return m_Type != SVN_UPDATE && m_Type != SVN_HELP;
}

bool wxExSVN::UseSubcommand() const
{
  return m_Type == SVN_HELP;
}
<commit_msg>fixed error with flags<commit_after>/******************************************************************************\
* File:          svn.cpp
* Purpose:       Implementation of wxExSVN class
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/config.h>
#include <wx/extension/svn.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/log.h>
#include <wx/extension/stc.h>
#include <wx/extension/util.h>

wxExSVN* wxExSVN::m_Self = NULL;
#if wxUSE_GUI
wxExSTCEntryDialog* wxExSVN::m_STCEntryDialog = NULL;
#endif
wxString wxExSVN::m_UsageKey;

wxExSVN::wxExSVN()
  : m_Type(SVN_NONE)
  , m_FullPath(wxEmptyString)
{
  Initialize();
}

wxExSVN::wxExSVN(int command_id, const wxString& fullpath)
  : m_Type(GetType(command_id))
  , m_FullPath(fullpath)
{
  Initialize();
}

wxExSVN::wxExSVN(wxExSVNType type, const wxString& fullpath)
  : m_Type(type)
  , m_FullPath(fullpath)
{
  Initialize();
}

#if wxUSE_GUI
int wxExSVN::ConfigDialog(
  wxWindow* parent,
  const wxString& title) const
{
  std::vector<wxExConfigItem> v;
  v.push_back(wxExConfigItem()); // a spacer
  v.push_back(wxExConfigItem(m_UsageKey, CONFIG_CHECKBOX));
  v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL));

  return wxExConfigDialog(parent, v, title).ShowModal();
}
#endif

bool wxExSVN::DirExists(const wxFileName& filename) const
{
  wxFileName path(filename);
  path.AppendDir(".svn");
  return path.DirExists();
}

wxStandardID wxExSVN::Execute()
{
  wxASSERT(m_Type != SVN_NONE);

  const wxString cwd = wxGetCwd();

  wxString file;

  if (m_FullPath.empty())
  {
    if (!wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder"))))
    {
      m_Output = _("Cannot set working directory");
      m_ReturnCode = wxID_ABORT;
      return m_ReturnCode;
    }

    if (m_Type == SVN_ADD)
    {
      file = wxExConfigFirstOf(_("Path"));
    }
  }
  else
  {
    file = " \"" + m_FullPath + "\"";
  }

  wxString comment;

  if (m_Type == SVN_COMMIT)
  {
    comment =
      " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\"";
  }

  wxString flags;
  wxString subcommand;

  if (UseSubcommand())
  {
    subcommand = wxConfigBase::Get()->Read(_("Subcommand"));

    if (!subcommand.empty())
    {
      subcommand = " " + subcommand;
    }
  }

  if (UseFlags())
  {
    flags = wxConfigBase::Get()->Read(_("Flags"));

    if (!flags.empty())
    {
      flags = " " + flags;
    }
  }

  m_CommandWithFlags = m_Command + flags;

  const wxString commandline =
    "svn " + m_Command + subcommand + flags + comment + file;

  wxArrayString output;
  wxArrayString errors;
  m_Output.clear();

  if (wxExecute(
    commandline,
    output,
    errors) == -1)
  {
    if (m_Output.empty())
    {
      m_Output = "Could not execute: " + commandline;
    }

    m_ReturnCode = wxID_ABORT;
    return m_ReturnCode;
  }

  wxExLog::Get()->Log(commandline);

  if (m_FullPath.empty())
  {
    wxSetWorkingDirectory(cwd);
  }

  // First output the errors.
  for (size_t i = 0; i < errors.GetCount(); i++)
  {
    m_Output += errors[i] + "\n";
  }

  // Then the normal output, will be empty if there are errors.
  for (size_t j = 0; j < output.GetCount(); j++)
  {
    m_Output += output[j] + "\n";
  }

  m_ReturnCode = wxID_OK;
  return m_ReturnCode;
}

#if wxUSE_GUI
wxStandardID wxExSVN::Execute(wxWindow* parent)
{
  wxASSERT(parent != NULL);

  // Key SVN is already used, so use other name.
  const wxString svn_flags_name = wxString::Format("svnflags/name%d", m_Type);

  std::vector<wxExConfigItem> v;

  if (m_Type == SVN_COMMIT)
  {
    v.push_back(wxExConfigItem(
      _("Revision comment"),
      CONFIG_COMBOBOX,
      wxEmptyString,
      true)); // required
  }

  if (m_FullPath.empty() && m_Type != SVN_HELP)
  {
    v.push_back(wxExConfigItem(
      _("Base folder"),
      CONFIG_COMBOBOXDIR,
      wxEmptyString,
      true)); // required

    if (m_Type == SVN_ADD)
    {
      v.push_back(wxExConfigItem(
        _("Path"),
        CONFIG_COMBOBOX,
        wxEmptyString,
        true)); // required
    }
  }

  if (UseFlags())
  {
    wxConfigBase::Get()->Write(
      _("Flags"),
      wxConfigBase::Get()->Read(svn_flags_name));

    v.push_back(wxExConfigItem(_("Flags")));
  }

  if (UseSubcommand())
  {
    v.push_back(wxExConfigItem(_("Subcommand")));
  }

  m_ReturnCode = (wxStandardID)wxExConfigDialog(parent,
    v,
    m_Caption).ShowModal();

  if (m_ReturnCode == wxID_CANCEL)
  {
    return m_ReturnCode;
  }

  if (UseFlags())
  {
    wxConfigBase::Get()->Write(svn_flags_name,
      wxConfigBase::Get()->Read(_("Flags")));
  }

  return Execute();
}
#endif

#if wxUSE_GUI
wxStandardID wxExSVN::ExecuteAndShowOutput(wxWindow* parent)
{
  // We must have a parent.
  wxASSERT(parent != NULL);

  // If an error occurred, already shown by wxExecute itself.
  if (Execute(parent) == wxID_OK)
  {
    ShowOutput(parent);
  }

  return m_ReturnCode;
}
#endif

wxExSVN* wxExSVN::Get(bool createOnDemand)
{
  if (m_Self == NULL && createOnDemand)
  {
    m_Self = new wxExSVN;

    if (!wxConfigBase::Get()->Exists(m_UsageKey))
    {
      if (!wxConfigBase::Get()->Write(m_UsageKey, true))
      {
        wxFAIL;
      }
    }
  }

  return m_Self;
}

wxExSVNType wxExSVN::GetType(int command_id) const
{
  switch (command_id)
  {
    case ID_EDIT_SVN_ADD: return SVN_ADD; break;
    case ID_EDIT_SVN_BLAME: return SVN_BLAME; break;
    case ID_EDIT_SVN_CAT: return SVN_CAT; break;
    case ID_EDIT_SVN_COMMIT: return SVN_COMMIT; break;
    case ID_EDIT_SVN_DIFF: return SVN_DIFF; break;
    case ID_EDIT_SVN_HELP: return SVN_HELP; break;
    case ID_EDIT_SVN_INFO: return SVN_INFO; break;
    case ID_EDIT_SVN_LOG: return SVN_LOG; break;
    case ID_EDIT_SVN_PROPLIST: return SVN_PROPLIST; break;
    case ID_EDIT_SVN_PROPSET: return SVN_PROPSET; break;
    case ID_EDIT_SVN_REVERT: return SVN_REVERT; break;
    case ID_EDIT_SVN_STAT: return SVN_STAT; break;
    case ID_EDIT_SVN_UPDATE: return SVN_UPDATE; break;
    default:
      wxFAIL;
      return SVN_NONE;
      break;
  }
}

void wxExSVN::Initialize()
{
  switch (m_Type)
  {
    case SVN_NONE:     m_Caption = ""; break;
    case SVN_ADD:      m_Caption = "SVN Add"; break;
    case SVN_BLAME:    m_Caption = "SVN Blame"; break;
    case SVN_CAT:      m_Caption = "SVN Cat"; break;
    case SVN_COMMIT:   m_Caption = "SVN Commit"; break;
    case SVN_DIFF:     m_Caption = "SVN Diff"; break;
    case SVN_HELP:     m_Caption = "SVN Help"; break;
    case SVN_INFO:     m_Caption = "SVN Info"; break;
    case SVN_LOG:      m_Caption = "SVN Log"; break;
    case SVN_LS:       m_Caption = "SVN Ls"; break;
    case SVN_PROPLIST: m_Caption = "SVN Proplist"; break;
    case SVN_PROPSET:  m_Caption = "SVN Propset"; break;
    case SVN_REVERT:   m_Caption = "SVN Revert"; break;
    case SVN_STAT:     m_Caption = "SVN Stat"; break;
    case SVN_UPDATE:   m_Caption = "SVN Update"; break;
    default:
      wxFAIL;
      break;
  }

  m_Command = m_Caption.AfterFirst(' ').Lower();

  // Currently no flags, as no command was executed.
  m_CommandWithFlags = m_Command;

  m_Output.clear();
  m_ReturnCode = wxID_NONE;
  m_UsageKey = _("Use SVN");
}

wxExSVN* wxExSVN::Set(wxExSVN* svn)
{
  wxExSVN* old = m_Self;
  m_Self = svn;
  return old;
}

#if wxUSE_GUI
void wxExSVN::ShowOutput(wxWindow* parent) const
{
  switch (m_ReturnCode)
  {
    case wxID_CANCEL:
      break;

    case wxID_ABORT:
      wxMessageBox(m_Output);
      break;

    case wxID_OK:
    {
      wxString caption = m_Caption;

      if (m_Type != SVN_HELP)
      {
        caption += " " + (!m_FullPath.empty() ?
          wxFileName(m_FullPath).GetFullName():
          wxExConfigFirstOf(_("Base folder")));
      }

      // Create a dialog for contents.
      if (m_STCEntryDialog == NULL)
      {
        m_STCEntryDialog = new wxExSTCEntryDialog(
          parent,
          caption,
          m_Output,
          wxEmptyString,
          wxOK,
          wxID_ANY,
          wxDefaultPosition, wxSize(575, 250));
      }
      else
      {
        m_STCEntryDialog->SetText(m_Output);
        m_STCEntryDialog->SetTitle(caption);

        // Reset a previous lexer.
        if (!m_STCEntryDialog->GetLexer().empty())
        {
          m_STCEntryDialog->SetLexer(wxEmptyString);
        }
      }

      // Add a lexer if we specified a path, asked for cat or blame
      // and there is a lexer.
      if (
        !m_FullPath.empty() &&
        (m_Type == SVN_CAT || m_Type == SVN_BLAME))
      {
        const wxExFileName fn(m_FullPath);

        if (!fn.GetLexer().GetScintillaLexer().empty())
        {
          m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer());
        }
      }

      m_STCEntryDialog->Show();
    }
    break;

    default:
      wxFAIL;
      break;
  }
}
#endif

bool wxExSVN::Use() const
{
  return wxConfigBase::Get()->ReadBool(m_UsageKey, true);
}

bool wxExSVN::UseFlags() const
{
  return m_Type != SVN_UPDATE && m_Type != SVN_HELP;
}

bool wxExSVN::UseSubcommand() const
{
  return m_Type == SVN_HELP;
}
<|endoftext|>


<commit_before>//****************************************************************************
// Copyright © 2017 Jan Erik Breimo. All rights reserved.
// Created by Jan Erik Breimo on 18.03.2017.
//
// This file is distributed under the BSD License.
// License text is included with the source distribution.
//****************************************************************************
#include "../Yson/JsonWriter.hpp"

#include <limits>
#include <sstream>
#include "../Externals/Ytest/Ytest.hpp"

namespace
{
    using namespace Yson;

    void test_Basics()
    {
        std::ostringstream stream;
        JsonWriter writer(stream);
        writer.key("Key");
        Y_EQUAL(writer.key(), "Key");
        writer.beginArray().value(12345678)
                .endArray();
        Y_EQUAL(stream.str(), "[12345678]");
    }

    void test_EscapedString()
    {
        std::stringstream ss;
        JsonWriter(ss)
            .value("\"foo\nbar\t\\x89baz\"");
        std::string expected = "\"\\\"foo\\nbar\\t\\\\x89baz\\\"\"";
        Y_EQUAL(ss.str(), expected);
    }

    void test_ManualFormatting()
    {
        std::stringstream ss;
        JsonWriter(ss)
            .beginArray(JsonParameters(JsonFormatting::FLAT))
            .writeNewline()
            .indent()

            .writeIndentation()
            .rawText("// A 4x4 sudoku")
            .writeNewline()

            .writeIndentation()
            .value(1).value(2).writeComma().writeSeparator(2)
            .value(3).value(4).writeComma().writeNewline()

            .writeIndentation()
            .value(3).value(4).writeComma().writeSeparator(2)
            .value(1).value(2).writeComma().writeNewline()

            .writeNewline()

            .writeIndentation()
            .value(2).value(1).writeComma().writeSeparator(2)
            .value(4).value(3).writeComma().writeNewline()

            .writeIndentation()
            .value(4).value(3).writeComma().writeSeparator(2)
            .value(2).value(1).writeNewline()

            .outdent()
            .endArray();

        std::string expected =
                "[\n"
                "  // A 4x4 sudoku\n"
                "  1, 2,  3, 4,\n"
                "  3, 4,  1, 2,\n"
                "\n"
                "  2, 1,  4, 3,\n"
                "  4, 3,  2, 1\n"
                "]";
        Y_EQUAL(ss.str(), expected);
    }

    void test_MultiValueLines()
    {
        std::stringstream ss;
        JsonWriter(ss)
            .beginArray(JsonParameters(4))
            .writeNewline().writeIndentation()
            .rawText("// A 4x4 sudoku").writeNewline()
            .value(1).value(2).writeComma().writeSeparator(2)
            .value(3).value(4)
            .value(3).value(4).writeComma().writeSeparator(2)
            .value(1).value(2)
            .writeComma().writeNewline().writeNewline()
            .value(2).value(1).writeComma().writeSeparator(2)
            .value(4).value(3)
            .value(4).value(3).writeComma().writeSeparator(2)
            .value(2).value(1)
            .endArray();

        std::string expected =
                "[\n"
                "  // A 4x4 sudoku\n"
                "  1, 2,  3, 4,\n"
                "  3, 4,  1, 2,\n"
                "\n"
                "  2, 1,  4, 3,\n"
                "  4, 3,  2, 1\n"
                "]";
        Y_EQUAL(ss.str(), expected);
    }

    void test_SimpleObject()
    {
        std::stringstream ss;
        JsonWriter(ss, JsonFormatting::FORMAT)
            .beginObject()
            .key("name")
            .beginObject()
            .endObject()
            .endObject();
        std::string expected =
                "{\n"
                "  \"name\": {}\n"
                "}";
        Y_EQUAL(ss.str(), expected);
    }

    template <typename T>
    void doTestInteger(T value,
                      const std::string& expected)
    {
       std::stringstream ss;
       JsonWriter writer(ss);
       writer.value(value);
       Y_EQUAL(ss.str(), expected);
    }

    void test_Integers()
    {
       doTestInteger(32, "32");
       doTestInteger(char(20), "20");
    }

    void test_FloatingPointValues()
    {
        std::stringstream ss;
        JsonWriter writer(ss);
        Y_THROWS(writer.value(std::numeric_limits<double>::infinity()),
                 std::logic_error);
        writer.setNonFiniteFloatsAsStringsEnabled(true);
        writer.value(std::numeric_limits<double>::infinity());
        Y_EQUAL(ss.str(), "\"infinity\"");
    }

    void test_UnquotedValueNames()
    {
        std::stringstream ss;
        JsonWriter writer(ss);
        writer.setUnquotedValueNamesEnabled(true);
        writer.beginObject()
              .key("Key1").value(0)
              .key("$Key2_").value(1)
              .key("_Key$3").value(2)
              .key("4Key4").value(3)
              .key("Key 5").value(4)
              .endObject();
        Y_EQUAL(ss.str(),
                "{Key1:0,$Key2_:1,_Key$3:2,\"4Key4\":3,\"Key 5\":4}");
    }

    void test_FormatAndFlat()
    {
        std::stringstream ss;
        JsonWriter writer(ss, JsonFormatting::FORMAT);
        writer.beginObject();
        writer.key("1").value(2);
        writer.key("array").beginArray(JsonParameters(JsonFormatting::FLAT)).value(1).value(2).endArray();
        writer.endObject();
        Y_EQUAL(ss.str(),
                "{\n"
                "  \"1\": 2,\n"
                "  \"array\": [1, 2]\n"
                "}");
    }

    Y_TEST(test_Basics,
           test_EscapedString,
           test_ManualFormatting,
           test_MultiValueLines,
           test_SimpleObject,
           test_Integers,
           test_FloatingPointValues,
           test_UnquotedValueNames,
           test_FormatAndFlat);
}
<commit_msg>Added test for null, bool etc.<commit_after>//****************************************************************************
// Copyright © 2017 Jan Erik Breimo. All rights reserved.
// Created by Jan Erik Breimo on 18.03.2017.
//
// This file is distributed under the BSD License.
// License text is included with the source distribution.
//****************************************************************************
#include "../Yson/JsonWriter.hpp"

#include <limits>
#include <sstream>
#include "../Externals/Ytest/Ytest.hpp"

namespace
{
    using namespace Yson;

    void test_Basics()
    {
        std::ostringstream stream;
        JsonWriter writer(stream);
        writer.key("Key");
        Y_EQUAL(writer.key(), "Key");
        writer.beginArray().value(12345678)
                .endArray();
        Y_EQUAL(stream.str(), "[12345678]");
    }

    void test_EscapedString()
    {
        std::stringstream ss;
        JsonWriter(ss)
            .value("\"foo\nbar\t\\x89baz\"");
        std::string expected = "\"\\\"foo\\nbar\\t\\\\x89baz\\\"\"";
        Y_EQUAL(ss.str(), expected);
    }

    void test_ManualFormatting()
    {
        std::stringstream ss;
        JsonWriter(ss)
            .beginArray(JsonParameters(JsonFormatting::FLAT))
            .writeNewline()
            .indent()

            .writeIndentation()
            .rawText("// A 4x4 sudoku")
            .writeNewline()

            .writeIndentation()
            .value(1).value(2).writeComma().writeSeparator(2)
            .value(3).value(4).writeComma().writeNewline()

            .writeIndentation()
            .value(3).value(4).writeComma().writeSeparator(2)
            .value(1).value(2).writeComma().writeNewline()

            .writeNewline()

            .writeIndentation()
            .value(2).value(1).writeComma().writeSeparator(2)
            .value(4).value(3).writeComma().writeNewline()

            .writeIndentation()
            .value(4).value(3).writeComma().writeSeparator(2)
            .value(2).value(1).writeNewline()

            .outdent()
            .endArray();

        std::string expected =
                "[\n"
                "  // A 4x4 sudoku\n"
                "  1, 2,  3, 4,\n"
                "  3, 4,  1, 2,\n"
                "\n"
                "  2, 1,  4, 3,\n"
                "  4, 3,  2, 1\n"
                "]";
        Y_EQUAL(ss.str(), expected);
    }

    void test_SemiManualFormatting()
    {
        std::stringstream ss;
        JsonWriter(ss)
            .beginArray(JsonParameters(4))
            .writeNewline().writeIndentation()
            .rawText("// A 4x4 sudoku").writeNewline()
            .value(1).value(2).writeComma().writeSeparator(2)
            .value(3).value(4)
            .value(3).value(4).writeComma().writeSeparator(2)
            .value(1).value(2)
            .writeComma().writeNewline().writeNewline()
            .value(2).value(1).writeComma().writeSeparator(2)
            .value(4).value(3)
            .value(4).value(3).writeComma().writeSeparator(2)
            .value(2).value(1)
            .endArray();

        std::string expected =
                "[\n"
                "  // A 4x4 sudoku\n"
                "  1, 2,  3, 4,\n"
                "  3, 4,  1, 2,\n"
                "\n"
                "  2, 1,  4, 3,\n"
                "  4, 3,  2, 1\n"
                "]";
        Y_EQUAL(ss.str(), expected);
    }

    void test_SimpleObject()
    {
        std::stringstream ss;
        JsonWriter(ss, JsonFormatting::FORMAT)
            .beginObject()
            .key("name")
            .beginObject()
            .endObject()
            .endObject();
        std::string expected =
                "{\n"
                "  \"name\": {}\n"
                "}";
        Y_EQUAL(ss.str(), expected);
    }

    template <typename T>
    void doTestInteger(T value,
                      const std::string& expected)
    {
       std::stringstream ss;
       JsonWriter writer(ss);
       writer.value(value);
       Y_EQUAL(ss.str(), expected);
    }

    void test_Integers()
    {
       doTestInteger(32, "32");
       doTestInteger(char(20), "20");
    }

    void test_FloatingPointValues()
    {
        std::stringstream ss;
        JsonWriter writer(ss);
        Y_THROWS(writer.value(std::numeric_limits<double>::infinity()),
                 std::logic_error);
        writer.setNonFiniteFloatsAsStringsEnabled(true);
        writer.value(std::numeric_limits<double>::infinity());
        Y_EQUAL(ss.str(), "\"infinity\"");
    }

    void test_UnquotedValueNames()
    {
        std::stringstream ss;
        JsonWriter writer(ss);
        writer.setUnquotedValueNamesEnabled(true);
        writer.beginObject()
              .key("Key1").value(0)
              .key("$Key2_").value(1)
              .key("_Key$3").value(2)
              .key("4Key4").value(3)
              .key("Key 5").value(4)
              .endObject();
        Y_EQUAL(ss.str(),
                "{Key1:0,$Key2_:1,_Key$3:2,\"4Key4\":3,\"Key 5\":4}");
    }

    void test_FormatAndFlat()
    {
        std::stringstream ss;
        JsonWriter writer(ss, JsonFormatting::FORMAT);
        writer.beginObject();
        writer.key("1").value(2);
        writer.key("array").beginArray(JsonParameters(JsonFormatting::FLAT)).value(1).value(2).endArray();
        writer.endObject();
        Y_EQUAL(ss.str(),
                "{\n"
                "  \"1\": 2,\n"
                "  \"array\": [1, 2]\n"
                "}");
    }

    void test_SpecialValues()
    {
        std::stringstream ss;
        JsonWriter writer(ss);
        writer.beginArray();
        writer.boolean(true).boolean(false).null();
        writer.endArray();
        Y_EQUAL(ss.str(), "[true,false,null]");
    }

    Y_TEST(test_Basics,
           test_EscapedString,
           test_ManualFormatting,
           test_SemiManualFormatting,
           test_SimpleObject,
           test_Integers,
           test_FloatingPointValues,
           test_UnquotedValueNames,
           test_FormatAndFlat,
           test_SpecialValues);
}
<|endoftext|>


<commit_before>/// \file
/// \ingroup tutorial_tree
/// Illustrates how to retrieve  TTree variables in arrays.
///
/// This example:
///   - creates a simple TTree,
///   - generates TTree variables thanks to the `Draw` method with `goff` option,
///   - retrieves some of them in arrays thanks to `GetVal`,
///   - generates and draw graphs with these arrays.
///
/// The option `goff` in `TTree::Draw` behaves like any other drawing option except
/// that, at the end, no graphics is produced ( `goff`= graphics off). This allows
/// to generate as many TTree variables as needed. All the graphics options
/// (except `para` and `candle`) are limited to four variables only. And `para`
/// and `candle` need at least two variables.
///
/// \macro_image
/// \macro_output
/// \macro_code
///
/// \author Olivier Couet

void treegetval() {
   // create a simple TTree with 5 branches
   Int_t run, evt;
   Float_t x,y,z;
   TTree *T = new TTree("T","test friend trees");
   T->Branch("Run",&run,"Run/I");
   T->Branch("Event",&evt,"Event/I");
   T->Branch("x",&x,"x/F");
   T->Branch("y",&y,"y/F");
   T->Branch("z",&z,"z/F");
   TRandom r;
   for (Int_t i=0;i<10000;i++) {
      if (i < 5000) run = 1;
      else          run = 2;
      evt = i;
      x = r.Gaus(10,1);
      y = r.Gaus(20,2);
      z = r.Landau(2,1);
      T->Fill();
   }

   // Draw with option goff and generate seven variables
   Int_t n = T->Draw("x:y:z:Run:Event:sin(x):cos(x)","Run==1","goff");
   printf("The arrays' dimension is %d\n",n);

   // Retrieve variables 5 et 6
   Double_t *vxs = T->GetVal(5);
   Double_t *vxc = T->GetVal(6);

   // Draw with option goff and generate only one variable
   T->Draw("x","Run==1","goff");

   // Retrieve variable 0
   Double_t *vx  = T->GetVal(0);

   // Create and draw graphs
   TGraph *gs = new TGraph(n,vx,vxs);
   TGraph *gc = new TGraph(n,vx,vxc);
   gs->Draw("ap");
   gc->Draw("p");
}

<commit_msg>complete doc<commit_after>/// \file
/// \ingroup tutorial_tree
/// Illustrates how to retrieve  TTree variables in arrays.
///
/// This example:
///   - creates a simple TTree,
///   - generates TTree variables thanks to the `Draw` method with `goff` option,
///   - retrieves some of them in arrays thanks to `GetVal`,
///   - generates and draw graphs with these arrays.
///
/// The option `goff` in `TTree::Draw` behaves like any other drawing option except
/// that, at the end, no graphics is produced ( `goff`= graphics off). This allows
/// to generate as many TTree variables as needed. All the graphics options
/// (except `para` and `candle`) are limited to four variables only. And `para`
/// and `candle` need at least two variables.
///
/// Note that by default TTree::Draw creates the arrays obtained
/// with GetVal with a length corresponding to the parameter `fEstimate`.
/// By default fEstimate=1000000 and can be modified
/// via TTree::SetEstimate. To keep in memory all the results use:
/// ~~~ {.cpp}
///   tree->SetEstimate(-1);
/// ~~~
/// SetEstimate should be called if the expected number of selected rows
/// is greater than 1000000.
///
/// \macro_image
/// \macro_output
/// \macro_code
///
/// \author Olivier Couet

void treegetval() {
   // create a simple TTree with 5 branches
   Int_t run, evt;
   Float_t x,y,z;
   TTree *T = new TTree("T","test friend trees");
   T->Branch("Run",&run,"Run/I");
   T->Branch("Event",&evt,"Event/I");
   T->Branch("x",&x,"x/F");
   T->Branch("y",&y,"y/F");
   T->Branch("z",&z,"z/F");
   TRandom r;
   for (Int_t i=0;i<10000;i++) {
      if (i < 5000) run = 1;
      else          run = 2;
      evt = i;
      x = r.Gaus(10,1);
      y = r.Gaus(20,2);
      z = r.Landau(2,1);
      T->Fill();
   }

   // Draw with option goff and generate seven variables
   Int_t n = T->Draw("x:y:z:Run:Event:sin(x):cos(x)","Run==1","goff");
   printf("The arrays' dimension is %d\n",n);

   // Retrieve variables 5 et 6
   Double_t *vxs = T->GetVal(5);
   Double_t *vxc = T->GetVal(6);

   // Draw with option goff and generate only one variable
   T->Draw("x","Run==1","goff");

   // Retrieve variable 0
   Double_t *vx  = T->GetVal(0);

   // Create and draw graphs
   TGraph *gs = new TGraph(n,vx,vxs);
   TGraph *gc = new TGraph(n,vx,vxc);
   gs->Draw("ap");
   gc->Draw("p");
}

<|endoftext|>