<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "serializer/merger.hpp"

#include "errors.hpp"

#include "arch/runtime/coroutines.hpp"
#include "concurrency/new_mutex.hpp"
#include "config/args.hpp"
#include "serializer/types.hpp"

merger_serializer_t::merger_serializer_t(scoped_ptr_t<serializer_t> _inner,
                                         int _max_active_writes) :
    inner(std::move(_inner)),
    index_writes_io_account(make_io_account(MERGED_INDEX_WRITE_IO_PRIORITY)),
    on_inner_index_write_complete(new counted_cond_t()),
    unhandled_index_write_waiter_exists(false),
    num_active_writes(0),
    max_active_writes(_max_active_writes) {
}

merger_serializer_t::~merger_serializer_t() {
    assert_thread();
    rassert(num_active_writes == 0);
    rassert(outstanding_index_write_ops.empty());
}

void merger_serializer_t::index_write(new_mutex_in_line_t *mutex_acq,
                                      const std::vector<index_write_op_t> &write_ops,
                                      file_account_t *) {
    rassert(coro_t::self() != NULL);
    assert_thread();

    counted_t<counted_cond_t> write_complete;
    {
        // Our set of write ops must be processed atomically...
        ASSERT_NO_CORO_WAITING;
        for (auto op = write_ops.begin(); op != write_ops.end(); ++op) {
            push_index_write_op(*op);
        }
        // ... and we also take a copy of the on_inner_index_write_complete signal
        // so we get notified exactly when all of our write ops have
        // been completed.
        write_complete = on_inner_index_write_complete;
        unhandled_index_write_waiter_exists = true;
    }

    // The caller is definitely "in line" for this merger serializer -- subsequent
    // index_write calls will get logically committed after ours.
    mutex_acq->reset();

    // Check if we can initiate a new index write
    if (num_active_writes < max_active_writes) {
        ++num_active_writes;
        do_index_write();
    }

    // Wait for the write to complete
    write_complete->wait_lazily_unordered();
}

void merger_serializer_t::do_index_write() {
    assert_thread();
    rassert(num_active_writes <= max_active_writes);

    // Assemble the currently outstanding index writes into
    // a vector of index_write_op_t-s.
    counted_t<counted_cond_t> write_complete;
    std::vector<index_write_op_t> write_ops;
    write_ops.reserve(outstanding_index_write_ops.size());
    {
        ASSERT_NO_CORO_WAITING;
        for (auto op_pair = outstanding_index_write_ops.begin();
             op_pair != outstanding_index_write_ops.end();
             ++op_pair) {
            write_ops.push_back(op_pair->second);
        }
        outstanding_index_write_ops.clear();
        unhandled_index_write_waiter_exists = false;

        // Swap out the on_inner_index_write_complete signal so subsequent index
        // writes can be captured by the next round of do_index_write().
        write_complete.reset(new counted_cond_t());
        write_complete.swap(on_inner_index_write_complete);
    }

    new_mutex_in_line_t mutex_acq(&inner_index_write_mutex);
    mutex_acq.acq_signal()->wait();
    inner->index_write(&mutex_acq, write_ops, index_writes_io_account.get());

    write_complete->pulse();

    --num_active_writes;

    // Check if we should start another index write
    if (num_active_writes < max_active_writes
        && unhandled_index_write_waiter_exists) {
        ++num_active_writes;
        coro_t::spawn_sometime(std::bind(&merger_serializer_t::do_index_write, this));
    }
}

void merger_serializer_t::merge_index_write_op(const index_write_op_t &to_be_merged,
                                               index_write_op_t *into_out) const {
    rassert(to_be_merged.block_id == into_out->block_id);
    if (to_be_merged.token.is_initialized()) {
        into_out->token = to_be_merged.token;
    }
    if (to_be_merged.recency.is_initialized()) {
        rassert(into_out->recency <= to_be_merged.recency);
        into_out->recency = to_be_merged.recency;
    }
}

void merger_serializer_t::push_index_write_op(const index_write_op_t &op) {
    auto existing_pair =
        outstanding_index_write_ops.insert(
            std::pair<block_id_t, index_write_op_t>(op.block_id, op));

    if (!existing_pair.second) {
        // new op could not be inserted because it already exists. Merge instead.
        merge_index_write_op(op, &existing_pair.first->second);
    }
}

<commit_msg>Removed wrong assertion.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "serializer/merger.hpp"

#include "errors.hpp"

#include "arch/runtime/coroutines.hpp"
#include "concurrency/new_mutex.hpp"
#include "config/args.hpp"
#include "serializer/types.hpp"

merger_serializer_t::merger_serializer_t(scoped_ptr_t<serializer_t> _inner,
                                         int _max_active_writes) :
    inner(std::move(_inner)),
    index_writes_io_account(make_io_account(MERGED_INDEX_WRITE_IO_PRIORITY)),
    on_inner_index_write_complete(new counted_cond_t()),
    unhandled_index_write_waiter_exists(false),
    num_active_writes(0),
    max_active_writes(_max_active_writes) {
}

merger_serializer_t::~merger_serializer_t() {
    assert_thread();
    rassert(num_active_writes == 0);
    rassert(outstanding_index_write_ops.empty());
}

void merger_serializer_t::index_write(new_mutex_in_line_t *mutex_acq,
                                      const std::vector<index_write_op_t> &write_ops,
                                      file_account_t *) {
    rassert(coro_t::self() != NULL);
    assert_thread();

    counted_t<counted_cond_t> write_complete;
    {
        // Our set of write ops must be processed atomically...
        ASSERT_NO_CORO_WAITING;
        for (auto op = write_ops.begin(); op != write_ops.end(); ++op) {
            push_index_write_op(*op);
        }
        // ... and we also take a copy of the on_inner_index_write_complete signal
        // so we get notified exactly when all of our write ops have
        // been completed.
        write_complete = on_inner_index_write_complete;
        unhandled_index_write_waiter_exists = true;
    }

    // The caller is definitely "in line" for this merger serializer -- subsequent
    // index_write calls will get logically committed after ours.
    mutex_acq->reset();

    // Check if we can initiate a new index write
    if (num_active_writes < max_active_writes) {
        ++num_active_writes;
        do_index_write();
    }

    // Wait for the write to complete
    write_complete->wait_lazily_unordered();
}

void merger_serializer_t::do_index_write() {
    assert_thread();
    rassert(num_active_writes <= max_active_writes);

    // Assemble the currently outstanding index writes into
    // a vector of index_write_op_t-s.
    counted_t<counted_cond_t> write_complete;
    std::vector<index_write_op_t> write_ops;
    write_ops.reserve(outstanding_index_write_ops.size());
    {
        ASSERT_NO_CORO_WAITING;
        for (auto op_pair = outstanding_index_write_ops.begin();
             op_pair != outstanding_index_write_ops.end();
             ++op_pair) {
            write_ops.push_back(op_pair->second);
        }
        outstanding_index_write_ops.clear();
        unhandled_index_write_waiter_exists = false;

        // Swap out the on_inner_index_write_complete signal so subsequent index
        // writes can be captured by the next round of do_index_write().
        write_complete.reset(new counted_cond_t());
        write_complete.swap(on_inner_index_write_complete);
    }

    new_mutex_in_line_t mutex_acq(&inner_index_write_mutex);
    mutex_acq.acq_signal()->wait();
    inner->index_write(&mutex_acq, write_ops, index_writes_io_account.get());

    write_complete->pulse();

    --num_active_writes;

    // Check if we should start another index write
    if (num_active_writes < max_active_writes
        && unhandled_index_write_waiter_exists) {
        ++num_active_writes;
        coro_t::spawn_sometime(std::bind(&merger_serializer_t::do_index_write, this));
    }
}

void merger_serializer_t::merge_index_write_op(const index_write_op_t &to_be_merged,
                                               index_write_op_t *into_out) const {
    rassert(to_be_merged.block_id == into_out->block_id);
    if (to_be_merged.token.is_initialized()) {
        into_out->token = to_be_merged.token;
    }
    if (to_be_merged.recency.is_initialized()) {
        into_out->recency = to_be_merged.recency;
    }
}

void merger_serializer_t::push_index_write_op(const index_write_op_t &op) {
    auto existing_pair =
        outstanding_index_write_ops.insert(
            std::pair<block_id_t, index_write_op_t>(op.block_id, op));

    if (!existing_pair.second) {
        // new op could not be inserted because it already exists. Merge instead.
        merge_index_write_op(op, &existing_pair.first->second);
    }
}

