text:
/**
 * \file Splice_Sites.cpp
 */

#include "Splice_Sites.hpp"
#include "Supporting_Methods.hpp"
#include "Global.hpp"

#include <string>
#include <vector>

#include <utility>
#include <ctype.h>
#include <iostream>

#include <boost/assign/std/vector.hpp>
#include <boost/algorithm/string/case_conv.hpp>

using namespace std;
using namespace boost::assign;
using namespace boost::algorithm;

pair<bool, string> check_sp_sites (const vector< pair <string, string> >& sp_sites, const string& sequence,
		unsigned start, unsigned end, bool strand_defined, string strand) {
	string don_site_scaff;
	string acc_site_scaff;
	unsigned sp_site_no = 0;
	unsigned length_don_site;
	unsigned length_acc_site;

	while ( (sp_site_no < sp_sites.size()) ) {
		length_don_site = sp_sites[sp_site_no].first.size();
		length_acc_site = sp_sites[sp_site_no].second.size();

		if ( ((start + length_don_site - 1) < end) && ((end - length_acc_site + 1) > start) ) {

			if (!strand_defined || strand == "+" ) {//possible plus strand or plus strand
				don_site_scaff = sequence.substr(start-1, length_don_site);
				acc_site_scaff = sequence.substr(end-length_acc_site, length_acc_site);

				to_lower(don_site_scaff); //to lower case, so unified format, donor and acceptor sites in lower case
				to_lower(acc_site_scaff);

				if ( (sp_sites[sp_site_no].first == don_site_scaff)
						&& (sp_sites[sp_site_no].second == acc_site_scaff) ) {
					return make_pair(true, "+");
				}
			}

			if (!strand_defined || strand == "-") {//possible minus strand or minus strand
				don_site_scaff = sp_site_conversion(sequence, end-1, end-length_don_site);
				acc_site_scaff = sp_site_conversion(sequence, start+length_acc_site-2, start-1);

				to_lower(don_site_scaff); //to lower case, so unified format, donor and acceptor sites in lower case
				to_lower(acc_site_scaff);

				if ( (sp_sites[sp_site_no].first == don_site_scaff)
						&& (sp_sites[sp_site_no].second == acc_site_scaff) ) {
					return make_pair(true, "-");
				}
			}
		}
		++sp_site_no;
	}

	return make_pair(false, strand);
}

string sp_site_conversion (const string& sequence, unsigned start, unsigned end) {
	string sp_site;

	for ( unsigned i = start; i >= end; i-- ) {
		char base = sequence[i];
		base = toupper(base);

		switch(base) {
			case 'A':
				sp_site += "T";
				break;
			case 'C':
				sp_site += "G";
				break;
			case 'G':
				sp_site += "C";
				break;
			case 'T':
				sp_site += "A";
				break;
			default: //Not specific Base, e.g. N,...
				sp_site += "N"; //in any case not an accepted splice site
		}
	}

	return sp_site;
}

vector< pair <string, string> > parse_sp_sites(string raw_sp_sites) {
	const string SEP_SP_SITES = "#";
	const string SEP_DON_ACC_SITE = "_";

	vector< pair<string, string> > sp_sites;

	unsigned all_pos = raw_sp_sites.find("all");
	if (all_pos != raw_sp_sites.npos) { //"all" found
		return sp_sites; //empty sp_sites returned, no filtering
	}

	//filtering, so splice sites must be parsed further
	vector<string> paired_sp_sites = tokenize(SEP_SP_SITES, raw_sp_sites);

	for (unsigned i = 0; i < paired_sp_sites.size(); i++) {
		if (!paired_sp_sites[i].empty()) {
			pair<string, string> seperated_sp_site;
			vector<string> don_acc_site = tokenize(SEP_DON_ACC_SITE, paired_sp_sites[i]);

			if (don_acc_site.size() == 2) { //only accepted when one donor and one acceptor site
				to_lower(don_acc_site[0]); //lower case, unified format
				to_lower(don_acc_site[1]);

				seperated_sp_site = make_pair(don_acc_site[0], don_acc_site[1]);
				sp_sites += seperated_sp_site;
			}
			//else Incomplete or unaccepted splice site. No donor or acceptor side (_AG, GT_, or no separator)
		}
	}

	return sp_sites;
}

max_stars_repo_name: sestaton/Augustus

max_issues_repo_name: sestaton/Augustus

max_forks_repo_name: sestaton/Augustus


