text:
/*
 * libcryptoplus - C++ portable OpenSSL cryptographic wrapper library.
 * Copyright (C) 2010-2011 Julien Kauffmann <julien.kauffmann@freelan.org>
 *
 * This file is part of libcryptoplus.
 *
 * libcryptoplus 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.
 *
 * libcryptoplus is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.  If you delete this exception statement from all source
 * files in the program, then also delete it here.
 *
 * If you intend to use libcryptoplus in a commercial software, please
 * contact me : we may arrange this for a small fee or no fee at all,
 * depending on the nature of your project.
 */

/**
 * \file cipher_context.hpp
 * \author Julien KAUFFMANN <julien.kauffmann@freelan.org>
 * \brief A cipher context class.
 */

#ifndef CRYPTOPLUS_CIPHER_CIPHER_CONTEXT_HPP
#define CRYPTOPLUS_CIPHER_CIPHER_CONTEXT_HPP

#include "../buffer.hpp"
#include "../error/helpers.hpp"
#include "cipher_algorithm.hpp"

#include <openssl/evp.h>

#include <boost/noncopyable.hpp>

#include <vector>
#include <string>
#include <cstring>

namespace cryptoplus
{
	namespace pkey
	{
		class pkey;
	}

	namespace cipher
	{
		/**
		 * \brief A cipher context class.
		 *
		 * The cipher_context class ease the computation of a cipher.
		 *
		 * The list of the available cipher methods depends on the version of OpenSSL and can be found on the man page of EVP_EncryptInit().
		 *
		 * cipher_context is noncopyable by design.
		 */
		class cipher_context : public boost::noncopyable
		{
			public:

				/**
				 * \brief The cipher direction.
				 */
				enum cipher_direction
				{
					unchanged = -1, /**< \brief The direction did not change since the last call. */
					decrypt = 0, /**< \brief Specifies a decryption cipher context. */
					encrypt = 1 /**< \brief Specifies an encryption cipher context. */
				};

				/**
				 * \brief Create a new cipher_context.
				 */
				cipher_context();

				/**
				 * \brief Destroy a cipher_context.
				 *
				 * Calls EVP_CIPHER_CTX_cleanup() on the internal EVP_CIPHER_CTX.
				 */
				~cipher_context();

				/**
				 * \brief Initialize the cipher_context.
				 * \param algorithm The cipher algorithm to use.
				 * \param direction The direction of the cipher_context. If a previous call to initialize() was done, you may specify cipher_direction::unchanged to keep the same direction value.
				 * \param key The key to use. Cannot be NULL.
				 * \param key_len The length of key. Must match algorithm.key_length() or a std::runtime_error is thrown.
				 * \param iv The iv to use (if one is needed for the specified algorithm, NULL otherwise).
				 * \param impl The engine to use. Default is NULL which indicates that no engine should be used.
				 * \see set_padding
				 *
				 * The list of the available hash methods depends on the version of OpenSSL and can be found on the man page of EVP_EncryptInit().
				 *
				 * Once the cipher_context is initialized, you may enable or disable PKCS padding by calling set_padding(). By default, PKCS padding is enabled.
				 */
				void initialize(const cipher_algorithm& algorithm, cipher_direction direction, const void* key, size_t key_len, const void* iv, ENGINE* impl = NULL);

				/**
				 * \brief Initialize the cipher_context for envelope sealing.
				 * \param algorithm The cipher algorithm to use.
				 * \param iv The iv that was generated (if one is needed for the specified algorithm, NULL otherwise).
				 * \param pkeys_begin A pointer to the first public pkey to use.
				 * \param pkeys_end A pointer past the last public pkey to use.
				 * \return The public encrypted shared secret keys array.
				 * \see seal_update
				 * \see seal_finalize
				 */
				template <typename T>
				std::vector<buffer> seal_initialize(const cipher_algorithm& algorithm, void* iv, T pkeys_begin, T pkeys_end);

				/**
				 * \brief Initialize the cipher_context for envelope sealing.
				 * \param algorithm The cipher algorithm to use.
				 * \param iv The iv that was generated (if one is needed for the specified algorithm, NULL otherwise).
				 * \param pkey The public pkey to use.
				 * \return The public encrypted shared secret key.
				 * \see seal_update
				 * \see seal_finalize
				 */
				buffer seal_initialize(const cipher_algorithm& algorithm, void* iv, pkey::pkey pkey);

				/**
				 * \brief Initialize the cipher_context for envelope opening.
				 * \param algorithm The cipher algorithm to use.
				 * \param key The encrypted shared secret key.
				 * \param key_len The length of key. Must match algorithm.key_length() or a std::runtime_error is thrown.
				 * \param iv The iv to use (if one is needed for the specified algorithm, NULL otherwise).
				 * \param pkey The private pkey to use.
				 * \see open_update
				 * \see open_finalize
				 */
				void open_initialize(const cipher_algorithm& algorithm, const void* key, size_t key_len, const void* iv, pkey::pkey pkey);

				/**
				 * \brief Set PKCS padding state.
				 * \param enabled If enabled is true, PKCS padding will be enabled.
				 * \see cipher_algorithm::block_size
				 *
				 * If PKCS padding is disabled, the input data size must be an exact multiple of the specified algorithm block size. See cipher_algorithm::block_size().
				 */
				void set_padding(bool enabled);

				/**
				 * \brief Get the size of the ISO 10126 padding for a buffer of the specified size.
				 * \param len The length of the buffer.
				 * \return The size of the ISO 10126 padded result.
				 */
				size_t get_iso_10126_padding_size(size_t len) const;

				/**
				 * \brief Pad the given buffer using the ISO 10126 padding.
				 * \param buf The buffer.
				 * \param buf_len The length of buf.
				 * \param max_buf_len The maximum length of buf. Should be at least ((buf_len / algorithm().block_size()) + 1) * algorithm().block_size().
				 * \return The new size of the buffer.
				 */
				size_t add_iso_10126_padding(void* buf, size_t buf_len, size_t max_buf_len) const;

				/**
				 * \brief Get an ISO 10126 padded copy of the specified buffer.
				 * \param buf The buffer.
				 * \param buf_len The length of buf.
				 * \return The resulting buffer.
				 */
				buffer get_iso_10126_padded_buffer(const void* buf, size_t buf_len) const;

				/**
				 * \brief Verify the given buffer and check if it matches ISO 10126 padding.
				 * \param buf The buffer.
				 * \param buf_len The length of buf, including its padding. Should be a multiple of algorithm().block_size().
				 * \return The size of the data, without any padding.
				 */
				size_t verify_iso_10126_padding(const void* buf, size_t buf_len) const;

				/**
				 * \brief Get the key length.
				 * \return The key length.
				 * \see set_key_length
				 *
				 * For fixed key length ciphers, returns the same value as algorithm().key_length().
				 * For variable key length ciphers, returns the current used key length value. See set_key_length().
				 */
				size_t key_length() const;

				/**
				 * \brief Set the current key length for variable key length ciphers.
				 * \param len The new key length.
				 * \warning Attempting to set the key length of a fixed key length cipher is an error.
				 */
				void set_key_length(size_t len);

				/**
				 * \brief Control cipher specific parameters.
				 * \param type The type.
				 * \param set_value The first value.
				 * \param get_value The second value.
				 */
				void ctrl(int type, int set_value, void* get_value);
				/**
				 * \brief Get cipher specific parameters.
				 * \param type The type.
				 * \param value The value to get.
				 */
				template <typename T>
				void ctrl_get(int type, T& value);

				/**
				 * \brief Set cipher specific parameters.
				 * \param type The type.
				 * \param value The value to set.
				 */
				void ctrl_set(int type, int value);

				/**
				 * \brief Update the cipher_context with some data.
				 * \param out The output buffer. Should be at least in_len + algorithm().block_size() bytes long. Cannot be NULL.
				 * \param out_len The length of the out buffer.
				 * \param in The input buffer.
				 * \param in_len The length of the in buffer.
				 * \return The count of bytes written.
				 */
				size_t update(void* out, size_t out_len, const void* in, size_t in_len);

				/**
				 * \brief Update the cipher_context with some data.
				 * \param out The output buffer. Should be at least in_len + algorithm().block_size() bytes long. Cannot be NULL.
				 * \param out_len The length of the out buffer. Will be updated to indicate the written bytes count.
				 * \param in The input buffer.
				 * \param in_len The length of the in buffer.
				 * \return The count of bytes written.
				 */
				size_t seal_update(void* out, size_t out_len, const void* in, size_t in_len);

				/**
				 * \brief Update the cipher_context with some data.
				 * \param out The output buffer. Should be at least in_len + algorithm().block_size() bytes long. Cannot be NULL.
				 * \param out_len The length of the out buffer. Will be updated to indicate the written bytes count.
				 * \param in The input buffer.
				 * \param in_len The length of the in buffer.
				 * \return The count of bytes written.
				 */
				size_t open_update(void* out, size_t out_len, const void* in, size_t in_len);

				/**
				 * \brief Update the cipher_context with some data.
				 * \param out The output buffer. Should be at least in_len + algorithm().block_size() bytes long. Cannot be NULL.
				 * \param out_len The length of the out buffer.
				 * \param in The input buffer.
				 * \return The count of bytes written.
				 */
				size_t update(void* out, size_t out_len, const buffer& in);

				/**
				 * \brief Update the cipher_context with some data.
				 * \param out The output buffer. Should be at least in_len + algorithm().block_size() bytes long. Cannot be NULL.
				 * \param out_len The length of the out buffer. Will be updated to indicate the written bytes count.
				 * \param in The input buffer.
				 * \return The count of bytes written.
				 */
				size_t seal_update(void* out, size_t out_len, const buffer& in);

				/**
				 * \brief Update the cipher_context with some data.
				 * \param out The output buffer. Should be at least in_len + algorithm().block_size() bytes long. Cannot be NULL.
				 * \param out_len The length of the out buffer. Will be updated to indicate the written bytes count.
				 * \param in The input buffer.
				 * \return The count of bytes written.
				 */
				size_t open_update(void* out, size_t out_len, const buffer& in);

