text:
/*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <boost/hana/detail/std/integer_sequence.hpp>

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

static_assert(std::is_same<
    detail::std::make_integer_sequence<int, 0>,
    detail::std::integer_sequence<int>
>::value, "");

static_assert(std::is_same<
    detail::std::make_integer_sequence<int, 1>,
    detail::std::integer_sequence<int, 0>
>::value, "");

static_assert(std::is_same<
    detail::std::make_integer_sequence<int, 2>,
    detail::std::integer_sequence<int, 0, 1>
>::value, "");

static_assert(std::is_same<
    detail::std::make_integer_sequence<int, 3>,
    detail::std::integer_sequence<int, 0, 1, 2>
>::value, "");

static_assert(std::is_same<
    detail::std::make_integer_sequence<int, 4>,
    detail::std::integer_sequence<int, 0, 1, 2, 3>
>::value, "");

static_assert(std::is_same<
    detail::std::make_integer_sequence<int, 5>,
    detail::std::integer_sequence<int, 0, 1, 2, 3, 4>
>::value, "");

static_assert(std::is_same<
    detail::std::make_integer_sequence<int, 6>,
    detail::std::integer_sequence<int, 0, 1, 2, 3, 4, 5>
>::value, "");

int main() { }

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


text:
//==================================================================================================
/*!
  @file

    @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_BITINTEGER_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_BITINTEGER_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-ieee
    This function object transforms a floating point value
    in an integer with a preserving order formula.
    This function is the converse of @ref bitfloating.

    @par Header <boost/simd/function/bitinteger.hpp>

    @par Note:
    This function is related to the computation of
    floating successors or predecessors as the ordering of the integers obtained
    by @c bifloating is the same as the original order on the floating elements,
    an increment can be used to find the successor.

    @see next, prev, successor,  predecessor,  nextafter, bitfloating

    @par Example:

      @snippet bitinteger.cpp bitinteger

    @par Possible output:

      @snippet bitinteger.txt bitinteger

  **/
  as_integer_t<Value> bitinteger(Value const& x);
} }
#endif

#include <boost/simd/function/scalar/bitinteger.hpp>
#include <boost/simd/function/simd/bitinteger.hpp>

#endif

ext: hpp

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <Inventor/SoDB.h>
#include <Inventor/SoOutput.h>
#include <Inventor/actions/SoWriteAction.h>
#include <Inventor/VRMLnodes/SoVRMLAppearance.h>
#include <Inventor/VRMLnodes/SoVRMLColor.h>
#include <Inventor/VRMLnodes/SoVRMLCoordinate.h>
#include <Inventor/VRMLnodes/SoVRMLIndexedFaceSet.h>
#include <Inventor/VRMLnodes/SoVRMLMaterial.h>
#include <Inventor/VRMLnodes/SoVRMLShape.h>
#include <Inventor/VRMLnodes/SoVRMLTransform.h>

int
main(int argc, char** argv)
{
	if (argc != 3)
	{
		std::cerr << "Usage: tris2wrl [input.tris] [output.wrl]" << std::endl;
		return EXIT_FAILURE;
	}

	SoDB::init();

	std::fstream file;
	file.open(argv[1]);

	std::string line;
	std::vector<std::string> tokens;

	std::getline(file, line);

	if (!boost::starts_with(line, "#"))
	{
		file.close();
		return EXIT_FAILURE;
	}

	SoVRMLTransform* root = new SoVRMLTransform();
	root->ref();

	SoVRMLShape* shape = new SoVRMLShape();
	root->addChild(shape);

	SoVRMLAppearance* appearance = new SoVRMLAppearance();
	shape->appearance = appearance;

	SoVRMLMaterial* material = new SoVRMLMaterial();
	appearance->material = material;

	SoVRMLIndexedFaceSet* indexedFaceSet = new SoVRMLIndexedFaceSet();
	shape->geometry = indexedFaceSet;

	SoVRMLCoordinate* coordinate = new SoVRMLCoordinate();
	indexedFaceSet->coord = coordinate;

	SoVRMLColor* color = new SoVRMLColor();
	indexedFaceSet->color = color;

	indexedFaceSet->colorPerVertex.setValue(false);
	indexedFaceSet->solid.setValue(false);

	while (-1 != file.peek())
	{
		std::getline(file, line);

		if (line.empty())
		{
			continue;
		}
		else if (boost::starts_with(line, "#"))
		{
			break;
		}

		boost::trim(line);
		boost::split(tokens, line, boost::is_space(), boost::token_compress_on);

		coordinate->point.set1Value(coordinate->point.getNum(), std::stof(tokens[0]), std::stof(tokens[1]), std::stof(tokens[2]));
	}

	while (-1 != file.peek())
	{
		std::getline(file, line);

		if (line.empty())
		{
			continue;
		}
		else if (boost::starts_with(line, "#"))
		{
			break;
		}

		boost::trim(line);
		boost::split(tokens, line, boost::is_space(), boost::token_compress_on);

		for (std::size_t i = 0; i < tokens.size(); ++i)
		{
			indexedFaceSet->coordIndex.set1Value(indexedFaceSet->coordIndex.getNum(), std::stoi(tokens[i]));
		}

		indexedFaceSet->coordIndex.set1Value(indexedFaceSet->coordIndex.getNum(), -1);
	}

	while (-1 != file.peek())
	{
		std::getline(file, line);

		if (line.empty())
		{
			continue;
		}
		else if (boost::starts_with(line, "#"))
		{
			break;
		}

		boost::trim(line);
		boost::split(tokens, line, boost::is_space(), boost::token_compress_on);

		if (tokens.size() > 5)
		{
			color->color.set1Value(color->color.getNum(), std::stof(tokens[3]), std::stof(tokens[4]), std::stof(tokens[5]));
		}
	}

	while (-1 != file.peek())
	{
		std::getline(file, line);

		if (line.empty())
		{
			continue;
		}
		else if (boost::starts_with(line, "#"))
		{
			break;
		}

		boost::trim_if(line, boost::is_any_of(", \t\n\v\f\r"));
		boost::split(tokens, line, boost::is_any_of(", "), boost::token_compress_on);

		for (std::size_t i = 0; i < tokens.size(); ++i)
		{
			indexedFaceSet->colorIndex.set1Value(indexedFaceSet->colorIndex.getNum(), std::stoi(tokens[i]));
		}
	}

	std::cout << "coordinates: " << coordinate->point.getNum() << std::endl;
	std::cout << "faces: " << indexedFaceSet->coordIndex.getNum() / 4 << std::endl;
	std::cout << "materials: " << color->color.getNum() << std::endl;
	std::cout << "material indices: " << indexedFaceSet->colorIndex.getNum() << std::endl;

	if (0 == indexedFaceSet->colorIndex.getNum())
	{
		color->ref();
		indexedFaceSet->color.setValue(nullptr);
		color->unref();
	}

	file.close();

	SoOutput out;
	out.openFile(argv[2]);
	out.setHeaderString("#VRML V2.0 utf8");
	SoWriteAction wra(&out);
	wra.apply(root);
	out.closeFile();

	root->unref();

	return EXIT_SUCCESS;
}

ext: cpp

max_stars_repo_name: Broekman/rl

max_issues_repo_name: jencureboy/rl

max_forks_repo_name: jencureboy/rl


text:
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

#include "stdafx.h"
#include "TestUtility.h"

using namespace std;
using namespace Common;
using namespace Reliability::LoadBalancingComponent;
using namespace PlacementAndLoadBalancingUnitTest;

#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"

wstring const ItemDelimiter = L",";
wstring const PairDelimiter = L"/";

StringLiteral const PLBTestSource("PLBTest");

Federation::NodeId PlacementAndLoadBalancingUnitTest::CreateNodeId(int id)
{
    return Federation::NodeId(Common::LargeInteger(0, id));
}

Federation::NodeInstance PlacementAndLoadBalancingUnitTest::CreateNodeInstance(int id, uint64 instance)
{
    return Federation::NodeInstance(CreateNodeId(id), instance);
}