<|endoftext|>


<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "InteriorEntityHighlightController.h"
#include "ISearchService.h"
#include "ISearchQueryPerformer.h"
#include "ISearchResultRepository.h"
#include "InteriorInteractionModel.h"
#include "InteriorsModel.h"
#include "InteriorsFloorModel.h"
#include "IInteriorsLabelController.h"
#include "VectorMath.h"
#include "InteriorHighlightRenderable.h"
#include "InteriorsLabelParser.h"
#include "InteriorsFloorCells.h"
#include "InteriorsFloorCell.h"
#include "PlaceNameModel.h"
#include "InteriorsCellResource.h"
#include "InteriorsCellResourceObserver.h"
#include "LabelAnchorFilterModel.h"
#include "IAnchoredLabel.h"
#include "document.h"
#include "IInteriorsHighlightService.h"

namespace ExampleApp
{
    namespace InteriorsExplorer
    {
        namespace SdkModel
        {
            namespace Highlights
            {
                std::vector<std::string> GetEntityIdsFromSearchResultModel(const Search::SdkModel::SearchResultModel& selectedSearchResult)
                {
                    rapidjson::Document json;
                    std::vector<std::string> entities;

                    if (!json.Parse<0>(selectedSearchResult.GetJsonData().c_str()).HasParseError())
                    {
                        if( json.HasMember("highlight")  )
                        {
                            entities.push_back(json["highlight"].GetString());
                        }

                        if(  json.HasMember("entity_highlight")  )
                        {
                            const rapidjson::Value& entity_highlight = json["entity_highlight"];
                            assert(entity_highlight.IsArray());

                            for (int i  = 0; i < entity_highlight.Size(); i++)
                            {
                                entities.push_back(entity_highlight[i].GetString());
                            }
                        }
                    }

                    return entities;
                }

                InteriorEntityHighlightController::InteriorEntityHighlightController(Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel,
                                                                                Eegeo::Resources::Interiors::InteriorsCellResourceObserver& interiorsCellResourceObserver,
                                                                                Search::SdkModel::ISearchService& searchService,
                                                                                Search::SdkModel::ISearchQueryPerformer& searchQueryPerformer, Eegeo::Resources::Interiors::Entities::IInteriorsLabelController& legacyLabelController,
                                                                                Eegeo::Labels::ILabelAnchorFilterModel& labelHiddenFilterModel,
                                                                                const Eegeo::Labels::LabelLayer::IdType interiorLabelLayer,
                                                                                ExampleAppMessaging::TMessageBus& messageBus,
                                                                                IHighlightColorMapper& highlightColorMapper,
                                                                                Eegeo::Resources::Interiors::Highlights::IInteriorsHighlightService& interiorsHighlightService)
                : m_interiorInteractionModel(interiorInteractionModel)
                , m_interiorsCellResourceObserver(interiorsCellResourceObserver)
                , m_interiorLabelLayer(interiorLabelLayer)
                , m_labelHiddenFilterModel(labelHiddenFilterModel)
                , m_searchQueryPerformer(searchQueryPerformer)
                , m_highlightColorMapper(highlightColorMapper)
                , m_searchResultsIndex(-1)
                , m_searchQueryResponseHandler(this, &InteriorEntityHighlightController::OnSearchQueryResponseReceived)
                , m_searchResultsClearedHandler(this, &InteriorEntityHighlightController::OnSearchResultCleared)
                , m_handleSearchResultSectionItemSelectedMessageBinding(this, &InteriorEntityHighlightController::OnSearchItemSelected)
                , m_interiorInteractionModelChangedHandler(this, &InteriorEntityHighlightController::OnInteriorChanged)
                , m_interiorCellAddedHandler(this, &InteriorEntityHighlightController::OnInteriorAddedToSceneGraph)
                , m_availabilityChangedHandlerBinding(this, &InteriorEntityHighlightController::OnAvailabilityChanged)
                , m_interiorLabelsBuiltHandler(this, &InteriorEntityHighlightController::OnInteriorLabelsBuilt)
                , m_interiorsHighlightService(interiorsHighlightService)
                , m_messageBus(messageBus)
                , m_hideLabelAlwaysFilter(this, &InteriorEntityHighlightController::HideLabelAlwaysPredicate)
                , m_hideLabelByNameFilter(this, &InteriorEntityHighlightController::HideLabelByNamePredicate)
                {
                    m_messageBus.SubscribeUi(m_searchQueryResponseHandler);
                    m_searchQueryPerformer.InsertOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
                    m_interiorInteractionModel.RegisterModelChangedCallback(m_interiorInteractionModelChangedHandler);

                    m_interiorsCellResourceObserver.RegisterAddedToSceneGraphCallback(m_interiorCellAddedHandler);
                    m_messageBus.SubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
                    m_labelHiddenFilterModel.SetFilter(m_interiorLabelLayer, &m_hideLabelAlwaysFilter);
                }

                InteriorEntityHighlightController::~InteriorEntityHighlightController()
                {
                    m_interiorsCellResourceObserver.UnregisterAddedToSceneGraphCallback(m_interiorCellAddedHandler);

                    m_messageBus.UnsubscribeUi(m_searchQueryResponseHandler);

                    m_searchQueryPerformer.RemoveOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
                    m_interiorInteractionModel.UnregisterModelChangedCallback(m_interiorInteractionModelChangedHandler);

                    m_messageBus.UnsubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
                }

                void InteriorEntityHighlightController::OnAvailabilityChanged()
                {
                }

                void InteriorEntityHighlightController::RemoveHighlights()
                {
                    m_interiorsHighlightService.ClearAllHighlights();

                }

                void InteriorEntityHighlightController::ActivateLabels(bool active)
                {
                    m_labelHiddenFilterModel.SetFilter(m_interiorLabelLayer, active ? NULL : &m_hideLabelByNameFilter);
                }

                void InteriorEntityHighlightController::OnInteriorLabelsBuilt()
                {
                    ApplyHighlightsForCurrentResults();
                    bool hasResults = m_searchResults.size() > 0;
                    ActivateLabels(!hasResults);
                }

                void InteriorEntityHighlightController::OnSearchResultCleared()
                {
                    m_searchResultsIndex = -1;
                    m_searchResults.clear();
                    RemoveHighlights();
                    ApplyHighlightsForCurrentResults();
                    ActivateLabels(true);
                }

                void InteriorEntityHighlightController::OnSearchItemSelected(const SearchResultSection::SearchResultSectionItemSelectedMessage& message)
                {
                    if (message.ItemIndex() >= m_searchResults.size())
                    {
                        m_searchResultsIndex = -1;
                    }
                    else
                    {
                        m_searchResultsIndex = message.ItemIndex();
                    }

                    ApplyHighlightsForCurrentResults();
                }

                void InteriorEntityHighlightController::OnInteriorChanged()
                {
                    namespace EegeoInteriors = Eegeo::Resources::Interiors;
                    namespace EegeoRenderables = Eegeo::Rendering::Renderables;

                    RemoveHighlights();
                    m_currentHighlightRenderables.clear();

                    if (m_interiorInteractionModel.HasInteriorModel())
                    {
                        const EegeoInteriors::InteriorsModel& model = *m_interiorInteractionModel.GetInteriorModel();

                        for (EegeoInteriors::TFloorModelVector::const_iterator floors = model.GetFloors().begin();
                             floors != model.GetFloors().end();
                             ++floors)
                        {
                            const EegeoInteriors::InteriorsFloorCells* floorCells = model.GetFloorCells((*floors)->GetFloorNumber());

                            for (int cellIndex = 0; cellIndex < floorCells->GetCellCount(); ++cellIndex)
                            {
                                const EegeoInteriors::InteriorsFloorCell* cell = floorCells->GetFloorCells()[cellIndex];
                                std::vector<EegeoRenderables::InteriorHighlightRenderable*> renderables = cell->GetHighlightRenderables();

                                for (std::vector<EegeoRenderables::InteriorHighlightRenderable*>::iterator renderableIterator = renderables.begin();
                                     renderableIterator != renderables.end();
                                     ++renderableIterator)
                                {
                                    AddHighlight(**renderableIterator);
                                }
                            }
                        }

                        RemoveHighlights();
                        bool hasResults = m_searchResults.size() > 0;
                        ActivateLabels(!hasResults);
                    }
                    else
                    {
                        RemoveHighlights();
                        m_currentHighlightRenderables.clear();
                    }
                }