				/**
				 * \brief Finalize the cipher_context and get the resulting buffer.
				 * \param out The output buffer. Should be at least algorithm().block_size() bytes long. Cannot be NULL.
				 * \param out_len The length of the out buffer.
				 * \return The count of bytes written.
				 *
				 * After a call to finalize() no more call to update() can be made unless initialize() is called again first.
				 */
				size_t finalize(void* out, size_t out_len);

				/**
				 * \brief Finalize the cipher_context and get the resulting buffer.
				 * \param out The output buffer. Should be at least algorithm().block_size() bytes long. Cannot be NULL.
				 * \param out_len The length of the out buffer.
				 * \return The count of bytes written.
				 *
				 * After a call to seal_finalize() no more call to seal_update() can be made unless seal_initialize() is called again first.
				 */
				size_t seal_finalize(void* out, size_t out_len);

				/**
				 * \brief Finalize the cipher_context and get the resulting buffer.
				 * \param out The output buffer. Should be at least algorithm().block_size() bytes long. Cannot be NULL.
				 * \param out_len The length of the out buffer.
				 * \return The count of bytes written.
				 *
				 * After a call to open_finalize() no more call to open_update() can be made unless open_initialize() is called again first.
				 */
				size_t open_finalize(void* out, size_t out_len);

				/**
				 * \brief Get the underlying context.
				 * \return The underlying context.
				 * \warning This method is provided for compatibility issues only. Its use is greatly discouraged.
				 */
				const EVP_CIPHER_CTX& raw() const;

				/**
				 * \brief Get the underlying context.
				 * \return The underlying context.
				 * \warning This method is provided for compatibility issues only. Its use is greatly discouraged.
				 */
				EVP_CIPHER_CTX& raw();

				/**
				 * \brief Get the associated cipher algorithm.
				 * \return The associated cipher algorithm. If no call to initialize was done, the behavior is undefined.
				 */
				cipher_algorithm algorithm() const;

			private:

				EVP_CIPHER_CTX m_ctx;
		};

		inline cipher_context::cipher_context()
		{
			EVP_CIPHER_CTX_init(&m_ctx);
		}

		inline cipher_context::~cipher_context()
		{
			EVP_CIPHER_CTX_cleanup(&m_ctx);
		}

		template <typename T>
		inline std::vector<buffer> cipher_context::seal_initialize(const cipher_algorithm& _algorithm, void* iv, T pkeys_begin, T pkeys_end)
		{
			size_t pkeys_count = std::distance(pkeys_begin, pkeys_end);

			std::vector<buffer> result;
			std::vector<unsigned char*> ek;
			std::vector<int> ekl(pkeys_count);
			std::vector<EVP_PKEY*> pubk;

			ek.reserve(pkeys_count);
			pubk.reserve(pkeys_count);
			result.reserve(pkeys_count);

			if (pkeys_count > 0)
			{
				try
				{
					for (T pkey = pkeys_begin; pkey != pkeys_end; ++pkey)
					{
						ek.push_back(new unsigned char[pkey->size()]);
						pubk.push_back(pkey->raw());
					}

					throw_error_if_not(EVP_SealInit(&m_ctx, _algorithm.raw(), &ek[0], &ekl[0], static_cast<unsigned char*>(iv), &pubk[0], static_cast<int>(pkeys_count)) != 0);

					for (std::vector<unsigned char*>::iterator p = ek.begin(); p != ek.end(); ++p)
					{
						result.push_back(buffer(*p, *p + ekl[std::distance(ek.begin(), p)]));
					}
				}
				catch (...)
				{
					for (std::vector<unsigned char*>::iterator p = ek.begin(); p != ek.end(); ++p)
					{
						delete[] *p;
					}

					throw;
				}

				for (std::vector<unsigned char*>::iterator p = ek.begin(); p != ek.end(); ++p)
				{
					delete[] *p;
				}
			}

			return result;
		}

		inline void cipher_context::set_padding(bool enabled)
		{
			// The call always returns 1 so testing its return value is useless.
			EVP_CIPHER_CTX_set_padding(&m_ctx, static_cast<int>(enabled));
		}

		inline size_t cipher_context::get_iso_10126_padding_size(size_t len) const
		{
			return ((len / algorithm().block_size()) + 1) * algorithm().block_size();
		}

		inline buffer cipher_context::get_iso_10126_padded_buffer(const void* buf, size_t buf_len) const
		{
			buffer result(get_iso_10126_padding_size(buf_len));
			std::memcpy(buffer_cast<uint8_t*>(result), buf, buf_len);
			result.data().resize(add_iso_10126_padding(buffer_cast<uint8_t*>(result), buf_len, buffer_size(result)));

			return result;
		}

		inline size_t cipher_context::key_length() const
		{
			return EVP_CIPHER_CTX_key_length(&m_ctx);
		}

		inline void cipher_context::set_key_length(size_t len)
		{
			throw_error_if_not(EVP_CIPHER_CTX_set_key_length(&m_ctx, static_cast<int>(len)) != 0);
		}

		inline void cipher_context::ctrl(int type, int set_value, void* get_value)
		{
			throw_error_if_not(EVP_CIPHER_CTX_ctrl(&m_ctx, type, set_value, get_value) != 0);
		}

		template <typename T>
		inline void cipher_context::ctrl_get(int type, T& value)
		{
			throw_error_if_not(EVP_CIPHER_CTX_ctrl(&m_ctx, type, 0, &value) != 0);
		}

		inline void cipher_context::ctrl_set(int type, int value)
		{
			throw_error_if_not(EVP_CIPHER_CTX_ctrl(&m_ctx, type, value, NULL) != 0);
		}

		inline size_t cipher_context::update(void* out, size_t out_len, const buffer& in)
		{
			return update(out, out_len, buffer_cast<const uint8_t*>(in), buffer_size(in));
		}

		inline size_t cipher_context::seal_update(void* out, size_t out_len, const buffer& in)
		{
			return seal_update(out, out_len, buffer_cast<const uint8_t*>(in), buffer_size(in));
		}

		inline size_t cipher_context::open_update(void* out, size_t out_len, const buffer& in)
		{
			return open_update(out, out_len, buffer_cast<const uint8_t*>(in), buffer_size(in));
		}

		inline const EVP_CIPHER_CTX& cipher_context::raw() const
		{
			return m_ctx;
		}

		inline EVP_CIPHER_CTX& cipher_context::raw()
		{
			return m_ctx;
		}

		inline cipher_algorithm cipher_context::algorithm() const
		{
			return cipher_algorithm(EVP_CIPHER_CTX_cipher(&m_ctx));
		}
	}
}

#endif /* CRYPTOPLUS_CIPHER_CIPHER_CONTEXT_HPP */

max_stars_repo_name: krattai/AEBL

max_issues_repo_name: krattai/AEBL

max_forks_repo_name: krattai/AEBL


text:
#include <Eigen/Core>
#include <boost/math/constants/constants.hpp>
#include <limits>
#include <nlopt.hpp>
#include <vector>

#include "common.hh"
#include "scenegraph.hh"
#include "solver.hh"

namespace planner::solver {
namespace {
  std::unique_ptr<Vec<double>> lower_bounds;
  std::unique_ptr<Vec<double>> upper_bounds;

  void make_bounds(const int dim, const bool robot_movable, const Transform3r* const base_pose) {
    if (lower_bounds != nullptr && upper_bounds != nullptr) {
      return;
    }

    lower_bounds = std::make_unique<Vec<double>>(dim, 0.0);
    upper_bounds = std::make_unique<Vec<double>>(dim, 0.0);
    // TODO(Wil): Spooky scary global state
    const size_t bounds_size = cspace::workspace_bounds->low.size();
    int offset               = 0;
    if (robot_movable) {
      for (size_t i = 0; i < bounds_size; ++i) {
        lower_bounds->at(i) = cspace::workspace_bounds->low.at(i);
        upper_bounds->at(i) = cspace::workspace_bounds->high.at(i);
      }

      // Fix the Z coordinate of the robot translation
      lower_bounds->at(2) = base_pose->translation().z();
      upper_bounds->at(2) = base_pose->translation().z();
      lower_bounds->at(3) = -boost::math::double_constants::pi;
      upper_bounds->at(3) = boost::math::double_constants::pi;
      offset += bounds_size + 1;
    }

    // Add pi bounds for the continuous joints
    for (size_t i = 0; i < cspace::cont_joint_idxs.size(); ++i) {
      lower_bounds->at(offset + i) = -boost::math::double_constants::pi;
      upper_bounds->at(offset + i) = boost::math::double_constants::pi;
    }

    offset += cspace::cont_joint_idxs.size();

    // Handle remaining joints
    for (size_t i = 0; i < cspace::joint_bounds.size(); ++i) {
      lower_bounds->at(offset + i) = cspace::joint_bounds[i].first;
      upper_bounds->at(offset + i) = cspace::joint_bounds[i].second;
    }
  }
  struct OptData {
    OptData(Vec<addn::DN>& diff_state,
            const structures::robot::Robot* const robot,
            Transform3<addn::DN>& base_tf,
            structures::scenegraph::Graph* const sg,
            const addn::DN* const cont_vals,
            const addn::DN* const joint_vals,
            pred::LuaEnv<double>& grad_env,
            const spec::Formula& formula)
    : diff_state(diff_state)
    , robot(robot)
    , base_tf(base_tf)
    , sg(sg)
    , cont_vals(cont_vals)
    , joint_vals(joint_vals)
    , grad_env(grad_env)
    , formula(formula) {}

