text:
#include <iostream>

#define BOOST_TEST_MODULE
#include <boost/test/included/unit_test.hpp>

#include <bluetoe/security_manager.hpp>

#include "test_sm.hpp"

template < class Manager, std::size_t MTU = 27 >
using sm = test::security_manager< Manager, MTU >;

BOOST_FIXTURE_TEST_SUITE( invalid_pairing_requests, sm< bluetoe::security_manager > )

    BOOST_AUTO_TEST_CASE( empty_request )
    {
        expected(
            {
            },
            {
                0x05,           // Pairing Failed
                0x0A            // Invalid Parameters
            }
        );
    }

    BOOST_AUTO_TEST_CASE( invalid_opcode )
    {
        expected(
            {
                0x55
            },
            {
                0x05,           // Pairing Failed
                0x07            // Command Not Supported
            }
        );
    }

    BOOST_AUTO_TEST_CASE( no_parameters )
    {
        expected(
            {
                0x01            // Pairing Request
            },
            {
                0x05,           // Pairing Failed
                0x0A            // Invalid Parameters
            }
        );
    }

    BOOST_AUTO_TEST_CASE( invalid_IO_Capability )
    {
        expected(
            {
                0x01,           // Pairing Request
                0x05,           // IO Capability RFU
                0x00,           // OOB data flag (data not present)
                0x00,           // AuthReq
                0x10,           // Maximum Encryption Key Size (16)
                0x00,           // Initiator Key Distribution
                0x00,           // Responder Key Distribution

            },
            {
                0x05,           // Pairing Failed
                0x0A            // Invalid Parameters
            }
        );
    }

    BOOST_AUTO_TEST_CASE( invalid_OOB_data_flag )
    {
        expected(
            {
                0x01,           // Pairing Request
                0x03,           // IO Capability NoInputNoOutput
                0x02,           // OOB data flag (RFU)
                0x00,           // AuthReq
                0x10,           // Maximum Encryption Key Size (16)
                0x00,           // Initiator Key Distribution
                0x00,           // Responder Key Distribution

            },
            {
                0x05,           // Pairing Failed
                0x0A            // Invalid Parameters
            }
        );
    }

    BOOST_AUTO_TEST_CASE( invalid_AuthReq )
    {
        expected(
            {
                0x01,           // Pairing Request
                0x03,           // IO Capability NoInputNoOutput
                0x00,           // OOB data flag (data not present)
                0x80,           // AuthReq (RFU)
                0x10,           // Maximum Encryption Key Size (16)
                0x00,           // Initiator Key Distribution
                0x00,           // Responder Key Distribution

            },
            {
                0x05,           // Pairing Failed
                0x0A            // Invalid Parameters
            }
        );
    }

    BOOST_AUTO_TEST_CASE( invalid_Encryption_Key_Size )
    {
        expected(
            {
                0x01,           // Pairing Request
                0x03,           // IO Capability NoInputNoOutput
                0x00,           // OOB data flag (data not present)
                0x00,           // AuthReq
                0x11,           // Maximum Encryption Key Size (17)
                0x00,           // Initiator Key Distribution
                0x00,           // Responder Key Distribution

            },
            {
                0x05,           // Pairing Failed
                0x0A            // Invalid Parameters
            }
        );
    }

    BOOST_AUTO_TEST_CASE( invalid_Encryption_Key_Size_II )
    {
        expected(
            {
                0x01,           // Pairing Request
                0x03,           // IO Capability NoInputNoOutput
                0x00,           // OOB data flag (data not present)
                0x00,           // AuthReq
                0x06,           // Maximum Encryption Key Size (6)
                0x00,           // Initiator Key Distribution
                0x00,           // Responder Key Distribution

            },
            {
                0x05,           // Pairing Failed
                0x0A            // Invalid Parameters
            }
        );
    }

    BOOST_AUTO_TEST_CASE( invalid_Initiator_Key_Distribution )
    {
        expected(
            {
                0x01,           // Pairing Request
                0x03,           // IO Capability NoInputNoOutput
                0x00,           // OOB data flag (data not present)
                0x00,           // AuthReq
                0x10,           // Maximum Encryption Key Size (16)
                0xF0,           // Initiator Key Distribution (RFU)
                0x00,           // Responder Key Distribution

            },
            {
                0x05,           // Pairing Failed
                0x0A            // Invalid Parameters
            }
        );
    }

    BOOST_AUTO_TEST_CASE( invalid_Responder_Key_Distribution )
    {
        expected(
            {
                0x01,           // Pairing Request
                0x03,           // IO Capability NoInputNoOutput
                0x00,           // OOB data flag (data not present)
                0x00,           // AuthReq
                0x10,           // Maximum Encryption Key Size (16)
                0x00,           // Initiator Key Distribution
                0xF0,           // Responder Key Distribution (RFU)
            },
            {
                0x05,           // Pairing Failed
                0x0A            // Invalid Parameters
            }
        );
    }

BOOST_AUTO_TEST_SUITE_END()

BOOST_FIXTURE_TEST_CASE( not_in_idle_state, test::pairing_features_exchanged )
{
        expected(
            {
                0x01,           // Pairing Request
                0x03,           // IO Capability NoInputNoOutput
                0x00,           // OOB data flag (data not present)
                0x00,           // AuthReq
                0x10,           // Maximum Encryption Key Size (16)
                0x00,           // Initiator Key Distribution
                0x00,           // Responder Key Distribution (RFU)
            },
            {
                0x05,           // Pairing Failed
                0x08            // Unspecified Reason
            }
        );
}

max_stars_repo_name: NAzT/bluetoe

max_issues_repo_name: NAzT/bluetoe

max_forks_repo_name: NAzT/bluetoe


text:
//          Copyright Carl Philipp Reh 2009 - 2016.
// 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 FCPPT_MPL_RUNTIME_INDEX_HPP_INCLUDED
#define FCPPT_MPL_RUNTIME_INDEX_HPP_INCLUDED

#include <fcppt/mpl/detail/runtime_index.hpp>
#include <fcppt/config/external_begin.hpp>
#include <boost/mpl/integral_c.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>

namespace fcppt
{
namespace mpl
{

/**
\brief Transforms a runtime index into a an integral constant

\ingroup fcpptmpl

Passes \a _index as an integral constant to \a _function if \a _index is less
than \a MaxIndex::value. Otherwise, \a _fail_function is called.

\tparam Index An integer type

\tparam MaxIndex An integral constant

\tparam Function A function callable with an integral constant

\tparam FailFunction A function callable with no arguments
*/
template<
	typename MaxIndex,
	typename Index,
	typename Function,
	typename FailFunction
>
inline
decltype(
	auto
)
runtime_index(
	Index const _index,
	Function const &_function,
	FailFunction const &_fail_function
)
{
	static_assert(
		std::is_unsigned<
			Index
		>::value,
		"runtime_index can only be used with unsigned indices"
	);

	return
		fcppt::mpl::detail::runtime_index<
			MaxIndex,
			boost::mpl::integral_c<
				Index,
				0
			>
		>::execute(
			_index,
			_function,
			_fail_function
		);

}

}
}

#endif

ext: hpp

max_stars_repo_name: vinzenz/fcppt

max_issues_repo_name: vinzenz/fcppt

max_forks_repo_name: vinzenz/fcppt


text:
#include <string>
#include <exception>
#include <stdexcept>
#include <stdio.h>
#include <stdlib.h>
#include <utility>

#include <glload/gl_3_3.hpp>
#include <glload/gl_load.hpp>
#include <GL/glfw.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/half_float.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glutil/glutil.h>
#include <glmesh/glmesh.h>
#include <glmesh/BoostDraw.h>
#include <boost/tuple/tuple.hpp>
#include <boost/range.hpp>
#include <boost/foreach.hpp>
#include "framework_draw.h"

typedef boost::tuple<glm::hvec4, glm::detail::tvec4<GLubyte> > VertexType;

namespace
{
	VertexType g_vertexData[] =
	{
		VertexType(glm::hvec4(0.75f, 0.75f, 0.0f, 1.0f), glm::detail::tvec4<GLubyte>(153, 204, 0, 255)),
		VertexType(glm::hvec4(0.75f, -0.75f, 0.0f, 1.0f), glm::detail::tvec4<GLubyte>(230, 51, 0, 255)),
		VertexType(glm::hvec4(-0.75f, -0.75f, 0.0f, 1.0f), glm::detail::tvec4<GLubyte>(26, 51, 179, 255)),
	};

	VertexType g_groundData[] =
	{
		VertexType(glm::hvec4(30.0f, 0.0f, 30.0f, 1.0f), glm::detail::tvec4<GLubyte>(51, 255, 51, 255)),
		VertexType(glm::hvec4(30.0f, 0.0f, -30.0f, 1.0f), glm::detail::tvec4<GLubyte>(51, 255, 51, 255)),
		VertexType(glm::hvec4(-30.0f, 0.0f, 30.0f, 1.0f), glm::detail::tvec4<GLubyte>(51, 255, 51, 255)),
		VertexType(glm::hvec4(-30.0f, 0.0f, -30.0f, 1.0f), glm::detail::tvec4<GLubyte>(51, 255, 51, 255)),
	};
}