text:
/***************************************************************************
 * Copyright 1998-2018 by authors (see AUTHORS.txt)                        *
 *                                                                         *
 *   This file is part of LuxCoreRender.                                   *
 *                                                                         *
 * 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 <vector>
#include <boost/foreach.hpp>
#include <boost/thread/mutex.hpp>

#include <embree2/rtcore.h>
#include <embree2/rtcore_builder.h>

#include "luxrays/core/bvh/bvhbuild.h"
#include "luxrays/utils/atomic.h"

using namespace std;

namespace luxrays {

//------------------------------------------------------------------------------
// Embree BVH node tree classes
//------------------------------------------------------------------------------

template<u_int CHILDREN_COUNT> class EmbreeBVHNode {
public:
	EmbreeBVHNode() { }
	virtual ~EmbreeBVHNode() { }
};

template<u_int CHILDREN_COUNT> class EmbreeBVHInnerNode : public EmbreeBVHNode<CHILDREN_COUNT> {
public:
	EmbreeBVHInnerNode() {
		for (u_int i = 0; i < CHILDREN_COUNT; ++i)
			children[i] = NULL;
	}
	virtual ~EmbreeBVHInnerNode() { }

	BBox bbox[CHILDREN_COUNT];
	EmbreeBVHNode<CHILDREN_COUNT> *children[CHILDREN_COUNT];
};

template<u_int CHILDREN_COUNT> class EmbreeBVHLeafNode : public EmbreeBVHNode<CHILDREN_COUNT> {
public:
	EmbreeBVHLeafNode(const size_t i) : index(i) { }
	virtual ~EmbreeBVHLeafNode() { }

	size_t index;
};

//------------------------------------------------------------------------------
// Embree builder data
//------------------------------------------------------------------------------

class EmbreeBuilderGlobalData {
public:
	EmbreeBuilderGlobalData();
	~EmbreeBuilderGlobalData();

	RTCDevice embreeDevice;
	RTCBVH embreeBVH;

	u_int nodeCounter;
};

// EmbreeBuilderGlobalData
EmbreeBuilderGlobalData::EmbreeBuilderGlobalData() {
	embreeDevice = rtcNewDevice(NULL);
	embreeBVH = rtcNewBVH(embreeDevice);

	nodeCounter = 0;
}

EmbreeBuilderGlobalData::~EmbreeBuilderGlobalData() {
	rtcDeleteBVH(embreeBVH);
	rtcDeleteDevice(embreeDevice);
}

//------------------------------------------------------------------------------
// BuildEmbreeBVHArray
//------------------------------------------------------------------------------

static inline void CopyBBox(const float *src, float *dst) {
	*dst++ = *src++;
	*dst++ = *src++;
	*dst++ = *src++;

	*dst++ = *src++;
	*dst++ = *src++;
	*dst = *src;
}

template<u_int CHILDREN_COUNT> static u_int BuildEmbreeBVHArray(const deque<const Mesh *> *meshes,
		const EmbreeBVHNode<CHILDREN_COUNT> *node, vector<BVHTreeNode *> &leafList,
		u_int offset, luxrays::ocl::BVHArrayNode *bvhArrayTree) {
	if (node) {
		luxrays::ocl::BVHArrayNode *arrayNode = &bvhArrayTree[offset];

		const EmbreeBVHInnerNode<CHILDREN_COUNT> *innerNode = dynamic_cast<const EmbreeBVHInnerNode<CHILDREN_COUNT> *>(node);

		if (innerNode) {
			// It is an inner node

			++offset;

			BBox bbox;
			for (u_int i = 0; i < CHILDREN_COUNT; ++i) {
				if (innerNode->children[i]) {
					// Add the child tree to the array
					const u_int childIndex = offset;
					offset = BuildEmbreeBVHArray<CHILDREN_COUNT>(meshes, innerNode->children[i], leafList, childIndex, bvhArrayTree);
					if (dynamic_cast<const EmbreeBVHInnerNode<CHILDREN_COUNT> *>(innerNode->children[i])) {
						// If the child was an inner node, set the skip index
						bvhArrayTree[childIndex].nodeData = offset;
					}

					bbox = Union(bbox, innerNode->bbox[i]);
				}
			}

			CopyBBox(&bbox.pMin.x, &arrayNode->bvhNode.bboxMin[0]);
		} else {
			// Must be a leaf
			const EmbreeBVHLeafNode<CHILDREN_COUNT> *leaf = (const EmbreeBVHLeafNode<CHILDREN_COUNT> *)node;
			const BVHTreeNode *leafTree = leafList[leaf->index];

			if (meshes) {
				// It is a BVH of triangles
				const Triangle *triangles = (*meshes)[leafTree->triangleLeaf.meshIndex]->GetTriangles();
				const Triangle *triangle = &triangles[leafTree->triangleLeaf.triangleIndex];
				arrayNode->triangleLeaf.v[0] = triangle->v[0];
				arrayNode->triangleLeaf.v[1] = triangle->v[1];
				arrayNode->triangleLeaf.v[2] = triangle->v[2];
				arrayNode->triangleLeaf.meshIndex = leafTree->triangleLeaf.meshIndex;
				arrayNode->triangleLeaf.triangleIndex = leafTree->triangleLeaf.triangleIndex;
			} else {
				// It is a BVH of BVHs (i.e. MBVH)
				arrayNode->bvhLeaf.leafIndex = leafTree->bvhLeaf.leafIndex;
				arrayNode->bvhLeaf.transformIndex = leafTree->bvhLeaf.transformIndex;
				arrayNode->bvhLeaf.motionIndex = leafTree->bvhLeaf.motionIndex;
				arrayNode->bvhLeaf.meshOffsetIndex = leafTree->bvhLeaf.meshOffsetIndex;
			}

			++offset;
			// Mark as a leaf
			arrayNode->nodeData = offset | 0x80000000u;
		}
	}

	return offset;
}

//------------------------------------------------------------------------------
// BuildEmbreeBVH
//------------------------------------------------------------------------------

template<u_int CHILDREN_COUNT> static void *CreateNodeFunc(RTCThreadLocalAllocator allocator,
		size_t numChildren, void *userPtr) {
	assert (numChildren <= CHILDREN_COUNT);

	EmbreeBuilderGlobalData *gd = (EmbreeBuilderGlobalData *)userPtr;
	AtomicInc(&gd->nodeCounter);

	return new (rtcThreadLocalAlloc(allocator, sizeof(EmbreeBVHInnerNode<CHILDREN_COUNT>), 16)) EmbreeBVHInnerNode<CHILDREN_COUNT>();
}

template<u_int CHILDREN_COUNT> static void *CreateLeafFunc(RTCThreadLocalAllocator allocator,
		const RTCBuildPrimitive *prims, size_t numPrims, void *userPtr) {
	// RTCBuildSettings::maxLeafSize is set to 1
	assert (numPrims == 1);

	EmbreeBuilderGlobalData *gd = (EmbreeBuilderGlobalData *)userPtr;
	AtomicInc(&gd->nodeCounter);

	return new (rtcThreadLocalAlloc(allocator, sizeof(EmbreeBVHLeafNode<CHILDREN_COUNT>), 16)) EmbreeBVHLeafNode<CHILDREN_COUNT>(prims[0].primID);
}

template<u_int CHILDREN_COUNT> static void NodeSetChildrensPtrFunc(void *nodePtr, void **children, size_t numChildren, void *userPtr) {
	assert (numChildren <= CHILDREN_COUNT);

	EmbreeBVHInnerNode<CHILDREN_COUNT> *node = (EmbreeBVHInnerNode<CHILDREN_COUNT> *)nodePtr;

	for (u_int i = 0; i < numChildren; ++i)
		node->children[i] = (EmbreeBVHNode<CHILDREN_COUNT> *)children[i];
}

template<u_int CHILDREN_COUNT> static void NodeSetChildrensBBoxFunc(void *nodePtr,
		const RTCBounds **bounds, size_t numChildren, void *userPtr) {
	EmbreeBVHInnerNode<CHILDREN_COUNT> *node = (EmbreeBVHInnerNode<CHILDREN_COUNT> *)nodePtr;

	for (u_int i = 0; i < numChildren; ++i) {
		node->bbox[i].pMin.x = bounds[i]->lower_x;
		node->bbox[i].pMin.y = bounds[i]->lower_y;
		node->bbox[i].pMin.z = bounds[i]->lower_z;

		node->bbox[i].pMax.x = bounds[i]->upper_x;
		node->bbox[i].pMax.y = bounds[i]->upper_y;
		node->bbox[i].pMax.z = bounds[i]->upper_z;
	}
}

//------------------------------------------------------------------------------
// BuildEmbreeBVH
//------------------------------------------------------------------------------

template<u_int CHILDREN_COUNT> static luxrays::ocl::BVHArrayNode *BuildEmbreeBVH(
		RTCBuildQuality quality, u_int *nNodes, const std::deque<const Mesh *> *meshes,
		std::vector<BVHTreeNode *> &leafList) {
	//const double t1 = WallClockTime();

	// Initialize RTCPrimRef vector
	vector<RTCBuildPrimitive> prims(leafList.size());
	for (
			// Visual C++ 2013 supports only OpenMP 2.5
#if _OPENMP >= 200805
			unsigned
#endif
			int i = 0; i < prims.size(); ++i) {
		RTCBuildPrimitive &prim = prims[i];
		BVHTreeNode *node = leafList[i];

		prim.lower_x = node->bbox.pMin.x;
		prim.lower_y = node->bbox.pMin.y;
		prim.lower_z = node->bbox.pMin.z;
		prim.geomID = 0;

		prim.upper_x = node->bbox.pMax.x;
		prim.upper_y = node->bbox.pMax.y;
		prim.upper_z = node->bbox.pMax.z;
		prim.primID = i;
	}

	//const double t2 = WallClockTime();
	//cout << "BuildEmbreeBVH preprocessing time: " << int((t2 - t1) * 1000) << "ms\n";

	RTCBuildSettings config = rtcDefaultBuildSettings();
	config.quality = quality;
	config.maxBranchingFactor = CHILDREN_COUNT;
	config.maxLeafSize = 1;

	EmbreeBuilderGlobalData *globalData = new EmbreeBuilderGlobalData();
	EmbreeBVHNode<CHILDREN_COUNT> *root = (EmbreeBVHNode<CHILDREN_COUNT> *)rtcBuildBVH(globalData->embreeBVH,
			config,
			&prims[0], prims.size(),
			&CreateNodeFunc<CHILDREN_COUNT>, &NodeSetChildrensPtrFunc<CHILDREN_COUNT>, &NodeSetChildrensBBoxFunc<CHILDREN_COUNT>,
			&CreateLeafFunc<CHILDREN_COUNT>, NULL, NULL,
			globalData);

	*nNodes = globalData->nodeCounter;

	//const double t3 = WallClockTime();
	//cout << "BuildEmbreeBVH rtcBVHBuilderBinnedSAH time: " << int((t3 - t2) * 1000) << "ms\n";

	luxrays::ocl::BVHArrayNode *bvhArrayTree = new luxrays::ocl::BVHArrayNode[*nNodes];
	bvhArrayTree[0].nodeData = BuildEmbreeBVHArray<CHILDREN_COUNT>(meshes, root, leafList, 0, bvhArrayTree);
	// If root was a leaf, mark the node
	if (dynamic_cast<const EmbreeBVHLeafNode<CHILDREN_COUNT> *>(root))
		bvhArrayTree[0].nodeData |= 0x80000000u;

	//const double t4 = WallClockTime();
	//cout << "BuildEmbreeBVH BuildEmbreeBVHArray time: " << int((t4 - t3) * 1000) << "ms\n";

	delete globalData;

	return bvhArrayTree;
}

//------------------------------------------------------------------------------
// BuildEmbreeBVHBinnedSAH
//------------------------------------------------------------------------------

luxrays::ocl::BVHArrayNode *BuildEmbreeBVHBinnedSAH(const BVHParams &params,
		u_int *nNodes, const std::deque<const Mesh *> *meshes,
		std::vector<BVHTreeNode *> &leafList) {
	// Performance analysis.
	//
	// Version #1:
	//  BuildEmbreeBVH rtcNewDevice time: 0ms
	//  BuildEmbreeBVH preprocessing time: 266ms
	//  BuildEmbreeBVH rtcBVHBuilderBinnedSAH time: 10060ms
	//  BuildEmbreeBVH TransformEmbreeBVH time: 4061ms
	//  BuildEmbreeBVH FreeEmbreeBVHTree time: 1739ms
	//  BuildEmbreeBVH rtcDeleteDevice time: 0ms
	//  [LuxRays][20.330] BVH build hierarchy time: 16823ms
	// Version #2 (using rtcNewAllocator()):
	//  BuildEmbreeBVH rtcNewDevice time: 0ms
	//  BuildEmbreeBVH preprocessing time: 217ms
	//  BuildEmbreeBVH rtcBVHBuilderBinnedSAH time: 2761ms
	//  BuildEmbreeBVH TransformEmbreeBVH time: 3254ms
	//  BuildEmbreeBVH rtcDeleteAllocator time: 4ms
	//  BuildEmbreeBVH rtcDeleteDevice time: 0ms
	//  [LuxRays][9.712] BVH build hierarchy time: 6752ms
	// Version #3 (using BuildEmbreeBVHArray()):
	//  BuildEmbreeBVH rtcNewDevice time: 0ms
	//  BuildEmbreeBVH preprocessing time: 219ms
	//  BuildEmbreeBVH rtcBVHBuilderBinnedSAH time: 2741ms
	//  BuildEmbreeBVH CountEmbreeBVHNodes time: 1017ms
	//  BuildEmbreeBVH BuildEmbreeBVHArray time: 2111ms
	//  BuildEmbreeBVH rtcDeleteAllocator time: 5ms
	//  BuildEmbreeBVH rtcDeleteDevice time: 0ms
	//  [LuxRays][9.025] BVH build hierarchy time: 6096ms
	// Version #4 (removed the need of CountEmbreeBVHNodes()):
	//  BuildEmbreeBVH rtcNewDevice time: 0ms
	//  BuildEmbreeBVH preprocessing time: 214ms
	//  BuildEmbreeBVH rtcBVHBuilderBinnedSAH time: 2828ms
	//  BuildEmbreeBVH BuildEmbreeBVHArray time: 2134ms
	//  BuildEmbreeBVH rtcDeleteDevice time: 5ms
	//  [LuxRays][8.229] BVH build hierarchy time: 5183ms

	luxrays::ocl::BVHArrayNode *bvhArrayTree;

	if (params.treeType == 2)
		bvhArrayTree = BuildEmbreeBVH<2>(RTC_BUILD_QUALITY_NORMAL, nNodes, meshes, leafList);
	else if (params.treeType == 4)
		bvhArrayTree = BuildEmbreeBVH<4>(RTC_BUILD_QUALITY_NORMAL, nNodes, meshes, leafList);
	else if (params.treeType == 8)
		bvhArrayTree = BuildEmbreeBVH<8>(RTC_BUILD_QUALITY_NORMAL, nNodes, meshes, leafList);
	else
		throw runtime_error("Unsupported tree type in BuildEmbreeBVHBinnedSAH(): " + ToString(params.treeType));

	return bvhArrayTree;
}

//------------------------------------------------------------------------------
// BuildEmbreeBVHMorton
//------------------------------------------------------------------------------

luxrays::ocl::BVHArrayNode *BuildEmbreeBVHMorton(const BVHParams &params,
		u_int *nNodes, const std::deque<const Mesh *> *meshes,
		std::vector<BVHTreeNode *> &leafList) {
	luxrays::ocl::BVHArrayNode *bvhArrayTree;

	if (params.treeType == 2)
		bvhArrayTree = BuildEmbreeBVH<2>(RTC_BUILD_QUALITY_LOW, nNodes, meshes, leafList);
	else if (params.treeType == 4)
		bvhArrayTree = BuildEmbreeBVH<4>(RTC_BUILD_QUALITY_LOW, nNodes, meshes, leafList);
	else if (params.treeType == 8)
		bvhArrayTree = BuildEmbreeBVH<8>(RTC_BUILD_QUALITY_LOW, nNodes, meshes, leafList);
	else
		throw runtime_error("Unsupported tree type in BuildEmbreeBVHMorton(): " + ToString(params.treeType));

	return bvhArrayTree;
}

}

ext: cpp

max_stars_repo_name: aedancullen/LuxCore

max_issues_repo_name: aedancullen/LuxCore

max_forks_repo_name: aedancullen/LuxCore


text:
//
//  fiber_object.hpp
//  fibio
//
//  Created by Chen Xu on 14-3-4.
//  Copyright (c) 2014 0d0a.com. All rights reserved.
//

#ifndef fibio_fiber_object_hpp
#define fibio_fiber_object_hpp

#include <memory>
#include <chrono>
#include <deque>
#include <atomic>
#include <map>
#include <exception>
#include <boost/assert.hpp>
#include <boost/asio/basic_waitable_timer.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/strand.hpp>
#include <boost/system/error_code.hpp>
#include <boost/coroutine2/coroutine.hpp>
#include <fibio/fibers/exceptions.hpp>
#include <fibio/fibers/detail/fiber_base.hpp>
#include <fibio/fibers/detail/fiber_data.hpp>
#include <fibio/fibers/detail/spinlock.hpp>

#if defined(__APPLE_CC__) && (__apple_build_version__<8000000)
// Clang on OS X doesn't support thread_local until Xcode 8.0
#   define THREAD_LOCAL __thread
#else
#   define THREAD_LOCAL thread_local
#endif

#if defined(DEBUG) && !defined(NDEBUG)
#define CHECK_CALLER(f)                                                                            \
    do {                                                                                \
        if (!f->caller_) assert(false);                                                            \
    } while (0)
#else
#define CHECK_CALLER(f)
#endif

#if defined(DEBUG) && !defined(NDEBUG)
#define CHECK_CURRENT_FIBER assert(::fibio::fibers::detail::fiber_object::current_fiber_)
#else
#define CHECK_CURRENT_FIBER
#endif

namespace fibio {
namespace fibers {
namespace detail {

typedef boost::asio::basic_waitable_timer<std::chrono::steady_clock> timer_t;

struct scheduler_object;
typedef std::shared_ptr<scheduler_object> scheduler_ptr_t;

struct fiber_object;
typedef std::shared_ptr<fiber_object> fiber_ptr_t;

struct fss_cleanup_function;
typedef const void* fss_key_t;
typedef std::pair<std::shared_ptr<fss_cleanup_function>, void*> fss_value_t;

typedef std::map<fss_key_t, fss_value_t> fss_map_t;

struct fiber_object : std::enable_shared_from_this<fiber_object>, fiber_base
{
    enum state_t
    {
        READY,
        RUNNING,
        BLOCKED,
        STOPPED,
    };

    typedef std::deque<std::function<void()>> cleanup_queue_t;
    typedef boost::coroutines2::coroutine<state_t>::pull_type runner_t;
    typedef boost::coroutines2::coroutine<state_t>::push_type caller_t;
    typedef std::shared_ptr<boost::asio::strand> strand_ptr_t;

    fiber_object(scheduler_ptr_t sched, fiber_data_base* entry, size_t stack_size);

    fiber_object(scheduler_ptr_t sched,
                 strand_ptr_t strand,
                 fiber_data_base* entry,
                 size_t stack_size);

    ~fiber_object();

    void set_name(const std::string& s);

    std::string get_name();

    void raw_set_state(state_t s) { state_ = s; }

    void set_state(state_t s)
    {
        if (caller_) {
            // We're in fiber context, switch to scheduler context to make state take effect
            (*caller_)(s);
        } else {
            // We're in scheduler context
            state_ = s;
        }
    }

    virtual void pause() override;

    virtual void activate() override;

    virtual void resume() override;

    virtual boost::asio::strand& get_fiber_strand() override;

    // Following functions can only be called inside coroutine
    void yield(fiber_ptr_t hint = fiber_ptr_t());

    void join(fiber_ptr_t f);

    void join_and_rethrow(fiber_ptr_t f);

    void sleep_rel(duration_t d);

    // Implementations
    void runner_wrapper(caller_t& c);

    void one_step();

    void detach();

    void add_cleanup_function(std::function<void()>&& f);

    scheduler_ptr_t get_scheduler() override { return sched_; }

    static fiber_object*& get_current_fiber_object()
    {
        static THREAD_LOCAL fiber_object* current_fiber_ = 0;
        return current_fiber_;
    }

    scheduler_ptr_t sched_;
    strand_ptr_t fiber_strand_;
    mutable spinlock mtx_;
    std::atomic<state_t> state_;
    std::unique_ptr<fiber_data_base> entry_;
    runner_t runner_;
    caller_t* caller_;
    cleanup_queue_t cleanup_queue_;
    cleanup_queue_t join_queue_;
    fss_map_t fss_;
    fiber_ptr_t this_ref_;
    std::string name_;
    std::exception_ptr uncaught_exception_;

    // Interruption support
    void interrupt();

    int interrupt_disable_level_ = 0;
    bool interrupt_requested_ = false;
};

template <typename Lockable>
struct relock_guard
{
    inline relock_guard(Lockable& mtx) : mtx_(mtx) { mtx_.unlock(); }

    inline ~relock_guard() { mtx_.lock(); }

    Lockable& mtx_;
};

} // End of namespace detail

inline detail::fiber_object* current_fiber() noexcept
{
    return detail::fiber_object::get_current_fiber_object();
}

inline detail::fiber_ptr_t current_fiber_ptr()
{
    CHECK_CURRENT_FIBER;
    return current_fiber()->shared_from_this();
}

} // End of namespace fibers
} // End of namespace fibio

#endif

ext: hpp

max_stars_repo_name: mind-owner/fibio

max_issues_repo_name: learnerzhang/fibio

max_forks_repo_name: learnerzhang/fibio


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2013-2021 Regents of the University of California.
 *
 * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
 *
 * ndn-cxx library is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * ndn-cxx library 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 Lesser General Public License for more details.
 *
 * You should have received copies of the GNU General Public License and GNU Lesser
 * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
 *
 * @author Davide Pesavento <davide.pesavento@lip6.fr>
 */

