<commit_before>////////////////////////////////////////
////////////////////////////////////////
//
//  File:
//      \file matrix-tests-01.cpp
//
//  Description:
//      \brief Matrix Tests
//
//  Author:
//      \author J. Caleb Wherry
//
////////////////////////////////////////
////////////////////////////////////////

// Local Includes:
#include "Matrix.hpp"

// Compiler includes:
//#include <vector>

// Test Includes:
#include <gtest/gtest.h>

// Namespaces:
namespace M = matrix;
//using namespace M;
using namespace std;

// Anonymous namespace:
namespace
{

// Matrix class test fixture:
class MatrixTest : public ::testing::Test
{
	protected:

		// Test Objects:
		M::Matrix<double> I3, real_1, real_1b, real_1c, real_2, real_3;
		M::Matrix<complex<double>> complex_1, complex_2, complex_3;

		// Print pad
		string pad;

		// Called before every test group:
		virtual void SetUp()
		{

			// Pad:
			pad = "\t";

			// Matrices
			I3 = { {1, 0, 0},
						 {0, 1, 0},
						 {0, 0, 1}
					  };
			I3.setPad(pad);

			real_1  = M::Matrix<double>(3, 3, 1.0, pad);
			real_1b = M::Matrix<double>(3, 3, 2.0, pad);
			real_1c = M::Matrix<double>(3, 3, 3.0, pad);
			real_2  = M::Matrix<double>(3, 4, 0, pad);
			real_3  = M::Matrix<double>(4, 4, 0, pad);
			complex_1  = M::Matrix<complex<double>>(3, 3, complex<double>(1,1), pad);
			complex_2  = M::Matrix<complex<double>>(3, 4, complex<double>(3,3), pad);
			complex_3  = M::Matrix<complex<double>>(4, 4, complex<double>(1,0), pad);

		}

		// Called after every test group:
		virtual void TearDown() {}
};

TEST_F(MatrixTest, OperatorDisplay)
{

	EXPECT_NO_THROW({
		cout << "Identity 3x3: " << endl << I3 << endl;
	});

	EXPECT_NO_THROW({
		cout << "Identity 4x4: " << endl << real_3.identity() << endl;
	});

	EXPECT_NO_THROW({
		cout << "Real 3x3 - Ones: " << endl << real_1 << endl;
	});

	EXPECT_NO_THROW({
		cout << "Real 3x4 - Zeroes: " << endl << real_2 << endl;
	});

	EXPECT_NO_THROW({
		cout << "Complex 3x3 - (1,1): " << endl << complex_1 << endl;
	});

	EXPECT_NO_THROW({
		cout << "Complex 3x4 - (3,3): " << endl << complex_2 << endl;
	});

	EXPECT_NO_THROW({
		cout << "Complex 4x4 - (1,0): " << endl << complex_3 << endl;
	});

}

TEST_F(MatrixTest, OperatorElementAccess)
{

	EXPECT_NO_THROW({
		auto temp  = I3(0,0);
	});

	EXPECT_NO_THROW({
		auto temp = real_1(0,0);
	});

	EXPECT_THROW({
		auto temp = I3(3,0);
	}, out_of_range);

	EXPECT_THROW({
		auto temp  = I3(0,10);
	}, out_of_range);

	EXPECT_THROW({
		auto temp = I3(10,0);
	}, out_of_range);

}

TEST_F(MatrixTest, OperatorEqual)
{

	EXPECT_FALSE( I3 == real_1 );
	EXPECT_TRUE (real_1 == real_1 );

	EXPECT_FALSE( real_1 == real_2 );
	real_1 = real_2;
	EXPECT_TRUE ( real_1 == real_2 );

	EXPECT_FALSE( complex_1 == complex_2 );
	complex_1 = complex_2;
	EXPECT_TRUE ( complex_1 == complex_2 );

	EXPECT_FALSE( complex_2 == complex_3 );
	complex_2 = complex_3;
	EXPECT_TRUE ( complex_2 == complex_3 );

}

TEST_F(MatrixTest, OperatorDivide_Scalar)
{
	// TODO
}

TEST_F(MatrixTest, OperatorMultiply_Matrix)
{

	EXPECT_TRUE( real_1 == (real_1*I3) );

	// B & I's inner dimensions don't match::
	EXPECT_THROW({
		real_2 = real_2*I3;
	}, logic_error);
}

TEST_F(MatrixTest, OperatorMultiply_Vector)
{
	// TODO
}

TEST_F(MatrixTest, OperatorMultiply_Scalar)
{
	// TODO
}

TEST_F(MatrixTest, OperatorPlus_Matrix)
{

	// Same size:
	EXPECT_NO_THROW({
		real_1 = real_1 + real_1b;
	});
	EXPECT_TRUE( real_1 == real_1c );

	// Not same size:
	EXPECT_THROW({
		real_1 = real_1 + real_2;
	}, logic_error);

}

TEST_F(MatrixTest, OperatorPlus_Scalar)
{
	// TODO
}

TEST_F(MatrixTest, OperatorMinus_Matrix)
{
	// TODO
}

TEST_F(MatrixTest, OperatorMinux_Scalar)
{
	// TODO
}

TEST_F(MatrixTest, Accessors_Size)
{

	EXPECT_EQ( real_1.getNumRows(), 3);
	EXPECT_NE( real_1.getNumRows(), 4);
	EXPECT_EQ( real_1.getNumRows(), I3.getNumRows() );
	EXPECT_EQ( real_2.getNumCols(), 4);
	EXPECT_NE( real_2.getNumCols(), I3.getNumCols() );

}

TEST_F(MatrixTest, Modifiers_Size)
{
	// TODO
}

TEST_F(MatrixTest, Properties_Numerical)
{
	// TODO
}

TEST_F(MatrixTest, Properties_Boolean)
{

	EXPECT_TRUE ( I3.isSquare() );
	EXPECT_TRUE ( I3.isReal() );
	EXPECT_FALSE( I3.isComplex() );
	EXPECT_TRUE ( I3.isSymmetric() );
	EXPECT_FALSE( I3.isSkewSymmetric() );
	EXPECT_TRUE ( I3.isHermitian() );
	EXPECT_FALSE( I3.isSkewHermitian() );
	EXPECT_TRUE ( I3.isOrthogonal() );
	EXPECT_TRUE ( I3.isProjection() );
	EXPECT_TRUE ( I3.commutesWith(I3) );

	EXPECT_TRUE ( real_1.isSquare() );
	EXPECT_TRUE ( real_1.isReal() );
	EXPECT_FALSE( real_1.isComplex() );
	EXPECT_TRUE ( real_1.isSymmetric() );
	EXPECT_FALSE( real_1.isSkewSymmetric() );
	EXPECT_TRUE ( real_1.isHermitian() );
	EXPECT_FALSE( real_1.isSkewHermitian() );
	EXPECT_FALSE( real_1.isOrthogonal() );
	EXPECT_FALSE( real_1.isProjection() );
	EXPECT_TRUE ( real_1.commutesWith(real_1) );

	EXPECT_FALSE( real_2.isSquare() );
	EXPECT_TRUE ( real_2.isReal() );
	EXPECT_FALSE( real_2.isComplex() );
	EXPECT_FALSE( real_2.isSymmetric() );
	EXPECT_FALSE( real_2.isSkewSymmetric() );
	EXPECT_FALSE( real_2.isHermitian() );
	EXPECT_FALSE( real_2.isSkewHermitian() );
	EXPECT_FALSE( real_2.isOrthogonal() );
	EXPECT_FALSE( real_2.isProjection() );
	EXPECT_FALSE( real_2.commutesWith(real_2) );

	EXPECT_TRUE ( complex_1.isSquare() );
	EXPECT_FALSE( complex_1.isReal() );
	EXPECT_TRUE ( complex_1.isComplex() );
	EXPECT_TRUE ( complex_1.isSymmetric() );
	EXPECT_FALSE( complex_1.isSkewSymmetric() );
	EXPECT_FALSE( complex_1.isHermitian() );
	EXPECT_FALSE( complex_1.isSkewHermitian() );
	EXPECT_FALSE( complex_1.isOrthogonal() );
	EXPECT_FALSE( complex_1.isProjection() );
	EXPECT_TRUE ( complex_1.commutesWith(complex_1) );

	EXPECT_FALSE( complex_2.isSquare() );
	EXPECT_FALSE( complex_2.isReal() );
	EXPECT_TRUE ( complex_2.isComplex() );
	EXPECT_FALSE( complex_2.isSymmetric() );
	EXPECT_FALSE( complex_2.isSkewSymmetric() );
	EXPECT_FALSE( complex_2.isHermitian() );
	EXPECT_FALSE( complex_2.isSkewHermitian() );
	EXPECT_FALSE( complex_2.isOrthogonal() );
	EXPECT_FALSE( complex_2.isProjection() );
	EXPECT_FALSE( complex_2.commutesWith(complex_2) );

	EXPECT_TRUE ( complex_3.isSquare() );
	EXPECT_TRUE ( complex_3.isReal() );
	EXPECT_FALSE( complex_3.isComplex() );
	EXPECT_TRUE ( complex_3.isSymmetric() );
	EXPECT_FALSE( complex_3.isSkewSymmetric() );
	EXPECT_TRUE ( complex_3.isHermitian() );
	EXPECT_FALSE( complex_3.isSkewHermitian() );
	EXPECT_FALSE( complex_3.isOrthogonal() );
	EXPECT_FALSE( complex_3.isProjection() );
	EXPECT_TRUE ( complex_3.commutesWith(complex_3) );

}

} // anon namepace
<commit_msg>cleanup<commit_after>////////////////////////////////////////
////////////////////////////////////////
//
//  File:
//      \file matrix-tests-01.cpp
//
//  Description:
//      \brief Matrix Tests
//
//  Author:
//      \author J. Caleb Wherry
//
////////////////////////////////////////
////////////////////////////////////////

// Local Includes:
#include "Matrix.hpp"

// Compiler includes:
//#include <vector>

// Test Includes:
#include <gtest/gtest.h>

// Namespaces:
namespace M = matrix;
//using namespace M;
using namespace std;

// Anonymous namespace:
namespace
{

// Matrix class test fixture:
class MatrixTest : public ::testing::Test
{
	protected:

		// Test Objects:
		M::Matrix<double> I0, I1, I2, I3, I4, real_1, real_1b, real_1c, real_2, real_3;
		M::Matrix<complex<double>> complex_1, complex_2, complex_3;

		// Print pad
		string pad;

		// Called before every test group:
		virtual void SetUp()
		{

			// Pad:
			pad = "\t";

			// Matrices:
			I0 = { {}
					 };
			I0.setPad(pad);

			I1 = { {1}
					 };
			I1.setPad(pad);

			I2 = { {1,0},
						 {0,1}
					 };
			I2.setPad(pad);

			I3 = { {1, 0, 0},
						 {0, 1, 0},
						 {0, 0, 1}
					  };
			I3.setPad(pad);

			real_1  = M::Matrix<double>(3, 3, 1.0, pad);
			real_1b = M::Matrix<double>(3, 3, 2.0, pad);
			real_1c = M::Matrix<double>(3, 3, 3.0, pad);
			real_2  = M::Matrix<double>(3, 4, 0, pad);
			real_3  = M::Matrix<double>(4, 4, 0, pad);
			I4 = real_3.identity();
			complex_1  = M::Matrix<complex<double>>(3, 3, complex<double>(1,1), pad);
			complex_2  = M::Matrix<complex<double>>(3, 4, complex<double>(3,3), pad);
			complex_3  = M::Matrix<complex<double>>(4, 4, complex<double>(1,0), pad);

		}