class BasicDrawable : public Drawable
{
public:
	BasicDrawable()
		: m_streamBuf(1024)
	{
		gl::ClearColor(1.0f, 1.0f, 1.0f, 1.0f);
		gl::ClearDepth(1.0);

		gl::Enable(gl::DEPTH_TEST);
		gl::DepthFunc(gl::LEQUAL);
		gl::Enable(gl::DEPTH_CLAMP);

		const std::string vertexShader(
			"#version 330\n"
			"\n"
			"layout(location = 0) in vec4 position;\n"
			"layout(location = 1) in vec4 color;\n"
			"\n"
			"smooth out vec4 theColor;\n"
			"\n"
			"uniform mat4 cameraToClipMatrix;\n"
			"uniform mat4 modelToCameraMatrix;\n"
			"\n"
			"void main()\n"
			"{\n"
			"	vec4 cameraPos = modelToCameraMatrix * position;\n"
			"	gl_Position = cameraToClipMatrix * cameraPos;\n"
			"	theColor = color;\n"
			"}\n"
			);

		const std::string fragmentShader(
			"#version 330\n"
			"\n"
			"smooth in vec4 theColor;\n"
			"out vec4 outputColor;\n"
			"\n"
			"void main()\n"
			"{\n"
			"	outputColor = theColor;\n"
			"}\n"
			);

		GLuint vertShader = glutil::CompileShader(gl::VERTEX_SHADER, vertexShader);
		GLuint fragShader = glutil::CompileShader(gl::FRAGMENT_SHADER, fragmentShader);

		m_program = glutil::LinkProgram(vertShader, fragShader);

		gl::DeleteShader(vertShader);
		gl::DeleteShader(fragShader);

		m_unifModelToCameraMatrix = gl::GetUniformLocation(m_program, "modelToCameraMatrix");
		m_unifCameraToClipMatrix = gl::GetUniformLocation(m_program, "cameraToClipMatrix");

		glmesh::AttributeList attribs;
		attribs.push_back(glmesh::AttribDesc(0, 4, glmesh::VDT_HALF_FLOAT, glmesh::ADT_FLOAT));
		attribs.push_back(glmesh::AttribDesc(1, 4, glmesh::VDT_UNSIGN_BYTE, glmesh::ADT_NORM_FLOAT));
		m_vertFmt = glmesh::VertexFormat(attribs);
	}

	~BasicDrawable()
	{
		gl::DeleteProgram(m_program);
	}

	virtual void Draw(const glm::mat4 &cameraToClip, const glm::mat4 &worldToCamera,
		const glm::mat4 &modelToWorld)
	{
		gl::ClearColor(0.9f, 0.9f, 0.9f, 1.0f);
		gl::ClearDepth(1.0f);
		gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);

		//Set uniforms.
		gl::UseProgram(m_program);
		gl::UniformMatrix4fv(m_unifCameraToClipMatrix, 1, gl::FALSE_,
			glm::value_ptr(cameraToClip));

		{
			gl::UniformMatrix4fv(m_unifModelToCameraMatrix, 1, gl::FALSE_,
				glm::value_ptr(worldToCamera * modelToWorld));

			glmesh::Draw immMode(gl::TRIANGLES, boost::size(g_vertexData), m_vertFmt, m_streamBuf);
			BOOST_FOREACH(const VertexType &vertex, g_vertexData)
			{
				glmesh::Attrib(immMode, vertex);
			}

			immMode.Render();
		}

		{
			gl::UniformMatrix4fv(m_unifModelToCameraMatrix, 1, gl::FALSE_,
				glm::value_ptr(worldToCamera));

			glmesh::Draw immMode(gl::TRIANGLE_STRIP, boost::size(g_groundData), m_vertFmt, m_streamBuf);
			BOOST_FOREACH(const VertexType &vertex, g_groundData)
			{
				glmesh::Attrib(immMode, vertex);
			}

			immMode.Render();
		}

		gl::UseProgram(0);
	}

private:
	glmesh::StreamBuffer m_streamBuf;
	glmesh::VertexFormat m_vertFmt;
	GLuint m_program;
	GLuint m_unifModelToCameraMatrix;
	GLuint m_unifCameraToClipMatrix;
};

Drawable *CreateDrawable()
{
	return new BasicDrawable();
}

ext: cpp


text:
// Copyright (C) 2018 Thanaphon Chavengsaksongkram <as12production@gmail.com>, He Sun <he.sun@ed.ac.uk>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.

#ifndef GSPARSE_INTERFACE_GRAPHWRITER_HPP
#define GSPARSE_INTERFACE_GRAPHWRITER_HPP

#include <cstddef>       // size_t
#include <memory>        //shared_ptr
#include <Eigen/Dense>   // Eigen Matrix

#include "../Config.hpp" // Library configuration
#include "Graph.hpp"     // Graph Interface

namespace gSparse
{
    //!  An interface class for Graph Output.
    /*!
        This class defines an interface for gSparse's graph writing functionality.
        New output source should derive this function.
    */
    class IGraphWriter
	{
	public:
        //!  Default Constructor for IGraphWriter.
		IGraphWriter() = default;

        //! A pure virtual member write Graph Data by passing an IGraph object.
        /*!
        \param graph: A shared_ptr of an IGraph Object
        */
		virtual void Write(const gSparse::Graph & graph) = 0;

        //! A pure virtual member write Graph Data by passing Edge List.
        /*!
        \param Edges: An Eigen Matrix representings Graph Edges.
        */
		virtual void Write(const gSparse::EdgeMatrix & Edges) = 0;

        //! A pure virtual member write read Graph Data by passing an Edge and a Weight Lists.
        /*!
        \param Edges: An Eigen Matrix of Graph's Edges.
        \param Weights: An Eigen Matrix of Graph's Weight.
        */
		virtual void Write(const gSparse::EdgeMatrix & Edges,
			const gSparse::PrecisionRowMatrix & Weights) = 0;

        //!  Default Constructor for IGraphWriter.
		virtual ~IGraphWriter() = default;
	};
    typedef std::shared_ptr<gSparse::IGraphWriter> GraphWriter;
}
#endif


text:
/*
 * Copyright (C) 2012-2016 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
/* Desc: Opaque Interface for Player
 * Author: Benjamin Kloster
 * Date: 13 March 2008
 */

/**
  @addtogroup player
  @par Opaque Interface
  */
/* TODO
   Do we need these?
   - PLAYER_OPAQUE_DATA_STATE
   - PLAYER_OPAQUE_CMD_DATA
   - PLAYER_OPAQUE_REQ_DATA
   */
#include <math.h>
#include <iostream>
#include <boost/thread/recursive_mutex.hpp>

#include "GazeboDriver.hh"
#include "OpaqueInterface.hh"

using namespace libgazebo;

boost::recursive_mutex *OpaqueInterface::mutex = NULL;

///////////////////////////////////////////////////////////////////////////////
// Constructor
OpaqueInterface::OpaqueInterface(player_devaddr_t addr,
    GazeboDriver *driver, ConfigFile *cf, int section)
: GazeboInterface(addr, driver, cf, section), iface(NULL), gz_id(NULL),
  datatime(0.0)
{
  /*
  // Get the ID of the interface
  this->gz_id = (char*) calloc(1024, sizeof(char));
  strcat(this->gz_id, GazeboClient::prefixId);
  strcat(this->gz_id, cf->ReadString(section, "gz_id", ""));

  // Allocate a Position Interface
  this->iface = new OpaqueIface();

  this->datatime = -1;

  if (this->mutex == NULL)
    this->mutex = new boost::recursive_mutex();
    */
}

///////////////////////////////////////////////////////////////////////////////
// Destructor
OpaqueInterface::~OpaqueInterface()
{
  /*
  // Release this interface
  delete this->iface;
  */
}

///////////////////////////////////////////////////////////////////////////////
// Handle all messages. This is called from GazeboDriver
int OpaqueInterface::ProcessMessage(QueuePointer &respQueue,
    player_msghdr_t *hdr, void *data)
{
  /*
  boost::recursive_mutex::scoped_lock lock(*this->mutex);
  if (this->iface->Lock(1))
  {
    // nothing yet
    return 0;
  }
  else
    this->Unsubscribe();
*/
  return -1;
}

///////////////////////////////////////////////////////////////////////////////
// Update this interface, publish new info. This is
// called from GazeboDriver::Update
void OpaqueInterface::Update()
{
  /*
  boost::recursive_mutex::scoped_lock lock(*this->mutex);
  player_opaque_data_t data;
  struct timeval ts;

  memset(&data, 0, sizeof(data));
  if (this->iface->Lock(1))
  {
    // Only Update when new data is present
    if (this->iface->data->head.time > this->datatime)
    {
      this->datatime = this->iface->data->head.time;

      ts.tv_sec = (int) (this->iface->data->head.time);
      ts.tv_usec = (int) (fmod(this->iface->data->head.time, 1) * 1e6);

      data.data_count = this->iface->data->data_count;
      data.data = this->iface->data->data;

      this->driver->Publish(this->device_addr,
          PLAYER_MSGTYPE_DATA,
          PLAYER_OPAQUE_DATA_STATE,
          (void*)&data, sizeof(data), &this->datatime);
    }

    this->iface->Unlock();
  }
  else
    this->Unsubscribe();
    */
}

///////////////////////////////////////////////////////////////////////////////
// Open a SHM interface when a subscription is received. This is called from
// GazeboDriver::Subscribe
void OpaqueInterface::Subscribe()
{
  /*
  // Open the interface
  try
  {
    boost::recursive_mutex::scoped_lock lock(*this->mutex);
    this->iface->Open(GazeboClient::client, this->gz_id);
  }
  catch (std::string &e)
  {
    // std::ostringstream stream;
    std::cout <<"Error Subscribing to Gazebo Opaque Interface\n"
      << e << "\n";
    // gzthrow(stream.str());
    exit(0);
  }
  */
}

///////////////////////////////////////////////////////////////////////////////
// Close a SHM interface. This is called from GazeboDriver::Unsubscribe
void OpaqueInterface::Unsubscribe()
{
  /*
  boost::recursive_mutex::scoped_lock lock(*this->mutex);
  this->iface->Close();
  */
}

ext: cc


