text:
/*
    Copyright 2004-2008 TouK sp. z o.o. s.k.a.

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

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

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

#include "StoreString.h"
#include "BeansException.h"
#include "defs.h"
#include "Tracer.h"
#include "TextUtils.h"

#include <cstring>

#include <boost/config.hpp>
#ifdef BOOST_HAS_THREADS
#include <boost/thread/recursive_mutex.hpp>
#define SYNC(mutex) boost::recursive_mutex::scoped_lock lock(mutex);
#else
#define SYNC(mutex)
#endif

namespace xmlbeansxx {
//------------------------------------------------

namespace {

char *duplicate(const char *str) {

    char *buf;
    int l=strlen(str)+1;
    buf=new char[l];

    if (!((((unsigned long)buf)&1)==0)) {
    	delete[] buf;
        throw IllegalStateException();
    }
    //strcpy(buf,str);
    for(int i=0;i<l;i++) buf[i]=str[i];
    return buf;
}

void freeDuplicate(char *str) {
    delete[] str;
}
}
//------------------------------------------------
SimpleString::SimpleString(const std::string &s) {
    buf=duplicate(s.c_str());
}
SimpleString::SimpleString(const SimpleString &from) {
    copyFrom(from);
}

SimpleString::~SimpleString() {
    freeDuplicate(buf);
}

void SimpleString::copyFrom(const SimpleString &from) {
    buf=duplicate(from.c_str());
}

SimpleString &SimpleString::operator=(const SimpleString &b) {
    copyFrom(b);
    return *this;
}

const char *SimpleString::c_str() const {
    return buf;
}
//------------------------------------------------

/*
CStr::CStr(const char *buf):buf(buf) {}
const char *CStr::get() const {
        return buf;
    }
bool CStr::operator<(const CStr &b) const {
    return strcmp(buf,b.buf)<0;
}
*/

//------------------------------------------------
StringStorage::StringStorage() {
    //add default storage
    add(std::string());
}

void StringStorage::add(const std::string &str) {
    const char *cs=str.c_str();
    return add(cs);
}

void StringStorage::add(const char * cs) {
    if (cs==NULL) cs="";
    if (!isStored(cs)) {
	SYNC(mutex);
        const char *s(duplicate(cs));
        contents.insert(std::pair<const char *,IndexType>(s,2*stored.size()+1));
        SSInfo ssi;
        ssi.str=s;
        ssi.hashCode=CStrHashFn()(s);
        stored.push_back(ssi);
    }
}
bool StringStorage::isStored(const char *str) const {
    SYNC(mutex);
    return  contents.find(str)!=contents.end();
}

StringStorage::IndexType StringStorage::get(const char *str) const {
    SYNC(mutex);
    StoreMap::const_iterator it=contents.find(str);
    if (it!=contents.end()) {
        return it->second;
    } else return 0;
}

StringStorage::~StringStorage() {
    while (!contents.empty()) {
        StoreMap::iterator it=contents.begin();
        contents.erase(it);
        freeDuplicate(const_cast<char *>(it->first));
    }

    stored.clear();
}

//------------------------------------------------

void StoreString::construct(const std::string &str) {
    free();
    buf=getStorage()->get(str.c_str());
    if (buf==0) {
        buf=(unsigned long)duplicate(str.c_str());
    }
}

StringStorage *StoreString::getStorage() {
    static StringStorage * storage =new StringStorage();
    return storage;
}

StoreString::StoreString() {
    buf=0;
    construct(std::string());
}

StoreString::StoreString(const std::string &str) {
    buf=0;
    construct(str);
}
StoreString::StoreString(const char *str) {
    buf=0;
    construct(std::string(str));
}

StoreString::StoreString(const StoreString &from) {
    buf=0;
    copyFrom(from);
}

void StoreString::free()
{
    if (!isStored() && buf!=0) {
        delete[] ((char *)buf);
    }
    buf=0;
}

StoreString::~StoreString() {
    free();
}

std::string StoreString::toString() const {
    return std::string(const_cast<char *>(c_str()));
}

StoreString StoreString::store(const std::string &str) {
    getStorage()->add(str);
    return StoreString(str);
}
StoreString StoreString::store(const char *str) {
    getStorage()->add(str);
    return StoreString(str);
}

}

max_stars_repo_name: rafalrusin/xmlbeansxx

max_issues_repo_name: rafalrusin/xmlbeansxx

max_forks_repo_name: rafalrusin/xmlbeansxx


text:
#include "AdaptiveLaw.hpp"
#include <Eigen/Dense>
#include <stdexcept>

using namespace Eigen;
using namespace std;

AdaptiveLaw::AdaptiveLaw(void)
{
    this->dt = 0.0;
}
AdaptiveLaw::~AdaptiveLaw(void)
{

}

void AdaptiveLaw::initialize(const AdaptiveLaw_Config_t _config)
{
    this->Gamma = _config.Gamma;
    this->P = _config.P;
    this->B = _config.B;
    this->dt = _config.dt;

    reset();
}

void AdaptiveLaw::reset()
{
	this->BigTheta = MatrixXd::Zero(this->Gamma.rows(), this->B.cols());
}

void AdaptiveLaw::update(const VectorXd error, const VectorXd  phi)
{
    MatrixXd BigTheta_dot = this->Gamma * phi * error.transpose() * this->P * this->B;
    this->BigTheta += BigTheta_dot * this->dt;
}

void AdaptiveLaw::get_gains(MatrixXd &outputs)
{
    outputs = this->BigTheta;
}

ext: cpp


text:
#ifndef FIELD_H
#define FIELD_H

#include "vector"
#include "array"

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
#pragma clang diagnostic ignored "-Wunused-parameter"
#pragma clang diagnostic ignored "-Wmissing-braces"
#include "dccrg.hpp"
#include "dccrg_cartesian_geometry.hpp"
#pragma clang diagnostic pop

#include "cell.hpp"
#include "parameters.hpp"
#include "common.h"

#include <Eigen/Dense>

using namespace std;
using namespace dccrg;
using namespace Eigen;

typedef Array<double, 4, 1> vec4;
// typedef Array<double, 3, 1> vec3;
typedef Array<double, 4, 4> mat4;

// class to handle neighborhood cells
class Field_Cube
{
public:

    std::array<vec4, 27> fields;

    vec4& operator [](const std::size_t i){return this->fields[i];}
    const vec4& operator [](const std::size_t i) const {return this->fields[i];}

    void init_currents()
    {
        for(int ijk=0; ijk<27; ijk++) {
            fields[ijk] = vec4::Zero();
        }
        return;
    };

    int index(int i, int j, int k) {
        return (i+1) + (j+1)*3 + (k+1)*3*3;
    };

    void add_J(int i, int j, int k, vec4 dJ)
    {
        int ijk = this->index(i,j,k);

        #ifdef DEBUG
        cout << "  addJ: " << i << j << k << " -> " << ijk
        << " A" << dJ << " B " << fields[ijk] << endl;
        #endif

        fields[ijk] += dJ;
    };

    vec4 J(int i, int j, int k) {
        return this->fields[index(i,j,k)];
    };

    void distribute(dccrg::Dccrg<Cell, dccrg::Cartesian_Geometry>& grid, uint64_t cell);

};

class Field_Solver
{
public:

    // Mesh() {};

    // MPI parameters
    int
        rank = 0;

    // Advance half of the B field
    void push_half_B(dccrg::Dccrg<Cell, dccrg::Cartesian_Geometry>& grid);

    // Advance E field
	void push_E(dccrg::Dccrg<Cell, dccrg::Cartesian_Geometry>& grid);

};

#endif

ext: hpp

max_stars_repo_name: Krissmedt/imprunko

max_issues_repo_name: Krissmedt/imprunko

max_forks_repo_name: Krissmedt/imprunko


text:
#pragma once

#include <nano/lib/config.hpp>
#include <nano/lib/numbers.hpp>
#include <nano/lib/utility.hpp>
#include <nano/secure/common.hpp>

#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/thread.hpp>

#include <condition_variable>
#include <deque>
#include <mutex>

namespace nano
{
class node;
class vote_generator final
{
public:
	vote_generator (nano::node &);
	void add (nano::block_hash const &);
	void stop ();

private:
	void run ();
	void send (nano::unique_lock<std::mutex> &);
	nano::node & node;
	std::mutex mutex;
	nano::condition_variable condition;
	std::deque<nano::block_hash> hashes;
	nano::network_params network_params;
	bool stopped{ false };
	bool started{ false };
	boost::thread thread;

	friend std::unique_ptr<seq_con_info_component> collect_seq_con_info (vote_generator & vote_generator, const std::string & name);
};

std::unique_ptr<seq_con_info_component> collect_seq_con_info (vote_generator & vote_generator, const std::string & name);
class cached_votes final
{
public:
	std::chrono::steady_clock::time_point time;
	nano::block_hash hash;
	std::vector<std::shared_ptr<nano::vote>> votes;
};
class votes_cache final
{
public:
	void add (std::shared_ptr<nano::vote> const &);
	std::vector<std::shared_ptr<nano::vote>> find (nano::block_hash const &);
	void remove (nano::block_hash const &);

private:
	std::mutex cache_mutex;
	boost::multi_index_container<
	nano::cached_votes,
	boost::multi_index::indexed_by<
	boost::multi_index::ordered_non_unique<boost::multi_index::member<nano::cached_votes, std::chrono::steady_clock::time_point, &nano::cached_votes::time>>,
	boost::multi_index::hashed_unique<boost::multi_index::member<nano::cached_votes, nano::block_hash, &nano::cached_votes::hash>>>>
	cache;
	nano::network_params network_params;
	friend std::unique_ptr<seq_con_info_component> collect_seq_con_info (votes_cache & votes_cache, const std::string & name);
};

std::unique_ptr<seq_con_info_component> collect_seq_con_info (votes_cache & votes_cache, const std::string & name);
}

max_stars_repo_name: ez-lol/nano-node

max_issues_repo_name: ez-lol/nano-node

max_forks_repo_name: ez-lol/nano-node