                void InteriorEntityHighlightController::OnInteriorAddedToSceneGraph(const Eegeo::Resources::Interiors::InteriorsCellResource& resource)
                {
                    if (m_interiorInteractionModel.HasInteriorModel())
                    {
                        const Eegeo::Resources::Interiors::InteriorsModel& model = *m_interiorInteractionModel.GetInteriorModel();
                        if (model.GetId() == resource.GetInteriorId())
                        {
                            OnInteriorChanged();
                        }
                    }
                }

                void InteriorEntityHighlightController::AddHighlight(Eegeo::Rendering::Renderables::InteriorHighlightRenderable& renderable)
                {
                    static const std::string highlightPrefix = "entity_highlight ";
                    const std::string& id = renderable.GetRenderableId();

                    if (id.compare(0, highlightPrefix.length(), highlightPrefix) == 0)
                    {
                        std::string highlightId = id.substr(highlightPrefix.length());
                        if (m_currentHighlightRenderables.find(highlightId) == m_currentHighlightRenderables.end())
                        {
                            std::vector<Eegeo::Rendering::Renderables::InteriorHighlightRenderable*> highlights;
                            m_currentHighlightRenderables.insert(std::make_pair(highlightId, highlights));
                        }
                        m_currentHighlightRenderables[highlightId].push_back(&renderable);
                    }
                }

                void InteriorEntityHighlightController::OnSearchQueryResponseReceived(const Search::SearchQueryResponseReceivedMessage& message)
                {
                    auto results = message.GetResults();
                    RemoveHighlights();
                    if (m_searchResultsIndex >= 0)
                    {
                        const Search::SdkModel::SearchResultModel& selectedSearchResult = m_searchResults.at(m_searchResultsIndex);

                        const std::vector<Search::SdkModel::SearchResultModel>& newSearchResults = results;

                        std::vector<Search::SdkModel::SearchResultModel>::const_iterator iter = std::find(newSearchResults.begin(), newSearchResults.end(), selectedSearchResult);
                        if (iter == newSearchResults.end())
                        {
                            m_searchResultsIndex = -1;
                        }
                        else
                        {
                            m_searchResultsIndex = static_cast<int>(std::distance(newSearchResults.begin(), iter));
                        }
                    }

                    m_searchResults = results;
                    ApplyHighlightsForCurrentResults();

                    bool hasResults = results.size() > 0;
                    ActivateLabels(!hasResults);
                }

                std::vector<Search::SdkModel::SearchResultModel> InteriorEntityHighlightController::GetCurrentSearchResults()
                {
                    std::vector<Search::SdkModel::SearchResultModel> results;
                    results.reserve(m_searchResults.size());

                    for (int i = 0; i < m_searchResults.size(); i++)
                    {
                        Search::SdkModel::SearchResultModel pResult = m_searchResults.at(i);
                        results.push_back(pResult);
                    }
                    return results;
                }

                void InteriorEntityHighlightController::ApplyHighlightsForCurrentResults()
                {
                    std::vector<Search::SdkModel::SearchResultModel> results = GetCurrentSearchResults();
                    ApplyHighlights(results);
                }

                void InteriorEntityHighlightController::HighlightSearchResult(const Search::SdkModel::SearchResultModel &searchResult)
                {
                    if (!searchResult.IsInterior())
                    {
                        return;
                    }
                    rapidjson::Document json;
                    std::string highlightedRoomId = "";

                    std::vector<std::string> filteredEntityIds = GetEntityIdsFromSearchResultModel(searchResult);
                    std::vector<Eegeo::v4> highlightColors = m_highlightColorMapper.GetColors(searchResult);

                    if (m_interiorInteractionModel.HasInteriorModel())
                    {
                        const std::string& interiorId = m_interiorInteractionModel.GetInteriorModel()->GetId().Value();
                        m_interiorsHighlightService.SetHighlights(interiorId, filteredEntityIds, highlightColors.front());
                     }
                }

                void InteriorEntityHighlightController::ApplyHighlights(const std::vector<Search::SdkModel::SearchResultModel> &results)
                {
                    RemoveHighlights();

                    if (m_interiorInteractionModel.HasInteriorModel() && m_currentHighlightRenderables.size() == 0)
                    {
                        OnInteriorChanged();
                    }

                    rapidjson::Document json;
                    std::string highlightedRoomId = "";

                    if (m_searchResultsIndex >= 0)
                    {
                        const Search::SdkModel::SearchResultModel& resultsItt = m_searchResults.at(m_searchResultsIndex);
                        HighlightSearchResult(resultsItt);
                    }
                    else
                    {
                        for (std::vector<Search::SdkModel::SearchResultModel>::const_iterator resultsItt = results.begin(); resultsItt != results.end(); ++resultsItt)
                        {
                            HighlightSearchResult(*resultsItt);
                        }
                    }
                }

                bool InteriorEntityHighlightController::HideLabelAlwaysPredicate(const Eegeo::Labels::IAnchoredLabel& anchoredLabel) const
                {
                    return true;
                }

                bool InteriorEntityHighlightController::HideLabelByNamePredicate(const Eegeo::Labels::IAnchoredLabel& anchoredLabel) const
                {
                    const std::string& labelCategoryName = anchoredLabel.GetLabelAnchorCategory().GetId();
                    bool shouldHide =  labelCategoryName != "interior_facility_escalator"
                    && labelCategoryName != "interior_facility_stairs"
                    && labelCategoryName != "interior_facility_elevator"
                    && labelCategoryName != "interior_facility_toilets";
                    return shouldHide;
                }
            }
        }
    }
}
<commit_msg>iOS Fix for MPLY-9783: POIs which highlight multiple room entities do not highlight correctly in WRLD App Buddy Ali Arslan https://eegeo-team.atlassian.net/browse/MPLY-9783<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "InteriorEntityHighlightController.h"
#include "ISearchService.h"
#include "ISearchQueryPerformer.h"
#include "ISearchResultRepository.h"
#include "InteriorInteractionModel.h"
#include "InteriorsModel.h"
#include "InteriorsFloorModel.h"
#include "IInteriorsLabelController.h"
#include "VectorMath.h"
#include "InteriorHighlightRenderable.h"
#include "InteriorsLabelParser.h"
#include "InteriorsFloorCells.h"
#include "InteriorsFloorCell.h"
#include "PlaceNameModel.h"
#include "InteriorsCellResource.h"
#include "InteriorsCellResourceObserver.h"
#include "LabelAnchorFilterModel.h"
#include "IAnchoredLabel.h"
#include "document.h"
#include "IInteriorsHighlightService.h"

namespace ExampleApp
{
    namespace InteriorsExplorer
    {
        namespace SdkModel
        {
            namespace Highlights
            {
                std::vector<std::string> GetEntityIdsFromJsonArray(const rapidjson::Value& jsonArray)
                {
                    assert(jsonArray.IsArray());
                    std::vector<std::string> entities;

                    for (int i  = 0; i < jsonArray.Size(); i++)
                    {
                        assert(jsonArray[i].IsString());
                        entities.push_back(jsonArray[i].GetString());
                    }

                    return entities;
                }

                std::vector<std::string> GetEntityIdsFromSearchResultModel(const Search::SdkModel::SearchResultModel& selectedSearchResult)
                {
                    rapidjson::Document json;
                    std::vector<std::string> entities;

                    if (!json.Parse<0>(selectedSearchResult.GetJsonData().c_str()).HasParseError())
                    {
                        if( json.HasMember("highlight")  )
                        {
                            const rapidjson::Value& area_highlight = json["highlight"];
                            if(area_highlight.IsString())
                            {
                                entities.push_back(json["highlight"].GetString());
                            }
                            else
                            {
                                std::vector<std::string> areaHighlights = GetEntityIdsFromJsonArray(area_highlight);
                                entities.insert(std::end(entities), std::begin(areaHighlights), std::end(areaHighlights));
                            }
                        }

                        if(  json.HasMember("entity_highlight")  )
                        {
                            std::vector<std::string> entityHighlights = GetEntityIdsFromJsonArray(json["entity_highlight"]);
                            entities.insert(std::end(entities), std::begin(entityHighlights), std::end(entityHighlights));
                        }
                    }

                    return entities;
                }