text:
//  Copyright (c) 2007-2012 Hartmut Kaiser
//  Copyright (c) 2011      Bryce Lelbach
//
//  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)

#if !defined(HPX_RUNTIME_GET_LVA_JUN_22_2008_0451PM)
#define HPX_RUNTIME_GET_LVA_JUN_22_2008_0451PM

#include <hpx/hpx_fwd.hpp>
#include <hpx/runtime/naming/address.hpp>

#include <boost/mpl/or.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/type_traits/is_base_and_derived.hpp>
#include <boost/type_traits/add_const.hpp>

///////////////////////////////////////////////////////////////////////////////
namespace hpx
{
    /// The \a get_lva template is a helper structure allowing to convert a
    /// local virtual address as stored in a local address (returned from
    /// the function \a resolver_client#resolve) to the address of the
    /// component implementing the action.
    ///
    /// The default implementation uses the template argument \a Component
    /// to deduce the type wrapping the component implementing the action. This
    /// is used to get the needed address.
    ///
    /// The specialization for the \a runtime_support component is needed
    /// because this is not wrapped by a separate type as all the other
    /// components.
    ///
    /// \tparam Component  This is the type of the component implementing the
    ///                    action to execute.
    template <typename Component>
    struct get_lva
    {
        struct is_simple_or_fixed_component
          : boost::mpl::or_<
                boost::is_base_and_derived<
                    components::detail::simple_component_tag, Component
                >,
                boost::is_base_and_derived<
                    components::detail::fixed_component_tag, Component
                >
            >
        {};

        template <typename Address>
        static Component*
        call(Address lva, boost::mpl::false_)
        {
            typedef typename Component::wrapping_type wrapping_type;
            return reinterpret_cast<wrapping_type*>(lva)->get_checked();
        }

        template <typename Address>
        static Component*
        call(Address lva, boost::mpl::true_)
        {
            return reinterpret_cast<Component*>(lva);
        }

        static Component*
        call(naming::address::address_type lva)
        {
            return call(lva, is_simple_or_fixed_component());
        }
    };

    template <typename Component>
    struct get_lva<Component const>
    {
        struct is_simple_or_fixed_component
          : boost::mpl::or_<
                boost::is_base_and_derived<
                    components::detail::simple_component_tag, Component
                >,
                boost::is_base_and_derived<
                    components::detail::fixed_component_tag, Component
                >
            >
        {};

        template <typename Address>
        static Component const*
        call(Address lva, boost::mpl::false_)
        {
            typedef typename boost::add_const<
                typename Component::wrapping_type
            >::type wrapping_type;
            return reinterpret_cast<wrapping_type*>(lva)->get_checked();
        }

        template <typename Address>
        static Component const*
        call(Address lva, boost::mpl::true_)
        {
            return reinterpret_cast<Component const*>(lva);
        }

        static Component const*
        call(naming::address::address_type lva)
        {
            return call(lva, is_simple_or_fixed_component());
        }
    };

    // specialization for components::server::runtime_support
    template <>
    struct get_lva<components::server::runtime_support>
    {
        // for server::runtime_support the provided lva is directly usable
        // as the required local address
        static components::server::runtime_support*
        call(naming::address::address_type lva)
        {
            return reinterpret_cast<components::server::runtime_support*>(lva);
        }
    };
    template <>
    struct get_lva<components::server::runtime_support const>
    {
        // for server::runtime_support the provided lva is directly usable
        // as the required local address
        static components::server::runtime_support const*
        call(naming::address::address_type lva)
        {
            return reinterpret_cast<components::server::runtime_support const*>(lva);
        }
    };

    // specialization for components::server::memory
    template <>
    struct get_lva<components::server::memory>
    {
        // for server::memory the provided lva is directly usable as the
        // required local address
        static components::server::memory*
        call(naming::address::address_type lva)
        {
            return reinterpret_cast<components::server::memory*>(lva);
        }
    };
    template <>
    struct get_lva<components::server::memory const>
    {
        // for server::memory the provided lva is directly usable as the
        // required local address
        static components::server::memory const*
        call(naming::address::address_type lva)
        {
            return reinterpret_cast<components::server::memory const*>(lva);
        }
    };

    // specialization for components::server::memory_block
    template <>
    struct get_lva<components::server::memory_block>
    {
        // for server::memory_block the provided lva is directly usable as the
        // required local address
        static components::server::memory_block*
        call(naming::address::address_type lva)
        {
            return reinterpret_cast<components::server::memory_block*>(lva);
        }
    };

    template <>
    struct get_lva<components::server::memory_block const>
    {
        // for server::memory_block the provided lva is directly usable as the
        // required local address
        static components::server::memory_block const*
        call(naming::address::address_type lva)
        {
            return reinterpret_cast<components::server::memory_block const*>(lva);
        }
    };
}

#endif

max_stars_repo_name: kempj/hpx

max_issues_repo_name: kempj/hpx

max_forks_repo_name: kempj/hpx


text:
/*
 * This benchmark times the performance of B += sqr(A), where A and B
 * are complex<double> arrays.
 *
 * Note: need to use -mv8 for SPARC v8.
 */

#include <blitz/array.h>
#include <blitz/timer.h>

BZ_USING_NAMESPACE(blitz)

#include <blitz/vector.h>

typedef Array<complex<double>,1> CArray;

void setup(Array<complex<double>,1>& A, Array<complex<double>,1>& B)
{
    int n = A.extent(firstDim);

    for (int i=0; i < n; ++i)
    {
        double x=-10.+20./(n-1.0)*i;
        A(i)=sin(x);
        B(i)=sin(x);
    }
}

void version1(CArray& A, CArray& B, int nIters)
{
    Timer timer;

    // Array notation
    setup(A, B);
    timer.start();
    for (int i=0; i < nIters; ++i)
    {
        B += A*A;
    }
    timer.stop();
    cout << "Time using array notation b += a*a: " << timer.elapsedSeconds()
         << endl;
}

void version2(CArray& A, CArray& B, int nIters)
{
    // Array notation, using sqr(a)
    Timer timer;

    setup(A,B);
    timer.start();
    for (int i=0; i < nIters; ++i)
    {
        B += sqr(A);
    }
    timer.stop();
    cout << "Time using array notation b += sqr(a): " << timer.elapsedSeconds()
         << endl;
}

void version2c(CArray& A, CArray& B)
{
    B += sqr(A);
}

void version2b(CArray& A, CArray& B, int nIters)
{
    // Array notation, using sqr(a)
    Timer timer;

    setup(A,B);
    timer.start();
    for (int i=0; i < nIters; ++i)
    {
        version2c(A,B);
    }
    timer.stop();
    cout << "Time using array notation b += sqr(a): " << timer.elapsedSeconds()
         << endl;
}

void version3(CArray& A, CArray& B, int nIters)
{
    Timer timer;

    int N = A.extent(firstDim);

    // Low-level implementation
    setup(A,B);
    timer.start();
    for (int i=0; i < nIters; ++i)
    {
        for (int j=0; j < N; ++j)
            B(j) += A(j) * A(j);
    }
    timer.stop();
    cout << "Time using low-level version: " << timer.elapsedSeconds()
         << endl;
}

void version4(CArray& A, CArray& B, int nIters)
{
    Timer timer;

    struct cmplx {
        double re, im;
    };
    cmplx* a = (cmplx*)A.data();
    cmplx* b = (cmplx*)B.data();
    setup(A,B);
    int N = A.extent(firstDim);

    timer.start();
    for (int i=0; i < nIters; ++i)
    {
        for (int j=0; j < N; ++j)
        {
            double ar = a[j].re;
            double ai = a[j].im;
            b[j].re += ar*ar - ai*ai;
            b[j].im += 2 * ar * ai;
        }
    }
    timer.stop();
    cout << "Time using really low-level version: " << timer.elapsedSeconds()
         << endl;
}

int run(int N, int nIters)
{
    Array<complex<double>,1> A(N), B(N);

    version1(A,B,nIters);
    version2(A,B,nIters);
    version2b(A,B,nIters);
    version3(A,B,nIters);
    version4(A,B,nIters);

    return 0;
}

int main()
{
    cout << "In-cache:" << endl;
    run(256,39063);

    cout << endl << "Out-of-cache:" << endl;
    run(1000000,10);
}

max_stars_repo_name: fraguela/depspawn

max_issues_repo_name: MSV-Project/IBAMR

max_forks_repo_name: MSV-Project/IBAMR


