text:
//
// $Id$
//
//
// Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu>
//
// Copyright 2009 Vanderbilt University - Nashville, TN 37232
//
// 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 "pwiz/utility/misc/Export.hpp"
#include "pwiz/data/msdata/SpectrumListBase.hpp"
#include "Reader_Waters_Detail.hpp"
#include "pwiz/utility/misc/Container.hpp"
#include "pwiz/utility/misc/String.hpp"
#include "pwiz/utility/misc/Stream.hpp"
#include "pwiz/data/msdata/Reader.hpp"
#include "pwiz/analysis/spectrum_processing/SpectrumList_3D.hpp"
#include <boost/thread.hpp>

using boost::shared_ptr;

namespace pwiz {
namespace msdata {
namespace detail {

//
// SpectrumList_Waters
//
class PWIZ_API_DECL SpectrumList_Waters : public SpectrumListIonMobilityBase
{
    public:
        struct VendorOptions
        {
            pwiz::util::IntegerSet msLevelsToCentroid;

        };
    virtual size_t size() const;
    virtual const SpectrumIdentity& spectrumIdentity(size_t index) const;
    virtual size_t find(const string& id) const;
    virtual SpectrumPtr spectrum(size_t index, bool getBinaryData) const;
    virtual SpectrumPtr spectrum(size_t index, DetailLevel detailLevel) const;

    // TODO: convert vendor-specific parameters to a single config struct, but all non-vendor wrappers are going to have to pass it along :(
    virtual SpectrumPtr spectrum(size_t index, bool getBinaryData, const pwiz::util::IntegerSet& msLevelsToCentroid) const;
    virtual SpectrumPtr spectrum(size_t index, DetailLevel detailLevel, const pwiz::util::IntegerSet& msLevelsToCentroid) const;
    virtual SpectrumPtr spectrum(size_t index, bool getBinaryData, double lockmassMzPosScans, double lockmassMzNegScans, double lockmassTolerance, const pwiz::util::IntegerSet& msLevelsToCentroid) const;
    virtual SpectrumPtr spectrum(size_t index, DetailLevel detailLevel, double lockmassMzPosScans, double lockmassMzNegScans, double lockmassTolerance, const pwiz::util::IntegerSet& msLevelsToCentroid) const;

    virtual pwiz::analysis::Spectrum3DPtr spectrum3d(double scanStartTime, const boost::icl::interval_set<double>& driftTimeRanges) const;

    /// returns true if any functions are SONAR-enabled
    virtual bool hasSonarFunctions() const;
    virtual pair<int, int> sonarMzToBinRange(double precursorMz, double tolerance) const; // If precursor mz is outside SONAR range, returns pair <-1,-1>
    virtual double sonarBinToPrecursorMz(int bin) const; // If bin is outside SONAR range, returns 0

    virtual bool hasIonMobility() const;
    virtual bool hasCombinedIonMobility() const;
    virtual bool canConvertIonMobilityAndCCS() const;
    virtual double ionMobilityToCCS(double ionMobility, double mz, int charge) const;
    virtual double ccsToIonMobility(double ccs, double mz, int charge) const;

#ifdef PWIZ_READER_WATERS
    SpectrumList_Waters(MSData& msd, RawDataPtr rawdata, const Reader::Config& config);

    private:

    MSData& msd_;
    RawDataPtr rawdata_;
    size_t size_;
    Reader::Config config_;

    struct IndexEntry : public SpectrumIdentity
    {
        int function;
        int process;
        int scan;
        int block; // block < 0 is not ion mobility
    };

    mutable vector<IndexEntry> index_;
    mutable map<string, size_t> idToIndexMap_;
    mutable boost::container::flat_map<double, vector<pair<int, int> > > scanTimeToFunctionAndBlockMap_;

    void getCombinedSpectrumData(int function, int block, BinaryData<double>& mz, BinaryData<double>& intensity, BinaryData<double>& driftTimeOrSonarRangeLow, BinaryData<double>& sonarRangeHigh, bool doCentroid) const;

    void initializeCoefficients() const;
    double calibrate(const double &mz) const;
    mutable vector<double> calibrationCoefficients_;
    mutable vector<double> imsCalibratedMasses_;
    mutable vector<float> imsMasses_;
    mutable vector<int> massIndices_;
    mutable vector<float> imsIntensities_;
    mutable boost::mutex readMutex;

    void createIndex();
#endif // PWIZ_READER_WATERS
};

} // detail
} // msdata
} // pwiz

max_stars_repo_name: vagisha/pwiz

max_issues_repo_name: vagisha/pwiz

max_forks_repo_name: vagisha/pwiz


text:
#define BOOST_TEST_MODULE DivisibleSumPairsTest

#include "DivisibleSumPairs.hpp"
#include <vector>
#include <cstddef>

#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include <boost/algorithm/string.hpp>

BOOST_AUTO_TEST_SUITE(DivisibleSumPairsSuite)

using namespace com::github::nimelo;
using namespace std;

