text:
/*==============================================================================
  Copyright (c) 2017, 2018, 2019 Matt Calabrese

  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 ARGOT_UNREACHABLE_FUNCTION_HPP_
#define ARGOT_UNREACHABLE_FUNCTION_HPP_

#include <argot/concepts/return_type.hpp>
#include <argot/detail/unreachable.hpp>
#include <argot/gen/concept_assert.hpp>
#include <argot/gen/requires.hpp>

#include <boost/config.hpp>

//[description
/*`
argot::unreachable_function is a function object of a user-specified return type
that produces undefined behavior when executed. It ignores any input that it is
given.

[note_for_ub]
*/
//]

//[docs
/*`
[synopsis_heading]
*/

namespace argot {

template< class Ret >
struct unreachable_function_fn
{
  //<-
  ARGOT_CONCEPT_ASSERT( ReturnType< Ret > );
  //->
  template< class... P >
  [[noreturn]]
  //<-
  BOOST_FORCEINLINE //->
  constexpr Ret operator()( P&&... ) const//=;
  //<-
  {
    ARGOT_DETAIL_UNREACHABLE();
  } //->
};

template< class Ret >
ARGOT_REQUIRES( ReturnType< Ret > )
< unreachable_function_fn< Ret > >
constexpr unreachable_function{};

} // namespace argot

//]

#endif  // ARGOT_UNREACHABLE_FUNCTION_HPP_

max_stars_repo_name: mattcalabrese/argot

max_issues_repo_name: mattcalabrese/argot

max_forks_repo_name: mattcalabrese/argot


text:
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2018 The Infinex Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparams.h"
#include "validation.h"
#include "messagesigner.h"
#include "net_processing.h"
#include "spork.h"

#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>

class CSporkMessage;
class CSporkManager;

CSporkManager sporkManager;

std::map<uint256, CSporkMessage> mapSporks;

void CSporkManager::ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv, CConnman& connman)
{
	if (fLiteMode) return; // disable all Infinex specific functionality

	if (strCommand == NetMsgType::SPORK) {

		CSporkMessage Spork;
		vRecv >> Spork;

		uint256 hash = Spork.GetHash();

		std::string strLogMsg;
		{
			LOCK(cs_main);
			pfrom->setAskFor.erase(hash);
			if (!chainActive.Tip()) return;
			strLogMsg = strprintf("SPORK -- hash: %s id: %d numeric value: %d text value: %s bestHeight: %d peer=%d", hash.ToString(), Spork.nSporkID, Spork.nNumericValue, Spork.nTextValue, chainActive.Height(), pfrom->id);
		}

		if (mapSporksActive.count(Spork.nSporkID)) {
			if (mapSporksActive[Spork.nSporkID].nTimeSigned >= Spork.nTimeSigned) {
				LogPrint("spork", "%s seen\n", strLogMsg);
				return;
			}
			else {
				LogPrintf("%s updated\n", strLogMsg);
			}
		}
		else {
			LogPrintf("%s new\n", strLogMsg);
		}

		if (!Spork.CheckSignature()) {
			LogPrintf("CSporkManager::ProcessSpork -- invalid signature\n");
			Misbehaving(pfrom->GetId(), 100);
			return;
		}

		mapSporks[hash] = Spork;
		mapSporksActive[Spork.nSporkID] = Spork;
		Spork.Relay(connman);

		int sporkType = GetSporkType(Spork.nSporkID);
		if (sporkType == SPORK_TEXT_TYPE) {
			ExecuteTextSpork(Spork.nSporkID, Spork.nTextValue);
		}
		else if (sporkType == SPORK_NUMERIC_TYPE || sporkType == SPORK_BOOL_TYPE || sporkType == SPORK_TIME_TYPE) {
			ExecuteNumericSpork(Spork.nSporkID, Spork.nNumericValue);
		}
	}
	else if (strCommand == NetMsgType::GETSPORKS) {

		std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin();

		while (it != mapSporksActive.end()) {
			connman.PushMessage(pfrom, NetMsgType::SPORK, it->second);
			it++;
		}
	}
}

void CSporkManager::ExecuteNumericSpork(int nSporkID, int nValue)
{
	//correct fork via spork technology
	if (nSporkID == SPORK_RECONSIDER_BLOCKS && nValue > 0) {
		// allow to reprocess 24h of blocks max, which should be enough to resolve any issues
		int64_t nMaxBlocks = 960;
		// this potentially can be a heavy operation, so only allow this to be executed once per 10 minutes
		int64_t nTimeout = 10 * 60;

		static int64_t nTimeExecuted = 0; // i.e. it was never executed before

		if (GetTime() - nTimeExecuted < nTimeout) {
			LogPrint("spork", "CSporkManager::ExecuteSpork -- ERROR: Trying to reconsider blocks, too soon - %d/%d\n", GetTime() - nTimeExecuted, nTimeout);
			return;
		}

		if (nValue > nMaxBlocks) {
			LogPrintf("CSporkManager::ExecuteSpork -- ERROR: Trying to reconsider too many blocks %d/%d\n", nValue, nMaxBlocks);
			return;
		}

		LogPrintf("CSporkManager::ExecuteSpork -- Reconsider Last %d Blocks\n", nValue);

		ReprocessBlocks(nValue);
		nTimeExecuted = GetTime();
	}
}

void CSporkManager::ExecuteTextSpork(int nSporkID, std::string nValue)
{
	if (nSporkID == SPORK_BEST_BLOCK_HASH)
	{
		if (nValue == "")
			return;

		if(!IsBestBlockHashFound(true))
		{
			ReprocessBlocks(960);
		}
	}
	else if (nSporkID == SPORK_MINIMUM_CHAIN_WORK)
	{
		if (nValue == "")
			return;

		!IsExceedMinimumChainWork(true);
	}
}

bool CSporkManager::UpdateNumericSpork(int nSporkID, int64_t nValue, CConnman& connman)
{
	CSporkMessage spork = CSporkMessage(nSporkID, nValue, "", GetAdjustedTime());

	if (!spork.Sign(strMasterPrivKey))
		return false;

	spork.Relay(connman);
	mapSporks[spork.GetHash()] = spork;
	mapSporksActive[nSporkID] = spork;
	return true;
}

bool CSporkManager::UpdateTextSpork(int nSporkID, std::string nValue, CConnman& connman)
{
	CSporkMessage spork = CSporkMessage(nSporkID, 0, nValue, GetAdjustedTime());

	if (!spork.Sign(strMasterPrivKey))
		return false;

	spork.Relay(connman);
	mapSporks[spork.GetHash()] = spork;
	mapSporksActive[nSporkID] = spork;
	return true;
}

bool CSporkManager::IsSporkActive(int nSporkID)
{
	int sporkType = GetSporkType(nSporkID);

	if (sporkType == SPORK_TEXT_TYPE || sporkType == SPORK_NUMERIC_TYPE)
		return true;

	if(sporkType == SPORK_BOOL_TYPE)
	{
		if(GetNumericSporkValue(nSporkID) == SPORK_ENABLED)
			return true;
		return false;
	}

	if (GetSporkType(nSporkID) == SPORK_TIME_TYPE)
	{
		return GetNumericSporkValue(nSporkID) > GetAdjustedTime();
	}

	return false;
}

int64_t CSporkManager::GetNumericSporkValue(int nSporkID)
{
	if (GetSporkType(nSporkID) != SPORK_NUMERIC_TYPE && GetSporkType(nSporkID) != SPORK_BOOL_TYPE && GetSporkType(nSporkID) != SPORK_TIME_TYPE)
	{
		LogPrint("spork", "CSporkManager::GetTextSporkValue -- Spork ID %d is not a numeric spork \n", nSporkID);
		return -1;
	}

	if (mapSporksActive.count(nSporkID))
		return mapSporksActive[nSporkID].nNumericValue;

	switch (nSporkID)
	{
		case SPORK_INSTANTSEND_ENABLED:
			return SPORK_INSTANTSEND_ENABLED_VALUE;
		case SPORK_INSTANTSEND_BLOCK_FILTERING:
			return SPORK_INSTANTSEND_BLOCK_FILTERING_VALUE;
		case SPORK_INSTANTSEND_MAX_VALUE:
			return SPORK_INSTANTSEND_MAX_VALUE_VALUE;
		case SPORK_MASTERNODE_PAYMENT_ENFORCEMENT:
			return SPORK_MASTERNODE_PAYMENT_ENFORCEMENT_VALUE;
		case SPORK_RECONSIDER_BLOCKS:
			return SPORK_RECONSIDER_BLOCKS_VALUE;
		case SPORK_REQUIRE_SENTINEL_FLAG:
			return SPORK_REQUIRE_SENTINEL_FLAG_VALUE;
		default:
			LogPrint("spork", "CSporkManager::GetNumericSporkValue -- Unknown Spork ID %d\n", nSporkID);
			return -1;
	}
}

std::string CSporkManager::GetTextSporkValue(int nSporkID)
{
	if (GetSporkType(nSporkID) != SPORK_TEXT_TYPE)
	{
		LogPrint("spork", "CSporkManager::GetTextSporkValue -- Spork ID %d is not a text spork \n", nSporkID);
		return "";
	}

	if (mapSporksActive.count(nSporkID))
		return mapSporksActive[nSporkID].nTextValue;

	switch (nSporkID)
	{
		case SPORK_MINIMUM_CHAIN_WORK:
			return SPORK_MINIMUM_CHAIN_WORK_VALUE;
		case SPORK_BEST_BLOCK_HASH:
			return SPORK_BEST_BLOCK_HASH_VALUE;
		default:
			LogPrint("spork", "CSporkManager::GetTextSporkValue -- Unknown Spork ID %d\n", nSporkID);
			return "";
	}
}

int CSporkManager::GetSporkIDByName(std::string strName)
{
	if (strName == "SPORK_BEST_BLOCK_HASH") return SPORK_BEST_BLOCK_HASH;
	if (strName == "SPORK_MINIMUM_CHAIN_WORK") return SPORK_MINIMUM_CHAIN_WORK;
    if (strName == "SPORK_INSTANTSEND_ENABLED") return SPORK_INSTANTSEND_ENABLED;
    if (strName == "SPORK_INSTANTSEND_BLOCK_FILTERING") return SPORK_INSTANTSEND_BLOCK_FILTERING;
    if (strName == "SPORK_INSTANTSEND_MAX_VALUE") return SPORK_INSTANTSEND_MAX_VALUE;
    if (strName == "SPORK_MASTERNODE_PAYMENT_ENFORCEMENT") return SPORK_MASTERNODE_PAYMENT_ENFORCEMENT;
    if (strName == "SPORK_RECONSIDER_BLOCKS") return SPORK_RECONSIDER_BLOCKS;
    if (strName == "SPORK_REQUIRE_SENTINEL_FLAG") return SPORK_REQUIRE_SENTINEL_FLAG;
    LogPrint("spork", "CSporkManager::GetSporkIDByName -- Unknown Spork name '%s'\n", strName);
    return -1;
}

std::string CSporkManager::GetSporkNameByID(int nSporkID)
{
	switch (nSporkID) {
	case SPORK_BEST_BLOCK_HASH: return "SPORK_BEST_BLOCK_HASH";
	case SPORK_MINIMUM_CHAIN_WORK: return "SPORK_MINIMUM_CHAIN_WORK";
	case SPORK_INSTANTSEND_ENABLED: return "SPORK_INSTANTSEND_ENABLED";
	case SPORK_INSTANTSEND_BLOCK_FILTERING: return "SPORK_INSTANTSEND_BLOCK_FILTERING";
	case SPORK_INSTANTSEND_MAX_VALUE: return "SPORK_INSTANTSEND_MAX_VALUE";
	case SPORK_MASTERNODE_PAYMENT_ENFORCEMENT: return "SPORK_MASTERNODE_PAYMENT_ENFORCEMENT";
	case SPORK_RECONSIDER_BLOCKS: return "SPORK_RECONSIDER_BLOCKS";
	case SPORK_REQUIRE_SENTINEL_FLAG: return "SPORK_REQUIRE_SENTINEL_FLAG";
	default:
		LogPrint("spork", "CSporkManager::GetSporkNameByID -- Unknown Spork ID %d\n", nSporkID);
		return "Unknown";
	}
}