                InteriorEntityHighlightController::InteriorEntityHighlightController(Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel,
                                                                                Eegeo::Resources::Interiors::InteriorsCellResourceObserver& interiorsCellResourceObserver,
                                                                                Search::SdkModel::ISearchService& searchService,
                                                                                Search::SdkModel::ISearchQueryPerformer& searchQueryPerformer, Eegeo::Resources::Interiors::Entities::IInteriorsLabelController& legacyLabelController,
                                                                                Eegeo::Labels::ILabelAnchorFilterModel& labelHiddenFilterModel,
                                                                                const Eegeo::Labels::LabelLayer::IdType interiorLabelLayer,
                                                                                ExampleAppMessaging::TMessageBus& messageBus,
                                                                                IHighlightColorMapper& highlightColorMapper,
                                                                                Eegeo::Resources::Interiors::Highlights::IInteriorsHighlightService& interiorsHighlightService)
                : m_interiorInteractionModel(interiorInteractionModel)
                , m_interiorsCellResourceObserver(interiorsCellResourceObserver)
                , m_interiorLabelLayer(interiorLabelLayer)
                , m_labelHiddenFilterModel(labelHiddenFilterModel)
                , m_searchQueryPerformer(searchQueryPerformer)
                , m_highlightColorMapper(highlightColorMapper)
                , m_searchResultsIndex(-1)
                , m_searchQueryResponseHandler(this, &InteriorEntityHighlightController::OnSearchQueryResponseReceived)
                , m_searchResultsClearedHandler(this, &InteriorEntityHighlightController::OnSearchResultCleared)
                , m_handleSearchResultSectionItemSelectedMessageBinding(this, &InteriorEntityHighlightController::OnSearchItemSelected)
                , m_interiorInteractionModelChangedHandler(this, &InteriorEntityHighlightController::OnInteriorChanged)
                , m_interiorCellAddedHandler(this, &InteriorEntityHighlightController::OnInteriorAddedToSceneGraph)
                , m_availabilityChangedHandlerBinding(this, &InteriorEntityHighlightController::OnAvailabilityChanged)
                , m_interiorLabelsBuiltHandler(this, &InteriorEntityHighlightController::OnInteriorLabelsBuilt)
                , m_interiorsHighlightService(interiorsHighlightService)
                , m_messageBus(messageBus)
                , m_hideLabelAlwaysFilter(this, &InteriorEntityHighlightController::HideLabelAlwaysPredicate)
                , m_hideLabelByNameFilter(this, &InteriorEntityHighlightController::HideLabelByNamePredicate)
                {
                    m_messageBus.SubscribeUi(m_searchQueryResponseHandler);
                    m_searchQueryPerformer.InsertOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
                    m_interiorInteractionModel.RegisterModelChangedCallback(m_interiorInteractionModelChangedHandler);

                    m_interiorsCellResourceObserver.RegisterAddedToSceneGraphCallback(m_interiorCellAddedHandler);
                    m_messageBus.SubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
                    m_labelHiddenFilterModel.SetFilter(m_interiorLabelLayer, &m_hideLabelAlwaysFilter);
                }

                InteriorEntityHighlightController::~InteriorEntityHighlightController()
                {
                    m_interiorsCellResourceObserver.UnregisterAddedToSceneGraphCallback(m_interiorCellAddedHandler);

                    m_messageBus.UnsubscribeUi(m_searchQueryResponseHandler);

                    m_searchQueryPerformer.RemoveOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
                    m_interiorInteractionModel.UnregisterModelChangedCallback(m_interiorInteractionModelChangedHandler);

                    m_messageBus.UnsubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
                }

                void InteriorEntityHighlightController::OnAvailabilityChanged()
                {
                }

                void InteriorEntityHighlightController::RemoveHighlights()
                {
                    m_interiorsHighlightService.ClearAllHighlights();

                }

                void InteriorEntityHighlightController::ActivateLabels(bool active)
                {
                    m_labelHiddenFilterModel.SetFilter(m_interiorLabelLayer, active ? NULL : &m_hideLabelByNameFilter);
                }

                void InteriorEntityHighlightController::OnInteriorLabelsBuilt()
                {
                    ApplyHighlightsForCurrentResults();
                    bool hasResults = m_searchResults.size() > 0;
                    ActivateLabels(!hasResults);
                }

                void InteriorEntityHighlightController::OnSearchResultCleared()
                {
                    m_searchResultsIndex = -1;
                    m_searchResults.clear();
                    RemoveHighlights();
                    ApplyHighlightsForCurrentResults();
                    ActivateLabels(true);
                }

                void InteriorEntityHighlightController::OnSearchItemSelected(const SearchResultSection::SearchResultSectionItemSelectedMessage& message)
                {
                    if (message.ItemIndex() >= m_searchResults.size())
                    {
                        m_searchResultsIndex = -1;
                    }
                    else
                    {
                        m_searchResultsIndex = message.ItemIndex();
                    }

                    ApplyHighlightsForCurrentResults();
                }

                void InteriorEntityHighlightController::OnInteriorChanged()
                {
                    namespace EegeoInteriors = Eegeo::Resources::Interiors;
                    namespace EegeoRenderables = Eegeo::Rendering::Renderables;

                    RemoveHighlights();
                    m_currentHighlightRenderables.clear();

                    if (m_interiorInteractionModel.HasInteriorModel())
                    {
                        const EegeoInteriors::InteriorsModel& model = *m_interiorInteractionModel.GetInteriorModel();

                        for (EegeoInteriors::TFloorModelVector::const_iterator floors = model.GetFloors().begin();
                             floors != model.GetFloors().end();
                             ++floors)
                        {
                            const EegeoInteriors::InteriorsFloorCells* floorCells = model.GetFloorCells((*floors)->GetFloorNumber());

                            for (int cellIndex = 0; cellIndex < floorCells->GetCellCount(); ++cellIndex)
                            {
                                const EegeoInteriors::InteriorsFloorCell* cell = floorCells->GetFloorCells()[cellIndex];
                                std::vector<EegeoRenderables::InteriorHighlightRenderable*> renderables = cell->GetHighlightRenderables();

                                for (std::vector<EegeoRenderables::InteriorHighlightRenderable*>::iterator renderableIterator = renderables.begin();
                                     renderableIterator != renderables.end();
                                     ++renderableIterator)
                                {
                                    AddHighlight(**renderableIterator);
                                }
                            }
                        }

                        RemoveHighlights();
                        bool hasResults = m_searchResults.size() > 0;
                        ActivateLabels(!hasResults);
                    }
                    else
                    {
                        RemoveHighlights();
                        m_currentHighlightRenderables.clear();
                    }
                }

                void InteriorEntityHighlightController::OnInteriorAddedToSceneGraph(const Eegeo::Resources::Interiors::InteriorsCellResource& resource)
                {
                    if (m_interiorInteractionModel.HasInteriorModel())
                    {
                        const Eegeo::Resources::Interiors::InteriorsModel& model = *m_interiorInteractionModel.GetInteriorModel();
                        if (model.GetId() == resource.GetInteriorId())
                        {
                            OnInteriorChanged();
                        }
                    }
                }

                void InteriorEntityHighlightController::AddHighlight(Eegeo::Rendering::Renderables::InteriorHighlightRenderable& renderable)
                {
                    static const std::string highlightPrefix = "entity_highlight ";
                    const std::string& id = renderable.GetRenderableId();

                    if (id.compare(0, highlightPrefix.length(), highlightPrefix) == 0)
                    {
                        std::string highlightId = id.substr(highlightPrefix.length());
                        if (m_currentHighlightRenderables.find(highlightId) == m_currentHighlightRenderables.end())
                        {
                            std::vector<Eegeo::Rendering::Renderables::InteriorHighlightRenderable*> highlights;
                            m_currentHighlightRenderables.insert(std::make_pair(highlightId, highlights));
                        }
                        m_currentHighlightRenderables[highlightId].push_back(&renderable);
                    }
                }

                void InteriorEntityHighlightController::OnSearchQueryResponseReceived(const Search::SearchQueryResponseReceivedMessage& message)
                {
                    auto results = message.GetResults();
                    RemoveHighlights();
                    if (m_searchResultsIndex >= 0)
                    {
                        const Search::SdkModel::SearchResultModel& selectedSearchResult = m_searchResults.at(m_searchResultsIndex);

                        const std::vector<Search::SdkModel::SearchResultModel>& newSearchResults = results;

                        std::vector<Search::SdkModel::SearchResultModel>::const_iterator iter = std::find(newSearchResults.begin(), newSearchResults.end(), selectedSearchResult);
                        if (iter == newSearchResults.end())
                        {
                            m_searchResultsIndex = -1;
                        }
                        else
                        {
                            m_searchResultsIndex = static_cast<int>(std::distance(newSearchResults.begin(), iter));
                        }
                    }

                    m_searchResults = results;
                    ApplyHighlightsForCurrentResults();

                    bool hasResults = results.size() > 0;
                    ActivateLabels(!hasResults);
                }