#ifndef NDN_CXX_NET_NETLINK_MESSAGE_HPP
#define NDN_CXX_NET_NETLINK_MESSAGE_HPP

#include "ndn-cxx/detail/common.hpp"
#include "ndn-cxx/net/ethernet.hpp"
#include "ndn-cxx/util/optional.hpp"

#ifndef NDN_CXX_HAVE_NETLINK
#error "This file should not be included ..."
#endif

#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <string.h>

#include <cstring>
#include <map>

#include <boost/asio/ip/address.hpp>

namespace ndn {
namespace net {

template<typename T>
constexpr size_t
getAttributeLength(const T* attr);

template<>
constexpr size_t
getAttributeLength(const nlattr* attr)
{
  return attr->nla_len;
}

template<>
constexpr size_t
getAttributeLength(const rtattr* attr)
{
  return attr->rta_len;
}

template<typename T>
constexpr size_t
getAttributeLengthAligned(const T* attr);

template<>
constexpr size_t
getAttributeLengthAligned(const nlattr* attr)
{
  return NLA_ALIGN(attr->nla_len);
}

template<>
constexpr size_t
getAttributeLengthAligned(const rtattr* attr)
{
  return RTA_ALIGN(attr->rta_len);
}

template<typename T>
constexpr uint16_t
getAttributeType(const T* attr);

template<>
constexpr uint16_t
getAttributeType(const nlattr* attr)
{
  return attr->nla_type & NLA_TYPE_MASK;
}

template<>
constexpr uint16_t
getAttributeType(const rtattr* attr)
{
  return attr->rta_type;
}

template<typename T>
const uint8_t*
getAttributeValue(const T* attr);

template<>
inline const uint8_t*
getAttributeValue(const nlattr* attr)
{
  return reinterpret_cast<const uint8_t*>(attr) + NLA_HDRLEN;
}

template<>
inline const uint8_t*
getAttributeValue(const rtattr* attr)
{
  return reinterpret_cast<const uint8_t*>(RTA_DATA(const_cast<rtattr*>(attr)));
}

template<typename T>
constexpr size_t
getAttributeValueLength(const T* attr);

template<>
constexpr size_t
getAttributeValueLength(const nlattr* attr)
{
  return attr->nla_len - NLA_HDRLEN;
}

template<>
constexpr size_t
getAttributeValueLength(const rtattr* attr)
{
  return RTA_PAYLOAD(attr);
}

template<typename T>
class NetlinkMessageAttributes;

class NetlinkMessage
{
public:
  explicit
  NetlinkMessage(const uint8_t* buf, size_t buflen) noexcept
    : m_msg(reinterpret_cast<const nlmsghdr*>(buf))
    , m_length(buflen)
  {
    BOOST_ASSERT(buf != nullptr);
  }

  const nlmsghdr&
  operator*() const noexcept
  {
    return *m_msg;
  }

  const nlmsghdr*
  operator->() const noexcept
  {
    return m_msg;
  }

  bool
  isValid() const noexcept
  {
    return NLMSG_OK(m_msg, m_length);
  }

  NetlinkMessage
  getNext() const noexcept
  {
    BOOST_ASSERT(isValid());

    // mimic NLMSG_NEXT
    auto thisLen = NLMSG_ALIGN(m_msg->nlmsg_len);
    return NetlinkMessage{reinterpret_cast<const uint8_t*>(m_msg) + thisLen, m_length - thisLen};
  }

  template<typename T>
  const T*
  getPayload() const noexcept
  {
    BOOST_ASSERT(isValid());

    if (m_msg->nlmsg_len < NLMSG_LENGTH(sizeof(T)))
      return nullptr;

    return reinterpret_cast<const T*>(NLMSG_DATA(const_cast<nlmsghdr*>(m_msg)));
  }

  template<typename AttributeT, typename PayloadT>
  NetlinkMessageAttributes<AttributeT>
  getAttributes(const PayloadT* p) const noexcept
  {
    BOOST_ASSERT(isValid());

    auto begin = reinterpret_cast<const uint8_t*>(p) + NLMSG_ALIGN(sizeof(PayloadT));
    auto length = NLMSG_PAYLOAD(m_msg, sizeof(PayloadT));
    return NetlinkMessageAttributes<AttributeT>{reinterpret_cast<const AttributeT*>(begin), length};
  }

private:
  const nlmsghdr* m_msg;
  size_t m_length;
};

template<typename T>
class NetlinkMessageAttributes
{
  // empty type used to implement tag dispatching in getAttributeByType()
  template<typename U>
  struct AttrValueTypeTag {};

public:
  explicit
  NetlinkMessageAttributes(const T* begin, size_t length) noexcept
  {
    for (; isAttrValid(begin, length); begin = getNextAttr(begin, length)) {
      m_attrs[getAttributeType(begin)] = begin;
    }
  }

  size_t
  size() const noexcept
  {
    return m_attrs.size();
  }

  template<typename U>
  optional<U>
  getAttributeByType(uint16_t attrType) const
  {
    auto it = m_attrs.find(attrType);
    if (it == m_attrs.end())
      return nullopt;

    return convertAttrValue(getAttributeValue(it->second),
                            getAttributeValueLength(it->second),
                            AttrValueTypeTag<U>{});
  }

private:
  static bool
  isAttrValid(const T* attr, size_t nBytesRemaining) noexcept
  {
    return attr != nullptr &&
           nBytesRemaining >= sizeof(T) &&
           getAttributeLength(attr) >= sizeof(T) &&
           getAttributeLength(attr) <= nBytesRemaining;
  }

  static const T*
  getNextAttr(const T* attr, size_t& nBytesRemaining) noexcept
  {
    auto len = getAttributeLengthAligned(attr);
    if (len > nBytesRemaining) // prevent integer underflow
      return nullptr;

    nBytesRemaining -= len;
    return reinterpret_cast<const T*>(reinterpret_cast<const uint8_t*>(attr) + len);
  }

  template<typename Integral>
  static std::enable_if_t<std::is_integral<Integral>::value, optional<Integral>>
  convertAttrValue(const uint8_t* val, size_t len, AttrValueTypeTag<Integral>)
  {
    if (len < sizeof(Integral))
      return nullopt;

    Integral i;
    std::memcpy(&i, val, sizeof(Integral));
    return i;
  }

  static optional<std::string>
  convertAttrValue(const uint8_t* val, size_t len, AttrValueTypeTag<std::string>)
  {
    auto str = reinterpret_cast<const char*>(val);
    if (::strnlen(str, len) >= len)
      return nullopt;

    return std::string(str);
  }

  static optional<ethernet::Address>
  convertAttrValue(const uint8_t* val, size_t len, AttrValueTypeTag<ethernet::Address>)
  {
    if (len < ethernet::ADDR_LEN)
      return nullopt;

    return ethernet::Address(val);
  }

  template<typename IpAddress>
  static std::enable_if_t<std::is_same<IpAddress, boost::asio::ip::address_v4>::value ||
                          std::is_same<IpAddress, boost::asio::ip::address_v6>::value,
                          optional<IpAddress>>
  convertAttrValue(const uint8_t* val, size_t len, AttrValueTypeTag<IpAddress>)
  {
    typename IpAddress::bytes_type bytes;
    if (len < bytes.size())
      return nullopt;

    std::copy_n(val, bytes.size(), bytes.begin());
    return IpAddress(bytes);
  }

private:
  std::map<uint16_t, const T*> m_attrs;
};

} // namespace net
} // namespace ndn

#endif // NDN_CXX_NET_NETLINK_MESSAGE_HPP

max_stars_repo_name: Pesa/ndn-cxx

max_issues_repo_name: Pesa/ndn-cxx

max_forks_repo_name: Pesa/ndn-cxx


text:
#include <boost_python_exception/traceback.hpp>

#include <boost/test/unit_test.hpp>

#include <sstream>

namespace bpe = boost_python_exception;

BOOST_AUTO_TEST_SUITE(traceback)

BOOST_AUTO_TEST_CASE(stream_inserter)
{
    bpe::traceback traceback;
    bpe::traceback_step const step_1 = {42, "file_1", "source_1"};
    bpe::traceback_step const step_2 = {23, "file_2", "source_2"};
    traceback.push_back(step_1);
    traceback.push_back(step_2);

    std::ostringstream expected;
    expected << step_1 << "\n" << step_2 << "\n";

    std::ostringstream actual;
    actual << traceback;
    BOOST_CHECK_EQUAL(expected.str(), actual.str());
}

BOOST_AUTO_TEST_SUITE_END()


text:
/*
    This file is part of FISCO-BCOS.

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

    FISCO-BCOS 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 FISCO-BCOS.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file SystemConfigPrecompiled.cpp
 *  @author chaychen
 *  @date 20181211
 */
#include "SystemConfigPrecompiled.h"