int CSporkManager::GetSporkType(int nSporkID)
{
	switch (nSporkID)
	{
	case SPORK_BEST_BLOCK_HASH:return SPORK_TEXT_TYPE;
	case SPORK_MINIMUM_CHAIN_WORK:return SPORK_TEXT_TYPE;
	case SPORK_INSTANTSEND_ENABLED: return SPORK_BOOL_TYPE;
	case SPORK_INSTANTSEND_BLOCK_FILTERING: return SPORK_BOOL_TYPE;
	case SPORK_INSTANTSEND_MAX_VALUE: return SPORK_NUMERIC_TYPE;
	case SPORK_MASTERNODE_PAYMENT_ENFORCEMENT: return SPORK_BOOL_TYPE;
	case SPORK_RECONSIDER_BLOCKS: return SPORK_NUMERIC_TYPE;
	case SPORK_REQUIRE_SENTINEL_FLAG: return SPORK_BOOL_TYPE;
	default:
		LogPrint("spork", "CSporkManager::GetSporkType -- Unknown Spork Type %d\n", nSporkID);
		return SPORK_UNKNOWN_TYPE;
	}
}

bool CSporkManager::SetPrivKey(std::string strPrivKey)
{
	CSporkMessage spork;

	spork.Sign(strPrivKey);

	if (spork.CheckSignature()) {
		// Test signing successful, proceed
		LogPrintf("CSporkManager::SetPrivKey -- Successfully initialized as spork signer\n");
		strMasterPrivKey = strPrivKey;
		return true;
	}
	else {
		return false;
	}
}

bool CSporkMessage::Sign(std::string strSignKey)
{
	CKey key;
	CPubKey pubkey;
	std::string strError = "";
	std::string strMessage = boost::lexical_cast<std::string>(nSporkID) + boost::lexical_cast<std::string>(nNumericValue) + boost::lexical_cast<std::string>(nTimeSigned);

	if (!CMessageSigner::GetKeysFromSecret(strSignKey, key, pubkey)) {
		LogPrintf("CSporkMessage::Sign -- GetKeysFromSecret() failed, invalid spork key %s\n", strSignKey);
		return false;
	}

	if (!CMessageSigner::SignMessage(strMessage, vchSig, key)) {
		LogPrintf("CSporkMessage::Sign -- SignMessage() failed\n");
		return false;
	}

	if (!CMessageSigner::VerifyMessage(pubkey, vchSig, strMessage, strError)) {
		LogPrintf("CSporkMessage::Sign -- VerifyMessage() failed, error: %s\n", strError);
		return false;
	}

	return true;
}

bool CSporkMessage::CheckSignature()
{
	std::string strError = "";
	std::string strMessage = boost::lexical_cast<std::string>(nSporkID) + boost::lexical_cast<std::string>(nNumericValue) + boost::lexical_cast<std::string>(nTimeSigned);
	CPubKey pubkey(ParseHex(Params().SporkPubKey()));

	if (!CMessageSigner::VerifyMessage(pubkey, vchSig, strMessage, strError)) {
		LogPrintf("CSporkMessage::CheckSignature -- VerifyMessage() failed, error: %s\n", strError);
		return false;
	}

	return true;
}

void CSporkMessage::Relay(CConnman& connman)
{
	CInv inv(MSG_SPORK, GetHash());
	connman.RelayInv(inv);
}

ext: cpp

max_stars_repo_name: CryptoBia/Infinex

max_issues_repo_name: CryptoBia/Infinex

max_forks_repo_name: CryptoBia/Infinex


text:
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/

#include <NumericalMethods_precompiled.h>
#include <NumericalMethods/Eigenanalysis.h>
#include <NumericalMethods/Optimization.h>
#include <Optimization/SolverBFGS.h>
#include <Eigenanalysis/Solver3x3.h>

namespace NumericalMethods
{
    namespace Optimization
    {
        SolverResult SolverBFGS(const Function& function, const AZStd::vector<double>& initialGuess)
        {
            return MinimizeBFGS(function, initialGuess);
        }
    }

    namespace Eigenanalysis
    {
        SolverResult<Real, 3> Solver3x3RealSymmetric(const SquareMatrix<Real, 3>& matrix)
        {
            // The matrix must be symmetric.
            if (matrix[0][1] == matrix[1][0] && matrix[0][2] == matrix[2][0] && matrix[1][2] == matrix[2][1])
            {
                return NonIterativeSymmetricEigensolver3x3(
                    matrix[0][0], matrix[0][1], matrix[0][2],
                                  matrix[1][1], matrix[1][2],
                                                matrix[2][2]
                );
            }
            else
            {
                return SolverResult<Real, 3>{SolverOutcome::FailureInvalidInput};
            }
        }
    }
} // namespace NumericalMethods

max_stars_repo_name: BadDevCode/lumberyard

max_issues_repo_name: olivier-be/lumberyard

max_forks_repo_name: olivier-be/lumberyard


text:
#include <iostream>
#include <functional>

#include <assert.h>
#include <boost/asio/write.hpp>
#include <boost/asio/placeholders.hpp>

#include "util/debug.hpp"

#include "parser.hpp"
#include "command_dispatcher.hpp"
#include "tcp_connection.hpp"

namespace paxos { namespace detail {

tcp_connection::tcp_connection (
   boost::asio::io_service &                    io_service)
   : socket_ (io_service)
{
}

tcp_connection::~tcp_connection ()
{
   PAXOS_DEBUG ("destructing connection " << this);
}

/*! static */ tcp_connection_ptr
tcp_connection::create (
   boost::asio::io_service &                    io_service)
{
   return tcp_connection_ptr (
      new tcp_connection (io_service));
}

void
tcp_connection::close ()
{
   socket_.close ();
}

bool
tcp_connection::is_open () const
{
   return socket_.is_open ();
}

boost::asio::ip::tcp::socket &
tcp_connection::socket ()
{
   return socket_;
}

void
tcp_connection::write_command (
   detail::command const &      command)
{
   parser::write_command (shared_from_this (),
                          command);
}

void
tcp_connection::read_command (
   read_callback        callback)
{
   parser::read_command (shared_from_this (),
                         callback);
}

void
tcp_connection::read_command_loop (
   read_callback        callback)
{
   read_command (
      [this,
       callback] (boost::optional <enum error_code>     error,
                  command const &                       command)
      {
         callback (error,
                   command);

         if (!error)
         {
            this->read_command_loop (callback);

         }
      });
}

void
tcp_connection::write (
   std::string const &  message)
{
   boost::mutex::scoped_lock lock (mutex_);
   write_locked (message);
}

void
tcp_connection::write_locked (
   std::string const &  message)
{
   /*!
     The problem with Boost.Asio is that it assumes that the buffer we send to async_write ()
     must stay alive until the callback to handle_write () has been called. Since there is no
     way we can guarantee that if we use the message object we get as a reference to this function,
     we have no alternative but to copy the data into our local buffer.

     But wait! What happends when write() is called when we are not yet done writing another
     block? In that case, we will just append that data onto the queue. The handle_write () function
     checks whether any data is still pending on the queue, and if so, ensures another async_write ()
     is called.
    */

   if (write_buffer_.empty () == true)
   {
      write_buffer_ = message;

      start_write_locked ();
   }
   else
   {
      write_buffer_ += message;
   }
}

void
tcp_connection::start_write_locked ()
{
   PAXOS_ASSERT (write_buffer_.empty () == false);

   boost::asio::async_write (socket_,
                             boost::asio::buffer (write_buffer_),
                             std::bind (&tcp_connection::handle_write,

                                        /*!
                                          Using shared_from_this here instead of this ensures that
                                          we obtain a shared pointer to ourselves, and so when our
                                          object would go out of scope normally, it at least stays
                                          alive until this callback is called.
                                        */
                                        shared_from_this(),
                                        std::placeholders::_1,
                                        std::placeholders::_2));
}

void
tcp_connection::handle_write (
   boost::system::error_code const &    error,
   size_t                               bytes_transferred)
{
   if (error)
   {
      PAXOS_WARN ("an error occured while writing data: " << error.message ());
      return;
   }

   boost::mutex::scoped_lock lock (mutex_);
   handle_write_locked (bytes_transferred);
}

void
tcp_connection::handle_write_locked (
   size_t                               bytes_transferred)
{
   PAXOS_ASSERT (write_buffer_.size () >= bytes_transferred);

   write_buffer_ = write_buffer_.substr (bytes_transferred);

   /*!
     As discussed in the write () function, if we still have data on the buffer, ensure
     that data is also written.
    */
   if (write_buffer_.empty () == false)
   {
      start_write_locked ();
   }
}

}; };

max_stars_repo_name: armos-db/libpaxos-cpp

max_issues_repo_name: armos-db/libpaxos-cpp

max_forks_repo_name: armos-db/libpaxos-cpp


text:
#include <haptic_sandbox/hydra_interaction_tool.h>
#include <hydra/CalibPaddle.h>

#include <tf/tf.h>
#include <Eigen/Geometry>
#include <ros/ros.h>

namespace something {

HydraInteractionTool::~HydraInteractionTool()
{
}

void HydraInteractionTool::init()
{

//    setPosition(tf::Vector3(pos.x(), pos.y(), pos.z()));
//    setQuaternion(tf::createQuaternionFromYaw(M_PI)*tf::createQuaternionFromRPY(0, 0.4, 0));

    ros::NodeHandle nh;
    hydra_sub_ = nh.subscribe<hydra::Calib>("hydra_calib", 1, boost::bind(&HydraInteractionTool::updateFromMsg, this, _1));

}

/////////////////////////////////////////////////////////////////////
// PROTECTED FUNCTIONS LIVE UNDER HERE
/////////////////////////////////////////////////////////////////////

void HydraInteractionTool::updateFromMsg(const hydra::CalibConstPtr &calib)
{
    ROS_DEBUG_NAMED("hydra", "Got hydra update!");
    hydra::CalibPaddle paddle = calib->paddles[0];

    // Update pose info
    tf::Transform interaction_handle;
    tf::transformMsgToTF(paddle.transform, interaction_handle);
    handle_->setTransform(interaction_handle);

    // Update button info
    if(getToolButtonCount() != paddle.buttons.size())
        setToolButtonCount(paddle.buttons.size());
    for(size_t i = 0; i < getToolButtonCount(); ++i)
    {
        setToolButtonState(i, paddle.buttons[i]);
    }
}

}  // namespace something

max_issues_repo_name: salisbury-robotics/jks-ros-pkg

max_forks_repo_name: salisbury-robotics/jks-ros-pkg


text:
//=======================================================================
// Copyright (c) 2013 Piotr Wygocki
//               2014 Piotr Smulewicz
//
// 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)
//=======================================================================
/**
 * @file metric_test.cpp
 * @brief
 * @author Piotr Wygocki ,Piotr Smulewicz
 * @version 1.0
 * @date 2013-02-04
 */

#include "test_utils/sample_graph.hpp"

#include "paal/utils/irange.hpp"
#include "paal/utils/floating.hpp"
#include "paal/data_structures/metric/euclidean_metric.hpp"
#include "paal/data_structures/metric/graph_metrics.hpp"
#include "paal/data_structures/metric/basic_metrics.hpp"

#include <boost/test/unit_test.hpp>

#include <cmath>

BOOST_AUTO_TEST_CASE(euclidean_metric_test) {
    auto metric=paal::data_structures::euclidean_metric<int>();
    std::pair<int,int> a={0,0},b={1,1};

    BOOST_CHECK(paal::utils::compare<double>().e(metric(a,b),std::sqrt(2)));
}

BOOST_AUTO_TEST_CASE(metric_test) {
    typedef sample_graphs_metrics SGM;
    auto gm = SGM::get_graph_metric_small();

    BOOST_CHECK_EQUAL(gm(SGM::A, SGM::B) , 2);
    BOOST_CHECK_EQUAL(gm(SGM::C, SGM::B) , 3);
}

BOOST_AUTO_TEST_CASE(copyrectangle_array_metric) {
    paal::data_structures::rectangle_array_metric<int> m(1, 2);
    m(0, 0) = 1;
    m(0, 1) = 2;

    auto r1 = paal::irange(1);
    auto r2 = paal::irange(2);
    paal::data_structures::rectangle_array_metric<int> copy(
        m, r1, r2);

    BOOST_CHECK_EQUAL(copy(0, 0) , 1);
    BOOST_CHECK_EQUAL(copy(0, 1) , 2);
}

BOOST_AUTO_TEST_CASE(copyarray_metric) {
    paal::data_structures::array_metric<int> m(1);
    m(0, 0) = 13;

    auto r1 = paal::irange(1);
    paal::data_structures::array_metric<int> copy(m, r1);

    BOOST_CHECK_EQUAL(copy(0, 0) , 13);
}

max_stars_repo_name: Kommeren/AA

max_issues_repo_name: Kommeren/AA

max_forks_repo_name: Kommeren/AA


text:
//
// Copyright 2018-2020 Mateusz Loskot <mateusz at loskot dot net>
//
// 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/gil.hpp>

#include <boost/core/lightweight_test.hpp>

#include <cstdint>