Guid PlacementAndLoadBalancingUnitTest::CreateGuid(int i)
{
    return Guid(i, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}

int PlacementAndLoadBalancingUnitTest::GetNodeId(Federation::NodeId nodeId)
{
    return static_cast<int>(nodeId.IdValue.Low);
}

int PlacementAndLoadBalancingUnitTest::GetFUId(Guid fuId)
{
    return static_cast<int>(fuId.AsGUID().Data1);
}

vector<wstring> PlacementAndLoadBalancingUnitTest::GetActionListString(map<Guid, FailoverUnitMovement> const& actionList)
{
    vector<wstring> ret;

    for (auto const& actionPair : actionList)
    {
        vector<FailoverUnitMovement::PLBAction> const& allActions = actionPair.second.Actions;
        auto itMovePrimary = find_if(allActions.begin(), allActions.end(), [](FailoverUnitMovement::PLBAction action)
        {
            return action.Action == FailoverUnitMovementType::MovePrimary;
        });

        for (FailoverUnitMovement::PLBAction currentAction : allActions)
        {
            wstring result;
            StringWriter w(result);

            w.Write("{0} ", GetFUId(actionPair.first));

            switch (currentAction.Action)
            {
            case FailoverUnitMovementType::MoveInstance:

                w.Write("move instance {0}=>{1}", GetNodeId(currentAction.SourceNode), GetNodeId(currentAction.TargetNode));

                break;

            case FailoverUnitMovementType::MoveSecondary:
                if (itMovePrimary != allActions.end() &&
                    currentAction.SourceNode == itMovePrimary->TargetNode &&
                    currentAction.TargetNode == itMovePrimary->SourceNode)
                {
                    w.Write("swap primary {0}<=>{1}", GetNodeId(itMovePrimary->SourceNode), GetNodeId(itMovePrimary->TargetNode));
                    itMovePrimary = allActions.end();
                }
                else
                {
                    w.Write("move secondary {0}=>{1}", GetNodeId(currentAction.SourceNode), GetNodeId(currentAction.TargetNode));
                }

                break;

            case FailoverUnitMovementType::MovePrimary:
                result.clear();
                break;

            case FailoverUnitMovementType::SwapPrimarySecondary:
                w.Write("swap primary {0}<=>{1}", GetNodeId(currentAction.SourceNode), GetNodeId(currentAction.TargetNode));
                break;

            case FailoverUnitMovementType::AddPrimary:
                w.Write("add primary {0}", GetNodeId(currentAction.TargetNode));
                break;

            case FailoverUnitMovementType::AddSecondary:
                w.Write("add secondary {0}", GetNodeId(currentAction.TargetNode));
                break;

            case FailoverUnitMovementType::AddInstance:
                w.Write("add instance {0}", GetNodeId(currentAction.TargetNode));
                break;

            case FailoverUnitMovementType::RequestedPlacementNotPossible:
                w.Write("void movement on {0}", GetNodeId(currentAction.SourceNode));
                break;

            case FailoverUnitMovementType::DropPrimary:
                w.Write("drop primary {0}", GetNodeId(currentAction.SourceNode));
                break;

            case FailoverUnitMovementType::DropSecondary:
                w.Write("drop secondary {0}", GetNodeId(currentAction.SourceNode));
                break;

            case FailoverUnitMovementType::DropInstance:
                w.Write("drop instance {0}", GetNodeId(currentAction.SourceNode));
                break;

            case FailoverUnitMovementType::PromoteSecondary:
                w.Write("promote secondary {0}", GetNodeId(currentAction.TargetNode));
                break;

            default:
                Assert::CodingError("Unknown Replica Move Type");
                break;
            }

            if (!result.empty())
            {
                ret.push_back(result);
            }
        }

        if (itMovePrimary != allActions.end())
        {
            wstring result;
            StringWriter w(result);

            w.Write("{0} ", GetFUId(actionPair.first));

            w.Write("move primary");
            w.Write(" {0}=>{1}", GetNodeId(itMovePrimary->SourceNode), GetNodeId(itMovePrimary->TargetNode));

            ret.push_back(result);
        }
    }

    Trace.WriteInfo(PLBTestSource, "{0}", ret);

    return ret;
}

size_t PlacementAndLoadBalancingUnitTest::GetActionRawCount(map<Guid, FailoverUnitMovement> const& actionList)
{
    size_t sum = 0;
    for (auto it = actionList.begin(); it != actionList.end(); ++it)
    {
        sum += it->second.Actions.size();
    }
    return sum;
}

bool PlacementAndLoadBalancingUnitTest::ActionMatch(wstring const& expected, wstring const& actual)
{
    vector<wstring> expectedList;
    vector<wstring> actualList;

    StringUtility::Split<wstring>(expected, expectedList, wstring(L" =<>"));
    StringUtility::Split<wstring>(actual, actualList, wstring(L" =<>"));

    if (expectedList.size() != actualList.size())
    {
        return false;
    }

    for (size_t i = 0; i < expectedList.size(); ++i)
    {
        if (!OneOfMatch(expectedList[i], actualList[i]) &&
            expectedList[i] != L"*")
        {
            return false;
        }
    }

    return true;
}

bool PlacementAndLoadBalancingUnitTest::OneOfMatch(std::wstring const& expected, std::wstring const& actual)
{
    vector<wstring> expectedCandidates;
    StringUtility::Split<wstring>(expected, expectedCandidates, wstring(L"|"));

    bool match = false;
    for (size_t i = 0; i < expectedCandidates.size(); ++i)
    {
        if (expectedCandidates[i] == actual)
        {
            match = true;
            break;
        }
    }

    return match;
}

vector<ReplicaDescription> PlacementAndLoadBalancingUnitTest::CreateReplicas(wstring replicas, std::vector<bool>& isReplicaUp)
{
    StringCollection replicaSet;
    vector<ReplicaDescription> replicaDescription;
    StringUtility::Split<wstring>(replicas, replicaSet, ItemDelimiter);

    if (replicaSet.size() != isReplicaUp.size())
    {
        return replicaDescription;
    }

    for (int i = 0; i < replicaSet.size(); i++)
    {
        replicaDescription.push_back(CreateReplicas(replicaSet[i], isReplicaUp[i])[0]);
    }

    return replicaDescription;
}

vector<ReplicaDescription> PlacementAndLoadBalancingUnitTest::CreateReplicas(wstring replicas, bool isUp)
{
    vector<ReplicaDescription> replicaVector;

    // format [replica1], [replica2], ...
    // each replica: [replicaRole]/[nodeIndex]/[IsToBePromoted][IsMoveInProgress][IsToBeDropped][IsInBuild]
    // replicaRole: P or S or SB
    // the last three descriptions optional inputs: PDB; treated as false by default
    StringCollection placement;
    StringUtility::Split<wstring>(replicas, placement, ItemDelimiter);

    for (wstring const& replica : placement)
    {
        StringCollection replicaFields;
        StringUtility::Split<wstring>(replica, replicaFields, PairDelimiter);

        ReplicaRole::Enum role = ReplicaRole::None;
        Reliability::ReplicaStates::Enum state = Reliability::ReplicaStates::Ready;
        StringUtility::TrimSpaces(replicaFields[0]);

        if (replicaFields[0] == L"P")
        {
            role = ReplicaRole::Primary;
        }
        else if (replicaFields[0] == L"S" || replicaFields[0] == L"I")
        {
            role = ReplicaRole::Secondary;
        }
        else if (replicaFields[0] == L"N")
        {
            role = ReplicaRole::None;
        }
        else if (replicaFields[0] == L"SB")
        {
            role = ReplicaRole::StandBy;
            state = Reliability::ReplicaStates::StandBy;
        }
        else if (replicaFields[0] == L"D")
        {
            role = ReplicaRole::Dropped;
            state = Reliability::ReplicaStates::Dropped;
        }

        int nodeIndex = _wtoi(replicaFields[1].c_str());
        Reliability::ReplicaFlags::Enum flags = Reliability::ReplicaFlags::None;

        if (replicaFields.size() >= 3)
        {
            wstring properties = replica.substr(replicaFields[0].length() + replicaFields[1].length() + 2);

            if (StringUtility::Contains<wstring>(properties, L"B"))
            {
                state = Reliability::ReplicaStates::InBuild;
            }

            if (StringUtility::Contains<wstring>(properties, L"I"))
            {
                flags = static_cast<Reliability::ReplicaFlags::Enum>(flags ^ Reliability::ReplicaFlags::PrimaryToBeSwappedOut);
            }

            if (StringUtility::Contains<wstring>(properties, L"J"))
            {
                flags = static_cast<Reliability::ReplicaFlags::Enum>(flags ^ Reliability::ReplicaFlags::PrimaryToBePlaced);
            }

            if (StringUtility::Contains<wstring>(properties, L"K"))
            {
                flags = static_cast<Reliability::ReplicaFlags::Enum>(flags ^ Reliability::ReplicaFlags::ReplicaToBePlaced);
            }

            if (StringUtility::Contains<wstring>(properties, L"V"))
            {
                flags = static_cast<Reliability::ReplicaFlags::Enum>(flags ^ Reliability::ReplicaFlags::MoveInProgress);
            }

            if (StringUtility::Contains<wstring>(properties, L"D"))
            {
                flags = static_cast<Reliability::ReplicaFlags::Enum>(flags ^ Reliability::ReplicaFlags::ToBeDroppedByFM);
            }

            if (StringUtility::Contains<wstring>(properties, L"R"))
            {
                flags = static_cast<Reliability::ReplicaFlags::Enum>(flags ^ Reliability::ReplicaFlags::ToBeDroppedByPLB);
            }

            if (StringUtility::Contains<wstring>(properties, L"T"))
            {
                flags = static_cast<Reliability::ReplicaFlags::Enum>(flags ^ Reliability::ReplicaFlags::ToBeDroppedForNodeDeactivation);
            }

            if (StringUtility::Contains<wstring>(properties, L"P"))
            {
                flags = static_cast<Reliability::ReplicaFlags::Enum>(flags ^ Reliability::ReplicaFlags::ToBePromoted);
            }

            if (StringUtility::Contains<wstring>(properties, L"N"))
            {
                flags = static_cast<Reliability::ReplicaFlags::Enum>(flags ^ Reliability::ReplicaFlags::PendingRemove);
            }

            if (StringUtility::Contains<wstring>(properties, L"Z"))
            {
                flags = static_cast<Reliability::ReplicaFlags::Enum>(flags ^ Reliability::ReplicaFlags::Deleted);
            }

            if (StringUtility::Contains<wstring>(properties, L"L"))
            {
                flags = static_cast<Reliability::ReplicaFlags::Enum>(flags ^ Reliability::ReplicaFlags::PreferredPrimaryLocation);
            }

            if (StringUtility::Contains<wstring>(properties, L"E"))
            {
                flags = static_cast<Reliability::ReplicaFlags::Enum>(flags ^ Reliability::ReplicaFlags::EndpointAvailable);
            }

            if (StringUtility::Contains<wstring>(properties, L"M"))
            {
                flags = static_cast<Reliability::ReplicaFlags::Enum>(flags ^ Reliability::ReplicaFlags::PreferredReplicaLocation);
            }
        }

        replicaVector.push_back(ReplicaDescription(
            CreateNodeInstance(nodeIndex, 0),
            role,
            state,
            isUp,   // isUp
            flags));
    }

    return replicaVector;
}

vector<ServiceMetric> PlacementAndLoadBalancingUnitTest::CreateMetrics(wstring metrics)
{
    StringCollection metricCollection;
    StringUtility::Split<wstring>(metrics, metricCollection, ItemDelimiter);

    vector<ServiceMetric> metricList;
    for (wstring const& metricStr : metricCollection)
    {
        StringCollection metricProperties;
        StringUtility::Split<wstring>(metricStr, metricProperties, PairDelimiter);

        ASSERT_IFNOT(metricProperties.size() == 4, "Metric error");

        metricList.push_back(ServiceMetric(move(metricProperties[0]), Common::Double_Parse(metricProperties[1]), _wtoi(metricProperties[2].c_str()), _wtoi(metricProperties[3].c_str())));
    }

    return metricList;
}

map<wstring, uint> PlacementAndLoadBalancingUnitTest::CreateCapacities(std::wstring capacityStr)
{
    map<wstring, uint> capacities;
    if (!capacityStr.empty())
    {
        StringCollection capacityCollection;
        StringUtility::Split<wstring>(capacityStr, capacityCollection, ItemDelimiter);
        for (int i = 0; i < capacityCollection.size(); ++i)
        {
            StringCollection capacityPair;
            StringUtility::Split<wstring>(capacityCollection[i], capacityPair, PairDelimiter);

            ASSERT_IFNOT(capacityPair.size() == 2, "Capacity error");
            capacities.insert(make_pair(capacityPair[0], _wtoi(capacityPair[1].c_str())));
        }
    }

    return capacities;
}

map<wstring, ApplicationCapacitiesDescription> PlacementAndLoadBalancingUnitTest::CreateApplicationCapacities(wstring appCapacities)
{
    map<std::wstring, ApplicationCapacitiesDescription> capacityDesc;

    StringCollection capacityCollection;
    StringUtility::Split<wstring>(appCapacities, capacityCollection, ItemDelimiter);
    for (wstring const& metricStr : capacityCollection)
    {
        StringCollection metricProperties;
        StringUtility::Split<wstring>(metricStr, metricProperties, PairDelimiter);

        ASSERT_IFNOT(metricProperties.size() == 4, "CreateApplicationCapacities metric error");

        wstring metricName = metricProperties[0];
        capacityDesc.insert(make_pair(metricName,
            ApplicationCapacitiesDescription(move(metricProperties[0]), _wtoi(metricProperties[1].c_str()), _wtoi(metricProperties[2].c_str()), _wtoi(metricProperties[3].c_str()))));
    }

    return capacityDesc;
}

LoadOrMoveCostDescription PlacementAndLoadBalancingUnitTest::CreateLoadOrMoveCost(
    int failoverUnitId,
    wstring serviceName,
    wstring metricName,
    uint primaryLoad,
    uint secondaryLoad)
{
    vector<LoadMetric> primaryEntries, secondaryEntries;
    primaryEntries.push_back(LoadMetric(wstring(metricName), primaryLoad));
    secondaryEntries.push_back(LoadMetric(move(metricName), secondaryLoad));
    LoadOrMoveCostDescription load(CreateGuid(failoverUnitId), move(serviceName), true);
    StopwatchTime now = Stopwatch::Now();
    load.MergeLoads(ReplicaRole::Primary, move(primaryEntries), now);
    load.MergeLoads(ReplicaRole::Secondary, move(secondaryEntries), now, false);
    return load;
}

LoadOrMoveCostDescription PlacementAndLoadBalancingUnitTest::CreateLoadOrMoveCost(
    int failoverUnitId,
    wstring serviceName,
    wstring metricName,
    uint instanceLoad)
{
    vector<LoadMetric> entries;
    entries.push_back(LoadMetric(move(metricName), instanceLoad));
    LoadOrMoveCostDescription load(CreateGuid(failoverUnitId), move(serviceName), false);
    StopwatchTime now = Stopwatch::Now();
    load.MergeLoads(ReplicaRole::Secondary, move(entries), now);
    return load;
}

LoadOrMoveCostDescription PlacementAndLoadBalancingUnitTest::CreateLoadOrMoveCost(
    int failoverUnitId,
    std::wstring serviceName,
    std::wstring metricName,
    uint primaryLoad,
    std::map<Federation::NodeId, uint> const& secondaryLoads,
    bool isStateful)
{
    vector<LoadMetric> primaryEntries;
    primaryEntries.push_back(LoadMetric(wstring(metricName), primaryLoad));
    LoadOrMoveCostDescription load(CreateGuid(failoverUnitId), move(serviceName), isStateful);
    StopwatchTime now = Stopwatch::Now();
    if (isStateful)
    {
        load.MergeLoads(ReplicaRole::Primary, move(primaryEntries), now);
    }

    for (auto sIt = secondaryLoads.begin(); sIt != secondaryLoads.end(); sIt++)
    {
        vector<LoadMetric> secondaryEntries;
        secondaryEntries.push_back(LoadMetric(wstring(metricName), sIt->second));
        load.MergeLoads(ReplicaRole::Secondary, move(secondaryEntries), now, true, sIt->first);
    }

    return load;

}

NodeDescription PlacementAndLoadBalancingUnitTest::CreateNodeDescription(
    int nodeId,
    wstring fdPath,
    wstring ud,
    map<wstring, wstring> && nodeProperties,
    std::wstring capacityStr,
    bool isUp)
{
    NodeDescription::DomainId fdId = fdPath.empty() ?
        NodeDescription::DomainId() : Uri(*Reliability::LoadBalancingComponent::Constants::FaultDomainIdScheme, L"", fdPath).Segments;

    //add fdPath and ud as implicit properties
    map<wstring, wstring> nodePropertiesWithImplicitProperties(nodeProperties);

    if (!fdPath.empty())
    {
        Uri fdUri = Uri(*Reliability::LoadBalancingComponent::Constants::FaultDomainIdScheme, L"", fdPath);
        nodePropertiesWithImplicitProperties.insert(make_pair(*Reliability::LoadBalancingComponent::Constants::ImplicitFaultDomainId, fdUri.ToString()));
    }

    if (!ud.empty())
    {
        nodePropertiesWithImplicitProperties.insert(make_pair(*Reliability::LoadBalancingComponent::Constants::ImplicitUpgradeDomainId, ud));
    }

    return NodeDescription(
        CreateNodeInstance(nodeId, 0),
        isUp,
        Reliability::NodeDeactivationIntent::Enum::None,
        Reliability::NodeDeactivationStatus::Enum::None,
        move(nodePropertiesWithImplicitProperties),
        move(fdId),
        move(ud),
        map<wstring, uint>(),
        CreateCapacities(capacityStr));
}

NodeDescription PlacementAndLoadBalancingUnitTest::CreateNodeDescriptionWithCapacity(
    int nodeId,
    wstring capacityStr,
    bool isUp)
{
    return NodeDescription(CreateNodeInstance(nodeId, 0), isUp, Reliability::NodeDeactivationIntent::Enum::None, Reliability::NodeDeactivationStatus::Enum::None,
        map<wstring, wstring>(), NodeDescription::DomainId(), wstring(), map<wstring, uint>(), CreateCapacities(capacityStr));
}

Reliability::LoadBalancingComponent::NodeDescription PlacementAndLoadBalancingUnitTest::CreateNodeDescriptionWithResources(int nodeId,
    uint cpuCores,
    uint memoryInMegaBytes,
    std::map<std::wstring, std::wstring> && nodeProperties,
    std::wstring capacityStr,
    std::wstring ud,
    std::wstring fdPath,
    bool isUp)
{
    NodeDescription::DomainId fdId = fdPath.empty() ?
        NodeDescription::DomainId() : Uri(*Reliability::LoadBalancingComponent::Constants::FaultDomainIdScheme, L"", fdPath).Segments;

    std::map<wstring, uint> capacities = CreateCapacities(capacityStr);
    capacities.insert(make_pair(ServiceModel::Constants::SystemMetricNameCpuCores, cpuCores));
    capacities.insert(make_pair(ServiceModel::Constants::SystemMetricNameMemoryInMB, memoryInMegaBytes));

    return NodeDescription(CreateNodeInstance(nodeId, 0),
        isUp,
        Reliability::NodeDeactivationIntent::Enum::None,
        Reliability::NodeDeactivationStatus::Enum::None,
        move(nodeProperties),
        move(fdId),
        wstring(ud),
        map<wstring, uint>(),
        move(capacities));
}

NodeDescription PlacementAndLoadBalancingUnitTest::CreateNodeDescriptionWithPlacementConstraintAndCapacity(
    int nodeId,
    wstring capacityStr,
    map<wstring, wstring> && nodeProperties)
{
    map<wstring, wstring> nodePropertiesWithImplicitProperties(nodeProperties);

    return NodeDescription(CreateNodeInstance(nodeId, 0), true, Reliability::NodeDeactivationIntent::Enum::None, Reliability::NodeDeactivationStatus::Enum::None,
        move(nodePropertiesWithImplicitProperties), NodeDescription::DomainId(), wstring(), map<wstring, uint>(), CreateCapacities(capacityStr));
}

NodeDescription PlacementAndLoadBalancingUnitTest::CreateNodeDescriptionWithFaultDomainAndCapacity(
    int nodeId,
    wstring fdPath,
    wstring capacityStr,
    Reliability::NodeDeactivationIntent::Enum deactivationIntent,
    Reliability::NodeDeactivationStatus::Enum deactivationStatus
    )
{
    NodeDescription::DomainId fdId = fdPath.empty() ?
        NodeDescription::DomainId() : Uri(*Reliability::LoadBalancingComponent::Constants::FaultDomainIdScheme, L"", fdPath).Segments;

    //add fdPath and ud as implicit properties
    map<wstring, wstring> nodePropertiesWithImplicitProperties;

    if (!fdPath.empty())
    {
        Uri fdUri = Uri(*Reliability::LoadBalancingComponent::Constants::FaultDomainIdScheme, L"", fdPath);
        nodePropertiesWithImplicitProperties.insert(make_pair(*Reliability::LoadBalancingComponent::Constants::ImplicitFaultDomainId, fdUri.ToString()));
    }

    return NodeDescription(CreateNodeInstance(nodeId, 0), true, deactivationIntent, deactivationStatus,
        move(nodePropertiesWithImplicitProperties), move(fdId), wstring(), map<wstring, uint>(), CreateCapacities(capacityStr));
}

NodeDescription PlacementAndLoadBalancingUnitTest::CreateNodeDescriptionWithDomainsAndCapacity(
    int nodeId,
    std::wstring fdPath,
    std::wstring ud,
    std::wstring capacityStr,
    Reliability::NodeDeactivationIntent::Enum deactivationIntent,
    Reliability::NodeDeactivationStatus::Enum deactivationStatus
    )
{
    NodeDescription::DomainId fdId = fdPath.empty() ?
        NodeDescription::DomainId() : Uri(*Reliability::LoadBalancingComponent::Constants::FaultDomainIdScheme, L"", fdPath).Segments;

    map<wstring, uint> capacities = CreateCapacities(capacityStr);

    //add fdPath and ud as implicit properties
    map<wstring, wstring> nodePropertiesWithImplicitProperties;

    if (!fdPath.empty())
    {
        Uri fdUri = Uri(*Reliability::LoadBalancingComponent::Constants::FaultDomainIdScheme, L"", fdPath);
        nodePropertiesWithImplicitProperties.insert(make_pair(*Reliability::LoadBalancingComponent::Constants::ImplicitFaultDomainId, fdUri.ToString()));
    }

    return NodeDescription(CreateNodeInstance(nodeId, 0), true, deactivationIntent, deactivationStatus,
        move(nodePropertiesWithImplicitProperties), move(fdId), move(ud), map<wstring, uint>(), move(capacities));
}

ServicePackageDescription PlacementAndLoadBalancingUnitTest::CreateServicePackageDescription(
    ServiceModel::ServicePackageIdentifier servicePackageIdentifier,
    double cpuCores,
    uint memoryInBytes,
    std::vector<std::wstring>&& codePackages)
{
    map<std::wstring, double> requiredResources;

    if (cpuCores != 0 || memoryInBytes != 0)
    {
        requiredResources.insert(make_pair(ServiceModel::Constants::SystemMetricNameCpuCores, cpuCores));
        requiredResources.insert(make_pair(ServiceModel::Constants::SystemMetricNameMemoryInMB, memoryInBytes));
    }

    return ServicePackageDescription(ServiceModel::ServicePackageIdentifier(servicePackageIdentifier), move(requiredResources), move(codePackages));
}

ServicePackageDescription PlacementAndLoadBalancingUnitTest::CreateServicePackageDescription(
    std::wstring servicePackageName,
    std::wstring appTypeName,
    std::wstring applicationName,
    double cpuCores,
    uint memoryInBytes,
    ServiceModel::ServicePackageIdentifier & spId,
    std::vector<std::wstring>&& codePackages)
{
    spId = ServiceModel::ServicePackageIdentifier(ServiceModel::ApplicationIdentifier(appTypeName, 0), servicePackageName);

    return CreateServicePackageDescription(ServiceModel::ServicePackageIdentifier(spId), cpuCores, memoryInBytes, move(codePackages));
}

ServiceDescription PlacementAndLoadBalancingUnitTest::CreateServiceDescriptionWithServicePackage(
    wstring serviceName,
    wstring serviceTypeName,
    bool isStateful,
    ServiceModel::ServicePackageIdentifier & spId,
    std::vector<Reliability::LoadBalancingComponent::ServiceMetric> && metrics,
    bool isSharedServicePackage,
    wstring appName,
    wstring placementConstraint)
{
    auto servicePackageKind = ServiceModel::ServicePackageActivationMode::SharedProcess;
    if (!isSharedServicePackage)
    {
        servicePackageKind = ServiceModel::ServicePackageActivationMode::ExclusiveProcess;
    }
    if (appName == L"" && PLBConfig::GetConfig().UseAppGroupsInBoost)
    {
        return ServiceDescription(
            move(wstring(serviceName)),
            move(wstring(serviceTypeName)),
            wstring(L"fabric:/NastyApplication314"),
            isStateful,
            wstring(placementConstraint),
            wstring(L""),
            true,
            move(metrics),
            FABRIC_MOVE_COST_LOW,
            false,
            0,
            4,
            true,
            ServiceModel::ServicePackageIdentifier(spId),
            servicePackageKind);
    }
    else
    {
        return ServiceDescription(
            move(wstring(serviceName)),
            move(wstring(serviceTypeName)),
            wstring(appName),
            isStateful,
            wstring(placementConstraint),
            wstring(L""),
            true,
            move(metrics),
            FABRIC_MOVE_COST_LOW,
            false,
            0,
            4,
            true,
            ServiceModel::ServicePackageIdentifier(spId),
            servicePackageKind);
    }
}

ServiceDescription PlacementAndLoadBalancingUnitTest::CreateServiceDescription(
    wstring serviceName,
    wstring serviceTypeName,
    bool isStateful,
    vector<ServiceMetric> && metrics,
    uint defaultMoveCost,
    bool onEveryNode,
    int targetReplicaSetSize,
    bool hasPersistedState,
    ServiceModel::ServicePackageIdentifier spId,
    bool isShared)
{
    auto servicePackageKind = ServiceModel::ServicePackageActivationMode::SharedProcess;
    if (!isShared)
    {
        servicePackageKind = ServiceModel::ServicePackageActivationMode::ExclusiveProcess;
    }
    if (PLBConfig::GetConfig().UseAppGroupsInBoost)
    {
        return ServiceDescription(
            move(serviceName),
            move(serviceTypeName),
            wstring(L"fabric:/NastyApplication314"),
            isStateful,
            wstring(L""),
            wstring(L""),
            true,
            move(metrics),
            defaultMoveCost,
            onEveryNode,
            0,
            targetReplicaSetSize,
            hasPersistedState,
            ServiceModel::ServicePackageIdentifier(spId),
            servicePackageKind);
    }
    else
    {
        return ServiceDescription(
            move(serviceName),
            move(serviceTypeName),
            wstring(L""),
            isStateful,
            wstring(L""),
            wstring(L""),
            true,
            move(metrics),
            defaultMoveCost,
            onEveryNode,
            0,
            targetReplicaSetSize,
            hasPersistedState,
            ServiceModel::ServicePackageIdentifier(spId),
            servicePackageKind);
    }
}

ServiceDescription PlacementAndLoadBalancingUnitTest::CreateServiceDescriptionWithPartitionAndReplicaCount(wstring serviceName, wstring serviceTypeName, bool isStateful, int partitionCount, int replicaCount, vector<ServiceMetric> && metrics)
{
    if (PLBConfig::GetConfig().UseAppGroupsInBoost)
    {
        return ServiceDescription(move(serviceName), move(serviceTypeName), wstring(L"fabric:/NastyApplication314"), isStateful, wstring(L""), wstring(L""), true, move(metrics), FABRIC_MOVE_COST_LOW, false, partitionCount, replicaCount);
    }
    else
    {
        return ServiceDescription(move(serviceName), move(serviceTypeName), wstring(L""), isStateful, wstring(L""), wstring(L""), true, move(metrics), FABRIC_MOVE_COST_LOW, false, partitionCount, replicaCount);
    }
}

ServiceDescription PlacementAndLoadBalancingUnitTest::CreateServiceDescriptionWithAffinity(
    wstring serviceName,
    wstring serviceTypeName,
    bool isStateful,
    wstring affinitizedService,
    vector<ServiceMetric> && metrics,
    bool onEveryNode,
    int targetReplicaSetSize,
    bool hasPersistedState,
    bool allignedAffinity,
    ServiceModel::ServicePackageIdentifier spId,
    bool isShared)
{
    auto servicePackageKind = ServiceModel::ServicePackageActivationMode::SharedProcess;
    if (!isShared)
    {
        servicePackageKind = ServiceModel::ServicePackageActivationMode::ExclusiveProcess;
    }
    if (PLBConfig::GetConfig().UseAppGroupsInBoost)
    {
        return ServiceDescription(
            move(serviceName),
            move(serviceTypeName),
            wstring(L"fabric:/NastyApplication314"),
            isStateful,
            wstring(L""),
            move(affinitizedService),
            allignedAffinity,
            move(metrics),
            FABRIC_MOVE_COST_LOW,
            onEveryNode,
            0,
            targetReplicaSetSize,
            hasPersistedState,
            ServiceModel::ServicePackageIdentifier(spId),
            servicePackageKind);
    }
    else
    {
        return ServiceDescription(
            move(serviceName),
            move(serviceTypeName),
            wstring(L""),
            isStateful,
            wstring(L""),
            move(affinitizedService),
            allignedAffinity,
            move(metrics),
            FABRIC_MOVE_COST_LOW,
            onEveryNode,
            0,
            targetReplicaSetSize,
            hasPersistedState,
            ServiceModel::ServicePackageIdentifier(spId),
            servicePackageKind);
    }
}

ServiceDescription PlacementAndLoadBalancingUnitTest::CreateServiceDescriptionWithAffinityWithEmptyApplication(wstring serviceName, wstring serviceTypeName, bool isStateful, wstring affinitizedService, vector<ServiceMetric> && metrics)
{
    return ServiceDescription(move(serviceName), move(serviceTypeName), wstring(L""), isStateful, wstring(L""), move(affinitizedService), true, move(metrics), FABRIC_MOVE_COST_LOW, false);
}
ServiceDescription PlacementAndLoadBalancingUnitTest::CreateServiceDescriptionWithAffinityAndApplication(wstring serviceName, wstring serviceTypeName, bool isStateful,wstring applicationName, wstring affinitizedService, vector<ServiceMetric> && metrics)
{
    return ServiceDescription(move(serviceName), move(serviceTypeName), move(applicationName), isStateful, wstring(L""), move(affinitizedService), true, move(metrics), FABRIC_MOVE_COST_LOW, false);
}

ServiceDescription PlacementAndLoadBalancingUnitTest::CreateServiceDescriptionWithNonAlignedAffinity(
    wstring serviceName,
    wstring serviceTypeName,
    bool isStateful,
    wstring affinitizedService,
    vector<ServiceMetric> && metrics)
{
    if (PLBConfig::GetConfig().UseAppGroupsInBoost)
    {
        return ServiceDescription(move(serviceName), move(serviceTypeName), wstring(L"fabric:/NastyApplication314"), isStateful, wstring(L""), move(affinitizedService), false, move(metrics), FABRIC_MOVE_COST_LOW, false);
    }
    else
    {
        return ServiceDescription(move(serviceName), move(serviceTypeName), wstring(L""), isStateful, wstring(L""), move(affinitizedService), false, move(metrics), FABRIC_MOVE_COST_LOW, false);
    }
}

size_t PlacementAndLoadBalancingUnitTest::NumberOfDomains(vector<set<wstring>> const& metricNameSetVector)
{
    if (metricNameSetVector.size() < 2)
    {
        return metricNameSetVector.size();
    }
    set<wstring> metrics;
    set<wstring> applicationMetrics;
    map<wstring, int> metricDomainMap;
    map<int, set<wstring>> domainMetricMap;
    int currentNewDomain = 0;
    for (auto metricSet : metricNameSetVector)
    {
        set<int> domainIdsToBeMerged;
        //add metrics in that domain
        set<wstring> allMetricsToMerge(metricSet.begin(), metricSet.end());

        for (auto metricName : metricSet)
        {
            metrics.insert(metricName);
            if (metricDomainMap.find(metricName) != metricDomainMap.end())
            {
                domainIdsToBeMerged.insert(metricDomainMap[metricName]);
            }
        }

        // add all metrics to related domain if any
        for (int domainId : domainIdsToBeMerged)
        {
            auto domainMetricSet = domainMetricMap[domainId];
            allMetricsToMerge.insert(domainMetricSet.begin(), domainMetricSet.end());
            domainMetricMap.erase(domainMetricMap.find(domainId));
        }

        // update all metrics to a new domain
        for (auto metricName : allMetricsToMerge)
        {
            metricDomainMap[metricName] = currentNewDomain;
        }

        if (!allMetricsToMerge.empty())
        {
            domainMetricMap[currentNewDomain] = move(allMetricsToMerge);
        }
        currentNewDomain++;
    }

    return domainMetricMap.size();
}

ServiceDescription PlacementAndLoadBalancingUnitTest::CreateServiceDescriptionWithConstraint(
    wstring serviceName,
    wstring serviceTypeName,
    bool isStateful,
    wstring placementConstraint,
    vector<ServiceMetric> && metrics,
    bool isOnEveryNode,
    int targetReplicaSetSize)
{
    if (PLBConfig::GetConfig().UseAppGroupsInBoost)
    {
        return ServiceDescription(
            move(serviceName),
            move(serviceTypeName),
            wstring(L"fabric:/NastyApplication314"),
            isStateful,
            move(placementConstraint),
            wstring(L""),
            true,
            move(metrics),
            FABRIC_MOVE_COST_LOW,
            isOnEveryNode,
            0,
            targetReplicaSetSize,
            true);
    }
    else
    {
        return ServiceDescription(
            move(serviceName),
            move(serviceTypeName),
            wstring(L""),
            isStateful,
            move(placementConstraint),
            wstring(L""),
            true,
            move(metrics),
            FABRIC_MOVE_COST_LOW,
            isOnEveryNode,
            0,
            targetReplicaSetSize,
            true);
    }
}

ServiceDescription PlacementAndLoadBalancingUnitTest::CreateServiceDescriptionWithApplication(
    wstring serviceName,
    wstring serviceTypeName,
    wstring applicationName,
    bool isStateful,
    vector<ServiceMetric> && metrics,
    ServiceModel::ServicePackageIdentifier servicePackageIdentifier,
    bool isShared,
    int partitionCount)
{
    auto servicePackageKind = ServiceModel::ServicePackageActivationMode::SharedProcess;
    if (!isShared)
    {
        servicePackageKind = ServiceModel::ServicePackageActivationMode::ExclusiveProcess;
    }
    return ServiceDescription(move(serviceName), move(serviceTypeName), move(applicationName), isStateful, wstring(L""), wstring(L""),
        true, move(metrics), FABRIC_MOVE_COST_LOW, false, partitionCount, 0, true,
        ServiceModel::ServicePackageIdentifier(servicePackageIdentifier), servicePackageKind);
}

ServiceDescription PlacementAndLoadBalancingUnitTest::CreateServiceDescriptionWithEmptyApplication(
wstring serviceName,
wstring serviceTypeName,
bool isStateful,
vector<ServiceMetric> && metrics)
{
    return ServiceDescription(move(serviceName), move(serviceTypeName), wstring(L""), isStateful, wstring(L""), wstring(L""), true, move(metrics), FABRIC_MOVE_COST_LOW, false);
}

vector<Reliability::ServiceScalingPolicyDescription> PlacementAndLoadBalancingUnitTest::CreateAutoScalingPolicyForPartition(
    wstring metricName,
    double lowerLoadThreshold,
    double upperLoadThreshold,
    uint scaleIntervalInSeconds,
    long minInstanceCount,
    long maxInstanceCount,
    long scaleIncrement)
{
    vector<Reliability::ServiceScalingPolicyDescription> result;
    Reliability::ScalingMechanismSPtr mechanism = make_shared<Reliability::InstanceCountScalingMechanism>(minInstanceCount, maxInstanceCount, scaleIncrement);
    Reliability::ScalingTriggerSPtr trigger = make_shared<Reliability::AveragePartitionLoadScalingTrigger>(metricName, lowerLoadThreshold, upperLoadThreshold, scaleIntervalInSeconds);
    result.push_back(Reliability::ServiceScalingPolicyDescription(trigger, mechanism));
    return result;
}

vector<Reliability::ServiceScalingPolicyDescription> PlacementAndLoadBalancingUnitTest::CreateAutoScalingPolicyForService(
    wstring metricName,
    double lowerLoadThreshold,
    double upperLoadThreshold,
    uint scaleIntervalInSeconds,
    long minPartitionCount,
    long maxPartitionCount,
    long scaleIncrement,
    bool useOnlyPrimaryLoad)
{
    vector<Reliability::ServiceScalingPolicyDescription> result;
    Reliability::ScalingMechanismSPtr mechanism = make_shared<Reliability::AddRemoveIncrementalNamedPartitionScalingMechanism>(minPartitionCount, maxPartitionCount, scaleIncrement);
    Reliability::ScalingTriggerSPtr trigger = make_shared<Reliability::AverageServiceLoadScalingTrigger>(metricName, lowerLoadThreshold, upperLoadThreshold, scaleIntervalInSeconds, useOnlyPrimaryLoad);
    result.push_back(Reliability::ServiceScalingPolicyDescription(trigger, mechanism));
    return result;
}

ServiceDescription PlacementAndLoadBalancingUnitTest::CreateServiceDescriptionWithAutoscalingPolicy(
    wstring serviceName,
    wstring serviceTypeName,
    bool isStateful,
    int targetReplicaSetSize,
    vector<Reliability::ServiceScalingPolicyDescription> && scalingPolicies,
    vector<ServiceMetric> && metrics,
    int partitionCount)
{
    if (PLBConfig::GetConfig().UseAppGroupsInBoost)
    {
        return ServiceDescription(
            move(serviceName),
            move(serviceTypeName),
            wstring(L"fabric:/NastyApplication314"),
            isStateful,
            wstring(L""),
            wstring(L""),
            true,
            move(metrics),
            FABRIC_MOVE_COST_LOW,
            false,
            partitionCount,
            targetReplicaSetSize,
            true,
            ServiceModel::ServicePackageIdentifier(),
            ServiceModel::ServicePackageActivationMode::ExclusiveProcess,
            0,
            move(scalingPolicies));
    }
    else
    {
        return ServiceDescription(
            move(serviceName),
            move(serviceTypeName),
            wstring(L""),
            isStateful,
            wstring(L""),
            wstring(L""),
            true,
            move(metrics),
            FABRIC_MOVE_COST_LOW,
            false,
            partitionCount,
            targetReplicaSetSize,
            true,
            ServiceModel::ServicePackageIdentifier(),
            ServiceModel::ServicePackageActivationMode::ExclusiveProcess,
            0,
            move(scalingPolicies));
    }
}

ApplicationDescription PlacementAndLoadBalancingUnitTest::CreateApplicationDescriptionWithCapacities(
    wstring applicationName,
    int scaleoutCount,
    map<std::wstring, ApplicationCapacitiesDescription> && capacities,
    std::vector<ServicePackageDescription> servicePackages,
    std::wstring appTypeName)
{
    map<ServiceModel::ServicePackageIdentifier, ServicePackageDescription> packageMap;

    ServiceModel::ApplicationIdentifier appId(appTypeName, 0);
    for (auto const& sp : servicePackages)
    {
        ServiceModel::ServicePackageIdentifier spId(appId, sp.Name);
        packageMap.insert(make_pair(spId, sp));
    }

    return ApplicationDescription(move(applicationName), move(capacities), 0, scaleoutCount, move(packageMap));
}

ApplicationDescription PlacementAndLoadBalancingUnitTest::CreateApplicationDescriptionWithCapacities(
    wstring applicationName,
    int minimalCount,
    int scaleoutCount,
    map<std::wstring, ApplicationCapacitiesDescription> && capacities,
    bool isUpgradeInProgress,
    std::set<std::wstring> && completedUDs)
{
    return ApplicationDescription(
        move(applicationName),
        move(capacities),
        minimalCount,
        scaleoutCount,
        move(map<ServiceModel::ServicePackageIdentifier, ServicePackageDescription>()),
        move(map<ServiceModel::ServicePackageIdentifier, ServicePackageDescription>()),
        isUpgradeInProgress,
        move(completedUDs));
}

ApplicationDescription PlacementAndLoadBalancingUnitTest::CreateApplicationWithServicePackages(
    std::wstring appTypeName,
    std::wstring appName,
    std::vector<ServicePackageDescription> servicePackages,
    std::vector<ServicePackageDescription> servicePackagesUpgrading)
{
    map<ServiceModel::ServicePackageIdentifier, ServicePackageDescription> packageMap1;

    ServiceModel::ApplicationIdentifier appId(appTypeName, 0);
    for (auto const& sp : servicePackages)
    {
        ServiceModel::ServicePackageIdentifier spId(appId, sp.Name);
        packageMap1.insert(make_pair(spId, sp));
    }

    map<ServiceModel::ServicePackageIdentifier, ServicePackageDescription> packageMap2;
    for (auto const& sp : servicePackagesUpgrading)
    {
        ServiceModel::ServicePackageIdentifier spId(appId, sp.Name);
        packageMap2.insert(make_pair(spId, sp));
    }

    bool isUpgrading = false;
    if (packageMap2.size() > 0)
    {
        isUpgrading = true;
    }
    return ApplicationDescription(move(appName), map<std::wstring, ApplicationCapacitiesDescription>(), 0, 0, move(packageMap1), move(packageMap2), isUpgrading, std::set<wstring> (), appId);
}

ApplicationDescription PlacementAndLoadBalancingUnitTest::CreateApplicationWithServicePackagesAndCapacity(
    std::wstring appTypeName,
    std::wstring appName,
    int minimumCount,
    int scaleoutCount,
    map<std::wstring, ApplicationCapacitiesDescription> && capacities,
    std::vector<ServicePackageDescription> servicePackages,
    std::vector<ServicePackageDescription> servicePackagesUpgrading)
{
    map<ServiceModel::ServicePackageIdentifier, ServicePackageDescription> packageMap1;

    ServiceModel::ApplicationIdentifier appId(appTypeName, 0);
    for (auto const& sp : servicePackages)
    {
        ServiceModel::ServicePackageIdentifier spId(appId, sp.Name);
        packageMap1.insert(make_pair(spId, sp));
    }

    map<ServiceModel::ServicePackageIdentifier, ServicePackageDescription> packageMap2;
    for (auto const& sp : servicePackagesUpgrading)
    {
        ServiceModel::ServicePackageIdentifier spId(appId, sp.Name);
        packageMap2.insert(make_pair(spId, sp));
    }

    bool isUpgrading = false;
    if (packageMap2.size() > 0)
    {
        isUpgrading = true;
    }
    return ApplicationDescription(move(appName), move(capacities), minimumCount, scaleoutCount, move(packageMap1), move(packageMap2), isUpgrading, std::set<wstring>(), appId);
}

void PlacementAndLoadBalancingUnitTest::VerifyPLBAction(Reliability::LoadBalancingComponent::PlacementAndLoadBalancing & plb, std::wstring const& action, std::wstring const & metricName)
{
    ServiceModel::ClusterLoadInformationQueryResult loadInformationResult;
    ErrorCode retValue = plb.GetClusterLoadInformationQueryResult(loadInformationResult);
    VERIFY_ARE_EQUAL(ErrorCodeValue::Success, retValue.ReadValue());
    for (auto loadMetricInfo : loadInformationResult.LoadMetric)
    {
        if (loadMetricInfo.Name == metricName || metricName == L"")
        {
            if (loadMetricInfo.Action == action) return;
        }
    }
    VERIFY_FAIL(wformatString("No Match for action {0}", action).c_str());
}

void PlacementAndLoadBalancingUnitTest::GetClusterLoadMetricInformation(
    Reliability::LoadBalancingComponent::PlacementAndLoadBalancing & plb,
    ServiceModel::LoadMetricInformation& loadMetricInfo,
    std::wstring metricName)
{
    ServiceModel::ClusterLoadInformationQueryResult queryResult;
    ErrorCode result = plb.GetClusterLoadInformationQueryResult(queryResult);
    VERIFY_ARE_EQUAL(ErrorCodeValue::Success, result.ReadValue());

    for (auto itMetric = queryResult.LoadMetric.begin(); itMetric != queryResult.LoadMetric.end(); ++itMetric)
    {
        if (itMetric->Name == metricName)
        {
            loadMetricInfo = *itMetric;
            return;
        }
    }

    VERIFY_FAIL(L"Metric is not present in the result, fail the test");
}

void PlacementAndLoadBalancingUnitTest::GetNodeLoadMetricInformation(
    Reliability::LoadBalancingComponent::PlacementAndLoadBalancing & plb,
    ServiceModel::NodeLoadMetricInformation& nodeLoadMetricInfo,
    int nodeIndex,
    std::wstring const& metricName)
{
    ServiceModel::NodeLoadInformationQueryResult queryResult;
    ErrorCode retValue = plb.GetNodeLoadInformationQueryResult(CreateNodeId(nodeIndex), queryResult);
    VERIFY_ARE_EQUAL(ErrorCodeValue::Success, retValue.ReadValue());

    for (auto itMetric = queryResult.NodeLoadMetricInformation.begin(); itMetric != queryResult.NodeLoadMetricInformation.end(); ++itMetric)
    {
        if (itMetric->Name == metricName)
        {
            nodeLoadMetricInfo =  *itMetric;
            return;
        }
    }

    VERIFY_FAIL(L"Metric is not present in the result, fail the test");
}

void PlacementAndLoadBalancingUnitTest::VerifyCapacity(
    ServiceModel::ClusterLoadInformationQueryResult & queryResult,
    std::wstring metricName,
    uint expectedValue)
{
    for (auto itMetric = queryResult.LoadMetric.begin(); itMetric != queryResult.LoadMetric.end(); ++itMetric)
    {
        if (itMetric->Name == metricName)
        {
            VERIFY_ARE_EQUAL(itMetric->ClusterCapacity, expectedValue);
            return;
        }
    }

    VERIFY_FAIL(L"Metric is not present in the result, fail the test");
}

void PlacementAndLoadBalancingUnitTest::VerifyLoad(
    ServiceModel::ClusterLoadInformationQueryResult & queryResult,
    std::wstring metricName,
    uint expectedValue)
{
    for (auto itMetric = queryResult.LoadMetric.begin(); itMetric != queryResult.LoadMetric.end(); ++itMetric)
    {
        if (itMetric->Name == metricName)
        {
            VERIFY_ARE_EQUAL(itMetric->ClusterLoad, expectedValue);
            return;
        }
    }

    VERIFY_FAIL(L"Metric is not present in the result, fail the test");
}

void PlacementAndLoadBalancingUnitTest::VerifyLoad(
    ServiceModel::ClusterLoadInformationQueryResult & queryResult,
    std::wstring metricName,
    uint expectedValue,
    bool expectedIsCapacityViolation)
{
    for (auto itMetric : queryResult.LoadMetric)
    {
        if (itMetric.Name == metricName)
        {
            VERIFY_ARE_EQUAL(itMetric.ClusterLoad, expectedValue);
            VERIFY_ARE_EQUAL(itMetric.IsClusterCapacityViolation, expectedIsCapacityViolation);
            return;
        }
    }

    VERIFY_FAIL(L"Metric is not present in the result, fail the test");
}

void PlacementAndLoadBalancingUnitTest::VerifyClusterLoadDouble(
    ServiceModel::ClusterLoadInformationQueryResult & queryResult,
    std::wstring metricName,
    uint expectedValue,
    double expectedValueD,
    uint expectedCapacity,
    uint expectedRemaining,
    double expectedRemainingD,
    bool expectedIsCapacityViolation)
{
    for (auto itMetric : queryResult.LoadMetric)
    {
        if (itMetric.Name == metricName)
        {
            VERIFY_ARE_EQUAL(itMetric.ClusterLoad, expectedValue);
            VERIFY_ARE_EQUAL(itMetric.RemainingUnbufferedCapacity, expectedRemaining);
            VERIFY_ARE_EQUAL(itMetric.ClusterCapacity, expectedCapacity);
            VERIFY_ARE_EQUAL(itMetric.IsClusterCapacityViolation, expectedIsCapacityViolation);
            double diff = abs(expectedValueD - itMetric.CurrentClusterLoad);
            VERIFY_IS_TRUE(diff < 0.000001);
            diff = abs(expectedRemainingD - itMetric.ClusterCapacityRemaining);
            VERIFY_IS_TRUE(diff < 0.000001);
            return;
        }
    }

    VERIFY_FAIL(L"Metric is not present in the result, fail the test");
}

void PlacementAndLoadBalancingUnitTest::VerifyNodeLoadQuery(
    Reliability::LoadBalancingComponent::PlacementAndLoadBalancing & plb,
    int nodeIndex,
    std::wstring const& metricName,
    std::vector<uint> const & expectedValues,
    bool metricMustBePresent)
{
    ServiceModel::NodeLoadInformationQueryResult queryResult;
    ErrorCode retValue = plb.GetNodeLoadInformationQueryResult(CreateNodeId(nodeIndex), queryResult);
    VERIFY_ARE_EQUAL(ErrorCodeValue::Success, retValue.ReadValue());

    for (auto itMetric = queryResult.NodeLoadMetricInformation.begin(); itMetric != queryResult.NodeLoadMetricInformation.end(); ++itMetric)
    {
        if (itMetric->Name == metricName)
        {
            for (uint expected : expectedValues)
            {
                if (itMetric->NodeLoad == expected)
                {
                    return;
                }
            }
            VERIFY_FAIL(wformatString("Metric load for metric {0} ({1}) on node {2} does not match any of the expected values ({3})",
                metricName,
                itMetric->NodeLoad,
                nodeIndex,
                expectedValues
                ).c_str());
        }
    }
    if (metricMustBePresent)
    {
        VERIFY_FAIL(wformatString("Metric {0} is not present in the result for node {1}",
            metricName,
            nodeIndex).c_str());
    }
}

void PlacementAndLoadBalancingUnitTest::VerifyNodeLoadQuery(
    Reliability::LoadBalancingComponent::PlacementAndLoadBalancing & plb,
    int nodeIndex,
    std::wstring const& metricName,
    uint expectedValue,
    bool metricMustBePresent)
{
    std::vector<uint> expectedValues;
    expectedValues.push_back(expectedValue);
    VerifyNodeLoadQuery(plb, nodeIndex, metricName, expectedValues, metricMustBePresent);
}

void PlacementAndLoadBalancingUnitTest::VerifyNodeLoadQueryWithDoubleValues(
    Reliability::LoadBalancingComponent::PlacementAndLoadBalancing & plb,
    int nodeIndex,
    std::wstring const& metricName,
    uint expectedValue,
    double expectedValueD,
    uint remainingCapacity,
    double remainingCapacityD)
{
    ServiceModel::NodeLoadInformationQueryResult queryResult;
    ErrorCode retValue = plb.GetNodeLoadInformationQueryResult(CreateNodeId(nodeIndex), queryResult);
    VERIFY_ARE_EQUAL(ErrorCodeValue::Success, retValue.ReadValue());

    for (auto itMetric = queryResult.NodeLoadMetricInformation.begin(); itMetric != queryResult.NodeLoadMetricInformation.end(); ++itMetric)
    {
        if (itMetric->Name == metricName)
        {
            VERIFY_ARE_EQUAL(itMetric->NodeLoad, expectedValue);
            VERIFY_ARE_EQUAL(itMetric->NodeRemainingCapacity, remainingCapacity);
            double diff = abs(itMetric->CurrentNodeLoad - expectedValueD);
            VERIFY_IS_TRUE(diff < 0.000001);
            diff = abs(itMetric->NodeCapacityRemaining - remainingCapacityD);
            VERIFY_IS_TRUE(diff < 0.000001);
            return;
        }
    }
    VERIFY_FAIL(wformatString("Metric {0} is not present in the result for node {1}",
        metricName,
        nodeIndex).c_str());
}

void PlacementAndLoadBalancingUnitTest::VerifyNodeCapacity(
    Reliability::LoadBalancingComponent::PlacementAndLoadBalancing & plb,
    int nodeIndex,
    std::wstring const& metricName,
    uint expectedValue)
{
    ServiceModel::NodeLoadInformationQueryResult queryResult;
    ErrorCode retValue = plb.GetNodeLoadInformationQueryResult(CreateNodeId(nodeIndex), queryResult);
    VERIFY_ARE_EQUAL(ErrorCodeValue::Success, retValue.ReadValue());

    for (auto itMetric = queryResult.NodeLoadMetricInformation.begin(); itMetric != queryResult.NodeLoadMetricInformation.end(); ++itMetric)
    {
        if (itMetric->Name == metricName)
        {
            if (itMetric->NodeCapacity == expectedValue)
            {
                return;
            }

            VERIFY_FAIL(wformatString("Metric capacity for metric {0} ({1}) on node {2} does not match the expected value ({3})",
                metricName,
                itMetric->NodeLoad,
                nodeIndex,
                expectedValue
            ).c_str());
        }
    }

    VERIFY_FAIL(wformatString("Metric {0} is not present in the result for node {1}",
        metricName,
        nodeIndex).c_str());

}

void PlacementAndLoadBalancingUnitTest::VerifyApplicationLoadQuery(
    ServiceModel::ApplicationLoadInformationQueryResult queryResult,
    std::wstring metricName,
    uint expectedValue)
{
    for (auto metricResult : queryResult.ApplicationLoadMetricInformation)
    {
        if (metricResult.Name == metricName)
        {
            VERIFY_ARE_EQUAL(metricResult.ApplicationLoad, expectedValue);
            return;
        }
    }
    VERIFY_FAIL(L"Metric is not present in the result, fail the test");
}

max_stars_repo_name: gridgentoo/ServiceFabricAzure

max_issues_repo_name: gridgentoo/ServiceFabricAzure

max_forks_repo_name: gridgentoo/ServiceFabricAzure


text:
#pragma once

#include <Eigen/Dense>
#include <vector>

class LinearModel
{
public:
    virtual Eigen::MatrixXd get_A(const std::vector<double>& x, const std::vector<double>& control) = 0;
    virtual Eigen::MatrixXd get_B(const std::vector<double>& x, const std::vector<double>& control) = 0;
    virtual Eigen::MatrixXd get_Xdot(const std::vector<double>& x, const std::vector<double>& control) = 0;
    static std::vector<double> flatten_matrix(Eigen::MatrixXd matrix);
    LinearModel(/* args */);
};

max_stars_repo_name: mahilab/mahi-mpc

max_issues_repo_name: mahilab/mahi-mpc

max_forks_repo_name: mahilab/mahi-mpc


text:
#include <fstream>
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include "VMD.h"
#include "smooth_reduce.h"

using namespace std;
namespace opt = boost::program_options;

void usage(char *prog, opt::options_description desc)
{
  cout << "usage: " << prog << " [options] input.vmd output.vmd" << endl;
  cout << desc << endl;
}

int main(int argc, char *argv[])
{
  opt::options_description desc("options");
  desc.add_options()
    ("help", "help message")
    ("cutoff", opt::value<float>(), "cutoff frequency [Hz]")
    ("th_pos", opt::value<float>(), "threshold(position) for keyframe reduction")
    ("th_rot", opt::value<float>(), "threshold(rotation) for keyframe reduction [degree]")
    ("th_morph", opt::value<float>(), "threshold(morph) for keyframe reduction")
    ("fps_in", opt::value<float>(), "frame rate of input-file")
    ("fps_out", opt::value<float>(), "frame rate of input-file")
    ("bezier", opt::bool_switch()->default_value(false), "bezier curve interpolation")
    ;

  opt::options_description hidden("hidden options");
  hidden.add_options()
    ("input-file", opt::value<string>(), "input VMD file")
    ("output-file", opt::value<string>(), "output VMD file")
    ;

  opt::options_description all_options;
  all_options.add(desc).add(hidden);

  opt::positional_options_description p;
  opt::variables_map vm;

  string fname_in;
  string fname_out;
  float cutoff_freq = 5.0; // [Hz]
  float threshold_pos = 0.5;
  float threshold_rot = 3.0; // [degree]
  float threshold_morph = 0.1; // 0-1
  float fps_in = 30.0;
  float fps_out = 30.0;
  bool bezier = false;

  try {
    p.add("input-file", 1);
    p.add("output-file", 1);
    opt::store(opt::command_line_parser(argc, argv).
	       options(all_options).positional(p).run(), vm);
    opt::notify(vm);

    if (vm.count("help") || !vm.count("input-file") || !vm.count("output-file")) {
      usage(argv[0], desc);
      return 1;
    }
    if (vm.count("cutoff")) {
      cutoff_freq = vm["cutoff"].as<float>();
    }
    if (vm.count("th_pos")) {
      threshold_pos = vm["th_pos"].as<float>();
    }
    if (vm.count("th_rot")) {
      threshold_rot = vm["th_rot"].as<float>();
    }
    if (vm.count("th_morph")) {
      threshold_morph = vm["th_morph"].as<float>();
    }
    if (vm.count("fps_in")) {
      fps_in = vm["fps_in"].as<float>();
    }
    if (vm.count("fps_out")) {
      fps_out = vm["fps_out"].as<float>();
    }
    if (vm.count("bezier")) {
      bezier = vm["bezier"].as<bool>();
    }
    fname_in = vm["input-file"].as<string>();
    fname_out = vm["output-file"].as<string>();
  } catch (exception& e) {
    cerr << e.what() << endl;
    return 1;
  }
  cout << "input file: " << fname_in << endl;
  cout << "output file: " << fname_out << endl;
  cout << "cutoff:" << cutoff_freq << endl;
  cout << "threshold(position): " << threshold_pos << endl;
  cout << "threshold(rotation): " << threshold_rot << endl;
  cout << "threshold(morph): " << threshold_morph << endl;
  cout << "fps_in: " << fps_in << endl;
  cout << "fps_out: " << fps_out << endl;

  ifstream in(fname_in, ios::binary);
  VMD v;
  v.input(in);
  in.close();

  bool success;
  success = smooth_and_reduce(v, cutoff_freq, threshold_pos, threshold_rot, threshold_morph,
                              fps_in, fps_out, bezier);
  if (! success) {
    return 1;
  }

  ofstream out(fname_out, ios::binary);
  v.output(out);
  out.close();

  return 0;
}

ext: cc

max_stars_repo_name: AotoKaburaki/Reborn

max_issues_repo_name: AotoKaburaki/Reborn

max_forks_repo_name: AotoKaburaki/Reborn


text:
//          Copyright Gavin Band 2008 - 2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef QCTOOL_MISSINGNESS_HETEROZYGOSITY_COMPUTATION_HPP
#define QCTOOL_MISSINGNESS_HETEROZYGOSITY_COMPUTATION_HPP

#include <Eigen/Core>
#include <boost/optional.hpp>
#include "components/SampleSummaryComponent/SampleSummaryComputation.hpp"

namespace sample_stats {
	struct MissingnessHeterozygosityComputation: public SampleSummaryComputation
	{
		MissingnessHeterozygosityComputation() ;
		MissingnessHeterozygosityComputation( genfile::Chromosome ) ;
		void accumulate( genfile::VariantIdentifyingData const&, Genotypes const&, genfile::VariantDataReader& ) ;
		void compute( int sample, ResultCallback ) ;
		std::string get_summary( std::string const& prefix = "", std::size_t column_width = 20 ) const ;
	private:
		boost::optional< genfile::Chromosome > const m_chromosome ;
		std::size_t m_snp_index ;
		double m_threshhold ;
		Eigen::VectorXd m_ones ;
		Eigen::VectorXd m_total_probabilities ;
		Eigen::VectorXd m_total_calls ;
		Eigen::VectorXd m_het_snps ;
		Eigen::VectorXd m_het_snp_calls ;
	} ;
}

#endif

max_stars_repo_name: CreRecombinase/qctool

max_issues_repo_name: CreRecombinase/qctool

max_forks_repo_name: gavinband/qctool


text:
/**
 * @brief Main file for HDF5 to GeoTIFF or BSQ to HDF5 conversion.
 * @author ndettmer <ndettmer@uos.de>
 */

#include "lvr2/io/HDF5IO.hpp"

#include <boost/range/iterator_range.hpp>
#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>

#include <string>
#include <fstream>

#include <sys/stat.h>

#include "lvr2/io/GeoTIFFIO.hpp"
#include "Options.hpp"

using namespace lvr2;

/**
 * @brief Extraction of radiometric data from a given HDF5 file into a new GeoTIFF file in (optionally) given output path
 * @param input_filename Path to the input HDF5 file formatted due to lvr_2 convention
 * @param position_code 5 character code of the scan position (e.g. 00000)
 * @param output_filename Path to the output GeoTIFF file
 * @param min_channel lowest channel to be extracted
 * @param max_channel highest channel to be extracted
 * @return standard C++ return value
 */
int processConversion(std::string input_filename,
        std::string position_code, std::string output_filename, size_t min_channel, size_t max_channel)
{
    /*------------------- HDF5 INPUT ------------------------*/
    HDF5IO hdf5(input_filename, false);
    std::vector<size_t> dim;

    // extract radiometric data
    std::string groupname = "raw/spectral/position_" + position_code;
    std::string datasetname = "spectral";
    boost::shared_array<uint16_t> spectrals = hdf5.getArray<uint16_t>(groupname, datasetname, dim);

    // extract array dimension information
    size_t num_channels = dim[0];
    size_t num_rows = dim[1];
    size_t num_cols = dim[2];

    // set upper boundary
    if(num_channels < max_channel)
    {
        std::cout << "The dataset has only " << num_channels << " channels. Using this as upper boundary." << std::endl;
        max_channel = num_channels;
    }
    num_channels = max_channel - min_channel;

    GeoTIFFIO gtifio(output_filename, num_cols, num_rows, num_channels);

    /*--------------- FILE CONVERSION --------------------*/
    // for each channel create a cv::Mat containing the spectral intensity data for the channel ...
    for(size_t channel = 0; channel < num_channels; channel++)
    {
        cv::Mat *mat = new cv::Mat(num_rows, num_cols, CV_16UC1);
        for(size_t row = 0; row < num_rows; row++)
        {
            for(size_t col = 0; col < num_cols; col++)
            {
                mat->at<uint16_t>(row, col) = spectrals.get()[(channel + min_channel) * num_cols * num_rows + row * num_cols + col];
            }
        }
        // ... and write it to the output GeoTIFF file
        int ret = gtifio.writeBand(mat, channel + 1);
        delete mat;
        if (ret != 0)
        {
            return ret;
        }
    }
    return 0;
}

int main(int argc, char**argv)
{
    hdf5togeotiff::Options options(argc, argv);

    /*--------------- GET PROGRAM OPTIONS --------------------*/

    boost::filesystem::path input_filename(options.getH5File());
    std::string input_extension = boost::filesystem::extension(input_filename);

    boost::filesystem::path output_filename(options.getGTIFFFile());
    std::string  output_extension = boost::filesystem::extension(output_filename);

    size_t min_channel = options.getMinChannel();
    size_t max_channel = options.getMaxChannel();

    std::string position_code = options.getPositionCode();

    /*---------------- PREPARE CONVERSION -------------------*/

    boost::filesystem::path output_dir = output_filename.parent_path();
    if (output_dir != "" && !boost::filesystem::exists(output_dir))
    {
        boost::filesystem::create_directory(output_dir);
    }

    std::cout << "Starting conversion..." <<  std::endl;
    if (processConversion(input_filename.string(), position_code, output_filename.string(), min_channel, max_channel) < 0)
    {
        std::cout << "An Error occurred during conversion." << std::endl;
    }

    return 0;
}

max_stars_repo_name: uos/lvr

max_issues_repo_name: uos/lvr

max_forks_repo_name: uos/lvr


text:
#include <pipeline/pipeline.hpp>
#include <pipeline/args.hpp>

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE pipeline_tests

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

using namespace pipeline;

struct Data {
    static int m_mut_call;
    static int m_const_call;

    static int m_def_constructor;
    static int m_copy_constructor;
    static int m_move_constructor;

    static int m_arg_value;

    static void clear() {
        m_mut_call = 0;
        m_const_call = 0;

        m_def_constructor = 0;
        m_copy_constructor = 0;
        m_move_constructor = 0;

        m_arg_value = 0;
    }

    Data() { ++m_def_constructor; }
    Data(const Data&) { ++m_copy_constructor; }
    Data(Data&&) { ++m_move_constructor; }

    const Data& constWithArg(int num = 1) const {
        ++m_const_call;
        m_arg_value = num;
        return *this;
    }

    Data& mutWithArg(int num = 1) {
        ++m_mut_call;
        m_arg_value = num;
        return *this;
    }

    void constWithoutArgs() const {
        ++m_const_call;
    }

    void mutWithoutArgs() {
        ++m_mut_call;
    }
};

int Data::m_mut_call;
int Data::m_const_call;

int Data::m_def_constructor;
int Data::m_copy_constructor;
int Data::m_move_constructor;

int Data::m_arg_value;

static int m_func_call;

void func_const(const Data&) {
    ++m_func_call;
}

void func_mut(Data&) {
    ++m_func_call;
}

template <class T>
void templ_func(T&) {
    ++m_func_call;
}

BOOST_AUTO_TEST_CASE(test_const_func) {
    Data::clear();

    Data mut_data;
    const Data const_data;

    auto mut_f = pipe_op(func_const);
    BOOST_CHECK(!std::is_const<decltype(mut_f)>::value);

    const auto const_f = pipe_op(func_const);
    BOOST_CHECK(std::is_const<decltype(const_f)>::value);

    m_func_call = 0;
    mut_data | mut_f;
    BOOST_CHECK_EQUAL(m_func_call, 1);

    m_func_call = 0;
    mut_data | const_f;
    BOOST_CHECK_EQUAL(m_func_call, 1);

    m_func_call = 0;
    const_data | mut_f;
    BOOST_CHECK_EQUAL(m_func_call, 1);

    m_func_call = 0;
    const_data | const_f;
    BOOST_CHECK_EQUAL(m_func_call, 1);

    BOOST_CHECK_EQUAL(Data::m_def_constructor, 2);
    BOOST_CHECK_EQUAL(Data::m_copy_constructor, 0);
    BOOST_CHECK_EQUAL(Data::m_move_constructor, 0);
}

BOOST_AUTO_TEST_CASE(test_mut_func) {
    Data::clear();

    Data mut_data;
    const Data const_data;

    auto mut_f = pipe_op(func_mut);
    BOOST_CHECK(!std::is_const<decltype(mut_f)>::value);

    const auto const_f = pipe_op(func_mut);
    BOOST_CHECK(std::is_const<decltype(const_f)>::value);

    m_func_call = 0;
    mut_data | mut_f;
    BOOST_CHECK_EQUAL(m_func_call, 1);

    m_func_call = 0;
    mut_data | const_f;
    BOOST_CHECK_EQUAL(m_func_call, 1);

    // TODO: сделать тесты для некомпилирующихся
    /// не должны компилироваться
    // const_data | mut_f
    // const_data | const_f;

    BOOST_CHECK_EQUAL(Data::m_def_constructor, 2);
    BOOST_CHECK_EQUAL(Data::m_copy_constructor, 0);
    BOOST_CHECK_EQUAL(Data::m_move_constructor, 0);
}

BOOST_AUTO_TEST_CASE(test_const_meth_wo_args) {
    Data::clear();

    Data mut_data;
    const Data const_data;

    auto mut_f = pipe_op(&Data::constWithoutArgs);
    BOOST_CHECK(!std::is_const<decltype(mut_f)>::value);

    const auto const_f = pipe_op(&Data::constWithoutArgs);
    BOOST_CHECK(std::is_const<decltype(const_f)>::value);

    Data::m_const_call = 0;
    mut_data | mut_f;
    BOOST_CHECK_EQUAL(Data::m_const_call, 1);

    Data::m_const_call = 0;
    mut_data | const_f;
    BOOST_CHECK_EQUAL(Data::m_const_call, 1);

    Data::m_const_call = 0;
    const_data | mut_f;
    BOOST_CHECK_EQUAL(Data::m_const_call, 1);

    Data::m_const_call = 0;
    const_data | const_f;
    BOOST_CHECK_EQUAL(Data::m_const_call, 1);

    BOOST_CHECK_EQUAL(Data::m_def_constructor, 2);
    BOOST_CHECK_EQUAL(Data::m_copy_constructor, 0);
    BOOST_CHECK_EQUAL(Data::m_move_constructor, 0);
}

BOOST_AUTO_TEST_CASE(test_mut_meth_wo_args) {
    Data::clear();

    Data mut_data;
    const Data const_data;

    auto mut_f = pipe_op(&Data::mutWithoutArgs);
    BOOST_CHECK(!std::is_const<decltype(mut_f)>::value);

    const auto const_f = pipe_op(&Data::mutWithoutArgs);
    BOOST_CHECK(std::is_const<decltype(const_f)>::value);

    Data::m_mut_call = 0;
    mut_data | mut_f;
    BOOST_CHECK_EQUAL(Data::m_mut_call, 1);

    Data::m_mut_call = 0;
    mut_data | const_f;
    BOOST_CHECK_EQUAL(Data::m_mut_call, 1);

    /// не должны компилироваться
    // const_data | mut_f;
    // const_data | const_f;

    BOOST_CHECK_EQUAL(Data::m_def_constructor, 2);
    BOOST_CHECK_EQUAL(Data::m_copy_constructor, 0);
    BOOST_CHECK_EQUAL(Data::m_move_constructor, 0);
}

BOOST_AUTO_TEST_CASE(test_mut_meth_with_args) {
    Data::clear();

    Data mut_data;
    const Data const_data;

    auto mut_f = pipe_op_factory(&Data::mutWithArg);
    BOOST_CHECK(!std::is_const<decltype(mut_f)>::value);

    const auto const_f = pipe_op_factory(&Data::mutWithArg);
    BOOST_CHECK(std::is_const<decltype(const_f)>::value);

    Data::m_mut_call = 0;
    Data::m_arg_value = 0;
    mut_data | mut_f(3);
    BOOST_CHECK_EQUAL(Data::m_mut_call, 1);
    BOOST_CHECK_EQUAL(Data::m_arg_value, 3);

    Data::m_mut_call = 0;
    Data::m_arg_value = 0;
    mut_data | const_f(3);
    BOOST_CHECK_EQUAL(Data::m_mut_call, 1);
    BOOST_CHECK_EQUAL(Data::m_arg_value, 3);

    /// не должны компилироваться
    // const_data | mut_f(1);
    // const_data | const_f(1);

    BOOST_CHECK_EQUAL(Data::m_def_constructor, 2);
    BOOST_CHECK_EQUAL(Data::m_copy_constructor, 0);
    BOOST_CHECK_EQUAL(Data::m_move_constructor, 0);
}

BOOST_AUTO_TEST_CASE(test_lambda_with_auto_args) {
    Data::clear();

    Data mut_data;
    const Data const_data;

    auto mut_f = pipe_op_factory([](auto& d, auto num) JUST_RETURN( d.mutWithArg(num) ));
    BOOST_CHECK(!std::is_const<decltype(mut_f)>::value);

    const auto const_f = pipe_op_factory([](auto& d, auto num) JUST_RETURN( d.mutWithArg(num) ));
    BOOST_CHECK(std::is_const<decltype(const_f)>::value);

    Data::m_mut_call = 0;
    Data::m_arg_value = 0;
    mut_data | mut_f(3);
    BOOST_CHECK_EQUAL(Data::m_mut_call, 1);
    BOOST_CHECK_EQUAL(Data::m_arg_value, 3);

    Data::m_mut_call = 0;
    Data::m_arg_value = 0;
    mut_data | const_f(3);
    BOOST_CHECK_EQUAL(Data::m_mut_call, 1);
    BOOST_CHECK_EQUAL(Data::m_arg_value, 3);

    /// не должны компилироваться
    // const_data | mut_f(1);
    // const_data | const_f(1);

    BOOST_CHECK_EQUAL(Data::m_def_constructor, 2);
    BOOST_CHECK_EQUAL(Data::m_copy_constructor, 0);
    BOOST_CHECK_EQUAL(Data::m_move_constructor, 0);
}

BOOST_AUTO_TEST_CASE(test_args_with_1_arg) {
    Data::clear();

    Data mut_data;
    const Data const_data;

    Data::m_mut_call = 0;
    Data::m_arg_value = 0;
    mut_data | &Data::mutWithArg A(3);
    BOOST_CHECK_EQUAL(Data::m_mut_call, 1);
    BOOST_CHECK_EQUAL(Data::m_arg_value, 3);

    Data::m_const_call = 0;
    Data::m_arg_value = 0;
    const_data | &Data::constWithArg A(3);
    BOOST_CHECK_EQUAL(Data::m_const_call, 1);
    BOOST_CHECK_EQUAL(Data::m_arg_value, 3);

    /// не должны компилироваться
    // const_data | &Data::mutWithArg A(3);

    BOOST_CHECK_EQUAL(Data::m_def_constructor, 2);
    BOOST_CHECK_EQUAL(Data::m_copy_constructor, 0);
    BOOST_CHECK_EQUAL(Data::m_move_constructor, 0);
}

BOOST_AUTO_TEST_CASE(test_template_func) {
    Data::clear();

    Data mut_data;
    const Data const_data;

    auto mut_f = pipe_op(templ_func<const Data>);
    BOOST_CHECK(!std::is_const<decltype(mut_f)>::value);

    const auto const_f = pipe_op(templ_func<const Data>);
    BOOST_CHECK(std::is_const<decltype(const_f)>::value);

    m_func_call = 0;
    mut_data | mut_f;
    BOOST_CHECK_EQUAL(m_func_call, 1);

    m_func_call = 0;
    mut_data | const_f;
    BOOST_CHECK_EQUAL(m_func_call, 1);

    m_func_call = 0;
    const_data | mut_f;
    BOOST_CHECK_EQUAL(m_func_call, 1);

    m_func_call = 0;
    const_data | const_f;
    BOOST_CHECK_EQUAL(m_func_call, 1);

    BOOST_CHECK_EQUAL(Data::m_def_constructor, 2);
    BOOST_CHECK_EQUAL(Data::m_copy_constructor, 0);
    BOOST_CHECK_EQUAL(Data::m_move_constructor, 0);
}

max_stars_repo_name: mdraven/pipeline

max_issues_repo_name: mdraven/pipeline

max_forks_repo_name: mdraven/pipeline


text:
#ifndef __NX_HANDLE_ERROR_H__
#define __NX_HANDLE_ERROR_H__

#include <iostream>

#include <boost/asio.hpp>

#include <nx/callbacks.hpp>
#include <nx/error_code.hpp>

namespace nx {

namespace tags {

struct on_error_tag : callback_tag {};

const on_error_tag on_error = {};

} // namespace tags

namespace asio = boost::asio;

template <typename Object>
bool
handle_error(Object& o, const char* what, const error_code& e)
{
    if (!e || e == asio::error::operation_aborted) {
        return false;
    }

    bool stop = false;

    if (e == asio::error::eof) {
        stop = true;
    } else if (!o.handler(tags::on_error)(o, e)) {
        // Unhandled error
        std::cerr << "unhandled error: " << what << " - "<< e.message() << std::endl;
        stop = true;
    }

    if (stop) {
        o.stop();
    }

    return true;
}

} // namespace nx

#endif // __NX_HANDLE_ERROR_H__

max_stars_repo_name: chybz/nx

max_issues_repo_name: chybz/nx

max_forks_repo_name: chybz/nx


text:
/*! \brief This file have the implementation for server.
    \file server.c
    \author Alvaro Denis <denisacostaq@gmail.com>
    \date 6/28/2019

    \copyright
    \attention
COPYRIGHT © 2019
    [denisacostaq][denisacostaq-URL].
    All rights reserved.

    \attention This file is part of
   [APIRestGenerator][APIRestGenerator-URL].

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

    THIS PRODUCT IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 PRODUCT, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

    [denisacostaq-URL]: https://about.me/denisacostaq "Alvaro Denis Acosta"
    [APIRestGenerator-URL]: http://github.com/denisacostaq/apirestgenerator
   "APIRestGenerator based on golang revel and gorm"
 */

#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <utility>

#include <boost/asio.hpp>

#include <messages.pb.h>

#include "src/database-server/data-access/dataaccess.h"
#include "src/database-server/data-source/sqlitewrapper.h"
#include "src/database-server/session.h"

namespace ba = boost::asio;
using ba::ip::tcp;

class server {
 public:
  server(ba::io_context& io_context, std::uint16_t port,
         const std::string& db_file)
      : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)),
        ds_{new SQLiteWrapper(db_file)},
        da_{new DataAccess(ds_)} {
    if (ds_->create_scheme() == IDataSource::Err::Ok) {
      // FIXME(denisacostaq@gmail.com): "color"
      Variable var{"temp", "color"};
      da_->add_variable(var);
    } else {
      throw std::string{"Unable to create schema."};
    }
    do_accept();
  }

  ~server() {
    delete da_;
    delete ds_;
  }

 private:
  void do_accept() {
    acceptor_.async_accept(
        [this](boost::system::error_code ec, tcp::socket socket) {
          if (!ec) {
            std::make_shared<Session>(std::move(socket), da_)->start();
          } else {
            std::cerr << "acepting " << ec.message() << "\n";
          }
          do_accept();
        });
  }

  tcp::acceptor acceptor_;
  IDataSource* ds_;
  IDataAccess* da_;
};