                std::vector<Search::SdkModel::SearchResultModel> InteriorEntityHighlightController::GetCurrentSearchResults()
                {
                    std::vector<Search::SdkModel::SearchResultModel> results;
                    results.reserve(m_searchResults.size());

                    for (int i = 0; i < m_searchResults.size(); i++)
                    {
                        Search::SdkModel::SearchResultModel pResult = m_searchResults.at(i);
                        results.push_back(pResult);
                    }
                    return results;
                }

                void InteriorEntityHighlightController::ApplyHighlightsForCurrentResults()
                {
                    std::vector<Search::SdkModel::SearchResultModel> results = GetCurrentSearchResults();
                    ApplyHighlights(results);
                }

                void InteriorEntityHighlightController::HighlightSearchResult(const Search::SdkModel::SearchResultModel &searchResult)
                {
                    if (!searchResult.IsInterior())
                    {
                        return;
                    }
                    rapidjson::Document json;
                    std::string highlightedRoomId = "";

                    std::vector<std::string> filteredEntityIds = GetEntityIdsFromSearchResultModel(searchResult);
                    std::vector<Eegeo::v4> highlightColors = m_highlightColorMapper.GetColors(searchResult);

                    if (m_interiorInteractionModel.HasInteriorModel())
                    {
                        const std::string& interiorId = m_interiorInteractionModel.GetInteriorModel()->GetId().Value();
                        m_interiorsHighlightService.SetHighlights(interiorId, filteredEntityIds, highlightColors.front());
                     }
                }

                void InteriorEntityHighlightController::ApplyHighlights(const std::vector<Search::SdkModel::SearchResultModel> &results)
                {
                    RemoveHighlights();

                    if (m_interiorInteractionModel.HasInteriorModel() && m_currentHighlightRenderables.size() == 0)
                    {
                        OnInteriorChanged();
                    }

                    rapidjson::Document json;
                    std::string highlightedRoomId = "";

                    if (m_searchResultsIndex >= 0)
                    {
                        const Search::SdkModel::SearchResultModel& resultsItt = m_searchResults.at(m_searchResultsIndex);
                        HighlightSearchResult(resultsItt);
                    }
                    else
                    {
                        for (std::vector<Search::SdkModel::SearchResultModel>::const_iterator resultsItt = results.begin(); resultsItt != results.end(); ++resultsItt)
                        {
                            HighlightSearchResult(*resultsItt);
                        }
                    }
                }

                bool InteriorEntityHighlightController::HideLabelAlwaysPredicate(const Eegeo::Labels::IAnchoredLabel& anchoredLabel) const
                {
                    return true;
                }