text:
/*
 [auto_generated]
 /boost/numeric/odeint/external/mtl4/mtl4.hpp

 [begin_description]
 includes all headers required for using mtl4 with odeint
 [end_description]

 Copyright 2009-2013 Karsten Ahnert
 Copyright 2009-2013 Mario Mulansky

 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_NUMERIC_ODEINT_EXTERNAL_MTL4_MTL4_HPP_INCLUDED
#define BOOST_NUMERIC_ODEINT_EXTERNAL_MTL4_MTL4_HPP_INCLUDED

#include <boost/numeric/odeint/external/mtl4/mtl4_algebra_dispatcher.hpp>
#include <boost/numeric/odeint/external/mtl4/mtl4_resize.hpp>

#endif // BOOST_NUMERIC_ODEINT_EXTERNAL_MTL4_MTL4_INCLUDED

max_stars_repo_name: MINATILO/packing-generation

max_issues_repo_name: MINATILO/packing-generation

max_forks_repo_name: MINATILO/packing-generation


text:
#include <iostream>
#include <numeric>
#include <algorithm>
#include <vector>
#include <map>
#include <chrono>
#include <memory>
#include <typeinfo>

#include <hpx/hpx_init.hpp>

#include <boost/serialization/access.hpp>

#include "VFParser.hpp"
#include "BitGraph.hpp"
#include "BitSet.hpp"

//#include "skeletons/Seq.hpp"
#include "skeletons/DepthBounded.hpp"
//#include "skeletons/StackStealing.hpp"

// Number of Words to use in our bitset representation
// Possible to specify at compile to to handler bigger graphs if required
#ifndef NWORDS
#define NWORDS 8
#endif

using Association = std::map<std::pair<unsigned, unsigned>, unsigned>;
using AssociatedEdges = std::vector<std::pair<unsigned, unsigned> >;

template<unsigned n_words_>
std::tuple<BitGraph<n_words_>, std::vector<int>, std::vector<int> >
buildGraph(const std::pair<Association, AssociatedEdges> & g) {
  std::vector<int> order(g.first.size());
  std::vector<int> invorder(g.first.size());
  std::iota(order.begin(), order.end(), 0);

  // Pre-calculate degrees
  std::vector<int> degrees;
  degrees.resize(g.first.size());
  for (auto & f : g.second) {
    ++degrees[f.first];
    ++degrees[f.second];
  }

  std::sort(order.begin(), order.end(),
            [&] (int a, int b) { return true ^ (degrees[a] < degrees[b] || (degrees[a] == degrees[b] && a > b)); });

  // Encode BitGraph
  BitGraph<n_words_> graph;
  graph.resize(g.first.size());

  for (unsigned i = 0 ; i < order.size() ; ++i)
    invorder[order[i]] = i;

  for (auto & f : g.second)
    graph.add_edge(invorder[f.first], invorder[f.second]);

  return std::make_tuple(graph, order, invorder);
}

auto modular_product(const VFGraph & g1, const VFGraph & g2) -> std::pair<Association, AssociatedEdges>
{
  unsigned next_vertex = 0;
  Association association;
  AssociatedEdges edges;

  for (unsigned l = 0 ; l < std::min(g1.vertices_by_label.size(), g2.vertices_by_label.size()) ; ++l)
      for (unsigned v1 : g1.vertices_by_label[l])
          for (unsigned v2 : g2.vertices_by_label[l])
              for (unsigned m = 0 ; m < std::min(g1.vertices_by_label.size(), g2.vertices_by_label.size()) ; ++m)
                  for (unsigned w1 : g1.vertices_by_label[m])
                      for (unsigned w2 : g2.vertices_by_label[m])
                          if (v1 != w1 && v2 != w2
                                  && (g1.edges[v1][v1] == g2.edges[v2][v2])
                                  && (g1.edges[w1][w1] == g2.edges[w2][w2])
                                  && (g1.edges[v1][w1] == g2.edges[v2][w2])
                                  && (g1.edges[w1][v1] == g2.edges[w2][v2])) {

                              if (! association.count({v1, v2}))
                                  association.insert({{v1, v2}, next_vertex++});
                              if (! association.count({w1, w2}))
                                  association.insert({{w1, w2}, next_vertex++});

                              edges.push_back({association.find({v1, v2})->second, association.find({w1, w2})->second});
                          }

  return { association, edges };
}

auto unproduct(const Association & association, unsigned v) -> std::pair<unsigned, unsigned>
{
  for (auto & a : association)
    if (a.second == v)
      return a.first;

  throw "oops";
}

template<unsigned n_words_>
auto colour_class_order(const BitGraph<n_words_> & graph,
                        const BitSet<n_words_> & p,
                        std::array<unsigned, n_words_ * bits_per_word> & p_order,
                        std::array<unsigned, n_words_ * bits_per_word> & p_bounds) -> void {
  BitSet<n_words_> p_left = p; // not coloured yet
  unsigned colour = 0;         // current colour
  unsigned i = 0;              // position in p_bounds

  // while we've things left to colour
  while (! p_left.empty()) {
    // next colour
    ++colour;
    // things that can still be given this colour
    BitSet<n_words_> q = p_left;

    // while we can still give something this colour
    while (! q.empty()) {
      // first thing we can colour
      int v = q.first_set_bit();
      p_left.unset(v);
      q.unset(v);

      // can't give anything adjacent to this the same colour
      graph.intersect_with_row_complement(v, q);

      // record in result
      p_bounds[i] = colour;
      p_order[i] = v;
      ++i;
    }
  }
}

// Main Maxclique B&B Functions
// Probably needs a copy constructor
struct MCSol {
  std::vector<int> members;
  int colours;

  template <class Archive>
  void serialize(Archive & ar, const unsigned int version) {
    ar & members;
    ar & colours;
  }
};

struct MCNode {
  friend class boost::serialization::access;

  MCSol sol;
  int size;
  BitSet<NWORDS> remaining;

  int getObj() const {
    return size;
  }

  template <class Archive>
  void serialize(Archive & ar, const unsigned int version) {
    ar & sol;
    ar & size;
    ar & remaining;
  }

};

struct GenNode : YewPar::NodeGenerator<MCNode, BitGraph<NWORDS> > {
  std::array<unsigned, NWORDS * bits_per_word> p_order;
  std::array<unsigned, NWORDS * bits_per_word> colourClass;

  std::reference_wrapper<const BitGraph<NWORDS> > graph;

  MCSol childSol;
  int childBnd;
  BitSet<NWORDS> p;

  int v;

  GenNode(const BitGraph<NWORDS> & graph, const MCNode & n) : graph(std::cref(graph)) {
    colour_class_order(graph, n.remaining, p_order, colourClass);
    childSol = n.sol;
    childBnd = n.size + 1;
    p = n.remaining;
    numChildren = p.popcount();
    v = numChildren - 1;
  }

  // Get the next value
  MCNode next() override {
    auto sol = childSol;
    sol.members.push_back(p_order[v]);
    sol.colours = colourClass[v] - 1;

    auto cands = p;
    graph.get().intersect_with_row(p_order[v], cands);

    // Side effectful function update
    p.unset(p_order[v]);
    v--;

    return {sol, childBnd, cands};
  }
};

int upperBound(const BitGraph<NWORDS> & space, const MCNode & n) {
  return n.size + n.sol.colours;
}

typedef func<decltype(&upperBound), &upperBound> upperBound_func;

// using ss_skel = YewPar::Skeletons::StackStealing<GenNode,
//                                                  YewPar::Skeletons::API::BnB,
//                                                  YewPar::Skeletons::API::BoundFunction<upperBound_func>,
//                                                  YewPar::Skeletons::API::PruneLevel>;
// using cfunc  = ss_skel::SubTreeTask;
// REGISTER_SEARCHMANAGER(MCNode, cfunc);

int hpx_main(boost::program_options::variables_map & opts) {
  auto patternF = opts["pattern-file"].as<std::string>();
  auto targetF  = opts["target-file"].as<std::string>();

  auto patternG = read_vf(patternF, opts.count("unlabelled"), opts.count("no-edge-labels"), opts.count("undirected"));
  auto targetG = read_vf(targetF, opts.count("unlabelled"), opts.count("no-edge-labels"), opts.count("undirected"));

  auto prod = modular_product(patternG, targetG);

  BitGraph<NWORDS> graph; std::vector<int> order, invorder;
  std::tie(graph, order, invorder) = buildGraph<NWORDS>(prod);

  if (graph.size() > bits_per_word*NWORDS) {
    std::cout << "Binary Cannot Handle Graph of this size. Recompile with a bigger NWORDS" << std::endl;
    hpx::finalize();
    return EXIT_FAILURE;
  }

  auto spawnDepth = opts["spawn-depth"].as<std::uint64_t>();
  auto start_time = std::chrono::steady_clock::now();

  // // Initialise Root Node
  MCSol mcsol;
  mcsol.members.reserve(graph.size());
  mcsol.colours = 0;

  BitSet<NWORDS> cands;
  cands.resize(graph.size());
  cands.set_all();
  MCNode root = {mcsol, 0, cands};

  YewPar::Skeletons::API::Params<int> searchParameters;
  searchParameters.spawnDepth = spawnDepth;
  auto result = YewPar::Skeletons::DepthBounded<GenNode,
                                               YewPar::Skeletons::API::Optimisation,
                                               YewPar::Skeletons::API::BoundFunction<upperBound_func>,
                                               YewPar::Skeletons::API::PruneLevel>
        ::search(graph, root, searchParameters);

  auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>
    (std::chrono::steady_clock::now() - start_time);

  std::map<int, int> isomorphism;
  auto sol = result.sol;
  for (auto const & v : sol.members) {
    isomorphism.insert(unproduct(prod.first, order[v]));
  }

  // Print Results
  std::cout << std::boolalpha << ! isomorphism.empty() << " " << 0;
  std::cout << " " << isomorphism.size() << std::endl;

  for (auto v : isomorphism)
      std::cout << "(" << v.first << " -> " << v.second << ") ";
  std::cout << std::endl;

  std::cout << overall_time.count() << std::endl;

  auto graphs = std::make_pair(patternG, targetG);
  for (auto & p : isomorphism) {
      if (graphs.first.vertex_labels.at(p.first) != graphs.second.vertex_labels.at(p.second)) {
          std::cerr << "Oops! not an isomorphism due to vertex labels" << std::endl;
          hpx::finalize();
          return EXIT_FAILURE;
      }
  }

  for (auto & p : isomorphism) {
      for (auto & q : isomorphism) {
          if (graphs.first.edges.at(p.first).at(q.first) != graphs.second.edges.at(p.second).at(q.second)) {
              std::cerr << "Oops! not an isomorphism due to edge " << std::to_string(p.first) << "--"
                  << std::to_string(q.first) << " (" << graphs.first.edges[p.first][q.first] << ") vs "
                  << std::to_string(p.second) << "--" << std::to_string(q.second) << " ("
                  << graphs.second.edges[p.second][q.second] << ")" << std::endl;
              hpx::finalize();
              return EXIT_FAILURE;
          }
      }
  }

  return hpx::finalize();
}

int main (int argc, char* argv[]) {
  boost::program_options::options_description
    desc_commandline("Usage: " HPX_APPLICATION_STRING " [options]");

  desc_commandline.add_options()
    ( "spawn-depth,d",
      boost::program_options::value<std::uint64_t>()->default_value(0),
      "Depth in the tree to spawn at"
      )
    ( "pattern-file",
      boost::program_options::value<std::string>(),
      "VF formatted input graph"
      )
    ( "target-file",
      boost::program_options::value<std::string>(),
      "VF formatted input graph"
    )
    ("unlabelled", "Make the graph unlabelled")
    ("no-edge-labels", "Get rid of edge labels, but keep vertex labels")
    ("undirected", "Make the graph undirected");

  return hpx::init(desc_commandline, argc, argv);
}

max_stars_repo_name: zxcvsop/YewPar

max_issues_repo_name: zxcvsop/YewPar

max_forks_repo_name: zxcvsop/YewPar


text:
/**
 * Mojang Authentication API
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * OpenAPI spec version: 2020-06-05
 *
 * NOTE: This class is auto generated by OpenAPI-Generator 3.3.4.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

#include "DefaultApi.h"
#include "IHttpBody.h"
#include "JsonBody.h"
#include "MultipartFormData.h"

#include <unordered_set>

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

namespace com {
namespace github {
namespace asyncmc {
namespace mojang {
namespace authentication {
namespace cpp {
namespace restsdk {
namespace api {

using namespace com::github::asyncmc::mojang::authentication::cpp::restsdk::model;

DefaultApi::DefaultApi( std::shared_ptr<ApiClient> apiClient )
    : m_ApiClient(apiClient)
{
}

DefaultApi::~DefaultApi()
{
}

pplx::task<std::shared_ptr<Authentication>> DefaultApi::authenticate(std::shared_ptr<AuthenticationRequest> authenticationRequest)
{

    // verify the required parameter 'authenticationRequest' is set
    if (authenticationRequest == nullptr)
    {
        throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'authenticationRequest' when calling DefaultApi->authenticate"));
    }

    std::shared_ptr<ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
    utility::string_t localVarPath = utility::conversions::to_string_t("/authenticate");

    std::map<utility::string_t, utility::string_t> localVarQueryParams;
    std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
    std::map<utility::string_t, utility::string_t> localVarFormParams;
    std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;

    std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
    localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );

    utility::string_t localVarResponseHttpContentType;

    // use JSON if possible
    if ( localVarResponseHttpContentTypes.size() == 0 )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // JSON
    else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // multipart formdata
    else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
    }
    else
    {
        throw ApiException(400, utility::conversions::to_string_t("DefaultApi->authenticate does not produce any supported media type"));
    }

    localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;

    std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
    localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );

    std::shared_ptr<IHttpBody> localVarHttpBody;
    utility::string_t localVarRequestHttpContentType;

    // use JSON if possible
    if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
        web::json::value localVarJson;

        localVarJson = ModelBase::toJson(authenticationRequest);

        localVarHttpBody = std::shared_ptr<IHttpBody>( new JsonBody( localVarJson ) );
    }
    // multipart formdata
    else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
        std::shared_ptr<MultipartFormData> localVarMultipart(new MultipartFormData);

        if(authenticationRequest.get())
        {
            authenticationRequest->toMultipart(localVarMultipart, utility::conversions::to_string_t("authenticationRequest"));
        }

        localVarHttpBody = localVarMultipart;
        localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary();
    }
    else
    {
        throw ApiException(415, utility::conversions::to_string_t("DefaultApi->authenticate does not consume any supported media type"));
    }

    return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("POST"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
    .then([=](web::http::http_response localVarResponse)
    {
        if (m_ApiClient->getResponseHeadersHandler())
        {
            m_ApiClient->getResponseHeadersHandler()(localVarResponse.headers());
        }

        // 1xx - informational : OK
        // 2xx - successful       : OK
        // 3xx - redirection   : OK
        // 4xx - client error  : not OK
        // 5xx - client error  : not OK
        if (localVarResponse.status_code() >= 400)
        {
            throw ApiException(localVarResponse.status_code()
                , utility::conversions::to_string_t("error calling authenticate: ") + localVarResponse.reason_phrase()
                , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
        }

        // check response content type
        if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
        {
            utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
            if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
            {
                throw ApiException(500
                    , utility::conversions::to_string_t("error calling authenticate: unexpected response type: ") + localVarContentType
                    , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
            }
        }

        return localVarResponse.extract_string();
    })
    .then([=](utility::string_t localVarResponse)
    {
        std::shared_ptr<Authentication> localVarResult(new Authentication());

        if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
        {
            web::json::value localVarJson = web::json::value::parse(localVarResponse);

            localVarResult->fromJson(localVarJson);
        }
        // else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
        // {
        // TODO multipart response parsing
        // }
        else
        {
            throw ApiException(500
                , utility::conversions::to_string_t("error calling authenticate: unsupported response type"));
        }

        return localVarResult;
    });
}
pplx::task<void> DefaultApi::invalidate(std::shared_ptr<AccessKeys> accessKeys)
{

    // verify the required parameter 'accessKeys' is set
    if (accessKeys == nullptr)
    {
        throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'accessKeys' when calling DefaultApi->invalidate"));
    }

    std::shared_ptr<ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
    utility::string_t localVarPath = utility::conversions::to_string_t("/invalidate");

    std::map<utility::string_t, utility::string_t> localVarQueryParams;
    std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
    std::map<utility::string_t, utility::string_t> localVarFormParams;
    std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;

    std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
    localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );

    utility::string_t localVarResponseHttpContentType;

    // use JSON if possible
    if ( localVarResponseHttpContentTypes.size() == 0 )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // JSON
    else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // multipart formdata
    else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
    }
    else
    {
        throw ApiException(400, utility::conversions::to_string_t("DefaultApi->invalidate does not produce any supported media type"));
    }

    localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;

    std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
    localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );

    std::shared_ptr<IHttpBody> localVarHttpBody;
    utility::string_t localVarRequestHttpContentType;

    // use JSON if possible
    if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
        web::json::value localVarJson;

        localVarJson = ModelBase::toJson(accessKeys);

        localVarHttpBody = std::shared_ptr<IHttpBody>( new JsonBody( localVarJson ) );
    }
    // multipart formdata
    else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
        std::shared_ptr<MultipartFormData> localVarMultipart(new MultipartFormData);

        if(accessKeys.get())
        {
            accessKeys->toMultipart(localVarMultipart, utility::conversions::to_string_t("accessKeys"));
        }

        localVarHttpBody = localVarMultipart;
        localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary();
    }
    else
    {
        throw ApiException(415, utility::conversions::to_string_t("DefaultApi->invalidate does not consume any supported media type"));
    }

    return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("POST"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
    .then([=](web::http::http_response localVarResponse)
    {
        if (m_ApiClient->getResponseHeadersHandler())
        {
            m_ApiClient->getResponseHeadersHandler()(localVarResponse.headers());
        }

        // 1xx - informational : OK
        // 2xx - successful       : OK
        // 3xx - redirection   : OK
        // 4xx - client error  : not OK
        // 5xx - client error  : not OK
        if (localVarResponse.status_code() >= 400)
        {
            throw ApiException(localVarResponse.status_code()
                , utility::conversions::to_string_t("error calling invalidate: ") + localVarResponse.reason_phrase()
                , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
        }

        // check response content type
        if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
        {
            utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
            if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
            {
                throw ApiException(500
                    , utility::conversions::to_string_t("error calling invalidate: unexpected response type: ") + localVarContentType
                    , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
            }
        }

        return localVarResponse.extract_string();
    })
    .then([=](utility::string_t localVarResponse)
    {
        return void();
    });
}
pplx::task<std::shared_ptr<RefreshResponse>> DefaultApi::refresh(std::shared_ptr<RefreshRequest> refreshRequest)
{

    // verify the required parameter 'refreshRequest' is set
    if (refreshRequest == nullptr)
    {
        throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'refreshRequest' when calling DefaultApi->refresh"));
    }

    std::shared_ptr<ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
    utility::string_t localVarPath = utility::conversions::to_string_t("/refresh");

    std::map<utility::string_t, utility::string_t> localVarQueryParams;
    std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
    std::map<utility::string_t, utility::string_t> localVarFormParams;
    std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;

    std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
    localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );

    utility::string_t localVarResponseHttpContentType;

    // use JSON if possible
    if ( localVarResponseHttpContentTypes.size() == 0 )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // JSON
    else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // multipart formdata
    else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
    }
    else
    {
        throw ApiException(400, utility::conversions::to_string_t("DefaultApi->refresh does not produce any supported media type"));
    }

    localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;

    std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
    localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );

    std::shared_ptr<IHttpBody> localVarHttpBody;
    utility::string_t localVarRequestHttpContentType;

    // use JSON if possible
    if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
        web::json::value localVarJson;

        localVarJson = ModelBase::toJson(refreshRequest);

        localVarHttpBody = std::shared_ptr<IHttpBody>( new JsonBody( localVarJson ) );
    }
    // multipart formdata
    else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
        std::shared_ptr<MultipartFormData> localVarMultipart(new MultipartFormData);

        if(refreshRequest.get())
        {
            refreshRequest->toMultipart(localVarMultipart, utility::conversions::to_string_t("refreshRequest"));
        }

        localVarHttpBody = localVarMultipart;
        localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary();
    }
    else
    {
        throw ApiException(415, utility::conversions::to_string_t("DefaultApi->refresh does not consume any supported media type"));
    }

    return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("POST"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
    .then([=](web::http::http_response localVarResponse)
    {
        if (m_ApiClient->getResponseHeadersHandler())
        {
            m_ApiClient->getResponseHeadersHandler()(localVarResponse.headers());
        }

        // 1xx - informational : OK
        // 2xx - successful       : OK
        // 3xx - redirection   : OK
        // 4xx - client error  : not OK
        // 5xx - client error  : not OK
        if (localVarResponse.status_code() >= 400)
        {
            throw ApiException(localVarResponse.status_code()
                , utility::conversions::to_string_t("error calling refresh: ") + localVarResponse.reason_phrase()
                , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
        }

        // check response content type
        if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
        {
            utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
            if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
            {
                throw ApiException(500
                    , utility::conversions::to_string_t("error calling refresh: unexpected response type: ") + localVarContentType
                    , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
            }
        }

        return localVarResponse.extract_string();
    })
    .then([=](utility::string_t localVarResponse)
    {
        std::shared_ptr<RefreshResponse> localVarResult(new RefreshResponse());

        if(localVarResponseHttpContentType == utility::conversions::to_string_t("application/json"))
        {
            web::json::value localVarJson = web::json::value::parse(localVarResponse);

            localVarResult->fromJson(localVarJson);
        }
        // else if(localVarResponseHttpContentType == utility::conversions::to_string_t("multipart/form-data"))
        // {
        // TODO multipart response parsing
        // }
        else
        {
            throw ApiException(500
                , utility::conversions::to_string_t("error calling refresh: unsupported response type"));
        }

        return localVarResult;
    });
}
pplx::task<void> DefaultApi::siginout(std::shared_ptr<UsernamePassword> usernamePassword)
{

    // verify the required parameter 'usernamePassword' is set
    if (usernamePassword == nullptr)
    {
        throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'usernamePassword' when calling DefaultApi->siginout"));
    }

    std::shared_ptr<ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
    utility::string_t localVarPath = utility::conversions::to_string_t("/signout");

    std::map<utility::string_t, utility::string_t> localVarQueryParams;
    std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
    std::map<utility::string_t, utility::string_t> localVarFormParams;
    std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;

    std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
    localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );

    utility::string_t localVarResponseHttpContentType;

    // use JSON if possible
    if ( localVarResponseHttpContentTypes.size() == 0 )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // JSON
    else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // multipart formdata
    else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
    }
    else
    {
        throw ApiException(400, utility::conversions::to_string_t("DefaultApi->siginout does not produce any supported media type"));
    }

    localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;

    std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
    localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );

    std::shared_ptr<IHttpBody> localVarHttpBody;
    utility::string_t localVarRequestHttpContentType;

    // use JSON if possible
    if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
        web::json::value localVarJson;

        localVarJson = ModelBase::toJson(usernamePassword);

        localVarHttpBody = std::shared_ptr<IHttpBody>( new JsonBody( localVarJson ) );
    }
    // multipart formdata
    else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
        std::shared_ptr<MultipartFormData> localVarMultipart(new MultipartFormData);

        if(usernamePassword.get())
        {
            usernamePassword->toMultipart(localVarMultipart, utility::conversions::to_string_t("usernamePassword"));
        }

        localVarHttpBody = localVarMultipart;
        localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary();
    }
    else
    {
        throw ApiException(415, utility::conversions::to_string_t("DefaultApi->siginout does not consume any supported media type"));
    }

    return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("POST"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
    .then([=](web::http::http_response localVarResponse)
    {
        if (m_ApiClient->getResponseHeadersHandler())
        {
            m_ApiClient->getResponseHeadersHandler()(localVarResponse.headers());
        }

        // 1xx - informational : OK
        // 2xx - successful       : OK
        // 3xx - redirection   : OK
        // 4xx - client error  : not OK
        // 5xx - client error  : not OK
        if (localVarResponse.status_code() >= 400)
        {
            throw ApiException(localVarResponse.status_code()
                , utility::conversions::to_string_t("error calling siginout: ") + localVarResponse.reason_phrase()
                , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
        }

        // check response content type
        if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
        {
            utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
            if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
            {
                throw ApiException(500
                    , utility::conversions::to_string_t("error calling siginout: unexpected response type: ") + localVarContentType
                    , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
            }
        }

        return localVarResponse.extract_string();
    })
    .then([=](utility::string_t localVarResponse)
    {
        return void();
    });
}
pplx::task<void> DefaultApi::validate(std::shared_ptr<AccessKeys> accessKeys)
{

    // verify the required parameter 'accessKeys' is set
    if (accessKeys == nullptr)
    {
        throw ApiException(400, utility::conversions::to_string_t("Missing required parameter 'accessKeys' when calling DefaultApi->validate"));
    }

    std::shared_ptr<ApiConfiguration> localVarApiConfiguration( m_ApiClient->getConfiguration() );
    utility::string_t localVarPath = utility::conversions::to_string_t("/validate");

    std::map<utility::string_t, utility::string_t> localVarQueryParams;
    std::map<utility::string_t, utility::string_t> localVarHeaderParams( localVarApiConfiguration->getDefaultHeaders() );
    std::map<utility::string_t, utility::string_t> localVarFormParams;
    std::map<utility::string_t, std::shared_ptr<HttpContent>> localVarFileParams;

    std::unordered_set<utility::string_t> localVarResponseHttpContentTypes;
    localVarResponseHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );

    utility::string_t localVarResponseHttpContentType;

    // use JSON if possible
    if ( localVarResponseHttpContentTypes.size() == 0 )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // JSON
    else if ( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("application/json");
    }
    // multipart formdata
    else if( localVarResponseHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarResponseHttpContentTypes.end() )
    {
        localVarResponseHttpContentType = utility::conversions::to_string_t("multipart/form-data");
    }
    else
    {
        throw ApiException(400, utility::conversions::to_string_t("DefaultApi->validate does not produce any supported media type"));
    }

    localVarHeaderParams[utility::conversions::to_string_t("Accept")] = localVarResponseHttpContentType;

    std::unordered_set<utility::string_t> localVarConsumeHttpContentTypes;
    localVarConsumeHttpContentTypes.insert( utility::conversions::to_string_t("application/json") );

    std::shared_ptr<IHttpBody> localVarHttpBody;
    utility::string_t localVarRequestHttpContentType;

    // use JSON if possible
    if ( localVarConsumeHttpContentTypes.size() == 0 || localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("application/json")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("application/json");
        web::json::value localVarJson;

        localVarJson = ModelBase::toJson(accessKeys);

        localVarHttpBody = std::shared_ptr<IHttpBody>( new JsonBody( localVarJson ) );
    }
    // multipart formdata
    else if( localVarConsumeHttpContentTypes.find(utility::conversions::to_string_t("multipart/form-data")) != localVarConsumeHttpContentTypes.end() )
    {
        localVarRequestHttpContentType = utility::conversions::to_string_t("multipart/form-data");
        std::shared_ptr<MultipartFormData> localVarMultipart(new MultipartFormData);

        if(accessKeys.get())
        {
            accessKeys->toMultipart(localVarMultipart, utility::conversions::to_string_t("accessKeys"));
        }

        localVarHttpBody = localVarMultipart;
        localVarRequestHttpContentType += utility::conversions::to_string_t("; boundary=") + localVarMultipart->getBoundary();
    }
    else
    {
        throw ApiException(415, utility::conversions::to_string_t("DefaultApi->validate does not consume any supported media type"));
    }

    return m_ApiClient->callApi(localVarPath, utility::conversions::to_string_t("POST"), localVarQueryParams, localVarHttpBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarRequestHttpContentType)
    .then([=](web::http::http_response localVarResponse)
    {
        if (m_ApiClient->getResponseHeadersHandler())
        {
            m_ApiClient->getResponseHeadersHandler()(localVarResponse.headers());
        }

        // 1xx - informational : OK
        // 2xx - successful       : OK
        // 3xx - redirection   : OK
        // 4xx - client error  : not OK
        // 5xx - client error  : not OK
        if (localVarResponse.status_code() >= 400)
        {
            throw ApiException(localVarResponse.status_code()
                , utility::conversions::to_string_t("error calling validate: ") + localVarResponse.reason_phrase()
                , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
        }

        // check response content type
        if(localVarResponse.headers().has(utility::conversions::to_string_t("Content-Type")))
        {
            utility::string_t localVarContentType = localVarResponse.headers()[utility::conversions::to_string_t("Content-Type")];
            if( localVarContentType.find(localVarResponseHttpContentType) == std::string::npos )
            {
                throw ApiException(500
                    , utility::conversions::to_string_t("error calling validate: unexpected response type: ") + localVarContentType
                    , std::make_shared<std::stringstream>(localVarResponse.extract_utf8string(true).get()));
            }
        }

        return localVarResponse.extract_string();
    })
    .then([=](utility::string_t localVarResponse)
    {
        return void();
    });
}

}
}
}
}
}
}
}
}

max_stars_repo_name: AsyncMC/Mojang-API-Libs

max_issues_repo_name: AsyncMC/Mojang-API-Libs

max_forks_repo_name: AsyncMC/Mojang-API-Libs


text:
//  numeric_cast.hpp
//
//  (C) Copyright 2011 Vicente J. Botet Escriba
//  Use, modification and distribution are subject to 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_RATIO_MPL_NUMERIC_CAST_HPP
#define BOOST_RATIO_MPL_NUMERIC_CAST_HPP

#include <boost/ratio/ratio.hpp>
#include <boost/mpl/integral_c.hpp>
#include <boost/ratio/mpl/rational_c_tag.hpp>
#include <boost/mpl/numeric_cast.hpp>

namespace boost {
namespace mpl {

template<> struct numeric_cast< integral_c_tag,rational_c_tag >
{
    template< typename N > struct apply
        : ratio< N::value, 1 >
    {
    };
};

}
}

#endif  // BOOST_RATIO_MPL_NUMERIC_CAST_HPP

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
/*
 *  Copyright (c), 2017, Adrien Devresse <adrien.devresse@epfl.ch>
 *
 *  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 <cstdlib>
#include <iostream>
#include <string>
#include <typeinfo>
#include <vector>

#include <highfive/H5File.hpp>
#include <highfive/H5DataSet.hpp>
#include <highfive/H5DataSpace.hpp>
#include <highfive/H5Group.hpp>

#define BOOST_TEST_MAIN HighFiveTest
#include <boost/mpl/list.hpp>
#include <boost/test/included/unit_test.hpp>

using namespace HighFive;

int argc = boost::unit_test::framework::master_test_suite().argc;
char** argv = boost::unit_test::framework::master_test_suite().argv;

struct MpiFixture {
    MpiFixture() { MPI_Init(&argc, &argv); }

    ~MpiFixture() { MPI_Finalize(); }
};

BOOST_GLOBAL_FIXTURE(MpiFixture);

typedef boost::mpl::list<int, unsigned, long, unsigned long, unsigned char,
                         char, float, double, long long, unsigned long long>
    numerical_test_types;

template <typename T>
struct ContentGenerate {
    ContentGenerate(T init_val = T(0), T inc_val = T(1) + T(1) / T(10))
        : _init(init_val), _inc(inc_val) {}

    T operator()() {
        T ret = _init;
        _init += _inc;
        return ret;
    }

    T _init, _inc;
};

template <>
struct ContentGenerate<char> {
    ContentGenerate() : _init('a') {}

    char operator()() {
        char ret = _init;
        if (++_init >= ('a' + 26))
            _init = 'a';
        return ret;
    }

    char _init;
};

template <>
struct ContentGenerate<std::string> {
    ContentGenerate() {}

    std::string operator()() {
        ContentGenerate<char> gen;
        std::string random_string;
        const size_t size_string = std::rand() % 1000;
        random_string.resize(size_string);
        std::generate(random_string.begin(), random_string.end(), gen);
        return random_string;
    }
};

template <typename T>
void selectionArraySimpleTestParallel() {

    int mpi_rank, mpi_size;
    MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
    MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);

    typedef typename std::vector<T> Vector;

    std::ostringstream filename;
    filename << "h5_rw_select_parallel_test_" << typeid(T).name() << "_test.h5";

    const size_t size_x = mpi_size;
    const size_t offset_x = mpi_rank, count_x = mpi_size - mpi_rank;

    const std::string DATASET_NAME("dset");

    Vector values(size_x);

    ContentGenerate<T> generator;
    std::generate(values.begin(), values.end(), generator);

    // Create a new file using the default property lists.
    File file(filename.str(), File::ReadWrite | File::Create | File::Truncate,
              MPIOFileDriver(MPI_COMM_WORLD, MPI_INFO_NULL));

    DataSet dataset =
        file.createDataSet<T>(DATASET_NAME, DataSpace::From(values));

    dataset.write(values);

    file.flush();

    // read it back
    Vector result;
    std::vector<size_t> offset;
    offset.push_back(offset_x);
    std::vector<size_t> size;
    size.push_back(count_x);

    Selection slice = dataset.select(offset, size);

    BOOST_CHECK_EQUAL(slice.getSpace().getDimensions()[0], size_x);
    BOOST_CHECK_EQUAL(slice.getMemSpace().getDimensions()[0], count_x);

    slice.read(result);

    BOOST_CHECK_EQUAL(result.size(), count_x);

    for (size_t i = offset_x; i < count_x; ++i) {
        // std::cout << result[i] << " ";
        BOOST_CHECK_EQUAL(values[i + offset_x], result[i]);
    }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(selectionArraySimple, T, numerical_test_types) {

    selectionArraySimpleTestParallel<T>();
}

max_stars_repo_name: genric/HighFive

max_issues_repo_name: genric/HighFive

max_forks_repo_name: genric/HighFive


text:
/*
 * Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
 */