int main(int argc, char* argv[]) {
  try {
    if (argc != 2) {
      std::cerr << "Usage: async_tcp_echo_server <port>\n";
      return 1;
    }
    ba::io_context io_context;
    server s(io_context, std::atoi(argv[1]), "/tmp/sql.db");
    io_context.run();
  } catch (const std::string& e) {
    std::cerr << "Exception: " << e << "\n";
  } catch (std::exception& e) {
    std::cerr << "Exception: " << e.what() << "\n";
  } catch (...) {
    std::cerr << "Unknow exception\n";
  }
  return 0;
}

max_stars_repo_name: denisacostaq/DAQs

max_issues_repo_name: denisacostaq/DAQs

max_forks_repo_name: denisacostaq/DAQs


text:
//  (C) Copyright John Maddock 2000.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifdef TEST_STD
#  include <type_traits>
#else
#  include <boost/type_traits/is_convertible.hpp>
#endif
#include "test.hpp"
#include "check_integral_constant.hpp"
#include <boost/utility/enable_if.hpp>

template <class T>
struct convertible_from
{
    convertible_from(T);
};

struct base2 { };
struct middle2 : public virtual base2 { };
struct derived2 : public middle2 { };

#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)

template<typename T>
struct test_bug_4530
{
    template<typename A>
    test_bug_4530(A&&, typename boost::enable_if< ::tt::is_convertible<A&&, T> >::type* =0);
};