                bool InteriorEntityHighlightController::HideLabelByNamePredicate(const Eegeo::Labels::IAnchoredLabel& anchoredLabel) const
                {
                    const std::string& labelCategoryName = anchoredLabel.GetLabelAnchorCategory().GetId();
                    bool shouldHide =  labelCategoryName != "interior_facility_escalator"
                    && labelCategoryName != "interior_facility_stairs"
                    && labelCategoryName != "interior_facility_elevator"
                    && labelCategoryName != "interior_facility_toilets";
                    return shouldHide;
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef LUABIND_ADOPT_POLICY_HPP_INCLUDED
#define LUABIND_ADOPT_POLICY_HPP_INCLUDED

#include <luabind/config.hpp>
#include <luabind/wrapper_base.hpp>
#include <luabind/detail/policy.hpp>
#include <luabind/detail/implicit_cast.hpp>
#include <luabind/back_reference_fwd.hpp>
#include <boost/type_traits/is_polymorphic.hpp>

namespace luabind { namespace detail
{
    template <class T>
    void adjust_backref_ownership(T* ptr, mpl::true_)
    {
        if (wrap_base* p = dynamic_cast<wrap_base*>(ptr))
        {
            wrapped_self_t& wrapper = wrap_access::ref(*p);
            wrapper.get(wrapper.state());
            wrapper.m_strong_ref.set(wrapper.state());
        }
    }

    inline void adjust_backref_ownership(void*, mpl::false_)
    {}

	template<class Direction = lua_to_cpp>
    struct adopt_pointer : pointer_converter
	{
		typedef adopt_pointer type;

        int const consumed_args(...)
        {
            return 1;
        }

		template<class T>
		T* apply(lua_State* L, by_pointer<T>, int index)
		{
            T* ptr = pointer_converter::apply(
                L, LUABIND_DECORATE_TYPE(T*), index);

            object_rep* obj = static_cast<object_rep*>(
                lua_touserdata(L, index));
            obj->release();

            adjust_backref_ownership(ptr, boost::is_polymorphic<T>());

            return ptr;
		}

		template<class T>
		int match(lua_State* L, by_pointer<T>, int index)
		{
            return pointer_converter::match(
                L, LUABIND_DECORATE_TYPE(T*), index);
		}

		template<class T>
		void converter_postcall(lua_State*, T, int) {}
	};

	template<>
	struct adopt_pointer<cpp_to_lua>
	{
		typedef adopt_pointer type;

		template<class T>
		void apply(lua_State* L, T* ptr)
		{
			if (ptr == 0)
			{
				lua_pushnil(L);
				return;
			}

			// if there is a back_reference, then the
			// ownership will be removed from the
			// back reference and put on the lua stack.
			if (luabind::move_back_reference(L, ptr))
				return;

            make_instance(L, std::auto_ptr<T>(ptr));
		}
	};

	template<int N>
//	struct adopt_policy : converter_policy_tag
	struct adopt_policy : conversion_policy<N>
	{
//		BOOST_STATIC_CONSTANT(int, index = N);

		static void precall(lua_State*, const index_map&) {}
		static void postcall(lua_State*, const index_map&) {}

		struct only_accepts_nonconst_pointers {};

		template<class T, class Direction>
		struct apply
		{
			typedef luabind::detail::is_nonconst_pointer<T> is_nonconst_p;
			typedef typename boost::mpl::if_<is_nonconst_p, adopt_pointer<Direction>, only_accepts_nonconst_pointers>::type type;
		};
	};

}}

namespace luabind
{
	template<int N>
	detail::policy_cons<detail::adopt_policy<N>, detail::null_type>
	adopt(LUABIND_PLACEHOLDER_ARG(N))
	{
		return detail::policy_cons<detail::adopt_policy<N>, detail::null_type>();
	}
}

#endif // LUABIND_ADOPT_POLICY_HPP_INCLUDE

<commit_msg>Add missing <luabind/wrapper_base.hpp> include.<commit_after>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef LUABIND_ADOPT_POLICY_HPP_INCLUDED
#define LUABIND_ADOPT_POLICY_HPP_INCLUDED

#include <luabind/config.hpp>
#include <luabind/wrapper_base.hpp>
#include <luabind/detail/policy.hpp>
#include <luabind/detail/implicit_cast.hpp>
#include <luabind/back_reference_fwd.hpp>
#include <luabind/wrapper_base.hpp>
#include <boost/type_traits/is_polymorphic.hpp>

namespace luabind { namespace detail
{
    template <class T>
    void adjust_backref_ownership(T* ptr, mpl::true_)
    {
        if (wrap_base* p = dynamic_cast<wrap_base*>(ptr))
        {
            wrapped_self_t& wrapper = wrap_access::ref(*p);
            wrapper.get(wrapper.state());
            wrapper.m_strong_ref.set(wrapper.state());
        }
    }

    inline void adjust_backref_ownership(void*, mpl::false_)
    {}

	template<class Direction = lua_to_cpp>
    struct adopt_pointer : pointer_converter
	{
		typedef adopt_pointer type;

        int const consumed_args(...)
        {
            return 1;
        }

		template<class T>
		T* apply(lua_State* L, by_pointer<T>, int index)
		{
            T* ptr = pointer_converter::apply(
                L, LUABIND_DECORATE_TYPE(T*), index);

            object_rep* obj = static_cast<object_rep*>(
                lua_touserdata(L, index));
            obj->release();

            adjust_backref_ownership(ptr, boost::is_polymorphic<T>());

            return ptr;
		}

		template<class T>
		int match(lua_State* L, by_pointer<T>, int index)
		{
            return pointer_converter::match(
                L, LUABIND_DECORATE_TYPE(T*), index);
		}

		template<class T>
		void converter_postcall(lua_State*, T, int) {}
	};

	template<>
	struct adopt_pointer<cpp_to_lua>
	{
		typedef adopt_pointer type;

		template<class T>
		void apply(lua_State* L, T* ptr)
		{
			if (ptr == 0)
			{
				lua_pushnil(L);
				return;
			}

			// if there is a back_reference, then the
			// ownership will be removed from the
			// back reference and put on the lua stack.
			if (luabind::move_back_reference(L, ptr))
				return;

            make_instance(L, std::auto_ptr<T>(ptr));
		}
	};

	template<int N>
//	struct adopt_policy : converter_policy_tag
	struct adopt_policy : conversion_policy<N>
	{
//		BOOST_STATIC_CONSTANT(int, index = N);

		static void precall(lua_State*, const index_map&) {}
		static void postcall(lua_State*, const index_map&) {}

		struct only_accepts_nonconst_pointers {};

		template<class T, class Direction>
		struct apply
		{
			typedef luabind::detail::is_nonconst_pointer<T> is_nonconst_p;
			typedef typename boost::mpl::if_<is_nonconst_p, adopt_pointer<Direction>, only_accepts_nonconst_pointers>::type type;
		};
	};

}}

namespace luabind
{
	template<int N>
	detail::policy_cons<detail::adopt_policy<N>, detail::null_type>
	adopt(LUABIND_PLACEHOLDER_ARG(N))
	{
		return detail::policy_cons<detail::adopt_policy<N>, detail::null_type>();
	}
}

#endif // LUABIND_ADOPT_POLICY_HPP_INCLUDE

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImportContainerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>
#include "itkImportImageContainer.h"
#include "itkNumericTraits.h"
#include "itkOutputWindow.h"
#include "itkTextOutput.h"

int itkImportContainerTest(int , char * [] )
{
  typedef float PixelType;
  typedef itk::ImportImageContainer<unsigned long, PixelType> ContainerType;

  itk::OutputWindow::SetInstance(itk::TextOutput::New());

// First test with ContainerManagesMemory false
  PixelType *ptr1;
  {
  // Test 1: Create an empty container and print it
  ContainerType::Pointer container1 = ContainerType::New();
  container1->Print(std::cout);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 2: Reserve memory
  container1->Reserve(1000);
  std::cout << "After container1->Reserve(1000), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Take control of the pointer
  container1->ContainerManageMemoryOff();
  ptr1 = container1->GetImportPointer();

  // Test 3: Reserve a smaller amount of memory
  container1->Reserve(100);
  std::cout << "After container1->Reserve(100), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 4: Squeeze the container
  container1->Squeeze();
  std::cout << "After container1->Squeeze() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 5: Initialize the container
  container1->Initialize();
  std::cout << "After container1->Initialize() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  }

// now repeat the tests with a user provided pointer
  PixelType *myPtr = new float[2000];
  {
  // Test 1: Create an empty container and print it
  ContainerType::Pointer container1 = ContainerType::New();
  container1->Print(std::cout);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  container1->SetImportPointer(myPtr, 2000);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  *(myPtr + 500) = 500.0;

  // Test 2: Reserve less memory than capacity
  container1->Reserve(1000);
  std::cout << "After container1->Reserve(1000), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  if (*(myPtr + 500) != 500.0)
    {
    std::cout << "Test failed: After container1->Reserve(1000), container1[500] does != 500." << std::endl;
    return EXIT_FAILURE;
    }

  // Test 3: Reserve more memory than capacity
  container1->Reserve(10000);
  std::cout << "After container1->Reserve(100), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  if (*(myPtr + 500) != 500.0)
    {
    std::cout << "Test failed: After container1->Reserve(10000), container1[500] does != 500." << std::endl;
    return EXIT_FAILURE;
    }

  // Test 4: Squeeze the container
  container1->Squeeze();
  std::cout << "After container1->Squeeze() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  if (*(myPtr + 500) != 500.0)
    {
    std::cout << "Test failed: After container1->Squeeze(), container1[500] does != 500." << std::endl;
    return EXIT_FAILURE;
    }

  // Test 5: Initialize the container
  container1->Initialize();
  std::cout << "After container1->Initialize() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  }

  // Now repeat tests with ContainerManagesMemory true
  {
  // Test 1: Create an empty container and print it
  ContainerType::Pointer container1 = ContainerType::New();
  container1->Print(std::cout);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 2: Reserve memory
  container1->Reserve(1000);
  std::cout << "After container1->Reserve(1000), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 3: Reserve a smaller amount of memory
  container1->Reserve(100);
  std::cout << "After container1->Reserve(100), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 4: Squeeze the container
  container1->Squeeze();
  std::cout << "After container1->Squeeze() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 5: Initialize the container
  container1->Initialize();
  std::cout << "After container1->Initialize() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  }

  // SGI's always say they can get you the memory you want.
#if !defined(__sgi)
  // Check the exception on the memory allocation
  bool caughtException = false;
  try
    {
    ContainerType::Pointer container1 = ContainerType::New();
    container1->Reserve( itk::NumericTraits<unsigned long>::max()/sizeof(PixelType));
    }
  catch (itk::ExceptionObject& err)
    {
    std::cout << "Caught expected exception: " << err << std::endl;
    caughtException = true;
    }
#endif

  // We must delete the memory we said we would manage
  delete [] ptr1;
  delete [] myPtr;

  if (!caughtException)
    {
    std::cout << "Failed to catch expected exception" << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}
<commit_msg>BUG: undefined var for SGIs.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImportContainerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>
#include "itkImportImageContainer.h"
#include "itkNumericTraits.h"
#include "itkOutputWindow.h"
#include "itkTextOutput.h"

int itkImportContainerTest(int , char * [] )
{
  typedef float PixelType;
  typedef itk::ImportImageContainer<unsigned long, PixelType> ContainerType;

  itk::OutputWindow::SetInstance(itk::TextOutput::New());

// First test with ContainerManagesMemory false
  PixelType *ptr1;
  {
  // Test 1: Create an empty container and print it
  ContainerType::Pointer container1 = ContainerType::New();
  container1->Print(std::cout);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 2: Reserve memory
  container1->Reserve(1000);
  std::cout << "After container1->Reserve(1000), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Take control of the pointer
  container1->ContainerManageMemoryOff();
  ptr1 = container1->GetImportPointer();

  // Test 3: Reserve a smaller amount of memory
  container1->Reserve(100);
  std::cout << "After container1->Reserve(100), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 4: Squeeze the container
  container1->Squeeze();
  std::cout << "After container1->Squeeze() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 5: Initialize the container
  container1->Initialize();
  std::cout << "After container1->Initialize() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  }

// now repeat the tests with a user provided pointer
  PixelType *myPtr = new float[2000];
  {
  // Test 1: Create an empty container and print it
  ContainerType::Pointer container1 = ContainerType::New();
  container1->Print(std::cout);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  container1->SetImportPointer(myPtr, 2000);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  *(myPtr + 500) = 500.0;

  // Test 2: Reserve less memory than capacity
  container1->Reserve(1000);
  std::cout << "After container1->Reserve(1000), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  if (*(myPtr + 500) != 500.0)
    {
    std::cout << "Test failed: After container1->Reserve(1000), container1[500] does != 500." << std::endl;
    return EXIT_FAILURE;
    }

  // Test 3: Reserve more memory than capacity
  container1->Reserve(10000);
  std::cout << "After container1->Reserve(100), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  if (*(myPtr + 500) != 500.0)
    {
    std::cout << "Test failed: After container1->Reserve(10000), container1[500] does != 500." << std::endl;
    return EXIT_FAILURE;
    }

  // Test 4: Squeeze the container
  container1->Squeeze();
  std::cout << "After container1->Squeeze() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  if (*(myPtr + 500) != 500.0)
    {
    std::cout << "Test failed: After container1->Squeeze(), container1[500] does != 500." << std::endl;
    return EXIT_FAILURE;
    }

  // Test 5: Initialize the container
  container1->Initialize();
  std::cout << "After container1->Initialize() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  }

  // Now repeat tests with ContainerManagesMemory true
  {
  // Test 1: Create an empty container and print it
  ContainerType::Pointer container1 = ContainerType::New();
  container1->Print(std::cout);
  std::cout << "After New(), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 2: Reserve memory
  container1->Reserve(1000);
  std::cout << "After container1->Reserve(1000), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 3: Reserve a smaller amount of memory
  container1->Reserve(100);
  std::cout << "After container1->Reserve(100), size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 4: Squeeze the container
  container1->Squeeze();
  std::cout << "After container1->Squeeze() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;

  // Test 5: Initialize the container
  container1->Initialize();
  std::cout << "After container1->Initialize() size is "
            << container1->Size()
            << ", capacity is "
            <<  container1->Capacity()
            << " and import pointer is "
            << container1->GetImportPointer()
            << std::endl;
  }

  // SGI's always say they can get you the memory you want.
#if !defined(__sgi)
  // Check the exception on the memory allocation
  bool caughtException = false;
  try
    {
    ContainerType::Pointer container1 = ContainerType::New();
    container1->Reserve( itk::NumericTraits<unsigned long>::max()/sizeof(PixelType));
    }
  catch (itk::ExceptionObject& err)
    {
    std::cout << "Caught expected exception: " << err << std::endl;
    caughtException = true;
    }
#else
  caughtException = true;
#endif

  // We must delete the memory we said we would manage
  delete [] ptr1;
  delete [] myPtr;

  if (!caughtException)
    {
    std::cout << "Failed to catch expected exception" << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before><commit_msg>Add complex text and font family supports for printing on Linux. Please NOTE that this is just a quick hack. Instead of using fonts in Cairo, we draw texts' paths from the given paint.<commit_after><|endoftext|>


<commit_before>#ifndef SM_STRING_ROUTINES_H
#define SM_STRING_ROUTINES_H

#include <string>
#include <cstdlib>
#include <sstream>
#include <iostream>
namespace sm
{
  /// replaces the 'target' with 'replacement' searching forward through
  /// the string and skipping 'skip' occurences
  inline std::string replace(std::string str, char target, char replacement, unsigned int skip = 0)
  {
    std::string::size_type pos = 0;
    while( (pos = str.find(target, pos)) != std::string::npos)
      {
	if(skip)
	  {
	    skip--;
	    pos++;
	  }
	else
	  str[pos] = replacement;
      }
    return str;
  }

  /// replaces the 'target' with 'replacement' searching backward through
  /// the string and skipping 'skip' occurences
  inline std::string replace_reverse(std::string str, char target, char replacement, unsigned int skip = 0)
  {
    std::string::size_type pos = std::string::npos;
    while( (pos = str.rfind(target, pos)) != std::string::npos)
      {
	if(skip)
	  {
	    skip--;
	    pos--;
	  }
	else
	  str[pos] = replacement;
      }
    return str;
  }

  inline std::string leading_pad( std::string str, unsigned int desiredLength, char padChar )
  {
    std::string result;
    if ( str.length() < desiredLength )
      {
	std::string padding( desiredLength - str.length(), padChar );
	result = padding.append(str);
      }
    else
      {
	result = str;
      }
    return result;
  }

  inline std::string tolower(std::string s) {
    for(unsigned int i = 0; i < s.size(); i++)
      s[i] = ::tolower(s[i]); // call tolower from the c std lib.
    return s;
  }

  // Find all substrings of the form $(XXX) and replace them
  // with the associated environment variable if they exist.
  inline std::string substituteEnvVars(std::string const & s) {
    std::string::size_type off = 0, pidx=0, idx=0, idxe=0;
    std::ostringstream out;
    idx = s.find("$(",off);
    while(idx != std::string::npos){
      //std::cout << "Found \"$(\" at " << idx << std::endl;
      idxe = s.find(')',idx);
      if(idxe != std::string::npos) {
	//std::cout << "Found \")\" at " << idxe << std::endl;
	// We've found an environment variable.
	std::string envVar = s.substr(idx+2,idxe-idx-2);
	//std::cout << "evname: " << envVar << std::endl;
	char * envSub = getenv(envVar.c_str());

	if(envSub != NULL) {
	  // Dump everything before the envVar
	  out << s.substr(pidx,idx-pidx);
	  out << envSub;
	  pidx = idxe+1;
	}
	off = idxe+1;
	idx = s.find("$(",off);
      } else {
	// No close brackets means no env vars.
	idx = std::string::npos;
      }

    }
    out << s.substr(pidx);
    return out.str();
  }

  inline std::string ensureTrailingBackslash(std::string const & s)
  {
    if(s.size() == 0)
      return "/";

    if(s[s.size()-1] == '/')
      return s;

    return s + "/";
  }

	// a nice and short to-string function.
	template<typename T>
	std::string ts(T t)
	{
		std::ostringstream s;
		s << t;
		return s.str();
	}

	// pad an int with zeros.
  template<typename T>
  inline std::string padded(const T & val, unsigned int digits, char fillChar = '0')
	{
		std::ostringstream s;
		s.fill(fillChar);
		s.width(digits);
		s << val;
		return s.str();
	}

	inline std::string padded(double val, unsigned width, unsigned precision) {
		std::ostringstream s;
		s.fill(' ');
		s.width(width);
		s.setf(std::ios::fixed,std::ios::floatfield);   // floatfield set to fixed
		s.precision(precision);
		s << val;

		return s.str();
	}

	inline std::string scientific(double val, unsigned width, unsigned precision) {
		std::ostringstream s;
		s.fill(' ');
		s.width(width);
		s.setf(std::ios::fixed,std::ios::floatfield);   // floatfield set to fixed
		s.precision(precision);
		s.setf(std::ios_base::scientific);
		s << val;

		return s.str();
	}

	inline std::string fixedFloat(double val, unsigned precision) {
		std::ostringstream s;
		s.precision(precision);
		s << std::fixed << val;
		return s.str();
	}

	template<typename T>
	std::string s_tuple(T t)
	{
		std::ostringstream s;
		s << t;
		return s.str();
	}

	template<typename T, typename U>
	std::string s_tuple(T t, U u)
	{
		std::ostringstream s;
		s << "[" << t << "," << u << "]";
		return s.str();
	}

	template<typename T, typename U, typename V>
	std::string s_tuple(T t, U u, V v)
	{
		std::ostringstream s;
		s << "[" << t << "," << u << "," << v << "]";
		return s.str();
	}

	template<typename T, typename U, typename V, typename W>
	std::string s_tuple(T t, U u, V v, W w)
	{
		std::ostringstream s;
		s << "[" << t << "," << u << "," << v << "," << w << "]";
		return s.str();
	}

	template<typename T, typename U, typename V, typename W, typename X>
	std::string s_tuple(T t, U u, V v, W w, X x)
	{
		std::ostringstream s;
		s << "[" << t << "," << u << "," << v << "," << w << "," << x <<"]";
		return s.str();
	}

	template<typename T, typename U, typename V, typename W, typename X, typename Y>
	std::string s_tuple(T t, U u, V v, W w, X x, Y y)
	{
		std::ostringstream s;
		s << "[" << t << "," << u << "," << v << "," << w << "," << x << "," << y << "]";
		return s.str();
	}

	template<typename T, typename U, typename V, typename W, typename X, typename Y, typename Z>
	std::string s_tuple(T t, U u, V v, W w, X x, Y y, Z z)
	{
		std::ostringstream s;
		s << "[" << t << "," << u << "," << v << "," << w << "," << x << "," << y << "," << z << "]";
		return s.str();
	}

	template<typename ConstIterator>
	inline void toStream(std::ostream & stream, ConstIterator begin, ConstIterator end, std::string delimiter = " ", std::string prefix = "", std::string postfix = "")
	{
		ConstIterator i = begin;
		stream << prefix;
		if(i != end)
		{
			stream << *i;
			i++;
			for( ; i != end; ++i)
				stream << delimiter << *i;
		}
		stream << postfix;
	}

	template<typename Iterator>
	std::string arrToString(Iterator start, Iterator end)
	{
          std::ostringstream s;
          toStream(s, start, end, ",", "[", "]");
            return s.str();
	}

	template<typename T>
	std::string arrToString(T * thearr, unsigned int size)
	{

	  return arrToString((T*)thearr, (T*)(thearr + size));
	}

	template<typename ConstIterator>
	inline void paddedToStream(std::ostream & stream, int padLength, int decimalLength, ConstIterator begin, ConstIterator end, std::string delimiter = " ", std::string prefix = "", std::string postfix = "")
	{
		stream << prefix;

		ConstIterator i = begin;

		if(i != end)
		{
			stream.fill(' ');
			stream.width(padLength);
			stream.setf(std::ios::fixed,std::ios::floatfield);   // floatfield set to fixed
			stream.precision(decimalLength);

			stream << *i;
			i++;
			for( ; i != end; ++i){
				stream << delimiter;
				stream.fill(' ');
				stream.width(padLength);
				stream.setf(std::ios::fixed,std::ios::floatfield);   // floatfield set to fixed
				stream.precision(decimalLength);

				stream << *i;
			}
		}
		stream << postfix;
	}

	template<typename ConstIterator>
	inline std::string paddedToString( int padLength, int decimalLength, ConstIterator begin, ConstIterator end, std::string delimiter = " ", std::string prefix = "", std::string postfix = "")
	{
          std::ostringstream stream;
          paddedToStream(stream,padLength,decimalLength,begin,end,delimiter,prefix,postfix);
          return stream.str();
        }

} // namespace sm

#endif

<commit_msg>Compilation problems for some reason<commit_after>#ifndef SM_STRING_ROUTINES_H
#define SM_STRING_ROUTINES_H

#include <string>
#include <cstdlib>
#include <sstream>
#include <iostream>
namespace sm
{
    /// replaces the 'target' with 'replacement' searching forward through
    /// the string and skipping 'skip' occurences
    inline std::string replace(std::string str, char target, char replacement, unsigned int skip = 0)
    {
        std::string::size_type pos = 0;
        while( (pos = str.find(target, pos)) != std::string::npos)
        {
            if(skip)
            {
                skip--;
                pos++;
            }
            else
                str[pos] = replacement;
        }
        return str;
    }

    /// replaces the 'target' with 'replacement' searching backward through
    /// the string and skipping 'skip' occurences
    inline std::string replace_reverse(std::string str, char target, char replacement, unsigned int skip = 0)
    {
        std::string::size_type pos = std::string::npos;
        while( (pos = str.rfind(target, pos)) != std::string::npos)
        {
            if(skip)
            {
                skip--;
                pos--;
            }
            else
                str[pos] = replacement;
        }
        return str;
    }

    inline std::string leading_pad( std::string str, unsigned int desiredLength, char padChar )
    {
        std::string result;
        if ( str.length() < desiredLength )
        {
            std::string padding( desiredLength - str.length(), padChar );
            result = padding.append(str);
        }
        else
        {
            result = str;
        }
        return result;
    }

    /*
    inline std::string tolower(std::string s) {
        for(unsigned int i = 0; i < s.size(); i++)
            s[i] = ::tolower(s[i]); // call tolower from the c std lib.
        return s;
    }
    */
    // Find all substrings of the form $(XXX) and replace them
    // with the associated environment variable if they exist.
    inline std::string substituteEnvVars(std::string const & s) {
        std::string::size_type off = 0, pidx=0, idx=0, idxe=0;
        std::ostringstream out;
        idx = s.find("$(",off);
        while(idx != std::string::npos){
            //std::cout << "Found \"$(\" at " << idx << std::endl;
            idxe = s.find(')',idx);
            if(idxe != std::string::npos) {
                //std::cout << "Found \")\" at " << idxe << std::endl;
                // We've found an environment variable.
                std::string envVar = s.substr(idx+2,idxe-idx-2);
                //std::cout << "evname: " << envVar << std::endl;
                char * envSub = getenv(envVar.c_str());

                if(envSub != NULL) {
                    // Dump everything before the envVar
                    out << s.substr(pidx,idx-pidx);
                    out << envSub;
                    pidx = idxe+1;
                }
                off = idxe+1;
                idx = s.find("$(",off);
            } else {
                // No close brackets means no env vars.
                idx = std::string::npos;
            }

        }
        out << s.substr(pidx);
        return out.str();
    }

    inline std::string ensureTrailingBackslash(std::string const & s)
    {
        if(s.size() == 0)
            return "/";

        if(s[s.size()-1] == '/')
            return s;

        return s + "/";
    }

	// a nice and short to-string function.
	template<typename T>
	std::string ts(T t)
	{
		std::ostringstream s;
		s << t;
		return s.str();
	}

	// pad an int with zeros.
    template<typename T>
    inline std::string padded(const T & val, unsigned int digits, char fillChar = '0')
	{
		std::ostringstream s;
		s.fill(fillChar);
		s.width(digits);
		s << val;
		return s.str();
	}

	inline std::string padded(double val, unsigned width, unsigned precision) {
		std::ostringstream s;
		s.fill(' ');
		s.width(width);
		s.setf(std::ios::fixed,std::ios::floatfield);   // floatfield set to fixed
		s.precision(precision);
		s << val;

		return s.str();
	}

	inline std::string scientific(double val, unsigned width, unsigned precision) {
		std::ostringstream s;
		s.fill(' ');
		s.width(width);
		s.setf(std::ios::fixed,std::ios::floatfield);   // floatfield set to fixed
		s.precision(precision);
		s.setf(std::ios_base::scientific);
		s << val;

		return s.str();
	}

	inline std::string fixedFloat(double val, unsigned precision) {
		std::ostringstream s;
		s.precision(precision);
		s << std::fixed << val;
		return s.str();
	}

	template<typename T>
	std::string s_tuple(T t)
	{
		std::ostringstream s;
		s << t;
		return s.str();
	}

	template<typename T, typename U>
	std::string s_tuple(T t, U u)
	{
		std::ostringstream s;
		s << "[" << t << "," << u << "]";
		return s.str();
	}

	template<typename T, typename U, typename V>
	std::string s_tuple(T t, U u, V v)
	{
		std::ostringstream s;
		s << "[" << t << "," << u << "," << v << "]";
		return s.str();
	}

	template<typename T, typename U, typename V, typename W>
	std::string s_tuple(T t, U u, V v, W w)
	{
		std::ostringstream s;
		s << "[" << t << "," << u << "," << v << "," << w << "]";
		return s.str();
	}

	template<typename T, typename U, typename V, typename W, typename X>
	std::string s_tuple(T t, U u, V v, W w, X x)
	{
		std::ostringstream s;
		s << "[" << t << "," << u << "," << v << "," << w << "," << x <<"]";
		return s.str();
	}

	template<typename T, typename U, typename V, typename W, typename X, typename Y>
	std::string s_tuple(T t, U u, V v, W w, X x, Y y)
	{
		std::ostringstream s;
		s << "[" << t << "," << u << "," << v << "," << w << "," << x << "," << y << "]";
		return s.str();
	}

	template<typename T, typename U, typename V, typename W, typename X, typename Y, typename Z>
	std::string s_tuple(T t, U u, V v, W w, X x, Y y, Z z)
	{
		std::ostringstream s;
		s << "[" << t << "," << u << "," << v << "," << w << "," << x << "," << y << "," << z << "]";
		return s.str();
	}

	template<typename ConstIterator>
	inline void toStream(std::ostream & stream, ConstIterator begin, ConstIterator end, std::string delimiter = " ", std::string prefix = "", std::string postfix = "")
	{
		ConstIterator i = begin;
		stream << prefix;
		if(i != end)
		{
			stream << *i;
			i++;
			for( ; i != end; ++i)
				stream << delimiter << *i;
		}
		stream << postfix;
	}

	template<typename Iterator>
	std::string arrToString(Iterator start, Iterator end)
	{
        std::ostringstream s;
        toStream(s, start, end, ",", "[", "]");
        return s.str();
	}

	template<typename T>
	std::string arrToString(T * thearr, unsigned int size)
	{

        return arrToString((T*)thearr, (T*)(thearr + size));
	}

	template<typename ConstIterator>
	inline void paddedToStream(std::ostream & stream, int padLength, int decimalLength, ConstIterator begin, ConstIterator end, std::string delimiter = " ", std::string prefix = "", std::string postfix = "")
	{
		stream << prefix;

		ConstIterator i = begin;

		if(i != end)
		{
			stream.fill(' ');
			stream.width(padLength);
			stream.setf(std::ios::fixed,std::ios::floatfield);   // floatfield set to fixed
			stream.precision(decimalLength);

			stream << *i;
			i++;
			for( ; i != end; ++i){
				stream << delimiter;
				stream.fill(' ');
				stream.width(padLength);
				stream.setf(std::ios::fixed,std::ios::floatfield);   // floatfield set to fixed
				stream.precision(decimalLength);

				stream << *i;
			}
		}
		stream << postfix;
	}

	template<typename ConstIterator>
	inline std::string paddedToString( int padLength, int decimalLength, ConstIterator begin, ConstIterator end, std::string delimiter = " ", std::string prefix = "", std::string postfix = "")
	{
        std::ostringstream stream;
        paddedToStream(stream,padLength,decimalLength,begin,end,delimiter,prefix,postfix);
        return stream.str();
    }

} // namespace sm

#endif

<|endoftext|>