#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include "base/os.h"
#include "testing/gunit.h"
#include "test/test_cmn_util.h"
#include "port_ipc/port_ipc_handler.h"

using namespace std;
namespace fs = boost::filesystem;

void RouterIdDepInit(Agent *agent) {
}

class PortIpcTest : public ::testing::Test {
 public:
     PortIpcTest() : agent_(Agent::GetInstance()) {
     }
     Agent *agent() { return agent_; }
     void AddPort(const PortIpcHandler &pih,
             const PortIpcHandler::AddPortParams &req) {
         string err_msg;
         pih.AddPort(req, false, err_msg);
     }
     bool IsUUID(const PortIpcHandler &pih, const string &file) {
         return pih.IsUUID(file);
     }
     void DeleteAllPorts(const string &dir) {
         string err_str;
         fs::path ports_dir(dir);
         fs::directory_iterator end_iter;
         //Pass directory as something different from where the files are
         //present. Otherwise it will result in deletion of files
         PortIpcHandler pih(agent(), "dummy", false);

         if (!fs::exists(ports_dir) || !fs::is_directory(ports_dir)) {
             return;
         }

         fs::directory_iterator it(ports_dir);
         BOOST_FOREACH(fs::path const &p, std::make_pair(it, end_iter)) {
             if (!fs::is_regular_file(p)) {
                 continue;
             }
             if (!IsUUID(pih, p.filename().string())) {
                 continue;
             }
             pih.DeletePort(p.filename().string(), err_str);
         }
     }