struct A4530
{
   template <class T>
   A4530(T);
};

#endif

#ifdef BOOST_MSVC

struct bug_5271a
{
    __declspec(align(16)) int value;
};

struct bug_5271b
{
    __declspec(align(16)) int value;
    bug_5271b(int v) : value(v) {}
};

#endif

#if (defined(BOOST_TT_CXX11_IS_CONVERTIBLE) || defined(BOOST_IS_CONVERTIBLE)) && !defined(BOOST_NO_CXX11_DELETED_FUNCTIONS)
struct bug9910
{
   bug9910() = default;
   bug9910(const bug9910&) = delete; // or private: A(const A&) = default;
};
struct Ref_bug9910
{
   // proxy reference to bug9910
   operator bug9910& () { return *_ptr; }
   bug9910* _ptr;
};
#endif

TT_TEST_BEGIN(is_convertible)

BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived,Base>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived,Derived>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base,Base>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base,Derived>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived,Derived>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<NonDerived,Base>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<virtual_inherit2,virtual_inherit1>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<VD,VB>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_derived1,polymorphic_base>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_derived2,polymorphic_base>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_base,polymorphic_derived1>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_base,polymorphic_derived2>::value), false);
#ifndef TEST_STD
// Ill-formed behaviour, supported by Boost as an extension:
#ifndef BOOST_NO_IS_ABSTRACT
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc1,test_abc1>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base,test_abc1>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_derived2,test_abc1>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int,test_abc1>::value), false);
#endif
#endif