    Vec<addn::DN>& diff_state;
    const structures::robot::Robot* const robot;
    Transform3<addn::DN>& base_tf;
    structures::scenegraph::Graph* const sg;
    const addn::DN* const cont_vals;
    const addn::DN* const joint_vals;
    pred::LuaEnv<double>& grad_env;
    const spec::Formula& formula;
  };
}  // namespace

double grad_fn(const Vec<double>& inp_val, Vec<double>& grad_out, void* f_data) {
  auto* data = static_cast<OptData*>(f_data);
  auto& [diff_state, robot, base_tf, sg, cont_vals, joint_vals, grad_env, formula] = *data;
  // Convert to DNs
  for (size_t i = 0; i < diff_state.size(); ++i) {
    diff_state[i] = inp_val[i];
  }

  if (robot->base_movable) {
    pred::make_base_tf(diff_state, base_tf);
  }

  addn::DN diff_result;
  // Update the pose cache
  if (!grad_out.empty()) {
    sg->update_transforms(cont_vals,
                          joint_vals,
                          base_tf,
                          [](const structures::scenegraph::Node* const node,
                             const bool new_value,
                             const Transform3<addn::DN>& pose,
                             const Transform3r& coll_pose) {});
    // Compute each component of the gradient
    for (size_t i = 0; i < diff_state.size(); ++i) {
      diff_state[i].a = 1.0;
      // Rebuild the base pose when we're computing those components of the gradient, then once
      // after to set it back to normal
      if (robot->base_movable && i <= 4) {
        pred::make_base_tf(diff_state, base_tf);
      }

      sg->update_transforms(
      cont_vals,
      joint_vals,
      base_tf,
      [&](const structures::scenegraph::Node* const node,
          const bool new_value,
          const Transform3<addn::DN>& pose,
          const Transform3r& coll_pose) { data->grad_env.update_object(node->name, pose); },
      false);

      diff_result     = grad_env.call_formula<addn::DN>(formula);
      grad_out[i]     = diff_result.a;
      diff_state[i].a = 0.0;
    }
  } else {
    sg->update_transforms(cont_vals,
                          joint_vals,
                          base_tf,
                          [&](const structures::scenegraph::Node* const node,
                              const bool new_value,
                              const Transform3<addn::DN>& pose,
                              const Transform3r& coll_pose) {
                            data->grad_env.update_object(node->name, pose);
                          });
    diff_result = grad_env.call_formula<addn::DN>(formula);
  }

  return diff_result.v;
}

bool gradient_solve(const ob::StateSpace* const space,
                    pred::LuaEnv<double>& grad_env,
                    const structures::robot::Robot* const robot,
                    const cspace::CompositeSpace::StateType* start,
                    const spec::Formula& formula,
                    const Map<Str, Str>& bindings,
                    ob::State* result,
                    double& last_value) {
  // Separate out the state spaces for dimension and index information
  auto full_space  = space->as<ob::CompoundStateSpace>();
  auto robot_space = full_space->getSubspace(cspace::ROBOT_SPACE)->as<ob::CompoundStateSpace>();

  auto& sg = start->sg;

  // Make a double vector of the continuous parts of the state.
  // It will have the form [robot base pose (if it exists), continuous joints, other joints]
  auto state = pred::generate_state_vector(space, start, robot->base_movable);

  // Make the space bounds (only happens once)
  make_bounds(cspace::num_dims, robot->base_movable, robot->base_pose.get());

  Vec<addn::DN> diff_state(state.size(), addn::DN());
  const addn::DN* const cont_vals  = &(*diff_state.begin()) + (robot->base_movable ? 4 : 0);
  const addn::DN* const joint_vals = cont_vals + cspace::cont_joint_idxs.size();

  Transform3<addn::DN> base_tf(*(robot->base_pose));
  nlopt::opt opt_problem(nlopt::AUGLAG, state.size());
  OptData opt_data(diff_state, robot, base_tf, sg, cont_vals, joint_vals, grad_env, formula);
  opt_problem.set_min_objective(grad_fn, &opt_data);
  opt_problem.set_lower_bounds(*lower_bounds);
  opt_problem.set_upper_bounds(*upper_bounds);
  opt_problem.set_xtol_rel(1e-6);
  opt_problem.set_xtol_abs(1e-6);
  nlopt::opt local_opt(nlopt::LD_LBFGS, state.size());
  local_opt.set_lower_bounds(*lower_bounds);
  local_opt.set_upper_bounds(*upper_bounds);
  local_opt.set_xtol_rel(1e-6);
  local_opt.set_xtol_abs(1e-6);
  opt_problem.set_local_optimizer(local_opt);

  // Set up Lua objects
  grad_env.setup_world<addn::DN>(formula, bindings, sg);

  // Run gradient descent
  nlopt::result opt_result = nlopt::FAILURE;
  try {
    opt_result = opt_problem.optimize(state, last_value);
  } catch (const std::runtime_error& e) {
    // dbg(e.what());
    // dbg(opt_problem.get_errmsg());
  }

  // Tear down Lua objects
  grad_env.teardown_world(formula);

  // If we succeeded, copy the result into the output
  if (opt_result > 0) {
    // NOTE: We assume that `result` has been initialized to be the same space as `start` by the
    // caller
    // This copies the discrete part of the state (and the rest, but we overwrite that), which
    // hasn't changed
    // NOTE: This does *not* update the object poses (for manipulated objects)
    full_space->copyState(result, start);
    auto robot_state = result->as<ob::CompoundState>()->as<ob::CompoundState>(
    full_space->getSubspaceIndex(cspace::ROBOT_SPACE));
    int offset = 0;
    if (robot->base_movable) {
      auto robot_base_state = robot_state->as<cspace::RobotBaseSpace::StateType>(
      robot_space->getSubspaceIndex(cspace::BASE_SPACE));
      robot_base_state->setXYZ(state[0], state[1], state[2]);

      ob::SO2StateSpace::StateType& base_rotation = robot_base_state->rotation();
      base_rotation.value                         = state[3];
      offset += 4;
    }

    for (size_t i = 0; i < cspace::cont_joint_idxs.size(); ++i) {
      const auto idx          = cspace::cont_joint_idxs[i];
      auto* cont_joint_state  = robot_state->as<ob::SO2StateSpace::StateType>(idx);
      cont_joint_state->value = state[offset + i];
    }

    offset += cspace::cont_joint_idxs.size();

    auto* joint_state = robot_state->as<cspace::RobotJointSpace::StateType>(
    robot_space->getSubspaceIndex(cspace::JOINT_SPACE));
    for (size_t i = 0; i < cspace::joint_bounds.size(); ++i) {
      joint_state->values[i] = state[offset + i];
    }
  }

  return opt_result > 0;
}
}  // namespace planner::solver

ext: cc

max_stars_repo_name: MiaoDragon/planet

max_issues_repo_name: MiaoDragon/planet

max_forks_repo_name: MiaoDragon/planet


text:
#pragma once
#include <Eigen/Core>
#include <numeric>

namespace mtao::linear_algebra {
    // M is matrix, B is initial vector, Q is the basis for the basis
    // N is the dimension of the subspace

    namespace internal {
        template <typename Derived, typename BDerived, typename QDerived, typename HDerived>
            auto arnoldi(const Eigen::MatrixBase<Derived>& M, const Eigen::MatrixBase<BDerived>& b, Eigen::PlainObjectBase<QDerived>& Q, Eigen::PlainObjectBase<HDerived>& H) {
                const int N = H.rows() - 1;
                using Scalar = typename Derived::Scalar;
                constexpr Scalar eps = std::numeric_limits<Scalar>::epsilon();
                using Vec = Eigen::Matrix<Scalar, Derived::RowsAtCompileTime, 1>;

                Q.setZero();
                H.setZero();
                Vec v;

                Q.col(0) = b.normalized();
                for(int j = 0; j <= N; ++j) {

                    auto q = Q.col(j);
                    v = M * q;
                    for(int k = 0; k <= j; ++k) {
                        auto l = Q.col(k);
                        const Scalar s = l.dot(v);
                        H(k,j) = s;
                        v -= s * l;
                    }
                    if(j < N) {
                        const Scalar n = H(j+1,j) = v.norm();
                        if(n > eps) {
                            v /= n;
                            Q.col(j+1) = v;
                            continue;
                        }
                    }
                    return;
                }
            }
    }

    template <typename Derived, typename BDerived>
        auto arnoldi(const Eigen::MatrixBase<Derived>& M, const Eigen::MatrixBase<BDerived>& B, int N) {
            assert(M.rows() == M.cols());

            using Scalar = typename Derived::Scalar;
            using Mat = Eigen::Matrix<Scalar,Derived::RowsAtCompileTime,Eigen::Dynamic>;
            using DMat = Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>;

            Mat Q(M.rows(),N);
            DMat H(N,N);

            internal::arnoldi(M,B,Q,H);
            return std::make_tuple(Q,H);
        }
    template <int N, typename Derived, typename BDerived>
        auto arnoldi(const Eigen::MatrixBase<Derived>& M, const Eigen::MatrixBase<BDerived>& B) {
            assert(M.rows() == M.cols());

            using Scalar = typename Derived::Scalar;
            using Mat = Eigen::Matrix<Scalar,Eigen::Dynamic,N>;
            using HMat = Eigen::Matrix<Scalar,N,N>;

            Mat Q(M.rows(),N);
            HMat H(N,N);
            internal::arnoldi(M,B,Q,H);
            return std::make_tuple(Q,H);
        }
    template <typename Derived>
        auto arnoldi(const Eigen::MatrixBase<Derived>& M, int N) {
            using Scalar = typename Derived::Scalar;
            auto B = Eigen::Matrix<Scalar,Derived::RowsAtCompileTime, 1>::Random(M.rows()) ;
            return arnoldi(M,B,N);
        }
    template <int N, typename Derived>
        auto arnoldi(const Eigen::MatrixBase<Derived>& M) {
            using Scalar = typename Derived::Scalar;
            auto B = Eigen::Matrix<Scalar,Derived::RowsAtCompileTime, 1>::Random(M.rows()) ;
            return arnoldi<N>(M,B);
        }
}

ext: hpp

max_stars_repo_name: mtao/core

max_issues_repo_name: mtao/core

max_forks_repo_name: mtao/core


text:
#include "lwtnn/parse_json.hh"

// this is needed to quiet some warnings from boost
#define BOOST_BIND_GLOBAL_PLACEHOLDERS
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include <cassert>
#include <string>
#include <cmath> // for NAN
#include <set>