 private:
     Agent *agent_;
};

/* Add/delete a port */
TEST_F(PortIpcTest, Port_Add_Del) {

    const string dir = "/tmp/";
    CfgIntTable *ctable = agent()->interface_config_table();
    assert(ctable);
    uint32_t port_count = ctable->Size();
    std::string err_str;

    PortIpcHandler::AddPortParams req("ea73b285-01a7-4d3e-8322-50976e8913da",
        "ea73b285-01a7-4d3e-8322-50976e8913db",
        "fa73b285-01a7-4d3e-8322-50976e8913de",
        "b02a3bfb-7946-4b1c-8cc4-bf8cedcbc48d", "vm1", "tap1af4bee3-04",
        "11.0.0.3", "", "02:1a:f4:be:e3:04", 0, -1, -1);
    PortIpcHandler pih(agent(), dir, false);
    AddPort(pih, req);
    client->WaitForIdle(2);
    WAIT_FOR(500, 1000, ((port_count + 1) == ctable->Size()));

    pih.DeletePort(req.port_id, err_str);
    client->WaitForIdle(2);
    WAIT_FOR(500, 1000, ((port_count) == ctable->Size()));
}

/* Reads files in a directory and adds port info into agent */
TEST_F(PortIpcTest, PortReload) {

    const string dir = "controller/src/vnsw/agent/port_ipc/test/";
    CfgIntTable *ctable = agent()->interface_config_table();
    assert(ctable);
    uint32_t port_count = ctable->Size();

    //There are 2 files present in controller/src/vnsw/agent/port_ipc/test/
    PortIpcHandler pih(agent(), dir, false);
    pih.ReloadAllPorts();
    client->WaitForIdle(2);

    // Port count should increase by 2 as we have 2 ports
    WAIT_FOR(500, 1000, ((port_count + 2) == ctable->Size()));

    //cleanup
    DeleteAllPorts(dir);
    client->WaitForIdle(2);
    WAIT_FOR(500, 1000, ((port_count) == ctable->Size()));
}