		// Called after every test group:
		virtual void TearDown() {}
};

TEST_F(MatrixTest, OperatorDisplay)
{

	EXPECT_NO_THROW({
		cout << "Identity 0x0: " << endl << I0 << endl;
	});

	EXPECT_NO_THROW({
		cout << "Identity 1x1: " << endl << I1 << endl;
	});

	EXPECT_NO_THROW({
		cout << "Identity 2x2: " << endl << I2 << endl;
	});

	EXPECT_NO_THROW({
		cout << "Identity 3x3: " << endl << I3 << endl;
	});

	EXPECT_NO_THROW({
		cout << "Identity 4x4: " << endl << I4 << endl;
	});

	EXPECT_NO_THROW({
		cout << "Real 3x3 - Ones: " << endl << real_1 << endl;
	});

	EXPECT_NO_THROW({
		cout << "Real 3x4 - Zeroes: " << endl << real_2 << endl;
	});

	EXPECT_NO_THROW({
		cout << "Complex 3x3 - (1,1): " << endl << complex_1 << endl;
	});

	EXPECT_NO_THROW({
		cout << "Complex 3x4 - (3,3): " << endl << complex_2 << endl;
	});

	EXPECT_NO_THROW({
		cout << "Complex 4x4 - (1,0): " << endl << complex_3 << endl;
	});

}

TEST_F(MatrixTest, OperatorElementAccess)
{

	EXPECT_NO_THROW({
		auto temp  = I3(0,0);
	});

	EXPECT_NO_THROW({
		auto temp = real_1(0,0);
	});

	EXPECT_THROW({
		auto temp = I3(3,0);
	}, out_of_range);

	EXPECT_THROW({
		auto temp  = I3(0,10);
	}, out_of_range);

	EXPECT_THROW({
		auto temp = I3(10,0);
	}, out_of_range);

}

TEST_F(MatrixTest, OperatorEqual)
{

	EXPECT_FALSE( I3 == real_1 );
	EXPECT_TRUE (real_1 == real_1 );

	EXPECT_FALSE( real_1 == real_2 );
	real_1 = real_2;
	EXPECT_TRUE ( real_1 == real_2 );

	EXPECT_FALSE( complex_1 == complex_2 );
	complex_1 = complex_2;
	EXPECT_TRUE ( complex_1 == complex_2 );

	EXPECT_FALSE( complex_2 == complex_3 );
	complex_2 = complex_3;
	EXPECT_TRUE ( complex_2 == complex_3 );

}

TEST_F(MatrixTest, OperatorDivide_Scalar)
{

	EXPECT_EQ( real_1 / 1, real_1);

	EXPECT_THROW({
		auto temp = real_1 / 0;
	}, logic_error);

}

TEST_F(MatrixTest, OperatorMultiply_Matrix)
{

	EXPECT_TRUE( real_1 == (real_1*I3) );

	// B & I's inner dimensions don't match::
	EXPECT_THROW({
		real_2 = real_2*I3;
	}, logic_error);
}

TEST_F(MatrixTest, OperatorMultiply_Vector)
{
	// TODO
}

TEST_F(MatrixTest, OperatorMultiply_Scalar)
{
	// TODO
}

TEST_F(MatrixTest, OperatorPlus_Matrix)
{

	// Same size:
	EXPECT_NO_THROW({
		real_1 = real_1 + real_1b;
	});
	EXPECT_TRUE( real_1 == real_1c );

	// Not same size:
	EXPECT_THROW({
		real_1 = real_1 + real_2;
	}, logic_error);

}

TEST_F(MatrixTest, OperatorPlus_Scalar)
{
	// TODO
}

TEST_F(MatrixTest, OperatorMinus_Matrix)
{
	// TODO
}

TEST_F(MatrixTest, OperatorMinux_Scalar)
{
	// TODO
}

TEST_F(MatrixTest, Accessors_Size)
{

	EXPECT_EQ( real_1.getNumRows(), 3);
	EXPECT_NE( real_1.getNumRows(), 4);
	EXPECT_EQ( real_1.getNumRows(), I3.getNumRows() );
	EXPECT_EQ( real_2.getNumCols(), 4);
	EXPECT_NE( real_2.getNumCols(), I3.getNumCols() );

}

TEST_F(MatrixTest, Modifiers_Size)
{
	// TODO
}

TEST_F(MatrixTest, Properties_Numerical)
{
	// TODO
}

TEST_F(MatrixTest, Properties_Boolean)
{

	EXPECT_TRUE ( I3.isSquare() );
	EXPECT_TRUE ( I3.isReal() );
	EXPECT_FALSE( I3.isComplex() );
	EXPECT_TRUE ( I3.isSymmetric() );
	EXPECT_FALSE( I3.isSkewSymmetric() );
	EXPECT_TRUE ( I3.isHermitian() );
	EXPECT_FALSE( I3.isSkewHermitian() );
	EXPECT_TRUE ( I3.isOrthogonal() );
	EXPECT_TRUE ( I3.isProjection() );
	EXPECT_TRUE ( I3.commutesWith(I3) );

	EXPECT_TRUE ( real_1.isSquare() );
	EXPECT_TRUE ( real_1.isReal() );
	EXPECT_FALSE( real_1.isComplex() );
	EXPECT_TRUE ( real_1.isSymmetric() );
	EXPECT_FALSE( real_1.isSkewSymmetric() );
	EXPECT_TRUE ( real_1.isHermitian() );
	EXPECT_FALSE( real_1.isSkewHermitian() );
	EXPECT_FALSE( real_1.isOrthogonal() );
	EXPECT_FALSE( real_1.isProjection() );
	EXPECT_TRUE ( real_1.commutesWith(real_1) );

	EXPECT_FALSE( real_2.isSquare() );
	EXPECT_TRUE ( real_2.isReal() );
	EXPECT_FALSE( real_2.isComplex() );
	EXPECT_FALSE( real_2.isSymmetric() );
	EXPECT_FALSE( real_2.isSkewSymmetric() );
	EXPECT_FALSE( real_2.isHermitian() );
	EXPECT_FALSE( real_2.isSkewHermitian() );
	EXPECT_FALSE( real_2.isOrthogonal() );
	EXPECT_FALSE( real_2.isProjection() );
	EXPECT_FALSE( real_2.commutesWith(real_2) );

	EXPECT_TRUE ( complex_1.isSquare() );
	EXPECT_FALSE( complex_1.isReal() );
	EXPECT_TRUE ( complex_1.isComplex() );
	EXPECT_TRUE ( complex_1.isSymmetric() );
	EXPECT_FALSE( complex_1.isSkewSymmetric() );
	EXPECT_FALSE( complex_1.isHermitian() );
	EXPECT_FALSE( complex_1.isSkewHermitian() );
	EXPECT_FALSE( complex_1.isOrthogonal() );
	EXPECT_FALSE( complex_1.isProjection() );
	EXPECT_TRUE ( complex_1.commutesWith(complex_1) );

	EXPECT_FALSE( complex_2.isSquare() );
	EXPECT_FALSE( complex_2.isReal() );
	EXPECT_TRUE ( complex_2.isComplex() );
	EXPECT_FALSE( complex_2.isSymmetric() );
	EXPECT_FALSE( complex_2.isSkewSymmetric() );
	EXPECT_FALSE( complex_2.isHermitian() );
	EXPECT_FALSE( complex_2.isSkewHermitian() );
	EXPECT_FALSE( complex_2.isOrthogonal() );
	EXPECT_FALSE( complex_2.isProjection() );
	EXPECT_FALSE( complex_2.commutesWith(complex_2) );

	EXPECT_TRUE ( complex_3.isSquare() );
	EXPECT_TRUE ( complex_3.isReal() );
	EXPECT_FALSE( complex_3.isComplex() );
	EXPECT_TRUE ( complex_3.isSymmetric() );
	EXPECT_FALSE( complex_3.isSkewSymmetric() );
	EXPECT_TRUE ( complex_3.isHermitian() );
	EXPECT_FALSE( complex_3.isSkewHermitian() );
	EXPECT_FALSE( complex_3.isOrthogonal() );
	EXPECT_FALSE( complex_3.isProjection() );
	EXPECT_TRUE ( complex_3.commutesWith(complex_3) );

}

} // anon namepace
<|endoftext|>


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

#include "votca/xtp/qpgrid.h"
#include <boost/format.hpp>
#include <votca/tools/globals.h>

namespace votca {
namespace xtp {

Eigen::VectorXd QPGrid::Evaluate(const Eigen::VectorXd frequencies) {
  const Index qptotal = _opt.qpmax - _opt.qpmin + 1;
  const Eigen::VectorXd c = _dft_energies.segment(_opt.qpmin, qptotal) + _sigma_x.diagonal() - _vxc.diagonal();
  const double delta = (2.0 * _opt.range) / (_opt.steps - 1);
  Eigen::MatrixXd sigmc_mat = Eigen::MatrixXd::Zero(qptotal, _opt.steps);
  for (Index i_node = 0; i_node < _opt.steps; ++i_node) {
    sigmc_mat.col(i_node) = _sigma.CalcCorrelationDiag(frequencies.array() - _opt.range + i_node * delta);
  }
  Eigen::VectorXd roots = frequencies;
  for (Index level = 0; level < qptotal; ++level) {
    const double freq_cur = frequencies[level];
    Eigen::VectorXd grid_freq = freq_cur + Eigen::VectorXd::LinSpaced(_opt.steps, -_opt.range, _opt.range).array();
    Eigen::VectorXd grid_sigc = sigmc_mat.row(level);
    Eigen::VectorXd grid_targ = grid_sigc.array() + c[level] - grid_freq.array();
    double root_best = 0.0;
    double weight_best = -1.0;
    for (Index i_node = 0; i_node < _opt.steps - 1; ++i_node) {
      if (grid_targ[i_node] * grid_targ[i_node + 1] < 0.0) { // Sign change
        double dsigc_dw = (grid_sigc[i_node + 1] - grid_sigc[i_node]) /
                          (grid_freq[i_node + 1] - grid_freq[i_node]);
        double dtarg_dw = (grid_targ[i_node + 1] - grid_targ[i_node]) /
                          (grid_freq[i_node + 1] - grid_freq[i_node]);
        double root = grid_freq[i_node] - grid_targ[i_node] / dtarg_dw; // Fixed-point estimate
        double weight = 1.0 / (1.0 - dsigc_dw); // Pole weight Z in (0, 1)
        if (weight >= 1e-5 && weight > weight_best) {
          root_best = root;
          weight_best = weight;
        }
      }
    }
    if (weight_best >= 0.0) {
      roots[level] = root_best;
    }
  }
  return roots;
}

}  // namespace xtp
}  // namespace votca
<commit_msg>Fixed compiler warning. Avoiding casting Index to int/double by caching Eigen's linespaced result.<commit_after>/*
 *            Copyright 2009-2019 The VOTCA Development Team
 *                       (http://www.votca.org)
 *
 *      Licensed under the Apache License, Version 2.0 (the "License")
 *
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *              http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "votca/xtp/qpgrid.h"
#include <boost/format.hpp>
#include <votca/tools/globals.h>

namespace votca {
namespace xtp {

Eigen::VectorXd QPGrid::Evaluate(const Eigen::VectorXd frequencies) {
  const Index qptotal = _opt.qpmax - _opt.qpmin + 1;
  const Eigen::VectorXd c = _dft_energies.segment(_opt.qpmin, qptotal) + _sigma_x.diagonal() - _vxc.diagonal();
  Eigen::VectorXd linSpaced = Eigen::VectorXd::LinSpaced(_opt.steps, -_opt.range, _opt.range);
  Eigen::MatrixXd sigmc_mat = Eigen::MatrixXd::Zero(qptotal, _opt.steps);
  for (Index i_node = 0; i_node < _opt.steps; ++i_node) {
    sigmc_mat.col(i_node) = _sigma.CalcCorrelationDiag(frequencies.array() + linSpaced[i_node]);
  }
  Eigen::VectorXd roots = frequencies;
  for (Index level = 0; level < qptotal; ++level) {
    const double freq_cur = frequencies[level];
    Eigen::VectorXd grid_freq = freq_cur + linSpaced.array();
    Eigen::VectorXd grid_sigc = sigmc_mat.row(level);
    Eigen::VectorXd grid_targ = grid_sigc.array() + c[level] - grid_freq.array();
    double root_best = 0.0;
    double weight_best = -1.0;
    for (Index i_node = 0; i_node < _opt.steps - 1; ++i_node) {
      if (grid_targ[i_node] * grid_targ[i_node + 1] < 0.0) { // Sign change
        double dsigc_dw = (grid_sigc[i_node + 1] - grid_sigc[i_node]) /
                          (grid_freq[i_node + 1] - grid_freq[i_node]);
        double dtarg_dw = (grid_targ[i_node + 1] - grid_targ[i_node]) /
                          (grid_freq[i_node + 1] - grid_freq[i_node]);
        double root = grid_freq[i_node] - grid_targ[i_node] / dtarg_dw; // Fixed-point estimate
        double weight = 1.0 / (1.0 - dsigc_dw); // Pole weight Z in (0, 1)
        if (weight >= 1e-5 && weight > weight_best) {
          root_best = root;
          weight_best = weight;
        }
      }
    }
    if (weight_best >= 0.0) {
      roots[level] = root_best;
    }
  }
  return roots;
}

}  // namespace xtp
}  // namespace votca
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkImageAnnotate.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to C. Charles Law who developed this class.

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include <math.h>
#include "vtkImageAnnotate.h"

//----------------------------------------------------------------------------
vtkImageAnnotate::vtkImageAnnotate()
{
}

//----------------------------------------------------------------------------
vtkImageAnnotate::~vtkImageAnnotate()
{
}

//----------------------------------------------------------------------------
void vtkImageAnnotate::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkImagePaint::PrintSelf(os,indent);
}