#include "libprecompiled/EntriesPrecompiled.h"
#include "libprecompiled/TableFactoryPrecompiled.h"
#include <libethcore/ABI.h>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

using namespace dev;
using namespace dev::blockverifier;
using namespace dev::storage;
using namespace dev::precompiled;

const char* const SYSCONFIG_METHOD_SET_STR = "setValueByKey(string,string)";

SystemConfigPrecompiled::SystemConfigPrecompiled()
{
    name2Selector[SYSCONFIG_METHOD_SET_STR] = getFuncSelector(SYSCONFIG_METHOD_SET_STR);
}

PrecompiledExecResult::Ptr SystemConfigPrecompiled::call(
    ExecutiveContext::Ptr context, bytesConstRef param, Address const& origin, Address const&)
{
    // parse function name
    uint32_t func = getParamFunc(param);
    bytesConstRef data = getParamData(param);

    dev::eth::ContractABI abi;
    auto callResult = m_precompiledExecResultFactory->createPrecompiledResult();
    int count = 0;
    int result = 0;
    if (func == name2Selector[SYSCONFIG_METHOD_SET_STR])
    {
        // setValueByKey(string,string)
        std::string configKey, configValue;
        abi.abiOut(data, configKey, configValue);
        // Uniform lowercase configKey
        boost::to_lower(configKey);
        PRECOMPILED_LOG(DEBUG) << LOG_BADGE("SystemConfigPrecompiled")
                               << LOG_DESC("setValueByKey func") << LOG_KV("configKey", configKey)
                               << LOG_KV("configValue", configValue);

        if (!checkValueValid(configKey, configValue))
        {
            PRECOMPILED_LOG(DEBUG)
                << LOG_BADGE("SystemConfigPrecompiled") << LOG_DESC("set invalid value")
                << LOG_KV("configKey", configKey) << LOG_KV("configValue", configValue);
            getErrorCodeOut(callResult->mutableExecResult(), CODE_INVALID_CONFIGURATION_VALUES);
            return callResult;
        }

        storage::Table::Ptr table = openTable(context, SYS_CONFIG);

        auto condition = table->newCondition();
        auto entries = table->select(configKey, condition);
        auto entry = table->newEntry();
        entry->setField(SYSTEM_CONFIG_KEY, configKey);
        entry->setField(SYSTEM_CONFIG_VALUE, configValue);
        entry->setField(SYSTEM_CONFIG_ENABLENUM,
            boost::lexical_cast<std::string>(context->blockInfo().number + 1));

        if (entries->size() == 0u)
        {
            count = table->insert(configKey, entry, std::make_shared<AccessOptions>(origin));
            if (count == storage::CODE_NO_AUTHORIZED)
            {
                PRECOMPILED_LOG(DEBUG)
                    << LOG_BADGE("SystemConfigPrecompiled") << LOG_DESC("permission denied");
                result = storage::CODE_NO_AUTHORIZED;
            }
            else
            {
                PRECOMPILED_LOG(DEBUG) << LOG_BADGE("SystemConfigPrecompiled")
                                       << LOG_DESC("setValueByKey successfully");
                result = count;
            }
        }
        else
        {
            count =
                table->update(configKey, entry, condition, std::make_shared<AccessOptions>(origin));
            if (count == storage::CODE_NO_AUTHORIZED)
            {
                PRECOMPILED_LOG(DEBUG)
                    << LOG_BADGE("SystemConfigPrecompiled") << LOG_DESC("permission denied");
                result = storage::CODE_NO_AUTHORIZED;
            }
            else
            {
                PRECOMPILED_LOG(DEBUG) << LOG_BADGE("SystemConfigPrecompiled")
                                       << LOG_DESC("update value by key successfully");
                result = count;
            }
        }
    }
    else
    {
        PRECOMPILED_LOG(ERROR) << LOG_BADGE("SystemConfigPrecompiled")
                               << LOG_DESC("call undefined function") << LOG_KV("func", func);
    }
    getErrorCodeOut(callResult->mutableExecResult(), result);
    return callResult;
}

bool SystemConfigPrecompiled::checkValueValid(std::string const& key, std::string const& value)
{
    int64_t configuredValue = 0;
    try
    {
        configuredValue = boost::lexical_cast<int64_t>(value);
    }
    catch (std::exception const& e)
    {
        PRECOMPILED_LOG(ERROR) << LOG_BADGE("SystemConfigPrecompiled")
                               << LOG_DESC("checkValueValid failed") << LOG_KV("key", key)
                               << LOG_KV("value", value) << LOG_KV("errorInfo", e.what());
        return false;
    }
    if (SYSTEM_KEY_TX_COUNT_LIMIT == key)
    {
        return (configuredValue >= TX_COUNT_LIMIT_MIN);
    }
    else if (SYSTEM_KEY_TX_GAS_LIMIT == key)
    {
        return (configuredValue >= TX_GAS_LIMIT_MIN);
    }
    else if (SYSTEM_KEY_RPBFT_EPOCH_SEALER_NUM == key)
    {
        return (configuredValue >= RPBFT_EPOCH_SEALER_NUM_MIN);
    }
    else if (SYSTEM_KEY_RPBFT_EPOCH_BLOCK_NUM == key)
    {
        if (g_BCOSConfig.version() < V2_6_0)
        {
            return (configuredValue >= RPBFT_EPOCH_BLOCK_NUM_MIN);
        }
        else
        {
            // epoch_block_num is at least 2 when supported_version >= v2.6.0
            return (configuredValue > RPBFT_EPOCH_BLOCK_NUM_MIN);
        }
    }
    else if (SYSTEM_KEY_CONSENSUS_TIMEOUT == key)
    {
        if (g_BCOSConfig.version() < V2_6_0)
        {
            return false;
        }
        return (configuredValue >= SYSTEM_CONSENSUS_TIMEOUT_MIN &&
                configuredValue < SYSTEM_CONSENSUS_TIMEOUT_MAX);
    }
    // only can insert tx_count_limit and tx_gas_limit, rpbft_epoch_sealer_num,
    // rpbft_epoch_block_num as system config
    return false;
}

max_stars_repo_name: imtypist/FISCO-BCOS

max_issues_repo_name: imtypist/FISCO-BCOS

max_forks_repo_name: imtypist/FISCO-BCOS


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

max_stars_repo_name: graypilgrim/linda-communication

max_issues_repo_name: graypilgrim/linda-communication

max_forks_repo_name: graypilgrim/linda-communication


text:
#include "verification/production/impl/threshold_util.hpp"

#include <boost/range/adaptors.hpp>
#include <boost/range/numeric.hpp>

namespace sgns::verification {

  Threshold calculateThreshold(
      const std::pair<uint64_t, uint64_t> &c_pair,
      const primitives::AuthorityList &authorities,
      primitives::AuthorityIndex authority_index) {
    double c = double(c_pair.first) / c_pair.second;

    using boost::adaptors::transformed;
    double theta =
        double(authorities[authority_index].weight)
        / boost::accumulate(authorities | transformed([](auto &authority) {
                              return authority.weight;
                            }),
                            0.);

    using namespace boost::multiprecision;  // NOLINT
    cpp_rational p_rat(1. - pow(1. - c, theta));
    static const auto a = (uint256_t{1} << 128);
    cpp_int t = a * numerator(p_rat) / denominator(p_rat);
    return Threshold{t};
  }

}  // namespace sgns::verification

max_stars_repo_name: GeniusVentures/SuperGenius

max_issues_repo_name: GeniusVentures/SuperGenius

max_forks_repo_name: GeniusVentures/SuperGenius


text:
#include <algorithm>
#include <eosio/chain/apply_context.hpp>
#include <eosio/chain/chain_controller.hpp>
#include <eosio/chain/wasm_interface.hpp>
#include <eosio/chain/generated_transaction_object.hpp>
#include <eosio/chain/scope_sequence_object.hpp>
#include <boost/container/flat_set.hpp>

using boost::container::flat_set;