int main (int argc, char **argv) {
    GETUSERARGS();
    client = TestInit(init_file, ksync_init);
    int ret = RUN_ALL_TESTS();
    client->WaitForIdle();
    TestShutdown();
    delete client;
    return ret;
}

max_stars_repo_name: madkiss/contrail-controller

max_issues_repo_name: madkiss/contrail-controller

max_forks_repo_name: madkiss/contrail-controller


text:
//----------------------------------------------------------------------------
/// \file  map.hpp
//----------------------------------------------------------------------------
/// \brief A class implementing an map object of Erlang external term format.
//----------------------------------------------------------------------------
// Copyright (c) 2020 Serge Aleynikov <saleyn@gmail.com>
// Created: 2020-06-10
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

Copyright 2010 Serge Aleynikov <saleyn at gmail dot com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

***** END LICENSE BLOCK *****
*/
#ifndef _IMPL_MAP_HPP_
#define _IMPL_MAP_HPP_

#include <ostream>
#include <initializer_list>
#include <map>
#include <boost/assert.hpp>
#include <eixx/marshal/alloc_base.hpp>
#include <eixx/marshal/varbind.hpp>
#include <eixx/marshal/visit.hpp>
#include <eixx/marshal/visit_encode_size.hpp>
#include <ei.h>

namespace eixx {
namespace marshal {

template <typename Alloc> class eterm;

template <typename Alloc>
class map {
public:
    using MapAlloc = typename std::allocator_traits<Alloc>::template rebind_alloc<std::pair<const eterm<Alloc>, eterm<Alloc>>>;
    using MapT     = std::map<eterm<Alloc>, eterm<Alloc>, std::less<eterm<Alloc>>, MapAlloc>;
protected:
    using BlobT    = blob<MapT, Alloc>;

    BlobT* m_blob;

    void release() { release(m_blob); m_blob = nullptr; }

    void release(BlobT* p) {
        if (p && p->release(false)) {
            p->data()->~MapT();
            p->free();
        }
    }

    void initialize(const Alloc& alloc = Alloc()) {
        m_blob = new BlobT(1, alloc);
        auto* m = m_blob->data();
        new  (m)  MapT();
    }
public:
    using const_iterator = typename MapT::const_iterator;
    using iterator       = typename MapT::iterator;