namespace boost { namespace gil {
namespace test { namespace fixture {

gil::point_t d{2, 2};
std::uint8_t r[] = { 1, 2, 3, 4 };
std::uint8_t g[] = { 10, 20, 30, 40 };
std::uint8_t b[] = { 110, 120, 130, 140 };
std::uint8_t a[] = { 251, 252, 253, 254 };

}}}}

namespace gil = boost::gil;
namespace fixture = boost::gil::test::fixture;

void test_dimensions()
{
    auto v = gil::planar_rgba_view(fixture::d.x, fixture::d.y, fixture::r, fixture::g, fixture::b, fixture::a, sizeof(std::uint8_t) * 2);
    BOOST_TEST(!v.empty());
    BOOST_TEST(v.dimensions() == fixture::d);
    BOOST_TEST(v.num_channels() == 4u);
    BOOST_TEST(v.size() == static_cast<std::size_t>(fixture::d.x * fixture::d.y));
}

void test_front()
{
    auto v = gil::planar_rgba_view(fixture::d.x, fixture::d.y, fixture::r, fixture::g, fixture::b, fixture::a, sizeof(std::uint8_t) * 2);
    gil::rgba8_pixel_t const pf{1, 10, 110, 251};
    BOOST_TEST(v.front() == pf);
}

void test_back()
{
    auto v = gil::planar_rgba_view(fixture::d.x, fixture::d.y, fixture::r, fixture::g, fixture::b, fixture::a, sizeof(std::uint8_t) * 2);
    gil::rgba8_pixel_t const pb{4, 40, 140, 254};
    BOOST_TEST(v.back() == pb);
}

void test_pixel_equal_to_operator()
{
    auto v = gil::planar_rgba_view(fixture::d.x, fixture::d.y, fixture::r, fixture::g, fixture::b, fixture::a, sizeof(std::uint8_t) * 2);
    for (std::ptrdiff_t i = 0; i < static_cast<std::ptrdiff_t>(v.size()); i++)
    {
        gil::rgba8_pixel_t const p{fixture::r[i], fixture::g[i], fixture::b[i], fixture::a[i]};
        BOOST_TEST(v[i] == p);
    }
}

int main()
{
    test_dimensions();
    test_front();
    test_back();
    test_pixel_equal_to_operator();

    return ::boost::report_errors();
}

max_stars_repo_name: martin-carrasco/gil

max_issues_repo_name: martin-carrasco/gil

max_forks_repo_name: martin-carrasco/gil


text:
#include <pxp-agent/modules/command.hpp>
#include <pxp-agent/configuration.hpp>
#include <pxp-agent/util/bolt_helpers.hpp>
#include <leatherman/file_util/file.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>

namespace PXPAgent {
namespace Modules {

namespace fs = boost::filesystem;
namespace lth_jc = leatherman::json_container;
namespace lth_file = leatherman::file_util;

static const std::string COMMAND_RUN_ACTION { "run" };

Command::Command(const fs::path& exec_prefix, std::shared_ptr<ResultsStorage> storage) :
    BoltModule { exec_prefix, std::move(storage), nullptr }
{
    module_name = "command";
    actions.push_back(COMMAND_RUN_ACTION);

    // Command actions require a single "command" string parameter
    PCPClient::Schema input_schema { COMMAND_RUN_ACTION };
    input_schema.addConstraint("command", PCPClient::TypeConstraint::String, true);
    input_validator_.registerSchema(input_schema);

    PCPClient::Schema output_schema { COMMAND_RUN_ACTION };
    results_validator_.registerSchema(output_schema);
}

Util::CommandObject Command::buildCommandObject(const ActionRequest& request)
{
    const auto params = request.params();

    assert(params.includes("command") &&
           params.type("command") == lth_jc::DataType::String);

    auto raw_command = params.get<std::string>("command");
    auto chunks = Util::splitArguments(raw_command);
    auto command = *chunks.begin();
    std::vector<std::string> arguments { chunks.begin() + 1, chunks.end() };
    const fs::path& results_dir { request.resultsDir() };

    Util::CommandObject cmd {
        command,    // Executable
        arguments,  // Arguments
        {},         // Environment
        "",         // Input
        [results_dir](size_t pid) {
            auto pid_file = (results_dir / "pid").string();
            lth_file::atomic_write_to_file(std::to_string(pid) + "\n", pid_file,
                                           NIX_FILE_PERMS, std::ios::binary);
        }  // PID Callback
    };

    return cmd;
}

}  // namespace Modules
}  // namespace PXPAgent

ext: cc

max_stars_repo_name: Dorin-Pleava/pxp-agent

max_issues_repo_name: Dorin-Pleava/pxp-agent

max_forks_repo_name: Dorin-Pleava/pxp-agent


text:
/***********************************************************************

Copyright (c) 2020, University of California, San Diego
All rights reserved.

Author: Jiangeng Dong <jid103@ucsd.edu>

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.

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.

*************************************************************************/
#include <boost/bind.hpp>
#include <openrave/plugin.h>

#include "Problem.h"

using namespace OpenRAVE;

// called to create a new plugin
InterfaceBasePtr CreateInterfaceValidated(InterfaceType type, const std::string &interfacename, std::istream &sinput, EnvironmentBasePtr penv) {
    if (type == PT_Planner && interfacename == "compnetx") {
        return InterfaceBasePtr(new CoMPNetX::Problem(std::move(penv), sinput));
    }

    return InterfaceBasePtr();
}

// called to query available plugins
void GetPluginAttributesValidated(PLUGININFO &info) {
    info.interfacenames[PT_Planner].push_back("CoMPNetX");
}

// called before plugin is terminated
OPENRAVE_PLUGIN_API void DestroyPlugin() {
}

max_stars_repo_name: JiangengDong/CoMPNetX

max_issues_repo_name: JiangengDong/CoMPNetX

max_forks_repo_name: JiangengDong/CoMPNetX


text:
/*===========================================================================*\
 *                                                                           *
 *                               CoMISo                                      *
 *      Copyright (C) 2008-2009 by Computer Graphics Group, RWTH Aachen      *
 *                           www.rwth-graphics.de                            *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of CoMISo.                                             *
 *                                                                           *
 *  CoMISo 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 3 of the License, or        *
 *  (at your option) any later version.                                      *
 *                                                                           *
 *  CoMISo 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 CoMISo.  If not, see <http://www.gnu.org/licenses/>.          *
 *                                                                           *
\*===========================================================================*/

#ifndef COMISO_Eigen_TOOLS_HH
#define COMISO_Eigen_TOOLS_HH

//== COMPILE-TIME PACKAGE REQUIREMENTS ========================================
#include <CoMISo/Config/config.hh>
#if COMISO_EIGEN3_AVAILABLE

//== INCLUDES =================================================================

#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
#include <cmath>

#include <Eigen/Dense>
#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET
#include <Eigen/Sparse>

#if COMISO_SUITESPARSE_AVAILABLE
#include <cholmod.h>
#endif

//== FORWARDDECLARATIONS ======================================================

//== NAMESPACES ===============================================================

namespace COMISO_EIGEN
{

/** \class EigenTools Eigen_Tools.hh

    A collection of helper functions for manipulating (Eigen) matrices.
*/

//== FUNCTION DEFINITION ======================================================

/// Get matrix data (CSC matrix format) from matrix
/** Used by Cholmod wrapper
 *  @param _mat matrix
 *  @param _c uplo parameter (l, L, u, U, c, C)
 *  @param _values values vector
 *  @param _rowind row indices
 *  @param _colptr column pointer  */
template<class MatrixT, class REALT, class INTT>
void get_ccs_symmetric_data( const MatrixT&      _mat,
                             const char          _c,
                             std::vector<REALT>& _values,
                             std::vector<INTT>&  _rowind,
                             std::vector<INTT>&  _colptr );

/// Inspect the matrix (print)
/** Prints useful matrix informations such as, dimension, symmetry, zero_rows, zero_cols, nnz, max, min, max_abs, min_abs, NAN, INF
  * @param _A matrix */
template<class MatrixT>
void inspect_matrix( const MatrixT& _A);

/** checks for symmetry
  * @param _A matrix
  * @return symmetric? (bool)*/
template<class MatrixT>
bool is_symmetric( const MatrixT& _A);

template< class Eigen_MatrixT, class IntT >
void permute( const Eigen_MatrixT& _QR, const std::vector< IntT>& _Pvec, Eigen_MatrixT& _A);

#if COMISO_SUITESPARSE_AVAILABLE

/// Eigen to Cholmod_sparse interface
template<class MatrixT>
void cholmod_to_eigen( const cholmod_sparse& _AC, MatrixT& _A);

template<class MatrixT>
void eigen_to_cholmod( const MatrixT&  _A,
                     cholmod_sparse* &_AC,
                     cholmod_common* _common,
                     int             _sparsity_type = 0,
                     bool            _long_int      = false);
#endif

// convert a gmm column-sparse matrix into an eigen sparse matrix
template<class GMM_MatrixT, class EIGEN_MatrixT>
void gmm_to_eigen( const GMM_MatrixT& _G, EIGEN_MatrixT& _E);

//=============================================================================
} // namespace COMISO_Eigen
//=============================================================================
#if defined(INCLUDE_TEMPLATES) && !defined(COMISO_Eigen_TOOLS_C)
#define COMISO_Eigen_TOOLS_TEMPLATES
#include "Eigen_Tools.cc"
#endif

//=============================================================================
#endif // COMISO_EIGEN3_AVAILABLE
//=============================================================================//=============================================================================
#endif // Eigen_TOOLS_HH defined
//=============================================================================

ext: hh


text:
#include "tpcc_worker.h"
#include "tpcc_schema.h"
#include "tpcc_mixin.h"
#include "tpcc_log_cleaner.h"
#include "tx_config.h"

#include <getopt.h>
#include <iostream>

#include "db/txs/dbsi.h"

#include "framework/bench_runner.h"

// for parsing config xml
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>

using namespace std;

extern size_t scale_factor;
extern size_t nthreads;
extern size_t nclients;
extern uint64_t ops_per_worker;
extern size_t total_partition;

extern size_t nthreads;
extern volatile bool running;
extern int verbose;

extern size_t distributed_ratio;

namespace nocc {

extern RdmaCtrl *cm;       // global RDMA handler
namespace oltp {

extern char *store_buffer; // the buffer used to store DrTM-kv
extern MemDB *backup_stores_[MAX_BACKUP_NUM];

namespace tpcc {

/* parameters of TPCC */
int g_uniform_item_dist = 0;
int g_new_order_remote_item_pct = 1;
int g_mico_dist_num = 20;
// unsigned g_txn_workload_mix[5] = { 45, 43, 4, 4, 4 }; // default TPC-C workload mix
unsigned g_txn_workload_mix[5] = { 0, 100, 0, 0, 0 }; // default TPC-C workload mix

// remote loc cache related functions
void populate_ware(MemDB *db);
void populate_dist(MemDB *db);
void populate_stock(MemDB *db);

class TpccClient : public BenchClient {
 public:
  TpccClient(unsigned worker_id,unsigned seed,int total_wares)
      : BenchClient(worker_id,seed),
        total_wares_(total_wares){ }
  virtual int get_workload(char *input,util::fast_random &rand) {
    // pick execute machine
    int ware = (int)(rand.next_uniform() * (total_wares_) + 1);
    int pid  = WarehouseToPartition(ware);

    // pick tx idx
    static auto workload = TpccWorker::_get_workload();
    double d = rand.next_uniform();

    uint tx_idx = 0;
    for(size_t i = 0;i < workload.size();++i) {
      if((i + 1) == workload.size() || d < workload[i].frequency) {
        tx_idx = i;
        break;
      }
      d -= workload[i].frequency;
    }
    //fprintf(stdout,"TPCC pick %d, tx_idx %d\n",pid,tx_idx);
    *(uint8_t *)input = tx_idx;
    return pid;
  }
 private:
  int total_wares_;
};

class TpccMainRunner : public BenchRunner {
 public:
  TpccMainRunner(std::string &config_file) ;
  virtual void init_put();
  virtual std::vector<BenchLoader *> make_loaders(int partition, MemDB* store = NULL);
  virtual std::vector<RWorker *> make_workers();
  virtual std::vector<BackupBenchWorker *> make_backup_workers();
  virtual void init_store(MemDB* &store);
  virtual void init_backup_store(MemDB* &store);
  virtual void warmup_buffer(char *);
  virtual void populate_cache();