//----------------------------------------------------------------------------
// Draw the bounds of a region
template <class T>
void vtkImageAnnotateBounds(vtkImageAnnotate *self, T *ptr)
{
  int temp;
  T *ptr0, *ptr1;
  int idx0, idx1;
  int inc0, inc1;
  int min0, max0, min1, max1;
  // g0=(1,0), g1=(0,1), g01=(1,1), g10=(1,-1)
  int g0Min, g0Max, g1Min, g1Max, g01Min, g01Max, g10Min, g10Max;

  self->GetIncrements(inc0, inc1);
  self->GetExtent(min0, max0, min1, max1);
  // Initialize min max for each direction
  g0Min = max0; g0Max = min0;
  g1Min = max1; g1Max = min1;
  g01Min = max0+max1; g01Max = min0+min1;
  g10Min = max0-min1; g10Max = min0-max1;

  ptr1 = ptr;
  for (idx1 = min1; idx1 <= max1; ++idx1)
    {
    ptr0 = ptr1;
    for (idx0 = min0; idx0 <= max0; ++idx0)
      {
      if (*ptr0)
	{
	temp = idx0;
	g0Min = (g0Min > temp) ? temp : g0Min;
	g0Max = (g0Max < temp) ? temp : g0Max;
	temp = idx1;
	g1Min = (g1Min > temp) ? temp : g1Min;
	g1Max = (g1Max < temp) ? temp : g1Max;
	temp = idx0+idx1;
	g01Min = (g01Min > temp) ? temp : g01Min;
	g01Max = (g01Max < temp) ? temp : g01Max;
	temp = idx0-idx1;
	g10Min = (g10Min > temp) ? temp : g10Min;
	g10Max = (g10Max < temp) ? temp : g10Max;
	}

      ptr0 += inc0;
      }
    ptr1 += inc1;
    }

  g01Min = g01Min / 2;
  g01Max = g01Max / 2;
  g10Min = g10Min / 2;
  g10Max = g10Max / 2;

  self->SetMin0(g0Min);
  self->SetMax0(g0Max);
  self->SetMin1(g1Min);
  self->SetMax1(g1Max);
  self->SetMin01(g01Min);
  self->SetMax01(g01Max);
  self->SetMin10(g10Min);
  self->SetMax10(g10Max);

  // Average the center of the two bounding boxes.
  temp = ((g0Min + g0Max) + (g01Min + g01Max) + (g10Min + g10Max)) / 4;
  self->SetCenter0(temp);
  temp = ((g1Min + g1Max) + (g01Min + g01Max) - (g10Min + g10Max)) / 4;
  self->SetCenter1(temp);
}

//----------------------------------------------------------------------------
void vtkImageAnnotate::ComputeBounds()
{
  void *ptr;
  int ka, kb;
  int g0Min, g0Max, g1Min, g1Max, g01Min, g01Max, g10Min, g10Max;

  ptr = this->GetScalarPointer();
  switch (this->GetScalarType())
    {
    case VTK_FLOAT:
      vtkImageAnnotateBounds(this, (float *)(ptr));
      break;
    case VTK_INT:
      vtkImageAnnotateBounds(this, (int *)(ptr));
      break;
    case VTK_SHORT:
      vtkImageAnnotateBounds(this, (short *)(ptr));
      break;
    case VTK_UNSIGNED_SHORT:
      vtkImageAnnotateBounds(this, (unsigned short *)(ptr));
      break;
    case VTK_UNSIGNED_CHAR:
      vtkImageAnnotateBounds(this, (unsigned char *)(ptr));
      break;
    default:
      vtkErrorMacro(<< "Draw: Cannot handle ScalarType.");
      return;
    }

  g0Min = this->GetMin0();
  g0Max = this->GetMax0();
  g1Min = this->GetMin1();
  g1Max = this->GetMax1();

  g01Min = this->GetMin01();
  g01Max = this->GetMax01();
  g10Min = this->GetMin10();
  g10Max = this->GetMax10();

  cerr << "g01Min: " << g01Min << ", g01Max: " << g01Max << "\n";

  // Draw the gem.
  this->SetDrawColor(255);
  // g0Min
  ka = g1Min;
  kb = g1Max;
  //this->DrawSegment(g0Min, ka, g0Min, kb);
  // g0Max
  ka = g1Min;
  kb = g1Max;
  //this->DrawSegment(g0Max, ka, g0Max, kb);
  // g1Min
  ka = g0Min;
  kb = g0Max;
  //this->DrawSegment(ka, g1Min, kb, g1Min);
  // g1Max
  ka = g0Min;
  kb = g0Max;
  //this->DrawSegment(ka, g1Max, kb, g1Max);

  // g01Min
  ka = g10Min;
  kb = g10Max;
  //this->DrawSegment(g01Min+ka, g01Min-ka, g01Min+kb, g01Min-kb);
  // g01Max
  ka = g10Min;
  kb = g10Max;
  //this->DrawSegment(g01Max+ka, g01Max-ka, g01Max+kb, g01Max-kb);

  // g10Min
  ka = g01Min;
  kb = g01Max;
  //this->DrawSegment(g10Min+ka, -g10Min+ka, g10Min+kb, -g10Min+kb);
  // g10Max
  ka = g01Min;
  kb = g01Max;
  //this->DrawSegment(g10Max+ka, -g10Max+ka, g10Max+kb, -g10Max+kb);

  this->DrawPoint(this->Center0, this->Center1);
}

//----------------------------------------------------------------------------
// Draw the bounds of a region
template <class T>
void vtkImageAnnotate(vtkImageAnnotate *self, T *ptr, int partIdx)
{
  T *ptr0, *ptr1;
  int idx0, idx1;
  int inc0, inc1;
  int min0, max0, min1, max1;
  // g0=(1,0), g1=(0,1), g01=(1,1), g10=(1,-1)
  int g0Min, g0Max, g1Min, g1Max, g01Min, g01Max, g10Min, g10Max;
  // For finding the best bound.
  int bestSplit, bestIdx0, bestIdx1;
  int annotationIdx0, annotationIdx1;
  float bestDistance, d, d0, d1;

  g0Min = self->GetMin0();
  g0Max = self->GetMax0();
  g1Min = self->GetMin1();
  g1Max = self->GetMax1();
  g01Min = self->GetMin01();
  g01Max = self->GetMax01();
  g10Min = self->GetMin10();
  g10Max = self->GetMax10();

  bestSplit = -1;
  // Pick a big distance as initial value.
  bestDistance = 2.0 * ((g0Max-g0Min) + (g0Max-g0Min) +
			(g01Max-g01Min) + (g10Max-g10Min));

  self->GetIncrements(inc0, inc1);
  self->GetExtent(min0, max0, min1, max1);

  ptr1 = ptr;
  for (idx1 = min1; idx1 <= max1; ++idx1)
    {
    ptr0 = ptr1;
    for (idx0 = min0; idx0 <= max0; ++idx0)
      {
      if ((int)(*ptr0) == partIdx)
	{
	// Compute the nearst bounding line.
	d = idx0 - g0Min;
	if (d < bestDistance)
	  {
	  bestDistance = d;
	  bestSplit = 0;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }
	d = g0Max - idx0;
	if (d < bestDistance)
	  {
	  bestDistance = d;
	  bestSplit = 1;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }

	d = idx1 - g1Min;
	if (d < bestDistance)
	  {
	  bestDistance = d;
	  bestSplit = 2;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }
	d = g1Max - idx1;
	if (d < bestDistance)
	  {
	  bestDistance = d;
	  bestSplit = 3;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }

	d = ((float)(idx0+idx1)*0.5 - g01Min) * 0.707;
	if (d < bestDistance)
	  {
	  cerr << "(" << idx0 << ", " << idx1 << "), d = " << d
	       << ", g01Min = " << g01Min << "\n";
	  bestDistance = d;
	  bestSplit = 4;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }
	d = (g01Max - (float)(idx0+idx1)*0.5) * 0.707;
	if (d < bestDistance)
	  {
	  bestDistance = d;
	  bestSplit = 5;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }

	d = ((float)(idx0-idx1)*0.5 - g10Min) * 0.707;
	if (d < bestDistance)
	  {
	  bestDistance = d;
	  bestSplit = 6;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }
	d = (g10Max - (float)(idx0-idx1)*0.5) * 0.707;
	if (d < bestDistance)
	  {
	  bestDistance = d;
	  bestSplit = 7;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }

	}

      ptr0 += inc0;
      }
    ptr1 += inc1;
    }
  cerr << "g01Min: " << g01Min << ", g01Max: " << g01Max << "\n";

  cerr << "best Distance: " << bestDistance << ", bestSplit: "
       << bestSplit << ", best point (" << bestIdx0 << ", "
       << bestIdx1 << ")\n";

  // Now we know the closest point to the bounds.
  // Find the annotation location.
  /*
  switch (bestSplit)
    {
    case 0:
      annotationIdx0 = bestIdx0 - (int)(bestDistance) - 80;
      annotationIdx1 = bestIdx1;
      break;
    case 1:
      annotationIdx0 = bestIdx0 + (int)(bestDistance) + 80;
      annotationIdx1 = bestIdx1;
      break;
    case 2:
      annotationIdx0 = bestIdx0;
      annotationIdx1 = bestIdx1 - (int)(bestDistance) - 80;
      break;
    case 3:
      annotationIdx0 = bestIdx0;
      annotationIdx1 = bestIdx1 + (int)(bestDistance) + 80;
      break;
    case 4:
      annotationIdx0 = bestIdx0 - (int)(bestDistance) - 80;
      annotationIdx1 = bestIdx1 - (int)(bestDistance) - 80;
      break;
    case 5:
      annotationIdx0 = bestIdx0 + (int)(bestDistance) + 80;
      annotationIdx1 = bestIdx1 + (int)(bestDistance) + 80;
      break;
    case 6:
      annotationIdx0 = bestIdx0 - (int)(bestDistance) - 80;
      annotationIdx1 = bestIdx1 + (int)(bestDistance) + 80;
      break;
    case 7:
      annotationIdx0 = bestIdx0 + (int)(bestDistance) + 80;
      annotationIdx1 = bestIdx1 - (int)(bestDistance) - 80;
      break;
    }
    */

  // Compute leader lines radiating from center
  d0 = bestIdx0 - self->GetCenter0();
  d1 = bestIdx1 - self->GetCenter1();
  // Normalize
  d = sqrt(d0*d0 + d1*d1);
  d0 = d0 / d;
  d1 = d1 / d;
  // Make a small gap between leader line and object
  bestIdx0 += (int)(4.0 * d0);
  bestIdx1 += (int)(4.0 * d1);
  // compute the annotation position
  annotationIdx0 = bestIdx0 + (int)(d0 * (bestDistance + 80.0));
  annotationIdx1 = bestIdx1 + (int)(d1 * (bestDistance + 80.0));

  // Draw a line showing the annotation.
  self->SetDrawColor(255);
  self->DrawSegment(bestIdx0, bestIdx1, annotationIdx0, annotationIdx1);
}

//----------------------------------------------------------------------------
void vtkImageAnnotate::Annotate(int partIdx)
{
  void *ptr;

  ptr = this->GetScalarPointer();
  switch (this->GetScalarType())
    {
    case VTK_FLOAT:
      vtkImageAnnotate(this, (float *)(ptr), partIdx);
      break;
    case VTK_INT:
      vtkImageAnnotate(this, (int *)(ptr), partIdx);
      break;
    case VTK_SHORT:
      vtkImageAnnotate(this, (short *)(ptr), partIdx);
      break;
    case VTK_UNSIGNED_SHORT:
      vtkImageAnnotate(this, (unsigned short *)(ptr), partIdx);
      break;
    case VTK_UNSIGNED_CHAR:
      vtkImageAnnotate(this, (unsigned char *)(ptr), partIdx);
      break;
    default:
      vtkErrorMacro(<< "Draw: Cannot handle ScalarType.");
      return;
    }

}