text:
/*
  Copyright (c) <2014-2016>, <BenHJ>
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.
  3. Neither the name of the copyright holder nor the names of its contributors
  may be used to endorse or promote products derived from this software without
  specific prior written permission.

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

/// A visitor for extracting fles and folders

#pragma once

#include "knoxcrypt/EntryInfo.hpp"
#include "knoxcrypt/CoreFS.hpp"
#include "knoxcrypt/FileDevice.hpp"
#include "utility/ContentFolderVisitor.hpp"

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/iostreams/copy.hpp>
#include <functional>

#include <sstream>

namespace knoxcrypt
{

    namespace utility
    {

        class FolderExtractionVisitor : public ContentFolderVisitor
        {
          public:
            FolderExtractionVisitor() = delete;
            FolderExtractionVisitor(CoreFS &theBfs,
                                    std::string teaPath,
                                    std::string fsPath,
                                    std::function<void(std::string)> const &callback)
            : m_theBfs(theBfs)
            , m_teaPath(teaPath)
            , m_fsPath(fsPath)
            , m_callback(callback)
            {
            }

            virtual void enterFolder(EntryInfo const &it)
            {
                // get the parent folder
                boost::filesystem::path fsLoc(m_fsPath);
                fsLoc /= it.filename();
                boost::filesystem::path teaLoc(m_teaPath);
                teaLoc /= it.filename();

                std::stringstream ss;
                ss << "Extracting folder "<<fsLoc<<"...";
                m_callback(ss.str());

                boost::filesystem::create_directory(fsLoc);
                m_fsPath = fsLoc.string();
                m_teaPath = teaLoc.string();
            }

            virtual void enterFile(EntryInfo const &it)
            {
                boost::filesystem::path fsLoc(m_fsPath);
                fsLoc /= it.filename();
                boost::filesystem::path teaLoc(m_teaPath);
                teaLoc /= it.filename();
                std::stringstream ss;
                ss << "Extracting file "<<fsLoc<<"...";
                m_callback(ss.str());
                knoxcrypt::FileDevice device = m_theBfs.openFile(teaLoc.string(), knoxcrypt::OpenDisposition::buildReadOnlyDisposition());
                device.seek(0, std::ios_base::beg);
                std::ofstream out(fsLoc.string().c_str(), std::ios_base::binary);
                boost::iostreams::copy(device, out);
            }

            virtual void exitFolder(EntryInfo const &)
            {
                boost::filesystem::path fsLoc(m_fsPath);
                fsLoc = fsLoc.parent_path();
                boost::filesystem::path teaLoc(m_teaPath);
                teaLoc = teaLoc.parent_path();
                m_fsPath = fsLoc.string();
                m_teaPath = teaLoc.string();
            }

          private:
            CoreFS &m_theBfs;
            std::string m_teaPath;
            std::string m_fsPath;
            std::function<void(std::string)> m_callback;
        };

    }

}

max_stars_repo_name: benhj/KnoxCrypt

max_issues_repo_name: benhj/KnoxCrypt

max_forks_repo_name: benhj/KnoxCrypt


text:
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_IMPL_HTTP_ASYNC_CONNECTION_HPP_20100601
#define BOOST_NETWORK_PROTOCOL_HTTP_IMPL_HTTP_ASYNC_CONNECTION_HPP_20100601

// Copyright 2010 (C) Dean Michael Berris
// Copyright 2010 (C) Sinefunc, Inc.
// Copyright 2011 Dean Michael Berris (dberris@google.com).
// Copyright 2011 Google,Inc.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/network/protocol/http/client/client_connection.hpp>
#include <boost/enable_shared_from_this.hpp>

namespace boost { namespace asio {

class io_service;

}  // namespace asio

}  // namespace boost

namespace boost { namespace network { namespace http {

struct request;
struct response;
struct resolver_delegate;
struct connection_delegate;

struct http_async_connection_pimpl;

struct http_async_connection : client_connection
                             , enable_shared_from_this<http_async_connection> {
  using client_connection::callback_type;
  http_async_connection(shared_ptr<resolver_delegate> resolver_delegate,
                        shared_ptr<connection_delegate> connection_delegate,
                        asio::io_service & io_service,
                        bool follow_redirects);
  http_async_connection * clone() const;
  virtual response send_request(std::string const & method,
                                request const & request,
                                bool get_body,
                                callback_type callback,
                                request_options const &options);  // override
  virtual void reset();  // override
  virtual ~http_async_connection();
 private:
  explicit http_async_connection(shared_ptr<http_async_connection_pimpl>);
  shared_ptr<http_async_connection_pimpl> pimpl;
};

} // namespace http

} // namespace network

} // namespace boost

#endif // BOOST_NETWORK_PROTOCOL_HTTP_IMPL_HTTP_ASYNC_CONNECTION_HPP_20100601

max_stars_repo_name: sureandrew/cpp-netlib

max_issues_repo_name: sureandrew/cpp-netlib

max_forks_repo_name: sureandrew/cpp-netlib


text:
//
// Timing Pinocchio
//
// Based on timings.cpp from Pinocchio
//

#include "pinocchio/spatial/fwd.hpp"
#include "pinocchio/spatial/se3.hpp"
#include "pinocchio/multibody/visitor.hpp"
#include "pinocchio/multibody/model.hpp"
#include "pinocchio/multibody/data.hpp"
#include "pinocchio/algorithm/crba.hpp"
#include "pinocchio/algorithm/centroidal.hpp"
#include "pinocchio/algorithm/aba.hpp"
#include "pinocchio/algorithm/rnea.hpp"
#include "pinocchio/algorithm/cholesky.hpp"
#include "pinocchio/algorithm/jacobian.hpp"
#include "pinocchio/algorithm/center-of-mass.hpp"
#include "pinocchio/algorithm/compute-all-terms.hpp"
#include "pinocchio/algorithm/kinematics.hpp"
#include "pinocchio/parsers/urdf.hpp"
#include "pinocchio/parsers/sample-models.hpp"

#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>

#include "csv_reader.h"
#include "tictoc_timer.h"

#include <Eigen/StdVector>
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::VectorXd)

int main(int argc, const char ** argv)
{
   using namespace Eigen;
   using namespace pinocchio;

   // Check arguments
   if (argc != 2)
   {
      std::cerr << "You have to specify a robot model. Choices are: iiwa, hyq, atlas" << std::endl;
      return 1;
   }

   // Set robot model
   bool floating_base;
   std::string robot_model(argv[1]);
   if (robot_model == "iiwa")
   {
      std::cout << "Robot Model = " << robot_model << std::endl;
      floating_base = false;
   }
   else if ((robot_model == "hyq")|(robot_model == "atlas"))
   {
      std::cout << "Robot Model = " << robot_model << std::endl;
      floating_base = true;
   }
   else
   {
      std::cerr << "Invalid robot model: " << robot_model << "\nChoices are: iiwa, hyq, atlas" << std::endl;
      return 2;
   }

   // Setup timer
   TicToc timer(TicToc::NS);
   const int NBT = 1000*100;

   // Import URDF model
   Model model;
   std::string urdf_filename;
   urdf_filename = RBD_BENCHMARKS_DIR"/description/urdf/"+robot_model+".urdf";
   if (floating_base)
      pinocchio::urdf::buildModel(urdf_filename,JointModelFreeFlyer(),model);
   else
      pinocchio::urdf::buildModel(urdf_filename,model);
   model.gravity = Eigen::Vector3d(0,0,0);
   Data data(model);
   int dof = model.nv;
   std::cout << "dof = " << dof << std::endl;

   // Import CSV inputs
   std::string input_filename;
   input_filename = RBD_BENCHMARKS_DIR"/csv/pinocchio/"+robot_model+"_inputs.csv";
   std::ifstream input_csv(input_filename.c_str());
   CSVRow row;
   std::vector<VectorXd> qs     (NBT, VectorXd::Zero(model.nq));
   std::vector<VectorXd> qdots  (NBT, VectorXd::Zero(model.nv));
   std::vector<VectorXd> qddots (NBT, VectorXd::Zero(model.nv));
   std::vector<VectorXd> taus   (NBT, VectorXd::Zero(model.nv));
   input_csv >> row;
   int tot_q, tot_qdot;
   tot_q    = model.nq;
   tot_qdot = model.nv;
   std::cout << "qs, qdots = " << tot_q << ", " << tot_qdot << std::endl;
   int col, start_col;
   for(int i=0;i<NBT;++i)
   {
      input_csv >> row;
      start_col = 0;                 // 0
      for(int j=0;j<tot_q;++j)
      {
            col = start_col+j;
            qs[i][j] = atof(row[col].c_str());
      }
      start_col = tot_q;               // 1xQ
      for(int j=0;j<tot_qdot;++j)
      {
            col = start_col+j;
            qdots[i][j] = atof(row[col].c_str());
      }
      start_col = tot_q+tot_qdot;      // 1xQ+1xQd
      for(int j=0;j<tot_qdot;++j)
      {
            col = start_col+j;
            qddots[i][j] = atof(row[col].c_str());
      }
      start_col = tot_q+2*tot_qdot;  // 1xQ+2xQd
      for(int j=0;j<tot_qdot;++j)
      {
            col = start_col+j;
            taus[i][j] = atof(row[col].c_str());
      }
   }

   // Initialize some output variables
   double time_data;

   std::cout << "--" << std::endl;

   // Dynamics Algorithms
   std::string algorithm_name;
   #ifdef RNEA_ALG
   algorithm_name = "rnea";
   std::cout << "RNEA" << std::endl;
   #elif  CRBA_ALG
   algorithm_name = "crba";
   std::cout << "CRBA" << std::endl;
   #elif  ABA_ALG
   algorithm_name = "aba";
   std::cout << "ABA" << std::endl;
   #else
   algorithm_name = "rnea";
   std::cout << "RNEA" << std::endl;
   #endif /* Dynamics Algorithms */

   // Write CSV outputs
   std::ofstream output_csv;
   std::string output_filename;
   std::stringstream num_inputs;
   num_inputs << NBT;
   output_filename = RESULTS_DIR"/terr_"+robot_model+"_"+num_inputs.str()+"_pinocchio_"+algorithm_name+".csv";
   output_csv.open (output_filename.c_str());

   SMOOTH(NBT)
   {
      if (_smooth != 0) output_csv << "\n";

      timer.tic();
      // Dynamics Algorithms
      #ifdef RNEA_ALG
      rnea(model,data,qs[_smooth],qdots[_smooth],qddots[_smooth]);
      #elif  CRBA_ALG
      crba(model,data,qs[_smooth]);
      #elif  ABA_ALG
      aba(model,data,qs[_smooth],qdots[_smooth],taus[_smooth]);
      #else
      rnea(model,data,qs[_smooth],qdots[_smooth],qddots[_smooth]);
      #endif /* Dynamics Algorithms */
      time_data = timer.toc(TicToc::NS);

      output_csv << time_data;
   }

   output_csv.close();

   std::cout << "--" << std::endl;

   return 0;
}

ext: cc

max_stars_repo_name: CobbledSteel/rbd-benchmarks-riscv

max_issues_repo_name: CobbledSteel/rbd-benchmarks-riscv

max_forks_repo_name: CobbledSteel/rbd-benchmarks-riscv


text:
#include "single_illuminant_pipeline.h"
#include "common/color.h"
#include "metadata/metadatastorage.h"
#include "evaluation/error.h"
#include <iostream>
#include <time.h>
#include <fstream>
#ifndef BOOST_FILESYSTEM_VERSION
#define BOOST_FILESYSTEM_VERSION 3
#endif // BOOST_FILESYSTEM_VERSION
#include <boost/filesystem.hpp>

namespace illumestimators {

bool SingleIlluminantPipeline::loadIlluminantEstimator(IlluminantEstimator& estimator, const std::string& filename)
{
	if (filename.size() > 0) {
		if (estimator.load(filename)) {
			std::cout << "Loading illuminant estimator from file." << std::endl << std::endl;
			return true;
		} else {
			std::cout << "Failed loading illuminant estimator from file." << std::endl << std::endl;
		}
	}

	return false;
}

bool SingleIlluminantPipeline::saveIlluminantEstimator(const IlluminantEstimator& estimator, const std::string& filename)
{
	if (filename.size() > 0) {
		estimator.save(filename);
		return true;
	}

	return false;
}

bool SingleIlluminantPipeline::runTraining(IlluminantEstimator& estimator, const std::vector<std::string>& filenames, MetadataStorage& storage, int verbosity)
{
	std::vector<std::string> trainingFilenames;

	for (unsigned int i = 0; i < filenames.size(); i++) {
		std::string filename = filenames[i];
		boost::filesystem::path path(filename);

		if (path.extension().string().compare(".txt") == 0) {
			std::ifstream in(filename.c_str(), std::ifstream::in);

			while (in.good()) {
				std::string line;
				std::getline(in, line);

				if (line.size() > 0) {
					if (boost::filesystem::path(line).is_absolute()) {
						trainingFilenames.push_back(line);
					} else {
						trainingFilenames.push_back(path.parent_path().string() + "/" + line);
					}
				}
			}
		} else {
			trainingFilenames.push_back(filename);
		}
	}

	if (verbosity > 0) {
		std::cout << "Training " << estimator.name();
		if (verbosity > 1) {
			std::cout << " on the following training files:" << std::endl;
			for (unsigned int i = 0; i < trainingFilenames.size(); i++) {
				 std::cout << "  " << trainingFilenames[i] << std::endl;
			}
		} else {
			std::cout << std::endl;
		}
	}

	std::vector<std::string> trainingColorspaces;
	std::vector<cv::Vec3d> trainingIlluminants;
	std::vector<std::string> trainingMasks;
	std::vector<std::string> trainingFiles;

	for (unsigned int i = 0; i < trainingFilenames.size(); i++) {
		Metadata meta = storage.getMetadata(trainingFilenames[i]);

		trainingFiles.push_back(meta.filename());
		trainingColorspaces.push_back(meta.colorspace());
		trainingIlluminants.push_back(cv::Vec3d(meta.dominantIlluminant().b, meta.dominantIlluminant().g, meta.dominantIlluminant().r));
		trainingMasks.push_back(meta.maskFilename());
	}

	if (trainingIlluminants.size() == 0) {
		std::cerr << "Error no training data." << std::endl << std::endl;
		return false;
	}

	clock_t start = clock();

	estimator.train(trainingFiles, trainingColorspaces, trainingIlluminants, trainingMasks);

	clock_t elapsed = (clock() - start) / 1000;

	if (verbosity > 0) {
		std::cout << "Training: " << elapsed << "ms" << std::endl << std::endl;
	}

	return true;
}

bool SingleIlluminantPipeline::runEstimator(Illum& estimate, double& error, const IlluminantEstimator& estimator, const std::string& filename, MetadataStorage& storage, int verbosity)
{
	if (!storage.hasMetadata(filename)) {
		std::cerr << "Error loading meta data file for " << filename << ", aborted." << std::endl;
		return false;
	}

	Metadata meta = storage.getMetadata(filename);

	cv::Mat_<cv::Vec3d> inputImage = IlluminantEstimator::cleanlyReadImage(filename, meta.colorspace());

	if (inputImage.empty()) {
		std::cerr << "Error loading input image " << filename << "!" << std::endl;
		return false;
	}

	cv::Mat_<unsigned char> mask = meta.mask();

	if (mask.empty()) {
		mask = cv::Mat_<unsigned char>(inputImage.rows, inputImage.cols, (unsigned char)0);
	}

	if (verbosity > 0) {
		std::cout << "Calling " << estimator.name() << ":" << std::endl;
		std::cout << "  " << filename << std::endl << std::endl;
	}

	cv::Mat_<cv::Vec3d> outputImage;
	cv::Mat_<unsigned char> outputMask;

	clock_t start = clock();

	estimator.preprocessImage(inputImage, mask, outputImage, outputMask);
	estimate = estimator.estimateIlluminant(outputImage, outputMask);

	clock_t elapsed = (clock() - start) / 1000;

	if (verbosity > 0) {
		std::cout << "Estimation: " << elapsed << "ms" << std::endl << std::endl;
	}

	Illum groundtruth = meta.dominantIlluminant();

	if (verbosity > 0) {
		std::cout << "Ground truth illuminant chromaticities:" << std::endl;
		std::cout << "  r = " << groundtruth.r << ", g = " << groundtruth.g << ", b = " << groundtruth.b << std::endl << std::endl;

		std::cout << "Estimated illuminant chromaticities:" << std::endl;
		std::cout << "  r = " << estimate.r << ", g = " << estimate.g << ", b = " << estimate.b << std::endl << std::endl;

		error = estimate.angularErrorDeg(groundtruth);
		std::cout << "Error: " << error << "°" <<  std::endl << std::endl;
	} else {
		error = estimate.angularErrorDeg(groundtruth);
		std::cout << error <<  std::endl;
	}
	return true;
}

} // illumestimators