    static const map<Alloc>& null() { static map<Alloc> s = map<Alloc>(Alloc()); return s; }

    explicit map(std::nullptr_t) : m_blob(nullptr) {}

    explicit map(const Alloc& a = Alloc()) {
        static_assert(sizeof(map<Alloc>) == sizeof(void*), "Invalid class size!");
        initialize(a);
    }

    map(const map<Alloc>& s) : m_blob(s.m_blob) {
        if (m_blob) m_blob->inc_rc();
    }

    map(map<Alloc>&& s) : m_blob(s.m_blob) {
        s.m_blob = nullptr;
    }

    map(std::initializer_list<std::pair<const eterm<Alloc>,eterm<Alloc>>> items, const Alloc& alloc = Alloc()) {
        initialize(alloc);
        auto* m = m_blob->data();
        for  (auto& pair : items)
            m->insert(pair);
    }

    map(const char* buf, uintptr_t& idx, size_t size, const Alloc& a_alloc = Alloc()) {
        BOOST_ASSERT(idx <= INT_MAX);
        int arity;
        if (ei_decode_map_header(buf, (int*)&idx, &arity) < 0)
            err_decode_exception("Error decoding tuple header", idx);
        initialize(a_alloc);
        auto* m = m_blob->data();
        for (int i=0; i < arity; i++) {
            auto key = eterm<Alloc>(buf, idx, size, a_alloc);
            auto val = eterm<Alloc>(buf, idx, size, a_alloc);
            m->emplace(std::make_pair(key, val));
        }
        BOOST_ASSERT((size_t)idx <= size);
    }

    ~map() {
        release();
    }

    map<Alloc>& operator= (const map<Alloc>& s) {
        if (this != &s) {
            release();
            m_blob = s.m_blob;
            if (m_blob) m_blob->inc_rc();
        }
        return *this;
    }

    map<Alloc>& operator= (map<Alloc>&& s) {
        if (this != &s) {
            release();
            m_blob = s.m_blob;
            s.m_blob = nullptr;
        }
        return *this;
    }

    const eterm<Alloc>& operator[](const eterm<Alloc>& key) const {
        static const eterm<Alloc> s_undefined = am_undefined;
        if (!m_blob) return s_undefined;
        auto    it =  m_blob->data()->find(key);
        return (it == m_blob->data()->end()) ? s_undefined : it->second;
    }

    void        insert(const eterm<Alloc>& key, const eterm<Alloc>& val) {
        if (!m_blob) initialize();
        m_blob->data()->insert(std::make_pair(key, val));
    }

    void        erase(const eterm<Alloc>& key) {
        if (!m_blob) return;
        m_blob->data()->erase(key);
    }

    const_iterator begin()  const { return m_blob ? m_blob->data()->cbegin() : null().begin(); }
    const_iterator end()    const { return m_blob ? m_blob->data()->cend()   : null().end();   }

    size_t      size()   const { return m_blob ? m_blob->data()->size() : 0; }
    bool        empty()  const { return !m_blob || m_blob->data()->empty();  }

    void        clear()        { if (m_blob) m_blob->data().clear(); }

    // Use only for debugging
    int         use_count() const { return m_blob ? m_blob->use_count() : -1000000; }

    bool operator== (const map<Alloc>& rhs) const {
        if (size() != rhs.size()) return false;
        auto it1  = begin();
        auto it2  = rhs.begin();
        auto end1 = end();
        for (; it1 != end1; ++it1, ++it2)
            if (!(*it1 == *it2))
                return false;
        return true;
    }

    bool operator<  (const map<Alloc>& rhs) const {
        if (size() < rhs.size()) return true;
        if (size() > rhs.size()) return false;
        BOOST_ASSERT(size() == rhs.size());
        auto it1  = begin();
        auto it2  = rhs.begin();
        auto end1 = end();
        for (; it1 != end1; ++it1, ++it2) {
            // 1. Is key1 < key2?
            if (it1->first < it2->first)
                return true;
            if (it2->first < it1->first)
                return false;
            // 1. Is value1 < value2?
            if (it1->second < it2->second)
                return true;
            if (it2->second < it1->second)
                return false;
        }
        return size() == 0;
    }

    /** Size of buffer needed to hold the encoded map. */
    size_t encode_size() const {
        BOOST_ASSERT(m_blob);
        size_t result = 5;
        for (const_iterator it = begin(), iend = end(); it != iend; ++it) {
            result += visit_eterm_encode_size_calc<Alloc>().apply_visitor(it->first);  // key
            result += visit_eterm_encode_size_calc<Alloc>().apply_visitor(it->second); // value
        }
        return result;
    }

    void encode(char* buf, uintptr_t& idx, size_t size) const {
        BOOST_ASSERT(m_blob);
        BOOST_ASSERT(idx <= INT_MAX);
        size_t arity = this->size();
        if (arity > INT_MAX)
            throw err_encode_exception("MAP_EXT arity exceeds maximum supported");
        ei_encode_map_header(buf, (int*)&idx, (int)arity);
        for(auto it = begin(), iend=end(); it != iend; ++it) {
            visit_eterm_encoder key_visitor(buf, idx, size);
            key_visitor.apply_visitor(it->first);
            visit_eterm_encoder val_visitor(buf, idx, size);
            val_visitor.apply_visitor(it->second);
        }
        BOOST_ASSERT((size_t)idx <= size);
    }

    std::ostream& dump(std::ostream& out, const varbind<Alloc>* binding=NULL) const {
        out << "#{";
        for(auto it = begin(), first=begin(), iend=end(); it != iend; ++it) {
            out << (it != first ? "," : "");
            visit_eterm_stringify<Alloc> key_visitor(out, binding);
            key_visitor.apply_visitor(it->first);
            out << " => ";
            visit_eterm_stringify<Alloc> val_visitor(out, binding);
            val_visitor.apply_visitor(it->second);
        }
        return out << '}';
    }
};

} // namespace marshal
} // namespace eixx

namespace std {

    template <typename Alloc>
    ostream& operator<< (ostream& out, const eixx::marshal::map<Alloc>& m) { return m.dump(out); }

}

//#include <eixx/marshal/map.hxx>

#endif // _IMPL_MAP_HPP_


text:
#include <haptic_sandbox/haptic_interaction_tool.h>
#include <conversions/tf_chai.h>

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

namespace something {

HapticInteractionTool::~HapticInteractionTool()
    {
        if(chai_device_handler_) delete chai_device_handler_;
        if(chai_device_)
        {
            chai_device_->setForceAndTorqueAndGripperForce(cVector3d(0,0,0), cVector3d(0,0,0), 0);
            chai_device_->close();
            delete chai_device_;
        }
    }

void HapticInteractionTool::init()
{

    cHapticDeviceInfo info = chai_device_->getSpecifications();
    cVector3d pos = info.m_positionOffset;
    setPosition(tf::Vector3(pos.x(), pos.y(), pos.z()));
    setQuaternion(tf::createQuaternionFromYaw(M_PI)*tf::createQuaternionFromRPY(0, 0.4, 0));

    std::string modelName = info.m_modelName;

    int button_count = 0;
    if(modelName == "PHANTOM Omni") button_count = 2;
    else if(modelName == "Falcon") button_count = 4;
    else if(modelName == "omega") button_count = 1;
    setToolButtonCount(button_count);

    workspace_radius_ = workspace_radius_ / info.m_workspaceRadius;

    // TODO this should be a chai thread...!
    ros::NodeHandle nh;
    float update_period = 0.01;
    interaction_timer_ = nh.createTimer(ros::Duration(update_period), boost::bind( &HapticInteractionTool::updateDevice, this ) );
}

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

void HapticInteractionTool::updateButtonStates()
{
    for(size_t i = 0; i < getToolButtonCount(); ++i)
    {
        bool state = false;
        chai_device_->getUserSwitch(i, state );
        setToolButtonState(i, state);
    }
}

// Call an update?
void HapticInteractionTool::updateDevice()
{

    // Get the state of all buttons
    updateButtonStates();

    // Get position and velocity info for the haptic handle

    // read position
    cVector3d position;
    chai_device_->getPosition(position);
    position = workspace_radius_*position;

    // read orientation
    cMatrix3d rotation;
    chai_device_->getRotation(rotation);

    // read gripper position
    double gripperAngle;
    chai_device_->getGripperAngleRad(gripperAngle);

    // read linear velocity
    cVector3d linearVelocity;
    chai_device_->getLinearVelocity(linearVelocity);
    linearVelocity = workspace_radius_*linearVelocity;

    // read angular velocity
    cVector3d angularVelocity;
    chai_device_->getAngularVelocity(angularVelocity);

    // read gripper angular velocity
    double gripperAngularVelocity;
    chai_device_->getGripperAngularVelocity(gripperAngularVelocity);

    tf::Transform haptic_handle, interaction_handle;
    haptic_handle = interaction_handle = tf::Transform::getIdentity();
    haptic_handle = tf::Transform(tf::matrixChaiToTf(rotation), tf::vectorChaiToTf(position));
    //if(getToolButtonState(0))
        interaction_handle = haptic_handle*tf::Transform(tf::createQuaternionFromRPY(0,0,M_PI));
    //else
    //    interaction_handle = haptic_handle;
    handle_->setTransform(interaction_handle);

    cVector3d force, torque;
    float gripperForce = 0;

    // send computed force, torque and gripper force to haptic device
    chai_device_->setForceAndTorqueAndGripperForce(force, torque, gripperForce);

}

}  // namespace something

max_issues_repo_name: salisbury-robotics/jks-ros-pkg

max_forks_repo_name: salisbury-robotics/jks-ros-pkg