  virtual void bootstrap_with_rdma(RdmaCtrl *r) {
  }
};

void TpccTest(int argc, char **argv) {

  optind = 1;
  bool did_spec_remote_pct = false;
#if 0
  while (1) {
    static struct option long_options[] =
        {
          {"new-order-remote-item-pct"            , required_argument , 0                                     , 'r'} ,
          {"micro-dist-num"                       , required_argument , 0                                     , 'n'} ,
          {"uniform-item-dist"                    , no_argument       , &g_uniform_item_dist                  , 1}   ,
          {"workload-mix"                         , required_argument , 0                                     , 'w'} ,
          {0, 0, 0, 0}
        };

    int option_index = 0;
    int c = getopt_long(argc, argv, "r:", long_options, &option_index);
    if (c == -1)
      break;
    switch (c) {
      case 0:
        if (long_options[option_index].flag != 0)
          break;
        abort();
        break;
      case 'r':
        g_new_order_remote_item_pct = strtoul(optarg, NULL, 10);
        ALWAYS_ASSERT(g_new_order_remote_item_pct >= 0 && g_new_order_remote_item_pct <= 100);
        did_spec_remote_pct = true;
        break;
      case 'n':
        g_mico_dist_num = strtoul(optarg,NULL,10);
        break;
      case 'w':
        {
          assert(false);
          const vector<string> toks = split(optarg, ',');
          ALWAYS_ASSERT(toks.size() == ARRAY_NELEMS(g_txn_workload_mix));
          unsigned s = 0;
          for (size_t i = 0; i < toks.size(); i++) {
            unsigned p = strtoul(toks[i].c_str(), nullptr, 10);
            ALWAYS_ASSERT(p >= 0 && p <= 100);
            s += p;
            g_txn_workload_mix[i] = p;
          }
          ALWAYS_ASSERT(s == 100);
        }
        break;

      case '?':
        /* getopt_long already printed an error message. */
        exit(1);

      default:
        abort();
    }
  }
#endif
  if (verbose) {
    cerr << "[tpcc] settings:" << endl;
    cerr << "  new_order_remote_item_pct    : " << g_new_order_remote_item_pct << endl;
    cerr << "  uniform_item_dist            : " << g_uniform_item_dist << endl;
    cerr << "  micro dist :" << g_mico_dist_num << endl;
    //format_list(g_txn_workload_mix,
    //g_txn_workload_mix + ARRAY_NELEMS(g_txn_workload_mix)) << endl;
  }
  TpccMainRunner runner(nocc::oltp::config_file_name);
  runner.run();
  /* End TPCC bootstrap function */
}

/**/

TpccMainRunner::TpccMainRunner(std::string &config_file)
    : BenchRunner(config_file) {

  // parse the TX mix ratio
  using boost::property_tree::ptree;
  using namespace boost;
  using namespace property_tree;

  ptree pt;
  bool init(true);

  // parse input xml
  try {
    read_xml(config_file,pt);
  } catch(const ptree_error &e) {
    init = false;
  }

  if(init) {
    // parse each TX's ratio
    try {
      int new_order = pt.get<int> ("bench.tpcc.new");
      int pay = pt.get<int> ("bench.tpcc.pay");
      int del = pt.get<int> ("bench.tpcc.del");
      int stock = pt.get<int> ("bench.tpcc.stock");
      int order = pt.get<int> ("bench.tpcc.order");

      g_txn_workload_mix[0] = new_order;
      g_txn_workload_mix[1] = pay;
      g_txn_workload_mix[2] = del;
      g_txn_workload_mix[3] = order;
      g_txn_workload_mix[4] = stock;

    } catch (const ptree_error &e) {
      // pass
    }

    // parse specific parameters
    try {
      //  g_new_order_remote_item_pct = pt.get<int> ("bench.tpcc.r");
      g_new_order_remote_item_pct = distributed_ratio;
    } catch (const ptree_error &e) {
      // pass
    }
  }

  workload_desc_vec_t workload = TpccWorker::_get_workload();
  for(uint i = 0;i < workload.size();++i) {
    cout << "Txn " << workload[i].name << ", "<< (workload[i].frequency * 100) << endl;
  }
  cout <<"Remote counts: " << g_new_order_remote_item_pct << endl;
  cout <<"NAIVE: " << NAIVE;

}

void TpccMainRunner::init_store(MemDB* &store){

  store = new MemDB(store_buffer);
  int meta_size = META_SIZE;
#if SI_TX
  meta_size = SI_META_LEN;
#endif

  // store as normal B-tree
  //store->AddSchema(WARE,TAB_BTREE,sizeof(uint64_t),sizeof(warehouse::value),meta_size);
  //store->AddSchema(DIST,TAB_BTREE,sizeof(uint64_t),sizeof(district::value),meta_size);
  //store->AddSchema(STOC,TAB_BTREE,sizeof(uint64_t),sizeof(stock::value),meta_size);
  assert(scale_factor > 0);
  // store as DrTM kv
  store->AddSchema(WARE,TAB_HASH,sizeof(uint64_t),sizeof(warehouse::value),meta_size,scale_factor * 2);
  store->AddSchema(DIST,TAB_HASH,sizeof(uint64_t),sizeof(district::value),meta_size,
                   scale_factor * NumDistrictsPerWarehouse() * 2);
  store->AddSchema(STOC,TAB_BTREE,sizeof(uint64_t),sizeof(stock::value),meta_size,
                   NumItems() * scale_factor);
#if ONE_SIDED_READ == 1
  store->EnableRemoteAccess(WARE,cm);
  store->EnableRemoteAccess(DIST,cm);
  store->EnableRemoteAccess(STOC,cm);
#endif

  store->AddSchema(CUST,TAB_BTREE,sizeof(uint64_t),sizeof(customer::value),meta_size);
  store->AddSchema(HIST,TAB_BTREE,sizeof(uint64_t),sizeof(history::value),meta_size);
  store->AddSchema(NEWO,TAB_BTREE,sizeof(uint64_t),sizeof(new_order::value),meta_size);
  store->AddSchema(ORDE,TAB_BTREE,sizeof(uint64_t),sizeof(oorder::value),meta_size);
  store->AddSchema(ORLI,TAB_BTREE,sizeof(uint64_t),sizeof(order_line::value),meta_size);
  store->AddSchema(ITEM,TAB_BTREE,sizeof(uint64_t),sizeof(item::value),meta_size);

  // secondary index
  //store->AddSchema(CUST_INDEX,TAB_SBTREE,sizeof(uint64_t),16,meta_size);
  //      store->AddSchema(ORDER_INDEX,TAB_BTREE,sizeof(uint64_t),16,meta_size);
  store->AddSchema(CUST_INDEX,TAB_BTREE1, 5,16,meta_size);
  store->AddSchema(ORDER_INDEX,TAB_BTREE, sizeof(uint64_t),16,meta_size);

}

void TpccMainRunner::init_backup_store(MemDB* &store){
  store = new MemDB();
  int meta_size = META_SIZE;

  // store as DrTM kv
  store->AddSchema(WARE,TAB_HASH,sizeof(uint64_t),sizeof(warehouse::value),meta_size,scale_factor * 2);
  store->AddSchema(DIST,TAB_HASH,sizeof(uint64_t),sizeof(district::value),meta_size,scale_factor * 2 * NumDistrictsPerWarehouse());
  store->AddSchema(STOC,TAB_HASH,sizeof(uint64_t),sizeof(stock::value),meta_size,
                   NumItems() * scale_factor);

  store->AddSchema(CUST,TAB_BTREE,sizeof(uint64_t),sizeof(customer::value),meta_size);
  store->AddSchema(HIST,TAB_BTREE,sizeof(uint64_t),sizeof(history::value),meta_size);
  store->AddSchema(NEWO,TAB_BTREE,sizeof(uint64_t),sizeof(new_order::value),meta_size);
  store->AddSchema(ORDE,TAB_BTREE,sizeof(uint64_t),sizeof(oorder::value),meta_size);
  store->AddSchema(ORLI,TAB_BTREE,sizeof(uint64_t),sizeof(order_line::value),meta_size);
  store->AddSchema(ITEM,TAB_BTREE,sizeof(uint64_t),sizeof(item::value),meta_size);

  // secondary index
  //store->AddSchema(CUST_INDEX,TAB_SBTREE,sizeof(uint64_t),16,meta_size);
  //      store->AddSchema(ORDER_INDEX,TAB_BTREE,sizeof(uint64_t),16,meta_size);
  store->AddSchema(CUST_INDEX,TAB_BTREE1, 5,16,meta_size);
  store->AddSchema(ORDER_INDEX,TAB_BTREE, sizeof(uint64_t),16,meta_size);
}

void TpccMainRunner::init_put() {

  uint64_t *temp = new uint64_t[4];
  temp[0] = 0; temp[1] = 0; temp[2] = 0;
  for (int i=0; i < 9; i++) {
    //Fixme: invalid value pointer
    store_->Put(i,(uint64_t)1<<60, temp);
  }
  //XXX: add empty record to identify the end of the table./
  store_->Put(ORDER_INDEX,(uint64_t)1<<60, temp);

  //FIXME, do we need to add a last value for the customer secondary index ?
}

std::vector<BenchLoader *> TpccMainRunner::make_loaders(int partition, MemDB* store) {

  //fprintf(stdout,"[TPCC loader] total %d warehouses\n",NumWarehouses());
  /* Current we do not consider parallal loading */
  std::vector<BenchLoader *> ret;
  if(store == NULL){
    ret.push_back(new TpccWarehouseLoader(9324,partition, store_));
    ret.push_back(new TpccItemLoader(235443,partition,store_));
    ret.push_back(new TpccStockLoader(89785943,partition,store_));
    ret.push_back(new TpccDistrictLoader(129856349,partition,store_));
    ret.push_back(new TpccCustomerLoader(923587856425,partition,store_));
    ret.push_back(new TpccOrderLoader(2343352,partition,store_));
  } else {
    // ret.push_back(new TpccWarehouseLoader(9324,partition, store));
    // ret.push_back(new TpccItemLoader(235443,partition,store));
    ret.push_back(new TpccStockLoader(89785943,partition,store,true));
    ret.push_back(new TpccDistrictLoader(129856349,partition,store));
    // ret.push_back(new TpccCustomerLoader(923587856425,partition,store));
    // ret.push_back(new TpccOrderLoader(2343352,partition,store));
  }
  return ret;
}

std::vector<RWorker *> TpccMainRunner::make_workers() {

  fast_random r(23984543 + current_partition);

  std::vector<RWorker *> ret;

  int n_ware_per_worker = scale_factor / nthreads;
  fprintf(stdout, "[Tpcc] n_ware_per_worker: %d\n", n_ware_per_worker);
  LOG(3) << "total warehouse used at this machine: " << (double)NumWarehouses() / total_partition;

  for(uint i = 0;i < nthreads; ++i) {
    //  assert(ops_per_worker > 0);
    if(n_ware_per_worker == 0) {
      ret.push_back(new TpccWorker(i,r.next(),(current_partition) * scale_factor + 1,
                                   (current_partition + 1) * scale_factor + 1,
                                   store_,ops_per_worker,
                                   &barrier_a_,&barrier_b_,this));
    } else {
      // TODO, current donot consider cases when one threads holds more warehouses
      ret.push_back(new TpccWorker(i,r.next(),current_partition * scale_factor + i + 1,
                                   current_partition * scale_factor + i + n_ware_per_worker + 1 ,
                                   store_,ops_per_worker,
                                   &barrier_a_,&barrier_b_,this));
    }
  }

#if CS == 1
  for(uint i = 0;i < nclients;++i)
    ret.push_back(new TpccClient(nthreads + i,r.next(),n_ware_per_worker * nthreads * total_partition));
#endif

#if SI_TX
  // add ts worker
  ts_manager = new TSManager(nthreads + nclients + 1,cm,total_partition - 1,0);
  //ts_manager = new TSManager(nthreads + nclients + 1,cm,0,0);
  ret.push_back(ts_manager);
#endif

  return ret;
}

std::vector<BackupBenchWorker *> TpccMainRunner::make_backup_workers() {
  std::vector<BackupBenchWorker *> ret;

  int num_backups = my_view->is_backup(current_partition);
  LogCleaner* log_cleaner = new TpccLogCleaner;
  for(uint j = 0; j < num_backups; j++){
    assert(backup_stores_[j] != NULL);
    log_cleaner->add_backup_store(backup_stores_[j]);
  }

  DBLogger::set_log_cleaner(log_cleaner);
  for(uint i = 0; i < backup_nthreads; i++){
    ret.push_back(new BackupBenchWorker(i));
  }
  return ret;
}

void TpccMainRunner::warmup_buffer(char *buffer) {
}

void TpccMainRunner::populate_cache() {
#if RDMA_CACHE == 1
  // create a temporal QP for usage
  int dev_id = cm->get_active_dev(0);
  int port_idx = cm->get_active_port(0);

  cm->thread_local_init();
  cm->open_device(dev_id);
  cm->register_connect_mr(dev_id); // register memory on the specific device

  cm->link_connect_qps(nthreads + nthreads + 1,dev_id,port_idx,0,IBV_QPT_RC);

  // calculate the time of populating the cache
  struct  timeval start;
  struct  timeval end;

  gettimeofday(&start,NULL);

  //populate_ware(store_);
  //populate_dist(store_);
  populate_stock(store_);

  gettimeofday(&end,NULL);

  auto diff = (end.tv_sec-start.tv_sec) + (end.tv_usec - start.tv_usec) /  1000000.0;
  fprintf(stdout,"Time to loader the caching is %f second\n",diff);
#endif
}

int GetStartWarehouse(int partition) {
  return partition * scale_factor  + 1;
}

int GetEndWarehouse(int partition) {
  return (partition + 1) * scale_factor;
}

int NumWarehouses() {
  return (int)(scale_factor * (total_partition-1));
}

int WarehouseToPartition(int wid) {
  return (wid - 1) / scale_factor;
}
/* end namespace tpcc */
}

}
}