namespace {
  using namespace boost::property_tree;
  using namespace lwt;
  LayerConfig get_layer(const ptree::value_type& pt);
  Input get_input(const ptree::value_type& pt);
  InputNodeConfig get_input_node(const ptree::value_type& pt);
  NodeConfig get_node(const ptree::value_type& pt);
  OutputNodeConfig get_output_node(const ptree::value_type& v);
  NodeConfig::Type get_node_type(const std::string&);
  ActivationConfig get_activation(const ptree&);
  Activation get_activation_function(const std::string&);
  Architecture get_architecture(const std::string&);
  void set_defaults(LayerConfig& lc);
  void add_dense_info(LayerConfig& lc, const ptree::value_type& pt);
  void add_maxout_info(LayerConfig& lc, const ptree::value_type& pt);
  void add_component_info(LayerConfig& lc, const ptree::value_type& pt);
  void add_embedding_info(LayerConfig& lc, const ptree::value_type& pt);

  std::map<std::string, double> get_defaults(const ptree& ptree);
}

namespace lwt {

  JSONConfig parse_json(std::istream& json)
  {
    boost::property_tree::ptree pt;
    boost::property_tree::read_json(json, pt);

    JSONConfig cfg;
    for (const auto& v: pt.get_child("inputs")) {
      cfg.inputs.push_back(get_input(v));
    }
    for (const auto& v: pt.get_child("layers")) {
      cfg.layers.push_back(get_layer(v));
    }
    for (const auto& v: pt.get_child("outputs"))
    {
      assert(v.first.empty()); // array elements have no names
      cfg.outputs.push_back(v.second.data());
    }
    cfg.defaults = get_defaults(pt);
    const std::string mname = "miscellaneous";
    if (pt.count(mname)) {
      for (const auto& misc: pt.get_child(mname)) {
        cfg.miscellaneous.emplace(
          misc.first, misc.second.get_value<std::string>());
      }
    }
    return cfg;
  }

  GraphConfig parse_json_graph(std::istream& json) {
    boost::property_tree::ptree pt;
    boost::property_tree::read_json(json, pt);

    GraphConfig cfg;
    for (const auto& v: pt.get_child("inputs")) {
      cfg.inputs.push_back(get_input_node(v));
    }
    for (const auto& v: pt.get_child("input_sequences")) {
      cfg.input_sequences.push_back(get_input_node(v));
    }
    for (const auto& v: pt.get_child("nodes")) {
      cfg.nodes.push_back(get_node(v));
    }
    for (const auto& v: pt.get_child("layers")) {
      cfg.layers.push_back(get_layer(v));
    }
    for (const auto& v: pt.get_child("outputs")) {
      cfg.outputs.emplace(v.first, get_output_node(v));
    }
    return cfg;
  }

}

namespace {

  lwt::Input get_input(const ptree::value_type& v) {
    std::string name = v.second.get<std::string>("name");
    auto offset = v.second.get<double>("offset");
    auto scale = v.second.get<double>("scale");
    return {name, offset, scale};
  }

  lwt::InputNodeConfig get_input_node(const ptree::value_type& v) {
    InputNodeConfig cfg;
    cfg.name = v.second.get<std::string>("name");
    for (const auto& var: v.second.get_child("variables")) {
      cfg.variables.push_back(get_input(var));
      if (var.second.count("default")) {
        std::string name = var.second.get<std::string>("name");
        cfg.defaults.emplace(name, var.second.get<double>("default"));
      }
    }
    return cfg;
  }

  const std::set<NodeConfig::Type> layerless_nodes {
    NodeConfig::Type::CONCATENATE, NodeConfig::Type::SUM };
  NodeConfig get_node(const ptree::value_type& v) {
    NodeConfig cfg;

    for (const auto& source: v.second.get_child("sources")) {
      int source_number = source.second.get_value<int>();
      if (source_number < 0) {
        throw std::logic_error("node source number must be positive");
      }
      cfg.sources.push_back(source_number);
    }

    cfg.type = get_node_type(v.second.get<std::string>("type"));
    typedef NodeConfig::Type Type;
    if (cfg.type == Type::INPUT || cfg.type == Type::INPUT_SEQUENCE) {
      cfg.index = v.second.get<int>("size");
    } else if (cfg.type == Type::FEED_FORWARD || cfg.type == Type::SEQUENCE ||
               cfg.type == Type::TIME_DISTRIBUTED) {
      cfg.index = v.second.get<int>("layer_index");
    } else if (layerless_nodes.count(cfg.type)){
      cfg.index = -1;
    } else {
      throw std::logic_error("unknown node type");
    }
    return cfg;
  }

  OutputNodeConfig get_output_node(const ptree::value_type& v) {
    OutputNodeConfig cfg;
    for (const auto& lab: v.second.get_child("labels")) {
      cfg.labels.push_back(lab.second.get_value<std::string>());
    }
    int idx = v.second.get<int>("node_index");
    if (idx < 0) throw std::logic_error("output node index is negative");
    cfg.node_index = idx;
    return cfg;
  }

  NodeConfig::Type get_node_type(const std::string& type) {
    typedef NodeConfig::Type Type;
    if (type == "feed_forward") return Type::FEED_FORWARD;
    if (type == "sequence") return Type::SEQUENCE;
    if (type == "input") return Type::INPUT;
    if (type == "input_sequence") return Type::INPUT_SEQUENCE;
    if (type == "concatenate") return Type::CONCATENATE;
    if (type == "time_distributed") return Type::TIME_DISTRIBUTED;
    if (type == "sum") return Type::SUM;
    throw std::logic_error("no node type '" + type + "'");
  }

  LayerConfig get_layer(const ptree::value_type& v) {
    using namespace lwt;
    LayerConfig layer;
    set_defaults(layer);
    Architecture arch = get_architecture(
      v.second.get<std::string>("architecture"));

    if (arch == Architecture::DENSE) {
      add_dense_info(layer, v);
    } else if (arch == Architecture::NORMALIZATION) {
      add_dense_info(layer, v); // re-use dense layer
    } else if (arch == Architecture::MAXOUT) {
      add_maxout_info(layer, v);
    } else if (arch == Architecture::LSTM ||
               arch == Architecture::GRU ||
               arch == Architecture::HIGHWAY) {
      add_component_info(layer, v);
    } else if (arch == Architecture::EMBEDDING) {
      add_embedding_info(layer, v);
    } else {
      throw std::logic_error("architecture not implemented");
    }
    layer.architecture = arch;
    return layer;
  }

  lwt::ActivationConfig get_activation(const ptree& v) {
    // check if this is an "advanced" activation function, in which
    // case it should store the values slightly differently
    lwt::ActivationConfig cfg;
    if (v.size() > 0) {
      cfg.function = get_activation_function(
        v.get<std::string>("function"));
      cfg.alpha = v.get<double>("alpha");
    } else {
      cfg.function = get_activation_function(v.data());
      cfg.alpha = NAN;
      // special case: kerasfunc2json converter used to pass through
      // the elu activation function. For cases where this has been
      // saved in JSON files we assume an alpha parameter of 1.
      if (cfg.function == Activation::ELU) {
        cfg.alpha = 1.0;
      }
    }
    return cfg;
  }

  lwt::Activation get_activation_function(const std::string& str) {
    using namespace lwt;
    if (str == "linear") return Activation::LINEAR;
    if (str == "sigmoid") return Activation::SIGMOID;
    if (str == "rectified") return Activation::RECTIFIED;
    if (str == "softmax") return Activation::SOFTMAX;
    if (str == "tanh") return Activation::TANH;
    if (str == "hard_sigmoid") return Activation::HARD_SIGMOID;
    if (str == "elu") return Activation::ELU;
    if (str == "leakyrelu") return Activation::LEAKY_RELU;
    if (str == "swish") return Activation::SWISH;
    if (str == "abs") return Activation::ABS;
    // legacy activations. These use UnaryActivationLayer. Just around
    // for benchmarks now.
    if (str == "sigmoid_legacy") return Activation::SIGMOID_LEGACY;
    if (str == "hard_sigmoid_legacy") return Activation::HARD_SIGMOID_LEGACY;
    if (str == "tanh_legacy") return Activation::TANH_LEGACY;
    if (str == "rectified_legacy") return Activation::RECTIFIED_LEGACY;
    throw std::logic_error("activation function " + str + " not recognized");
    return Activation::LINEAR;
  }

  lwt::Architecture get_architecture(const std::string& str) {
    using namespace lwt;
    if (str == "dense") return Architecture::DENSE;
    if (str == "normalization") return Architecture::NORMALIZATION;
    if (str == "highway") return Architecture::HIGHWAY;
    if (str == "maxout") return Architecture::MAXOUT;
    if (str == "lstm") return Architecture::LSTM;
    if (str == "gru") return Architecture::GRU;
    if (str == "embedding") return Architecture::EMBEDDING;
    throw std::logic_error("architecture " + str + " not recognized");
  }

  void set_defaults(LayerConfig& layer) {
    layer.activation.function = Activation::NONE;
    layer.inner_activation.function = Activation::NONE;
    layer.architecture = Architecture::NONE;
  }

  void add_dense_info(LayerConfig& layer, const ptree::value_type& v) {
    for (const auto& wt: v.second.get_child("weights")) {
      layer.weights.push_back(wt.second.get_value<double>());
    }
    for (const auto& bs: v.second.get_child("bias")) {
      layer.bias.push_back(bs.second.get_value<double>());
    }
    // this last category is currently only used for LSTM
    if (v.second.count("U") != 0) {
      for (const auto& wt: v.second.get_child("U") ) {
        layer.U.push_back(wt.second.get_value<double>());
      }
    }

    if (v.second.count("activation") != 0) {
      layer.activation = get_activation(v.second.get_child("activation"));
    }

  }

  void add_maxout_info(LayerConfig& layer, const ptree::value_type& v) {
    using namespace lwt;
    for (const auto& sub: v.second.get_child("sublayers")) {
      LayerConfig sublayer;
      set_defaults(sublayer);
      add_dense_info(sublayer, sub);
      layer.sublayers.push_back(sublayer);
    }
  }

  const std::map<std::string, lwt::Component> component_map {
    {"i", Component::I},
    {"o", Component::O},
    {"c", Component::C},
    {"f", Component::F},
    {"z", Component::Z},
    {"r", Component::R},
    {"h", Component::H},
    {"t", Component::T},
    {"carry", Component::CARRY}
  };