max_stars_repo_name: rodrigobressan/PADify

max_issues_repo_name: rodrigobressan/PADify

max_forks_repo_name: rodrigobressan/PADify


text:
// Copyright Louis Dionne 2015
// Distributed under the Boost Software License, Version 1.0.

#include <boost/hana.hpp>
#include <boost/hana/ext/std/type_traits.hpp>

#include <type_traits>
using namespace boost::hana;
using namespace boost::hana::literals;

// sample(printf-formats)
auto formats = make_map(
  make_pair(char_<'i'>, type<int>),
  make_pair(char_<'f'>, type<double>),
  make_pair(char_<'s'>, type<char*>)

  // ...
);
// end-sample

// sample(printf-core)
template <typename Fmt, typename ...Args>
int type_safe_printf(Fmt fmt, Args const& ...args) {
  static_assert(is_a<String>(fmt),
  "the format string must be a compile-time hana::String");

  auto format_chars = filter(to<Tuple>(fmt), [](auto c) {
    return contains(formats, c);
  });

  static_assert(length(format_chars) == sizeof...(args),
  "number of arguments not matching the number of format characters");

  auto conversions = zip(tuple_t<std::decay_t<Args>...>, format_chars);
  for_each(conversions, fuse([](auto arg_type, auto format_char) {
    static_assert(decltype(formats[format_char] == arg_type){},
    "the type of the argument does not match the format character");
  }));

  return std::printf(to<char const*>(fmt), args...);
};
// end-sample

int main() {

#if 1
// sample(printf-usage)
type_safe_printf(BOOST_HANA_STRING("%i, %f, %s"), 2, 3.4, "abcd");
// end-sample
#elif 0
// sample(printf-wrong_type)
type_safe_printf(BOOST_HANA_STRING("%i, %f, %s"), 2, 2, "abcd");
// end-sample
#elif 0
// sample(printf-wrong_narg)
type_safe_printf(BOOST_HANA_STRING("%i, %f, %s"), 2, 3.4);
// end-sample
#endif

}


text:
/**
 * Copyright (C) 2022 AMD, Inc
 *
 * Licensed under the Apache License, Version
 * 2.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is located
 * 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.
 */

// ------ I N C L U D E   F I L E S -------------------------------------------
// Local - Include Files
#include "OO_Hotplug.h"
#include "tools/common/XBUtilitiesCore.h"
#include "tools/common/XBUtilities.h"

// XRT - Include Files
#include "core/common/query_requests.h"
#include "core/common/system.h"

// 3rd Party Library - Include Files
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
namespace po = boost::program_options;

// System - Include Files
#include <fstream>
// =============================================================================

// ----- H E L P E R M E T H O D S ------------------------------------------
static void
hotplug_online()
{
  static const std::string  rescan_path = "/sys/bus/pci/rescan";

  if (!boost::filesystem::exists(rescan_path))
    throw xrt_core::error((boost::format("Invalid sysfs file path '%s'.") % rescan_path).str());

  std::ofstream rescan_file(rescan_path);
  if (!rescan_file.is_open())
    throw xrt_core::error((boost::format("Unable to open the sysfs file '%s'.") % rescan_path).str());

  // Writing "1" to /sys/bus/pci/rescan will trigger the hotplug event.
  rescan_file << 1;
  rescan_file.flush();
  if (!rescan_file.good()) {
    rescan_file.close();
    throw std::runtime_error(boost::str(boost::format("Can't write to file %s") % rescan_path));
  }

  rescan_file.close();
}

// ----- C L A S S   M E T H O D S -------------------------------------------

OO_Hotplug::OO_Hotplug(const std::string &_longName, bool _isHidden )
    : OptionOptions(_longName, _isHidden, "Perform hotplug for the given device")
{
  m_optionsDescription.add_options()
    ("device,d", po::value<decltype(m_devices)>(&m_devices), "The Bus:Device.Function (e.g., 0000:d8:00.0) device of interest")
    ("action", po::value<decltype(m_action)>(&m_action)->required(), "Action to perform: online or offline")
    ("help", po::bool_switch(&m_help), "Help to use this sub-command")
  ;

  m_positionalOptions.
    add("action", 1 /* max_count */)
  ;
}

void
OO_Hotplug::execute(const SubCmdOptions& _options) const
{
  XBUtilities::verbose("SubCommand option: Hotplug");

  XBUtilities::verbose("Option(s):");
  for (const auto & aString : _options)
    XBUtilities::verbose(std::string(" ") + aString);

  // Honor help option first
  if (std::find(_options.begin(), _options.end(), "--help") != _options.end()) {
    printHelp();
    return;
  }

  // Parse sub-command ...
  po::variables_map vm;

  try {
    po::store(po::command_line_parser(_options).options(m_optionsDescription).positional(m_positionalOptions).run(), vm);
    po::notify(vm); // Can throw
  }
  catch (po::error& e) {
    std::cerr << "ERROR: " << e.what() << "\n\n";
    printHelp();
    throw xrt_core::error(std::errc::operation_canceled);
  }

  if (m_help) {
    printHelp();
    return;
  }

  try {
    if (!boost::iequals(m_action, "online") && !boost::iequals(m_action, "offline")) {
      std::cerr << boost::format("ERROR: Invalid action value: '%s'\n") % m_action;
      printHelp();
      throw xrt_core::error(std::errc::operation_canceled);
    }

    const bool is_offline = boost::iequals(m_action, "offline");

    // Device BDF need to spcify for offline (hot removal) case
    if (is_offline) {
      if (m_devices.empty()) {
        std::cerr << boost::format("ERROR: A device needs to be specified for offline.\n");
        throw xrt_core::error(std::errc::operation_canceled);
      }
    }
    else {
      if (!m_devices.empty()) {
        std::cerr << boost::format("ERROR: Please do not specify any device for online.\n");
        throw xrt_core::error(std::errc::operation_canceled);
      }
    }

    // Collect all the devices of interest
    std::set<std::string> deviceNames;
    xrt_core::device_collection deviceCollection;
    for (const auto & deviceName : m_devices)
      deviceNames.insert(boost::algorithm::to_lower_copy(deviceName));

    XBUtilities::collect_devices(deviceNames, false /*inUserDomain*/, deviceCollection);

    // enforce 1 device specification
    if (deviceCollection.size() > 1) {
      std::stringstream errmsg;
      errmsg << "Multiple devices are not supported. Please specify a single device using --device option\n\n";
      errmsg << "List of available devices:\n";
      boost::property_tree::ptree available_devices = XBUtilities::get_available_devices(true);
      for (auto& kd : available_devices) {
        boost::property_tree::ptree& _dev = kd.second;
        errmsg << boost::format("  [%s] : %s\n") % _dev.get<std::string>("bdf") % _dev.get<std::string>("vbnv");
      }
      throw xrt_core::error(std::errc::operation_canceled, errmsg.str());
    }

    XBUtilities::sudo_or_throw("Root privileges required to perform hotplug operation");
    std::cout << "CAUTION: Performing hotplug command. " <<
	  "This command is going to impact both user pf and mgmt pf.\n" <<
	  "Please make sure no application is currently running." << std::endl;

    // Get permission from user.
    if (!XBUtilities::can_proceed(XBUtilities::getForce()))
      throw xrt_core::error(std::errc::operation_canceled);

    if (is_offline) {
      auto &dev = deviceCollection[0];
      xrt_core::device_query<xrt_core::query::hotplug_offline>(dev);
    }
    else {
      // For online, no specific device is attached with it.
      // Hence can't implement as a query. Implemented it locally
      hotplug_online();
    }

    std::cout << boost::format("\nHotplug %s successfully\n") % (is_offline ? "offline" : "online");
  }
  catch (const xrt_core::error& e) {
    std::cerr << boost::format("\nERROR: %s\n") % e.what();
    throw xrt_core::error(std::errc::operation_canceled);
  }
  catch (const std::runtime_error& e) {
    std::cerr << boost::format("\nERROR: %s\n") % e.what();
    throw xrt_core::error(std::errc::operation_canceled);
  }
}


text:
//////////////////////////////////////////////////////////////////////////////
//  Boost.Assign v2                                                         //
//                                                                          //
//  Copyright (C) 2003-2004 Thorsten Ottosen                                //
//  Copyright (C) 2010 Erwann Rogard                                        //
//  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 LIBS_ASSIGN_V2_TEST_UNIT_TEST_CSV_PUT_ER_2010_CPP
#define LIBS_ASSIGN_V2_TEST_UNIT_TEST_CSV_PUT_ER_2010_CPP

#include <boost/test/test_tools.hpp>
#define BOOST_ASSIGN_V2_CHECK( p ) BOOST_CHECK( p )

#include <libs/assign/v2/test/put/csv_put_basic.cpp>
#include <libs/assign/v2/test/put/csv_put_ext.cpp>
#include <libs/assign/v2/test/put/do_csv_put.cpp>

#include <boost/test/unit_test.hpp>
using boost::unit_test::test_suite;
test_suite* init_unit_test_suite( int argc, char* argv[] )
{
    test_suite* test = BOOST_TEST_SUITE( "BOOST_ASSIGN_V2" );
    using namespace test_assign_v2;
    {
        namespace ns = xxx_put;
        test->add( BOOST_TEST_CASE( &ns::xxx_csv_put_basic::test ) );
        test->add( BOOST_TEST_CASE( &ns::xxx_csv_put_ext::test ) );
        test->add( BOOST_TEST_CASE( &ns::xxx_do_csv_put::test ) );
    }
    return test;
}

#endif // LIBS_ASSIGN_V2_TEST_UNIT_TEST_CSV_PUT_ER_2010_CPP


text:
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <map>
#include <stdlib.h>

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

#include <boost/foreach.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/domains/gis/io/wkt/wkt.hpp>

using namespace std;
using namespace boost;

// data type declaration
typedef boost::geometry::model::d2::point_xy<int> point;
typedef boost::geometry::model::polygon<point> polygon;
typedef boost::geometry::model::box<point> box;

typedef map<string,map<int,vector<polygon*> > > polymap;
typedef map<string,map<int,vector<box*> > > boxmap;
typedef map<string,map<int,vector<string> > > datamap;

// data block
polymap markup;
boxmap outline;
datamap data;
const string tab = "\t";
const string sep =  "\x02";
vector<int> join_idx ;

bool cleanup();
bool readSpatialInput();

bool readSpatialInput() {
    string input_line;
    string record;
    string tile_id;
    string row ;
    vector<string> sp;
    vector<string> fields;

    polygon * shape= NULL;
    box * mbb = NULL;

    int index = 0;
    int pos   = -1;

    while(cin && getline(cin, input_line) && !cin.eof()) {
	//cerr << input_line << endl;
	split( sp,input_line, is_any_of("\t")); // SplitVec == { "hello abc","ABC","aBc goodbye" }

	index = boost::lexical_cast<int>(sp[2]);

	pos = join_idx[index];

	split(fields,sp[1], is_any_of(sep));

	record= boost::algorithm::join(fields, tab);

	shape = new polygon();
	mbb   = new box();
	boost::geometry::read_wkt(fields[pos],*shape);
	boost::geometry::correct(*shape);
	boost::geometry::envelope(*shape, *mbb);
	//assert(boost::geometry::area(*mbb)>=0);
	outline[sp[0]][index].push_back(mbb);
	markup[sp[0]][index].push_back(shape);
	data[sp[0]][index].push_back(record);

	cerr <<"Field Count = " << fields.size() << " , index = " << index << endl;
	fields.clear();
	sp.clear();
    }
    return true;
}
bool cleanup() {
}