max_stars_repo_name: SJTU-IPADS/dst

max_issues_repo_name: SJTU-IPADS/dst

max_forks_repo_name: SJTU-IPADS/dst


text:
#include <stdio.h>
#include <string>
#include <string.h>
#include <sys/types.h>
#include "base.h"
#include <boost/thread.hpp>
#define __USE_GNU
#include <ucontext.h>

#define nprint_reg(in)\
    fprintf(stderr, "\t\tin fun self section====%s:%lx\n", #in, in);

#define NPP\
        ucontext_t uc;\
        getcontext(&uc); \
        uint64_t reg0    = uc.uc_mcontext.gregs[REG_RAX];\
        uint64_t reg1    = uc.uc_mcontext.gregs[REG_RDX];\
        uint64_t reg2    = uc.uc_mcontext.gregs[REG_RCX];\
        uint64_t reg3    = uc.uc_mcontext.gregs[REG_RBX];\
        uint64_t reg4    = uc.uc_mcontext.gregs[REG_RSI];\
        uint64_t reg5    = uc.uc_mcontext.gregs[REG_RDI];\
        uint64_t reg6    = uc.uc_mcontext.gregs[REG_RBP];\
        uint64_t reg7    = uc.uc_mcontext.gregs[REG_RSP];\
        uint64_t reg8    = uc.uc_mcontext.gregs[REG_R8];\
        uint64_t reg9    = uc.uc_mcontext.gregs[REG_R9];\
        uint64_t reg10    = uc.uc_mcontext.gregs[REG_R10];\
        uint64_t reg11    = uc.uc_mcontext.gregs[REG_R11];\
        uint64_t reg12    = uc.uc_mcontext.gregs[REG_R12];\
        uint64_t reg13    = uc.uc_mcontext.gregs[REG_R13]; \
        uint64_t reg14    = uc.uc_mcontext.gregs[REG_R14]; \
        uint64_t reg15    = uc.uc_mcontext.gregs[REG_R15]; \
        uint64_t reg16    = uc.uc_mcontext.gregs[REG_RIP];    \
        nprint_reg(reg0) \
        nprint_reg(reg1)\
        nprint_reg(reg2)\
        nprint_reg(reg3)\
        nprint_reg(reg4)\
        nprint_reg(reg5)\
        nprint_reg(reg6)\
        nprint_reg(reg7)\
        nprint_reg(reg8)\
        nprint_reg(reg9)\
        nprint_reg(reg10)\
        nprint_reg(reg11)\
        nprint_reg(reg12)\
        nprint_reg(reg13)\
        nprint_reg(reg14)\
        nprint_reg(reg15)\
        nprint_reg(reg16)

void process(const ff_node &fn){
    fprintf(stderr, "fn.addr:%lx, fn.get().addr:%lx, fn:(%s, %d)\n", &fn, fn.get(), fn->name_.c_str(), fn->age_);
}
int fun0(char xxxxchr, char mmmm){
    //NPP
    #ifdef PADDR
    fprintf(stderr, "fun0 xxxxchr:%lx %x\n", &xxxxchr, xxxxchr);
    #else
    fprintf(stderr, "fun0 xxxxchr:%x, mmmm:%lx %x\n", xxxxchr, &mmmm, mmmm);
    #endif
    return 1;
}
int fun(const std::string &head, char chr, int xxxxinteger, const std::string &file, uint64_t num, char xxxxnchr){
    //NPP
    #ifdef PADDR
    fprintf(stderr, "head_ptr:%lx, chr:%lx %x, xxxxinteger:%x, file_ptr:%lx, num:%lx, xxxxnchr:%lx %x\n", &head, &chr, chr, xxxxinteger, &file, num, &xxxxnchr, xxxxnchr);
    #else
    fprintf(stderr, "head_ptr:%lx, chr:%x, xxxxinteger:%x, file_ptr:%lx, num:%lx, xxxxnchr:%x\n", &head, chr, xxxxinteger, &file, num, xxxxnchr);
    #endif
    FILE *fl = fopen(file.c_str(), "wb");
    if(fl == NULL){
        return 0;
    }
    fwrite(&num, 1, sizeof(num), fl);
    fclose(fl);
    fprintf(stderr, "enter any key to continue...\n");
    getchar();

    return 1;
}

class ff{
public:
    void process(const ff_node &fn){
        fprintf(stderr, "this:%lx, fn.addr:%lx, fn.get().addr:%lx, fn:(%s, %d)\n", this, &fn, fn.get(), fn->name_.c_str(), fn->age_);
    }
    void process(const std::string &str, uint64_t num, const ff_node &fn, char chr){
        fprintf(stderr, "this:%lx, str.addr:%lx, num:%lx, fn.addr:%lx, fn.get().addr:%lx, fn:(%s, %d), chr:%x\n", this, &str, num, &fn, fn.get(), fn->name_.c_str(), fn->age_, chr);
    }
};

int main(int argc, char **argv){
    if(argc < 3){
        fprintf(stderr, "usage:\n./main file nums(number)\n");
        return 0;
    }
    std::string file = argv[1];
    std::string nums = argv[2];
    // fun
    uint64_t num = 0;
    try{
        num = std::stoll(nums);
    }
    catch(const std::exception &e){
        fprintf(stderr, "usage:\n./main file nums(number)\n");
        return 0;
    }
    int chr = 110;
    boost::thread th0(boost::bind(fun0, chr, 111));
    th0.join();
    //getchar();

    //int integer = 222222222;
    boost::thread th(boost::bind(fun, "oylzyonkenjanetjason", 110, 222222222, file, num, 111));
    th.join();
    //fun("oylzyonkenjanetjason", 110, integer, file, num, 111);
    //getchar();
    // ff
    ff_node fn(new ff_node_n("Jason", 5));
    ff f;
    f.process(fn);

    ff_node nfn(new ff_node_n("Janet", 33));
    ff nf;
    nf.process(nfn);

    ff_node mfn(new ff_node_n("Yonken", 35));
    process(mfn);

    ff_node ofn(new ff_node_n("MM", 99));
    ff of;
    uint64_t nnum = 111;
    of.process("aa", nnum, ofn, 9);

    return 0;
}

max_stars_repo_name: oylz/gperftools

max_issues_repo_name: oylz/gperftools

max_forks_repo_name: oylz/gperftools


text:
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Helmet Software Framework
//
// Copyright (C) 2018 Hat Boy Software, Inc.
//
//  @author Matthew Alan Gray - <mgray@hatboysoftware.com>
//  @author Tony Richards - <trichards@indiezen.com>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#pragma once

#include "Configuration.hpp"

#include <memory>

#include <boost/noncopyable.hpp>

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Helmet {
namespace Enterprise {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~

class HELMET_ENTERPRISE_DLL_LINK I_SessionEvent
:   boost::noncopyable
{
    /// @name Types
    /// @{
public:
    /// @}

    /// @name I_SessionEvent interface.
    /// @{
public:
    /// @}

    /// @name Events
    /// @{
public:
    /// @}

    /// @name 'Structors
    /// @{
protected:
             I_SessionEvent() = default;
    virtual ~I_SessionEvent() = default;
    /// @}

};  // interface I_SessionEvent

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
}   // namespace Enterprise
}   // namespace Helmet
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~

ext: hpp

max_stars_repo_name: hatboysoftware/helmet

max_issues_repo_name: hatboysoftware/helmet

max_forks_repo_name: hatboysoftware/helmet


text:
/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */
/*
 * Copyright (c) 2017-2018 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

#ifndef __VPP_UTIL_H__
#define __VPP_UTIL_H__

#include <opflex/modb/MAC.h>

#include <boost/optional.hpp>

#include <vom/interface.hpp>

using namespace VOM;

namespace VPP
{
const interface::type_t &getIntfTypeFromName(const std::string &name);

boost::optional<mac_address_t>
mac_from_modb(boost::optional<const opflex::modb::MAC &>);
};

/*
 * Local Variables:
 * eval: (c-set-style "llvm.org")
 * End:
 */

#endif

max_stars_repo_name: opflex-vpp/vpp-renderer

max_issues_repo_name: nranns/vpp-renderer

max_forks_repo_name: nranns/vpp-renderer


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

#include <DataDBManager.h>

#include <boost/algorithm/string.hpp>

std::string readEntireRecord(DataRecord record)
{
	std::stringstream buffer;
	buffer << record.input.rdbuf();
	return buffer.str();
}

BOOST_AUTO_TEST_SUITE(DBManagers)

BOOST_AUTO_TEST_SUITE(LineData)

BOOST_AUTO_TEST_CASE(LoadsProperDataCount)
{
    std::stringstream s;
    s << "1;1;1;jajko" << std::endl;
    s << "2;2;2;zupa" << std::endl;

    LineDataDBManager mgr(s, 3);

    auto rec1 = mgr.take();
    BOOST_CHECK_EQUAL("jajko", rec1.className);

    auto rec2 = mgr.take();
    BOOST_CHECK_EQUAL("zupa", rec2.className);

    BOOST_CHECK(!mgr.areRecordsAvailable());
    BOOST_CHECK_THROW(mgr.take(), DataDBManager::NoMoreRecordsException);

    mgr.release(rec1.dbKey);
    mgr.release(rec2.dbKey);
}

BOOST_AUTO_TEST_CASE(LoadsProperDataCountWithOtherOrder)
{
    std::stringstream s;
    s << "jajko;1;1;1" << std::endl;
    s << "zupa;2;2;2" << std::endl;
    s << "okno;4.3;4.4;4.1" << std::endl;

    LineDataDBManager mgr(s, 0);

    char f;
    double a, b, c;

    auto rec1 = mgr.take();
    rec1.input >> a >> f >> b >> f >> c;
    BOOST_CHECK_EQUAL("jajko", rec1.className);
    BOOST_CHECK_CLOSE(1, a, 0.1);
    BOOST_CHECK_CLOSE(1, b, 0.1);
    BOOST_CHECK_CLOSE(1, c, 0.1);

    auto rec2 = mgr.take();
    rec2.input >> a >> f >> b >> f >> c;
    BOOST_CHECK_EQUAL("zupa", rec2.className);
    BOOST_CHECK_CLOSE(2, a, 0.1);
    BOOST_CHECK_CLOSE(2, b, 0.1);
    BOOST_CHECK_CLOSE(2, c, 0.1);

    auto rec3 = mgr.take();
    rec3.input >> a >> f >> b >> f >> c;
    BOOST_CHECK_EQUAL("okno", rec3.className);
    BOOST_CHECK_CLOSE(4.3, a, 0.1);
    BOOST_CHECK_CLOSE(4.4, b, 0.1);
    BOOST_CHECK_CLOSE(4.1, c, 0.1);

    BOOST_CHECK(!mgr.areRecordsAvailable());
    BOOST_CHECK_THROW(mgr.take(), DataDBManager::NoMoreRecordsException);

    mgr.release(rec1.dbKey);
    mgr.release(rec2.dbKey);
    mgr.release(rec3.dbKey);
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE(FileData)

BOOST_AUTO_TEST_CASE(DirThatDoesNotExist)
{
	BOOST_CHECK_THROW(FileDataDBManager dbManager(boost::filesystem::current_path().string() + "\\non_existent_dir", ".txt"), DataDBManager::InvalidPathException);
}

BOOST_AUTO_TEST_CASE(ReleaseNonExistentTrickyDir)
{
	FileDataDBManager dbManager("../../../InstrumentRecognizerTester/test_files/tricky_dir", ".txt");

	BOOST_CHECK_THROW(dbManager.release("0"), AssertException);
}

BOOST_AUTO_TEST_CASE(ClassNameIsFirstPreLastPartOfName)
{
	FileDataDBManager dbManagerOne("../../../InstrumentRecognizerTester/test_files/tree_root/one", ".txt");

	while(dbManagerOne.areRecordsAvailable())
	{
		DataRecord record = dbManagerOne.take();
		BOOST_CHECK_EQUAL(record.className, "one");
		dbManagerOne.release(record.dbKey);
	}

	FileDataDBManager dbManagerTricky("../../../InstrumentRecognizerTester/test_files/tree_root/tricky_dir", ".txt");
	while(dbManagerTricky.areRecordsAvailable())
	{
		DataRecord record = dbManagerTricky.take();
		BOOST_CHECK_EQUAL(record.className, "tricky_dir");
		dbManagerTricky.release(record.dbKey);
	}

}

BOOST_AUTO_TEST_CASE(GetThreeReleaseThreeTrickyDir)
{
	FileDataDBManager dbManager("../../../InstrumentRecognizerTester/test_files/tricky_dir", ".txt");

	while(dbManager.areRecordsAvailable())
	{
		DataRecord record = dbManager.take();
		dbManager.release(record.dbKey);
	}

	BOOST_CHECK_EQUAL(dbManager.filesInBufferCount(), 0);
	BOOST_CHECK_EQUAL(dbManager.dirsInBufferCount(), 0);
	BOOST_CHECK_EQUAL(dbManager.currentlyProcessedCount(), 0);
}

BOOST_AUTO_TEST_CASE(ThreeSubdirsAndNoFilesInTreeRootDir)
{
	FileDataDBManager dbManager("../../../InstrumentRecognizerTester/test_files/tree_root", ".txt");

	BOOST_CHECK_EQUAL(dbManager.filesInBufferCount(), 0);
	BOOST_CHECK_EQUAL(dbManager.dirsInBufferCount(), 3);
}

BOOST_AUTO_TEST_CASE(OneFileToGetThenNewDirectoryThenEmptyException)
{
	FileDataDBManager dbManager("../../../InstrumentRecognizerTester/test_files/single_file_and_single_directory", ".txt");

	BOOST_CHECK_EQUAL(dbManager.dirsInBufferCount(), 1);

	BOOST_CHECK_EQUAL(dbManager.filesInBufferCount(), 1);

	DataRecord firstRecord = dbManager.take();
	BOOST_CHECK_EQUAL(readEntireRecord(firstRecord), "one_and_only");

	BOOST_CHECK_EQUAL(dbManager.filesInBufferCount(), 0);

	DataRecord secondRecord = dbManager.take();
	BOOST_CHECK_EQUAL(readEntireRecord(secondRecord), "second hidden");

	BOOST_CHECK_EQUAL(dbManager.filesInBufferCount(), 0);
	BOOST_CHECK_EQUAL(dbManager.dirsInBufferCount(), 0);

	BOOST_CHECK_EQUAL(dbManager.currentlyProcessedCount(), 2);
	BOOST_CHECK_THROW(dbManager.take(), DataDBManager::NoMoreRecordsException);

	dbManager.release(firstRecord.dbKey);
	dbManager.release(secondRecord.dbKey);
}

BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Lewerow/InstrumentRecognizer

max_issues_repo_name: Lewerow/InstrumentRecognizer

max_forks_repo_name: Lewerow/InstrumentRecognizer


text:
#include <boost/program_options.hpp>
#include <chi/Context.hpp>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

extern int get(const std::vector<std::string>& opts);

namespace po = boost::program_options;
namespace fs = std::filesystem;

int init(const std::vector<std::string>& opts) {
	po::options_description init_ops("init options");
	init_ops.add_options()("no-hello-world", "Do not fetch the hello world module");

	auto options = po::command_line_parser(opts).options(init_ops).run();

	auto workspacePath = chi::workspaceFromChildPath(fs::current_path());
	if (!workspacePath.empty()) {
		std::cerr << "Already in a chigraph workspace! Exiting..." << std::endl;
		return 1;
	}

	// make the chigraph workspace file
	{ std::ofstream workspacefile(".chigraphworkspace"); }

	// create the src/ directory
	fs::create_directory("src");

	// get the hellochigrpah module
	return get({"github.com/chigraph/hellochigraph/hello/main"});
}

max_stars_repo_name: edowson/chigraph

max_issues_repo_name: GuapoTaco/chigraph

max_forks_repo_name: GuapoTaco/chigraph


text:
// The MIT License
// (c) 2019 Daniel Williams

#include <memory>
#include <string>
#include <iostream>

#include <Eigen/Geometry>

#include "geometry/cell_value.hpp"
#include "geometry/sample.hpp"

using std::cerr;
using std::endl;
using std::make_unique;
using std::string;
using std::unique_ptr;

using Eigen::Vector2d;

namespace terrain::geometry {

cell_value_t interpolate_linear(const Eigen::Vector2d& to, const Sample& s1, const Sample& s2){
    if(s1.at.isApprox(s2.at)){
        return s1.is;
    }

    // distances from query point to each interpolation point
    const double dist1 = (s1.at - to).norm();
    const double dist2 = (s2.at - to).norm();

    // If the point is farther than from a point than the distance between the two interpolation points,
    //     return the value at one of the end-points.
    // This is not perfect, but it's a reasonable heuristic.
    // ... in particular, it will return odd values at large distances
    // ... arguably, this should return a NAN value instead -- for not-applicable
    const double dist12 = (s1.at - s2.at).norm();
    if(dist12 < dist1){
        return s2.is;
    }else if( dist12 < dist2){
        return s1.is;
    }

    const double combined_distance = dist1 + dist2;
    const double normdist1 = 1 - dist1 / combined_distance;
    const double normdist2 = 1 - dist2 / combined_distance;
    const double interp_value = (normdist1*s1.is + normdist2*s2.is);

    return round(interp_value);
}

cell_value_t interpolate_bilinear(  const Eigen::Vector2d& to,
                                    const Sample& ne,
                                    const Sample& nw,
                                    const Sample& sw,
                                    const Sample& se)
{
    // cerr << "    ==>>  to:    @" << to[0] << ", " << to[1] << endl;
    // cerr << "        - NE:     " << ne.at[0] << ", " << ne.at[1] << " = " << (int)ne.is << endl;
    // cerr << "        - NW:     " << nw.at[0] << ", " << nw.at[1] << " = " << (int)nw.is << endl;
    // cerr << "        - SW:     " << sw.at[0] << ", " << sw.at[1] << " = " << (int)sw.is << endl;
    // cerr << "        - SE:     " << se.at[0] << ", " << se.at[1] << " = " << (int)se.is << endl;

    // not necessary ?
    // // test for degenerate cases:
    // if( &sx == &sd ){
    //     // top or bottom border
    //     return interpolate_linear(to, {to[0], xn.at[1]}, xn);
    // }else if( &sy  == &sd ){
    //     // left or right border
    //     return interpolate_linear({yn[0], to[1]}, yn);
    // }

    // calculate full bilinear interpolation:
    const Eigen::Vector2d upper_point = {to[0], (nw.at[1] + ne.at[1])/2};
    const Sample upper_sample = { upper_point,
                                  interpolate_linear(upper_point, nw, ne)};

    const Eigen::Vector2d lower_point = {to[0], (sw.at[1] + se.at[1])/2};
    const Sample lower_sample = { lower_point,
                                interpolate_linear(lower_point, sw, se) };

    // cerr << "        ::Upper:    " << upper_point[0] << ", " << upper_point[1] << " = " << (int)upper_sample.is << endl;
    // cerr << "        ::Lower:    " << lower_point[0] << ", " << lower_point[1] << " = " << (int)lower_sample.is << endl;

    return interpolate_linear(to, upper_sample, lower_sample);
}

} // namespace terrain::geometry

max_stars_repo_name: teyrana/quadtree

max_issues_repo_name: teyrana/quadtree

max_forks_repo_name: teyrana/quadtree


text:
/*
    Copyright (c) 2022 Xavier Leclercq
    Released under the MIT License
    See https://github.com/nemu-cpp/web-framework/blob/main/LICENSE.txt
*/

#ifndef _NEMU_CPP_WEBFRAMEWORK_REQUESTHANDLERS_VIEWWEBREQUESTHANDLER_HPP_
#define _NEMU_CPP_WEBFRAMEWORK_REQUESTHANDLERS_VIEWWEBREQUESTHANDLER_HPP_

#include "../MapViewContext.hpp"
#include "../WebRequestHandler.hpp"
#include <boost/optional.hpp>
#include <Ishiko/Errors.hpp>
#include <string>

namespace Nemu
{

// TODO: in the end this has become quite complex with the callbacks to implement and in the end we are only calling
// responsebuilder.view and holding a view context. If developer is coding this he might as well make his own class
// it will be easier than implementing the callbacks, but derivation from the class might be a good option. And where
// this class will be needed is when it is used in a declarative configuration (which seems to be the
// seems to be a suitable role for the DeclarativeCallbacks class).
class ViewWebRequestHandler : public WebRequestHandler
{
public:
    class Callbacks
    {
    public:
        virtual ~Callbacks() = default;

        virtual boost::optional<std::string> getProfile(const WebRequest& request, Ishiko::Error& error);
        virtual boost::optional<std::string> getLayout(const WebRequest& request, Ishiko::Error& error);
        virtual std::string getView(const WebRequest& request, Ishiko::Error& error) = 0;

        // TODO: ultimately this is what I want I think but until I make ViewContext an interface this would involve
        // too much copying
        //virtual ViewContext getContext(const WebRequest& request, Ishiko::Error& error) const = 0;
    };

    // TODO: this is in fact a mixin.
    // TODO: should be called something with "View" in it beacuse it only implements getView
    // TODO: the most basic case would be to remove the leading '/' to make it a relative path. Should I make this the
    // default constructor?
    class PrefixMappingCallbacks : public Callbacks
    {
    public:
        PrefixMappingCallbacks(std::string urlPathPrefix, std::string contentPrefix);

        std::string getView(const WebRequest& request, Ishiko::Error& error) override;

    private:
        // If the URL path starts with hm_urlPathPrefix then the m_urlPathPrefix prefix will be removed and replaced by
        //  the value of m_contentPrefix. If m_urlPathPrefix is empty then the value of m_contentPrefix will always be
        // preprended to the URL path. Both m_urlPathPrefix and m_contentPrefix can be empty.
        std::string m_urlPathPrefix;
        std::string m_contentPrefix;
    };

    class DeclarativeCallbacks : public PrefixMappingCallbacks
    {
    public:
        DeclarativeCallbacks(const char* profile, const char* layout, const char* urlPathPrefix,
            const char* contentPrefix);
        DeclarativeCallbacks(boost::optional<std::string> profile, boost::optional<std::string> layout,
            std::string urlPathPrefix, std::string contentPrefix);

        boost::optional<std::string> getProfile(const WebRequest& request, Ishiko::Error& error) override;
        boost::optional<std::string> getLayout(const WebRequest& request, Ishiko::Error& error) override;

    private:
        boost::optional<std::string> m_profile;
        boost::optional<std::string> m_layout;
    };

    ViewWebRequestHandler(Callbacks& callbacks);

    void run(const WebRequest& request, WebResponseBuilder& response, Ishiko::Logger& logger) override;

    const MapViewContext& context() const noexcept;
    MapViewContext& context() noexcept;

private:
    Callbacks& m_callbacks;
    MapViewContext m_context;
};

}

#endif

max_stars_repo_name: nemu-cpp/web-server

max_issues_repo_name: nemu-cpp/web-server

max_forks_repo_name: nemu-cpp/web-server


text:
// Copyright (c) James Percent and Unlock contributors.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//    1. Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//
//    2. Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//    3. Neither the name of Unlock nor the names of its contributors may be used
//       to endorse or promote products derived from this software without
//       specific prior written permission.

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

#include <boost/assert.hpp>
#include <algorithm>
#include <iostream>

#include "NonblockingSignal.hpp"
#include "AsyncSampleCollector.hpp"

using namespace std;
using namespace boost;
using namespace boost::lockfree;

NonblockingSignal::NonblockingSignal(ISignal* pSignal) : mpSignal(pSignal), mpProducerSamples(0), mpConsumerSamples(0), mpSampleRingBuffer(0), mpQueue(0), mpWorkController(0), mpAsyncSampleCollector(0) {
  BOOST_VERIFY(mpSignal != 0);
  // XXX - these should be injected
  mpProducerSamples = new Sample<uint32_t>[NonblockingSignal::SAMPLE_BUFFER_SIZE];
  mpConsumerSamples = new Sample<uint32_t>[NonblockingSignal::SAMPLE_BUFFER_SIZE];
  mpSampleRingBuffer = new SampleBuffer<uint32_t>();
  mpQueue = new spsc_queue<Sample<uint32_t> > (NonblockingSignal::SAMPLE_BUFFER_SIZE-1);
  mpWorkController = new ManagedWorkController(false);
  BOOST_VERIFY(mpQueue != 0);
  BOOST_VERIFY(mpProducerSamples != 0);
  BOOST_VERIFY(mpConsumerSamples != 0);
  BOOST_VERIFY(mpSampleRingBuffer != 0);
  BOOST_VERIFY(mpWorkController != 0 && !mpWorkController->doWork());
}

NonblockingSignal::NonblockingSignal(const NonblockingSignal& copy)
  : mpSignal(copy.mpSignal), mpProducerSamples(copy.mpProducerSamples), mpConsumerSamples(copy.mpConsumerSamples),
    mpSampleRingBuffer(copy.mpSampleRingBuffer), mpQueue(copy.mpQueue), mpWorkController(copy.mpWorkController),
    mpAsyncSampleCollector(copy.mpAsyncSampleCollector)
{
}

NonblockingSignal::~NonblockingSignal()  {
  BOOST_VERIFY(mpWorkController != 0);
  if (mpWorkController->doWork()) {
    waitForAsyncCollector();
  }

  if(mpAsyncSampleCollector != 0) {
    mpWorkController->setDoWorkState(false);
    mpAsyncSampleCollector->join();
    delete mpAsyncSampleCollector;
    mpAsyncSampleCollector = 0;
  }

  delete mpSignal;
  delete[] mpProducerSamples;
  delete[] mpConsumerSamples;
  delete mpSampleRingBuffer;
  delete mpQueue;
  delete mpWorkController;

  mpSignal=0;
  mpProducerSamples=0;
  mpConsumerSamples=0;
  mpSampleRingBuffer=0;
  mpQueue=0;
  mpWorkController=0;
}

NonblockingSignal& NonblockingSignal::operator=(const NonblockingSignal& other)
{
  mpSignal = other.mpSignal;
  mpProducerSamples = other.mpProducerSamples;
  mpConsumerSamples = other.mpConsumerSamples;
  mpSampleRingBuffer = other.mpSampleRingBuffer;
  mpQueue = other.mpQueue;
  mpWorkController = other.mpWorkController;
  mpAsyncSampleCollector = other.mpAsyncSampleCollector;
  return *this;
}

bool NonblockingSignal::open(uint8_t* pMacAddress) {
  BOOST_VERIFY(mpSignal != 0);
  return mpSignal->open(pMacAddress);
}

bool NonblockingSignal::init(size_t channels) {
  BOOST_VERIFY(mpSignal != 0);
  return mpSignal->init(channels);
}

size_t NonblockingSignal::channels() {
  BOOST_VERIFY(mpSignal != 0);
  return mpSignal->channels();
}

bool NonblockingSignal::start()  {
  BOOST_VERIFY(mpSignal != 0);
  waitForAsyncCollector();
  bool ret = mpSignal->start();
  if(ret) {
    BOOST_VERIFY(mpAsyncSampleCollector == 0);
    mpWorkController->setDoWorkState(true);
    mpAsyncSampleCollector = new thread(AsyncSampleCollector(mpSignal, (boost::lockfree::spsc_queue<Sample<uint32_t> >*)mpQueue,
							     mpWorkController, mpProducerSamples, NonblockingSignal::SAMPLE_BUFFER_SIZE, mpSampleRingBuffer));
  }
  return ret;
}

size_t NonblockingSignal::acquire()  {
  BOOST_VERIFY(mpWorkController != 0);
  BOOST_VERIFY(mpQueue != 0);

  if (!mpWorkController->doWork()) {
    // XXX - setup logging.
    cerr << "NonblockingSignal.acquire: WARNING acquire called when device not started; returning 0"
         << endl;
    return 0;
  }
  size_t count = 0;
  size_t samples = 0;
  while(count < NonblockingSignal::SAMPLE_BUFFER_SIZE && mpQueue->pop(mpConsumerSamples[count])) {
    samples += mpConsumerSamples[count].length();
    count++;
  }

  if (samples > 0) {
//    cout << "Nonblocking signal. acquire samples = " << samples << " index = " << count << endl;
  }
  return samples;
}

void NonblockingSignal::getdata(uint32_t* buffer, size_t samples)  {
  BOOST_VERIFY(mpWorkController != 0);
  BOOST_VERIFY(mpConsumerSamples != 0);
  if (!mpWorkController->doWork()) {
    cerr << "NonblockingSignal.getdata: WARNING getdata called with " << buffer << ":"
         <<  samples << " when device not started; not copying any data" << endl;
    return;
  }

  if (samples > NonblockingSignal::SAMPLE_BUFFER_SIZE) {
    samples = NonblockingSignal::SAMPLE_BUFFER_SIZE;
    cerr << "NonblockingSignal.getdata: WARNING requested " << samples << ", which is more samples than can be held; returning " << NonblockingSignal::SAMPLE_BUFFER_SIZE << " samples " << endl;
  }

  for (int sample=0, pos=0; ; pos++) {
    uint32_t* pSample = mpConsumerSamples[pos].sample();
    size_t sample_count = mpConsumerSamples[pos].length();
    if (sample+sample_count > samples) {
      cerr << "NonblockingSignal.getdata: WARNING " << sample+sample_count << " available, but only " << samples << " requested; only returning available samples " << pos << endl;
      sample_count = samples - sample;
    }
    std::copy(pSample, pSample+sample_count, buffer);
    sample += sample_count;
    if(sample < samples) {
      buffer += sample_count;
    } else {
      break;
    }
  }
}

uint64_t NonblockingSignal::timestamp()  {
  BOOST_VERIFY(mpSignal != 0);
  return mpSignal->timestamp();
}

bool NonblockingSignal::stop()  {
  BOOST_VERIFY(mpSignal != 0);
  waitForAsyncCollector();
  bool ret = mpSignal->stop();
  return ret;
}

bool NonblockingSignal::close()  {
  BOOST_VERIFY(mpSignal != 0);
  return mpSignal->close();
}

void NonblockingSignal::waitForAsyncCollector() {
  BOOST_VERIFY(mpWorkController != 0);
  if(mpWorkController->doWork()) {
    mpWorkController->setDoWorkState(false);
  }

  if(mpAsyncSampleCollector != 0) {
    mpAsyncSampleCollector->join();
    delete mpAsyncSampleCollector;
    mpAsyncSampleCollector = 0;
  }
}

max_stars_repo_name: NeuralProsthesisLab/unlock

max_issues_repo_name: NeuralProsthesisLab/unlock

max_forks_repo_name: NeuralProsthesisLab/unlock


text:
/* boost random/independent_bits.hpp header file
 *
 * Copyright Steven Watanabe 2011
 * 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)
 *
 * See http://www.boost.org for most recent version including documentation.
 *
 * $Id: independent_bits.hpp 71018 2011-04-05 21:27:52Z steven_watanabe $
 *
 */

#ifndef BOOST_RANDOM_INDEPENDENT_BITS_HPP
#define BOOST_RANDOM_INDEPENDENT_BITS_HPP

#include <istream>
#include <iosfwd>
#include <boost/assert.hpp>
#include <boost/limits.hpp>
#include <boost/config.hpp>
#include <boost/cstdint.hpp>
#include <boost/integer/integer_mask.hpp>
#include <boost/type_traits/make_unsigned.hpp>
#include <boost/random/detail/config.hpp>
#include <boost/random/detail/integer_log2.hpp>
#include <boost/random/detail/operators.hpp>
#include <boost/random/detail/seed.hpp>
#include <boost/random/detail/seed_impl.hpp>
#include <boost/random/detail/signed_unsigned_tools.hpp>

namespace boost {
namespace random {

/**
 * An instantiation of class template @c independent_bits_engine
 * model a \pseudo_random_number_generator.  It generates random
 * numbers distributed between [0, 2^w) by combining one or
 * more invocations of the base engine.
 *
 * Requires: 0 < w <= std::numeric_limits<UIntType>::digits
 */
template<class Engine, std::size_t w, class UIntType>
class independent_bits_engine
{
public:
    typedef Engine base_type;
    typedef UIntType result_type;

    // Required by old Boost.Random concept
    BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);

    /** Returns the smallest value that the generator can produce. */
    static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()
    { return 0; }
    /** Returns the largest value that the generator can produce. */
    static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()
    { return boost::low_bits_mask_t<w>::sig_bits; }

    /**
     * Constructs an @c independent_bits_engine using the
     * default constructor of the base generator.
     */
    independent_bits_engine() { }

    /**
     * Constructs an @c independent_bits_engine, using seed as
     * the constructor argument for both base generators.
     */
    BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(independent_bits_engine,
        result_type, seed_arg)
    {
        _base.seed(seed_arg);
    }

    /**
     * Constructs an @c independent_bits_engine, using seq as
     * the constructor argument for the base generator.
     */
    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(independent_bits_engine,
        SeedSeq, seq)
    { _base.seed(seq); }

    /** Constructs an @c independent_bits_engine by copying @c base. */
    independent_bits_engine(const base_type& base_arg) : _base(base_arg) {}

    /**
     * Contructs an @c independent_bits_engine with
     * values from the range defined by the input iterators first
     * and last.  first will be modified to point to the element
     * after the last one used.
     *
     * Throws: @c std::invalid_argument if the input range is too small.
     *
     * Exception Safety: Basic
     */
    template<class It>
    independent_bits_engine(It& first, It last) : _base(first, last) { }

    /**
     * Seeds an @c independent_bits_engine using the default
     * seed of the base generator.
     */
    void seed() { _base.seed(); }

    /**
     * Seeds an @c independent_bits_engine, using @c seed as the
     * seed for the base generator.
     */
    BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(independent_bits_engine,
        result_type, seed_arg)
    { _base.seed(seed_arg); }

    /**
     * Seeds an @c independent_bits_engine, using @c seq to
     * seed the base generator.
     */
    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(independent_bits_engine,
        SeedSeq, seq)
    { _base.seed(seq); }

    /**
     * Seeds an @c independent_bits_engine with
     * values from the range defined by the input iterators first
     * and last.  first will be modified to point to the element
     * after the last one used.
     *
     * Throws: @c std::invalid_argument if the input range is too small.
     *
     * Exception Safety: Basic
     */
    template<class It> void seed(It& first, It last)
    { _base.seed(first, last); }

    /** Returns the next value of the generator. */
    result_type operator()()
    {
        // While it may seem wasteful to recalculate this
        // every time, both msvc and gcc can propagate
        // constants, resolving this at compile time.
        base_unsigned range =
            detail::subtract<base_result>()((_base.max)(), (_base.min)());
        std::size_t m =
            (range == (std::numeric_limits<base_unsigned>::max)()) ?
                std::numeric_limits<base_unsigned>::digits :
                detail::integer_log2(range + 1);
        std::size_t n = (w + m - 1) / m;
        std::size_t w0, n0;
        base_unsigned y0, y1;
        base_unsigned y0_mask, y1_mask;
        calc_params(n, range, w0, n0, y0, y1, y0_mask, y1_mask);
        if(base_unsigned(range - y0 + 1) > y0 / n) {
            // increment n and try again.
            ++n;
            calc_params(n, range, w0, n0, y0, y1, y0_mask, y1_mask);
        }

        BOOST_ASSERT(n0*w0 + (n - n0)*(w0 + 1) == w);

        result_type S = 0;
        for(std::size_t k = 0; k < n0; ++k) {
            base_unsigned u;
            do {
                u = detail::subtract<base_result>()(_base(), (_base.min)());
            } while(u > base_unsigned(y0 - 1));
            S = (S << w0) + (u & y0_mask);
        }
        for(std::size_t k = 0; k < (n - n0); ++k) {
            base_unsigned u;
            do {
                u = detail::subtract<base_result>()(_base(), (_base.min)());
            } while(u > base_unsigned(y1 - 1));
            S = (S << (w0 + 1)) + (u & y1_mask);
        }
        return S;
    }

    /** Fills a range with random values */
    template<class Iter>
    void generate(Iter first, Iter last)
    { detail::generate_from_int(*this, first, last); }

    /** Advances the state of the generator by @c z. */
    void discard(boost::uintmax_t z)
    {
        for(boost::uintmax_t i = 0; i < z; ++i) {
            (*this)();
        }
    }

    const base_type& base() const { return _base; }

    /**
     * Writes the textual representation if the generator to a @c std::ostream.
     * The textual representation of the engine is the textual representation
     * of the base engine.
     */
    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, independent_bits_engine, r)
    {
        os << r._base;
        return os;
    }

    /**
     * Reads the state of an @c independent_bits_engine from a
     * @c std::istream.
     */
    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, independent_bits_engine, r)
    {
        is >> r._base;
        return is;
    }

    /**
     * Returns: true iff the two @c independent_bits_engines will
     * produce the same sequence of values.
     */
    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(independent_bits_engine, x, y)
    { return x._base == y._base; }
    /**
     * Returns: true iff the two @c independent_bits_engines will
     * produce different sequences of values.
     */
    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(independent_bits_engine)

private:

    /// \cond show_private
    typedef typename base_type::result_type base_result;
    typedef typename make_unsigned<base_result>::type base_unsigned;

    void calc_params(
        std::size_t n, base_unsigned range,
        std::size_t& w0, std::size_t& n0,
        base_unsigned& y0, base_unsigned& y1,
        base_unsigned& y0_mask, base_unsigned& y1_mask)
    {
        BOOST_ASSERT(w >= n);
        w0 = w/n;
        n0 = n - w % n;
        y0_mask = (base_unsigned(2) << (w0 - 1)) - 1;
        y1_mask = (y0_mask << 1) | 1;
        y0 = (range + 1) & ~y0_mask;
        y1 = (range + 1) & ~y1_mask;
        BOOST_ASSERT(y0 != 0 || base_unsigned(range + 1) == 0);
    }
    /// \endcond

    Engine _base;
};

#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
template<class Engine, std::size_t w, class UIntType>
const bool independent_bits_engine<Engine, w, UIntType>::has_fixed_range;
#endif

} // namespace random
} // namespace boost