// The following four do not compile without member template support:
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,void>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<void,void>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<void,float>::value), false);

BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<enum1, int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived*, Base*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base*, Derived*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived&, Base&>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base&, Derived&>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const Derived*, const Base*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const Base*, const Derived*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const Derived&, const Base&>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const Base&, const Derived&>::value), false);

BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int *, int*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int&, int&>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int*, int[3]>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int&, int>::value), true);
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int&&, int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int&&, const int&>::value), true);
#if !defined(__GNUC__) || ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 6)))
// Machinary required to support this, not available prior to gcc-4.7.0:
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int, int&>::value), false);
#endif
#endif
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int(&)[4], const int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int(&)(int), int(*)(int)>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int *, const int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int&, const int&>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int[2], int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int[2], const int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int[2], int*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int*, int[3]>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc3, const test_abc1&>::value), true);

BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<non_pointer, void*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<non_pointer, int*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<non_int_pointer, int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<non_int_pointer, void*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc1&, test_abc2&>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc1&, int_constructible>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int_constructible, test_abc1&>::value), false);
#if !defined(BOOST_NO_IS_ABSTRACT) && !(defined(__hppa) && defined(__HP_aCC))
//
// This doesn't work with aCC on PA RISC even though the is_abstract tests do
// all pass, this may indicate a deeper problem...
//
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc1&, test_abc2>::value), false);
#endif