<commit_msg>sgi CC had troubles with the name (Ted)<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkImageAnnotate.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to C. Charles Law who developed this class.

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include <math.h>
#include "vtkImageAnnotate.h"

//----------------------------------------------------------------------------
vtkImageAnnotate::vtkImageAnnotate()
{
}

//----------------------------------------------------------------------------
vtkImageAnnotate::~vtkImageAnnotate()
{
}

//----------------------------------------------------------------------------
void vtkImageAnnotate::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkImagePaint::PrintSelf(os,indent);
}

//----------------------------------------------------------------------------
// Draw the bounds of a region
template <class T>
void vtkImageAnnotateBounds(vtkImageAnnotate *self, T *ptr)
{
  int temp;
  T *ptr0, *ptr1;
  int idx0, idx1;
  int inc0, inc1;
  int min0, max0, min1, max1;
  // g0=(1,0), g1=(0,1), g01=(1,1), g10=(1,-1)
  int g0Min, g0Max, g1Min, g1Max, g01Min, g01Max, g10Min, g10Max;

  self->GetIncrements(inc0, inc1);
  self->GetExtent(min0, max0, min1, max1);
  // Initialize min max for each direction
  g0Min = max0; g0Max = min0;
  g1Min = max1; g1Max = min1;
  g01Min = max0+max1; g01Max = min0+min1;
  g10Min = max0-min1; g10Max = min0-max1;

  ptr1 = ptr;
  for (idx1 = min1; idx1 <= max1; ++idx1)
    {
    ptr0 = ptr1;
    for (idx0 = min0; idx0 <= max0; ++idx0)
      {
      if (*ptr0)
	{
	temp = idx0;
	g0Min = (g0Min > temp) ? temp : g0Min;
	g0Max = (g0Max < temp) ? temp : g0Max;
	temp = idx1;
	g1Min = (g1Min > temp) ? temp : g1Min;
	g1Max = (g1Max < temp) ? temp : g1Max;
	temp = idx0+idx1;
	g01Min = (g01Min > temp) ? temp : g01Min;
	g01Max = (g01Max < temp) ? temp : g01Max;
	temp = idx0-idx1;
	g10Min = (g10Min > temp) ? temp : g10Min;
	g10Max = (g10Max < temp) ? temp : g10Max;
	}

      ptr0 += inc0;
      }
    ptr1 += inc1;
    }

  g01Min = g01Min / 2;
  g01Max = g01Max / 2;
  g10Min = g10Min / 2;
  g10Max = g10Max / 2;

  self->SetMin0(g0Min);
  self->SetMax0(g0Max);
  self->SetMin1(g1Min);
  self->SetMax1(g1Max);
  self->SetMin01(g01Min);
  self->SetMax01(g01Max);
  self->SetMin10(g10Min);
  self->SetMax10(g10Max);

  // Average the center of the two bounding boxes.
  temp = ((g0Min + g0Max) + (g01Min + g01Max) + (g10Min + g10Max)) / 4;
  self->SetCenter0(temp);
  temp = ((g1Min + g1Max) + (g01Min + g01Max) - (g10Min + g10Max)) / 4;
  self->SetCenter1(temp);
}

//----------------------------------------------------------------------------
void vtkImageAnnotate::ComputeBounds()
{
  void *ptr;
  int ka, kb;
  int g0Min, g0Max, g1Min, g1Max, g01Min, g01Max, g10Min, g10Max;

  ptr = this->GetScalarPointer();
  switch (this->GetScalarType())
    {
    case VTK_FLOAT:
      vtkImageAnnotateBounds(this, (float *)(ptr));
      break;
    case VTK_INT:
      vtkImageAnnotateBounds(this, (int *)(ptr));
      break;
    case VTK_SHORT:
      vtkImageAnnotateBounds(this, (short *)(ptr));
      break;
    case VTK_UNSIGNED_SHORT:
      vtkImageAnnotateBounds(this, (unsigned short *)(ptr));
      break;
    case VTK_UNSIGNED_CHAR:
      vtkImageAnnotateBounds(this, (unsigned char *)(ptr));
      break;
    default:
      vtkErrorMacro(<< "Draw: Cannot handle ScalarType.");
      return;
    }

  g0Min = this->GetMin0();
  g0Max = this->GetMax0();
  g1Min = this->GetMin1();
  g1Max = this->GetMax1();

  g01Min = this->GetMin01();
  g01Max = this->GetMax01();
  g10Min = this->GetMin10();
  g10Max = this->GetMax10();

  cerr << "g01Min: " << g01Min << ", g01Max: " << g01Max << "\n";

  // Draw the gem.
  this->SetDrawColor(255);
  // g0Min
  ka = g1Min;
  kb = g1Max;
  //this->DrawSegment(g0Min, ka, g0Min, kb);
  // g0Max
  ka = g1Min;
  kb = g1Max;
  //this->DrawSegment(g0Max, ka, g0Max, kb);
  // g1Min
  ka = g0Min;
  kb = g0Max;
  //this->DrawSegment(ka, g1Min, kb, g1Min);
  // g1Max
  ka = g0Min;
  kb = g0Max;
  //this->DrawSegment(ka, g1Max, kb, g1Max);

  // g01Min
  ka = g10Min;
  kb = g10Max;
  //this->DrawSegment(g01Min+ka, g01Min-ka, g01Min+kb, g01Min-kb);
  // g01Max
  ka = g10Min;
  kb = g10Max;
  //this->DrawSegment(g01Max+ka, g01Max-ka, g01Max+kb, g01Max-kb);

  // g10Min
  ka = g01Min;
  kb = g01Max;
  //this->DrawSegment(g10Min+ka, -g10Min+ka, g10Min+kb, -g10Min+kb);
  // g10Max
  ka = g01Min;
  kb = g01Max;
  //this->DrawSegment(g10Max+ka, -g10Max+ka, g10Max+kb, -g10Max+kb);

  this->DrawPoint(this->Center0, this->Center1);
}

//----------------------------------------------------------------------------
// Draw the bounds of a region
template <class T>
void vtkImageAnnotateFunction(vtkImageAnnotate *self, T *ptr, int partIdx)
{
  T *ptr0, *ptr1;
  int idx0, idx1;
  int inc0, inc1;
  int min0, max0, min1, max1;
  // g0=(1,0), g1=(0,1), g01=(1,1), g10=(1,-1)
  int g0Min, g0Max, g1Min, g1Max, g01Min, g01Max, g10Min, g10Max;
  // For finding the best bound.
  int bestSplit, bestIdx0, bestIdx1;
  int annotationIdx0, annotationIdx1;
  float bestDistance, d, d0, d1;

  g0Min = self->GetMin0();
  g0Max = self->GetMax0();
  g1Min = self->GetMin1();
  g1Max = self->GetMax1();
  g01Min = self->GetMin01();
  g01Max = self->GetMax01();
  g10Min = self->GetMin10();
  g10Max = self->GetMax10();

  bestSplit = -1;
  // Pick a big distance as initial value.
  bestDistance = 2.0 * ((g0Max-g0Min) + (g0Max-g0Min) +
			(g01Max-g01Min) + (g10Max-g10Min));

  self->GetIncrements(inc0, inc1);
  self->GetExtent(min0, max0, min1, max1);

  ptr1 = ptr;
  for (idx1 = min1; idx1 <= max1; ++idx1)
    {
    ptr0 = ptr1;
    for (idx0 = min0; idx0 <= max0; ++idx0)
      {
      if ((int)(*ptr0) == partIdx)
	{
	// Compute the nearst bounding line.
	d = idx0 - g0Min;
	if (d < bestDistance)
	  {
	  bestDistance = d;
	  bestSplit = 0;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }
	d = g0Max - idx0;
	if (d < bestDistance)
	  {
	  bestDistance = d;
	  bestSplit = 1;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }

	d = idx1 - g1Min;
	if (d < bestDistance)
	  {
	  bestDistance = d;
	  bestSplit = 2;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }
	d = g1Max - idx1;
	if (d < bestDistance)
	  {
	  bestDistance = d;
	  bestSplit = 3;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }

	d = ((float)(idx0+idx1)*0.5 - g01Min) * 0.707;
	if (d < bestDistance)
	  {
	  cerr << "(" << idx0 << ", " << idx1 << "), d = " << d
	       << ", g01Min = " << g01Min << "\n";
	  bestDistance = d;
	  bestSplit = 4;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }
	d = (g01Max - (float)(idx0+idx1)*0.5) * 0.707;
	if (d < bestDistance)
	  {
	  bestDistance = d;
	  bestSplit = 5;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }

	d = ((float)(idx0-idx1)*0.5 - g10Min) * 0.707;
	if (d < bestDistance)
	  {
	  bestDistance = d;
	  bestSplit = 6;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }
	d = (g10Max - (float)(idx0-idx1)*0.5) * 0.707;
	if (d < bestDistance)
	  {
	  bestDistance = d;
	  bestSplit = 7;
	  bestIdx0 = idx0;   bestIdx1 = idx1;
	  }

	}

      ptr0 += inc0;
      }
    ptr1 += inc1;
    }
  cerr << "g01Min: " << g01Min << ", g01Max: " << g01Max << "\n";

  cerr << "best Distance: " << bestDistance << ", bestSplit: "
       << bestSplit << ", best point (" << bestIdx0 << ", "
       << bestIdx1 << ")\n";

  // Now we know the closest point to the bounds.
  // Find the annotation location.
  /*
  switch (bestSplit)
    {
    case 0:
      annotationIdx0 = bestIdx0 - (int)(bestDistance) - 80;
      annotationIdx1 = bestIdx1;
      break;
    case 1:
      annotationIdx0 = bestIdx0 + (int)(bestDistance) + 80;
      annotationIdx1 = bestIdx1;
      break;
    case 2:
      annotationIdx0 = bestIdx0;
      annotationIdx1 = bestIdx1 - (int)(bestDistance) - 80;
      break;
    case 3:
      annotationIdx0 = bestIdx0;
      annotationIdx1 = bestIdx1 + (int)(bestDistance) + 80;
      break;
    case 4:
      annotationIdx0 = bestIdx0 - (int)(bestDistance) - 80;
      annotationIdx1 = bestIdx1 - (int)(bestDistance) - 80;
      break;
    case 5:
      annotationIdx0 = bestIdx0 + (int)(bestDistance) + 80;
      annotationIdx1 = bestIdx1 + (int)(bestDistance) + 80;
      break;
    case 6:
      annotationIdx0 = bestIdx0 - (int)(bestDistance) - 80;
      annotationIdx1 = bestIdx1 + (int)(bestDistance) + 80;
      break;
    case 7:
      annotationIdx0 = bestIdx0 + (int)(bestDistance) + 80;
      annotationIdx1 = bestIdx1 - (int)(bestDistance) - 80;
      break;
    }
    */

  // Compute leader lines radiating from center
  d0 = bestIdx0 - self->GetCenter0();
  d1 = bestIdx1 - self->GetCenter1();
  // Normalize
  d = sqrt(d0*d0 + d1*d1);
  d0 = d0 / d;
  d1 = d1 / d;
  // Make a small gap between leader line and object
  bestIdx0 += (int)(4.0 * d0);
  bestIdx1 += (int)(4.0 * d1);
  // compute the annotation position
  annotationIdx0 = bestIdx0 + (int)(d0 * (bestDistance + 80.0));
  annotationIdx1 = bestIdx1 + (int)(d1 * (bestDistance + 80.0));

  // Draw a line showing the annotation.
  self->SetDrawColor(255);
  self->DrawSegment(bestIdx0, bestIdx1, annotationIdx0, annotationIdx1);
}