  void add_component_info(LayerConfig& layer, const ptree::value_type& v) {
    using namespace lwt;
    for (const auto& comp: v.second.get_child("components")) {
      LayerConfig cfg;
      set_defaults(cfg);
      add_dense_info(cfg, comp);
      layer.components[component_map.at(comp.first)] = cfg;
    }
    layer.activation = get_activation(v.second.get_child("activation"));
    if (v.second.count("inner_activation") != 0) {
      layer.inner_activation = get_activation(
        v.second.get_child("inner_activation"));
    }
  }

  void add_embedding_info(LayerConfig& layer, const ptree::value_type& v) {
    using namespace lwt;
    for (const auto& sub: v.second.get_child("sublayers")) {
      EmbeddingConfig emb;
      for (const auto& wt: sub.second.get_child("weights")) {
        emb.weights.push_back(wt.second.get_value<double>());
      }
      emb.index = sub.second.get<int>("index");
      emb.n_out = sub.second.get<int>("n_out");
      layer.embedding.push_back(emb);
    }
  }

  std::map<std::string, double> get_defaults(const ptree& pt) {
    const std::string dname = "defaults";
    std::map<std::string, double> defaults;
    // NOTE: at some point we may deprecate this first way of storing
    // default values.
    if (pt.count(dname)) {
      for (const auto& def: pt.get_child(dname)) {
        defaults.emplace(def.first, def.second.get_value<double>());
      }
    } else {
      const std::string dkey = "default";
      for (const auto& v: pt.get_child("inputs")) {
        if (v.second.count(dkey)) {
          std::string key = v.second.get<std::string>("name");
          defaults.emplace(key, v.second.get<double>(dkey));
        }
      }
    }
    return defaults;
  }
}

ext: cxx

max_stars_repo_name: fwinkl/lwtnn

max_issues_repo_name: fwinkl/lwtnn

max_forks_repo_name: fwinkl/lwtnn


text:
//| This file is a part of the sferes2 framework.
//| Copyright 2009, ISIR / Universite Pierre et Marie Curie (UPMC)
//| Main contributor(s): Jean-Baptiste Mouret, mouret@isir.fr
//|
//| This software is a computer program whose purpose is to facilitate
//| experiments in evolutionary computation and evolutionary robotics.
//|
//| This software is governed by the CeCILL license under French law
//| and abiding by the rules of distribution of free software.  You
//| can use, modify and/ or redistribute the software under the terms
//| of the CeCILL license as circulated by CEA, CNRS and INRIA at the
//| following URL "http://www.cecill.info".
//|
//| As a counterpart to the access to the source code and rights to
//| copy, modify and redistribute granted by the license, users are
//| provided only with a limited warranty and the software's author,
//| the holder of the economic rights, and the successive licensors
//| have only limited liability.
//|
//| In this respect, the user's attention is drawn to the risks
//| associated with loading, using, modifying and/or developing or
//| reproducing the software by the user in light of its specific
//| status of free software, that may mean that it is complicated to
//| manipulate, and that also therefore means that it is reserved for
//| developers and experienced professionals having in-depth computer
//| knowledge. Users are therefore encouraged to load and test the
//| software's suitability as regards their requirements in conditions
//| enabling the security of their systems and/or data to be ensured
//| and, more generally, to use and operate it in the same conditions
//| as regards security.
//|
//| The fact that you are presently reading this means that you have
//| had knowledge of the CeCILL license and that you accept its terms.

#ifndef RANK_SIMPLE_HPP_
#define RANK_SIMPLE_HPP_

#include <algorithm>
#include <boost/foreach.hpp>
#include <sferes/stc.hpp>
#include "ea_custom.hpp"
#include <sferes/fit/fitness.hpp>

#include <exp/images/continue_run/continue_run.hpp>

namespace sferes {
  namespace ea {
    SFERES_EA(RankSimple, EaCustom) {
    public:

    	typedef boost::shared_ptr<Phen> indiv_t;
    	typedef std::vector<indiv_t> raw_pop_t;
    	typedef std::vector<indiv_t> pop_t;
    	typedef RankSimple<Phen, Eval, Stat, FitModifier, Params, Exact> this_t;

      SFERES_CONST unsigned nb_keep = (unsigned)(Params::pop::keep_rate * Params::pop::size);

      void random_pop()
      {
    		sferes::cont::Continuator<this_t, Params> continuator;

    		// Continuing a run manually from command line or continuing a run automatically if the job was pre-empted
    		bool continue_run = continuator.enabled() || this->_gen_file_path != "";
    		if(continue_run)
    		{
    			// Load the population file
    			raw_pop_t raw_pop;

    			if (this->_gen_file_path == "")
    			{
    				raw_pop = continuator.getPopulationFromFile(*this);
    			}
    			else
    			{
    				raw_pop = continuator.getPopulationFromFile(*this, this->_gen_file_path);
    			}

					// Get the number of population to continue with
					const size_t init_size = raw_pop.size();

					// Resize the current population archive
					this->_pop.resize(init_size);

					// Add loaded individuals to the new population
					int i = 0;
					BOOST_FOREACH(boost::shared_ptr<Phen>&indiv, this->_pop)
					{
						indiv = boost::shared_ptr<Phen>(new Phen(*raw_pop[i]));
						++i;
					}
    		}
    		else
    		{
    			// Original Map-Elites code
					// Intialize a random population
					this->_pop.resize(Params::pop::size * Params::pop::initial_aleat);
					BOOST_FOREACH(boost::shared_ptr<Phen>& indiv, this->_pop)
					{
						indiv = boost::shared_ptr<Phen>(new Phen());
						indiv->random();
					}
    		}

        // Evaluate the initialized population
        this->_eval.eval(this->_pop, 0, this->_pop.size());
        this->apply_modifier();
        std::partial_sort(this->_pop.begin(), this->_pop.begin() + Params::pop::size,
                          this->_pop.end(), fit::compare());
        this->_pop.resize(Params::pop::size);

        // Continue a run from a specific generation
				if(continue_run)
				{
					if (this->_gen_file_path == "")
					{
						continuator.run_with_current_population(*this);
					}
					else
					{
						continuator.run_with_current_population(*this, this->_gen_file_path);
					}
				}
      }

			//ADDED
			void setGen(size_t gen)
			{
				this->_gen = gen;
			}
			//ADDED END

      void epoch()
      {
        assert(this->_pop.size());
        for (unsigned i = nb_keep; i < 	this->_pop.size(); i += 2)
        {
          unsigned r1 = _random_rank();
          unsigned r2 = _random_rank();
          boost::shared_ptr<Phen> i1, i2;
          this->_pop[r1]->cross(this->_pop[r2], i1, i2);
          i1->mutate();
          i2->mutate();
          this->_pop[i] = i1;
          this->_pop[i + 1] = i2;
        }
#ifndef EA_EVAL_ALL
        this->_eval.eval(this->_pop, nb_keep, Params::pop::size);
#else
        this->_eval.eval(this->_pop, 0, Params::pop::size);
#endif
        this->apply_modifier();
        std::partial_sort(this->_pop.begin(), this->_pop.begin() + nb_keep,
                          this->_pop.end(), fit::compare());
        dbg::out(dbg::info, "ea")<<"best fitness: " << this->_pop[0]->fit().value() << std::endl;
      }
    protected:
      unsigned _random_rank() {
        static float kappa = pow(Params::pop::coeff, nb_keep + 1.0f) - 1.0f;
        static float facteur = nb_keep / ::log(kappa + 1);
        return (unsigned) (this->_pop.size() - facteur * log(misc::rand<float>(1) * kappa + 1));
      }
    };
  }
}
#endif

max_stars_repo_name: Evolving-AI-Lab/innovation-engine

max_issues_repo_name: Evolving-AI-Lab/innovation-engine

max_forks_repo_name: Evolving-AI-Lab/innovation-engine


text:
#include <QString>
#include <QtTest>
#include <QCoreApplication>
#include <QMap>
#include <algorithm>
#include <utility>
#include <map>
#include <unordered_map>
#include "qfasthash_p.h"
#include <stdint.h>
#ifdef USE_BOOST
#include <boost/unordered_map.hpp>
#endif

#ifdef TEST_KEY_STRING

namespace std{
    /* std::hash specialization for QString so it can be used
     * as a key in std::unordered_map */

    template<> struct hash<QString> {
        typedef QString Key;
        typedef uint result_type;
        inline uint operator()(const QString &s) const { return qHash(s); }
    };
}

std::size_t hash_value(const QString &s)
    {
        boost::hash<int> hasher;
        return hasher(qHash(s));
    }

static std::vector<QString>  s_vec;
void createStringNumberArray(size_t n)
{

    if(n  >= s_vec.size())
    {
         for (auto i=s_vec.size(); i <= n; ++i)
            s_vec.push_back(QString("%1").arg(QString::number(i),12) + "                               ");
    }
}

typedef QString tTestKey;
#define MAKE_KEY(x) s_vec[x]
//#define MAKE_KEY(x) QString::number(x)
#else
#if defined(TEST_KEY_DOUBLE)
typedef double tTestKey;
#elif defined(TEST_KEY_INT32)
typedef int32_t tTestKey;
#endif
#define MAKE_KEY(x) x
#endif

#if defined(TEST_KEY_DOUBLE)
typedef double tTestValue;
#elif defined(TEST_KEY_INT32)
typedef int32_t tTestValue;
#endif

struct tVecData
{
    tVecData(tTestKey f,tTestValue s)
        :first(f)
        ,second(s)
    {}
    tVecData()
        :
#ifndef TEST_KEY_STRING
        first(0),
#endif
        second(0)
    {}
    bool operator<( const tVecData &t2) const
    {
        return first < t2.first;
    }
    tTestKey first;
    tTestValue second;
};

inline size_t calcContainerCount(int testcount)
{
    return std::max(1UL,100000UL/testcount);
}

class QtContainerBench : public QObject
{
    Q_OBJECT

public:
    QtContainerBench();

private Q_SLOTS:
    void initTestCase();
    void cleanupTestCase();