namespace eosio { namespace chain {
void apply_context::exec_one()
{
   try {
      auto native = mutable_controller.find_apply_handler(receiver, act.account, act.name);
      if (native) {
         (*native)(*this);
      } else {
         const auto &a = mutable_controller.get_database().get<account_object, by_name>(receiver);

         if (a.code.size() > 0) {
            // get code from cache
            auto code = mutable_controller.get_wasm_cache().checkout_scoped(a.code_version, a.code.data(),
                                                                            a.code.size());

            // get wasm_interface
            auto &wasm = wasm_interface::get();
            wasm.apply(code, *this);
         }
      }
   } FC_CAPTURE_AND_RETHROW((_pending_console_output.str()));

   if (!_write_scopes.empty()) {
      std::sort(_write_scopes.begin(), _write_scopes.end());
   }

   if (!_read_locks.empty()) {
      std::sort(_read_locks.begin(), _read_locks.end());
      // remove any write_scopes
      auto r_iter = _read_locks.begin();
      for( auto w_iter = _write_scopes.cbegin(); (w_iter != _write_scopes.cend()) && (r_iter != _read_locks.end()); ++w_iter) {
         shard_lock w_lock = {receiver, *w_iter};
         while(r_iter != _read_locks.end() && *r_iter < w_lock ) {
            ++r_iter;
         }

         if (*r_iter == w_lock) {
            r_iter = _read_locks.erase(r_iter);
         }
      }
   }

   // create a receipt for this
   vector<data_access_info> data_access;
   data_access.reserve(_write_scopes.size() + _read_locks.size());
   for (const auto& scope: _write_scopes) {
      auto key = boost::make_tuple(scope, receiver);
      const auto& scope_sequence = mutable_controller.get_database().find<scope_sequence_object, by_scope_receiver>(key);
      if (scope_sequence == nullptr) {
         try {
            mutable_controller.get_mutable_database().create<scope_sequence_object>([&](scope_sequence_object &ss) {
               ss.scope = scope;
               ss.receiver = receiver;
               ss.sequence = 1;
            });
         } FC_CAPTURE_AND_RETHROW((scope)(receiver));
         data_access.emplace_back(data_access_info{data_access_info::write, receiver, scope, 0});
      } else {
         data_access.emplace_back(data_access_info{data_access_info::write, receiver, scope, scope_sequence->sequence});
         try {
            mutable_controller.get_mutable_database().modify(*scope_sequence, [&](scope_sequence_object& ss) {
               ss.sequence += 1;
            });
         } FC_CAPTURE_AND_RETHROW((scope)(receiver));
      }
   }

   for (const auto& lock: _read_locks) {
      auto key = boost::make_tuple(lock.scope, lock.account);
      const auto& scope_sequence = mutable_controller.get_database().find<scope_sequence_object, by_scope_receiver>(key);
      if (scope_sequence == nullptr) {
         data_access.emplace_back(data_access_info{data_access_info::read, lock.account, lock.scope, 0});
      } else {
         data_access.emplace_back(data_access_info{data_access_info::read, lock.account, lock.scope, scope_sequence->sequence});
      }
   }

   results.applied_actions.emplace_back(action_trace {receiver, act, _pending_console_output.str(), 0, 0, move(data_access)});
   _pending_console_output = std::ostringstream();
   _read_locks.clear();
   _write_scopes.clear();
}

void apply_context::exec()
{
   _notified.push_back(act.account);

   for( uint32_t i = 0; i < _notified.size(); ++i ) {
      receiver = _notified[i];
      exec_one();
   }

   for( uint32_t i = 0; i < _inline_actions.size(); ++i ) {
      apply_context ncontext( mutable_controller, mutable_db, _inline_actions[i], trx_meta);
      ncontext.exec();
      append_results(move(ncontext.results));
   }

} /// exec()

void apply_context::require_authorization( const account_name& account )const {
  for( const auto& auth : act.authorization )
     if( auth.actor == account ) return;
  EOS_ASSERT( false, tx_missing_auth, "missing authority of ${account}", ("account",account));
}
void apply_context::require_authorization(const account_name& account,
                                          const permission_name& permission)const {
  for( const auto& auth : act.authorization )
     if( auth.actor == account ) {
        if( auth.permission == permission ) return;
     }
  EOS_ASSERT( false, tx_missing_auth, "missing authority of ${account}/${permission}",
              ("account",account)("permission",permission) );
}

static bool scopes_contain(const vector<scope_name>& scopes, const scope_name& scope) {
   return std::find(scopes.begin(), scopes.end(), scope) != scopes.end();
}

static bool locks_contain(const vector<shard_lock>& locks, const account_name& account, const scope_name& scope) {
   return std::find(locks.begin(), locks.end(), shard_lock{account, scope}) != locks.end();
}

void apply_context::require_write_lock(const scope_name& scope) {
   if (trx_meta.allowed_write_locks) {
      EOS_ASSERT( locks_contain(**trx_meta.allowed_write_locks, receiver, scope), block_lock_exception, "write lock \"${a}::${s}\" required but not provided", ("a", receiver)("s",scope) );
   }

   if (!scopes_contain(_write_scopes, scope)) {
      _write_scopes.emplace_back(scope);
   }
}

void apply_context::require_read_lock(const account_name& account, const scope_name& scope) {
   if (trx_meta.allowed_read_locks || trx_meta.allowed_write_locks ) {
      bool locked_for_read = trx_meta.allowed_read_locks && locks_contain(**trx_meta.allowed_read_locks, account, scope);
      if (!locked_for_read && trx_meta.allowed_write_locks) {
         locked_for_read = locks_contain(**trx_meta.allowed_write_locks, account, scope);
      }
      EOS_ASSERT( locked_for_read , block_lock_exception, "read lock \"${a}::${s}\" required but not provided", ("a", account)("s",scope) );
   }

   if (!locks_contain(_read_locks, account, scope)) {
      _read_locks.emplace_back(shard_lock{account, scope});
   }
}

bool apply_context::has_recipient( account_name code )const {
   for( auto a : _notified )
      if( a == code )
         return true;
   return false;
}

void apply_context::require_recipient( account_name code ) {
   if( !has_recipient(code) )
      _notified.push_back(code);
}

void apply_context::execute_inline( action &&a ) {
   // todo: rethink this special case
   if (receiver != config::system_account_name) {
      controller.check_authorization({a}, flat_set<public_key_type>(), false, {receiver});
   }
   _inline_actions.emplace_back( move(a) );
}

void apply_context::execute_deferred( deferred_transaction&& trx ) {
   try {
      FC_ASSERT( trx.expiration > (controller.head_block_time() + fc::milliseconds(2*config::block_interval_ms)),
                                   "transaction is expired when created" );

      FC_ASSERT( trx.execute_after < trx.expiration, "transaction expires before it can execute" );

      /// TODO: make default_max_gen_trx_count a producer parameter
      FC_ASSERT( results.generated_transactions.size() < config::default_max_gen_trx_count );

      FC_ASSERT( !trx.actions.empty(), "transaction must have at least one action");

      // todo: rethink this special case
      if (receiver != config::system_account_name) {
         controller.check_authorization(trx.actions, flat_set<public_key_type>(), false, {receiver});
      }

      trx.sender = receiver; //  "Attempting to send from another account"
      trx.set_reference_block(controller.head_block_id());

      /// TODO: make sure there isn't already a deferred transaction with this ID or senderID?
      results.generated_transactions.emplace_back(move(trx));
   } FC_CAPTURE_AND_RETHROW((trx));
}

void apply_context::cancel_deferred( uint32_t sender_id ) {
   results.canceled_deferred.emplace_back(receiver, sender_id);
}

const contracts::table_id_object* apply_context::find_table( name scope, name code, name table ) {
   require_read_lock(code, scope);
   return db.find<table_id_object, contracts::by_scope_code_table>(boost::make_tuple(scope, code, table));
}

const contracts::table_id_object& apply_context::find_or_create_table( name scope, name code, name table ) {
   require_read_lock(code, scope);
   const auto* existing_tid =  db.find<contracts::table_id_object, contracts::by_scope_code_table>(boost::make_tuple(scope, code, table));
   if (existing_tid != nullptr) {
      return *existing_tid;
   }

   require_write_lock(scope);
   return mutable_db.create<contracts::table_id_object>([&](contracts::table_id_object &t_id){
      t_id.scope = scope;
      t_id.code = code;
      t_id.table = table;
   });
}

vector<account_name> apply_context::get_active_producers() const {
   const auto& gpo = controller.get_global_properties();
   vector<account_name> accounts;
   for(const auto& producer : gpo.active_producers.producers)
      accounts.push_back(producer.producer_name);

   return accounts;
}

} } /// eosio::chain

max_stars_repo_name: anauman/eosio

max_issues_repo_name: anauman/eosio

max_forks_repo_name: anauman/eosio