//----------------------------------------------------------------------------
void vtkImageAnnotate::Annotate(int partIdx)
{
  void *ptr;

  ptr = this->GetScalarPointer();
  switch (this->GetScalarType())
    {
    case VTK_FLOAT:
      vtkImageAnnotateFunction(this, (float *)(ptr), partIdx);
      break;
    case VTK_INT:
      vtkImageAnnotateFunction(this, (int *)(ptr), partIdx);
      break;
    case VTK_SHORT:
      vtkImageAnnotateFunction(this, (short *)(ptr), partIdx);
      break;
    case VTK_UNSIGNED_SHORT:
      vtkImageAnnotateFunction(this, (unsigned short *)(ptr), partIdx);
      break;
    case VTK_UNSIGNED_CHAR:
      vtkImageAnnotateFunction(this, (unsigned char *)(ptr), partIdx);
      break;
    default:
      vtkErrorMacro(<< "Draw: Cannot handle ScalarType.");
      return;
    }

}

<|endoftext|>


<commit_before>/*
 *
 * CosmosLikeReward
 *
 * Created by Hakim Aammar on 17/03/2020.
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2019 Ledger
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

#include <wallet/cosmos/api_impl/CosmosLikeReward.hpp>
#include <wallet/cosmos/CosmosLikeCurrencies.hpp>
#include <wallet/common/Amount.h>

#include <cmath>

namespace ledger {
    namespace core {

        CosmosLikeReward::CosmosLikeReward(const cosmos::Reward& rewardData, const std::string& delegatorAddress) :
            _rewardData(rewardData),
            _delegatorAddress(delegatorAddress)
        {}

        std::string CosmosLikeReward::getDelegatorAddress() const {
            return _delegatorAddress;
        }

        std::string CosmosLikeReward::getValidatorAddress() const {
            return _rewardData.validatorAddress;
        }

        std::shared_ptr<api::Amount> CosmosLikeReward::getRewardAmount() const {
            auto reward = _rewardData.pendingReward.amount;
            reward.erase(reward.find('.'), std::string::npos);
            return std::make_shared<Amount>(currencies::ATOM, 0, BigInt::fromDecimal(reward));
        }
    }
}
<commit_msg>Make Reward/Delegation amounts aware of empty objects<commit_after>/*
 *
 * CosmosLikeReward
 *
 * Created by Hakim Aammar on 17/03/2020.
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2019 Ledger
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

#include <wallet/cosmos/api_impl/CosmosLikeReward.hpp>
#include <wallet/cosmos/CosmosLikeCurrencies.hpp>
#include <wallet/common/Amount.h>

#include <cmath>

namespace ledger {
    namespace core {

        CosmosLikeReward::CosmosLikeReward(const cosmos::Reward& rewardData, const std::string& delegatorAddress) :
            _rewardData(rewardData),
            _delegatorAddress(delegatorAddress)
        {}

        std::string CosmosLikeReward::getDelegatorAddress() const {
            return _delegatorAddress;
        }

        std::string CosmosLikeReward::getValidatorAddress() const {
            return _rewardData.validatorAddress;
        }

        std::shared_ptr<api::Amount> CosmosLikeReward::getRewardAmount() const {
            auto reward = _rewardData.pendingReward.amount;
            if (reward.empty()) {
                return std::make_shared<Amount>(currencies::ATOM, 0, BigInt::ZERO);
            }
            reward.erase(reward.find('.'), std::string::npos);
            return std::make_shared<Amount>(currencies::ATOM, 0, BigInt::fromDecimal(reward));
        }
    }
}
<|endoftext|>


<commit_before>// cfiles, an analysis frontend for the Chemfiles library
// Copyright (C) Guillaume Fraux and contributors -- BSD license

#ifndef CFILES_ERRORS_HPP
#define CFILES_ERRORS_HPP

#include <stdexcept>

struct CFilesError : public std::runtime_error {
    CFilesError(const std::string& message): std::runtime_error(message) {}
};

#endif
<commit_msg>Move message in CFilesError constructor<commit_after>// cfiles, an analysis frontend for the Chemfiles library
// Copyright (C) Guillaume Fraux and contributors -- BSD license

#ifndef CFILES_ERRORS_HPP
#define CFILES_ERRORS_HPP

#include <stdexcept>
#include <string>

struct CFilesError : public std::runtime_error {
    CFilesError(std::string message): std::runtime_error(std::move(message)) {}
};

#endif
<|endoftext|>


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

#include "google/cloud/internal/background_threads_impl.h"
#include <algorithm>

namespace google {
namespace cloud {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {

AutomaticallyCreatedBackgroundThreads::AutomaticallyCreatedBackgroundThreads(
    std::size_t thread_count)
    : pool_(thread_count == 0 ? 1 : thread_count) {
  std::generate_n(pool_.begin(), pool_.size(), [this] {
    return std::thread([](CompletionQueue cq) { cq.Run(); }, cq_);
  });
}

AutomaticallyCreatedBackgroundThreads::
    ~AutomaticallyCreatedBackgroundThreads() {
  Shutdown();
}

void AutomaticallyCreatedBackgroundThreads::Shutdown() {
  cq_.Shutdown();
  for (auto& t : pool_) t.join();
  pool_.clear();
}

}  // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace cloud
}  // namespace google
<commit_msg>cleanup(common): fail early when trying to join the current thread (#7747)<commit_after>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "google/cloud/internal/background_threads_impl.h"
#include "google/cloud/log.h"
#include <algorithm>
#include <system_error>

namespace google {
namespace cloud {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {

AutomaticallyCreatedBackgroundThreads::AutomaticallyCreatedBackgroundThreads(
    std::size_t thread_count)
    : pool_(thread_count == 0 ? 1 : thread_count) {
  std::generate_n(pool_.begin(), pool_.size(), [this] {
    return std::thread([](CompletionQueue cq) { cq.Run(); }, cq_);
  });
}

AutomaticallyCreatedBackgroundThreads::
    ~AutomaticallyCreatedBackgroundThreads() {
  Shutdown();
}

void AutomaticallyCreatedBackgroundThreads::Shutdown() {
  cq_.Shutdown();
  for (auto& t : pool_) {
#if GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS
    try {
#endif
      t.join();
#if GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS
    } catch (std::system_error const& e) {
      GCP_LOG(FATAL) << "AutomaticallyCreatedBackgroundThreads::Shutdown: "
                     << e.what();
    }
#endif
  }
  pool_.clear();
}

}  // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace cloud
}  // namespace google
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2014 The QXmpp developers
 *
 * Authors:
 *  Manjeet Dahiya
 *  Jeremy Lainé
 *
 * Source:
 *  https://github.com/qxmpp-project/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include "QXmppConstants.h"
#include "QXmppLogger.h"
#include "QXmppStanza.h"
#include "QXmppStream.h"
#include "QXmppUtils.h"

#include <QBuffer>
#include <QDomDocument>
#include <QHostAddress>
#include <QRegExp>
#include <QSslSocket>
#include <QStringList>
#include <QTime>
#include <QXmlStreamWriter>

static bool randomSeeded = false;
static const QByteArray streamRootElementEnd = "</stream:stream>";

class QXmppStreamPrivate
{
public:
    QXmppStreamPrivate();

    QByteArray dataBuffer;
    QSslSocket* socket;

    // stream state
    QByteArray streamStart;
};

QXmppStreamPrivate::QXmppStreamPrivate()
    : socket(0)
{
}

/// Constructs a base XMPP stream.
///
/// \param parent

QXmppStream::QXmppStream(QObject *parent)
    : QXmppLoggable(parent),
    d(new QXmppStreamPrivate)
{
    // Make sure the random number generator is seeded
    if (!randomSeeded)
    {
        qsrand(QTime(0,0,0).msecsTo(QTime::currentTime()) ^ reinterpret_cast<quintptr>(this));
        randomSeeded = true;
    }
}

/// Destroys a base XMPP stream.

QXmppStream::~QXmppStream()
{
    delete d;
}

/// Disconnects from the remote host.
///

void QXmppStream::disconnectFromHost()
{
    sendData(streamRootElementEnd);
    if (d->socket)
    {
        d->socket->flush();
        d->socket->disconnectFromHost();
    }
}

/// Handles a stream start event, which occurs when the underlying transport
/// becomes ready (socket connected, encryption started).
///
/// If you redefine handleStart(), make sure to call the base class's method.

void QXmppStream::handleStart()
{
    d->dataBuffer.clear();
    d->streamStart.clear();
}

/// Returns true if the stream is connected.
///

bool QXmppStream::isConnected() const
{
    return d->socket &&
           d->socket->state() == QAbstractSocket::ConnectedState;
}

/// Sends raw data to the peer.
///
/// \param data

bool QXmppStream::sendData(const QByteArray &data)
{
    logSent(QString::fromUtf8(data));
    if (!d->socket || d->socket->state() != QAbstractSocket::ConnectedState)
        return false;
    return d->socket->write(data) == data.size();
}

/// Sends an XMPP packet to the peer.
///
/// \param packet

bool QXmppStream::sendPacket(const QXmppStanza &packet)
{
    // prepare packet
    QByteArray data;
    QXmlStreamWriter xmlStream(&data);
    packet.toXml(&xmlStream);

    // send packet
    return sendData(data);
}

/// Returns the QSslSocket used for this stream.
///

QSslSocket *QXmppStream::socket() const
{
    return d->socket;
}

/// Sets the QSslSocket used for this stream.
///

void QXmppStream::setSocket(QSslSocket *socket)
{
    bool check;
    Q_UNUSED(check);

    d->socket = socket;
    if (!d->socket)
        return;

    // socket events
    check = connect(socket, SIGNAL(connected()),
                    this, SLOT(_q_socketConnected()));
    Q_ASSERT(check);

    check = connect(socket, SIGNAL(encrypted()),
                    this, SLOT(_q_socketEncrypted()));
    Q_ASSERT(check);

    check = connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
                    this, SLOT(_q_socketError(QAbstractSocket::SocketError)));
    Q_ASSERT(check);

    check = connect(socket, SIGNAL(readyRead()),
                    this, SLOT(_q_socketReadyRead()));
    Q_ASSERT(check);
}

void QXmppStream::_q_socketConnected()
{
    info(QString("Socket connected to %1 %2").arg(
        d->socket->peerAddress().toString(),
        QString::number(d->socket->peerPort())));
    handleStart();
}

void QXmppStream::_q_socketEncrypted()
{
    debug("Socket encrypted");
    handleStart();
}

void QXmppStream::_q_socketError(QAbstractSocket::SocketError socketError)
{
    Q_UNUSED(socketError);
    warning(QString("Socket error: " + socket()->errorString()));
}

void QXmppStream::_q_socketReadyRead()
{
    d->dataBuffer.append(d->socket->readAll());

    // handle whitespace pings
    if (!d->dataBuffer.isEmpty() && d->dataBuffer.trimmed().isEmpty()) {
        d->dataBuffer.clear();
        handleStanza(QDomElement());
    }

    // FIXME : maybe these QRegExps could be static?
    QRegExp startStreamRegex("^(<\\?xml.*\\?>)?\\s*<stream:stream.*>");
    startStreamRegex.setMinimal(true);
    QRegExp endStreamRegex("</stream:stream>$");
    endStreamRegex.setMinimal(true);

    // check whether we need to add stream start / end elements
    QByteArray completeXml = d->dataBuffer;
    const QString strData = QString::fromUtf8(d->dataBuffer);
    bool streamStart = false;
    if (d->streamStart.isEmpty() && strData.contains(startStreamRegex))
        streamStart = true;
    else
        completeXml.prepend(d->streamStart);
    if (!strData.contains(endStreamRegex))
        completeXml.append(streamRootElementEnd);

    // check whether we have a valid XML document
    QDomDocument doc;
    if (!doc.setContent(completeXml, true))
        return;

    // remove data from buffer
    logReceived(strData);
    d->dataBuffer.clear();
    if (streamStart)
        d->streamStart = startStreamRegex.cap(0).toUtf8();

    // process stream start
    if (streamStart)
        handleStream(doc.documentElement());

    // process stanzas
    QDomElement nodeRecv = doc.documentElement().firstChildElement();
    while (!nodeRecv.isNull()) {
        handleStanza(nodeRecv);
        nodeRecv = nodeRecv.nextSiblingElement();
    }
}

<commit_msg>don't try to send stream end if socket is disconnected<commit_after>/*
 * Copyright (C) 2008-2014 The QXmpp developers
 *
 * Authors:
 *  Manjeet Dahiya
 *  Jeremy Lainé
 *
 * Source:
 *  https://github.com/qxmpp-project/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include "QXmppConstants.h"
#include "QXmppLogger.h"
#include "QXmppStanza.h"
#include "QXmppStream.h"
#include "QXmppUtils.h"

#include <QBuffer>
#include <QDomDocument>
#include <QHostAddress>
#include <QRegExp>
#include <QSslSocket>
#include <QStringList>
#include <QTime>
#include <QXmlStreamWriter>

static bool randomSeeded = false;
static const QByteArray streamRootElementEnd = "</stream:stream>";

class QXmppStreamPrivate
{
public:
    QXmppStreamPrivate();

    QByteArray dataBuffer;
    QSslSocket* socket;

    // stream state
    QByteArray streamStart;
};

QXmppStreamPrivate::QXmppStreamPrivate()
    : socket(0)
{
}

/// Constructs a base XMPP stream.
///
/// \param parent

QXmppStream::QXmppStream(QObject *parent)
    : QXmppLoggable(parent),
    d(new QXmppStreamPrivate)
{
    // Make sure the random number generator is seeded
    if (!randomSeeded)
    {
        qsrand(QTime(0,0,0).msecsTo(QTime::currentTime()) ^ reinterpret_cast<quintptr>(this));
        randomSeeded = true;
    }
}

/// Destroys a base XMPP stream.

QXmppStream::~QXmppStream()
{
    delete d;
}

/// Disconnects from the remote host.
///

void QXmppStream::disconnectFromHost()
{
    if (d->socket) {
        if (d->socket->state() == QAbstractSocket::ConnectedState) {
            sendData(streamRootElementEnd);
            d->socket->flush();
        }
        // FIXME: according to RFC 6120 section 4.4, we should wait for
        // the incoming stream to end before closing the socket
        d->socket->disconnectFromHost();
    }
}

/// Handles a stream start event, which occurs when the underlying transport
/// becomes ready (socket connected, encryption started).
///
/// If you redefine handleStart(), make sure to call the base class's method.

void QXmppStream::handleStart()
{
    d->dataBuffer.clear();
    d->streamStart.clear();
}

/// Returns true if the stream is connected.
///

bool QXmppStream::isConnected() const
{
    return d->socket &&
           d->socket->state() == QAbstractSocket::ConnectedState;
}

/// Sends raw data to the peer.
///
/// \param data

bool QXmppStream::sendData(const QByteArray &data)
{
    logSent(QString::fromUtf8(data));
    if (!d->socket || d->socket->state() != QAbstractSocket::ConnectedState)
        return false;
    return d->socket->write(data) == data.size();
}

/// Sends an XMPP packet to the peer.
///
/// \param packet

bool QXmppStream::sendPacket(const QXmppStanza &packet)
{
    // prepare packet
    QByteArray data;
    QXmlStreamWriter xmlStream(&data);
    packet.toXml(&xmlStream);

    // send packet
    return sendData(data);
}

/// Returns the QSslSocket used for this stream.
///

QSslSocket *QXmppStream::socket() const
{
    return d->socket;
}

/// Sets the QSslSocket used for this stream.
///

void QXmppStream::setSocket(QSslSocket *socket)
{
    bool check;
    Q_UNUSED(check);

    d->socket = socket;
    if (!d->socket)
        return;

    // socket events
    check = connect(socket, SIGNAL(connected()),
                    this, SLOT(_q_socketConnected()));
    Q_ASSERT(check);

    check = connect(socket, SIGNAL(encrypted()),
                    this, SLOT(_q_socketEncrypted()));
    Q_ASSERT(check);

    check = connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
                    this, SLOT(_q_socketError(QAbstractSocket::SocketError)));
    Q_ASSERT(check);

    check = connect(socket, SIGNAL(readyRead()),
                    this, SLOT(_q_socketReadyRead()));
    Q_ASSERT(check);
}

void QXmppStream::_q_socketConnected()
{
    info(QString("Socket connected to %1 %2").arg(
        d->socket->peerAddress().toString(),
        QString::number(d->socket->peerPort())));
    handleStart();
}

void QXmppStream::_q_socketEncrypted()
{
    debug("Socket encrypted");
    handleStart();
}

void QXmppStream::_q_socketError(QAbstractSocket::SocketError socketError)
{
    Q_UNUSED(socketError);
    warning(QString("Socket error: " + socket()->errorString()));
}

void QXmppStream::_q_socketReadyRead()
{
    d->dataBuffer.append(d->socket->readAll());

    // handle whitespace pings
    if (!d->dataBuffer.isEmpty() && d->dataBuffer.trimmed().isEmpty()) {
        d->dataBuffer.clear();
        handleStanza(QDomElement());
    }

    // FIXME : maybe these QRegExps could be static?
    QRegExp startStreamRegex("^(<\\?xml.*\\?>)?\\s*<stream:stream.*>");
    startStreamRegex.setMinimal(true);
    QRegExp endStreamRegex("</stream:stream>$");
    endStreamRegex.setMinimal(true);

    // check whether we need to add stream start / end elements
    QByteArray completeXml = d->dataBuffer;
    const QString strData = QString::fromUtf8(d->dataBuffer);
    bool streamStart = false;
    if (d->streamStart.isEmpty() && strData.contains(startStreamRegex))
        streamStart = true;
    else
        completeXml.prepend(d->streamStart);
    if (!strData.contains(endStreamRegex))
        completeXml.append(streamRootElementEnd);

    // check whether we have a valid XML document
    QDomDocument doc;
    if (!doc.setContent(completeXml, true))
        return;

    // remove data from buffer
    logReceived(strData);
    d->dataBuffer.clear();
    if (streamStart)
        d->streamStart = startStreamRegex.cap(0).toUtf8();

    // process stream start
    if (streamStart)
        handleStream(doc.documentElement());

    // process stanzas
    QDomElement nodeRecv = doc.documentElement().firstChildElement();
    while (!nodeRecv.isNull()) {
        handleStanza(nodeRecv);
        nodeRecv = nodeRecv.nextSiblingElement();
    }
}

<|endoftext|>


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

#ifndef IOX_HOOFS_CXX_UNIQUE_ID_INL
#define IOX_HOOFS_CXX_UNIQUE_ID_INL

#include "iceoryx_hoofs/cxx/newtype.hpp"

#include <atomic>

namespace iox
{
namespace cxx
{
/// @brief Unique IDs within a process starting with 1. Monotonic increasing IDs are
/// created with each call to the constructor. The IDs are copy/move constructible/assignable,
/// comparable, sortable and convertable to the underlying value type.
class UniqueId : public cxx::NewType<uint64_t,
                                     cxx::newtype::ProtectedConstructByValueCopy,
                                     cxx::newtype::Comparable,
                                     cxx::newtype::Sortable,
                                     cxx::newtype::Convertable,
                                     cxx::newtype::CopyConstructable,
                                     cxx::newtype::MoveConstructable,
                                     cxx::newtype::CopyAssignable,
                                     cxx::newtype::MoveAssignable>
{
  public:
    using ThisType::ThisType;

    /// @brief the constructor creates an ID which is greater than the previous created ID
    UniqueId() noexcept;

  private:
    static std::atomic<value_type> g_IdCounter; // = 1U
};

} // namespace cxx
} // namespace iox

#endif // IOX_HOOFS_CXX_UNIQUE_ID_INL
<commit_msg>iox-#1010 Fix include guard<commit_after>// Copyright (c) 2022 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

#ifndef IOX_HOOFS_CXX_UNIQUE_ID_HPP
#define IOX_HOOFS_CXX_UNIQUE_ID_HPP

#include "iceoryx_hoofs/cxx/newtype.hpp"

#include <atomic>

namespace iox
{
namespace cxx
{
/// @brief Unique IDs within a process starting with 1. Monotonic increasing IDs are
/// created with each call to the constructor. The IDs are copy/move constructible/assignable,
/// comparable, sortable and convertable to the underlying value type.
class UniqueId : public cxx::NewType<uint64_t,
                                     cxx::newtype::ProtectedConstructByValueCopy,
                                     cxx::newtype::Comparable,
                                     cxx::newtype::Sortable,
                                     cxx::newtype::Convertable,
                                     cxx::newtype::CopyConstructable,
                                     cxx::newtype::MoveConstructable,
                                     cxx::newtype::CopyAssignable,
                                     cxx::newtype::MoveAssignable>
{
  public:
    using ThisType::ThisType;

    /// @brief the constructor creates an ID which is greater than the previous created ID
    UniqueId() noexcept;

  private:
    static std::atomic<value_type> g_IdCounter; // initialized in corresponding cpp file
};

} // namespace cxx
} // namespace iox

#endif // IOX_HOOFS_CXX_UNIQUE_ID_HPP
<|endoftext|>


<commit_before>// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

int main(int argc, char* argv[]) {
  return 0;
}
<commit_msg>Remove dead libdart_dependency_helper.cc.<commit_after><|endoftext|>


<commit_before>/**
  * Touhou Community Reliant Automatic Patcher
  * Main DLL
  *
  * ----
  *
  * Globals, compile-time constants and runconfig abstractions.
  */

#include "thcrap.h"

CRITICAL_SECTION cs_file_access;
json_t* run_cfg = NULL;

const char* PROJECT_NAME(void)
{
	return "Touhou Community Reliant Automatic Patcher";
}
const char* PROJECT_NAME_SHORT(void)
{
	return "thcrap";
}
DWORD PROJECT_VERSION(void)
{
	return 0x20180513;
}
const char* PROJECT_VERSION_STRING(void)
{
	static char ver_str[11] = {0};
	if(!ver_str[0]) {
		str_hexdate_format(ver_str, PROJECT_VERSION());
	}
	return ver_str;
}
json_t* runconfig_get(void)
{
	return run_cfg;
}
void runconfig_set(json_t *new_run_cfg)
{
	json_decref(run_cfg);
	run_cfg = json_incref(new_run_cfg);
}

const json_t *runconfig_title_get(void)
{
	const json_t *id = json_object_get(run_cfg, "game");
	const json_t *title = strings_get(json_string_value(id));
	if(!title) {
		title = json_object_get(run_cfg, "title");
	}
	return title ? title : (id ? id : NULL);
}
<commit_msg>Update version number<commit_after>/**
  * Touhou Community Reliant Automatic Patcher
  * Main DLL
  *
  * ----
  *
  * Globals, compile-time constants and runconfig abstractions.
  */

#include "thcrap.h"

CRITICAL_SECTION cs_file_access;
json_t* run_cfg = NULL;

const char* PROJECT_NAME(void)
{
	return "Touhou Community Reliant Automatic Patcher";
}
const char* PROJECT_NAME_SHORT(void)
{
	return "thcrap";
}
DWORD PROJECT_VERSION(void)
{
	return 0x20180521;
}
const char* PROJECT_VERSION_STRING(void)
{
	static char ver_str[11] = {0};
	if(!ver_str[0]) {
		str_hexdate_format(ver_str, PROJECT_VERSION());
	}
	return ver_str;
}
json_t* runconfig_get(void)
{
	return run_cfg;
}
void runconfig_set(json_t *new_run_cfg)
{
	json_decref(run_cfg);
	run_cfg = json_incref(new_run_cfg);
}

const json_t *runconfig_title_get(void)
{
	const json_t *id = json_object_get(run_cfg, "game");
	const json_t *title = strings_get(json_string_value(id));
	if(!title) {
		title = json_object_get(run_cfg, "title");
	}
	return title ? title : (id ? id : NULL);
}
<|endoftext|>


<commit_before>#include "ros/ros.h"
#include "std_msgs/String.h"

#include <sstream>
#include "math.h"
#include <vector>
#include "../EventTriggerUtility.h"
#include "../PerformTaskConstants.h"
#include "elderly_care_simulation/EventTrigger.h"
using namespace elderly_care_simulation;
#include "../EventNode.h"
#include <unistd.h> // sleep

#define private public
#include "../EscortRobot.h"

#include "gtest/gtest.h"

EscortRobot doctor;

// Publishers and subcribers
//ros::Publisher residentEventPublisher;
//ros::Subscriber residentEventSubscriber;

//void eventTriggeredCallback(EventTrigger msg) {
//    doctor.eventTriggered(msg);
//}

/**
 * This test suite tests the functionality of the EscortRobot class.
 * The EscortRobot ROS node under test is DoctorRobot.
 */
class EscortRobotTest : public ::testing::Test {
    protected:
        // You can remove any or all of the following functions if its body
        // is empty.

        EscortRobotTest() {
            // You can put any initialisation here.
        }

        virtual ~EscortRobotTest() {
            // You can do clean-up work that doesn't throw exceptions here.
        }

        // If the constructor and destructor are not enough for setting up
        // and cleaning up each test, you can define the following methods:

        virtual void SetUp() {
            // Instantiate a new doctor for each test
            geometry_msgs::Point base;
            base.x = 3.0f;
            base.y = 3.0f;

            geometry_msgs::Point hospital;
            hospital.x = 4.0f;
            hospital.y = 4.0f;

            doctor = EscortRobot(EVENT_TRIGGER_EVENT_TYPE_VERY_ILL, base, hospital);
        }

        virtual void TearDown() {
            // Code here will be called immediately after each test (right
            // before the destructor).
        }
};

EventTrigger eventTriggerForEventType(int eventType) {
    ROS_INFO("Making a message");
    EventTrigger msg;
    msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST;
    msg.event_type = eventType;
    msg.event_priority = EVENT_TRIGGER_PRIORITY_HIGH;
    msg.event_weight = getEventWeight(eventType);
    msg.result = EVENT_TRIGGER_RESULT_UNDEFINED;
    return msg;
}

/**
 * Any calls to the doctor that are not VERY_ILL events should be ignored.
 */
TEST_F(EscortRobotTest, ignoreIrrelevantEvents) {
    ROS_INFO("Starting test");

    ASSERT_EQ(EscortRobot::AT_BASE, doctor.currentLocationState);
    ASSERT_FALSE(doctor.performingTask);

    doctor.eventTriggered(eventTriggerForEventType(EVENT_TRIGGER_EVENT_TYPE_MEDICATION));

    // The doctor should not change its state
    ASSERT_EQ(EscortRobot::AT_BASE, doctor.currentLocationState);
    ASSERT_FALSE(doctor.performingTask);
}

/**
 * Any calls to the doctor that are VERY_ILL events should result in a change
 * of state in the doctor.
 */
TEST_F(EscortRobotTest, acceptRelevantEvents) {

    ASSERT_EQ(EscortRobot::AT_BASE, doctor.currentLocationState);
    ASSERT_FALSE(doctor.performingTask);

    doctor.eventTriggered(eventTriggerForEventType(EVENT_TRIGGER_EVENT_TYPE_VERY_ILL));

    // The doctor should change its state
    //ASSERT_GT(doctor.locationQueue.size(), 0);
    ASSERT_TRUE(doctor.performingTask);
    ASSERT_EQ(EscortRobot::GOING_TO_POI, doctor.currentLocationState);
}

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

    ros::init(argc, argv, "TestEscortRobot");
    ros::NodeHandle nodeHandle;

    // Advertise and subscribe to topics
    //residentEventPublisher = nodeHandle.advertise<EventTrigger>("event_trigger",1000, true);
    //residentEventSubscriber = nodeHandle.subscribe<EventTrigger>("event_trigger",1000, eventTriggeredCallback);

    // Run tests to see if we received messages as expected
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}<commit_msg>Tested that the correct EventTrigger is sent when an EscortRobot is told to notify the scheduler of its task completion. [#56]<commit_after>#include "ros/ros.h"
#include "std_msgs/String.h"

#include <sstream>
#include "math.h"
#include <vector>
#include "../EventTriggerUtility.h"
#include "../PerformTaskConstants.h"
#include "elderly_care_simulation/EventTrigger.h"
using namespace elderly_care_simulation;
#include "../EventNode.h"
#include <unistd.h> // sleep

#define private public
#include "../EscortRobot.h"

#include "gtest/gtest.h"

EscortRobot doctor;

// Store received messages
std::vector<EventTrigger> receivedEventTriggers;

// Publishers and subcribers
//ros::Publisher residentEventPublisher;
ros::Subscriber residentEventSubscriber;

/**
 * Callback for the 'event_trigger' topic messages.
 * Simply logs the received message into a list.
 */
void eventTriggerCallback(EventTrigger msg) {
    receivedEventTriggers.push_back(msg);
}

//void eventTriggeredCallback(EventTrigger msg) {
//    doctor.eventTriggered(msg);
//}

/**
 * This test suite tests the functionality of the EscortRobot class.
 * The EscortRobot ROS node under test is DoctorRobot.
 */
class EscortRobotTest : public ::testing::Test {
    protected:
        // You can remove any or all of the following functions if its body
        // is empty.

        EscortRobotTest() {
            // You can put any initialisation here.
        }

        virtual ~EscortRobotTest() {
            // You can do clean-up work that doesn't throw exceptions here.
        }

        // If the constructor and destructor are not enough for setting up
        // and cleaning up each test, you can define the following methods:

        virtual void SetUp() {
            // Clear any received messages
            // Store received messages
            receivedEventTriggers.clear();

            doctor.performingTask = false;
            doctor.currentLocationState = EscortRobot::AT_BASE;
        }

        virtual void TearDown() {
            // Code here will be called immediately after each test (right
            // before the destructor).
        }
};

EventTrigger eventTriggerForEventType(int eventType) {
    ROS_INFO("Making a message");
    EventTrigger msg;
    msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST;
    msg.event_type = eventType;
    msg.event_priority = EVENT_TRIGGER_PRIORITY_HIGH;
    msg.event_weight = getEventWeight(eventType);
    msg.result = EVENT_TRIGGER_RESULT_UNDEFINED;
    return msg;
}

/**
 * Any calls to the doctor that are not VERY_ILL events should be ignored.
 */
TEST_F(EscortRobotTest, ignoreIrrelevantEvents) {
    ROS_INFO("Starting test");

    ASSERT_EQ(EscortRobot::AT_BASE, doctor.currentLocationState);
    ASSERT_FALSE(doctor.performingTask);

    doctor.eventTriggered(eventTriggerForEventType(EVENT_TRIGGER_EVENT_TYPE_MEDICATION));

    // The doctor should not change its state
    ASSERT_EQ(EscortRobot::AT_BASE, doctor.currentLocationState);
    ASSERT_FALSE(doctor.performingTask);
}

/**
 * Any calls to the doctor that are VERY_ILL events should result in a change
 * of state in the doctor.
 */
TEST_F(EscortRobotTest, acceptRelevantEvents) {

    ASSERT_EQ(EscortRobot::AT_BASE, doctor.currentLocationState);
    ASSERT_FALSE(doctor.performingTask);

    doctor.eventTriggered(eventTriggerForEventType(EVENT_TRIGGER_EVENT_TYPE_VERY_ILL));

    // The doctor should change its state
    //ASSERT_GT(doctor.locationQueue.size(), 0);
    ASSERT_TRUE(doctor.performingTask);
    ASSERT_EQ(EscortRobot::GOING_TO_POI, doctor.currentLocationState);
}

/**
 * Asking the doctor to notify completion of its task should result in the correct
 * EventTrigger message being send on the "event_trigger" topic.
 */
TEST_F(EscortRobotTest, notifyTaskCompletion) {

    doctor.notifySchedulerOfTaskCompletion();

    // Wait until a message has been received
    ros::Rate loop_rate(10);
    while(receivedEventTriggers.size() == 0) {
        loop_rate.sleep();
        ros::spinOnce();
    }

    /*** ASSERTIONS BEGIN ***/

    // Check we received only one EventTrigger
    ASSERT_EQ(1, receivedEventTriggers.size());

    EventTrigger msg = receivedEventTriggers[0];

    // Check that the message has the correct information
    ASSERT_EQ(EVENT_TRIGGER_MSG_TYPE_RESPONSE, msg.msg_type);
    ASSERT_EQ(EVENT_TRIGGER_EVENT_TYPE_VERY_ILL, msg.event_type);
    ASSERT_EQ(EVENT_TRIGGER_RESULT_SUCCESS, msg.result);
}

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

    ros::init(argc, argv, "TestEscortRobot");
    ros::NodeHandle nodeHandle;

    // Instantiate a new doctor for each test
    geometry_msgs::Point base;
    base.x = 3.0f;
    base.y = 3.0f;

    geometry_msgs::Point hospital;
    hospital.x = 4.0f;
    hospital.y = 4.0f;

    doctor = EscortRobot(EVENT_TRIGGER_EVENT_TYPE_VERY_ILL, base, hospital);

    // Advertise and subscribe to topics
    //residentEventPublisher = nodeHandle.advertise<EventTrigger>("event_trigger",1000, true);
    doctor.eventTriggerPub = nodeHandle.advertise<EventTrigger>("event_trigger",1000, true);
    ros::Subscriber eventTriggerSub = nodeHandle.subscribe<EventTrigger>("event_trigger", 1000, eventTriggerCallback);

    // Run tests to see if we received messages as expected
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}<|endoftext|>


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

#include "iceoryx_posh/internal/log/posh_logging.hpp"
#include "iceoryx_posh/roudi/iceoryx_roudi_app.hpp"
#include "iceoryx_posh/roudi/roudi_cmd_line_parser_config_file_option.hpp"
#include "iceoryx_posh/roudi/roudi_config_toml_file_provider.hpp"
#include "iceoryx_utils/platform/getopt.hpp"

#include "test.hpp"

#include <regex>

using namespace ::testing;
using ::testing::Return;

using iox::roudi::IceOryxRouDiApp;
using namespace iox::config;

namespace iox
{
namespace test
{
class OutputBuffer
{
  public:
    OutputBuffer()
    {
        m_oldBuffer = std::clog.rdbuf();
        std::clog.rdbuf(m_capture.rdbuf());
    }
    ~OutputBuffer()
    {
        std::clog.rdbuf(m_oldBuffer);
    }

    std::string str()
    {
        return m_capture.str();
    }

    void clear()
    {
        m_capture.str(std::string());
    }

  private:
    std::stringstream m_capture;
    std::streambuf* m_oldBuffer{nullptr};
};

class IceoryxRoudiApp_Child : public IceOryxRouDiApp
{
  public:
    IceoryxRoudiApp_Child(const config::CmdLineArgs_t& cmdLineArgs, const RouDiConfig_t& roudiConfig)
        : IceOryxRouDiApp(cmdLineArgs, roudiConfig)
    {
    }

    bool getVariableRun()
    {
        return m_run;
    }

    iox::log::LogLevel getLogLevel()
    {
        return m_logLevel;
    }

    roudi::MonitoringMode getMonitoringMode()
    {
        return m_monitoringMode;
    }

    void setVariableRun(bool condition)
    {
        m_run = condition;
    }

    uint8_t callRun() noexcept
    {
        return run();
    }

    bool callWaitForSignal()
    {
        return waitForSignal();
    }
};

/// @brief Test goal: This file tests class roudi app
class IceoryxRoudiApp_test : public Test
{
  public:
    CmdLineParserConfigFileOption cmdLineParser;

    void SetUp() override
    {
        outBuffer.clear();
    }

    void TearDown()
    {
        // Reset optind to be able to parse again
        optind = 0;
    };

    OutputBuffer outBuffer;
    const std::regex colorCode{"\\x1B\\[([0-9]*;?)*m"};
};

TEST_F(IceoryxRoudiApp_test, VerifyConstructorIsSuccessful)
{
    constexpr uint8_t NUMBER_OF_ARGS{1U};
    char* args[NUMBER_OF_ARGS];
    char appName[] = "./foo";
    args[0] = &appName[0];

    auto cmdLineArgs = cmdLineParser.parse(NUMBER_OF_ARGS, args);

    ASSERT_FALSE(cmdLineArgs.has_error());

    IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());

    EXPECT_TRUE(roudi.getVariableRun());
    EXPECT_EQ(roudi.getLogLevel(), iox::log::LogLevel::kWarn);
    EXPECT_EQ(roudi.getMonitoringMode(), roudi::MonitoringMode::ON);
}

TEST_F(IceoryxRoudiApp_test, CreateTwoRoudiAppIsSuccessful)
{
    constexpr uint8_t NUMBER_OF_ARGS{1U};
    char* args[NUMBER_OF_ARGS];
    char appName[] = "./foo";
    args[0] = &appName[0];

    auto cmdLineArgs = cmdLineParser.parse(NUMBER_OF_ARGS, args);

    ASSERT_FALSE(cmdLineArgs.has_error());

    IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());

    IceoryxRoudiApp_Child roudiTest(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());

    EXPECT_TRUE(roudiTest.getVariableRun());
}

TEST_F(IceoryxRoudiApp_test, VerifyRunMethodWithFalseConditionReturnExitSuccess)
{
    constexpr uint8_t NUMBER_OF_ARGS{1U};
    char* args[NUMBER_OF_ARGS];
    char appName[] = "./foo";
    args[0] = &appName[0];

    auto cmdLineArgs = cmdLineParser.parse(NUMBER_OF_ARGS, args);

    ASSERT_FALSE(cmdLineArgs.has_error());

    IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());

    roudi.setVariableRun(false);

    uint8_t result = roudi.callRun();

    EXPECT_EQ(result, EXIT_SUCCESS);
}

TEST_F(IceoryxRoudiApp_test, ConstructorCalledWithArgUniqueIdTwoTimesReturnError)
{
    constexpr uint8_t NUMBER_OF_ARGS{3U};
    char* args[NUMBER_OF_ARGS];
    char appName[] = "./foo";
    char option[] = "--unique-roudi-id";
    char value[] = "4242";
    args[0] = &appName[0];
    args[1] = &option[0];
    args[2] = &value[0];

    auto cmdLineArgs = cmdLineParser.parse(NUMBER_OF_ARGS, args);

    ASSERT_FALSE(cmdLineArgs.has_error());

    iox::cxx::optional<iox::Error> detectedError;
    auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler(
        [&detectedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel errorLevel) {
            detectedError.emplace(error);
            EXPECT_EQ(errorLevel, iox::ErrorLevel::MODERATE);
        });

    IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());

    IceoryxRoudiApp_Child roudiTest(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());

    ASSERT_TRUE(detectedError.has_value());
    EXPECT_EQ(detectedError.value(), iox::Error::kPOPO__TYPED_UNIQUE_ID_ROUDI_HAS_ALREADY_DEFINED_UNIQUE_ID);
}

TEST_F(IceoryxRoudiApp_test, ConstructorCalledWithArgVersionSetRunVariableToFalse)
{
    constexpr uint8_t NUMBER_OF_ARGS{2U};
    char* args[NUMBER_OF_ARGS];
    char appName[] = "./foo";
    char option[] = "-v";
    args[0] = &appName[0];
    args[1] = &option[0];

    auto cmdLineArgs = cmdLineParser.parse(NUMBER_OF_ARGS, args);

    ASSERT_FALSE(cmdLineArgs.has_error());

    IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());

    EXPECT_FALSE(roudi.getVariableRun());
}

TEST_F(IceoryxRoudiApp_test, VerifyConstructorWithEmptyConfigSetRunVariableToFalse)
{
    constexpr uint8_t NUMBER_OF_ARGS{1U};
    char* args[NUMBER_OF_ARGS];
    char appName[] = "./foo";
    args[0] = &appName[0];
    const std::string expected = "A RouDiConfig without segments was specified! Please provide a valid config!";

    auto cmdLineArgs = cmdLineParser.parse(NUMBER_OF_ARGS, args);

    ASSERT_FALSE(cmdLineArgs.has_error());

    iox::RouDiConfig_t roudiConfig;

    IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), roudiConfig);

    std::string output = std::regex_replace(outBuffer.str(), colorCode, std::string(""));

    EXPECT_FALSE(roudi.getVariableRun());
    EXPECT_NE(output.find(expected), std::string::npos);
}

TEST_F(IceoryxRoudiApp_test, VerifyConstructorUsingConfigWithSegmentWithoutMemPoolSetRunVariableToFalse)
{
    constexpr uint8_t NUMBER_OF_ARGS{1U};
    char* args[NUMBER_OF_ARGS];
    char appName[] = "./foo";
    args[0] = &appName[0];
    const std::string expected =
        "A RouDiConfig with segments without mempools was specified! Please provide a valid config!";

    auto cmdLineArgs = cmdLineParser.parse(NUMBER_OF_ARGS, args);

    ASSERT_FALSE(cmdLineArgs.has_error());

    iox::mepoo::MePooConfig mempoolConfig;
    auto currentGroup = iox::posix::PosixGroup::getGroupOfCurrentProcess();

    iox::RouDiConfig_t roudiConfig;

    roudiConfig.m_sharedMemorySegments.push_back({currentGroup.getName(), currentGroup.getName(), mempoolConfig});

    IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), roudiConfig);

    std::string output = std::regex_replace(outBuffer.str(), colorCode, std::string(""));

    EXPECT_FALSE(roudi.getVariableRun());
    EXPECT_NE(output.find(expected), std::string::npos);
}

} // namespace test
} // namespace iox
<commit_msg>iox-#454 remove useless function<commit_after>// Copyright (c) 2021 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

#include "iceoryx_posh/internal/log/posh_logging.hpp"
#include "iceoryx_posh/roudi/iceoryx_roudi_app.hpp"
#include "iceoryx_posh/roudi/roudi_cmd_line_parser_config_file_option.hpp"
#include "iceoryx_posh/roudi/roudi_config_toml_file_provider.hpp"
#include "iceoryx_utils/platform/getopt.hpp"

#include "test.hpp"

#include <regex>

using namespace ::testing;
using ::testing::Return;

using iox::roudi::IceOryxRouDiApp;
using namespace iox::config;

namespace iox
{
namespace test
{
class OutputBuffer
{
  public:
    OutputBuffer()
    {
        m_oldBuffer = std::clog.rdbuf();
        std::clog.rdbuf(m_capture.rdbuf());
    }
    ~OutputBuffer()
    {
        std::clog.rdbuf(m_oldBuffer);
    }

    std::string str()
    {
        return m_capture.str();
    }

    void clear()
    {
        m_capture.str(std::string());
    }

  private:
    std::stringstream m_capture;
    std::streambuf* m_oldBuffer{nullptr};
};

class IceoryxRoudiApp_Child : public IceOryxRouDiApp
{
  public:
    IceoryxRoudiApp_Child(const config::CmdLineArgs_t& cmdLineArgs, const RouDiConfig_t& roudiConfig)
        : IceOryxRouDiApp(cmdLineArgs, roudiConfig)
    {
    }

    bool getVariableRun()
    {
        return m_run;
    }

    iox::log::LogLevel getLogLevel()
    {
        return m_logLevel;
    }

    roudi::MonitoringMode getMonitoringMode()
    {
        return m_monitoringMode;
    }

    void setVariableRun(bool condition)
    {
        m_run = condition;
    }

    uint8_t callRun() noexcept
    {
        return run();
    }
};

/// @brief Test goal: This file tests class roudi app
class IceoryxRoudiApp_test : public Test
{
  public:
    CmdLineParserConfigFileOption cmdLineParser;

    void SetUp() override
    {
        outBuffer.clear();
    }

    void TearDown()
    {
        // Reset optind to be able to parse again
        optind = 0;
    };

    OutputBuffer outBuffer;
    const std::regex colorCode{"\\x1B\\[([0-9]*;?)*m"};
};

TEST_F(IceoryxRoudiApp_test, VerifyConstructorIsSuccessful)
{
    constexpr uint8_t NUMBER_OF_ARGS{1U};
    char* args[NUMBER_OF_ARGS];
    char appName[] = "./foo";
    args[0] = &appName[0];

    auto cmdLineArgs = cmdLineParser.parse(NUMBER_OF_ARGS, args);

    ASSERT_FALSE(cmdLineArgs.has_error());

    IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());

    EXPECT_TRUE(roudi.getVariableRun());
    EXPECT_EQ(roudi.getLogLevel(), iox::log::LogLevel::kWarn);
    EXPECT_EQ(roudi.getMonitoringMode(), roudi::MonitoringMode::ON);
}

TEST_F(IceoryxRoudiApp_test, CreateTwoRoudiAppIsSuccessful)
{
    constexpr uint8_t NUMBER_OF_ARGS{1U};
    char* args[NUMBER_OF_ARGS];
    char appName[] = "./foo";
    args[0] = &appName[0];

    auto cmdLineArgs = cmdLineParser.parse(NUMBER_OF_ARGS, args);

    ASSERT_FALSE(cmdLineArgs.has_error());

    IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());

    IceoryxRoudiApp_Child roudiTest(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());

    EXPECT_TRUE(roudiTest.getVariableRun());
}

TEST_F(IceoryxRoudiApp_test, VerifyRunMethodWithFalseConditionReturnExitSuccess)
{
    constexpr uint8_t NUMBER_OF_ARGS{1U};
    char* args[NUMBER_OF_ARGS];
    char appName[] = "./foo";
    args[0] = &appName[0];

    auto cmdLineArgs = cmdLineParser.parse(NUMBER_OF_ARGS, args);

    ASSERT_FALSE(cmdLineArgs.has_error());

    IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());

    roudi.setVariableRun(false);

    uint8_t result = roudi.callRun();

    EXPECT_EQ(result, EXIT_SUCCESS);
}

TEST_F(IceoryxRoudiApp_test, ConstructorCalledWithArgUniqueIdTwoTimesReturnError)
{
    constexpr uint8_t NUMBER_OF_ARGS{3U};
    char* args[NUMBER_OF_ARGS];
    char appName[] = "./foo";
    char option[] = "--unique-roudi-id";
    char value[] = "4242";
    args[0] = &appName[0];
    args[1] = &option[0];
    args[2] = &value[0];

    auto cmdLineArgs = cmdLineParser.parse(NUMBER_OF_ARGS, args);

    ASSERT_FALSE(cmdLineArgs.has_error());

    iox::cxx::optional<iox::Error> detectedError;
    auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler(
        [&detectedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel errorLevel) {
            detectedError.emplace(error);
            EXPECT_EQ(errorLevel, iox::ErrorLevel::MODERATE);
        });

    IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());

    IceoryxRoudiApp_Child roudiTest(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());

    ASSERT_TRUE(detectedError.has_value());
    EXPECT_EQ(detectedError.value(), iox::Error::kPOPO__TYPED_UNIQUE_ID_ROUDI_HAS_ALREADY_DEFINED_UNIQUE_ID);
}

TEST_F(IceoryxRoudiApp_test, ConstructorCalledWithArgVersionSetRunVariableToFalse)
{
    constexpr uint8_t NUMBER_OF_ARGS{2U};
    char* args[NUMBER_OF_ARGS];
    char appName[] = "./foo";
    char option[] = "-v";
    args[0] = &appName[0];
    args[1] = &option[0];

    auto cmdLineArgs = cmdLineParser.parse(NUMBER_OF_ARGS, args);

    ASSERT_FALSE(cmdLineArgs.has_error());

    IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());

    EXPECT_FALSE(roudi.getVariableRun());
}

TEST_F(IceoryxRoudiApp_test, VerifyConstructorWithEmptyConfigSetRunVariableToFalse)
{
    constexpr uint8_t NUMBER_OF_ARGS{1U};
    char* args[NUMBER_OF_ARGS];
    char appName[] = "./foo";
    args[0] = &appName[0];
    const std::string expected = "A RouDiConfig without segments was specified! Please provide a valid config!";

    auto cmdLineArgs = cmdLineParser.parse(NUMBER_OF_ARGS, args);

    ASSERT_FALSE(cmdLineArgs.has_error());

    iox::RouDiConfig_t roudiConfig;

    IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), roudiConfig);

    std::string output = std::regex_replace(outBuffer.str(), colorCode, std::string(""));

    EXPECT_FALSE(roudi.getVariableRun());
    EXPECT_NE(output.find(expected), std::string::npos);
}

TEST_F(IceoryxRoudiApp_test, VerifyConstructorUsingConfigWithSegmentWithoutMemPoolSetRunVariableToFalse)
{
    constexpr uint8_t NUMBER_OF_ARGS{1U};
    char* args[NUMBER_OF_ARGS];
    char appName[] = "./foo";
    args[0] = &appName[0];
    const std::string expected =
        "A RouDiConfig with segments without mempools was specified! Please provide a valid config!";

    auto cmdLineArgs = cmdLineParser.parse(NUMBER_OF_ARGS, args);

    ASSERT_FALSE(cmdLineArgs.has_error());

    iox::mepoo::MePooConfig mempoolConfig;
    auto currentGroup = iox::posix::PosixGroup::getGroupOfCurrentProcess();

    iox::RouDiConfig_t roudiConfig;

    roudiConfig.m_sharedMemorySegments.push_back({currentGroup.getName(), currentGroup.getName(), mempoolConfig});

    IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), roudiConfig);

    std::string output = std::regex_replace(outBuffer.str(), colorCode, std::string(""));

    EXPECT_FALSE(roudi.getVariableRun());
    EXPECT_NE(output.find(expected), std::string::npos);
}

} // namespace test
} // namespace iox
<|endoftext|>