    void testCase_insert_data();
    void testCase_insert();
    void testCase_find();
    void testCase_find_data();

};

QtContainerBench::QtContainerBench()
{
}

void QtContainerBench::initTestCase()
{

}

void QtContainerBench::cleanupTestCase()
{
}
static int testcounts[] = {100};//{5,7,10,12,15,17,20,25,29,34,41,47, 50,75,80,90,100};//,1000,10000,100000,1000000};

void QtContainerBench::testCase_insert_data()
{
    QTest::addColumn<QString>("testcontainer");
    QTest::addColumn<int>("testcount");
    QString testContainer;

    static const char * tests[] = {
      "QMap_insert",
        "QHash_insert",
        "stdmap_insert",
        "QVector_pb_sort",
        "stdvector_pb_sort",
        "stdunordered_insert",
        "qfasthash_insert",
#ifdef USE_BOOST
        "boostunordered_insert"
#endif
     };

    for (unsigned int t = 0; t < sizeof(tests)/sizeof(tests[0]);++t)
    {
        for(int count : testcounts)
        {

            QString text;
            text += QLatin1String(tests[t]);
            text = text.leftJustified(20, ' ', true);
            text +=  QLatin1String(" -- ");
            text += QString::number(count).leftJustified(12, ' ');

            QTest::newRow(text.toLatin1().constData()) << QString(tests[t]) << count;
        }

    }
}
void QtContainerBench::testCase_find_data()
{
    QTest::addColumn<QString>("testcontainer");
    QTest::addColumn<int>("testcount");
    QString testContainer;
    static const char * tests[] = {
      "QMap_find",
        "QMap_constFind",
        "QHash_find",
        "QHash_constFind",
        "QVector_lowerbound",
        "stdvector_lowerbound",
        "stdmap_find",
        "stdunordered_find",
        "qfasthash_find",
#ifdef USE_BOOST
        "boostunordered_find"
#endif
     };

     for (unsigned int t = 0; t < sizeof(tests)/sizeof(tests[0]);++t)
     {

        for(int count : testcounts)
        {
            QString text;
            text += QLatin1String(tests[t]);
            text = text.leftJustified(20, ' ', true);
            text +=  QLatin1String(" -- ");
            text += QString::number(count).leftJustified(12, ' ');

            QTest::newRow(text.toLatin1().constData()) << QString(tests[t]) << count;
        }

    }
}

inline void insertdata(std::vector<QMap<tTestKey,tTestValue>> & m,int testcount)
{
    m.clear();
    m.resize(calcContainerCount(testcount));
    for(int i = testcount ;i> 0 ;--i)
    {
        for(size_t x=0;x < m.size();++x)
        {
            m[x].insert(MAKE_KEY(i),i);
        }
    }
}
inline void insertdata(std::vector<QHash<tTestKey,tTestValue>> & m,int testcount)
{
    m.clear();
    m.resize(calcContainerCount(testcount));
    for(int i = testcount ;i> 0 ;--i)
    {
        for(size_t x=0;x < m.size();++x)
        {
            m[x].insert(MAKE_KEY(i),i);
        }
    }

}
inline void insertdata(std::vector<std::map<tTestKey,tTestValue>> & m,int testcount)
{
    m.clear();
    m.resize(calcContainerCount(testcount));
    for(int i = testcount ;i> 0 ;--i)
    {
        for(size_t x=0;x < m.size();++x)
        {
            m[x][MAKE_KEY(i)]=i;
        }
    }
}

inline void insertdata(std::vector<std::unordered_map <tTestKey,tTestValue>> & m,int testcount)
{
    m.clear();
    m.resize(calcContainerCount(testcount));
    for(int i = testcount ;i> 0 ;--i)
    {
        for(size_t x=0;x < m.size();++x)
        {
            m[x][MAKE_KEY(i)]=i;
        }
    }
}
#ifdef USE_BOOST
inline void insertdata(std::vector<boost::unordered_map <tTestKey,tTestValue>> & m,int testcount)
{
    m.clear();
    m.resize(calcContainerCount(testcount));
    for(int i = testcount ;i> 0 ;--i)
    {
        for(size_t x=0;x < m.size();++x)
        {
            m[x][MAKE_KEY(i)]=i;
        }
    }
}
#endif

inline void insertdata(std::vector<QFastHash<tTestKey,tTestValue>> & m,int testcount)
{
    m.clear();
    m.resize(calcContainerCount(testcount));
    for(int i = testcount ;i> 0 ;--i)
    {
        for(size_t x=0;x < m.size();++x)
        {
            m[x][MAKE_KEY(i)]=i;
        }
    }
}

inline void insertdata(std::vector<std::vector<tVecData>>  & m,int testcount)
{
    m.clear();
    m.resize(calcContainerCount(testcount));

    for(int i = testcount ;i>0 ;--i)
    {
        for(size_t x=0;x < m.size();++x)
        {
            m[x].push_back(tVecData(MAKE_KEY(i),i));
        }
    }
    for(size_t x=0;x < m.size();++x)
    {
        std::sort(std::begin(m[x]),std::end(m[x]),std::less<tVecData>());
    }
}
inline void insertdata(std::vector<QVector<tVecData>>  & m,int testcount)
{
    m.clear();
    m.resize(calcContainerCount(testcount));

    for(int i = testcount ;i>0 ;--i)
    {
        for(size_t x=0;x < m.size();++x)
        {
            m[x].push_back(tVecData(MAKE_KEY(i),i));
        }
    }
    for(size_t x=0;x < m.size();++x)
    {
        std::sort(std::begin(m[x]),std::end(m[x]),std::less<tVecData>());
    }
}
void QtContainerBench::testCase_insert()
{
    QFETCH(QString,testcontainer);
    QFETCH(int,testcount);

#ifdef TEST_KEY_STRING
    createStringNumberArray(testcount);
#endif

    if(testcontainer == QLatin1String("QMap_insert"))
    {
        std::vector<QMap<tTestKey,tTestValue>> m;

        QBENCHMARK {
            insertdata(m,testcount);
        }
        auto it = m[0].find(MAKE_KEY(testcount));
        if(*it != testcount) QFAIL( "fail");
    }
    else if (testcontainer == QLatin1String("QHash_insert"))
    {
        std::vector<QHash<tTestKey,tTestValue>> m;

        QBENCHMARK {
            insertdata(m,testcount);
        }
        auto it = m[0].find(MAKE_KEY(testcount));
        if(*it != testcount) QFAIL( "fail");

    }
    else if (testcontainer == QLatin1String("QVector_pb_sort"))
    {
        std::vector<QVector<tVecData>> m;

        QBENCHMARK {
            insertdata(m,testcount);
        }
        auto it = std::lower_bound(std::begin(m[0]),std::end(m[0]),tVecData(MAKE_KEY(testcount),0));
        if(it->second != testcount) QFAIL( "fail");

    }
    else if (testcontainer == QLatin1String("stdvector_pb_sort"))
    {
        std::vector<std::vector<tVecData>> m;

        QBENCHMARK {
            insertdata(m,testcount);
        }
        auto it = std::lower_bound(std::begin(m[0]),std::end(m[0]),tVecData(MAKE_KEY(testcount),0));
        if(it->second != testcount) QFAIL( "fail");

    }
    else if (testcontainer == QLatin1String("stdmap_insert"))
    {
        std::vector<std::map<tTestKey,tTestValue>> m;

        QBENCHMARK {
            insertdata(m,testcount);
        }
        auto it = m[0].find(MAKE_KEY(testcount));
        if(it->second != testcount) QFAIL( "fail");

    }
    else if (testcontainer == QLatin1String("stdunordered_insert"))
    {
        std::vector<std::unordered_map<tTestKey,tTestValue>> m;

        QBENCHMARK {
            insertdata(m,testcount);
        }
        auto it = m[0].find(MAKE_KEY(testcount));
        if(it->second != testcount) QFAIL( "fail");

    }
#ifdef USE_BOOST
    else if (testcontainer == QLatin1String("boostunordered_insert"))
    {
        std::vector<boost::unordered_map<tTestKey,tTestValue>> m;

        QBENCHMARK {
            insertdata(m,testcount);
        }
        auto it = m[0].find(MAKE_KEY(testcount));
        if(it->second != testcount) QFAIL( "fail");

    }
#endif
    else if (testcontainer == QLatin1String("qfasthash_insert"))
    {
        std::vector<QFastHash<tTestKey,tTestValue>> m;

        QBENCHMARK {
            insertdata(m,testcount);
        }
        auto it = m[0].constFind(MAKE_KEY(testcount));
        if(it != testcount) QFAIL( "fail");

    }
}