BOOST_AUTO_TEST_CASE(TestSet_1)
{
  // Arrange
  vector<int> set = { 1, 3, 2, 6, 1, 2};
  int k = 3;

  size_t expected_result = 5;
  DivisibleSumPairs<int> dsp(set);

  // Act
  auto actual_result = dsp.get(k);

  // Assert
  BOOST_CHECK_EQUAL(expected_result, actual_result);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cc

max_stars_repo_name: Nimelo/hacker-rank

max_issues_repo_name: Nimelo/hacker-rank

max_forks_repo_name: Nimelo/hacker-rank


text:
#ifndef MYSQL_ASIO_IMPL_RESULTSET_HPP
#define MYSQL_ASIO_IMPL_RESULTSET_HPP

#include "boost/mysql/detail/network_algorithms/read_row.hpp"
#include <boost/asio/coroutine.hpp>
#include <cassert>
#include <limits>
#include <boost/asio/yield.hpp>

template <typename StreamType>
const boost::mysql::row* boost::mysql::resultset<StreamType>::fetch_one(
	error_code& err,
	error_info& info
)
{
	assert(valid());

	err.clear();
	info.clear();

	if (complete())
	{
		return nullptr;
	}
	auto result = detail::read_row(
		deserializer_,
		*channel_,
		meta_.fields(),
		buffer_,
		current_row_.values(),
		ok_packet_,
		err,
		info
	);
	eof_received_ = result == detail::read_row_result::eof;
	return result == detail::read_row_result::row ? &current_row_ : nullptr;
}

template <typename StreamType>
const boost::mysql::row* boost::mysql::resultset<StreamType>::fetch_one()
{
	error_code code;
	error_info info;
	const row* res = fetch_one(code, info);
	detail::check_error_code(code, info);
	return res;
}

template <typename StreamType>
std::vector<boost::mysql::owning_row> boost::mysql::resultset<StreamType>::fetch_many(
	std::size_t count,
	error_code& err,
	error_info& info
)
{
	assert(valid());

	err.clear();
	info.clear();

	std::vector<mysql::owning_row> res;

	if (!complete()) // support calling fetch on already exhausted resultset
	{
		for (std::size_t i = 0; i < count; ++i)
		{
			detail::bytestring buff;
			std::vector<value> values;

			auto result = detail::read_row(
				deserializer_,
				*channel_,
				meta_.fields(),
				buff,
				values,
				ok_packet_,
				err,
				info
			);
			eof_received_ = result == detail::read_row_result::eof;
			if (result == detail::read_row_result::row)
			{
				res.emplace_back(std::move(values), std::move(buff));
			}
			else
			{
				break;
			}
		}
	}

	return res;
}

template <typename StreamType>
std::vector<boost::mysql::owning_row> boost::mysql::resultset<StreamType>::fetch_many(
	std::size_t count
)
{
	error_code code;
	error_info info;
	auto res = fetch_many(count, code, info);
	detail::check_error_code(code, info);
	return res;
}

template <typename StreamType>
std::vector<boost::mysql::owning_row> boost::mysql::resultset<StreamType>::fetch_all(
	error_code& err,
	error_info& info
)
{
	return fetch_many(std::numeric_limits<std::size_t>::max(), err, info);
}

template <typename StreamType>
std::vector<boost::mysql::owning_row> boost::mysql::resultset<StreamType>::fetch_all()
{
	return fetch_many(std::numeric_limits<std::size_t>::max());
}

template <typename StreamType>
template <typename CompletionToken>
BOOST_ASIO_INITFN_RESULT_TYPE(
	CompletionToken,
	void(boost::mysql::error_code, boost::mysql::error_info, const boost::mysql::row*)
)
boost::mysql::resultset<StreamType>::async_fetch_one(
	CompletionToken&& token
)
{
	using HandlerSignature = void(error_code, error_info, const row*);
	using HandlerType = BOOST_ASIO_HANDLER_TYPE(CompletionToken, HandlerSignature);
	using BaseType = boost::beast::async_base<HandlerType, typename StreamType::executor_type>;

	struct Op: BaseType, boost::asio::coroutine
	{
		resultset<StreamType>& resultset_;

		Op(
			HandlerType&& handler,
			resultset<StreamType>& obj
		):
			BaseType(std::move(handler), obj.channel_->next_layer().get_executor()),
			resultset_(obj) {};

		void operator()(
			error_code err,
			error_info info,
			detail::read_row_result result,
			bool cont=true
		)
		{
			reenter(*this)
			{
				if (resultset_.complete())
				{
					this->complete(cont, error_code(), error_info(), nullptr);
				}
				else
				{
					yield detail::async_read_row(
						resultset_.deserializer_,
						*resultset_.channel_,
						resultset_.meta_.fields(),
						resultset_.buffer_,
						resultset_.current_row_.values(),
						resultset_.ok_packet_,
						std::move(*this)
					);
					resultset_.eof_received_ = result == detail::read_row_result::eof;
					this->complete(
						cont,
						err,
						std::move(info),
						result == detail::read_row_result::row ? &resultset_.current_row_ : nullptr
					);
				}
			}
		}
	};

	assert(valid());

	boost::asio::async_completion<CompletionToken, HandlerSignature> initiator(token);

	Op(
		std::move(initiator.completion_handler),
		*this
	)(error_code(), error_info(), detail::read_row_result::error, false);
	return initiator.result.get();
}

template <typename StreamType>
template <typename CompletionToken>
BOOST_ASIO_INITFN_RESULT_TYPE(
	CompletionToken,
	void(boost::mysql::error_code, boost::mysql::error_info, std::vector<boost::mysql::owning_row>)
)
boost::mysql::resultset<StreamType>::async_fetch_many(
	std::size_t count,
	CompletionToken&& token
)
{
	using HandlerSignature = void(error_code, error_info, std::vector<owning_row>);
	using HandlerType = BOOST_ASIO_HANDLER_TYPE(CompletionToken, HandlerSignature);
	using BaseType = boost::beast::async_base<HandlerType, typename StreamType::executor_type>;

	struct OpImpl
	{
		resultset<StreamType>& parent_resultset;
		std::vector<owning_row> rows;
		detail::bytestring buffer;
		std::vector<value> values;
		std::size_t remaining;

		OpImpl(resultset<StreamType>& obj, std::size_t count):
			parent_resultset(obj), remaining(count) {};

		void row_received()
		{
			rows.emplace_back(std::move(values), std::move(buffer));
			values = std::vector<value>{};
			buffer = detail::bytestring{};
			--remaining;
		}
	};

	struct Op: BaseType, boost::asio::coroutine
	{
		std::shared_ptr<OpImpl> impl_;

		Op(
			HandlerType&& handler,
			std::shared_ptr<OpImpl>&& impl
		):
			BaseType(std::move(handler), impl->parent_resultset.channel_->next_layer().get_executor()),
			impl_(std::move(impl))
		{
		};

		void operator()(
			error_code err,
			error_info info,
			detail::read_row_result result,
			bool cont=true
		)
		{
			reenter(*this)
			{
				while (!impl_->parent_resultset.complete() && impl_->remaining > 0)
				{
					yield detail::async_read_row(
						impl_->parent_resultset.deserializer_,
						*impl_->parent_resultset.channel_,
						impl_->parent_resultset.meta_.fields(),
						impl_->buffer,
						impl_->values,
						impl_->parent_resultset.ok_packet_,
						std::move(*this)
					);
					if (result == detail::read_row_result::error)
					{
						this->complete(cont, err, std::move(info), std::move(impl_->rows));
						yield break;
					}
					else if (result == detail::read_row_result::eof)
					{
						impl_->parent_resultset.eof_received_ = true;
					}
					else
					{
						impl_->row_received();
					}
				}
				this->complete(cont, err, error_info(), std::move(impl_->rows));
			}
		}
	};

	assert(valid());

	boost::asio::async_completion<CompletionToken, HandlerSignature> initiator(token);

	Op(
		std::move(initiator.completion_handler),
		std::make_shared<OpImpl>(*this, count)
	)(error_code(), error_info(), detail::read_row_result::error, false);
	return initiator.result.get();
}

template <typename StreamType>
template <typename CompletionToken>
BOOST_ASIO_INITFN_RESULT_TYPE(
	CompletionToken,
	void(boost::mysql::error_code, boost::mysql::error_info, std::vector<boost::mysql::owning_row>)
)
boost::mysql::resultset<StreamType>::async_fetch_all(
	CompletionToken&& token
)
{
	return async_fetch_many(
		std::numeric_limits<std::size_t>::max(),
		std::forward<CompletionToken>(token)
	);
}

#include <boost/asio/unyield.hpp>

#endif

ext: hpp


text:
/*
 * Copyright Andrey Semashev 2020
 *
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or copy at
 * https://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file bit_ceil.hpp
 *
 * This header defines \c bit_ceil algorithm, which produces a nearest power of 2 integer
 * that is greater or equal to the input integer.
 */

#ifndef BOOST_BIT_OPS_POW2_BIT_CEIL_HPP_INCLUDED_
#define BOOST_BIT_OPS_POW2_BIT_CEIL_HPP_INCLUDED_

#include <limits>
#include <boost/bit_ops/detail/config.hpp>
#include <boost/bit_ops/detail/type_traits/enable_if.hpp>
#include <boost/bit_ops/detail/type_traits/is_integral.hpp>
#include <boost/bit_ops/detail/type_traits/is_unsigned.hpp>
#include <boost/bit_ops/count/countl_zero.hpp>

namespace boost {
namespace bit_ops {

/*!
 * \brief Returns the nearest power of 2 integer that is greater or equal to \a value
 *
 * \pre \a value must not be zero
 */
template< typename T >
inline typename bit_ops::detail::enable_if<
    bit_ops::detail::is_integral< T >::value && bit_ops::detail::is_unsigned< T >::value,
    T
>::type bit_ceil_nz(T value) BOOST_NOEXCEPT
{
    return static_cast< T >(1u) << ((std::numeric_limits< T >::digits - 1u) - bit_ops::countl_zero_nz(value) + ((value & (value - 1u)) != 0u));
}

//! Returns the nearest power of 2 integer that is greater or equal to \a value
template< typename T >
inline typename bit_ops::detail::enable_if<
    bit_ops::detail::is_integral< T >::value && bit_ops::detail::is_unsigned< T >::value,
    T
>::type bit_ceil(T value) BOOST_NOEXCEPT
{
    // bit_ceil(0) == bit_ceil(1) == 1
    return value == 0u ? static_cast< T >(1u) : bit_ops::bit_ceil_nz(value);
}

} // namespace bit_ops
} // namespace boost

#endif // BOOST_BIT_OPS_POW2_BIT_CEIL_HPP_INCLUDED_


text:
// Copyright (c) 2018-2021 Antony Polukhin
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/pfr/detail/fields_count.hpp>

struct some_struct {
    int i;
    int j;
};

int main() {
    return static_cast<int>(boost::pfr::detail::fields_count<some_struct&>());
}

ext: cpp


text:
#include <boost/test/unit_test.hpp>
#include "triangle.h"

BOOST_AUTO_TEST_SUITE(test_triangle)

BOOST_AUTO_TEST_CASE(test_triangle_trace)
{
	math::triangle<3> tri(math::vec<3>(0, 1, 0), math::vec<3>(0, 3, 1), math::vec<3>(1, 3, 0));
	math::scalar t;
	math::vec<3> v;
	bool result = tri.trace(math::ray<3>(math::vec<3>(-1, 2, 0), math::vec<3>(10, 0, 0)), t, v);
	BOOST_CHECK (result == true);
	BOOST_CHECK ((math::vec<3>(0.5f, 2, 0) - v).length() < math::EPSILON);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: mnvl/scratch

max_issues_repo_name: mnvl/scratch

max_forks_repo_name: mnvl/scratch


text:
#pragma once

#include <OIS.h>
#include <CEGUI.h>

#include <boost/bind.hpp>
#include <boost/mem_fn.hpp>
#include <boost/fusion/include/vector_tie.hpp>
#include <boost/range/algorithm/for_each.hpp>
#include <boost/foreach.hpp>
#include <boost/fusion/include/for_each.hpp>

//#include <WRAP_TMP_PROC/boost_range.hpp>

class OISSystem{
private:
	OIS::InputManager *m_pIM;
	std::vector<OIS::Keyboard *> m_keyboards;
	std::vector<OIS::Mouse *> m_mice;
	void CreateDevices(){
		//for(int i=m_pIM->numKeyBoards();i;--i){
		if(m_pIM->getNumberOfDevices(OIS::OISKeyboard)){
			m_keyboards.push_back(dynamic_cast<OIS::Keyboard *>( m_pIM->createInputObject(OIS::OISKeyboard,true) ));
			assert(m_keyboards.back());
		}
		if(m_pIM->getNumberOfDevices(OIS::OISMouse)){
			m_mice.push_back(dynamic_cast<OIS::Mouse*>( m_pIM->createInputObject( OIS::OISMouse, true ) ));
			assert(m_mice.back());
		}
	}
public:
	OISSystem(Ogre::RenderWindow *pWindow)
	{
		std::size_t windowHandle=0;
		pWindow->getCustomAttribute("WINDOW",&windowHandle);
		assert(windowHandle);
		m_pIM = OIS::InputManager::createInputSystem(windowHandle);
		CreateDevices();
		unsigned int width, height, depth;
		int top, left;
		pWindow->getMetrics(width, height, depth, left, top);
		BOOST_FOREACH( OIS::Mouse *p, m_mice )
		{
			p->getMouseState().width = width;
			p->getMouseState().height = height;
		}
	}

	const std::vector<OIS::Keyboard *> &Keyboards(){ return m_keyboards; }
	const std::vector<OIS::Mouse *> &Mice(){ return m_mice; }
	~OISSystem(){
		using namespace boost;
		//using namespace boost::bind;
		//function template wrapper needed again;
		//fusion::for_each
		//(
		//	fusion::vector_tie(m_mice,m_keyboards),
		//	bind
		//	(
		//		range::for_each_PROC_OBJ_2() ,
		//		_1 , bind(mem_fun(&OIS::InputManager::destroyInputObject),m_pIM,_1)
		//	)
		//);
		//bind( &range::for_each< std::vector<OIS::Mouse *> >, _1 , bind(mem_fn(&OIS::InputManager::destroyInputObject),m_pIM,_1) )	(m_mice);
		//range::for_each_PROC_OBJ_2()(m_mice,bind(mem_fn(&OIS::InputManager::destroyInputObject),m_pIM,_1));
		range::for_each(m_mice,bind(mem_fn(&OIS::InputManager::destroyInputObject),m_pIM,_1));
		range::for_each(m_keyboards,bind(mem_fn(&OIS::InputManager::destroyInputObject),m_pIM,_1));
		OIS::InputManager::destroyInputSystem(m_pIM);
	}
};

//template<typename _OISDevice,typename _Target>
//class OISInputRouter;
//
//template<>
//class OISInputRouter<OIS::Mouse,CEGUI::System>: public OIS::MouseListener
//{
//public:
//
//};

template<typename _Dest, typename _Src> _Dest TranslateEnum(_Src s);

template<>
CEGUI::MouseButton TranslateEnum(OIS::MouseButtonID s){
	return (CEGUI::MouseButton)s;
}

class OIS2CEGUIMouseListener: public OIS::MouseListener
{
	CEGUI::System &m_cegui;
public:
	virtual bool 	mouseMoved (const OIS::MouseEvent &arg){
		//m_cegui.injectMousePosition(arg.state.X.abs,arg.state.Y.abs);
		m_cegui.injectMouseMove(arg.state.X.rel,arg.state.Y.rel);
		m_cegui.injectMouseWheelChange(arg.state.Z.rel);
		return true;
	}
	virtual bool 	mousePressed (const OIS::MouseEvent &arg, OIS::MouseButtonID id){
		m_cegui.injectMouseButtonDown(TranslateEnum<CEGUI::MouseButton>(id));
		return true;
	}
	virtual bool 	mouseReleased (const OIS::MouseEvent &arg, OIS::MouseButtonID id){
		m_cegui.injectMouseButtonUp(TranslateEnum<CEGUI::MouseButton>(id));
		return true;
	}
	OIS2CEGUIMouseListener(CEGUI::System &cegui):m_cegui(cegui){}
};

class OIS2CEGUIKeyListener: public OIS::KeyListener
{
	CEGUI::System &m_cegui;
public:
	virtual bool 	keyPressed (const OIS::KeyEvent &arg){
		m_cegui.injectKeyDown(arg.key);
		return true;
	}
	virtual bool 	keyReleased (const OIS::KeyEvent &arg){
		m_cegui.injectKeyUp(arg.key);
		return true;
	}
	OIS2CEGUIKeyListener(CEGUI::System &cegui):m_cegui(cegui){}
};

template<typename _OISDevice>
struct GetOISDeviceListenerInterface;

template<> struct GetOISDeviceListenerInterface<OIS::Mouse>{
	typedef OIS::MouseListener Type;
};
template<> struct GetOISDeviceListenerInterface<OIS::Keyboard>{
	typedef OIS::KeyListener Type;
};

template<typename _OISDevice,typename _CopyableListener>
void RouteOISUserInput( _OISDevice &ois, _CopyableListener l)
{
	assert(ois.buffered());
	typename GetOISDeviceListenerInterface<_OISDevice>::Type *p = ois.getEventCallback();
	ois.setEventCallback(&l);
	ois.capture();
	ois.setEventCallback(p);
}

max_stars_repo_name: ducis/pile-of-cpp

max_issues_repo_name: ducis/pile-of-cpp

max_forks_repo_name: ducis/pile-of-cpp


text:
/* a zero-sum game example
 payoff matrix
 4 1 8
 2 3 1
 0 4 3
 player's optimal strategy
 I's  (.25,.75,0)
 II's (.5,.5,0)
 Nash equilibrium value 5/2

 Another zero-sum game example
 payoff matrix
 2 3 1 5
 4 1 6 0
 player's optimal strategy
 I's  (0.7143,0.2857)
 II's (0,0.7143,0.2857,0)
 Nash equilibrium value 2.42857
*/

#include <armadillo>
#include "zeroSumGame.h"

using namespace arma;
using namespace std;

int main()
{
//    Mat<double> payoffMat(3,3);
//    payoffMat << 4 << 1 << 8 << endr
//    << 2 << 3 << 1 << endr
//    << 0 << 4 << 3 << endr;

    Mat<double> payoffMat(2,4);
    payoffMat << 2 << 3 << 1 << 5 << endr
              << 4 << 1 << 6 << 0 << endr;

    double gameValue = 0;
    //Col<double> p(payoffMat.n_rows);
    //p.fill(0.0);
    //Col<double> q(payoffMat.n_cols);
    //q.fill(0.0);
    Col<double> p;
    Col<double> q;
    double equilibriumThreshold = 1e-4;
    bool checkNonnegative = true;

    double maxAbsValue = max(max(abs(payoffMat)));
    Mat<double> normPayoffMat = payoffMat/maxAbsValue+1.0;
    if(ZeroSumGame::solveGame(normPayoffMat,gameValue,p,q,equilibriumThreshold,checkNonnegative)){
        gameValue = (gameValue-1)*maxAbsValue;
        cout << gameValue << endl;
        p.print("p:");
        q.print("q:");
    }
    return 0;
}

max_stars_repo_name: xiangli-chen/two-person-zero-sum-game

max_issues_repo_name: xiangli-chen/two-person-zero-sum-game

max_forks_repo_name: xiangli-chen/two-person-zero-sum-game


text:
/*
 * This file is a part of the TChecker project.
 *
 * See files AUTHORS and LICENSE for copyright details.
 *
 */

#if BOOST_VERSION <= 106600
#include <boost/functional/hash.hpp>
#else
#include <boost/container_hash/hash.hpp>
#endif

#include "tchecker/ta/transition.hh"

namespace tchecker {

namespace ta {

/* transition_t */

tchecker::range_t<tchecker::clock_constraint_container_const_iterator_t> transition_t::src_invariant() const
{
  return tchecker::make_range(_src_invariant.begin(), _src_invariant.end());
}

tchecker::range_t<tchecker::clock_constraint_container_const_iterator_t> transition_t::guard() const
{
  return tchecker::make_range(_guard.begin(), _guard.end());
}

tchecker::range_t<tchecker::clock_reset_container_const_iterator_t> transition_t::reset() const
{
  return tchecker::make_range(_reset.begin(), _reset.end());
}

tchecker::range_t<tchecker::clock_constraint_container_const_iterator_t> transition_t::tgt_invariant() const
{
  return tchecker::make_range(_tgt_invariant.begin(), _tgt_invariant.end());
}

bool operator==(tchecker::ta::transition_t const & t1, tchecker::ta::transition_t const & t2)
{
  return (tchecker::syncprod::operator==(t1, t2) && t1.src_invariant_container() == t2.src_invariant_container() &&
          t1.guard_container() == t2.guard_container() && t1.reset_container() == t2.reset_container() &&
          t1.tgt_invariant_container() == t2.tgt_invariant_container());
}

std::size_t hash_value(tchecker::ta::transition_t const & t)
{
  std::size_t h = tchecker::syncprod::hash_value(t);
  boost::hash_combine(h, t.src_invariant_container());
  boost::hash_combine(h, t.guard_container());
  boost::hash_combine(h, t.reset_container());
  boost::hash_combine(h, t.tgt_invariant_container());
  return h;
}

int lexical_cmp(tchecker::ta::transition_t const & t1, tchecker::ta::transition_t const & t2)
{
  int syncprod_cmp = tchecker::syncprod::lexical_cmp(t1, t2);
  if (syncprod_cmp != 0)
    return syncprod_cmp;
  int src_invariant_cmp = tchecker::lexical_cmp(t1.src_invariant_container(), t2.src_invariant_container());
  if (src_invariant_cmp != 0)
    return src_invariant_cmp;
  int guard_cmp = tchecker::lexical_cmp(t1.guard_container(), t2.guard_container());
  if (guard_cmp != 0)
    return guard_cmp;
  int reset_cmp = tchecker::lexical_cmp(t1.reset_container(), t2.reset_container());
  if (reset_cmp != 0)
    return reset_cmp;
  return tchecker::lexical_cmp(t1.tgt_invariant_container(), t2.tgt_invariant_container());
}

} // end of namespace ta

} // end of namespace tchecker

max_stars_repo_name: arnabSur/tchecker

max_issues_repo_name: arnabSur/tchecker

max_forks_repo_name: arnabSur/tchecker


text:
/*
* Copyright 2021 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés
*/
#include <string>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include "../thirdParty/MBES-lib/src/utils/StringUtils.hpp"
#include "../OpenSidescan/sidescan/sidescanimager.h"
#include "../OpenSidescan/sidescan/sidescanfile.h"
#include "../OpenSidescan/sidescan/sidescanimage.h"
#include "../OpenSidescan/inventoryobject/inventoryobject.h"
#include "../OpenSidescan/detector/roidetector.h"

#include <Eigen/Dense>

typedef struct{
    int channel;
    int x;
    int y;
} hit ;

void load_SSS_Files(std::vector<SidescanFile*> & files, std::string & directoryPath){
    DIR *dir = NULL;

    //TODO: read this lever arm from metadata or user input
    Eigen::Vector3d antenna2TowPoint(0.0,0.0,0.0);

    if(dir = opendir(directoryPath.c_str())){

        //std::cerr << "Processing " << directoryPath << std::endl;

        dirent* file;

        std::stringstream filenameStream;

        while(file=readdir(dir)){

            if(StringUtils::ends_with(file->d_name,".xtf")){
                filenameStream.str("");
                filenameStream << directoryPath << "/" << file->d_name;
                std::string fileName(filenameStream.str());

                //std::cerr << "[+] Processing " << fileName << std::endl;

                //std::cerr << "[-]     Reading image data from " << fileName << std::endl;

                //Read image data
                SidescanImager imager;
                DatagramParser * parser = DatagramParserFactory::build(fileName,imager);
                parser->parse(fileName);

                SidescanFile * sidescanFile = imager.generate(fileName, antenna2TowPoint);
                REQUIRE(sidescanFile);
                files.push_back(sidescanFile);
                REQUIRE(files.size() == 1 );
            }
        }

        closedir(dir);
    }
    else{
        throw std::runtime_error("Can't open directory");
    }
}
void load_HITS_Files(std::vector<std::vector<hit*>*> & hits, std::string & directoryPath){
    DIR *dir = NULL;
    if(dir = opendir(directoryPath.c_str())){

        //std::cerr << "Processing " << directoryPath << std::endl;

        dirent* file;

        std::stringstream filenameStream;

        while(file=readdir(dir)){
            if(StringUtils::ends_with(file->d_name,".hits")){
                filenameStream.str("");
                filenameStream << directoryPath << "/" << file->d_name;
                std::string hitsFilename = filenameStream.str();

                //std::cerr << "[-]     Reading hits data from " << hitsFilename << std::endl;

                std::ifstream hitsFile(hitsFilename);

                if(hitsFile){
                    std::string line;
                    std::vector<hit*> * fileHits = new std::vector<hit*>();

                    while(std::getline(hitsFile,line)){
                        hit * h = (hit*) malloc(sizeof(hit));

                        if(sscanf(line.c_str(),"%d %d %d",&h->channel,&h->x,&h->y) == 3){
                            fileHits->push_back(h);
                        }
                        else{
                            std::cerr<<file->d_name<<"\n";
                            throw std::runtime_error("hits file not formatted properly"); //seems to be unstable
                        }
                    }
                    //std::cerr << "[+]     " << fileHits->size() << " hits read" << std::endl;
                    REQUIRE(fileHits->size() == 2);
                    hits.push_back(fileHits);
                    hitsFile.close();
                }

            }

        }

        closedir(dir);
    }
    else{
        throw std::runtime_error("Can't open directory");
    }
}

bool insideHits(InventoryObject * obj,std::vector<hit*> & hits){
    for(auto i=hits.begin();i!=hits.end();i++){
        if(
                (*i)->channel == obj->getImage().getChannelNumber() &&
                ((*i)->x >= obj->getX()) && ((*i)->x <= (obj->getX() + obj->getPixelWidth())) &&
                ((*i)->y >= obj->getY()) && ((*i)->y <= (obj->getY() + obj->getPixelHeight()))
        ){
            return true;
        }
    }

    return false;
}

bool insideDetections(hit * h, std::vector<InventoryObject*> & detections){
    for(auto i=detections.begin();i!=detections.end();i++){
        if(
                h->channel == (*i)->getImage().getChannelNumber() &&
                (h->x >= (*i)->getX()) && (h->x <= ((*i)->getX() + (*i)->getPixelWidth())) &&
                (h->y >= (*i)->getY()) && (h->y <= ((*i)->getY() + (*i)->getPixelHeight()))
        ){
            return true;
        }
    }

    return false;
}

void testing_inside_X_functions(std::vector<SidescanFile*> & files,std::vector<std::vector<hit*> *> & hits){

    int truePositive   = 0;
    int precisionCount = 0;

    int recalled = 0;
    int recallCount = 0;

    std::vector<InventoryObject*> detections;
    SidescanFile *element = files[0];
    SidescanImage * image = element->getImages()[1];
    REQUIRE(image);
    InventoryObject crabpot4_1(*image,600,1050,700,1150);
    InventoryObject crabpot4_2(*image,500,1300,600,1400);
    InventoryObject false_detect1(*image,1,1,100,100);
    InventoryObject false_detect2(*image,100,100,200,200);
    detections.push_back(&crabpot4_1);
    detections.push_back(&crabpot4_2);
    detections.push_back(&false_detect1);
    detections.push_back(&false_detect2);
        // check if detection contain a hit
        for(auto detection=detections.begin();detection != detections.end(); detection++){
            if(insideHits(*detection,* hits[0])){
                truePositive++;
            }
            precisionCount++;
        }

        // check if all hits have been detect
        for(auto h=hits[0]->begin(); h!=hits[0]->end(); h++){
            if(insideDetections(*h,detections)){
                recalled++;
            }
            recallCount++;
        }

    detections.clear();

    double precision = (truePositive > 0 && precisionCount > 0)?((double)truePositive/(double)precisionCount) * 100 : 0.0;
    double recall = (recalled > 0 && recallCount > 0)?((double)recalled/(double)recallCount)*100:0.0;

    //std::cout<<"True positive : "<< precision<<"\n";
    //std::cout<<"% of targets detected : "<<recall<<"\n";
    REQUIRE (precision == 50);
    REQUIRE (recall == 100);

}

TEST_CASE("fit-detector"){

    std::string directory = "../../../test/fit-detector_unit-test/testdata";
    std::vector<SidescanFile*>       files;
    std::vector<std::vector<hit*> *> hits;

    try{
        load_SSS_Files(files,directory);
        load_HITS_Files(hits,directory);
        REQUIRE(files.size() == hits.size());

        testing_inside_X_functions(files,hits);
        }

    catch(Exception  *e){
    std::cerr << "Error: " << e->what() << std::endl;
    }

}

max_stars_repo_name: patcmorneau/OpenSidescan

max_issues_repo_name: patcmorneau/OpenSidescan

max_forks_repo_name: patcmorneau/OpenSidescan


text:
#include "v_2_EMPCircuit.h"

#include <boost/program_options.hpp>
#include <boost/format.hpp>
#include <iostream>
#include <fstream>
#include "parse_netlist.h"
#include "emp_circuit.h"
#include "log.h"

namespace po = boost::program_options;
using std::ofstream;
using std::endl;

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

  string input_netlist_file;
  string output_circuit_file;

  boost::format fmter(
      "Verilog to EMPCircuit\nAllowed options");
  po::options_description desc(fmter.str());
  desc.add_options()  //
  ("help,h", "produce help message.")  //
  ("netlist,i", po::value<string>(&input_netlist_file),
   "Input netlist (verilog .v) file address.")  //
  ("emp,o", po::value<string>(&output_circuit_file),
   "Output EMPCircuit file address.");

  po::variables_map vm;
  try {
    po::parsed_options parsed = po::command_line_parser(argc, argv).options(
        desc).allow_unregistered().run();
    po::store(parsed, vm);
    if (vm.count("help")) {
      std::cout << desc << endl;
      return SUCCESS;
    }
    po::notify(vm);
  } catch (po::error& e) {
    LOG(ERROR) << "ERROR: " << e.what() << endl << endl;
    std::cout << desc << endl;
    return FAILURE;
  }

  if (output_circuit_file.empty()) {
    std::cerr << "ERROR: output circuit (-o) flag must be indicated." << endl;
    std::cout << desc << endl;
    return FAILURE;
  }

  string out_mapping_filename = output_circuit_file + ".map";

  if (!input_netlist_file.empty()) {
    LOG(INFO) << "V2EMPCircuit " << input_netlist_file << " to " << output_circuit_file
              << endl;
    if (Verilog2EMPCircuit(input_netlist_file, out_mapping_filename,
                    output_circuit_file) == FAILURE) {
      LOG(ERROR) << "Verilog to EMPCircuit failed." << endl;
      return FAILURE;
    }
  } else {
    std::cerr << "ERROR: input netlist flags must be indicated." << endl;
    std::cout << desc << endl;
    return FAILURE;
  }

  LogFinish();
  return SUCCESS;
}


text:
//
// Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

// Test that header file is self-contained.
#include <beast/http/streambuf_body.hpp>

#include <beast/core/to_string.hpp>
#include <beast/http/headers.hpp>
#include <beast/http/parser_v1.hpp>
#include <beast/http/read.hpp>
#include <beast/http/write.hpp>
#include <beast/test/string_stream.hpp>
#include <beast/unit_test/suite.hpp>
#include <boost/lexical_cast.hpp>

namespace beast {
namespace http {

class streambuf_body_test : public beast::unit_test::suite
{
    boost::asio::io_service ios_;

public:
    void run() override
    {
        std::string const s =
            "HTTP/1.1 200 OK\r\n"
            "Server: test\r\n"
            "Content-Length: 3\r\n"
            "\r\n"
            "xyz";
        test::string_stream ss(ios_, s);
        parser_v1<false, streambuf_body, headers> p;
        streambuf sb;
        parse(ss, sb, p);
        expect(to_string(p.get().body.data()) == "xyz");
        expect(boost::lexical_cast<std::string>(p.get()) == s);
    }
};

BEAST_DEFINE_TESTSUITE(streambuf_body,http,beast);

} // http
} // beast

max_issues_repo_name: somayeghahari/beast

max_forks_repo_name: somayeghahari/beast


text:
#pragma once
#include <fc/crypto/sha256.hpp>
#include <boost/filesystem/fstream.hpp>

namespace cyberway { namespace genesis {

namespace bfs = boost::filesystem;

class ofstream_sha256: public bfs::ofstream {
public:
    ofstream_sha256(): bfs::ofstream() {
    }
    ofstream_sha256(const bfs::path& p): bfs::ofstream(p, std::ios_base::binary) {
        bfs::ofstream::exceptions(std::ofstream::failbit | std::ofstream::badbit);
    }
    ~ofstream_sha256() {
    }

    template<typename T>
    void write(const T& x) {
        write((const char*)&x, sizeof(T));
    }
    void write(const char* p, uint32_t l) {
        _e.write(p, l);
        bfs::ofstream::write(p, l);
    }
    fc::sha256 hash() {
        return _e.result();
    }

private:
    fc::sha256::encoder _e;
};

}} // cyberway::genesis

max_stars_repo_name: GolosChain/eos

max_issues_repo_name: GolosChain/eos

max_forks_repo_name: GolosChain/eos


text:
// Copyright (C) 2020 T. Zachary Laine
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_TEXT_STRING_UTILITY_HPP
#define BOOST_TEXT_STRING_UTILITY_HPP

#include <boost/text/transcode_view.hpp>
#include <boost/text/detail/sentinel_tag.hpp>

namespace boost { namespace text { BOOST_TEXT_NAMESPACE_V1 {

#ifdef BOOST_TEXT_DOXYGEN

    /** Returns a UTF-8-encoded string constructed from [first, last).

        This function only participates in overload resolution if `CPIter`
        models the CPIter concept. */
    template<typename CPIter, typename Sentinel>
    std::string to_string(CPIter first, Sentinel last);

    /** Returns a UTF-8-encoded string constructed from range.

        This function only participates in overload resolution if `CPRange`
        models the CPRange concept. */
    template<typename CPRange>
    std::string to_string(CPRange const & range);

#else

    template<typename CPIter, typename Sentinel>
    auto to_string(CPIter first, Sentinel last)
        -> detail::cp_iter_ret_t<std::string, CPIter>
    {
        auto const r = boost::text::as_utf8(first, last);
        return std::string(r.begin(), r.end());
    }

    template<typename CPRange>
    auto to_string(CPRange const & range)
        -> detail::cp_rng_alg_ret_t<std::string, CPRange>
    {
        return v1::to_string(std::begin(range), std::end(range));
    }

#endif

}}}

#if defined(BOOST_TEXT_DOXYGEN) || BOOST_TEXT_USE_CONCEPTS

namespace boost { namespace text { BOOST_TEXT_NAMESPACE_V2 {

    template<code_point_iter I, std::sentinel_for<I> S>
    std::string to_string(I first, S last)
    {
        auto const r = boost::text::as_utf8(first, last);
        return std::string(r.begin(), r.end());
    }

    template<code_point_range R>
    std::string to_string(R const & r)
    {
        return boost::text::to_string(
            std::ranges::begin(r), std::ranges::end(r));
    }

}}}

#endif

#endif


text:
/**
   @author Shin'ichiro Nakaoka
*/

#include "KinematicsBar.h"
#include <cnoid/MainWindow>
#include <cnoid/Archive>
#include <cnoid/EigenUtil>
#include <cnoid/SpinBox>
#include <cnoid/Button>
#include <cnoid/Dialog>
#include <cnoid/LazyCaller>
#include <QBoxLayout>
#include <boost/bind.hpp>
#include "gettext.h"

using namespace std;
using namespace cnoid;

namespace {

const char* modeSymbol[] = { "AUTO", "FK", "IK" };

class KinematicsBarSetupDialog : public Dialog
{
public:
    DoubleSpinBox snapDistanceSpin;
    SpinBox snapAngleSpin;
    DoubleSpinBox penetrationBlockDepthSpin;
    CheckBox lazyCollisionDetectionModeCheck;
    PushButton okButton;

    KinematicsBarSetupDialog();
    void storeState(Archive& archive);
    void restoreState(const Archive& archive);
};

}

namespace cnoid {

class KinematicsBarImpl
{
public:
    ToolButton* autoModeRadio;
    ToolButton* fkModeRadio;
    ToolButton* ikModeRadio;

    ToolButton* draggerToggle;
    ToolButton* footSnapToggle;
    ToolButton* jointPositionLimitToggle;
    ToolButton* penetrationBlockToggle;

    ToolButton* collisionLinkHighlightToggle;
    int collisionDetectionPriority;
    Signal<void()> sigCollisionVisualizationChanged;

    KinematicsBarSetupDialog* setup;

    KinematicsBarImpl(KinematicsBar* self);
    void onCollisionVisualizationChanged();
    void onLazyCollisionDetectionModeToggled();
    bool storeState(Archive& archive);
    bool restoreState(const Archive& archive);
};

}

KinematicsBar* KinematicsBar::instance()
{
    static KinematicsBar* instance = new KinematicsBar();
    return instance;
}

KinematicsBar::KinematicsBar()
    : ToolBar(N_("KinematicsBar"))
{
    impl = new KinematicsBarImpl(this);
}

KinematicsBarImpl::KinematicsBarImpl(KinematicsBar* self)
{
    self->setVisibleByDefault(true);

    setup = new KinematicsBarSetupDialog();

    fkModeRadio = self->addRadioButton(QIcon(":/Body/icons/fk.png"), _("Forward kinematics mode"));
    autoModeRadio = self->addRadioButton(QIcon(":/Body/icons/fkik.png"), _("Preset kinematics mode"));
    ikModeRadio = self->addRadioButton(QIcon(":/Body/icons/ik.png"), _("Inverse kinematics mode"));
    autoModeRadio->setChecked(true);
    self->addSeparator(2);

    draggerToggle = self->addToggleButton(QIcon(":/Body/icons/rotation.png"), _("Enable link orientation editing"));
    draggerToggle->setChecked(true);

    /*
      footSnapToggle = self->addToggleButton(xpmfootsnapon, _("Snap foot to the floor"));
      footSnapToggle->setChecked(true);
    */
    /*
      jointPositionLimitToggle = self->addToggleButton(
      xpmlimitangle, _("Limit joint positions within the movable range specifications"));
      jointPositionLimitToggle->setChecked(true);
    */

    penetrationBlockToggle = self->addToggleButton(QIcon(":/Body/icons/block.png"), _("Penetration block mode"));
    penetrationBlockToggle->setChecked(false);

    collisionLinkHighlightToggle = self->addToggleButton(QIcon(":/Body/icons/collisionoutline.png"), _("Highlight colliding links"));
    collisionLinkHighlightToggle->setChecked(false);
    collisionLinkHighlightToggle->sigToggled().connect(
        boost::bind(&KinematicsBarImpl::onCollisionVisualizationChanged, this));

    self->addButton(QIcon(":/Base/icons/setup.png"))
        ->sigClicked().connect(
            boost::bind(&KinematicsBarSetupDialog::show, setup));

    setup->lazyCollisionDetectionModeCheck.sigToggled().connect(
        boost::bind(&KinematicsBarImpl::onLazyCollisionDetectionModeToggled, this));

    onLazyCollisionDetectionModeToggled();
}

KinematicsBar::~KinematicsBar()
{
    delete impl;
}

int KinematicsBar::mode() const
{
    if(impl->fkModeRadio->isChecked()){
        return FK_MODE;
    } else if(impl->ikModeRadio->isChecked()){
        return IK_MODE;
    }
    return AUTO_MODE;
}

bool KinematicsBar::isPositionDraggerEnabled() const
{
    return impl->draggerToggle->isChecked();
}

bool KinematicsBar::isFootSnapMode() const
{
    return impl->footSnapToggle->isChecked();
}

void KinematicsBar::getSnapThresholds(double& distance, double& angle) const
{
    distance = impl->setup->snapDistanceSpin.value();
    angle = radian(impl->setup->snapAngleSpin.value());
}

bool KinematicsBar::isJointPositionLimitMode() const
{
    return impl->jointPositionLimitToggle->isChecked();
}

bool KinematicsBar::isPenetrationBlockMode() const
{
    return impl->penetrationBlockToggle->isChecked();
}

double KinematicsBar::penetrationBlockDepth() const
{
    return impl->setup->penetrationBlockDepthSpin.value();
}

bool KinematicsBar::isCollisionLinkHighlihtMode() const
{
    return impl->collisionLinkHighlightToggle->isChecked();
}

int KinematicsBar::collisionDetectionPriority() const
{
    return impl->collisionDetectionPriority;
}

SignalProxy<void()> KinematicsBar::sigCollisionVisualizationChanged()
{
    return impl->sigCollisionVisualizationChanged;
}

void KinematicsBarImpl::onCollisionVisualizationChanged()
{
    sigCollisionVisualizationChanged();
}

void KinematicsBarImpl::onLazyCollisionDetectionModeToggled()
{
    if(setup->lazyCollisionDetectionModeCheck.isChecked()){
        collisionDetectionPriority = LazyCaller::PRIORITY_NORMAL;
    } else {
        collisionDetectionPriority = LazyCaller::PRIORITY_HIGH;
    }
}

bool KinematicsBar::storeState(Archive& archive)
{
    archive.write("mode", modeSymbol[mode()]);
    return impl->storeState(archive);
}

bool KinematicsBarImpl::storeState(Archive& archive)
{
    archive.write("enablePositionDragger", draggerToggle->isChecked());
    archive.write("penetrationBlock", penetrationBlockToggle->isChecked());
    //archive.write("footSnap", footSnapToggle->isChecked());
    archive.write("collisionLinkHighlight", collisionLinkHighlightToggle->isChecked());
    setup->storeState(archive);
    return true;
}

bool KinematicsBar::restoreState(const Archive& archive)
{
    return impl->restoreState(archive);
}

bool KinematicsBarImpl::restoreState(const Archive& archive)
{
    string storedModeSymbol = archive.get("mode", "AUTO");
    if(storedModeSymbol == "FK"){
        fkModeRadio->setChecked(true);
    } else if(storedModeSymbol == "IK"){
        ikModeRadio->setChecked(true);
    } else {
        autoModeRadio->setChecked(true);
        fkModeRadio->setChecked(false);
        ikModeRadio->setChecked(false);
    }

    draggerToggle->setChecked(archive.get("enablePositionDragger", draggerToggle->isChecked()));
    penetrationBlockToggle->setChecked(archive.get("penetrationBlock", penetrationBlockToggle->isChecked()));
    //footSnapToggle->setChecked(archive.get("footSnap", footSnapToggle->isChecked()));
    collisionLinkHighlightToggle->setChecked(archive.get("collisionLinkHighlight", collisionLinkHighlightToggle->isChecked()));
    setup->restoreState(archive);

    return true;
}

KinematicsBarSetupDialog::KinematicsBarSetupDialog()
{
    setWindowTitle(_("Kinematics Operation Setup"));

    QVBoxLayout* vbox = new QVBoxLayout();
    setLayout(vbox);

    QHBoxLayout* hbox = new QHBoxLayout();
    hbox->addWidget(new QLabel(_("Snap thresholds:")));
    hbox->addSpacing(10);

    hbox->addWidget(new QLabel(_("distance")));
    snapDistanceSpin.setAlignment(Qt::AlignCenter);
    snapDistanceSpin.setDecimals(3);
    snapDistanceSpin.setRange(0.0, 0.999);
    snapDistanceSpin.setSingleStep(0.001);
    snapDistanceSpin.setValue(0.025);
    hbox->addWidget(&snapDistanceSpin);
    hbox->addWidget(new QLabel(_("[m]")));

    hbox->addSpacing(5);
    hbox->addWidget(new QLabel(_("angle")));
    snapAngleSpin.setAlignment(Qt::AlignCenter);
    snapAngleSpin.setRange(0, 90);
    snapAngleSpin.setValue(30);
    hbox->addWidget(&snapAngleSpin);
    hbox->addWidget(new QLabel(_("[deg]")));
    vbox->addLayout(hbox);

    hbox = new QHBoxLayout();
    hbox->addWidget(new QLabel(_("Penetration block depth")));
    penetrationBlockDepthSpin.setAlignment(Qt::AlignCenter);
    penetrationBlockDepthSpin.setDecimals(4);
    penetrationBlockDepthSpin.setRange(0.0, 0.0099);
    penetrationBlockDepthSpin.setSingleStep(0.0001);
    penetrationBlockDepthSpin.setValue(0.0005);
    hbox->addWidget(&penetrationBlockDepthSpin);
    hbox->addWidget(new QLabel(_("[m]")));
    vbox->addLayout(hbox);

    hbox = new QHBoxLayout();
    lazyCollisionDetectionModeCheck.setText(_("Lazy collision detection mode"));
    lazyCollisionDetectionModeCheck.setChecked(true);
    hbox->addWidget(&lazyCollisionDetectionModeCheck);
    vbox->addLayout(hbox);

    hbox = new QHBoxLayout();
    okButton.setText(_("OK"));
    okButton.setDefault(true);
    hbox->addWidget(&okButton);
    vbox->addLayout(hbox);
}

void KinematicsBarSetupDialog::storeState(Archive& archive)
{
    archive.write("snapDistance", snapDistanceSpin.value());
    archive.write("penetrationBlockDepth", penetrationBlockDepthSpin.value());
    archive.write("lazyCollisionDetectionMode", lazyCollisionDetectionModeCheck.isChecked());
}

void KinematicsBarSetupDialog::restoreState(const Archive& archive)
{
    snapDistanceSpin.setValue(archive.get("snapDistance", snapDistanceSpin.value()));
    penetrationBlockDepthSpin.setValue(archive.get("penetrationBlockDepth", penetrationBlockDepthSpin.value()));
    lazyCollisionDetectionModeCheck.setChecked(archive.get("lazyCollisionDetectionMode", lazyCollisionDetectionModeCheck.isChecked()));
}

max_stars_repo_name: geenux/choreonoid

max_issues_repo_name: geenux/choreonoid

max_forks_repo_name: geenux/choreonoid


text:
/** $Id: Generator.cxx 137064 2015-08-31 18:24:47Z jvansanten $
 * @file
 * @author Jakob van Santen <vansanten@wisc.edu>
 *
 * $Revision: 137064 $
 * $Date: 2015-08-31 12:24:47 -0600 (Mon, 31 Aug 2015) $
 */

#include <MuonGun/Generator.h>
#include <MuonGun/SamplingSurface.h>

#include <icetray/I3Module.h>
#include <dataclasses/physics/I3MCTreeUtils.h>
#include <dataclasses/I3Double.h>
#include <phys-services/I3RandomService.h>
#include <boost/make_shared.hpp>
#include <boost/foreach.hpp>

namespace I3MuonGun {

GenerationProbability::~GenerationProbability() {}
Generator::~Generator() {}

template <typename Archive>
void
GenerationProbability::serialize(Archive &ar, unsigned version)
{
	if (version > 0)
		log_fatal_stream("Version "<<version<<" is from the future");

	ar & make_nvp("I3FrameObject", base_object<I3FrameObject>(*this));
	ar & make_nvp("NEvents", numEvents_);
}

template <typename Archive>
void
Generator::serialize(Archive &ar, unsigned version)
{
	if (version > 0)
		log_fatal_stream("Version "<<version<<" is from the future");

	ar & make_nvp("GenerationProbability", base_object<GenerationProbability>(*this));
}

double
GenerationProbability::GetLogGeneratedEvents(const I3Particle &axis, const BundleConfiguration &bundle) const
{
	return std::log(double(numEvents_)) + GetLogGenerationProbability(axis, bundle);
}

double
GenerationProbability::GetGeneratedEvents(const I3Particle &axis, const BundleConfiguration &bundle) const
{
	return numEvents_*std::exp(GetLogGenerationProbability(axis, bundle));
}

GenerationProbabilityCollection::GenerationProbabilityCollection(GenerationProbabilityPtr p1, GenerationProbabilityPtr p2)
{
	push_back(p1);
	push_back(p2);
}

void
GenerationProbabilityCollection::push_back(const GenerationProbabilityPtr &other)
{
	BOOST_FOREACH(value_type &p, *this)
		if (p && p->IsCompatible(other)) {
			p = p->Clone();
			p->SetTotalEvents(p->GetTotalEvents() + other->GetTotalEvents());
			return;
		}
	std::vector<GenerationProbabilityPtr>::push_back(other);
}

bool
GenerationProbabilityCollection::IsCompatible(GenerationProbabilityConstPtr) const
{
	log_fatal("I should never be called.");
}

double
GenerationProbabilityCollection::GetLogGenerationProbability(const I3Particle &axis,
    const BundleConfiguration &bundle) const
{
	// Collect log probabilities from members
	std::vector<double> values(this->size(), -std::numeric_limits<double>::infinity());
	BOOST_FOREACH(const value_type &p, *this)
		if (p)
			values.push_back(p->GetLogGeneratedEvents(axis, bundle));

	// Calculate log(sum(exp)) in a numerically stable way
	double bias = *std::max_element(values.begin(), values.end());
	double prob = 0.;
	BOOST_FOREACH(double v, values)
		prob += std::exp(v-bias);

	return bias + std::log(prob);
}

SamplingSurfaceConstPtr
GenerationProbabilityCollection::GetInjectionSurface() const
{
	SamplingSurfaceConstPtr surface;
	BOOST_FOREACH(const value_type &p, *this) {
		if (p) {
			if (!surface)
				surface = p->GetInjectionSurface();
			else if (!(*surface == *(p->GetInjectionSurface())))
				log_fatal("All injection surfaces in a collection must be identical!");
		}
	}

	return surface;
}

GenerationProbabilityPtr
GenerationProbabilityCollection::Clone() const
{
	return boost::make_shared<GenerationProbabilityCollection>(*this);
}

template <typename Archive>
void
GenerationProbabilityCollection::serialize(Archive &ar, unsigned version)
{
	if (version > 0)
		log_fatal_stream("Version "<<version<<" is from the future");

	ar & make_nvp("GenerationProbability", base_object<GenerationProbability>(*this));
	ar & make_nvp("Vector", base_object<std::vector<GenerationProbabilityPtr> >(*this));
}

GenerationProbabilityPtr
operator*=(GenerationProbabilityPtr p, double n)
{
	p->SetTotalEvents(p->GetTotalEvents()*n);

	return p;
}

GenerationProbabilityPtr
operator*(GenerationProbabilityPtr p, double n)
{
	GenerationProbabilityPtr pn = p->Clone();
	pn *= n;

	return pn;
}

GenerationProbabilityPtr
operator*(double n, GenerationProbabilityPtr p)
{
	return p*n;
}

GenerationProbabilityPtr
operator+(GenerationProbabilityPtr p1, GenerationProbabilityPtr p2)
{

	// If one or both is a collection, merge
	boost::shared_ptr<GenerationProbabilityCollection> c1 =
	    boost::dynamic_pointer_cast<GenerationProbabilityCollection>(p1);
	boost::shared_ptr<GenerationProbabilityCollection> c2 =
	    boost::dynamic_pointer_cast<GenerationProbabilityCollection>(p2);
	if (c1 && c2) {
		c1 = boost::make_shared<GenerationProbabilityCollection>(*c1);
		BOOST_FOREACH(const GenerationProbabilityPtr &other, *c2)
			c1->push_back(other);
		return c1;
	} else if (c1) {
		c1 = boost::make_shared<GenerationProbabilityCollection>(*c1);
		c1->push_back(p2);
		return c1;
	} else if (c2) {
		c2 = boost::make_shared<GenerationProbabilityCollection>(*c2);
		c2->push_back(c1);
		return c2;
	} else if (p1->IsCompatible(p2)) {
		// If the two elements are identical, just scale up.
		GenerationProbabilityPtr p = p1->Clone();
		p->SetTotalEvents(p1->GetTotalEvents() + p2->GetTotalEvents());
		return p;
	} else {
		// If all else fails, start a new collection
		return boost::make_shared<GenerationProbabilityCollection>(p1, p2);
	}
}

I3Particle
Generator::CreateParallelTrack(double radius, double azimuth,
    const I3Surfaces::Surface &surface, const I3Particle &axis)
{
	I3Particle track;
	track.SetLocationType(I3Particle::InIce);
	track.SetType(I3Particle::MuMinus);
	track.SetDir(axis.GetDir());
	track.SetSpeed(I3Constants::c);
	track.SetPos(axis.GetPos());
	track.SetTime(axis.GetTime());

	if (radius > 0) {
		// Shift the track parallel to the axis
		I3Position offset(radius, 0, 0);
		offset.RotateY(axis.GetDir().GetZenith());
		offset.RotateZ(azimuth);
		offset += axis.GetPos();
		// Find the distance from the offset position to the sampling
		// surface, and shift so that all tracks have their origin
		// on the surface, but remain in a plane
		double shift =
		    surface.GetIntersection(offset, track.GetDir()).first
		    -surface.GetIntersection(axis.GetPos(), axis.GetDir()).first;
		if (std::isfinite(shift)) {
			track.SetTime(axis.GetTime() + shift/track.GetSpeed());
			track.SetPos(offset + shift*track.GetDir());
		} else {
			track.SetPos(offset);
		}
	}

	return track;
}

/**
 * @brief Interface between Generator and IceTray
 */
class GeneratorModule : public I3Module {
public:
	GeneratorModule(const I3Context &ctx) : I3Module(ctx), maxEvents_(0), numEvents_(0)
	{
		AddOutBox("OutBox");
		AddParameter("Generator", "Muon bundle generator", generator_);

		mctreeName_ = "I3MCTree";
	}

	void Configure()
	{
		GetParameter("Generator", generator_);

		rng_ = context_.Get<I3RandomServicePtr>();
		if (!rng_)
			log_fatal("No RandomService configured!");
		maxEvents_ = size_t(std::floor(generator_->GetTotalEvents()));

		firstFrame_ = true;
	}

	void DAQ(I3FramePtr frame)
	{
		if (firstFrame_) {
			firstFrame_ = false;
			I3FramePtr sframe = boost::make_shared<I3Frame>('S');
			sframe->Put(GetName(), generator_);
			PushFrame(sframe);
		}

		I3MCTreePtr mctree = boost::make_shared<I3MCTree>();
		BundleConfiguration bundlespec;

		generator_->Generate(*rng_, *mctree, bundlespec);

		frame->Put(mctreeName_, mctree);

		PushFrame(frame);
		if (++numEvents_ >= maxEvents_)
			RequestSuspension();
	}

	void Finish();
private:
	GeneratorPtr generator_;
	I3RandomServicePtr rng_;
	size_t maxEvents_, numEvents_;
	std::string mctreeName_;
	bool firstFrame_;
};

// Out-of-line virtual method definition to force the vtable into this translation unit
void GeneratorModule::Finish() {}

}

I3_SERIALIZABLE(I3MuonGun::GenerationProbability);
I3_SERIALIZABLE(I3MuonGun::GenerationProbabilityCollection);
I3_SERIALIZABLE(I3MuonGun::Generator);
I3_MODULE(I3MuonGun::GeneratorModule);

ext: cxx


text: #include <boost/multiprecision/debug_adaptor.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//  Copyright (c) 2007-2012 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <hpx/hpx_fwd.hpp>
#include <hpx/runtime/components/server/memory.hpp>
#include <hpx/lcos/base_lco_with_value.hpp>
#include <hpx/runtime/applier/apply.hpp>
#include <hpx/runtime/actions/continuation.hpp>

#include <hpx/util/portable_binary_iarchive.hpp>
#include <hpx/util/portable_binary_oarchive.hpp>

#include <boost/assert.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/export.hpp>

///////////////////////////////////////////////////////////////////////////////
HPX_DEFINE_GET_COMPONENT_TYPE_STATIC(hpx::components::server::memory,
    hpx::components::component_memory)

///////////////////////////////////////////////////////////////////////////////
// Serialization support for the runtime_support actions
HPX_REGISTER_ACTION(hpx::components::server::memory::store8_action, store8_action)
HPX_REGISTER_ACTION(hpx::components::server::memory::store16_action, store16_action)
HPX_REGISTER_ACTION(hpx::components::server::memory::store32_action, store32_action)
HPX_REGISTER_ACTION(hpx::components::server::memory::store64_action, store64_action)

HPX_REGISTER_ACTION(hpx::components::server::memory::load8_action, load8_action)
HPX_REGISTER_ACTION(hpx::components::server::memory::load16_action, load16_action)
HPX_REGISTER_ACTION(hpx::components::server::memory::load32_action, load32_action)
HPX_REGISTER_ACTION(hpx::components::server::memory::load64_action, load64_action)

max_stars_repo_name: andreasbuhr/hpx

max_issues_repo_name: andreasbuhr/hpx

max_forks_repo_name: andreasbuhr/hpx


text: #include <boost/thread/v2/thread.hpp>


text:
/*
 * Copyright 2013 Stanford University.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the
 *   distribution.
 *
 * - Neither the name of the copyright holders nor the names of
 *   its contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Author: Hang Qu <quhang@stanford.edu>
 */

#include <string>
#include <boost/functional/hash.hpp>

#include "applications/physbam/water//app_utils.h"
#include "applications/physbam/water//physbam_include.h"
#include "applications/physbam/water//physbam_tools.h"
#include "src/data/app_data/app_var.h"
#include "src/shared/dbg.h"
#include "src/shared/geometric_region.h"
#include "src/worker/data.h"

#include "applications/physbam/water//app_data_compressed_scalar_array.h"

namespace application {

template<class T> AppDataCompressedScalarArray<T>::
AppDataCompressedScalarArray() {
  data_ = NULL;
  index_data_ = NULL;
}

template<class T> AppDataCompressedScalarArray<T>::
AppDataCompressedScalarArray(const nimbus::GeometricRegion &global_reg,
                           const int ghost_width,
                           bool make_proto,
                           const std::string& name)
    : global_region_(global_reg),
      ghost_width_(ghost_width) {
  set_name(name);
  data_ = new DataType();
  index_data_ = NULL;
  data_length_ = -1;
  if (make_proto)
    MakePrototype();
}

template<class T> AppDataCompressedScalarArray<T>::
AppDataCompressedScalarArray(const nimbus::GeometricRegion &global_reg,
                           const nimbus::GeometricRegion &ob_reg,
                           const int ghost_width)
    : AppVar(ob_reg),
      global_region_(global_reg),
      local_region_(ob_reg.NewEnlarged(-ghost_width)),
      ghost_width_(ghost_width) {
  data_ = new DataType();
  index_data_ = NULL;
  data_length_ = -1;
  shift_.x = local_region_.x() - global_reg.x();
  shift_.y = local_region_.y() - global_reg.y();
  shift_.z = local_region_.z() - global_reg.z();
}

template<class T> AppDataCompressedScalarArray<T>::
~AppDataCompressedScalarArray() {
  Destroy();
}

template<class T> void AppDataCompressedScalarArray<T>::
Destroy() {
  if (data_) {
    delete data_;
    data_ = NULL;
  }
  if (index_data_) {
    delete index_data_;
    index_data_ = NULL;
  }
}

template<class T> nimbus::AppVar *AppDataCompressedScalarArray<T>::
CreateNew(const nimbus::GeometricRegion &ob_reg) const {
  nimbus::AppVar* temp = new AppDataCompressedScalarArray<T>(global_region_,
                                                             ob_reg,
                                                             ghost_width_);
  temp->set_name(name());
  return temp;
}

template<class T> void AppDataCompressedScalarArray<T>::
ReadAppData(const nimbus::DataArray &read_set,
            const nimbus::GeometricRegion &read_reg) {
  nimbus::GeometricRegion ob_reg = object_region();
  nimbus::GeometricRegion final_read_reg =
      nimbus::GeometricRegion::GetIntersection(read_reg, ob_reg);
  assert(final_read_reg.dx() > 0 && final_read_reg.dy() > 0 && final_read_reg.dz() > 0);
  // Loop through each element in read set, and fetch it to the app_data object.
  assert(index_data_ != NULL);
  Translator::template
      ReadCompressedScalarArray<T>(final_read_reg, shift_, read_set, data_,
                                   data_length_, *index_data_);
}

template<class T> void AppDataCompressedScalarArray<T>::
WriteAppData(const nimbus::DataArray &write_set,
               const nimbus::GeometricRegion &write_reg) const {
  if (write_reg.dx() <= 0 || write_reg.dy() <= 0 || write_reg.dz() <= 0)
    return;
  nimbus::GeometricRegion ob_reg = object_region();
  nimbus::GeometricRegion final_write_reg =
      nimbus::GeometricRegion::GetIntersection(write_reg, ob_reg);
  assert(final_write_reg.dx() > 0 && final_write_reg.dy() > 0 && final_write_reg.dz() > 0);
  // Loop through each element in write_set, look up the region using index, and
  // then write.
  assert(index_data_ != NULL);
  Translator::template
      WriteCompressedScalarArray<T>(write_reg, shift_, write_set, *data_,
                                    data_length_, *index_data_);
}

template<class T> void AppDataCompressedScalarArray<T>::
set_index_data(IndexType* d) {
  // delete index_data_;
  // index_data_ = new IndexType(*d);
  // return;
  if (d->hash_code == 0) {
    dbg(APP_LOG, "Recalculate hash code for meta data.\n");
    d->hash_code = CalculateHashCode(*d);
  }
  assert(index_data_ == NULL || index_data_->hash_code != 0);
  if (index_data_ == NULL || index_data_->hash_code != d->hash_code) {
    if (index_data_) {
      delete index_data_;
    }
    index_data_ = new IndexType(*d);
    index_data_->hash_code = 0;
    dbg(APP_LOG, "Replace meta data, hash=%d replaced by hash=%d.\n",
        index_data_->hash_code, d->hash_code);
    index_data_->hash_code = d->hash_code;
  }
}

template<class T> long AppDataCompressedScalarArray<T>::
CalculateHashCode(IndexType& index) {
  size_t seed = 99;
  boost::hash_range(seed,
      index.array.base_pointer,
      index.array.base_pointer + index.array.m);
  return (long) seed;
}

template class AppDataCompressedScalarArray<float>;

} // namespace application

max_stars_repo_name: schinmayee/nimbus

max_issues_repo_name: schinmayee/nimbus

max_forks_repo_name: schinmayee/nimbus


text:
/*
	Copyright (C) 2003-2013 by David White <davewx7@gmail.com>

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

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

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <map>

#include <boost/tuple/tuple.hpp>
#include <boost/filesystem.hpp>

#include "graphics.hpp"
#include "asserts.hpp"
#include "color_utils.hpp"
#include "font.hpp"
#include "foreach.hpp"
#include "formatter.hpp"
#include "module.hpp"
#include "preferences.hpp"
#include "string_utils.hpp"
#include "surface.hpp"

/*  This manages the TTF loading library, and allows you to use fonts.
	The only thing one will normally need to use is render_text(), and
	possibly char_width(), char_height() if you need to know the size
	of the resulting text. */

namespace font {
#if TARGET_IPHONE_SIMULATOR || TARGET_OS_HARMATTAN || TARGET_OS_IPHONE
class TTF_Font;
#endif

namespace {
typedef std::map<std::pair<std::string, int>, TTF_Font*> font_map;
font_map font_table;

std::map<std::string,std::string>& get_font_list()
{
	static std::map<std::string,std::string> res;
	return res;
}

const std::string& get_font_path(const std::string& name)
{
	std::map<std::string,std::string>& res = get_font_list();
	if(res.empty()) {
		module::get_unique_filenames_under_dir("data/fonts/", &res);
	}
	std::map<std::string, std::string>::const_iterator itor = module::find(res, name);
	if(itor == res.end()) {
		ASSERT_LOG(false, "FONT FILE NOT FOUND: " << name);
	}
	return itor->second;
}

std::string make_font_filename(const std::string& fontname)
{
	auto itor = std::find(fontname.begin(), fontname.end(), '.');
	if(itor == fontname.end()) {
		return fontname + ".ttf";
	} else {
		return fontname;
	}
}

TTF_Font* get_font(int size, const std::string& font_name="")
{
#if !TARGET_IPHONE_SIMULATOR && !TARGET_OS_HARMATTAN && !TARGET_OS_IPHONE
	std::string fontn = get_font_path(make_font_filename(font_name.empty() ? module::get_default_font() == "bitmap" ? "FreeMono" : module::get_default_font()  : font_name));
	TTF_Font* font = NULL;
	font_map::const_iterator it = font_table.find(std::pair<std::string,int>(fontn,size));
	if(it == font_table.end()) {
		font = TTF_OpenFont(fontn.c_str(), size);
		if(font == NULL) {
			std::ostringstream s;

			s << "Failed to open font: " << fontn;
			ASSERT_LOG(false, s.str());
			exit(0);
		}
		font_table[std::pair<std::string,int>(fontn,size)] = font;
	} else {
		font = it->second;
	}

	return font;
#else
	return NULL;
#endif
}

struct CacheKey {
	std::string text;
	graphics::color color;
	int font_size;
	std::string font_name;

	bool operator<(const CacheKey& k) const {
		return text < k.text || text == k.text && color < k.color
			|| text == k.text && color == k.color && font_size < k.font_size
			|| text == k.text && color == k.color && font_size == k.font_size && font_name < k.font_name;
	}
};

typedef std::map<CacheKey, graphics::texture> RenderCache;

int g_render_cache_size = 0;

RenderCache& cache() {
	static RenderCache instance;
	return instance;
}

bool fonts_initialized = false;

}

bool is_init() {
	return fonts_initialized;
}

manager::manager()
{
#if !TARGET_IPHONE_SIMULATOR && !TARGET_OS_HARMATTAN && !TARGET_OS_IPHONE
	const int res = TTF_Init();
	if(res == -1) {
		std::cerr << "Could not initialize ttf\n";
		exit(0);
	} else {
		fonts_initialized = true;
		std::cerr << "initialized ttf\n";
	}
#endif
}

manager::~manager()
{
#if !TARGET_IPHONE_SIMULATOR && !TARGET_OS_HARMATTAN && !TARGET_OS_IPHONE
	font_map::iterator it = font_table.begin();
	while(it != font_table.end()) {
		TTF_CloseFont(it->second);
		font_table.erase(it++);
	}

	TTF_Quit();
#endif
}

graphics::texture render_text_uncached(const std::string& text,
                                       const SDL_Color& color, int size, const std::string& font_name)
{
#if !TARGET_IPHONE_SIMULATOR && !TARGET_OS_HARMATTAN && !TARGET_OS_IPHONE
	TTF_Font* font = get_font(size, font_name);

	graphics::surface s;
	if(std::find(text.begin(), text.end(), '\n') == text.end()) {
		s = graphics::surface(TTF_RenderUTF8_Blended(font, text.c_str(), color));
	} else {
		std::vector<graphics::surface> parts;
		std::vector<std::string> lines = util::split(text, '\n');
		int height = 0, width = 0;
		foreach(const std::string& line, lines) {
			parts.push_back(graphics::surface(TTF_RenderUTF8_Blended(font, line.c_str(), color)));
			if(parts.back().get() == NULL) {
				std::cerr << "FAILED TO RENDER STRING: '" << line << "'\n";
				throw error();
			}

			if(parts.back()->w > width) {
				width = parts.back()->w;
			}

			height += parts.back()->h;
		}

		const SDL_PixelFormat* f = parts.front()->format;
		s = graphics::surface(SDL_CreateRGBSurface(0, width, height, f->BitsPerPixel, f->Rmask, f->Gmask, f->Bmask, f->Amask));
		int ypos = 0;
		foreach(graphics::surface part, parts) {
			SDL_Rect rect = {0, ypos, part->w, part->h};
			SDL_SetSurfaceBlendMode(part.get(), SDL_BLENDMODE_NONE);
			SDL_BlitSurface(part.get(), NULL, s.get(), &rect);
			ypos += part->h;
		}
	}
#else
	graphics::surface s;
#endif
	return graphics::texture::get_no_cache(s);
}

graphics::texture render_text(const std::string& text,
                              const SDL_Color& color, int size, const std::string& font_name)
{
	CacheKey key = {text, graphics::color(color.r, color.g, color.b), size, font_name};
	RenderCache::const_iterator cache_itor = cache().find(key);
	if(cache_itor != cache().end()) {
		return cache_itor->second;
	}

	graphics::texture res = render_text_uncached(text, color, size, font_name);

	if(res.width()*res.height() <= 256*256) {
		if(cache().size() > 16) {
			cache().clear();
			g_render_cache_size = 0;
		}
		cache()[key] = res;
		g_render_cache_size += res.width()*res.height()*4;
	}
	return res;
}

int char_width(int size, const std::string& fn)
{
	static std::map<std::string, std::map<int, int> > size_cache;
	int& width = size_cache[fn][size];
	if(width) {
		return width;
	}
	SDL_Color color = {0, 0, 0, 0};
	graphics::texture t(render_text("ABCDEFABCDEF", color, size, fn));
	width = t.width()/12;
	return width;
}

int char_height(int size, const std::string& fn)
{
	static std::map<std::string, std::map<int, int> > size_cache;
	int& height = size_cache[fn][size];
	if(height) {
		return height;
	}
	SDL_Color color = {0, 0, 0, 0};
	graphics::texture t(render_text("A", color, size, fn));
	height = t.height();
	return height;
}

void reload_font_paths()
{
	get_font_list().clear();
}

std::vector<std::string> get_available_fonts()
{
	using namespace boost::filesystem;
	auto& res = get_font_list();
	if(res.empty()) {
		module::get_unique_filenames_under_dir("data/fonts/", &res);
	}
	std::vector<std::string> v;
	for(auto it : res) {
		path p(it.second);
		if(p.extension() == ".ttf") {
			v.push_back(p.stem().generic_string());
		}
	}
	return v;
}

std::string get_default_monospace_font()
{
	return "FreeMono";
}

}

max_stars_repo_name: sweetkristas/anura

max_issues_repo_name: sweetkristas/anura

max_forks_repo_name: sweetkristas/anura


text:
// Copyright (c) 2012 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <hpx/hpx_fwd.hpp>

#if defined(BOOST_WINDOWS)

#include <hpx/exception.hpp>
#include <boost/format.hpp>
#include <psapi.h>

namespace hpx { namespace performance_counters { namespace memory
{
    ///////////////////////////////////////////////////////////////////////////
    // returns virtual memory value
    boost::uint64_t read_psm_virtual(bool)
    {
        PROCESS_MEMORY_COUNTERS_EX pmc;
        std::memset(&pmc, '\0', sizeof(PROCESS_MEMORY_COUNTERS_EX));
        pmc.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);

        if (!GetProcessMemoryInfo(GetCurrentProcess(),
                reinterpret_cast<PPROCESS_MEMORY_COUNTERS>(&pmc),
                sizeof(PROCESS_MEMORY_COUNTERS_EX)))
        {
            HRESULT hr = GetLastError();
            LPVOID buffer = 0;
            if (!FormatMessage(
                FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS,
                NULL, hr,
                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                (LPTSTR) &buffer, 0, NULL))
            {
                HPX_THROW_EXCEPTION(kernel_error,
                    "hpx::performance_counters::memory::read_psm_virtual",
                    boost::str(boost::format("format message failed with %x (while "
                        "retrieving message for %x)") % GetLastError() % hr));
                return boost::uint64_t(-1);
            }

            std::string msg(static_cast<char*>(buffer));
            LocalFree(buffer);
            HPX_THROW_EXCEPTION(kernel_error,
                "hpx::performance_counters::memory::read_psm_virtual", msg);
            return boost::uint64_t(-1);
        }

        return pmc.WorkingSetSize;
    }

    ///////////////////////////////////////////////////////////////////////////
    // returns resident memory value
    boost::uint64_t read_psm_resident(bool)
    {
        PROCESS_MEMORY_COUNTERS_EX pmc;
        std::memset(&pmc, '\0', sizeof(PROCESS_MEMORY_COUNTERS_EX));
        pmc.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);

        if (!GetProcessMemoryInfo(GetCurrentProcess(),
                reinterpret_cast<PPROCESS_MEMORY_COUNTERS>(&pmc),
                sizeof(PROCESS_MEMORY_COUNTERS_EX)))
        {
            HRESULT hr = GetLastError();
            LPVOID buffer = 0;
            if (!FormatMessage(
                FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS,
                NULL, hr,
                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                (LPTSTR) &buffer, 0, NULL))
            {
                HPX_THROW_EXCEPTION(kernel_error,
                    "hpx::performance_counters::memory::read_psm_resident",
                    boost::str(boost::format("format message failed with %x (while "
                        "retrieving message for %x)") % GetLastError() % hr));
                return boost::uint64_t(-1);
            }

            std::string msg(static_cast<char*>(buffer));
            LocalFree(buffer);
            HPX_THROW_EXCEPTION(kernel_error,
                "hpx::performance_counters::memory::read_psm_resident", msg);
            return boost::uint64_t(-1);
        }

        return pmc.PrivateUsage;
    }
}}}