#endif // BOOST_RANDOM_INDEPENDENT_BITS_HPP


text:
//
// Copyright 2005-2007 Adobe Systems Incorporated
//
// 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_GIL_GRAY_HPP
#define BOOST_GIL_GRAY_HPP

#include <boost/mpl/range_c.hpp>
#include <boost/mpl/vector_c.hpp>
#include <boost/type_traits.hpp>

#include <boost/gil/utilities.hpp>

namespace boost { namespace gil {

/// \ingroup ColorNameModel
/// \brief Gray
struct gray_color_t {};

/// \ingroup ColorSpaceModel
using gray_t = mpl::vector1<gray_color_t>;

/// \ingroup LayoutModel
using gray_layout_t = layout<gray_t>;

} }  // namespace boost::gil

#endif

max_stars_repo_name: Netis/packet-agent

max_issues_repo_name: Netis/packet-agent

max_forks_repo_name: Netis/packet-agent


text:
#pragma once
#include <vector>
#include <map>
#include <memory>

#include "Variable.hpp"

#include "PysimTypes.hpp"

#include "boost/variant.hpp"

#include <Eigen/Dense>

namespace pysim {

struct VariablePrivate{
    std::map<std::string, double* > scalars;
    std::vector<std::string> scalarNames;
    std::map<std::string, pysim::vector* > vectors;
    std::vector<std::string> vectorNames;
    std::map<std::string, pysim::matrix* > matrices;
    std::vector<std::string> matrixNames;
    std::map<std::string, std::string> descriptions;
};

}