//
// the following tests all involve user defined conversions which do
// not compile with Borland C++ Builder 5:
//
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int, int_constructible>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<float> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<float const&> >::value), true);
//
// These two tests give different results with different compilers, we used to require *true* results
// from these, but C++0x behaviour requires *false*:
//
//BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<float&> >::value), false);
//BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<char,convertible_from<char&> >::value), false);

#if !(defined(__GNUC__) && (__GNUC__ < 4))
// GCC 3.x emits warnings here, which causes the tests to fail when we compile with warnings-as-errors:
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<char> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<char const&> >::value), true);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<char&> >::value), false);

BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<char,convertible_from<char> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<char,convertible_from<char const&> >::value), true);

BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float&,convertible_from<float> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float const&,convertible_from<float> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float&,convertible_from<float&> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float const&,convertible_from<float const&> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float&,convertible_from<float const&> >::value), true);

//
// the following all generate warnings unless we can find a way to
// suppress them:
//
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<double,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<double,float>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<long,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int,char>::value), true);
#ifdef BOOST_HAS_LONG_LONG
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<boost::long_long_type,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<boost::long_long_type,char>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<boost::long_long_type,float>::value), true);
#elif defined(BOOST_HAS_MS_INT64)
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<__int64,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<__int64,char>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<__int64,float>::value), true);
#endif

#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
// Test bug case 4530:
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_bug_4530<A4530>,A4530>::value), true);
#endif

#if defined(BOOST_MSVC) && (BOOST_MSVC > 1310)
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int, bug_5271a>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int, bug_5271b>::value), true);
#endif

#if (defined(BOOST_TT_CXX11_IS_CONVERTIBLE) || defined(BOOST_IS_CONVERTIBLE)) && !defined(BOOST_NO_CXX11_DELETED_FUNCTIONS)
#ifndef _MSC_VER
// MSVC gives the wrong answer here, see https://connect.microsoft.com/VisualStudio/feedback/details/858956/std-is-convertible-returns-incorrect-value
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Ref_bug9910, bug9910>::value), false);
#endif
// From https://svn.boost.org/trac/boost/ticket/9910#comment:2:
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int, incomplete_type[]>::value), false);
#endif

TT_TEST_END

max_stars_repo_name: pdu/boost

max_issues_repo_name: pdu/boost

max_forks_repo_name: ZeroInfinite/turicreate