int main(int argc, char** argv)
{
    if (argc< 3)
    {
	cerr << "usage: join [shape_idx 1] [shape_idx 2] " <<endl;
	return 0;
    }

    // prepare join parameters
    for (int i =1 ; i <argc ;i++)
	join_idx.push_back(atoi(argv[i]));

    boxmap::iterator iter;
    string key ;
    int size = -1;

    if (readSpatialInput())
    {
	// for each key(tile) in the input stream
	for (iter= outline.begin(); iter != outline.end(); iter++)
	{
	    key  = iter->first;
	    map<int ,vector<box*> > &mbbs = outline[key];
	    map<int ,vector<polygon*> > &shapes = markup[key];

	    size = mbbs.size(); // join cardinality
	    vector<polygon> output;

	    int outerloop_size = (mbbs[0]).size(); //src tile polygon size
	    for (int i =1; i< size ;i++)
	    {
		int innerloop_size = (mbbs[i]).size(); // tar tile polygon size
		for (int j =0; j< outerloop_size; j++)
		{
		    for (int k=0; k< innerloop_size; k++)
		    {
			if (boost::geometry::intersects( *(mbbs[0][j]), *(mbbs[i][k])) &&
				boost::geometry::intersects(*(shapes[0][j]), *(shapes[i][k])) ) // if the mbb && shapes intersects
			{
			    cout << data[key][0][j]<< tab << data[key][i][k] << endl; // cross product
			}
		    }
		}
	    }

	}
	return 0;
    }
    else
	return 1;

}

max_stars_repo_name: ablimit/hivesp

max_issues_repo_name: ablimit/hivesp

max_forks_repo_name: ablimit/hivesp


text:
#define BOOST_TEST_MODULE CmdLineUtil Master Test Suite
#include <boost/test/unit_test.hpp>

max_stars_repo_name: IanEmmons/CmdLineUtil

max_issues_repo_name: IanEmmons/CmdLineUtil

max_forks_repo_name: IanEmmons/CmdLineUtil


text:
/*
    This file is part of Nori, a simple educational ray tracer

    Copyright (c) 2012 by Wenzel Jakob and Steve Marschner.

    Nori is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License Version 3
    as published by the Free Software Foundation.

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

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

#include <nori/parser.h>
#include <nori/scene.h>
#include <nori/camera.h>
#include <nori/block.h>
#include <nori/bitmap.h>
#include <nori/integrator.h>
#include <nori/gui.h>
#include <nori/object.h>
#include <boost/scoped_ptr.hpp>
#include <QApplication>
#include <string>

using namespace nori;

void render(Scene *scene, const QString &filename, int version) {
	const Camera *camera = scene->getCamera();
	Vector2i outputSize = camera->getOutputSize();

	/* Create a block generator (i.e. a work scheduler) */
	BlockGenerator blockGenerator(outputSize, NORI_BLOCK_SIZE);

	/* Allocate memory for the entire output image */
	ImageBlock result(outputSize, camera->getReconstructionFilter());
	result.clear();

	/* Launch the GUI */
	NoriWindow window(&result);

	/* Launch one render thread per core */
	int nCores = getCoreCount();
	std::vector<BlockRenderThread *> threads;
	for (int i=0; i<nCores; ++i) {
		BlockRenderThread *thread = new BlockRenderThread(
			scene, scene->getSampler(), &blockGenerator, &result);
		thread->start();
		threads.push_back(thread);
	}

	window.startRefresh();
	qApp->exec();
	window.stopRefresh();

	/* Wait for them to finish */
	for (int i=0; i<nCores; ++i) {
		threads[i]->wait();
		delete threads[i];
	}

	/* Now turn the rendered image block into
	   a properly normalized bitmap */
	Bitmap *bitmap = result.toBitmap();

        /* Evaluate it if meaningful */
        const Evaluator *ev = scene->getEvaluator();
        if(ev) ev->evaluate(bitmap);

	/* Determine the filename of the output bitmap */
	QFileInfo inputInfo(filename);
	QString outputName = inputInfo.path()
		+ QDir::separator()
		+ inputInfo.completeBaseName() + (version < 0 ? QString(".exr") : QString("_%1.exr").arg(version));

	/* Save using the OpenEXR format */
	bitmap->save(outputName);

	delete bitmap;
}

int main(int argc, char **argv) {
	QApplication app(argc, argv);
	Q_INIT_RESOURCE(resources);

        if (argc != 2 && argc != 3) {
                cerr << "Syntax: nori <scene.xml>" << endl;
                return -1;
        }

        // hidden version number
        int version = -1;
        if (argc == 3) {
                version = atoi(argv[2]);
                if(version < 0){
                        cerr << "The version should be positive or null!\n";
                        return -2;
                }
                nori::NoriObjectFactory::setVersion((unsigned int)version);

                cout << "Using version " << version << "\n";
        }else   cout << "Using default version (0)\n";

        // the file name
        QString filename(argv[1]);

	try {
            if (filename.endsWith(".exr")) {
                // image mode
                boost::scoped_ptr<Bitmap> bitmap(new Bitmap(filename));
                ImageBlock image(bitmap.get());

                /* Launch the GUI */
                NoriWindow window(&image);
                return qApp->exec();

            } else {
                // rendering mode
                boost::scoped_ptr<NoriObject> root(loadScene(filename));

		if (root->getClassType() == NoriObject::EScene) {
			/* The root object is a scene! Start rendering it.. */
			render(static_cast<Scene *>(root.get()), filename, version);
		}
            }
	} catch (const NoriException &ex) {
		cerr << "Caught a critical exception: " << qPrintable(ex.getReason()) << endl;
		return -1;
	}

	return 0;
}


text:
#ifndef PROCON_28_GEO_HPP
#define PROCON_28_GEO_HPP

#include <iostream>
#include <vector>

#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/segment.hpp>
#include <boost/geometry/geometry.hpp>

namespace bg = boost::geometry;
namespace trans = bg::strategy::transform;

namespace procon28 {
using Point_Type = long double;                     // x, y座標に使用する型
using Point = bg::model::d2::point_xy<Point_Type>;  // 座標
using Polygon = bg::model::polygon<Point>;          // 図形
using Segment = bg::model::segment<Point>;          // 線分
using Ring = typename Polygon::ring_type;
using InnerContainer = typename Polygon::inner_container_type;
const long double EPS = 1e-10;
const long double PI = std::acos(-1);

std::istream& operator>>(std::istream&, Polygon&);
std::ostream& operator<<(std::ostream&, Polygon&);

const Point operator+(const Point&, const Point&);
const Point operator-(const Point&, const Point&);

Point get_point(const Ring&, int);
Point get_point(const Polygon&, int);
Point get_point(const Segment&, int);
Segment inv_segment(const Segment&);
Segment get_segment(const Ring&, int, int);
Segment get_segment(const Polygon&, int, int);
Segment get_segment(const Ring&, int);
Segment get_segment(const Polygon&, int);
long double get_angle(const Segment&);
long double get_angle(const Segment&, const Segment&);
long double get_corner(const Ring&, int);
long double get_corner(const Polygon&, int);
Point to_vec(const Segment&);
Polygon to_frame(const std::vector<Polygon>&);
std::vector<Polygon> to_piece(const Polygon&);
Polygon translate(const Polygon&, Point_Type, Point_Type);
Polygon translate(const Polygon&, Point);
Polygon rotate(const Polygon&, long double);
Polygon rotate(const Polygon&, long double, Point);
Polygon inverse(const Polygon&);
Polygon scale(const Polygon&, double);
void printFrame(const Polygon&, std::ostream&);

}  // namespace procon28

#endif


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

max_stars_repo_name: wordring/wordring

max_issues_repo_name: wordring/libwordring

max_forks_repo_name: wordring/libwordring


text:
// Copyright (C) 2014-2016 Vicente J. Botet Escriba
//
//  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)

// <experimental/make.hpp>

//  template <template <class ...> class M, class X>
//  auto make(X&& x);
//  template <class M, class X>
//  auto make(X&& x);
//  template <class M, class ...Args>
//  auto make(Args&& ...args);

#include <experimental/make.hpp>
#include <experimental/meta.hpp>
#include <experimental/memory.hpp>

#include <boost/detail/lightweight_test.hpp>

struct A
{
  int v;
  A(): v(3) {}
  A(int v): v(std::move(v)) {}
  A(int v1, int v2): v(v1+v2) {}
};

int main()
{
  namespace stde = std::experimental;
  static_assert(stde::is_nullable<std::unique_ptr<int>>::value, "ERROR");

  static_assert(std::is_same<stde::meta::rebind_t<std::default_delete<int>, long>, std::default_delete<long>>::value, "ERROR");
  {
    int v=0;
    std::unique_ptr<int> x = stde::make<std::unique_ptr>(v);
    BOOST_TEST(*x == 0);
  }
  {
    int v=0;
    std::unique_ptr<int> x = std::make_unique<int>(v);
    BOOST_TEST(*x == 0);
  }
  {
    int v=0;
    std::unique_ptr<int> x = stde::make<std::unique_ptr<int>>(v);
    BOOST_TEST(*x == 0);
  }
  {
    int v=1;
    std::unique_ptr<A> x = std::make_unique<A>(v,v);
    BOOST_TEST(x->v == 2);
  }
  {
    int v=1;
    std::unique_ptr<A> x = stde::make<std::unique_ptr<A>>(v,v);
    BOOST_TEST(x->v == 2);
  }
  {
    std::unique_ptr<A> x = stde::make<std::unique_ptr<A>>();
    BOOST_TEST_EQ(x->v,  3);
  }
  {
    //static_assert(! std::experimental::meta::is_callable<std::default_delete<stde::_t>(void)>::value, "");
    int v=0;
    std::unique_ptr<int> x = stde::make<std::unique_ptr<stde::_t>>(v);
    BOOST_TEST(*x == 0);
  }
  {
    int v=0;
    std::unique_ptr<int,std::default_delete<int> > x = stde::make<std::unique_ptr<stde::_t, std::default_delete<stde::_t> >>(v);
    BOOST_TEST(*x == 0);
  }
  return ::boost::report_errors();
}

max_stars_repo_name: jwakely/std-make

max_issues_repo_name: jwakely/std-make

max_forks_repo_name: jwakely/std-make


text:
//
// Created by leanne on 11/23/20.
//

#include "utility.h"
#include "VWAP.h"
#include <ctime>
#include <cmath>
#include <random>
#include <algorithm>
#include <cstdio>
#include <boost/timer/timer.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
#include <boost/accumulators/statistics/variance.hpp>

using std::vector;
using std::ofstream;
using namespace boost::accumulators;
using timer = boost::timer::auto_cpu_timer;

void VWAPOption::computefirst2Moments(ofstream& file) {
    timer t;
    accumulator_set<double, stats<tag::moment<1>,tag::variance(immediate) > > moment1;
    accumulator_set<double, stats<tag::moment<2>,tag::variance(immediate) > > moment2;

    //compute estimate for 1st moment
    for (int i = 0; i < NPaths_; ++i) {
        double VWAP_T = simulateSinglePath();
        moment1(VWAP_T);
    }

    //compute estimate for 2nd moment
    for (int i = 0; i < NPaths_; ++i) {
        double VWAP_T = simulateSinglePath();
        moment2(VWAP_T);
    }

    cout << std::endl;
    cout << "computation time = " << t.format(3) << std::endl;
    cout << "sigmaPrice = " << sigmaPrice_ << std::endl;
    cout << "E(VWAP) = " << moment<1>(moment1) << std::endl;
    cout << "E(VWAP^2) = " << moment<2>(moment2) << std::endl;

    file << sigmaPrice_
         << ", "
         << moment<1>(moment1) //E(VWAP)
         << ", "
         << sqrt(variance(moment1)) //StdErr(VWAP)
         << ", "
         << moment<2>(moment2) //E(VWAP)
         << ", "
         << sqrt(variance(moment2)) //StdErr(VWAP^2)
         << std::endl;
}

void VWAPOption::computeMoment3(ofstream& file) {
    timer t;
    accumulator_set<double, stats<tag::moment<3> > > moment3;

    //compute estimate for 3rd moment
    for (int i = 0; i < NPaths_; ++i) {
        double VWAP_T = simulateSinglePath();
        moment3(VWAP_T);
    }

    cout << std::endl;
    cout << "computation time = " << t.format(3) << std::endl;
    cout << "sigmaPrice = " << sigmaPrice_ << std::endl;
    cout << "E(VWAP^3) = " << moment<3>(moment3) << std::endl;

    file << sigmaPrice_
         << ", "
         << moment<3>(moment3) //E(VWAP^3)
         << std::endl;
}

void VWAPOption::computePrice(ofstream& file) {
    timer t;
    accumulator_set<double, stats<tag::mean, tag::variance(immediate) > > price;

    //compute estimate for VWAP price
    for (int i = 0; i < NPaths_; ++i) {
        double VWAP_T = simulateSinglePath();
        if((VWAP_T - K_ ) > 0)
        {
            price(VWAP_T - K_);
        }
        else
        {
            price(0.0);
        }
    }
    cout << std::endl;
    cout << "computation time = " << t.format(3) << std::endl;
    cout << "sigmaPrice = " << sigmaPrice_ << std::endl;
    cout << "price = " << mean(price) << std::endl;
    cout << "stdDevPrice = " << sqrt(variance(price)) << std::endl;

    file << sigmaPrice_
         << ", "
         << mean(price) //option price
         << ", "
         << sqrt(variance(price)) << std::endl;

}
void VWAPOption::computeMoment3AndPrice(ofstream& file) {
    timer t;
    accumulator_set<double, stats<tag::moment<3> > > moment3;
    accumulator_set<double, stats<tag::mean, tag::variance(immediate) > > price;

    //compute estimate for 3rd moment
    for (int i = 0; i < NPaths_; ++i) {
        double VWAP_T = simulateSinglePath();
        moment3(VWAP_T);
    }

    //compute estimate for VWAP price
    for (int i = 0; i < NPaths_; ++i) {
        double VWAP_T = simulateSinglePath();
        if((VWAP_T - K_ ) > 0)
            price(VWAP_T - K_);
        else
            price(0.0);
    }

    cout << std::endl;
    cout << "computation time = " << t.format(2) << std::endl;
    cout << "sigmaPrice = " << sigmaPrice_ << std::endl;
    cout << "E(VWAP^3) = " << moment<3>(moment3) << std::endl;
    cout << "price = " << mean(price) << std::endl;
    cout << "stdDevPrice = " << sqrt(variance(price)) << std::endl;

    file << sigmaPrice_
         << ", "
         << moment<3>(moment3) //E(VWAP^3)
         << ", "
         << mean(price) //option price
         << ", "
         << sqrt(variance(price)) << std::endl;

}

void VWAPOption::computeParameters(ofstream& file) {
    using std::cout;
    timer t;
    for (int i = 0; i < NPaths_; ++i) {

        double VWAP_T = simulateSinglePath();

        VWAPMoments_(VWAP_T);

        if((VWAP_T - K_ ) > 0)
            callOptionPayoffs_(VWAP_T - K_);
        else
            callOptionPayoffs_(0.0);
    }

    cout << std::endl;
    cout << "computation time = " << t.format(3) << std::endl;
    cout << "sigmaPrice = " << sigmaPrice_ << std::endl;
    cout << "Delta = " << delta_ << std::endl;
    cout << "E(VWAP) = " << moment<1>(VWAPMoments_) << std::endl;
    cout << "E(VWAP^2) = " << moment<2>(VWAPMoments_) << std::endl;
    cout << "E(VWAP^3) = " << moment<3>(VWAPMoments_) << std::endl;
    cout << "price = " << mean(callOptionPayoffs_) << std::endl;
    cout << "stdDev = " << sqrt(variance(callOptionPayoffs_)) << std::endl;

    file << sigmaPrice_
         << ", "
         << moment<1>(VWAPMoments_) //E(VWAP)
         << ", "
         << moment<2>(VWAPMoments_) //E(VWAP^2)
         << ", "
         << moment<3>(VWAPMoments_) //E(VWAP^3)
         << ", "
         << mean(callOptionPayoffs_) //option price
         << ", "
         << sqrt(variance(callOptionPayoffs_)) << std::endl;
}

double VWAPOption::GetNormDistrDouble(std::mt19937 &gen)
{
    double val = 1;
    std::normal_distribution<> nd;
    //   val = nd(gen);
    do { val = nd(gen);}
    while(val < 0.4 || val > 2.5);

    return val;
}

//return a realisation of VWAP_T
double VWAPOption::simulateSinglePath() {
    int seed = -107;
    std::mt19937 gen(seed);

    double sumStUt = S0_*X0_*X0_;
    double sumUt   = X0_*X0_;

    double Sti = S0_;
    double Xti = X0_;
    double Uti = 0.0;
    const double muX = a_*(1-exp(-lambda_ * delta_));
    const double sigmaX2 = pow(sigmaVol_,2)/(2*lambda_)*(1-exp(-2*lambda_*delta_));

    //simulate path over [0,T]
    for (int i = 1; i <= numIncrements_; i++) {
        Sti = Sti*exp((mu_-0.5*sigmaPrice_*sigmaPrice_)*delta_
                      + sigmaPrice_*sqrt(delta_))*GetNormDistrDouble(gen);

        Xti = exp(-lambda_*delta_)*Xti + muX + sqrt(sigmaX2)*GetNormDistrDouble(gen);
        Uti = pow(Xti,2);

        sumStUt+= Sti*Uti;
        sumUt += Uti;
    }

    return (sumStUt/sumUt);
}

max_stars_repo_name: leannejdong/VWAPOpt

max_issues_repo_name: leannejdong/VWAPOpt

max_forks_repo_name: leannejdong/VWAPOpt


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

#include <boost/test/unit_test.hpp>
#include <boost/program_options.hpp>

#include <graphene/account_history/account_history_plugin.hpp>
#include <graphene/market_history/market_history_plugin.hpp>

#include <graphene/db/simple_index.hpp>

#include <graphene/chain/asset_object.hpp>
#include <graphene/chain/protocol/asset_ops.hpp>
#include <graphene/chain/protocol/wire.hpp>
#include <graphene/chain/wire_object.hpp>

#include <graphene/utilities/tempdir.hpp>

#include <fc/crypto/digest.hpp>

#include <iostream>
#include <iomanip>
#include <sstream>

#include "database_fixture.hpp"

using namespace graphene::chain::test;

namespace graphene { namespace chain {

const wire_out_holder_object& database_fixture::wire_out(account_id_type account_id, asset asset_to_wire,
                                                         const string& memo)
{ try {

  wire_out_operation op;
  op.account = account_id;
  op.asset_to_wire = asset_to_wire;
  op.memo = memo;

  signed_transaction tx;
  set_expiration(db, tx);
  tx.operations.push_back(op);
  tx.validate();
  processed_transaction ptx = db.push_transaction(tx, ~0);
  tx.clear();

  return db.get<wire_out_holder_object>(ptx.operation_results[0].get<object_id_type>());

} FC_LOG_AND_RETHROW() }

vector<wire_out_holder_object> database_fixture::get_wire_out_holders(account_id_type account_id,
                                                                      const flat_set<asset_id_type>& asset_ids) const
{
   vector<wire_out_holder_object> result;
   const auto& idx = db.get_index_type<wire_out_holder_index>().indices().get<by_account_asset>();
   if ( asset_ids.empty() )
   {
      // if the caller passes in an empty list of asset ID's, return holders for all assets the account owns
      for ( auto it = idx.find(boost::make_tuple(account_id)); it != std::end(idx) && it->account == account_id; ++it )
        result.emplace_back(*it);
   }
   else
   {
      for ( auto asset_id : asset_ids )
      {
        for ( auto it = idx.find(boost::make_tuple(account_id, asset_id));
              it != std::end(idx) && it->account == account_id;
              ++it
            )
          result.emplace_back(*it);
      }
   }
   return result;
}

void database_fixture::wire_out_complete(wire_out_holder_id_type holder_id)
{
  wire_out_complete_operation op;

  op.wire_out_handler = get_wire_out_handler_id();
  op.holder_object_id = holder_id;

  signed_transaction tx;
  set_expiration(db, tx);
  tx.operations.push_back(op);
  tx.validate();
  processed_transaction ptx = db.push_transaction(tx, ~0);
  tx.clear();
}

void database_fixture::wire_out_reject(wire_out_holder_id_type holder_id)
{
  wire_out_reject_operation op;

  op.wire_out_handler = get_wire_out_handler_id();
  op.holder_object_id = holder_id;

  signed_transaction tx;
  set_expiration(db, tx);
  tx.operations.push_back(op);
  tx.validate();
  processed_transaction ptx = db.push_transaction(tx, ~0);
  tx.clear();
}

} }  // namespace graphene::chain

max_stars_repo_name: powerchain-ltd/greenpower-blockchain


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

#include "base/os.h"
#include "oper/instance_manager.h"

#include <cstdlib>
#include <boost/filesystem.hpp>
#include <boost/uuid/random_generator.hpp>

#include "base/logging.h"
#include "testing/gunit.h"
#include <test/test_cmn_util.h>
#include "base/test/task_test_util.h"
#include "cfg/cfg_init.h"
#include "db/db_graph.h"
#include "db/test/db_test_util.h"
#include "ifmap/ifmap_agent_table.h"
#include "ifmap/ifmap_node.h"
#include "ifmap/test/ifmap_test_util.h"
#include "oper/ifmap_dependency_manager.h"
#include "oper/instance_task.h"
#include "oper/operdb_init.h"
#include "oper/service_instance.h"
#include "schema/vnc_cfg_types.h"

using namespace std;
class Agent;
void RouterIdDepInit(Agent *agent) {
}

static boost::uuids::uuid IdPermsGetUuid(const autogen::IdPermsType &id) {
    boost::uuids::uuid uuid;
    CfgUuidSet(id.uuid.uuid_mslong, id.uuid.uuid_lslong, uuid);
    return uuid;
}

class InstanceManagerTest : public ::testing::Test {
public:
    bool IsExpectedStatusType(InstanceState *state, int expected) {
        return state->status_type() == expected;
    }

    bool IsUpdateCommand(InstanceState *state) {
        return string::npos != state->cmd().find("--update");
    }

    bool WaitForAWhile(time_t target) {
        time_t now = time(NULL);
        return now >= target;
    }

protected:
    static const int kTimeoutSeconds = 15;

    InstanceManagerTest() {
    }

    ~InstanceManagerTest() {
    }

    virtual void TearDown() {
        IFMapAgentStaleCleaner *cl = new IFMapAgentStaleCleaner(agent_->db(),
                    agent_->cfg()->cfg_graph());
        cl->StaleTimeout(1);
        task_util::WaitForIdle();
        delete cl;
    }

    virtual void SetUp() {
        agent_ = Agent::GetInstance();
        stringstream ss;
        boost::filesystem::path curr_dir(boost::filesystem::current_path());
        ss << curr_dir.string() << "/" << getpid() << "/";
        agent_->oper_db()-> instance_manager()->loadbalancer_config_path_ = ss.str();

    }

    boost::uuids::uuid AddServiceInstance(const string &name) {
        ifmap_test_util::IFMapMsgNodeAdd(agent_->db(), "service-instance", name);
        task_util::WaitForIdle();
        IFMapTable *table = IFMapTable::FindTable(agent_->db(),
                                                  "service-instance");
        ServiceInstanceTable *si_table = agent_->service_instance_table();
        IFMapNode *node = table->FindNode(name);
        if (node == NULL) {
            return boost::uuids::nil_uuid();
        }
        DBRequest request;
        boost::uuids::uuid si_uuid;
        si_table->IFNodeToUuid(node, si_uuid);
        si_table->IFNodeToReq(node, request, si_uuid);
        si_table->Enqueue(&request);
        task_util::WaitForIdle();

        autogen::ServiceInstance *si_object =
                static_cast<autogen::ServiceInstance *>(node->GetObject());
        const autogen::IdPermsType &id = si_object->id_perms();
        boost::uuids::uuid instance_id = IdPermsGetUuid(id);
        ServiceInstanceKey key(instance_id);
        ServiceInstance *svc_instance =
                static_cast<ServiceInstance *>(si_table->Find(&key, true));
        if (svc_instance == NULL) {
            return boost::uuids::nil_uuid();
        }

        /*
         * Set non-nil uuids
         */
        UpdateProperties(svc_instance, true);
        return instance_id;
    }

    void DeleteServiceInstance(const string &name) {
        ifmap_test_util::IFMapMsgNodeDelete(agent_->db(), "service-instance", name);
    }

    void MarkServiceInstanceAsDeleted(boost::uuids::uuid id) {
        ServiceInstanceKey key(id);
        ServiceInstance *svc_instance =
                static_cast<ServiceInstance
                *>(agent_->service_instance_table()->Find(&key, true));
        if (svc_instance != NULL) {
            svc_instance->MarkDelete();
            agent_->service_instance_table()->Change(svc_instance);
        }
    }

    bool UpdateProperties(boost::uuids::uuid id, bool usable) {
        ServiceInstanceKey key(id);
        ServiceInstance *svc_instance = static_cast<ServiceInstance *>
                (agent_->service_instance_table()->Find(&key, true));
        if (svc_instance == NULL) {
            return false;
        }
        UpdateProperties(svc_instance, usable);

        return true;
    }

    ServiceInstance *GetServiceInstance(boost::uuids::uuid id) {
        ServiceInstanceKey key(id);
        ServiceInstance *svc_instance = static_cast<ServiceInstance *>
            (agent_->service_instance_table()->Find(&key, true));
        if (svc_instance == NULL) {
            return NULL;
        }
        return svc_instance;
    }

    InstanceState *ServiceInstanceState(boost::uuids::uuid id) {
        ServiceInstance *svc_instance = GetServiceInstance(id);
        if (svc_instance == NULL) {
            return NULL;
        }
        return agent_->oper_db()->instance_manager()->GetState(svc_instance);
    }

    InstanceTaskQueue *GetTaskQueue(boost::uuids::uuid id) {
        ServiceInstance *svc_instance = GetServiceInstance(id);
        if (svc_instance == NULL) {
            return NULL;
        }

        stringstream ss;
        ss << svc_instance->properties().instance_id;
        return agent_->oper_db()->instance_manager()->GetTaskQueue(ss.str());
    }

    void NotifyChange(boost::uuids::uuid id) {
        ServiceInstance *svc_instance = GetServiceInstance(id);
        if (svc_instance == NULL) {
            return;
        }
        agent_->service_instance_table()->Change(svc_instance);
    }

    void UpdateProperties(ServiceInstance* svc_instance, bool usable) {
        /*
         * Set non-nil uuids
         */
        ServiceInstance::Properties prop;
        prop.Clear();
        prop.virtualization_type = ServiceInstance::NetworkNamespace;
        boost::uuids::random_generator gen;
        prop.instance_id = svc_instance->uuid();
        prop.vmi_inside = gen();
        prop.vmi_outside = gen();
        prop.ip_addr_inside = "10.0.0.1";
        prop.ip_addr_outside = "10.0.0.2";
        prop.ip_prefix_len_inside = 24;
        prop.gw_ip = "10.0.0.254";
        if (usable) {
            prop.ip_prefix_len_outside = 24;
        }
        svc_instance->set_properties(prop);
        if (usable) {
            EXPECT_TRUE(svc_instance->IsUsable());
        } else {
            EXPECT_FALSE(svc_instance->IsUsable());
        }
        agent_->service_instance_table()->Change(svc_instance);
    }

    const std::string &loadbalancer_config_path() const {
        return agent_->oper_db()->instance_manager()->loadbalancer_config_path_;
    }
protected:
    Agent *agent_;
};

TEST_F(InstanceManagerTest, ExecTrue) {
    agent_->oper_db()->instance_manager()->SetNetNSCmd("/bin/true");
    boost::uuids::uuid id = AddServiceInstance("exec-true");
    EXPECT_FALSE(id.is_nil());
    task_util::WaitForIdle();
    InstanceState *ns_state = ServiceInstanceState(id);
    ASSERT_TRUE(ns_state != NULL);

    EXPECT_EQ(0, ns_state->status());
    EXPECT_EQ(InstanceState::Starting, ns_state->status_type());
    EXPECT_NE(0, ns_state->pid());

    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsExpectedStatusType, this, ns_state, InstanceState::Started),
            kTimeoutSeconds);

    EXPECT_EQ(InstanceState::Started, ns_state->status_type());
    EXPECT_EQ(0, ns_state->status());
    ASSERT_TRUE(ns_state->errors().empty() == true);

    DeleteServiceInstance("exec-true");
    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsExpectedStatusType, this, ns_state, InstanceState::Stopped),
            kTimeoutSeconds);
    task_util::WaitForIdle();
    IFMapTable *table = IFMapTable::FindTable(agent_->db(),
                                                  "service-instance");
    IFMapNode *node = table->FindNode("exec-true");
    ASSERT_TRUE(node == NULL);
}

TEST_F(InstanceManagerTest, ExecNotExisting) {
    agent_->oper_db()->instance_manager()->SetNetNSCmd("/bin/junk");
    boost::uuids::uuid id = AddServiceInstance("exec-false");
    EXPECT_FALSE(id.is_nil());
    task_util::WaitForIdle();
    InstanceState *ns_state = ServiceInstanceState(id);
    ASSERT_TRUE(ns_state != NULL);

    EXPECT_EQ(0, ns_state->status());
    EXPECT_EQ(InstanceState::Starting, ns_state->status_type());
    ASSERT_TRUE(ns_state->errors().empty() == true);

    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsExpectedStatusType, this, ns_state, InstanceState::Error),
            kTimeoutSeconds);

    EXPECT_EQ(InstanceState::Error, ns_state->status_type());
    EXPECT_NE(0, ns_state->status());
    ASSERT_TRUE(ns_state->errors().empty() == false);

    DeleteServiceInstance("exec-false");
    task_util::WaitForIdle();
    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsExpectedStatusType, this, ns_state, InstanceState::Stopped),
            kTimeoutSeconds);
    task_util::WaitForIdle();
    IFMapTable *table = IFMapTable::FindTable(agent_->db(),
                                                  "service-instance");
    IFMapNode *node = table->FindNode("exec-false");
    ASSERT_TRUE(node == NULL);
}

TEST_F(InstanceManagerTest, Update) {
    agent_->oper_db()->instance_manager()->SetNetNSCmd("/bin/true");
    boost::uuids::uuid id = AddServiceInstance("exec-update");
    EXPECT_FALSE(id.is_nil());
    task_util::WaitForIdle();
    InstanceState *ns_state = ServiceInstanceState(id);
    ASSERT_TRUE(ns_state != NULL);

    EXPECT_EQ(0, ns_state->status());
    EXPECT_EQ(InstanceState::Starting, ns_state->status_type());

    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsExpectedStatusType, this, ns_state, InstanceState::Started),
            kTimeoutSeconds);

    EXPECT_EQ(InstanceState::Started, ns_state->status_type());
    EXPECT_EQ(0, ns_state->status());

    bool updated = UpdateProperties(id, true);
    EXPECT_EQ(true, updated);

    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsUpdateCommand, this, ns_state),
            kTimeoutSeconds);

    EXPECT_TRUE(IsUpdateCommand(ns_state));

    DeleteServiceInstance("exec-update");
    task_util::WaitForIdle();

    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsExpectedStatusType, this, ns_state, InstanceState::Stopped),
            kTimeoutSeconds);
    task_util::WaitForIdle();
    IFMapTable *table = IFMapTable::FindTable(agent_->db(),
                                                  "service-instance");
    IFMapNode *node = table->FindNode("exec-update");
    ASSERT_TRUE(node == NULL);

}

TEST_F(InstanceManagerTest, UpdateProperties) {
    agent_->oper_db()->instance_manager()->SetNetNSCmd("/bin/true");
    boost::uuids::uuid id = AddServiceInstance("exec-update");
    EXPECT_FALSE(id.is_nil());
    task_util::WaitForIdle();
    InstanceState *ns_state = ServiceInstanceState(id);
    ASSERT_TRUE(ns_state != NULL);

    EXPECT_EQ(0, ns_state->status());
    EXPECT_EQ(InstanceState::Starting, ns_state->status_type());

    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsExpectedStatusType, this, ns_state, InstanceState::Started),
            kTimeoutSeconds);

    EXPECT_EQ(InstanceState::Started, ns_state->status_type());
    EXPECT_EQ(0, ns_state->status());

    NotifyChange(id);
    task_util::WaitForIdle();

    EXPECT_NE(InstanceState::Starting, ns_state->status_type());

    bool updated = UpdateProperties(id, true);
    EXPECT_EQ(true, updated);

    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsExpectedStatusType, this, ns_state, InstanceState::Starting),
            kTimeoutSeconds);

    DeleteServiceInstance("exec-update");
    task_util::WaitForIdle();

    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsExpectedStatusType, this, ns_state, InstanceState::Stopped),
            kTimeoutSeconds);
    task_util::WaitForIdle();
    IFMapTable *table = IFMapTable::FindTable(agent_->db(),
                                                  "service-instance");
    IFMapNode *node = table->FindNode("exec-update");
    ASSERT_TRUE(node == NULL);
}

/**
 * Timeout test works by not plugin in the signal manager and receiving
 * SIGCHLD rather than by executing a sleep.
 */

#if 0
TEST_F(InstanceManagerTest, Timeout) {

    agent_->oper_db()->instance_manager()->SetNetNSCmd("/bin/tr");
    boost::uuids::uuid id = AddServiceInstance("exec-timeout");
    EXPECT_FALSE(id.is_nil());
    task_util::WaitForIdle();
    InstanceState *ns_state = ServiceInstanceState(id);
    ASSERT_TRUE(ns_state != NULL);

    EXPECT_EQ(0, ns_state->status());
    EXPECT_EQ(InstanceState::Starting, ns_state->status_type());

    time_t now = time(NULL);
    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::WaitForAWhile, this, now + 5),
            kTimeoutSeconds);

    EXPECT_EQ(InstanceState::Timeout, ns_state->status_type());

    MarkServiceInstanceAsDeleted(id);
    task_util::WaitForIdle();
}
#endif

TEST_F(InstanceManagerTest, TaskQueue) {
    static const int kNumUpdate = 5;
    agent_->oper_db()->instance_manager()->SetNetNSCmd("/bin/true");
    boost::uuids::uuid id = AddServiceInstance("exec-queue");
    EXPECT_FALSE(id.is_nil());
    task_util::WaitForIdle();
    InstanceState *ns_state = ServiceInstanceState(id);
    ASSERT_TRUE(ns_state != NULL);

    EXPECT_EQ(0, ns_state->status());
    EXPECT_EQ(InstanceState::Starting, ns_state->status_type());
    InstanceTaskQueue *queue = GetTaskQueue(id);

    EXPECT_EQ(1, queue->Size());

    for (int i = 0; i != kNumUpdate; i++) {
        bool updated = UpdateProperties(id, true);
        EXPECT_EQ(true, updated);
        task_util::WaitForIdle();

        EXPECT_EQ(i + 2, queue->Size());
    }

    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsExpectedStatusType, this, ns_state, InstanceState::Started),
            kTimeoutSeconds);

    EXPECT_EQ(InstanceState::Started, ns_state->status_type());
    EXPECT_EQ(0, ns_state->status());

    DeleteServiceInstance("exec-queue");
    task_util::WaitForIdle();

    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsExpectedStatusType, this, ns_state, InstanceState::Stopped),
            kTimeoutSeconds);
    task_util::WaitForIdle();
    IFMapTable *table = IFMapTable::FindTable(agent_->db(),
                                                  "service-instance");
    IFMapNode *node = table->FindNode("exec-queue");
    ASSERT_TRUE(node == NULL);
}
TEST_F(InstanceManagerTest, Usable) {
    agent_->oper_db()->instance_manager()->SetNetNSCmd("/bin/true");
    boost::uuids::uuid id = AddServiceInstance("exec-usable");
    EXPECT_FALSE(id.is_nil());
    task_util::WaitForIdle();
    InstanceState *ns_state = ServiceInstanceState(id);
    ASSERT_TRUE(ns_state != NULL);

    EXPECT_EQ(0, ns_state->status());
    EXPECT_EQ(InstanceState::Starting, ns_state->status_type());

    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsExpectedStatusType, this, ns_state, InstanceState::Started),
            kTimeoutSeconds);

    EXPECT_EQ(InstanceState::Started, ns_state->status_type());
    EXPECT_EQ(0, ns_state->status());

    NotifyChange(id);
    task_util::WaitForIdle();

    EXPECT_NE(InstanceState::Starting, ns_state->status_type());

    bool updated = UpdateProperties(id, false);
    EXPECT_EQ(true, updated);

    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsExpectedStatusType, this, ns_state, InstanceState::Stopped),
            kTimeoutSeconds);

    DeleteServiceInstance("exec-usable");
    task_util::WaitForIdle();

    task_util::WaitForCondition(agent_->event_manager(),
            boost::bind(&InstanceManagerTest::IsExpectedStatusType, this, ns_state, InstanceState::Stopped),
            kTimeoutSeconds);
    task_util::WaitForIdle();
    IFMapTable *table = IFMapTable::FindTable(agent_->db(),
                                                  "service-instance");
    IFMapNode *node = table->FindNode("exec-usable");
    ASSERT_TRUE(node == NULL);
}

TEST_F(InstanceManagerTest, InstanceStaleCleanup) {

    agent_->oper_db()->instance_manager()->SetNetNSCmd("/bin/true");
    boost::uuids::random_generator gen;
    std::string vm_uuid = UuidToString(gen());
    std::string lb_uuid = UuidToString(gen());

    boost::filesystem::path curr_dir (boost::filesystem::current_path());
    stringstream ss;
    ss << curr_dir.string() << "/" << getpid() << "/";
    string store_path = ss.str();

    agent_->oper_db()->instance_manager()->SetNamespaceStorePath(store_path.c_str());
    store_path +=  ("vrouter-" + vm_uuid + ":" + lb_uuid);
    boost::system::error_code error;
    if (!boost::filesystem::exists(store_path, error)) {
        boost::filesystem::create_directories(store_path, error);
        if (error) {
            LOG(ERROR, "Error : " << error.message() << "in creating directory");
        }
    }
    store_path  = loadbalancer_config_path();
    store_path += (lb_uuid + ".conf");
    if (!boost::filesystem::exists(store_path, error)) {
        std::ofstream fs(store_path.c_str());
        fs << "Test Config for " << lb_uuid;
        fs.close();
        if (error) {
            LOG(ERROR, "Error : " << error.message() << "in creating conf file");
        }
    }
    EXPECT_EQ(1, boost::filesystem::exists(store_path));

    agent_->oper_db()->instance_manager()->StaleTimeout();
    task_util::WaitForIdle();
    EXPECT_EQ(0, boost::filesystem::exists(store_path));

    boost::filesystem::remove_all(ss.str(), error);
    if (error) {
        LOG(ERROR, "Error : " << error.message() << "in removing directory");
    }
}
int main(int argc, char **argv) {
   GETUSERARGS();

   //Asio is disabled below to take control of event manager in the
   //tests
    client = TestInit(init_file, ksync_init, false, false, false, 30000,
            1000, false);
    usleep(100000);
    client->WaitForIdle();

    int ret = RUN_ALL_TESTS();
    TestShutdown();
    client->WaitForIdle();
    delete client;
    return ret;

}

max_stars_repo_name: jnpr-pranav/contrail-controller

max_issues_repo_name: jnpr-pranav/contrail-controller

max_forks_repo_name: jnpr-pranav/contrail-controller


text:
#include <algorithm>
#include <iostream>
#include <sstream>

#include <dlib/cmd_line_parser.h>
#include <dlib/image_io.h>
#include <dlib/gui_widgets.h>
#include <dlib/dir_nav.h>
#include <dlib/image_transforms.h>

int main(int argc, char** argv) try
{
    dlib::command_line_parser cmd_parser;
    cmd_parser.add_option("max-size", "max num of pixels per image", 1);
    cmd_parser.add_option("max-images", "maximum number of images", 1);
    cmd_parser.add_option("show", "show the resulting image");
    cmd_parser.set_group_name("Help Options");
    cmd_parser.add_option("h", "");
    cmd_parser.add_option("help", "display this message and exit");
    cmd_parser.parse(argc, argv);

    if (cmd_parser.number_of_arguments() == 0 || cmd_parser.option("h") || cmd_parser.option("help"))
    {
        std::cout << "\nUsage: tiler [options] directory\n\n";
        cmd_parser.print_options();
        return EXIT_SUCCESS;
    }

    const std::string& root = cmd_parser[0];
    const double max_size = dlib::get_option(cmd_parser, "max-size", std::numeric_limits<double>::max());
    const size_t max_images = dlib::get_option(cmd_parser, "max-images", std::numeric_limits<size_t>::max());
    auto files = dlib::get_files_in_directory_tree(root, dlib::match_endings(".jpg .JPG .jpeg .JPEG .png .PNG"));
    std::sort(files.begin(), files.end());
    std::cout << "Found " << files.size() << " images\n";
    auto num_images = std::min(max_images, files.size());
    files.erase(files.begin() + num_images, files.end());
    std::cout << "Generating tiled image with " << files.size() << " images\n";

    std::vector<dlib::matrix<dlib::rgb_pixel>> images;
    images.assign(files.size(), dlib::matrix<dlib::rgb_pixel>());
    dlib::parallel_for(0, files.size(), [&files, max_size, &images](size_t i)
    {
        const auto& file = files[i];
        dlib::matrix<dlib::rgb_pixel> image;
        dlib::load_image(image, file.full_name());
        if (const auto scaling_factor = std::sqrt(max_size / image.size()); scaling_factor < 1)
        {
            dlib::resize_image(scaling_factor, image);
        }
        images[i] = std::move(image);
    });

    dlib::matrix<dlib::rgb_pixel> tiled_image = dlib::tile_images(images);
    dlib::save_jpeg(tiled_image, "tiled_image.jpg");
    if (cmd_parser.option("show"))
    {
        dlib::image_window win(tiled_image, "tiled image");
        win.wait_until_closed();
    }
    return EXIT_SUCCESS;
}
catch (std::exception& e)
{
    std::cout << e.what() << std::endl;
    return EXIT_FAILURE;
}

max_stars_repo_name: arrufat/tiler

max_issues_repo_name: arrufat/tiler

max_forks_repo_name: arrufat/tiler


text:
/**
* \file Mapping.hpp
*
* \brief Functions for mapping from tensors to Eigen matrices
*
* \date   Jun 18, 2018
* \author Mathias Bøgh Stokholm
*/

#ifndef NEURAL_MAPPING_HPP
#define NEURAL_MAPPING_HPP

#include <Eigen/Core>

namespace neural {
    /**
     * @brief Maps a const tensor to an Eigen Matrix
     * @tparam Rows The number of rows in the input tensor
     * @tparam Cols The number of cols in the input tensor
     * @tparam TensorIn The type of the input tensor
     * @param input The input tensor
     * @return The tensor mapped to an Eigen Matrix
     */
    template <unsigned int Rows, unsigned int Cols, class TensorIn>
    Eigen::Map<const Eigen::Matrix<typename TensorIn::CoeffReturnType, Rows, Cols>>
    ConstTensorToMatrix(const TensorIn &input) {
        return Eigen::Map<const Eigen::Matrix<typename TensorIn::CoeffReturnType, Rows, Cols>>(input.data());
    }

    /**
     * @brief Maps a slice of a const tensor to a const Eigen Matrix (vector)
     * @tparam Size The number of elements to map (size of output vector)
     * @tparam Stride The size of the stride of the input tensor
     * @tparam TensorIn The type of the input tensor
     * @param input The input tensor
     * @param slice The index at which to slice the tensor
     * @return A slice of the tensor mapped to a const Eigen Matrix
     */
    template <unsigned int Size, unsigned int Stride, class TensorIn>
    Eigen::Map<const Eigen::Matrix<typename TensorIn::CoeffReturnType, Size, 1>, Eigen::Unaligned, Eigen::Stride<Size, Stride>>
    ConstTensorSliceToVector(const TensorIn &input, unsigned int slice) {
        assert(slice <= Stride);
        return Eigen::Map<const Eigen::Matrix<typename TensorIn::CoeffReturnType, Size, 1>, Eigen::Unaligned, Eigen::Stride<Size, Stride>>(input.data() + slice);
    }

    /**
     * @brief Maps a slice of a tensor to an Eigen Matrix (vector)
     * @tparam Size The number of elements to map (size of output vector)
     * @tparam Stride The size of the stride of the input tensor
     * @tparam TensorIn The type of the input tensor
     * @param input The input tensor
     * @param slice The index at which to slice the tensor
     * @return A slice of the tensor mapped to an Eigen Matrix
     */
    template <unsigned int Size, unsigned int Stride, class TensorIn>
    Eigen::Map<Eigen::Matrix<typename TensorIn::CoeffReturnType, Size, 1>, Eigen::Unaligned, Eigen::Stride<Size, Stride>>
    TensorSliceToVector(TensorIn &input, unsigned int slice) {
        assert(slice <= Stride);
        return Eigen::Map<Eigen::Matrix<typename TensorIn::CoeffReturnType, Size, 1>, Eigen::Unaligned, Eigen::Stride<Size, Stride>>(input.data() + slice);
    }
}

#endif //NEURAL_MAPPING_HPP

max_stars_repo_name: MathiasStokholm/neural

max_issues_repo_name: MathiasStokholm/neural

max_forks_repo_name: MathiasStokholm/neural


text:
#ifdef STAND_ALONE
#   define BOOST_TEST_MODULE DemoTests
#endif

#include <boost/test/unit_test.hpp>
#include "../src/shared/Bar.hpp"

BOOST_AUTO_TEST_SUITE(bar_suite)

    BOOST_AUTO_TEST_CASE(constructor_test)
    {
        Bar bar("fooey");

        BOOST_CHECK_EQUAL(bar.get(), "fooey");
    }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: albertchan/cmake-boost-demo

max_issues_repo_name: albertchan/cmake-boost-demo

max_forks_repo_name: albertchan/cmake-boost-demo


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

#include "../aoaoaott.hpp"

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE CONTAINER

#ifndef CONTAINER
#error "CONTAINER macro must be defined"
#endif

#include <boost/test/included/unit_test.hpp>
#include <cstring>

#define PASTER(x,y) x ## y
#define EVALUATOR(x,y) PASTER(x,y)
#define VECTOR_CONTAINER EVALUATOR(CONTAINER, Vector)
#define ARRAY_CONTAINER EVALUATOR(CONTAINER, Array)

using namespace aoaoaott;

template<typename R>
constexpr const char* bold_cast(const R& ref)
{
    return reinterpret_cast<const char*>(&ref);
}

BOOST_AUTO_TEST_CASE(principal_test)
{
    struct Structure
    {
        int val;
        int key;
        int dum;
    };
    static_assert(sizeof(Structure) != sizeof(int));

    ARRAY_CONTAINER<Structure, 20> storage;
    ptrdiff_t distance = bold_cast(storage[10]->*(&Structure::key)) - bold_cast(storage[0]->*(&Structure::key));

    // That is the only test dependent on container type
    if constexpr (std::is_same_v<ARRAY_CONTAINER<Structure, 20>, AoSArray<Structure, 20>>)
        BOOST_TEST( distance == 10 * sizeof(Structure) );
    else
        BOOST_TEST( distance == 10 * sizeof(int) );
}

struct A {
    int val;
    int key;
    int dum;
};

/*
static const constexpr ARRAY_CONTAINER<A, 11> array = {};
static const constexpr size_t distance = bold_cast(array[10].get<&A::key>()) - bold_cast(array[0].get<&A::key>());
static_assert(std::is_same_v<decltype(array), AoSArray<A, 11>>
                ? distance == 10 * sizeof(A)
                : distance == 10 * sizeof(int));
*/

BOOST_AUTO_TEST_CASE(initialize_and_rw)
{
    VECTOR_CONTAINER<A> storage( 10);
    storage[3]->*(&A::key) = 10;
    storage[3]->*(&A::val) = 3;
    storage[4]->*(&A::key) = 9;
    storage[4]->*(&A::val) = 6;

    BOOST_TEST( (storage[3]->*(&A::key)) == 10 );
    BOOST_TEST( (storage[3]->*(&A::val)) == 3 );
    BOOST_TEST( (storage[4]->*(&A::key)) == 9 );
    BOOST_TEST( (storage[4]->*(&A::val)) == 6 );
};

BOOST_AUTO_TEST_CASE(get__interface)
{
    VECTOR_CONTAINER<A> storage(10);
    storage[2].get<&A::val>() = 234;
    BOOST_TEST( storage[2].get<&A::val>() == 234 );
};

BOOST_AUTO_TEST_CASE(assign_structure)
{
    VECTOR_CONTAINER<A> storage( 10);
    const A x{3, 7, 11};
    storage[2] = x; // copy assignment
    storage[3] = A{10, 3, 8}; // move assignment

    BOOST_TEST( (storage[2]->*(&A::val)) == 3 );
    BOOST_TEST( (storage[2]->*(&A::key)) == 7 );
    BOOST_TEST( (storage[2]->*(&A::dum)) == 11 );
    BOOST_TEST( (storage[3]->*(&A::val)) == 10 );
    BOOST_TEST( (storage[3]->*(&A::key)) == 3 );
    BOOST_TEST( (storage[3]->*(&A::dum)) == 8 );
}

BOOST_AUTO_TEST_CASE(constant_functions)
{
    VECTOR_CONTAINER<A> storage( 10);
    storage[3]->*(&A::key) = 10;
    storage[3]->*(&A::val) = 3;

    const auto& const_ref = storage;
    BOOST_TEST( (const_ref[3]->*(&A::key)) == 10 );
    BOOST_TEST( (const_ref[3]->*(&A::val)) == 3 );
    BOOST_TEST( (const_ref[3].get<&A::val>()) == 3 );
}

struct WithArray {
    int size;
    std::array<char, 16> array;
};

static_assert(sizeof(WithArray) == sizeof(int) + 16);

BOOST_AUTO_TEST_CASE(structure_with_array)
{
    VECTOR_CONTAINER<WithArray> storage(10);
    std::memset(&(storage[3]->*(&WithArray::array)), 0x11, 16);
    BOOST_TEST( ((storage[3]->*(&WithArray::array))[8]) == 0x11);
}

BOOST_AUTO_TEST_CASE(assign_array)
{
    VECTOR_CONTAINER<WithArray> storage( 10);
    WithArray hw{ 16, {"Hello World!!!!"}};
    storage[6] = hw;

    BOOST_TEST( std::strcmp((storage[6]->*(&WithArray::array)).data(), "Hello World!!!!") == 0 );
}

struct DefaultInitializer
{
    int x = 9;
    float y = 0;
};