max_stars_repo_name: sspasweden/pysim

max_issues_repo_name: sspasweden/pysim

max_forks_repo_name: sspasweden/pysim


text:
// Copyright Eric Crampton, 2014.
// 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 meridian__core__event_source__hpp
#define meridian__core__event_source__hpp

#include <boost/intrusive/unordered_set.hpp>
#include <boost/intrusive/unordered_set_hook.hpp>
#include <functional>

namespace meridian {
namespace core {

struct event_source_tag;

//! \brief Intrusive hashtable base hook for event_source.
typedef boost::intrusive::unordered_set_base_hook<boost::intrusive::tag<event_source_tag>>
event_source_base_hook;

//! \brief Represents a file descriptor which can be monitored for events.
//! \class event_source event_source.hpp meridian/core/event_source.hpp
//!
//! The file descriptor can be associated with any kinds of monitorable entity (e.g., sockets, pipes, an inotify (Linux)
//! instance, etc.). The event_source is a object which can be intrusively placed into a hashtable (an
//! event_source_unordered_set) which manages association with the OS file descriptor. An event_source tracks the
//! callback, if any, associated with each of the monitorable events: readable, writable, and exception.
//!
//! Associating a callback with a monitorable event cannot be done directly on the event_source. You must use a reactor,
//! such as the meridian::reactor::select_reactor. Often, a reactor will have work to be done each time an event_source
//! callback is registered, so registration must be done via functions on that reactor.
//!
//! \author Eric Crampton

class event_source : public event_source_base_hook {
protected:
    //! \brief Construction.
    //!
    //! \param fd - the OS file descriptor
    //!
    //! The file descriptor @a may be an invalid file descriptor (e.g., -1). However, it must be reset using
    //! reset_fd(int) before any attempts are made to register a callback.