void QtContainerBench::testCase_find()
{
    QFETCH(QString,testcontainer);
    QFETCH(int,testcount);

#ifdef TEST_KEY_STRING
    createStringNumberArray(testcount);
#endif

    if(testcontainer == QLatin1String("QMap_find"))
    {
        std::vector<QMap<tTestKey,tTestValue>> m;
        insertdata(m,testcount);
        QBENCHMARK {
            for(int i = 1 ;i <= testcount ;++i)
            {
                for(size_t x=0;x < m.size();++x)
                {
                    auto it = m[x].find(MAKE_KEY(i));
                    if(*it != i) QFAIL( "fail");
                }
            }
        }
    }
    else if (testcontainer == QLatin1String("QMap_constFind"))
    {
        std::vector<QMap<tTestKey,tTestValue>> m;
        insertdata(m,testcount);
        QBENCHMARK {
            for(int i = 1 ;i <= testcount ;++i)
            {
                for(size_t x=0;x < m.size();++x)
                {
                    auto it = m[x].constFind(MAKE_KEY(i));
                    if(*it != i) QFAIL( "fail");
                }
            }
        }

    }
    else if (testcontainer == QLatin1String("QHash_find"))
    {
        std::vector<QHash<tTestKey,tTestValue>> m;
        insertdata(m,testcount);
        QBENCHMARK {
            for(int i = 1 ;i <= testcount ;++i)
            {
                for(size_t x=0;x < m.size();++x)
                {
                    auto it = m[x].find(MAKE_KEY(i));
                    if(*it != i) QFAIL( "fail");
                }
            }
        }

    }
    else if (testcontainer == QLatin1String("QHash_constFind"))
    {
        std::vector<QHash<tTestKey,tTestValue>> m;
        insertdata(m,testcount);
        QBENCHMARK {
            for(int i = 1 ;i <= testcount ;++i)
            {
                for(size_t x=0;x < m.size();++x)
                {
                    auto it = m[x].constFind(MAKE_KEY(i));
                    if(*it != i) QFAIL( "fail");
                }
            }
        }

    }
    else if (testcontainer == QLatin1String("QVector_lowerbound"))
    {
        std::vector<QVector<tVecData>> m;
        insertdata(m,testcount);
        QBENCHMARK {
            for(int i = 1 ;i <= testcount ;++i)
            {
                for(size_t x=0;x < m.size();++x)
                {
                    auto it = std::lower_bound(std::begin(m[x]),std::end(m[x]),tVecData(MAKE_KEY(i),0));
                    if(it->second != i)
                        QFAIL( "fail");
                }
            }
        }

    }
    else if (testcontainer == QLatin1String("stdvector_lowerbound"))
    {
        std::vector<std::vector<tVecData>> m;
        insertdata(m,testcount);

        QBENCHMARK {
            for(int i = 1 ;i <= testcount ;++i)
            {
                for(size_t x=0;x < m.size();++x)
                {
                    auto it = std::lower_bound(std::begin(m[x]),std::end(m[x]),tVecData(MAKE_KEY(i),0));
                    if(it->second != i)
                        QFAIL( "fail");
                }
            }
        }

    }
    else if (testcontainer == QLatin1String("stdmap_find"))
    {
        std::vector<std::map<tTestKey,tTestValue>> m;
        insertdata(m,testcount);
        QBENCHMARK {
            for(int i = 1 ;i <= testcount ;++i)
            {
                for(size_t x=0;x < m.size();++x)
                {
                    auto it = m[x].find(MAKE_KEY(i));
                    if(it->second != i) QFAIL( "fail");
                }
            }
        }

    }
    else if (testcontainer == QLatin1String("stdunordered_find"))
    {
        std::vector<std::unordered_map <tTestKey,tTestValue>> m;
        insertdata(m,testcount);
        QBENCHMARK {
            for(int i = 1 ;i <= testcount ;++i)
            {
                for(size_t x=0;x < m.size();++x)
                {
                    auto it = m[x].find(MAKE_KEY(i));
                    if(it->second != i) QFAIL( "fail");
                }
            }
        }

    }
#ifdef USE_BOOST
    else if (testcontainer == QLatin1String("boostunordered_find"))
    {
        std::vector<boost::unordered_map <tTestKey,tTestValue>> m;
        insertdata(m,testcount);
        QBENCHMARK {
            for(int i = 1 ;i <= testcount ;++i)
            {
                for(size_t x=0;x < m.size();++x)
                {
                    auto it = m[x].find(MAKE_KEY(i));
                    if(it->second != i) QFAIL( "fail");
                }
            }
        }

    }
#endif
    else if (testcontainer == QLatin1String("qfasthash_find"))
    {
        std::vector<QFastHash<tTestKey,tTestValue>> m;
        insertdata(m,testcount);
        QBENCHMARK {
            for(int i = 1 ;i <= testcount ;++i)
            {
                for(size_t x=0;x < m.size();++x)
                {
                    auto it = m[x].constFind(MAKE_KEY(i));
                    if(it != i) QFAIL( "fail");
                }
            }
        }

    }
    else
    {
        QFAIL( "fail, unknown test ");
    }

}

QTEST_MAIN(QtContainerBench)

#include "tst_qtcontainerbench.moc"

ext: cpp

max_stars_repo_name: gunrot/qtcontainerbench

max_issues_repo_name: gunrot/qtcontainerbench

max_forks_repo_name: gunrot/qtcontainerbench


text:
// Copyright Takatoshi Kondo 2017
//
// 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(MQTT_TEST_SERVER_TLS_HPP)
#define MQTT_TEST_SERVER_TLS_HPP

#if defined(MQTT_USE_TLS)
#include <set>

#include <boost/lexical_cast.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>

#include <mqtt_server_cpp.hpp>

namespace mi = boost::multi_index;
namespace as = boost::asio;

class test_server_tls {
public:
    test_server_tls(as::io_context& ioc, boost::asio::ssl::context&& ctx, MQTT_NS::broker::broker_t& b, uint16_t port = broker_tls_port)
        : server_(
            as::ip::tcp::endpoint(
                as::ip::tcp::v4(), port
            ),
            MQTT_NS::force_move(ctx),
            ioc,
            ioc,
            [](auto& acceptor) {
                acceptor.set_option(as::ip::tcp::acceptor::reuse_address(true));
            }
        ), b_(b) {
        server_.set_error_handler(
            [](MQTT_NS::error_code /*ec*/) {
            }
        );

        server_.set_accept_handler(
            [&](std::shared_ptr<MQTT_NS::server_tls<>::endpoint_t> spep) {
                b_.handle_accept(MQTT_NS::force_move(spep));
            }
        );

        server_.listen();
    }

    MQTT_NS::broker::broker_t& broker() const {
        return b_;
    }

    void close() {
        server_.close();
    }

    /**
     * @brief Get boost asio ssl context.
     * @return ssl context
     */
    MQTT_NS::tls::context& get_ssl_context() {
        return server_.get_ssl_context();
    }

    /**
     * @brief Get boost asio ssl context.
     * @return ssl context
     */
    MQTT_NS::tls::context const& get_ssl_context() const {
        return server_.get_ssl_context();
    }

private:
    MQTT_NS::server_tls<> server_;
    MQTT_NS::broker::broker_t& b_;
};

#endif

#endif // MQTT_TEST_SERVER_TLS_HPP


text: #include <boost/python/return_value_policy.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <cstdint>
#include <cstdlib>
#include <future>
#include <iostream>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>

#include "../tiny-lib/Log.hpp"
#include "../tiny-lib/NetClient.hpp"
#include "../tiny-lib/NodeConfig.hpp"
#include "../tiny-lib/PoW.hpp"
#include "../tiny-lib/Wallet.hpp"

namespace po = boost::program_options;

void atexit_handler()
{
	Log::StopLog();
}

int main(int argc, char** argv)
{
	Log::StartLog();
	if (std::atexit(atexit_handler) != 0)
		return EXIT_FAILURE;

	po::options_description desc("allowed options");
	desc.add_options()
		("node_type", po::value<std::string>(), "specify node type")
		("port", po::value<uint16_t>(), "port to listen on network connections")
		("wallet", po::value<std::string>(), "path to wallet");

	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if (!vm.contains("port"))
	{
		LOG_ERROR("A port for network connection must be specified");

		return EXIT_FAILURE;
	}

	if (!vm.contains("node_type"))
	{
		LOG_ERROR("Node type must be specified");

		return EXIT_FAILURE;
	}

	if (vm["node_type"].as<std::string>() == "miner")
	{
		NodeConfig::Type = NodeType::Miner;
	}
	else if (vm["node_type"].as<std::string>() == "wallet")
	{
		NodeConfig::Type = NodeType::Wallet;
	}
	else if (vm["node_type"].as<std::string>() == "full")
	{
		NodeConfig::Type = NodeType::Full; //TODO: implement full node
	}
	else
	{
		LOG_ERROR("Invalid node type");

		return EXIT_FAILURE;
	}

	const auto [privKey, pubKey, address] = vm.contains("wallet")
		                                        ? Wallet::InitWallet(vm["wallet"].as<std::string>())
		                                        : Wallet::InitWallet();
	const auto port = vm["port"].as<uint16_t>();
	NetClient::ListenAsync(port);
	NetClient::RunAsync();

	std::vector<std::future<void>> pendingConnections;
	for (const auto& [k, v] : NetClient::InitialPeers)
	{
		if (v == port)
		{
			continue;
		}

		pendingConnections.emplace_back(std::async(std::launch::async, &NetClient::Connect, k, v));
	}
	for (const auto& pendingConnection : pendingConnections)
		pendingConnection.wait();

	if (NodeConfig::Type == NodeType::Miner)
	{
		PoW::MineForever();
	}
	else
	{
		std::string wallet_address = "address ";
		std::string balance_address = "balance ";
		std::string balance_own = "balance";
		std::string send = "send ";
		std::string tx_status = "tx_status ";
		while (true)
		{
			std::string command;
			std::getline(std::cin, command);

			if (command == "exit" || command == "quit")
			{
				break;
			}

			if (command.starts_with(wallet_address))
			{
				command.erase(0, wallet_address.length());
				Wallet::PrintWalletAddress(command);
			}
			else if (command.starts_with(balance_address))
			{
				command.erase(0, balance_address.length());
				Wallet::PrintBalance(command);
			}
			else if (command.starts_with(balance_own))
			{
				Wallet::PrintBalance(address);
			}
			else if (command.starts_with(send))
			{
				command.erase(0, send.length());
				std::vector<std::string> send_args;
				boost::split(send_args, command, boost::is_any_of(" "));
				if (send_args.size() != 2 && send_args.size() != 3)
				{
					LOG_ERROR(
						"Send command requires 2 arguments, receiver address, send value and optionally fee per byte");

					continue;
				}
				const auto& send_address = send_args[0];
				const auto& send_value = send_args[1];
				if (send_args.size() == 3)
				{
					const auto& send_fee = send_args[2];
					Wallet::SendValue(std::stoull(send_value), std::stoull(send_fee), send_address, privKey);
				}
				else
				{
					Wallet::SendValue(std::stoull(send_value), 100, send_address, privKey);
				}
			}
			else if (command.starts_with(tx_status))
			{
				command.erase(0, tx_status.length());
				Wallet::PrintTxStatus(command);
			}
			else
			{
				LOG_ERROR("Unknown command");
			}
		}
	}

	NetClient::Stop();

	return EXIT_SUCCESS;
}

max_stars_repo_name: aizuon/tiny-coin