#endif

max_stars_repo_name: kempj/hpx

max_issues_repo_name: kempj/hpx

max_forks_repo_name: kempj/hpx


text:
#include <boost/test/unit_test.hpp>
#include <string>
#include <memory>

#include "aisql_connection.hpp"
#include "aisql_conns_manage.hpp"

using namespace aisqlpp::db_config;

BOOST_AUTO_TEST_SUITE(request_free_test)

BOOST_AUTO_TEST_CASE(simple_request_free)
{
    aisqlpp::conns_manage mng(5, host, user, passwd, db);

    BOOST_CHECK_EQUAL(5, mng.free_count());

    aisqlpp::connection_ptr ptr1 = mng.request_conn();
    aisqlpp::connection_ptr ptr2 = mng.request_conn();

    BOOST_CHECK_EQUAL(3, mng.free_count());

    mng.free_conn(ptr1);
    BOOST_CHECK_EQUAL(4, mng.free_count());
    mng.free_conn(ptr2);
    BOOST_CHECK_EQUAL(5, mng.free_count());

    ptr2 = mng.try_request_conn(1000);
    assert(ptr2 != nullptr);
    BOOST_CHECK_EQUAL(4, mng.free_count());

    mng.conn_check();
    mng.free_conn(ptr2);

    cout << "simple_request_free FINISHED!" << endl;
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: taozhijiang/aisqlpp

max_issues_repo_name: taozhijiang/aisqlpp

max_forks_repo_name: taozhijiang/aisqlpp


text:
/* Copyright Institue of Sound and Vibration Research - All rights reserved. */

#include <librrl/audio_signal_flow.hpp>
#include <librrl/integrity_checking.hpp>

#include <libvisr/atomic_component.hpp>
#include <libvisr/parameter_input.hpp>
#include <libvisr/parameter_output.hpp>
#include <libvisr/composite_component.hpp>
#include <libvisr/signal_flow_context.hpp>

#include <libpml/double_buffering_protocol.hpp>
#include <libpml/matrix_parameter.hpp>
#include <libpml/matrix_parameter_config.hpp>
#include <libpml/initialise_parameter_library.hpp>

#include <boost/test/unit_test.hpp>

#include <ciso646>
#include <cstddef>
#include <iostream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>

namespace visr
{
namespace rrl
{
namespace test
{

namespace // unnamed
{

std::size_t const numRows =3;
std::size_t const numCols = 5;

class Sender: public AtomicComponent
{
public:
  Sender( SignalFlowContext & context, char const * componentName, CompositeComponent * parent )
   : AtomicComponent( context, componentName, parent )
   , mParamOutput( "paramOut", *this, pml::MatrixParameterConfig(numRows, numCols) )
  {
  }
  void process() override {}
private:
  ParameterOutput<pml::DoubleBufferingProtocol, pml::MatrixParameter<float> > mParamOutput;
};

class Receiver: public AtomicComponent
{
public:
  Receiver( SignalFlowContext & context, char const * componentName, CompositeComponent * parent )
    : AtomicComponent( context, componentName, parent )
    , mParamInput( "paramIn", *this, pml::MatrixParameterConfig( numRows, numCols ) )
  {
  }
  void process() override
  {
    pml::MatrixParameter<float> const & mtx = mParamInput.data();
    if( (mtx.numberOfRows() != numRows) or (mtx.numberOfColumns() != numCols) )
    {
      status( StatusMessage::Warning, "ParameterConnection::Receiver: Matrix dimension mismatch. Expected (", numRows, ",", numCols,
        ") received (", mtx.numberOfRows(), ",", mtx.numberOfColumns(), ")." );
    }

  }
private:
  ParameterInput<pml::DoubleBufferingProtocol, pml::MatrixParameter<float> > mParamInput;
};

class MyComposite: public CompositeComponent
{
public:
  MyComposite( SignalFlowContext & context, char const * componentName, CompositeComponent * parent )
    : CompositeComponent( context, componentName, parent )
    , mSender( context, "Sender", this )
    , mReceiver( context, "Receiver", this)
  {
    parameterConnection( mSender.parameterPort("paramOut"), mReceiver.parameterPort("paramIn") );
  }
private:
  Sender mSender;
  Receiver mReceiver;
};

} // namespace unnamed

BOOST_AUTO_TEST_CASE( CheckParamConnection )
{
  pml::initialiseParameterLibrary();

  const std::size_t blockSize{64};
  std::size_t const numBlocks{16};

  SignalFlowContext context( blockSize, 48000 );

  MyComposite myComp( context, "topLevel", nullptr );

  std::stringstream checkMsg;
  bool const res = rrl::checkConnectionIntegrity( myComp, true, checkMsg );
  BOOST_CHECK_MESSAGE( res, checkMsg.str().c_str() );

  rrl::AudioSignalFlow flow( myComp );

  float ** inputPtr =  nullptr;
  float ** outputPtr = nullptr;

  for( std::size_t blockIdx(0); blockIdx < numBlocks; ++blockIdx )
  {
    flow.process( inputPtr, outputPtr );
  }

}

} // namespace test
} // namespace rrl
} // namespace visr


text:
#include "categorySearchHandler.h"

#include <boost/algorithm/string/trim.hpp>
#include <Poco/JSON/Object.h>

#include <Poco/Net/HTMLForm.h>
#include <Poco/URI.h>

namespace WikiMainPath {

	CategorySearchHandler::CategorySearchHandler(const WikiDataCache& wiki_data_cache, const InvertedIndex& inverted_index)
		:_wiki_data_cache(wiki_data_cache),
		_inverted_index(inverted_index)
	{}

	void CategorySearchHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
	{
		using namespace Poco::JSON;

		response.setChunkedTransferEncoding(true);
		response.setContentType("text/json");
		response.set("Access-Control-Allow-Origin", "*");

		// get parameters
		Poco::URI uri(request.getURI());
		auto parameters = uri.getQueryParameters();

		if(parameters.size() == 0 || parameters[0].first != "query-str")
		{
			response.setStatus("400"); // = Bad Request

			Object root;
			root.set("error", "GET-Parameter query-str not specified or too many parameters.");

			root.stringify(response.send(), 4);

			return;
		}

		std::string query_str = parameters[0].second;
		boost::trim(query_str);

		std::size_t n_limit = 0;
		if(parameters.size() == 2)
		{
			std::string limit_str = parameters[1].second;
			boost::trim(limit_str);

			n_limit = std::stoul(limit_str);
		}

		DocumentSet results;
		if(query_str != "")
			 results = query(_inverted_index, query_str);

		std::vector<std::size_t> results_ordered(results.begin(), results.end());
		std::sort(results_ordered.begin(), results_ordered.end(), [this](const std::size_t i1, const std::size_t i2) {
			return _wiki_data_cache.category_titles()[i1].size() < _wiki_data_cache.category_titles()[i2].size();
		});

		Object root;
		Array matchingCategoriesArray;

		std::size_t count = 0;
		for (auto res : results_ordered) {
			Object el;
			el.set("title", _wiki_data_cache.category_titles()[res]);
			el.set("id", res);
			el.set("n_articles", _wiki_data_cache.category_has_article()[res].size());
			el.set("n_subcategories", boost::out_degree(res, _wiki_data_cache.category_hirachy_graph()));

			matchingCategoriesArray.add(el);
			count++;

			if(count > n_limit && n_limit != 0)
				break;
		}

		root.set("matching-categories", matchingCategoriesArray);

		root.stringify(response.send(), 4);
	}

}

max_stars_repo_name: bencabrera/wikiMainPath

max_issues_repo_name: bencabrera/wikiMainPath

max_forks_repo_name: bencabrera/wikiMainPath


text:
// Copyright 2013-2019 Antony Polukhin

// Distributed under the Boost Software License, Version 1.0.
// (See the accompanying file LICENSE_1_0.txt
// or a copy at <http://www.boost.org/LICENSE_1_0.txt>.)

//[type_index_names_example
/*`
    The following example shows how short (mangled) and human readable type names could be obtained from a type.
    Works with and without RTTI.
*/

#include <boost/type_index.hpp>
#include <iostream>

template <class T>
void foo(T) {
    std::cout << "\n Short name: " << boost::typeindex::type_id<T>().raw_name();
    std::cout << "\n Readable name: " << boost::typeindex::type_id<T>().pretty_name();
}

struct user_defined_type{};

namespace ns1 { namespace ns2 {
    struct user_defined_type{};
}} // namespace ns1::ns2

namespace {
    struct in_anon_type{};
} // anonymous namespace

int main() {
    // Call to
    foo(1);
    // will output something like this:
    //
    // (RTTI on)                                            (RTTI off)
    // Short name: i                                        Short name: int]
    // Readable name: int                                   Readable name: int

    user_defined_type t;
    foo(t);
    // Will output:
    //
    // (RTTI on)                                            (RTTI off)
    // Short name: 17user_defined_type                      user_defined_type]
    // Readable name: user_defined_type                     user_defined_type

    ns1::ns2::user_defined_type t_in_ns;
    foo(t_in_ns);
    // Will output:
    //
    // (RTTI on)                                            (RTTI off)
    // Short name: N3ns13ns217user_defined_typeE            ns1::ns2::user_defined_type]
    // Readable name: ns1::ns2::user_defined_type           ns1::ns2::user_defined_type

    in_anon_type anon_t;
    foo(anon_t);
    // Will output:
    //
    // (RTTI on)                                            (RTTI off)
    // Short name: N12_GLOBAL__N_112in_anon_typeE           {anonymous}::in_anon_type]
    // Readable name: (anonymous namespace)::in_anon_type   {anonymous}::in_anon_type
}

/*`
    Short names are very compiler dependant: some compiler will output `.H`, others `i`.

    Readable names may also differ between compilers: `struct user_defined_type`, `user_defined_type`.

    [warning With RTTI off different classes with same names in anonymous namespace may collapse. See 'RTTI emulation limitations'. ]
*/

//] [/type_index_names_example]

max_stars_repo_name: cpp-pm/boost

max_issues_repo_name: cpp-pm/boost

max_forks_repo_name: cpp-pm/boost


text:
//=======================================================================
// Copyright Baptiste Wicht 2011-2016.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef MTAC_VARIABLE_REPLACE_H
#define MTAC_VARIABLE_REPLACE_H

#include <unordered_map>
#include <memory>

#include <boost/optional.hpp>

#include "mtac/forward.hpp"
#include "mtac/Argument.hpp"

namespace eddic {

class Variable;

namespace mtac {

typedef std::unordered_map<std::shared_ptr<Variable>, mtac::Argument> VariableClones;

struct VariableReplace {
    VariableClones& clones;

    VariableReplace(VariableClones& clones) : clones(clones) {}

    void update_usage(mtac::Argument& value);
    void update_usage_optional(boost::optional<mtac::Argument>& opt);

    void replace(mtac::Quadruple& quadruple);
};

} //end of mtac

} //end of eddic

#endif

max_stars_repo_name: wichtounet/eddic

max_issues_repo_name: wichtounet/eddic

max_forks_repo_name: wichtounet/eddic


text:
#define BOOST_TEST_MODULE ValleyCounterTest

#include "ValleyCounter.hpp"
#include <vector>

#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include <boost/algorithm/string.hpp>

BOOST_AUTO_TEST_SUITE(ValleyCounterSuite)

using namespace com::github::nimelo;
using namespace std;

BOOST_AUTO_TEST_CASE(TestScenario_1)
{
    // Arrange
    vector<char> topography = { 'U', 'D', 'D', 'D', 'U', 'D', 'U', 'U' };
    ValleyCounter vc(topography);
    size_t expected_valleys_count = 1;

    // Act
    auto actual_valleys_count = vc.get();

    // Assert
    BOOST_CHECK_EQUAL(expected_valleys_count, actual_valleys_count);
}

BOOST_AUTO_TEST_CASE(TestScenario_2)
{
    // Arrange
    vector<char> topography = { 'D', 'D', 'U', 'U', 'D', 'D', 'U', 'D', 'U', 'U', 'U', 'D' };
    ValleyCounter vc(topography);
    size_t expected_valleys_count = 2;

    // Act
    auto actual_valleys_count = vc.get();

    // Assert
    BOOST_CHECK_EQUAL(expected_valleys_count, actual_valleys_count);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Nimelo/hacker-rank

max_issues_repo_name: Nimelo/hacker-rank

max_forks_repo_name: Nimelo/hacker-rank


text:
#include <cmath>
#include <memory>
#include <utility>

#include <Eigen/Core>
#include <glog/logging.h>
#include <gtest/gtest.h>

#include <geometric-vision/linear-triangulation.h>
#include <maplab-common/pose_types.h>
#include <maplab-common/quaternion-math.h>
#include <maplab-common/test/testing-entrypoint.h>
#include <maplab-common/test/testing-predicates.h>

using namespace geometric_vision;  // NOLINT

class GeometricVisionTwoViewTriangulationTest
    : public ::testing::TestWithParam<std::pair<double, double> > {};  // NOLINT

TEST_P(GeometricVisionTwoViewTriangulationTest, ParallelOpticalAxes) {
  LinearTriangulation triangulator;

  pose::Transformation camera0(
      pose::Position3D(0, 0, 0), pose::Quaternion(1, 0, 0, 0));
  pose::Transformation camera1(
      pose::Position3D(1, 0, 0), pose::Quaternion(1, 0, 0, 0));

  std::pair<double, double> measurements = GetParam();
  Eigen::Vector2d measurement0(measurements.first, 0);
  Eigen::Vector2d measurement1(measurements.second, 0);

  Eigen::Vector3d triangulated_point;
  EXPECT_TRUE(
      triangulator.triangulateFromNormalizedTwoViews(
          measurement0, camera0, measurement1, camera1, &triangulated_point));

  // Calculation of expected result.
  const double b = camera0.getPosition()(0) - camera1.getPosition()(0);
  const double f = 1;
  const double Z = (b * f) / (measurement0(0) - measurement1(0));
  const double X = measurement0(0) * Z / f;
  const double Y = measurement0(1) * Z / f;
  Eigen::Vector3d expected_result(X, Y, Z);

  EXPECT_NEAR_EIGEN(expected_result, triangulated_point, 1e-15);
}

INSTANTIATE_TEST_CASE_P(
    GeometricVision, GeometricVisionTwoViewTriangulationTest,
    ::testing::Values(
        std::pair<double, double>(0.1, -0.1),
        std::pair<double, double>(0.2, -0.2),
        std::pair<double, double>(0.1, -0.2),
        std::pair<double, double>(0.05, -0.4),
        std::pair<double, double>(0.3, 0.0)));

struct TriangulationParams {
  TriangulationParams(
      double camera1_rotation_y, double camera1_x, double camera1_y,
      double camera1_z, double G_p_fi_x, double G_p_fi_y, double G_p_fi_z)
      : camera1_rotation_Y_(camera1_rotation_y),
        camera1_position_(camera1_x, camera1_y, camera1_z),
        G_p_fi_(G_p_fi_x, G_p_fi_y, G_p_fi_z) {}

  double camera1_rotation_Y_;
  Eigen::Vector3d camera1_position_;
  Eigen::Vector3d G_p_fi_;

  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};

class GeometricVisionRotatedTwoViewParamTest
    : public ::testing::TestWithParam<TriangulationParams> {
 protected:
  Eigen::Vector2d reprojectPoint(
      const pose::Transformation& transform, const Eigen::Vector3d& G_p_fi) {
    const Eigen::Quaterniond& G_q_C =
        transform.getRotation().toImplementation();
    Eigen::Matrix3d G_R_C = G_q_C.toRotationMatrix();

    // TODO(dymczykm) Investigate why the transformation need to be
    // inverted here
    //    const Eigen::Vector3d C_p_fi = C_R_G
    //        * (G_p_fi - transform.getPosition().toImplementation());
    const Eigen::Vector3d C_p_fi = G_R_C * G_p_fi + transform.getPosition();

    return C_p_fi.hnormalized().head<2>();
  }

  pose::Quaternion getQuaternionFromYRotation(double rotation) {
    // Invert quaternion to get passive rotation.
    return pose::Quaternion(cos(rotation / 2), 0.0, -sin(rotation / 2), 0.0);
  }
};

INSTANTIATE_TEST_CASE_P(
    GeometricVision, GeometricVisionRotatedTwoViewParamTest,
    ::testing::Values(
        TriangulationParams(0, 3, 0, 0, 1.5, 0, 5),
        TriangulationParams(0, 1, 0.05, 0, 0.5, 0.1, 5),
        TriangulationParams(0, 1.2, 0, 0.1, 0.64, 0, 3.2),
        TriangulationParams(-0.4, 1, 0.1, -0.3, 0.64, 0.05, 5.1),
        TriangulationParams(-M_PI / 2, 1, 0.0, 1.0, 0, 0, 1)));

TEST_P(
    GeometricVisionRotatedTwoViewParamTest, TwoViewTriangulationOneCamRotated) {
  LinearTriangulation triangulator;
  TriangulationParams params = GetParam();

  pose::Transformation camera0(
      pose::Position3D(0, 0, 0), pose::Quaternion(1, 0, 0, 0));
  pose::Transformation camera1(
      pose::Position3D(params.camera1_position_),
      getQuaternionFromYRotation(params.camera1_rotation_Y_));

  Eigen::Vector2d measurement0 = this->reprojectPoint(camera0, params.G_p_fi_);
  Eigen::Vector2d measurement1 = this->reprojectPoint(camera1, params.G_p_fi_);

  Eigen::Vector3d triangulated_point, triangulated_point_homog;
  EXPECT_TRUE(
      triangulator.triangulateFromNormalizedTwoViews(
          measurement0, camera0, measurement1, camera1, &triangulated_point));
  EXPECT_TRUE(
      triangulator.triangulateFromNormalizedTwoViewsHomogeneous(
          measurement0, camera0, measurement1, camera1,
          &triangulated_point_homog));
  EXPECT_NEAR_EIGEN(params.G_p_fi_, triangulated_point, 1e-12);
  EXPECT_NEAR_EIGEN(triangulated_point, triangulated_point_homog, 1e-12);
}

TEST(GeometricVision, TwoViewTriangulationParallelRays) {
  LinearTriangulation triangulator;
  pose::Transformation camera0(
      pose::Position3D(0, 0, 0), pose::Quaternion(1, 0, 0, 0));
  pose::Transformation camera1(
      pose::Position3D(1, 0, 0), pose::Quaternion(1, 0, 0, 0));

  Eigen::Vector2d measurement0(0, 0);
  Eigen::Vector2d measurement1(0, 0);

  Eigen::Vector3d triangulated_point;
  EXPECT_FALSE(
      triangulator.triangulateFromNormalizedTwoViews(
          measurement0, camera0, measurement1, camera1, &triangulated_point));
}

MAPLAB_UNITTEST_ENTRYPOINT

max_stars_repo_name: AdronTech/maplab

max_issues_repo_name: AdronTech/maplab

max_forks_repo_name: AdronTech/maplab


text:
//boost库引用文件
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
//标准库
#include <iostream>
#include <string>
#include <sstream>

using namespace std;
using namespace boost::archive::iterators;

//Base64编码
bool Base64Encode(string * outPut, const string & inPut);
//Base64解码
bool Base64Decode(string * outPut, const string & inPut);
int main(void)
{

	cout<<"***************************************"<<endl;
	cout<<"*       boost库Base64编码解码         *"<<endl;
	cout<<"***************************************"<<endl;

	string inputstr = "http://blog.csdn.net/nk_wang/article/details/44536269/\n#@$%^^&**(*(())+=";
	//Base64编码
	string Output;
	string Input;
	cout<<"Base64编码前："<<inputstr<<endl;
	Base64Encode(&Output,inputstr);
	cout<<"Base64编码后："<<Output<<endl;
	//Base64解码
	cout<<"Base64解码前："<<Output<<endl;
	Base64Decode(&Input,Output);
	cout<<"Base64解码后："<<Input<<endl;
	return 0;
}

bool Base64Encode(string * outPut, const string & inPut)
{
	typedef base64_from_binary<transform_width<string::const_iterator,6,8>> Base64EncodeIter;

	stringstream  result;
	copy(Base64EncodeIter(inPut.begin()),
		Base64EncodeIter(inPut.end()),
		ostream_iterator<char>(result));

	size_t Num = (3 - inPut.length() % 3) % 3;
	for (size_t i = 0; i < Num; i++)
	{
		result.put('=');
	}
	*outPut = result.str();
	return outPut->empty() == false;
}
bool Base64Decode(string * outPut, const string & inPut)
{
	typedef transform_width<binary_from_base64<string::const_iterator>,8,6> Base64DecodeIter;

	stringstream result;
	try
	{
		copy(Base64DecodeIter(inPut.begin()),
			Base64DecodeIter(inPut.end()),
			ostream_iterator<char>(result));
	}
	catch (...)
	{
		return false;
	}
	*outPut = result.str();
	return outPut->empty() == false;
}

max_stars_repo_name: vogro-x/vogro-utils

max_issues_repo_name: vogro-x/vogro-utils

max_forks_repo_name: vogro-x/vogro-utils


text:
#include "Poly1d.h"

#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <sstream>

#include <Eigen/Dense>

#include <isce3/core/Poly1d.h>
#include <isce3/except/Error.h>

// alias
namespace py = pybind11;
using isce3::core::Poly1d;
using isce3::except::InvalidArgument;
using isce3::except::LengthError;

void addbinding(pybind11::class_<isce3::core::Poly1d>& pyPoly1d)
{
    pyPoly1d
            // constructors
            .def(py::init([](const std::vector<double>& coeffs,
                                  double mean = 0.0, double std = 1.0) {
                if (!(std > 0.0))
                    throw InvalidArgument(
                            ISCE_SRCINFO(), "STD must be a positive value!");
                auto pf_obj = Poly1d(coeffs.size() - 1, mean, std);
                pf_obj.coeffs = coeffs;
                return pf_obj;
            }),
                    py::arg("coeffs"), py::arg("mean") = 0.0,
                    py::arg("std") = 1.0)

            // dunder methods
            .def("__repr__",
                    [](const Poly1d& self) {
                        std::stringstream os;
                        os << "Poly1d(order= " << self.order
                           << ", mean=" << self.mean << ", std=" << self.norm
                           << ")";
                        return os.str();
                    })
            .def("__str__",
                    [](const Poly1d& self) {
                        Eigen::Map<const Eigen::ArrayXd> coeff(
                                self.coeffs.data(), self.coeffs.size());
                        std::stringstream os;
                        os << "Coeffs in ascending order -> " << coeff;
                        return os.str();
                    })
            .def("__call__", [](const Poly1d& self) { return self.coeffs; })
            .def("__getitem__",
                    [](const Poly1d& self, int pos) {
                        return self.coeffs.at(pos);
                    })
            .def("__getitem__",
                    [](const Poly1d& self, py::slice slice) {
                        size_t start, stop, step, slicelength;
                        if (!slice.compute(self.order + 1, &start, &stop, &step,
                                    &slicelength))
                            throw py::error_already_set();
                        py::list result;
                        for (size_t i = 0; i < slicelength; ++i) {
                            result.append(self.coeffs[start]);
                            start += step;
                        }
                        return result;
                    })
            .def("__len__",
                    [](const Poly1d& self) { return self.coeffs.size(); })

            // methods
            .def("eval", &Poly1d::eval, py::arg("x"))
            .def("eval",
                    [](const Poly1d& self, const std::vector<double>& x) {
                        if (x.size() < 1)
                            throw LengthError(ISCE_SRCINFO(),
                                    "The size of the vector must be non zero!");
                        std::vector<double> y;
                        y.reserve(x.size());
                        for (const auto& element : x)
                            y.push_back(self.eval(element));
                        return y;
                    },
		 py::arg("x"))
            .def("derivative",
                    [](const Poly1d& self) { return self.derivative(); })

            // properties
            .def_property_readonly("order",
                    [](const Poly1d& self) { return self.coeffs.size() - 1; })
            .def_property_readonly(
                    "mean", [](const Poly1d& self) { return self.mean; })
            .def_property_readonly(
                    "std", [](const Poly1d& self) { return self.norm; })
            .def_property_readonly(
                    "coeffs", [](const Poly1d& self) { return self.coeffs; })
            .doc() = R"(
Data structure for representing 1D polynomials in ascending order with centralization and scaling)";
}