    event_source(int fd);

    //! \brief Reset the OS file descriptor associated with this event_source.
    //!
    //! \param fd - the new OS file descriptor
    //!
    //! This function may not be called if this event_source has any callbacks associated with it.

    inline void reset_fd(int fd);

public:
    //! \brief Callback function type.
    //!
    //! Note that this function takes no parameters and returns @c void. If you would like to have data associated with
    //! a callback at registration time, the recommended method is to use @c std::bind to pass the data. There are
    //! numerous examples distributed with Meridian which show this.

    typedef std::function<void ()> event_callback;

    //! \brief Return the callback for the readable event, if any.
    //!
    //! \return the callback, or an empty function if no callback is associated

    inline event_callback read_callback() const;

    //! \brief Return the callback for the writable event, if any.
    //!
    //! \return the callback, or an empty function if no callback is associated

    inline event_callback write_callback() const;

    //! \brief Return the callback for the exception event, if any.
    //!
    //! \return the callback, or an empty function if no callback is associated

    inline event_callback except_callback() const;

    //! \brief Returns true if this event_source has any registered callbacks.

    inline bool has_callback() const;

    //! \brief Returns the OS file descriptor for this event_source.

    inline int fd() const;

    //! \brief Equality operator for two \ref event_source "event_source"s.
    //!
    //! This is used in the creation of the Boost Intrusive hashtable which holds \ref event_source "event_source"s by
    //! file descriptor.

    struct equal {
        inline bool operator()(event_source const & lhs, event_source const & rhs) const;
    };

    //! \brief Hashing function for an event_source.
    //!
    //! This is used in the creation of the Boost Intrusive hashtable which holds \ref event_source "event_source"s by
    //! file descriptor.

    struct hash {
        inline size_t operator()(event_source const & source) const;
    };

private:
    friend class event_source_registry;

    //! \brief Sets the readable callback for this event_source.
    //!
    //! \param callback - the callback
    //!
    //! Overwrites any previously set readable callback.

    inline void set_read_callback(event_callback callback);

    //! \brief Sets the writable callback for this event_source.
    //!
    //! \param callback - the callback
    //!
    //! Overwrites any previously set writable callback.

    inline void set_write_callback(event_callback callback);

    //! \brief Sets the exception callback for this event_source.
    //!
    //! \param callback - the callback
    //!
    //! Overwrites any previously set exception callback.

    inline void set_except_callback(event_callback callback);

    //! \brief Removes the readable callback for this event_source.
    //!
    //! This is more readable than calling set_read_callback with an empty function.

    inline void remove_read_callback();

    //! \brief Removes the writable callback for this event_source.
    //!
    //! This is more readable than calling set_write_callback with an empty function.

    inline void remove_write_callback();

    //! \brief Removes the exception callback for this event_source.
    //!
    //! This is more readable than calling set_except_callback with an empty function.

    inline void remove_except_callback();

private:
    int fd_;
    event_callback read_callback_;
    event_callback write_callback_;
    event_callback except_callback_;
};

//! \brief An intrusive hashtable mapping file descriptors to \ref event_source "event_source"s.
typedef boost::intrusive::unordered_set<
    event_source,
    boost::intrusive::base_hook<event_source_base_hook>,
    boost::intrusive::equal<event_source::equal>,
    boost::intrusive::hash<event_source::hash>
    >
event_source_unordered_set;

#include "event_source.ipp"

} // namespace core
} // namespace meridian

#endif /* meridian__core__event_source__hpp */

max_stars_repo_name: yggchan/meridian

max_issues_repo_name: yggchan/meridian

max_forks_repo_name: yggchan/meridian


text:
#ifndef CLUSTERPARAMS_HPP
#define CLUSTERPARAMS_HPP

#include <string>

#ifdef RCPP_INTERFACE
#include <RcppArmadillo.h>
using namespace Rcpp;
using namespace arma;
#else
#include <armadillo>
using namespace arma;
#endif

namespace gmum {

	enum ClusterType {
		kstandard, kfixed_covariance, kdiagonal, kfixed_spherical, kspherical, kno_type, kmix, kcustom
	};

/**
 * You need to store somewhere data about cluster. Each type can have its own.
 */
	struct ClusterParams {
		ClusterType type;
		ClusterParams(ClusterType _type) :
				type(_type) {
		}
		virtual ~ClusterParams() { };
	};

	struct ClusterFixedCovarianceParams : public ClusterParams {
		bool cov_mat_set;
		mat cov_mat;
		ClusterFixedCovarianceParams(mat _cov_mat) :
				ClusterParams(kfixed_covariance), cov_mat_set(true), cov_mat(_cov_mat) {
		}
		ClusterFixedCovarianceParams() :
				ClusterParams(kfixed_covariance), cov_mat_set(false) {
		}
		virtual ~ClusterFixedCovarianceParams() { }
	};

	struct ClusterSphericalFixedRParams : public ClusterParams {
		bool radius_set;
		double radius;
		ClusterSphericalFixedRParams(double _radius) :
				ClusterParams(kfixed_spherical), radius_set(true), radius(_radius) {
		}
		ClusterSphericalFixedRParams() :
				ClusterParams(kfixed_spherical), radius_set(false) {
		}
		virtual ~ClusterSphericalFixedRParams() { }
	};

#ifdef RCPP_INTERFACE
	struct ClusterCustomParams: public ClusterParams {
		boost::shared_ptr<Rcpp::Function> function;
		ClusterCustomParams(boost::shared_ptr<Rcpp::Function> _function) : ClusterParams(kcustom), function(_function) {}
		ClusterCustomParams() : ClusterParams(kcustom) {}
		virtual ~ClusterCustomParams() { }
	};
#endif

}

#endif


text:
#ifndef BOOST_STATECHART_TERMINATION_HPP_INCLUDED
#define BOOST_STATECHART_TERMINATION_HPP_INCLUDED
//////////////////////////////////////////////////////////////////////////////
// Copyright 2002-2006 Andreas Huber Doenni
// Distributed under the Boost Software License, Version 1.0. (See accompany-
// ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//////////////////////////////////////////////////////////////////////////////

#include <boost/statechart/result.hpp>

namespace boost
{
namespace statechart
{

class event_base;

//////////////////////////////////////////////////////////////////////////////
template< class Event >
class termination
{
  public:
    //////////////////////////////////////////////////////////////////////////
    // The following declarations should be private.
    // They are only public because many compilers lack template friends.
    //////////////////////////////////////////////////////////////////////////
    template< class State, class EventBase, class IdType >
    static detail::reaction_result react(
      State & stt, const EventBase &, const IdType & eventType )
    {
      if ( eventType == Event::static_type() )
      {
        return detail::result_utility::get_result( stt.terminate() );
      }
      else
      {
        return detail::no_reaction;
      }
    }
};

template<>
class termination< event_base >
{
  public:
    //////////////////////////////////////////////////////////////////////////
    // The following declarations should be private.
    // They are only public because many compilers lack template friends.
    //////////////////////////////////////////////////////////////////////////
    template< class State, class EventBase, class IdType >
    static detail::reaction_result react(
      State & stt, const EventBase &, const IdType & )
    {
      return detail::result_utility::get_result( stt.terminate() );
    }
};

} // namespace statechart
} // namespace boost

#endif

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
/**
 * @file
 * @brief Interface for MNIST image file parsers.
 * @author Arno Bastenhof
 */

#ifndef IMG_PARSER_HPP_
#define IMG_PARSER_HPP_

#include <armadillo>

#include "mnist_parser.hpp"

namespace mnist {

class ImageParser : public MnistParser<arma::Mat<uint8_t>> {
public:
  explicit              ImageParser(const char *);
                        ImageParser(const ImageParser&) = delete;
                        ImageParser(ImageParser&&) = delete;
  ImageParser&          operator=(const ImageParser&) = delete;
  arma::Mat<uint8_t>    Parse() override;
private:
  int                   num_row_;
  int                   num_col_;
  uint8_t               buffer_[kImageSize];
};

} // namespace mnist

#endif // IMG_PARSER_HPP_

max_stars_repo_name: deryger/mnist

max_issues_repo_name: deryger/mnist

max_forks_repo_name: deryger/mnist