static_assert(!std::is_trivially_constructible_v<DefaultInitializer>);

BOOST_AUTO_TEST_CASE(default_initialization)
{
    VECTOR_CONTAINER<DefaultInitializer> storage( 10);
    BOOST_TEST( (storage[2]->*(&DefaultInitializer::x)) == 9 );
    BOOST_TEST( (storage[3]->*(&DefaultInitializer::x)) == 9 );
}

BOOST_AUTO_TEST_CASE(initialization_via_copies)
{
    DefaultInitializer example{ 234, 123};
    VECTOR_CONTAINER<DefaultInitializer> storage( 10, example);
    BOOST_TEST( (storage[2]->*(&DefaultInitializer::x)) == 234 );
    BOOST_TEST( (storage[2]->*(&DefaultInitializer::y)) == 123 );
    BOOST_TEST( (storage[3]->*(&DefaultInitializer::x)) == 234 );
}

BOOST_AUTO_TEST_CASE(resize_by_example)
{
    DefaultInitializer example{ 234, 123};
    VECTOR_CONTAINER<DefaultInitializer> storage(10);
    storage.resize(20, example);
    BOOST_TEST( (storage[5]->*(&DefaultInitializer::x)) == 9 );
    BOOST_TEST( (storage[15]->*(&DefaultInitializer::x)) == 234 );
}

BOOST_AUTO_TEST_CASE(structure_with_constant_member)
{
    struct ConstantMember
    {
        const int x = 9;
        int y = 0;
    };
    VECTOR_CONTAINER<ConstantMember> storage;
    storage.resize(20);
    BOOST_TEST( (storage[5]->*(&ConstantMember::x)) == 9 );
    BOOST_TEST( (storage[15]->*(&ConstantMember::x)) == 9 );
}

BOOST_AUTO_TEST_CASE(allow_substructure)
{
    struct WithA {
        A a;
        int val;
        int key;
        int dum;
    };
    VECTOR_CONTAINER<WithA> storage( 10);
    const A x{3, 7, 11};
    const WithA y{x, 4, 8, 12};
    storage[5] = y;

    BOOST_TEST(((storage[5]->*(&WithA::a)).dum) == 11 );
    BOOST_TEST((storage[5]->*(&WithA::dum)) == 12 );
}

struct HasMethod
{
    int alain;
    int delon;

    int drink_cologne(int cologne) const
    {
        return alain + delon + 3 * cologne;
    }

    void drink_double_bourbon()
    {
        std::swap(alain, delon);
    }
};

BOOST_AUTO_TEST_CASE(aggregate_and_run_method)
{
    VECTOR_CONTAINER<HasMethod> storage( 10);
    storage[4] = HasMethod{33, 44};
    auto val = storage[4].aggregate();
    val.drink_double_bourbon();

    BOOST_TEST( val.alain == 44 );
    BOOST_TEST( val.delon == 33 );
    BOOST_TEST( (storage[4]->*(&HasMethod::alain)) == 33 );
    BOOST_TEST( (storage[4]->*(&HasMethod::delon)) == 44 );
}

BOOST_AUTO_TEST_CASE(implicit_aggregate)
{
    VECTOR_CONTAINER<HasMethod> storage( 10);
    storage[4] = HasMethod{33, 44};
    HasMethod x(storage[4]);
    x.drink_double_bourbon();

    BOOST_TEST( x.alain == 44 );
    BOOST_TEST( x.delon == 33 );
}

BOOST_AUTO_TEST_CASE(const_iterator)
{
    VECTOR_CONTAINER<A> storage(10, { 11, 12, 13});
    size_t i = 0;
    for (const auto& entry : storage) {
        BOOST_TEST( (entry->*(&A::val)) == 11);
        BOOST_TEST( (entry->*(&A::key)) == 12);
        BOOST_TEST( (entry->*(&A::dum)) == 13);
        ++i;
    }
    BOOST_TEST(i == 10);
}

BOOST_AUTO_TEST_CASE(mutable_iterator)
{
    VECTOR_CONTAINER<A> storage(10);
    for (auto& entry : storage) {
        entry->*(&A::val) = 21;
        entry->*(&A::key) = 22;
        entry->*(&A::dum) = 23;
    }
    for (const auto& entry : storage) {
        BOOST_TEST( (entry->*(&A::val)) == 21);
        BOOST_TEST( (entry->*(&A::key)) == 22);
        BOOST_TEST( (entry->*(&A::dum)) == 23);
    }
}

BOOST_AUTO_TEST_CASE(iterator_arrow_operator)
{
    VECTOR_CONTAINER<A> storage(10, { 11, 12, 13});
    BOOST_TEST( storage.cbegin()->get<&A::val>() == 11 );
    BOOST_TEST( storage.begin()->get<&A::key>()  == 12 );
}

BOOST_AUTO_TEST_CASE(bidirectional_iterator)
{
    VECTOR_CONTAINER<A> storage(10, { 11, 12, 13});
    size_t i = 0;
    auto it = storage.cend();
    do {
        --it;
        BOOST_TEST( (*it->*(&A::val)) == 11);
        BOOST_TEST( (*it->*(&A::key)) == 12);
        BOOST_TEST( (*it->*(&A::dum)) == 13);
        ++i;
    } while (it != storage.cbegin());
    BOOST_TEST(i == 10);
}

BOOST_AUTO_TEST_CASE(random_access_iterator)
{
    VECTOR_CONTAINER<A> storage(90);
    BOOST_TEST((storage.end() - storage.begin()) == 90 );
    BOOST_TEST((storage.begin() <= storage.end()));
    auto it = std::next(storage.begin(), 60);
    BOOST_TEST((storage.end() - it) == 30 );
}

BOOST_AUTO_TEST_CASE(reverse_iterator)
{
    VECTOR_CONTAINER<A> storage(10);
    int value = 20;
    for (auto& entry : storage) {
        entry->*(&A::val) = ++value;
        entry->*(&A::key) = ++value;
        entry->*(&A::dum) = ++value;
    }
    size_t i = 0;
    for (auto it = storage.crbegin(); it != storage.crend(); ++it) {
        BOOST_TEST( it->get<&A::val>() == value - 3 * i - 2 );
        BOOST_TEST( it->get<&A::key>() == value - 3 * i - 1 );
        BOOST_TEST( it->get<&A::dum>() == value - 3 * i );
        ++i;
    }
}

BOOST_AUTO_TEST_CASE(const_method)
{
    const VECTOR_CONTAINER<HasMethod> storage( 10, HasMethod{33, 44});
    BOOST_TEST( storage[3].method<&HasMethod::drink_cologne>(1) == 80);
}

BOOST_AUTO_TEST_CASE(non_const_method)
{
    VECTOR_CONTAINER<HasMethod> storage( 10, HasMethod{33, 44});
    storage[3].method<&HasMethod::drink_double_bourbon>();

    BOOST_TEST( (storage[3]->*(&HasMethod::alain)) == 44 );
    BOOST_TEST( (storage[3]->*(&HasMethod::delon)) == 33 );
}

BOOST_AUTO_TEST_CASE(const_method_and_mutable_field)
{
    struct HasMutable {
        mutable int x;
        void update_x() const { ++x; }
    };

    const VECTOR_CONTAINER<HasMutable> storage( 10, HasMutable{109});
    storage[3].method<&HasMutable::update_x>();
    BOOST_TEST( (storage[3]->*(&HasMutable::x)) == 110 );
}

BOOST_AUTO_TEST_CASE(arrow_star_method)
{
    const VECTOR_CONTAINER<HasMethod> storage( 10, HasMethod{33, 44});
    BOOST_TEST( (storage[3]->*(&HasMethod::drink_cologne))(1) == 80);
}

BOOST_AUTO_TEST_CASE(arrow_star_non_const_method)
{
    VECTOR_CONTAINER<HasMethod> storage( 10, HasMethod{33, 44});
    (storage[3]->*(&HasMethod::drink_double_bourbon))();

    BOOST_TEST( (storage[3]->*(&HasMethod::alain)) == 44 );
    BOOST_TEST( (storage[3]->*(&HasMethod::delon)) == 33 );
}

BOOST_AUTO_TEST_CASE(initialize_array_and_r_w)
{
    ARRAY_CONTAINER<A, 10> storage;
    storage[3]->*(&A::key) = 10;
    storage[3]->*(&A::val) = 3;
    storage[4]->*(&A::key) = 9;
    storage[4]->*(&A::val) = 6;

    BOOST_TEST( (storage[3]->*(&A::key)) == 10 );
    BOOST_TEST( (storage[3]->*(&A::val)) == 3 );
    BOOST_TEST( (storage[4]->*(&A::key)) == 9 );
    BOOST_TEST( (storage[4]->*(&A::val)) == 6 );
}

BOOST_AUTO_TEST_CASE(array_get__interface)
{
    ARRAY_CONTAINER<A, 10> storage;
    storage[2].get<&A::val>() = 234;
    BOOST_TEST( storage[2].get<&A::val>() == 234 );
}

BOOST_AUTO_TEST_CASE(array_assign_structure)
{
    ARRAY_CONTAINER<A, 10> storage;
    const A x{3, 7, 11};
    storage[2] = x; // copy assignment
    storage[3] = A{10, 3, 8}; // move assignment

    BOOST_TEST( (storage[2]->*(&A::val)) == 3 );
    BOOST_TEST( (storage[2]->*(&A::key)) == 7 );
    BOOST_TEST( (storage[2]->*(&A::dum)) == 11 );
    BOOST_TEST( (storage[3]->*(&A::val)) == 10 );
    BOOST_TEST( (storage[3]->*(&A::key)) == 3 );
    BOOST_TEST( (storage[3]->*(&A::dum)) == 8 );
}

BOOST_AUTO_TEST_CASE(vector_methods)
{
    VECTOR_CONTAINER<A> storage;
    storage.push_back(A{3, 14, 15});
    BOOST_TEST( (storage[0]->*(&A::val)) == 3 );
    BOOST_TEST( !storage.empty() );
    BOOST_CHECK_THROW( storage.at(1000), std::out_of_range );
    BOOST_TEST( (storage.front()->*(&A::dum)) == 15);
    BOOST_TEST( (storage.back()->*(&A::dum)) == 15);
}

BOOST_AUTO_TEST_CASE(vector_assign)
{
    VECTOR_CONTAINER<A> storage(10, A{3, 14, 15});
    storage.assign(5, A{2, 7, 1828});
    BOOST_TEST( (storage[7]->*(&A::dum)) == 15 );
    BOOST_TEST( (storage[2]->*(&A::dum)) == 1828 );
}

BOOST_AUTO_TEST_CASE(vector_capacity)
{
    VECTOR_CONTAINER<A> storage(10);
    storage.reserve(200);
    BOOST_TEST( storage.capacity() >= 200 );
    BOOST_TEST( storage.size() == 10 );

    storage.shrink_to_fit();
    BOOST_TEST( storage.capacity() >= 10 );
}

BOOST_AUTO_TEST_CASE(array_fill)
{
    ARRAY_CONTAINER<A, 100> storage;
    storage.fill(A{2, 7, 1828});
    BOOST_TEST( (storage[93]->*(&A::dum)) == 1828 );
}

BOOST_AUTO_TEST_CASE(move_semantics)
{
    struct Point
    {
        int x = 0;
        int y = 0;
        std::unique_ptr<int> z;
    };

    ARRAY_CONTAINER<Point, 100> storage;
    storage[3] = Point{2, 4, std::make_unique<int>(10)};
    storage[4] = Point{2, 4, std::make_unique<int>(7)};

    BOOST_TEST( (storage[3]->*(&Point::x)) == 2 );
    BOOST_TEST( (storage[3]->*(&Point::y)) == 4 );
    BOOST_TEST( *(storage[3]->*(&Point::z)) == 10 );

    Point point = storage[4].aggregate_move();
    BOOST_TEST( *(point.z) == 7 );

    Point point2 = std::move(storage[3]);
    BOOST_TEST( *(point2.z) == 10 );
}

max_stars_repo_name: pavelkryukov/AoAoAoTT

max_issues_repo_name: pavelkryukov/AoAoAoTT

max_forks_repo_name: pavelkryukov/AoAoAoTT


text:
#ifndef OUTCOME_HPP
#define OUTCOME_HPP

#define BOOST_SYSTEM_NO_DEPRECATED
#include <boost/outcome.hpp>
namespace outcome {
template <class R>
using result = BOOST_OUTCOME_V2_NAMESPACE::std_result<R>;
template <class R>
using outcome = BOOST_OUTCOME_V2_NAMESPACE::std_outcome<R>;
using BOOST_OUTCOME_V2_NAMESPACE::success;
}  // namespace outcome

#endif  // OUTCOME_HPP

max_stars_repo_name: MGfoundation/mgcpp

max_issues_repo_name: MGfoundation/mgcpp

max_forks_repo_name: MGfoundation/mgcpp