max_issues_repo_name: aizuon/tiny-coin

max_forks_repo_name: aizuon/tiny-coin


text:
//Make sure THREAD SAFE is Active
#define BOOST_SPIRIT_THREADSAFE

#include <gtest/gtest.h>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/date_time.hpp>

/**
 * @brief Basic shared lock tests
 * @see http://www.boost.org/doc/libs/1_41_0/doc/html/thread/synchronization.html#thread.synchronization.locks.shared_lock
 */
TEST ( boost, locks )
{
    return;
    boost::shared_mutex m1;
    {
        boost::unique_lock<boost::shared_mutex> wlock(m1);
        ASSERT_TRUE(wlock);
        {
            boost::shared_lock<boost::shared_mutex> rlock(m1, boost::try_to_lock);
            ASSERT_FALSE(rlock);
        }
        {
            boost::shared_mutex* mutexptr = wlock.release();
            ASSERT_EQ(mutexptr, &m1);
        }
        {
            boost::shared_lock<boost::shared_mutex> rlock(m1);
            ASSERT_TRUE(rlock);
        }
    }
}

/**
 * @short Test shared mutex 5 times
 */
void testsharedmutex(boost::shared_mutex &m1) // NOLINT
{
//     std::cout << "thread " << boost::this_thread::get_id() << std::endl;

    for (int i = 0; i < 1; ++i)
    {
        //lock_guard is a unique_lock aka a write lock!
        boost::lock_guard<boost::shared_mutex> r1lock(m1);
//         std::cout << "thread locked " << boost::this_thread::get_id() << std::endl;

//         for (int v = 0; v < 50; ++v)
//             boost::this_thread::yield();
    }
}

/**
 * @short Test shared 3 mutexs 5 times
 */
void testshared3mutex(boost::shared_mutex &m1, boost::shared_mutex &m2, boost::shared_mutex &m3) // NOLINT
{
//     std::cout << "thread " << boost::this_thread::get_id() << std::endl;

    for (int i = 0; i < 1; ++i)
    {

        boost::shared_lock<boost::shared_mutex> r1lock(m1, boost::defer_lock);
        boost::shared_lock<boost::shared_mutex> r2lock(m2, boost::defer_lock);
        boost::shared_lock<boost::shared_mutex> r3lock(m3, boost::defer_lock);

        boost::lock(r1lock, r2lock, r3lock);
        {
            boost::this_thread::sleep(boost::posix_time::seconds(1));
//             std::cout << "thread locked " << boost::this_thread::get_id() << std::endl;

            EXPECT_TRUE(r1lock);
            EXPECT_TRUE(r2lock);
            EXPECT_TRUE(r3lock);

//             for (int v = 0; v < 50; ++v)
//                 boost::this_thread::yield();
        }
    }
}

/**
 * @brief Tests locking and threads
 *  Loads 10 threads and three mutexs,
 *  then runs half the of the threads trying
 *  to lock 1 mutex with the other 5 threads
 *  locking all three mutexs
 * @see http://www.boost.org/dboc/libs/1_47_0/doc/html/thread/synchronization.html#thread.synchronization.locks.shared_lock
 * @see http://www.boost.org/doc/libs/1_47_0/doc/html/thread/thread_management.html
 */
TEST ( boost, threaded_locks )
{
//     std::cout << boost::this_thread::get_id() << std::endl;
//     std::cout << boost::thread::hardware_concurrency() << std::endl;

    boost::shared_mutex m1, m2, m3;
    boost::thread t1(testsharedmutex, boost::ref(m1));
    boost::thread t2(testsharedmutex, boost::ref(m1));
    boost::thread t3(testsharedmutex, boost::ref(m1));
    boost::thread t4(testsharedmutex, boost::ref(m1));
    boost::thread t5(testsharedmutex, boost::ref(m1));
    boost::thread t10(testshared3mutex, boost::ref(m1), boost::ref(m2), boost::ref(m3));
    boost::thread t20(testshared3mutex, boost::ref(m1), boost::ref(m2), boost::ref(m3));
    boost::thread t30(testshared3mutex, boost::ref(m1), boost::ref(m2), boost::ref(m3));
    boost::thread t40(testshared3mutex, boost::ref(m1), boost::ref(m2), boost::ref(m3));
    boost::thread t50(testshared3mutex, boost::ref(m1), boost::ref(m2), boost::ref(m3));
//     std::cout << "threading" << std::endl;
    t1.join();
    t2.join();
    t3.join();
    t4.join();
    t5.join();
    t10.join();
    t20.join();
    t30.join();
    t40.join();
    t50.join();
}

class boost_asio_server_test : public ::testing::Test
{
public:
    boost_asio_server_test()
            : endpoint(boost::asio::ip::address::from_string("127.0.0.1") , 8129),
            acceptor(io_service, endpoint), lsock(io_service), sock(io_service), data("SOME DATA TO TEST")
    {
    }

    boost::asio::io_service io_service;
    boost::asio::ip::tcp::endpoint endpoint;
    boost::asio::ip::tcp::acceptor acceptor;
    boost::asio::ip::tcp::socket lsock;
    boost::asio::ip::tcp::socket sock;
    const std::string data;
    boost::array<char, 4096> buffer1;
    boost::array<char, 4096> buffer2;

    void connect_handler(const boost::system::error_code &ec)
    {
        EXPECT_FALSE(ec);
        boost::asio::async_write(sock,
                                 boost::asio::buffer(data),
                                 boost::bind(&boost_asio_server_test::write_handler,
                                             this, boost::asio::placeholders::error,
                                             boost::asio::placeholders::bytes_transferred));
        boost::asio::async_read(sock,
                                boost::asio::buffer(buffer1),
                                boost::asio::transfer_at_least(data.length()),
                                boost::bind(&boost_asio_server_test::read_handler1,
                                            this,
                                            boost::asio::placeholders::error,
                                            boost::asio::placeholders::bytes_transferred));
    }

    void read_handler1(const boost::system::error_code& ec, std::size_t bytes_transferred)
    {
        EXPECT_FALSE(ec);
        EXPECT_EQ(bytes_transferred, data.length());
        EXPECT_EQ(data, std::string(buffer1.begin(), buffer1.begin() + bytes_transferred));
    }

    void read_handler2(const boost::system::error_code& ec, std::size_t bytes_transferred)
    {
        EXPECT_FALSE(ec);
        EXPECT_EQ(bytes_transferred, data.length());
        EXPECT_EQ(data, std::string(buffer2.begin(), buffer2.begin() + bytes_transferred));
    }

    void accept_handler(const boost::system::error_code &ec)
    {
        EXPECT_FALSE(ec);
        boost::asio::async_write(lsock,
                                 boost::asio::buffer(data),
                                 boost::bind(&boost_asio_server_test::write_handler,
                                             this,
                                             boost::asio::placeholders::error,
                                             boost::asio::placeholders::bytes_transferred));
        boost::asio::async_read(lsock,
                                boost::asio::buffer(buffer2),
                                boost::asio::transfer_at_least(data.length()),
                                boost::bind(&boost_asio_server_test::read_handler2,
                                            this,
                                            boost::asio::placeholders::error,
                                            boost::asio::placeholders::bytes_transferred));
    }

    void write_handler(const boost::system::error_code &ec, std::size_t bytes_transferred)
    {
        EXPECT_FALSE(ec);
        EXPECT_EQ(bytes_transferred, data.length());
    }
};

/**
 * @brief Listen and Read TCP Socket test
 * listens on a port, then connects to same port
 * the same data is sent accross both sockets
 * and then verified.
 * runs in 3 threads to verify it works with threads
 * @see http://en.highscore.de/cpp/boost/asio.html
 */
TEST_F ( boost_asio_server_test, listenread )
{
    boost::thread_group threads;
    acceptor.listen();
    acceptor.async_accept(lsock, boost::bind(&boost_asio_server_test::accept_handler, this, boost::asio::placeholders::error ));
    sock.async_connect(endpoint, boost::bind(&boost_asio_server_test::connect_handler, this, boost::asio::placeholders::error ));

    threads.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
    threads.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
    threads.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
    threads.join_all();
}


text:
#include <stan/math/prim/scal.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gtest/gtest.h>

TEST(MathFunctions, log1m) {
  EXPECT_FLOAT_EQ(stan::math::log1p(-0.1),stan::math::log1m(0.1));
}

TEST(MathFunctions, log1mOverflow) {
    EXPECT_EQ(-std::numeric_limits<double>::infinity(),
              stan::math::log1m(1.0));
    EXPECT_EQ(-std::numeric_limits<double>::infinity(),
              stan::math::log1m(1));

}

TEST(MathFunctions, log1m_exception) {
  EXPECT_THROW(stan::math::log1m(10.0), std::domain_error);
}

TEST(MathFunctions, log1m_nan) {
  double nan = std::numeric_limits<double>::quiet_NaN();
  EXPECT_PRED1(boost::math::isnan<double>,
               stan::math::log1m(nan));
}

max_stars_repo_name: yizhang-cae/torsten

max_issues_repo_name: yizhang-cae/torsten

max_forks_repo_name: yizhang-cae/torsten


text:
#ifndef P2P_HANDLER_H
#define P2P_HANDLER_H

#include <ctime>
#include <string>
#include <boost/asio.hpp>
#include <iostream>

#include <boost/array.hpp>

using boost::asio::ip::tcp;

using namespace std;
using namespace boost::asio;
using namespace boost::asio::ip;

extern bool break_server_loop;

namespace crowd
{
    class p2p_handler
    {
    public:
        void p2p_switch(string, string);
        vector<string> parse_ip_peers_json();
    private:
        std::string client(string&, string&);
        int server_main();
        string getDataServer(tcp::socket&);
        void sendDataServer(tcp::socket&, const string&);
        string getDataClient(tcp::socket&);
        void sendDataClient(tcp::socket&, const string&);
        void save_blockchain(string);
    };
}

#endif /* P2P_HANDLER_H */

max_stars_repo_name: nvrrdt/crowd

max_issues_repo_name: nvrrdt/crowd

max_forks_repo_name: nvrrdt/crowd