text:
//=============================================================================================================
/**
* @file     ecddatatreeitem.cpp
* @author   Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     November, 2015
*
* @section  LICENSE
*
* Copyright (C) 2015, Lorenz Esch and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors 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.
*
*
* @brief    EcdDataTreeItem class definition.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "ecddatatreeitem.h"
#include "../common/metatreeitem.h"
#include "../../3dhelpers/renderable3Dentity.h"

#include <inverse/dipoleFit/ecd_set.h>

//*************************************************************************************************************
//=============================================================================================================
// Qt INCLUDES
//=============================================================================================================

#include <QList>
#include <QVariant>
#include <QStringList>
#include <QColor>
#include <QVector3D>
#include <QStandardItem>
#include <QStandardItemModel>
#include <Qt3DRender/qshaderprogram.h>
#include <Qt3DExtras/QSphereMesh>
#include <Qt3DExtras/QPhongMaterial>
#include <Qt3DCore/QTransform>
#include <QQuaternion>
#include <Qt3DExtras/QConeMesh>

//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================

#include <Eigen/Core>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace Eigen;
using namespace INVERSELIB;
using namespace DISP3DLIB;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

EcdDataTreeItem::EcdDataTreeItem(int iType, const QString &text)
: AbstractTreeItem(iType, text)
, m_bIsInit(false)
, m_pRenderable3DEntity(new Renderable3DEntity())
{
    this->setEditable(false);
    this->setCheckable(true);
    this->setCheckState(Qt::Checked);
    this->setToolTip("Dipole fit data");
}

//*************************************************************************************************************

EcdDataTreeItem::~EcdDataTreeItem()
{
    //Schedule deletion/Decouple of all entities so that the SceneGraph is NOT plotting them anymore.
    for(int i = 0; i < m_lDipoles.size(); ++i) {
        m_lDipoles.at(i)->deleteLater();
    }

    if(m_pRenderable3DEntity) {
        m_pRenderable3DEntity->deleteLater();
    }
}

//*************************************************************************************************************

QVariant EcdDataTreeItem::data(int role) const
{
    return AbstractTreeItem::data(role);
}

//*************************************************************************************************************

void EcdDataTreeItem::setData(const QVariant& value, int role)
{
    AbstractTreeItem::setData(value, role);
}

//*************************************************************************************************************

bool EcdDataTreeItem::init(Qt3DCore::QEntity* parent)
{
    //Create renderable 3D entity
    m_pRenderable3DEntity->setParent(parent);

    //Add meta information as item children
    QList<QStandardItem*> list;
    QVariant data;

    m_bIsInit = true;

    return true;
}

//*************************************************************************************************************

bool EcdDataTreeItem::addData(const ECDSet& pECDSet)
{
    if(!m_bIsInit) {
        qDebug() << "EcdDataTreeItem::addData - EcdDataTreeItem has not been initialized yet!";
        return false;
    }

    //Add further infos as children
    QList<QStandardItem*> list;
    MetaTreeItem *pItemNumDipoles = new MetaTreeItem(MetaTreeItemTypes::NumberDipoles, QString::number(pECDSet.size()));
    pItemNumDipoles->setEditable(false);
    list.clear();
    list << pItemNumDipoles;
    list << new QStandardItem(pItemNumDipoles->toolTip());
    this->appendRow(list);

    //Add data which is held by this NetworkTreeItem
    QVariant data;

    data.setValue(pECDSet);
    this->setData(data, Data3DTreeModelItemRoles::ECDSetData);

    //Plot dipole moment
    plotDipoles(pECDSet);

    return true;
}

//*************************************************************************************************************

void EcdDataTreeItem::onCheckStateChanged(const Qt::CheckState& checkState)
{
    this->setVisible(checkState == Qt::Unchecked ? false : true);
}

//*************************************************************************************************************

void EcdDataTreeItem::setVisible(bool state)
{
    for(int i = 0; i < m_lDipoles.size(); ++i) {
        m_lDipoles.at(i)->setEnabled(state);
    }

    m_pRenderable3DEntity->setEnabled(state);
}

//*************************************************************************************************************

void EcdDataTreeItem::plotDipoles(const ECDSet& tECDSet)
{
    //Plot dipoles
    QVector3D pos, to, from;

    //The Qt3D default cone orientation and the top of the cone lies in line with the positive y-axis.
    from = QVector3D(0.0, 1.0, 0.0);
    double norm;

    for(int i = 0; i < tECDSet.size(); ++i) {
        pos.setX(tECDSet[i].rd(0));
        pos.setY(tECDSet[i].rd(1));
        pos.setZ(tECDSet[i].rd(2));

        norm = sqrt(pow(tECDSet[i].Q(0),2)+pow(tECDSet[i].Q(1),2)+pow(tECDSet[i].Q(2),2));

        to.setX(tECDSet[i].Q(0)/norm);
        to.setY(tECDSet[i].Q(1)/norm);
        to.setZ(tECDSet[i].Q(2)/norm);

//        qDebug()<<"EcdDataTreeItem::plotDipoles - from" << from;
//        qDebug()<<"EcdDataTreeItem::plotDipoles - to" << to;

        QQuaternion final = QQuaternion::rotationTo(from, to);

        Renderable3DEntity* dipoleEntity = new Renderable3DEntity(m_pRenderable3DEntity);

        Qt3DExtras::QConeMesh* dipoleCone = new Qt3DExtras::QConeMesh();
        dipoleCone->setBottomRadius(0.001f);

//        //Calculate cone length based on norm 0.1mm -> 1nAm
//        double cm = 0.001;
//        double scale = (pow(10,-9))/(cm*0.01);
//        dipoleCone->setLength(norm/scale);
////        qDebug()<<"setLength"<<norm/scale;

        dipoleCone->setLength(0.003f);

        dipoleEntity->addComponent(dipoleCone);

        //Set dipole position and orientation
        Qt3DCore::QTransform* transform = new Qt3DCore::QTransform();
        QMatrix4x4 m;
        m.translate(pos);
        m.rotate(final);
        transform->setMatrix(m);
        dipoleEntity->addComponent(transform);

        Qt3DExtras::QPhongMaterial* material = new Qt3DExtras::QPhongMaterial();
        material->setAmbient(QColor(rand()%255, rand()%255, rand()%255));
        dipoleEntity->addComponent(material);

        m_lDipoles.append(dipoleEntity);
    }
}

max_stars_repo_name: LostSign/mne-cpp

max_issues_repo_name: LostSign/mne-cpp

max_forks_repo_name: LostSign/mne-cpp


text:
/*
    Copyright 2015 Adobe
    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/test/unit_test.hpp>

#include <stlab/concurrency/default_executor.hpp>
#include <stlab/concurrency/future.hpp>
#include <stlab/concurrency/utility.hpp>
#include <stlab/test/model.hpp>

#include "future_test_helper.hpp"

using namespace stlab;
using namespace future_test_helper;

BOOST_FIXTURE_TEST_SUITE(future_then_void, test_fixture<void>)

BOOST_AUTO_TEST_CASE(future_void_single_task) {
    BOOST_TEST_MESSAGE("running future void single task");

    int p = 0;

    sut = async(custom_scheduler<0>(), [& _p = p] { _p = 42; });

    check_valid_future(sut);
    wait_until_future_completed(sut);

    BOOST_REQUIRE_EQUAL(42, p);
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_void_single_task_detached) {
    BOOST_TEST_MESSAGE("running future void single task detached");

    std::atomic_int p{0};
    {
        auto detached = async(custom_scheduler<0>(), [& _p = p] { _p = 42; });
        detached.detach();
    }
    while (p.load() != 42) {
    }
}

BOOST_AUTO_TEST_CASE(future_void_two_tasks_with_same_scheduler_then_on_rvalue) {
    BOOST_TEST_MESSAGE("running future void with two task on same scheduler, then on r-value");

    std::atomic_int p{0};

    sut = async(custom_scheduler<0>(), [& _p = p] { _p = 42; }).then([& _p = p] { _p += 42; });

    check_valid_future(sut);
    wait_until_future_completed(sut);

    BOOST_REQUIRE_EQUAL(42 + 42, p);
    BOOST_REQUIRE_LE(2, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_void_two_tasks_with_same_scheduler_then_on_lvalue) {
    BOOST_TEST_MESSAGE("running future void with two task on same scheduler, then on l-value");

    std::atomic_int p{0};
    auto interim = async(custom_scheduler<0>(), [& _p = p] { _p = 42; });

    sut = interim.then([& _p = p] { _p += 42; });

    check_valid_future(sut);
    wait_until_future_completed(sut);

    BOOST_REQUIRE_EQUAL(42 + 42, p);
    BOOST_REQUIRE_LE(2, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_int_void_two_tasks_with_same_scheduler) {
    BOOST_TEST_MESSAGE("running future int void tasks with same scheduler");

    std::atomic_int p{0};

    sut = async(custom_scheduler<0>(), [] { return 42; }).then([& _p = p](auto x) { _p = x + 42; });
    check_valid_future(sut);

    wait_until_future_completed(sut);

    BOOST_REQUIRE_EQUAL(42 + 42, p);
    BOOST_REQUIRE_LE(2, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_int_void_two_tasks_with_different_scheduler) {
    BOOST_TEST_MESSAGE("running future int void tasks with different schedulers");

    std::atomic_int p{0};

    sut = async(custom_scheduler<0>(), [] { return 42; })
              .then(custom_scheduler<1>(), [& _p = p](auto x) { _p = x + 42; });
    check_valid_future(sut);

    wait_until_future_completed(sut);

    BOOST_REQUIRE_EQUAL(42 + 42, p);
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
    BOOST_REQUIRE_LE(1, custom_scheduler<1>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_void_two_tasks_with_different_scheduler) {
    BOOST_TEST_MESSAGE("running future void two tasks with different schedulers");

    std::atomic_int p{0};

    sut = async(custom_scheduler<0>(), [& _p = p] { _p = 42; })
              .then(custom_scheduler<1>(), [& _p = p] { _p += 42; });
    check_valid_future(sut);

    wait_until_future_completed(sut);

    BOOST_REQUIRE_EQUAL(42 + 42, p);
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
    BOOST_REQUIRE_LE(1, custom_scheduler<1>::usage_counter());
}

/*
        f1
       /
    sut
       \
        f2
*/
BOOST_AUTO_TEST_CASE(future_void_Y_formation_tasks_with_same_scheduler) {
    BOOST_TEST_MESSAGE("running future void with Y formation with same scheduler");

    std::atomic_int p{0};
    int r1 = 0;
    int r2 = 0;

    sut = async(custom_scheduler<0>(), [& _p = p] { _p = 42; });
    auto f1 = sut.then(custom_scheduler<0>(), [& _p = p, &_r = r1] { _r = 42 + _p; });
    auto f2 = sut.then(custom_scheduler<0>(), [& _p = p, &_r = r2] { _r = 4711 + _p; });

    check_valid_future(sut, f1, f2);
    wait_until_future_completed(f1, f2);

    BOOST_REQUIRE_EQUAL(42 + 42, r1);
    BOOST_REQUIRE_EQUAL(42 + 4711, r2);
    BOOST_REQUIRE_LE(3, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(reduction_future_void) {
    BOOST_TEST_MESSAGE("running future reduction void to void");

    std::atomic_bool first{false};
    std::atomic_bool second{false};

    sut = async(default_executor, [& _flag = first] { _flag = true; }).then([& _flag = second] {
        return async(default_executor, [&_flag] { _flag = true; });
    });

    wait_until_future_completed(sut);

    BOOST_REQUIRE(first);
    BOOST_REQUIRE(second);
}

BOOST_AUTO_TEST_CASE(reduction_future_int_to_void) {
    BOOST_TEST_MESSAGE("running future reduction int to void");
    std::atomic_bool first{false};
    std::atomic_bool second{false};
    std::atomic_int result{0};

    sut = async(default_executor,
                [& _flag = first] {
                    _flag = true;
                    return 42;
                })
              .then([& _flag = second, &_result = result](auto x) {
                  return async(default_executor,
                               [&_flag, &_result](auto x) {
                                   _flag = true;
                                   _result = x + 42;
                               },
                               x);
              });

    wait_until_future_completed(sut);

    BOOST_REQUIRE(first);
    BOOST_REQUIRE(second);
    BOOST_REQUIRE_EQUAL(84, result);
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_FIXTURE_TEST_SUITE(future_then_non_copyable, test_fixture<stlab::move_only>)
BOOST_AUTO_TEST_CASE(future_non_copyable_single_task) {
    BOOST_TEST_MESSAGE("running future non copyable single task");

    sut = async(custom_scheduler<0>(), [] { return move_only(42); });

    check_valid_future(sut);
    auto result = wait_until_future_r_completed(sut);

    BOOST_REQUIRE_EQUAL(42, result->member());
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_then_non_copyable_detach) {
    BOOST_TEST_MESSAGE("running future non copyable, detached");
    std::atomic_bool check{false};
    {
        async(custom_scheduler<0>(),
              [& _check = check] {
                  _check = true;
                  return move_only(42);
              })
            .detach();
    }
    while (!check) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
}

BOOST_AUTO_TEST_CASE(future_non_copyable_capture) {
    BOOST_TEST_MESSAGE("running future non copyable capture");

    stlab::v1::move_only m{42};

    sut = async(custom_scheduler<0>(), [& _m = m] { return move_only(_m.member()); });

    check_valid_future(sut);
    auto result = wait_until_future_r_completed(sut);

    BOOST_REQUIRE_EQUAL(42, result->member());
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(
    future_copyable_with_non_copyable_as_continuation_with_same_scheduler_then_on_rvalue) {
    BOOST_TEST_MESSAGE(
        "running future copyable with non copyable as contination with same scheduler, then on r-value");

    sut = async(custom_scheduler<0>(), [] { return 42; }).then([](auto x) { return move_only(x); });

    check_valid_future(sut);
    auto result = wait_until_future_r_completed(sut);

    BOOST_REQUIRE_EQUAL(42, result->member());
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(
    future_copyable_with_non_copyable_as_continuation_with_different_scheduler_then_on_rvalue) {
    BOOST_TEST_MESSAGE(
        "running future copyable with non copyable as contination with different scheduler, then on r-value");

    sut = async(custom_scheduler<0>(), [] { return 42; }).then(custom_scheduler<1>(), [](auto x) {
        return move_only(x);
    });

    check_valid_future(sut);
    auto result = wait_until_future_r_completed(sut);

    BOOST_REQUIRE_EQUAL(42, result->member());
    BOOST_REQUIRE_EQUAL(1, custom_scheduler<0>::usage_counter());
    BOOST_REQUIRE_EQUAL(1, custom_scheduler<1>::usage_counter());
}

BOOST_AUTO_TEST_CASE(
    future_copyable_with_non_copyable_as_continuation_with_same_scheduler_then_on_lvalue) {
    BOOST_TEST_MESSAGE(
        "running future copyable with non copyable as contination with same scheduler, then on l-value");

    auto interim = async(custom_scheduler<0>(), [] { return 42; });

    sut = interim.then([](auto x) { return move_only(x); });

    check_valid_future(sut);
    auto result = wait_until_future_r_completed(sut);

    BOOST_REQUIRE_EQUAL(42, result->member());
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(
    future_copyable_with_non_copyable_as_continuation_with_different_scheduler_then_on_lvalue) {
    BOOST_TEST_MESSAGE(
        "running future copyable with non copyable as contination with different scheduler, then on l-value");

    auto interim = async(custom_scheduler<0>(), [] { return 42; });

    sut = interim.then(custom_scheduler<1>(), [](auto x) { return move_only(x); });

    check_valid_future(sut);
    auto result = wait_until_future_r_completed(sut);

    BOOST_REQUIRE_EQUAL(42, result->member());
    BOOST_REQUIRE_EQUAL(1, custom_scheduler<0>::usage_counter());
    BOOST_REQUIRE_EQUAL(1, custom_scheduler<1>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_non_copyable_as_continuation_with_same_scheduler_then_on_rvalue) {
    BOOST_TEST_MESSAGE(
        "running future non copyable as contination with same scheduler, then on r-value");

    sut = async(custom_scheduler<0>(), [] { return move_only(42); }).then([](auto x) {
        return move_only(x.member() * 2);
    });

    check_valid_future(sut);
    auto result = wait_until_future_r_completed(sut);

    BOOST_REQUIRE_EQUAL(42 * 2, result->member());
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_non_copyable_as_continuation_with_different_scheduler_then_on_rvalue) {
    BOOST_TEST_MESSAGE(
        "running future non copyable as contination with different scheduler, then on r-value");

    sut = async(custom_scheduler<0>(), [] { return move_only(42); })
              .then(custom_scheduler<1>(), [](auto x) { return move_only(x.member() * 2); });

    check_valid_future(sut);
    auto result = wait_until_future_r_completed(sut);

    BOOST_REQUIRE_EQUAL(42 * 2, result->member());
    BOOST_REQUIRE_EQUAL(1, custom_scheduler<0>::usage_counter());
    BOOST_REQUIRE_EQUAL(1, custom_scheduler<1>::usage_counter());
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_FIXTURE_TEST_SUITE(future_then_move_only, test_fixture<stlab::v1::move_only>)

BOOST_AUTO_TEST_CASE(future_async_move_only_move_captured_to_result) {
    BOOST_TEST_MESSAGE("running future move only move to result");

    sut = async(custom_scheduler<0>(), [] { return move_only{42}; }).then([](auto x) {
        return std::move(x);
    });

    check_valid_future(sut);
    auto result = wait_until_future_r_completed(sut);

    BOOST_REQUIRE_EQUAL(42, result->member());
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_async_moving_move_only_capture_to_result) {
    BOOST_TEST_MESSAGE("moving move_only capture to result");

    stlab::v1::move_only m{42};

    sut = async(custom_scheduler<0>(), [& _m = m] { return std::move(_m); });

    check_valid_future(sut);
    auto result = wait_until_future_r_completed(sut);

    BOOST_REQUIRE_EQUAL(42, result->member());
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_async_mutable_move_move_only_capture_to_result) {
    BOOST_TEST_MESSAGE("moving move_only capture to result in mutable task");

    stlab::v1::move_only m{42};

    sut = async(custom_scheduler<0>(), [& _m = m]() mutable { return std::move(_m); });

    check_valid_future(sut);
    auto result = wait_until_future_r_completed(sut);

    BOOST_REQUIRE_EQUAL(42, result->member());
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_continuation_moving_move_only_capture_to_result) {
    BOOST_TEST_MESSAGE("moving move_only capture to result");

    stlab::v1::move_only m{42};

    sut = async(custom_scheduler<0>(), [] { return stlab::v1::move_only{10}; })
              .then([& _m = m](auto) mutable { return std::move(_m); });

    check_valid_future(sut);
    auto result = wait_until_future_r_completed(sut);

    BOOST_REQUIRE_EQUAL(42, result->member());
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_continuation_async_mutable_move_move_only_capture_to_result) {
    BOOST_TEST_MESSAGE("moving move_only capture to result in mutable task");

    stlab::v1::move_only m{42};

    sut = async(custom_scheduler<0>(), []() mutable { return stlab::v1::move_only{10}; })
              .then([& _m = m](auto) mutable { return std::move(_m); });

    check_valid_future(sut);
    auto result = wait_until_future_r_completed(sut);

    BOOST_REQUIRE_EQUAL(42, result->member());
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_FIXTURE_TEST_SUITE(future_then_int, test_fixture<int>)

BOOST_AUTO_TEST_CASE(future_int_single_task) {
    BOOST_TEST_MESSAGE("running future int single tasks");

    sut = async(custom_scheduler<0>(), [] { return 42; });

    check_valid_future(sut);
    wait_until_future_completed(sut);

    BOOST_REQUIRE_EQUAL(42, *sut.get_try());
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_int_single_task_get_try_on_rvalue) {
    BOOST_TEST_MESSAGE("running future int single tasks, get_try on r-value");

    sut = async(custom_scheduler<0>(), [] { return 42; });

    auto test_result_1 = std::move(sut).get_try(); // test for r-value implementation
    (void)test_result_1;
    wait_until_future_completed(sut);
    auto test_result_2 = std::move(sut).get_try();

    BOOST_REQUIRE_EQUAL(42, *sut.get_try());
    BOOST_REQUIRE_EQUAL(42, *test_result_2);
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_int_single_task_detached) {
    BOOST_TEST_MESSAGE("running future int single tasks, detached");
    std::atomic_bool check{false};
    {
        auto detached = async(custom_scheduler<0>(), [& _check = check] {
            _check = true;
            return 42;
        });
        detached.detach();
    }
    while (!check) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
}

BOOST_AUTO_TEST_CASE(future_int_two_tasks_with_same_scheduler_then_on_rvalue) {
    BOOST_TEST_MESSAGE("running future int two tasks with same scheduler, then on r-value");

    sut = async(custom_scheduler<0>(), [] { return 42; }).then([](auto x) { return x + 42; });

    check_valid_future(sut);
    wait_until_future_completed(sut);

    BOOST_REQUIRE_EQUAL(42 + 42, *sut.get_try());
    BOOST_REQUIRE_LE(2, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_int_two_tasks_with_same_scheduler_then_on_lvalue) {
    BOOST_TEST_MESSAGE("running future int two tasks with same scheduler, then on l-value");

    auto interim = async(custom_scheduler<0>(), [] { return 42; });

    sut = interim.then([](auto x) { return x + 42; });

    check_valid_future(sut);
    wait_until_future_completed(sut);

    BOOST_REQUIRE_EQUAL(42 + 42, *sut.get_try());
    BOOST_REQUIRE_LE(2, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_int_two_tasks_with_different_scheduler) {
    BOOST_TEST_MESSAGE("running future int two tasks with different scheduler");

    sut = async(custom_scheduler<0>(), [] { return 42; }).then(custom_scheduler<1>(), [](auto x) {
        return x + 42;
    });

    check_valid_future(sut);
    wait_until_future_completed(sut);

    BOOST_REQUIRE_EQUAL(42 + 42, *sut.get_try());
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
    BOOST_REQUIRE_LE(1, custom_scheduler<1>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_void_int_two_tasks_with_same_scheduler) {
    BOOST_TEST_MESSAGE("running future void int tasks with same scheduler");

    std::atomic_int p{0};

    sut = async(custom_scheduler<0>(), [& _p = p] { _p = 42; }).then([& _p = p] {
        _p += 42;
        return _p.load();
    });

    check_valid_future(sut);
    wait_until_future_completed(sut);

    BOOST_REQUIRE_EQUAL(42 + 42, p);
    BOOST_REQUIRE_LE(2, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_void_int_two_tasks_with_different_scheduler) {
    BOOST_TEST_MESSAGE("running future void int tasks with different schedulers");

    std::atomic_int p{0};

    sut = async(custom_scheduler<0>(), [& _p = p] { _p = 42; })
              .then(custom_scheduler<1>(), [& _p = p] {
                  _p += 42;
                  return _p.load();
              });

    check_valid_future(sut);
    wait_until_future_completed(sut);

    BOOST_REQUIRE_EQUAL(42 + 42, p);
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
    BOOST_REQUIRE_LE(1, custom_scheduler<1>::usage_counter());
}

/*
    sut - f - f
*/
BOOST_AUTO_TEST_CASE(future_int_three_tasks_with_same_scheduler) {
    BOOST_TEST_MESSAGE("running future int with three tasks with same scheduler");

    sut = async(custom_scheduler<0>(), [] { return 42; })
              .then(custom_scheduler<0>(), [](auto x) { return x + 42; })
              .then(custom_scheduler<0>(), [](auto x) { return x + 42; });

    check_valid_future(sut);
    wait_until_future_completed(sut);

    BOOST_REQUIRE_EQUAL(42 + 42 + 42, *sut.get_try());
    BOOST_REQUIRE_LE(3, custom_scheduler<0>::usage_counter());
}

/*
        f1
       /
    sut
       \
        f2
*/
BOOST_AUTO_TEST_CASE(future_int_Y_formation_tasks_with_same_scheduler) {
    BOOST_TEST_MESSAGE("running future int Y formation tasks with same scheduler");

    sut = async(custom_scheduler<0>(), [] { return 42; });
    auto f1 = sut.then(custom_scheduler<0>(), [](auto x) -> int { return x + 42; });
    auto f2 = sut.then(custom_scheduler<0>(), [](auto x) -> int { return x + 4177; });

    check_valid_future(sut, f1, f2);
    wait_until_future_completed(f1, f2);

    BOOST_REQUIRE_EQUAL(42 + 42, *f1.get_try());
    BOOST_REQUIRE_EQUAL(42 + 4177, *f2.get_try());
    BOOST_REQUIRE_LE(3, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(reduction_future_void_to_int) {
    BOOST_TEST_MESSAGE("running future reduction void to int");
    std::atomic_bool first{false};
    std::atomic_bool second{false};

    sut = async(default_executor, [& _flag = first] { _flag = true; }).then([& _flag = second] {
        return async(default_executor, [&_flag] {
            _flag = true;
            return 42;
        });
    });

    wait_until_future_completed(sut);

    BOOST_REQUIRE(first);
    BOOST_REQUIRE(second);
    BOOST_REQUIRE_EQUAL(42, *sut.get_try());
}

BOOST_AUTO_TEST_CASE(reduction_future_int_to_int) {
    BOOST_TEST_MESSAGE("running future reduction int to int");
    std::atomic_bool first{false};
    std::atomic_bool second{false};

    sut = async(default_executor,
                [& _flag = first] {
                    _flag = true;
                    return 42;
                })
              .then([& _flag = second](auto x) {
                  return async(default_executor,
                               [&_flag](auto x) {
                                   _flag = true;
                                   return x + 42;
                               },
                               x);
              });

    wait_until_future_completed(sut);

    BOOST_REQUIRE(first);
    BOOST_REQUIRE(second);
    BOOST_REQUIRE_EQUAL(84, *sut.get_try());
}
BOOST_AUTO_TEST_SUITE_END()

// ----------------------------------------------------------------------------
//                             Error cases
// ----------------------------------------------------------------------------

BOOST_FIXTURE_TEST_SUITE(future_void_then_error, test_fixture<void>)
BOOST_AUTO_TEST_CASE(future_void_single_task_error) {
    BOOST_TEST_MESSAGE("running future void with single tasks that fails");

    sut = async(custom_scheduler<0>(), [] { throw test_exception("failure"); });

    wait_until_future_fails<test_exception>(sut);
    check_failure<test_exception>(sut, "failure");
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_void_two_tasks_error_in_1st_task_with_same_scheduler) {
    BOOST_TEST_MESSAGE("running future void with two tasks which first fails");

    std::atomic_int p{0};

    sut = async(custom_scheduler<0>(), [] { throw test_exception("failure"); }).then([& _p = p] {
        _p = 42;
    });

    wait_until_future_fails<test_exception>(sut);
    check_failure<test_exception>(sut, "failure");
    BOOST_REQUIRE_EQUAL(0, p);
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_void_two_tasks_error_in_2nd_task_with_same_scheduler) {
    BOOST_TEST_MESSAGE("running future void with two tasks which second fails");

    std::atomic_int p{0};

    sut = async(custom_scheduler<0>(), [& _p = p] { _p = 42; }).then([& _p = p] {
        throw test_exception("failure");
    });

    wait_until_future_fails<test_exception>(sut);

    check_failure<test_exception>(sut, "failure");
    BOOST_REQUIRE_EQUAL(42, p);
    BOOST_REQUIRE_LE(2, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(reduction_future_void_to_void_error) {
    BOOST_TEST_MESSAGE("running future reduction void to void where the inner future fails");
    std::atomic_bool first{false};
    std::atomic_bool second{false};

    sut = async(default_executor, [& _flag = first] { _flag = true; }).then([& _flag = second] {
        return async(default_executor, [&_flag] {
            _flag = true;
            throw test_exception("failure");
        });
    });

    wait_until_future_fails<test_exception>(sut);

    BOOST_REQUIRE(first);
    BOOST_REQUIRE(second);
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_FIXTURE_TEST_SUITE(future_then_int_error, test_fixture<int>)

BOOST_AUTO_TEST_CASE(future_int_single_task_error) {
    BOOST_TEST_MESSAGE("running future int with single tasks that fails");

    sut = async(custom_scheduler<0>(), []() -> int { throw test_exception("failure"); });
    wait_until_future_fails<test_exception>(sut);

    check_failure<test_exception>(sut, "failure");
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}
#if 0 // currently disabled, because I have doubts that get_try on an r-value makes any sense at al
    BOOST_AUTO_TEST_CASE(future_int_single_task_with_error_get_try_on_rvalue) {
        BOOST_TEST_MESSAGE("running future int single tasks, with error on get_try on r-value");

        sut = async(custom_scheduler<0>(), []()->int { throw test_exception("failure"); });
        auto test_result_1 = std::move(sut).get_try(); // test for r-value implementation
        wait_until_future_fails<test_exception>(sut);
        check_failure<test_exception>(std::move(sut), "failure");
        BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
    }
#endif
BOOST_AUTO_TEST_CASE(future_int_two_tasks_error_in_1st_task_with_same_scheduler) {
    BOOST_TEST_MESSAGE("running future int with two tasks which first fails");
    int p = 0;

    sut = async(custom_scheduler<0>(), [] { throw test_exception("failure"); })
              .then([& _p = p]() -> int {
                  _p = 42;
                  return _p;
              });

    wait_until_future_fails<test_exception>(sut);

    check_failure<test_exception>(sut, "failure");
    BOOST_REQUIRE_EQUAL(0, p);
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_int_two_tasks_error_in_2nd_task_with_same_scheduler) {
    BOOST_TEST_MESSAGE("running future void with two tasks which second fails");

    std::atomic_int p{0};

    sut = async(custom_scheduler<0>(), [& _p = p] { _p = 42; }).then([]() -> int {
        throw test_exception("failure");
    });

    wait_until_future_fails<test_exception>(sut);

    check_failure<test_exception>(sut, "failure");
    BOOST_REQUIRE_EQUAL(42, p);
    BOOST_REQUIRE_LE(2, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_int_Y_formation_tasks_with_failing_1st_task) {
    BOOST_TEST_MESSAGE("running future int Y formation tasks where the 1st tasks fails");

    std::atomic_int p{0};

    sut = async(custom_scheduler<0>(), []() -> int { throw test_exception("failure"); });
    auto f1 = sut.then(custom_scheduler<0>(), [& _p = p](auto x) -> int {
        _p += 1;
        return x + 42;
    });
    auto f2 = sut.then(custom_scheduler<0>(), [& _p = p](auto x) -> int {
        _p += 1;
        return x + 4177;
    });

    wait_until_future_fails<test_exception>(f1, f2);

    check_failure<test_exception>(f1, "failure");
    check_failure<test_exception>(f2, "failure");
    BOOST_REQUIRE_EQUAL(0, p);
    BOOST_REQUIRE_LE(1, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_int_Y_formation_tasks_where_one_of_the_2nd_task_failing) {
    BOOST_TEST_MESSAGE("running future int Y formation tasks where one of the 2nd tasks fails");

    sut = async(custom_scheduler<0>(), []() -> int { return 42; });
    auto f1 = sut.then(custom_scheduler<0>(), [](auto) -> int { throw test_exception("failure"); });
    auto f2 = sut.then(custom_scheduler<0>(), [](auto x) -> int { return x + 4711; });

    wait_until_future_completed(f2);
    wait_until_future_fails<test_exception>(f1);

    check_failure<test_exception>(f1, "failure");
    BOOST_REQUIRE_EQUAL(42 + 4711, *f2.get_try());
    BOOST_REQUIRE_LE(3, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(future_int_Y_formation_tasks_where_both_of_the_2nd_task_failing) {
    BOOST_TEST_MESSAGE("running future int Y formation tasks where both of the 2nd tasks fails");

    sut = async(custom_scheduler<0>(), []() -> int { return 42; });
    auto f1 = sut.then(custom_scheduler<0>(), [](auto) -> int { throw test_exception("failure"); });
    auto f2 = sut.then(custom_scheduler<0>(), [](auto) -> int { throw test_exception("failure"); });

    wait_until_future_fails<test_exception>(f1, f2);

    check_failure<test_exception>(f1, "failure");
    check_failure<test_exception>(f2, "failure");
    BOOST_REQUIRE_LE(3, custom_scheduler<0>::usage_counter());
}

BOOST_AUTO_TEST_CASE(reduction_future_void_to_int_error) {
    BOOST_TEST_MESSAGE("running future reduction void to int where the outer future fails");
    std::atomic_bool first{false};
    std::atomic_bool second{false};

    sut = async(default_executor, [& _flag = first] { _flag = true; })
              .then([& _flag = second]() -> future<int> { throw test_exception("failure"); });

    wait_until_future_fails<test_exception>(sut);

    BOOST_REQUIRE(first);
    BOOST_REQUIRE(!second);
}

BOOST_AUTO_TEST_CASE(reduction_future_int_to_int_error) {
    BOOST_TEST_MESSAGE("running future reduction int to int where the inner future fails");
    std::atomic_bool first{false};
    std::atomic_bool second{false};

    sut = async(default_executor,
                [& _flag = first] {
                    _flag = true;
                    return 42;
                })
              .then([& _flag = second](auto x) {
                  return async(default_executor,
                               [&_flag](auto) -> int {
                                   _flag = true;
                                   throw test_exception("failure");
                               },
                               x);
              });

    wait_until_future_fails<test_exception>(sut);

    BOOST_REQUIRE(first);
    BOOST_REQUIRE(second);
}

BOOST_AUTO_TEST_SUITE_END()

#if 0
BOOST_AUTO_TEST_CASE(reduction_future_move_only_to_move_only) {
    BOOST_TEST_MESSAGE("running future reduction move-only to move-only");
    std::atomic_bool first{ false };
    std::atomic_bool second{ false };

    future<move_only> a = async(default_executor, [&_flag = first] {
        _flag = true; std::cout << 1 << std::endl; return move_only(42); }).then([&_flag = second] (auto&& x) {
        return async(default_executor, [&_flag] (auto&& x) {
            _flag = true; std::cout << 2 << std::endl; return std::forward<move_only>(x); }, std::forward<move_only>(x));
    });

    while (!a.get_try()) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }

    BOOST_REQUIRE(first);
    BOOST_REQUIRE(second);
    BOOST_REQUIRE_EQUAL(42, a.get_try().value().member());
}
#endif

max_stars_repo_name: superfunc/libraries

max_issues_repo_name: superfunc/libraries

max_forks_repo_name: superfunc/libraries


text:
/*
    Copyright 2012 efalex <email>

    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.
*/

#ifndef FIGURE_HPP
#define FIGURE_HPP

#include "common.hpp"
#include <boost/numeric/ublas/matrix.hpp>
#include "cube.hpp"
#include "figure_cube.hpp"
#include <boost/ptr_container/ptr_vector.hpp>

class figure {
public:
    boost::ptr_vector < figure_cube > cubes;

    figure();
    figure(const figure &);
    figure & operator=(const figure &);

    vector_int direction[3];
    void reset();
    void addFigureCube(figure_cube);
    void rotate(boost::numeric::ublas::matrix < int >);
    figure *new_clone();
};

#endif // FIGURE_HPP

max_stars_repo_name: EfAlex/Puzzle-Box-Solver

max_issues_repo_name: EfAlex/Puzzle-Box-Solver

max_forks_repo_name: EfAlex/Puzzle-Box-Solver


text:
/**
 * @file    A_Command_Argument.cpp
 * @author  Marvin Smith
 * @date    5/18/2015
*/
#include "A_Command_Argument.hpp"

// Boost Libraries
#include <boost/regex.hpp>

// C++ Standard Libraries
#include <iostream>
#include <sstream>

// CLI Libraries
#include "../utility/Filesystem_Utilities.hpp"
#include "../utility/String_Utilities.hpp"

namespace CLI{
namespace CMD{

/**********************************/
/*          Constructor           */
/**********************************/
A_Command_Argument::A_Command_Argument()
  : m_class_name("A_Command_Argument"),
    m_name(""),
    m_type(CommandArgumentType::UNKNOWN),
    m_description(""),
    m_default_value(""),
    m_required(true),
    m_autocomplete_path(false)
{
}

/**********************************/
/*          Constructor           */
/**********************************/
A_Command_Argument::A_Command_Argument( const std::string&             arg_name,
                                        const CommandArgumentType&  arg_type,
                                        const std::string&             arg_description,
                                        const bool&                    arg_required,
                                        const std::string&             arg_default_value )
   : m_class_name("A_Command_Argument"),
     m_name(arg_name),
     m_type(arg_type),
     m_description(arg_description),
     m_default_value(arg_default_value),
     m_required(arg_required),
     m_autocomplete_path(false)
{
}

/**********************************/
/*          Constructor           */
/**********************************/
A_Command_Argument::A_Command_Argument( const std::string&             arg_name,
                                        const CommandArgumentType&     arg_type,
                                        const std::string&             arg_description,
                                        const bool&                    arg_required,
                                        const std::string&             arg_default_value,
                                        const bool&                    arg_autocomplete_path,
                                        std::vector<std::string>const& arg_autocomplete_terms )
   : m_class_name("A_Command_Argument"),
     m_name(arg_name),
     m_type(arg_type),
     m_description(arg_description),
     m_default_value(arg_default_value),
     m_required(arg_required),
     m_autocomplete_path(arg_autocomplete_path),
     m_autocomplete_terms(arg_autocomplete_terms)
{
}

/*****************************************/
/*          Check String Type            */
/*****************************************/
bool A_Command_Argument::Is_Valid_Type( const std::string& test_str )const
{
    // String Match
    boost::smatch what;

    // Compare Integer Types
    if( m_type == CommandArgumentType::INTEGER ){
        return boost::regex_match( test_str, what, boost::regex("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"));
    }

    // Compare Float Types
    if( m_type == CommandArgumentType::FLOAT ){
        return boost::regex_match( test_str, what, boost::regex("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"));
    }

    // Compare Path Types
    if( m_type == CommandArgumentType::PATH ){
        return true;
    }

    // Compare String Types
    if( m_type == CommandArgumentType::STRING ){
        return true;
    }

    // Otherwise, there is a problem
    return false;
}

/*****************************************/
/*          Equivalent Operator          */
/*****************************************/
bool A_Command_Argument::operator == ( A_Command_Argument const& other )const
{
    // Check the name
    if( m_name != other.m_name ){
        return false;
    }

    // Check the type
    if( m_type != other.m_type ){
        return false;
    }

    // Skip the description

    // Check the default value
    if( m_default_value != other.m_default_value ){
        return false;
    }

    // Check if required
    if( m_required != other.m_required ){
        return false;
    }

    // Otherwise, true
    return true;
}

/*********************************************/
/*          Not-Equivalent Operator          */
/*********************************************/
bool A_Command_Argument::operator != ( A_Command_Argument const& other )const
{
    return (!((*this) == other));
}

/************************************************/
/*       Check if Argument is a Substring       */
/************************************************/
bool A_Command_Argument::Is_Argument_Substring( const std::string& argument_name,
                                                std::string& match_name )const
{
    // List of potential matches
    std::vector<std::string> match_list;

    // Iterate over autocomplete terms
    for( size_t i=0; i<m_autocomplete_terms.size(); i++ )
    {
        // Check the size
        if( argument_name.size() > m_autocomplete_terms[i].size() ){
            continue;
        }

        // Check if equal
        if( argument_name == m_autocomplete_terms[i] ){
            match_list.push_back(m_autocomplete_terms[i]);
            continue;
        }

        // Check substring
        if( m_autocomplete_terms[i].substr(0, argument_name.size()) == argument_name )
        {
            match_list.push_back(m_autocomplete_terms[i]);
            continue;
        }
    }

    // If the type if a filesystem type, get a list of files
    if( m_type == CommandArgumentType::PATH && m_autocomplete_path == true )
    {

        // Get a list of paths
        std::vector<std::string> pathname_list = FS::Get_Contents( argument_name );

        // iterate over the list, checking the names
        for( size_t i=0; i<pathname_list.size(); i++ ){

            // If the pathname is shorter, it cannot be valid
            if( pathname_list[i].size() < argument_name.size() ){
                continue;
            }

            // Otherwise, do a substring check
            std::string temp_path = pathname_list[i].substr(0, argument_name.size());
            if( temp_path == argument_name ){
                match_list.push_back( pathname_list[i] );
            }
        }
    }

    // Check if we found any matches
    if( match_list.size() <= 0 ){
        match_name = "";
        return false;
    }

    // Find the minimum spanning substring
    match_name = match_list[0];
    for( size_t i=1; i<match_list.size(); i++ ){
        match_name = UTILS::String_Substring_Match( match_name, match_list[i]);
    }
    return true;
}

/*********************************************/
/*          Print as a Debug String          */
/*********************************************/
std::string A_Command_Argument::To_Debug_String( int const& offset )const
{
    // Create output stream
    std::stringstream sin;
    std::string gap( offset, ' ');

    // Start adding info
    sin << gap << m_class_name << ":\n";
    sin << gap << "    Name        : " << m_name << std::endl;
    sin << gap << "    Arg Type    : " << CommandArgumentTypeToString(m_type) << std::endl;
    sin << gap << "    Description : " << m_description << std::endl;
    sin << gap << "    Default     : " << m_default_value << std::endl;
    sin << gap << "    Required    : " << std::boolalpha << m_required << std::endl;
    sin << gap << "    Autocomplete Terms: " << std::endl;
    for( size_t i=0; i<m_autocomplete_terms.size(); i++ ){
        sin << gap << "       " << i << " : " << m_autocomplete_terms[i] << std::endl;
    }

    // return output
    return sin.str();
}

} // End of CMD Namespace
} // End of CLI Namespace

max_stars_repo_name: marvins/cli-cpp

max_issues_repo_name: marvins/cli-cpp

max_forks_repo_name: marvins/cli-cpp


text: #include <boost/align/aligned_allocator_forward.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino