<commit_before>// Copyright (c) 2014, Salesforce.com, Inc.  All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// - Neither the name of Salesforce.com nor the names of its contributors
//   may be used to endorse or promote products derived from this
//   software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#pragma once

#include <distributions/common.hpp>
#include <distributions/schema.pb.h>
#include <distributions/clustering.hpp>
#include <distributions/models/dd.hpp>
#include <distributions/models/dpd.hpp>
#include <distributions/models/nich.hpp>
#include <distributions/models/gp.hpp>

namespace distributions
{

namespace protobuf { using namespace ::protobuf::distributions; }

//----------------------------------------------------------------------------
// Clustering

// FIXME g++ fails if these are made template<count_t>

inline void clustering_load (
        typename Clustering<int>::PitmanYor & model,
        const protobuf::Clustering::PitmanYor & message)
{
    model.alpha = message.alpha();
    model.d = message.d();
}

inline void clustering_load (
        typename Clustering<int>::PitmanYor & model,
        const protobuf::Clustering & message)
{
    clustering_load(model, message.pitman_yor());
}

inline void clustering_load (
        typename Clustering<int>::LowEntropy & model,
        const protobuf::Clustering::LowEntropy & message)
{
    model.dataset_size = message.dataset_size();
}

template<class count_t>
inline void clustering_load (
        typename Clustering<int>::LowEntropy & model,
        const protobuf::Clustering & message)
{
    clustering_load(model, message.low_entropy());
}

//----------------------------------------------------------------------------
// Models

template<int max_dim>
inline void model_load (
        DirichletDiscrete<max_dim> & model,
        const protobuf::DirichletDiscrete & message)
{
    model.dim = message.alphas_size();
    DIST_ASSERT(model.dim <= max_dim, "dim is too large: " << model.dim);
    for (size_t i = 0; i < model.dim; ++i) {
        model.alphas[i] = message.alphas(i);
    }
}

inline void model_load (
        DirichletProcessDiscrete & model,
        const protobuf::DirichletProcessDiscrete & message)
{
    model.gamma = message.gamma();
    model.alpha = message.alpha();
    model.betas.resize(message.betas_size());
    double beta_sum = 0;
    for (size_t i = 0; i < model.betas.size(); ++i) {
        beta_sum += model.betas[i] = message.betas(i);
    }
    model.beta0 = 1 - beta_sum;
}

inline void model_load (
        GammaPoisson & model,
        const protobuf::GammaPoisson & message)
{
    model.alpha = message.alpha();
    model.inv_beta = message.inv_beta();
}

inline void model_load (
        NormalInverseChiSq & model,
        const protobuf::NormalInverseChiSq & message)
{
    model.mu = message.mu();
    model.kappa = message.kappa();
    model.sigmasq = message.sigmasq();
    model.nu = message.nu();
}

//----------------------------------------------------------------------------
// Groups

template<int max_dim>
inline void group_dump (
        const DirichletDiscrete<max_dim> & model,
        const typename DirichletDiscrete<max_dim>::Group & group,
        protobuf::DirichletDiscrete::Group & message)
{
    message.Clear();
    auto & counts = * message.mutable_counts();
    for (size_t i = 0; i < model.dim; ++i) {
        counts.Add(group.counts[i]);
    }
}

inline void group_dump (
        const DirichletProcessDiscrete &,
        const DirichletProcessDiscrete::Group & group,
        protobuf::DirichletProcessDiscrete::Group & message)
{
    message.Clear();
    auto & keys = * message.mutable_keys();
    auto & values = * message.mutable_values();
    for (const auto & pair : group.counts) {
        keys.Add(pair.first);
        values.Add(pair.second);
    }
}

inline void group_dump (
        const GammaPoisson &,
        const GammaPoisson::Group & group,
        protobuf::GammaPoisson::Group & message)
{
    message.set_count(group.count);
    message.set_sum(group.sum);
    message.set_log_prod(group.log_prod);
}

inline void group_dump (
        const NormalInverseChiSq &,
        const NormalInverseChiSq::Group & group,
        protobuf::NormalInverseChiSq::Group & message)
{
    message.set_count(group.count);
    message.set_mean(group.mean);
    message.set_count_times_variance(group.count_times_variance);
}

} // namespace distributions
<commit_msg>Fix include path in protobuf.hpp<commit_after>// Copyright (c) 2014, Salesforce.com, Inc.  All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// - Neither the name of Salesforce.com nor the names of its contributors
//   may be used to endorse or promote products derived from this
//   software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#pragma once

#include <distributions/common.hpp>
#include <distributions/clustering.hpp>
#include <distributions/models/dd.hpp>
#include <distributions/models/dpd.hpp>
#include <distributions/models/nich.hpp>
#include <distributions/models/gp.hpp>
#include <distributions/io/schema.pb.h>

namespace distributions
{

namespace protobuf { using namespace ::protobuf::distributions; }

//----------------------------------------------------------------------------
// Clustering

// FIXME g++ fails if these are made template<count_t>

inline void clustering_load (
        typename Clustering<int>::PitmanYor & model,
        const protobuf::Clustering::PitmanYor & message)
{
    model.alpha = message.alpha();
    model.d = message.d();
}

inline void clustering_load (
        typename Clustering<int>::PitmanYor & model,
        const protobuf::Clustering & message)
{
    clustering_load(model, message.pitman_yor());
}

inline void clustering_load (
        typename Clustering<int>::LowEntropy & model,
        const protobuf::Clustering::LowEntropy & message)
{
    model.dataset_size = message.dataset_size();
}

template<class count_t>
inline void clustering_load (
        typename Clustering<int>::LowEntropy & model,
        const protobuf::Clustering & message)
{
    clustering_load(model, message.low_entropy());
}

//----------------------------------------------------------------------------
// Models

template<int max_dim>
inline void model_load (
        DirichletDiscrete<max_dim> & model,
        const protobuf::DirichletDiscrete & message)
{
    model.dim = message.alphas_size();
    DIST_ASSERT(model.dim <= max_dim, "dim is too large: " << model.dim);
    for (size_t i = 0; i < model.dim; ++i) {
        model.alphas[i] = message.alphas(i);
    }
}

inline void model_load (
        DirichletProcessDiscrete & model,
        const protobuf::DirichletProcessDiscrete & message)
{
    model.gamma = message.gamma();
    model.alpha = message.alpha();
    model.betas.resize(message.betas_size());
    double beta_sum = 0;
    for (size_t i = 0; i < model.betas.size(); ++i) {
        beta_sum += model.betas[i] = message.betas(i);
    }
    model.beta0 = 1 - beta_sum;
}

inline void model_load (
        GammaPoisson & model,
        const protobuf::GammaPoisson & message)
{
    model.alpha = message.alpha();
    model.inv_beta = message.inv_beta();
}

inline void model_load (
        NormalInverseChiSq & model,
        const protobuf::NormalInverseChiSq & message)
{
    model.mu = message.mu();
    model.kappa = message.kappa();
    model.sigmasq = message.sigmasq();
    model.nu = message.nu();
}

//----------------------------------------------------------------------------
// Groups

template<int max_dim>
inline void group_dump (
        const DirichletDiscrete<max_dim> & model,
        const typename DirichletDiscrete<max_dim>::Group & group,
        protobuf::DirichletDiscrete::Group & message)
{
    message.Clear();
    auto & counts = * message.mutable_counts();
    for (size_t i = 0; i < model.dim; ++i) {
        counts.Add(group.counts[i]);
    }
}

inline void group_dump (
        const DirichletProcessDiscrete &,
        const DirichletProcessDiscrete::Group & group,
        protobuf::DirichletProcessDiscrete::Group & message)
{
    message.Clear();
    auto & keys = * message.mutable_keys();
    auto & values = * message.mutable_values();
    for (const auto & pair : group.counts) {
        keys.Add(pair.first);
        values.Add(pair.second);
    }
}

inline void group_dump (
        const GammaPoisson &,
        const GammaPoisson::Group & group,
        protobuf::GammaPoisson::Group & message)
{
    message.set_count(group.count);
    message.set_sum(group.sum);
    message.set_log_prod(group.log_prod);
}

inline void group_dump (
        const NormalInverseChiSq &,
        const NormalInverseChiSq::Group & group,
        protobuf::NormalInverseChiSq::Group & message)
{
    message.set_count(group.count);
    message.set_mean(group.mean);
    message.set_count_times_variance(group.count_times_variance);
}

} // namespace distributions
<|endoftext|>


<commit_before>/*!
    \file console.cpp
    \brief Console management implementation
    \author Ivan Shynkarenka
    \date 29.07.2015
    \copyright MIT License
*/

#include "benchmark/console.h"

#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
#include <cstdio>
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif

namespace CppBenchmark {

std::ostream& operator<<(std::ostream& stream, Color color)
{
    Console::SetColor(color);
    return stream;
}

std::ostream& operator<<(std::ostream& stream, std::pair<Color, Color> colors)
{
    Console::SetColor(colors.first, colors.second);
    return stream;
}

void Console::SetColor(Color color, Color background)
{
#if defined(_WIN32) || defined(_WIN64)
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, (((WORD)color) & 0x0F) + ((((WORD)background) & 0x0F) << 4));
#elif defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
    const char* colors[] =
    {
        "\033[22;30m",  // Black color
        "\033[22;34m",  // Blue color
        "\033[22;32m",  // Green color
        "\033[22;36m",  // Cyan color
        "\033[22;31m",  // Red color
        "\033[22;35m",  // Magenta color
        "\033[22;33m",  // Brown color
        "\033[22;37m",  // Grey color
        "\033[01;30m",  // Dark grey color
        "\033[01;34m",  // Light blue color
        "\033[01;32m",  // Light green color
        "\033[01;36m",  // Light cyan color
        "\033[01;31m",  // Light red color
        "\033[01;35m",  // Light magenta color
        "\033[01;33m",  // Yellow color
        "\033[01;37m"   // White color
    };
    const char* backgrounds[] =
    {
        "\033[00000m",  // Black color
        "\033[02;44m",  // Blue color
        "\033[02;42m",  // Green color
        "\033[02;46m",  // Cyan color
        "\033[02;41m",  // Red color
        "\033[02;45m",  // Magenta color
        "\033[02;43m",  // Brown color
        "\033[02;47m",  // Grey color
        "\033[00;40m",  // Dark grey color
        "\033[00;44m",  // Light blue color
        "\033[00;42m",  // Light green color
        "\033[00;46m",  // Light cyan color
        "\033[00;41m",  // Light red color
        "\033[00;45m",  // Light magenta color
        "\033[00;43m",  // Yellow color
        "\033[00;47m"   // White color
    };
    std::fwrite(backgrounds[(int)background - (int)Color::BLACK], 1, 8, stdout);
    std::fwrite(colors[(int)color - (int)Color::BLACK], 1, 8, stdout);
#endif
}

} // namespace CppBenchmark
<commit_msg>Code clean<commit_after>/*!
    \file console.cpp
    \brief Console management implementation
    \author Ivan Shynkarenka
    \date 29.07.2015
    \copyright MIT License
*/

#include "benchmark/console.h"

#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
#include <cstdio>
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif

namespace CppBenchmark {

std::ostream& operator<<(std::ostream& stream, Color color)
{
    Console::SetColor(color);
    return stream;
}

std::ostream& operator<<(std::ostream& stream, std::pair<Color, Color> colors)
{
    Console::SetColor(colors.first, colors.second);
    return stream;
}

void Console::SetColor(Color color, Color background)
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
    const char* colors[] =
    {
        "\033[22;30m",  // Black color
        "\033[22;34m",  // Blue color
        "\033[22;32m",  // Green color
        "\033[22;36m",  // Cyan color
        "\033[22;31m",  // Red color
        "\033[22;35m",  // Magenta color
        "\033[22;33m",  // Brown color
        "\033[22;37m",  // Grey color
        "\033[01;30m",  // Dark grey color
        "\033[01;34m",  // Light blue color
        "\033[01;32m",  // Light green color
        "\033[01;36m",  // Light cyan color
        "\033[01;31m",  // Light red color
        "\033[01;35m",  // Light magenta color
        "\033[01;33m",  // Yellow color
        "\033[01;37m"   // White color
    };
    const char* backgrounds[] =
    {
        "\033[00000m",  // Black color
        "\033[02;44m",  // Blue color
        "\033[02;42m",  // Green color
        "\033[02;46m",  // Cyan color
        "\033[02;41m",  // Red color
        "\033[02;45m",  // Magenta color
        "\033[02;43m",  // Brown color
        "\033[02;47m",  // Grey color
        "\033[00;40m",  // Dark grey color
        "\033[00;44m",  // Light blue color
        "\033[00;42m",  // Light green color
        "\033[00;46m",  // Light cyan color
        "\033[00;41m",  // Light red color
        "\033[00;45m",  // Light magenta color
        "\033[00;43m",  // Yellow color
        "\033[00;47m"   // White color
    };
    std::fwrite(backgrounds[(int)background - (int)Color::BLACK], 1, 8, stdout);
    std::fwrite(colors[(int)color - (int)Color::BLACK], 1, 8, stdout);
#elif defined(_WIN32) || defined(_WIN64)
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, (((WORD)color) & 0x0F) + ((((WORD)background) & 0x0F) << 4));
#endif
}

} // namespace CppBenchmark
<|endoftext|>


<commit_before>// Copyright (c) 2011 Zeex
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <sampgdk/plugin.h>
#include <sampgdk/wrapper.h>

#include "amxapihooks.h"
#include "gamemode.h"

static std::string lastPublicName;

namespace sampgdk {

int AmxApiHooks::Register(AMX *amx, AMX_NATIVE_INFO *nativelist, int number) {
    AmxApiHooks::GetInstance()->amxRegisterHook.Remove();

    int error = amx_Register(amx, nativelist, number);

    for (int i = 0; nativelist[i].name != 0 && (i < number || number == -1); ++i) {
        sampgdk::Wrapper::GetInstance()->SetNative(nativelist[i].name, nativelist[i].func);
    }

    // Fix funcidx
    extern cell AMX_NATIVE_CALL funcidx(AMX *amx, cell *params);
    HookNative(amx, "funcidx", funcidx);

    AmxApiHooks::GetInstance()->amxRegisterHook.Reinstall();

    return error;
}

int AmxApiHooks::FindPublic(AMX *amx, const char *name, int *index) {
    AmxApiHooks::GetInstance()->amxFindPublicHook.Remove();

    int error = amx_FindPublic(amx, name, index);

    if (amx == GetGameMode() && GetGameMode() != 0) {
        if (error != AMX_ERR_NONE) {
            // Make it think that any public it wants does exist.
            *index = AMX_EXEC_GDK;
            error = AMX_ERR_NONE;
        }
        ::lastPublicName = name;
    }

    AmxApiHooks::GetInstance()->amxFindPublicHook.Reinstall();

    return error;
}

int AmxApiHooks::Exec(AMX *amx, cell *retval, int index) {
    AmxApiHooks::GetInstance()->amxExecHook.Remove();

    int error = AMX_ERR_NONE;
    if (index == AMX_EXEC_MAIN) {
        // main() is being called -> this is the game mode.
        SetGameMode(amx);
        // OnGameModeInit is called before main so we must exec it manually somehow.
        sampgdk::Wrapper::GetInstance()->ExecutePublicHook(amx, retval, "OnGameModeInit");
        // Allow calls to main()
        error = amx_Exec(amx, retval, index);
    } else {
        // Check whether we deal with a game mode
        if (amx == GetGameMode() && GetGameMode() != 0) {
            bool canDoExec = true;
            if (index != AMX_EXEC_MAIN && index != AMX_EXEC_CONT) {
                // Handle this public call.
                canDoExec = sampgdk::Wrapper::GetInstance()->ExecutePublicHook(
                    GetGameMode(), retval, ::lastPublicName);
            }
            // The handler could return a value indicating that the call should
            // not be propagated to the gamemode or other handlers, if any (there can
            // be multiple handlers since recently).
            if (canDoExec) {
                error = amx_Exec(amx, retval, index);
                if (error == AMX_ERR_INDEX && index == AMX_EXEC_GDK) {
                    // Return no error if it's our fault that it executes a non-existing public.
                    error = AMX_ERR_NONE;
                }
            }
        } else {
            // Not a game mode - just call the original amx_Exec.
            error = amx_Exec(amx, retval, index);
        }
    }

    AmxApiHooks::GetInstance()->amxExecHook.Reinstall();

    return error;
}

AmxApiHooks::AmxApiHooks() {}

void AmxApiHooks::Initialize(void **amxExportsTable) {
    amxRegisterHook.Install(amxExportsTable[PLUGIN_AMX_EXPORT_Register], (void*)Register);
    amxFindPublicHook.Install(amxExportsTable[PLUGIN_AMX_EXPORT_FindPublic], (void*)FindPublic);
    amxExecHook.Install(amxExportsTable[PLUGIN_AMX_EXPORT_Exec], (void*)Exec);
}

} // namespace sampgdk
<commit_msg>Revert "Remove #include "hooknative.h" as it doesn't exist"<commit_after>// Copyright (c) 2011 Zeex
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <sampgdk/plugin.h>
#include <sampgdk/wrapper.h>

#include "amxapihooks.h"
#include "gamemode.h"
#include "hooknative.h"

static std::string lastPublicName;

namespace sampgdk {

int AmxApiHooks::Register(AMX *amx, AMX_NATIVE_INFO *nativelist, int number) {
    AmxApiHooks::GetInstance()->amxRegisterHook.Remove();

    int error = amx_Register(amx, nativelist, number);

    for (int i = 0; nativelist[i].name != 0 && (i < number || number == -1); ++i) {
        sampgdk::Wrapper::GetInstance()->SetNative(nativelist[i].name, nativelist[i].func);
    }

    // Fix funcidx
    extern cell AMX_NATIVE_CALL funcidx(AMX *amx, cell *params);
    HookNative(amx, "funcidx", funcidx);

    AmxApiHooks::GetInstance()->amxRegisterHook.Reinstall();

    return error;
}

int AmxApiHooks::FindPublic(AMX *amx, const char *name, int *index) {
    AmxApiHooks::GetInstance()->amxFindPublicHook.Remove();

    int error = amx_FindPublic(amx, name, index);

    if (amx == GetGameMode() && GetGameMode() != 0) {
        if (error != AMX_ERR_NONE) {
            // Make it think that any public it wants does exist.
            *index = AMX_EXEC_GDK;
            error = AMX_ERR_NONE;
        }
        ::lastPublicName = name;
    }

    AmxApiHooks::GetInstance()->amxFindPublicHook.Reinstall();

    return error;
}

int AmxApiHooks::Exec(AMX *amx, cell *retval, int index) {
    AmxApiHooks::GetInstance()->amxExecHook.Remove();

    int error = AMX_ERR_NONE;
    if (index == AMX_EXEC_MAIN) {
        // main() is being called -> this is the game mode.
        SetGameMode(amx);
        // OnGameModeInit is called before main so we must exec it manually somehow.
        sampgdk::Wrapper::GetInstance()->ExecutePublicHook(amx, retval, "OnGameModeInit");
        // Allow calls to main()
        error = amx_Exec(amx, retval, index);
    } else {
        // Check whether we deal with a game mode
        if (amx == GetGameMode() && GetGameMode() != 0) {
            bool canDoExec = true;
            if (index != AMX_EXEC_MAIN && index != AMX_EXEC_CONT) {
                // Handle this public call.
                canDoExec = sampgdk::Wrapper::GetInstance()->ExecutePublicHook(
                    GetGameMode(), retval, ::lastPublicName);
            }
            // The handler could return a value indicating that the call should
            // not be propagated to the gamemode or other handlers, if any (there can
            // be multiple handlers since recently).
            if (canDoExec) {
                error = amx_Exec(amx, retval, index);
                if (error == AMX_ERR_INDEX && index == AMX_EXEC_GDK) {
                    // Return no error if it's our fault that it executes a non-existing public.
                    error = AMX_ERR_NONE;
                }
            }
        } else {
            // Not a game mode - just call the original amx_Exec.
            error = amx_Exec(amx, retval, index);
        }
    }

    AmxApiHooks::GetInstance()->amxExecHook.Reinstall();

    return error;
}

AmxApiHooks::AmxApiHooks() {}

void AmxApiHooks::Initialize(void **amxExportsTable) {
    amxRegisterHook.Install(amxExportsTable[PLUGIN_AMX_EXPORT_Register], (void*)Register);
    amxFindPublicHook.Install(amxExportsTable[PLUGIN_AMX_EXPORT_FindPublic], (void*)FindPublic);
    amxExecHook.Install(amxExportsTable[PLUGIN_AMX_EXPORT_Exec], (void*)Exec);
}

} // namespace sampgdk
<|endoftext|>


<commit_before>#include "./application.h"
#include <QQmlContext>
#include <QStateMachine>
#include <QDebug>
#include <vector>
#include "./window.h"
#include "./scene.h"
#include "./scene_controller.h"
#include "./nodes.h"
#include "./nodes_controller.h"
#include "./label_node.h"
#include "./input/invoke_manager.h"
#include "./input/signal_manager.h"
#include "./input/scxml_importer.h"
#include "./mouse_shape_controller.h"
#include "./labeller_model.h"
#include "./placement_labeller_model.h"
#include "./labels_model.h"
#include "./camera_positions_model.h"
#include "./labelling/labels.h"
#include "./labelling_coordinator.h"
#include "./labelling_controller.h"
#include "./picking_controller.h"
#include "./forces_visualizer_node.h"
#include "./camera_node.h"
#include "./default_scene_creator.h"
#include "./video_recorder.h"
#include "./video_recorder_controller.h"
#include "./texture_mapper_manager.h"
#include "./texture_mapper_manager_controller.h"
#include "./utils/memory.h"
#include "./utils/path_helper.h"
#include "./recording_automation.h"
#include "./recording_automation_controller.h"

const int LAYER_COUNT = 4;

Application::Application(int &argc, char **argv) : application(argc, argv)
{
  application.setApplicationName("voly-labeller");
  application.setApplicationVersion("0.0.1");
  application.setOrganizationName("LBI");

  setupCommandLineParser();
  parser.process(application);
  invokeManager = std::make_shared<InvokeManager>();

  nodes = std::make_shared<Nodes>();
  nodesController = std::make_shared<NodesController>(nodes);

  labels = std::make_shared<Labels>();
  forcesLabeller = std::make_shared<Forces::Labeller>(labels);

  int layerCount = parseLayerCount();

  auto labellingCoordinator = std::make_shared<LabellingCoordinator>(
      layerCount, forcesLabeller, labels, nodes);

  bool synchronousCapturing = parser.isSet("offline");
  const float offlineFPS = 24;
  videoRecorder =
      std::make_shared<VideoRecorder>(synchronousCapturing, offlineFPS);
  videoRecorderController =
      std::make_unique<VideoRecorderController>(videoRecorder);
  recordingAutomation = std::make_shared<RecordingAutomation>(
      labellingCoordinator, nodes, videoRecorder);
  if (parser.isSet("screenshot"))
    recordingAutomation->takeScreenshotOfPositionAndExit(
        parser.value("screenshot").toStdString());

  recordingAutomationController =
      std::make_unique<RecordingAutomationController>(recordingAutomation);

  const int postProcessingTextureSize = 512;
  textureMapperManager =
      std::make_shared<TextureMapperManager>(postProcessingTextureSize);
  textureMapperManagerController =
      std::make_unique<TextureMapperManagerController>(textureMapperManager);
  scene = std::make_shared<Scene>(layerCount, invokeManager, nodes, labels,
                                  labellingCoordinator, textureMapperManager,
                                  recordingAutomation);

  float offlineRenderingFrameTime =
      parser.isSet("offline") ? 1.0f / offlineFPS : 0.0f;
  window =
      std::make_unique<Window>(scene, videoRecorder, offlineRenderingFrameTime);

  sceneController = std::make_unique<SceneController>(scene);
  labellerModel = std::make_unique<LabellerModel>(forcesLabeller);
  placementLabellerModel =
      std::make_unique<PlacementLabellerModel>(labellingCoordinator);
  cameraPositionsModel = std::make_unique<CameraPositionsModel>(nodes);
  mouseShapeController = std::make_unique<MouseShapeController>();
  pickingController = std::make_shared<PickingController>(scene);
  labelsModel = std::make_unique<LabelsModel>(labels, pickingController);
  labellingController =
      std::make_unique<LabellingController>(labellingCoordinator);
}

Application::~Application()
{
}

int Application::execute()
{
  qInfo() << "Application start";

  auto unsubscribeLabelChanges = labels->subscribe(
      std::bind(&Application::onLabelChangedUpdateLabelNodes, this,
                std::placeholders::_1, std::placeholders::_2));

  setupWindow();

  connect(labellerModel.get(), &LabellerModel::isVisibleChanged, this,
          &Application::onFocesLabellerModelIsVisibleChanged);

  window->setSource(QUrl("qrc:ui.qml"));

  forcesLabeller->resize(window->size().width(), window->size().height());

  nodes->setOnNodeAdded(
      [this](std::shared_ptr<Node> node) { this->onNodeAdded(node); });

  nodes->getCameraNode()->setOnCameraPositionsChanged(
      [this](std::vector<CameraPosition> cameraPositions) {
        this->cameraPositionsModel->update(cameraPositions);
      });

  if (parser.positionalArguments().size())
  {
    auto absolutePath = QDir(parser.positionalArguments()[0]).absolutePath();
    auto filename = absolutePathToProjectRelativePath(absolutePath);
    qInfo() << "import scene:" << filename;
    nodesController->addSceneNodesFrom(filename);
  }
  else
  {
    DefaultSceneCreator sceneCreator(nodes, labels);
    sceneCreator.create();
  }

  createAndStartStateMachine();

  window->show();

  auto resultCode = application.exec();

  unsubscribeLabelChanges();

  return resultCode;
}

void Application::setupCommandLineParser()
{
  QGuiApplication::setApplicationName("voly-labeller");
  QGuiApplication::setApplicationVersion("0.1");

  parser.setApplicationDescription(
      "Multiple labelling implementations for volume rendered medical data");
  parser.addHelpOption();
  parser.addVersionOption();
  parser.addPositionalArgument(
      "scene", QCoreApplication::translate("main", "Scene file to load."));
  QCommandLineOption offlineRenderingOption("offline",
                                            "Enables offline rendering");
  parser.addOption(offlineRenderingOption);

  QCommandLineOption layersOption("layers", "Number of layers. Default is 4",
                                  "layerCount", "4");
  parser.addOption(layersOption);

  QCommandLineOption screenshotOption(
      QStringList() << "s"
                    << "screenshot",
      "Takes a screenshot of the given camera position", "Camera Position");
  parser.addOption(screenshotOption);
}

void Application::setupWindow()
{
  window->setResizeMode(QQuickView::SizeRootObjectToView);
  auto context = window->rootContext();
  auto assetsPath =
      QUrl::fromLocalFile(absolutePathOfProjectRelativePath(QString("assets")));
  context->setContextProperty("assetsPath", assetsPath);
  auto projectRootPath =
      QUrl::fromLocalFile(absolutePathOfProjectRelativePath(QString(".")));
  context->setContextProperty("projectRootPath", projectRootPath);

  context->setContextProperty("window", window.get());
  context->setContextProperty("nodes", nodesController.get());
  context->setContextProperty("bufferTextures",
                              textureMapperManagerController.get());
  context->setContextProperty("scene", sceneController.get());
  context->setContextProperty("labeller", labellerModel.get());
  context->setContextProperty("placement", placementLabellerModel.get());
  context->setContextProperty("cameraPositions", cameraPositionsModel.get());
  context->setContextProperty("labels", labelsModel.get());
  context->setContextProperty("labelling", labellingController.get());
  context->setContextProperty("videoRecorder", videoRecorderController.get());
  context->setContextProperty("automation",
                              recordingAutomationController.get());
}

void Application::createAndStartStateMachine()
{
  auto signalManager = std::shared_ptr<SignalManager>(new SignalManager());
  ScxmlImporter importer(QUrl::fromLocalFile("config/states.xml"),
                         invokeManager, signalManager);

  invokeManager->addHandler(window.get());
  invokeManager->addHandler("mouseShape", mouseShapeController.get());
  invokeManager->addHandler("picking", pickingController.get());
  invokeManager->addHandler("scene", sceneController.get());
  signalManager->addSender("KeyboardEventSender", window.get());
  signalManager->addSender("window", window.get());
  signalManager->addSender("labels", labelsModel.get());

  stateMachine = importer.import();

  // just for printCurrentState slot for debugging
  window->stateMachine = stateMachine;

  stateMachine->start();
}

void Application::onNodeAdded(std::shared_ptr<Node> node)
{
  std::shared_ptr<LabelNode> labelNode =
      std::dynamic_pointer_cast<LabelNode>(node);
  if (labelNode.get())
  {
    labelNode->anchorSize = nodesController->getAnchorSize();
    labels->add(labelNode->label);
  }

  std::shared_ptr<CameraNode> cameraNode =
      std::dynamic_pointer_cast<CameraNode>(node);
  if (cameraNode.get())
  {
    cameraNode->setOnCameraPositionsChanged(
        [this](std::vector<CameraPosition> cameraPositions) {
          this->cameraPositionsModel->update(cameraPositions);
        });
  }
}

void Application::onLabelChangedUpdateLabelNodes(Labels::Action action,
                                                 const Label &label)
{
  auto labelNodes = nodes->getLabelNodes();
  auto labelNode = std::find_if(labelNodes.begin(), labelNodes.end(),
                                [label](std::shared_ptr<LabelNode> labelNode) {
                                  return labelNode->label.id == label.id;
                                });

  if (labelNode == labelNodes.end())
  {
    nodes->addNode(std::make_shared<LabelNode>(label));
  }
  else if (action == Labels::Action::Delete)
  {
    nodes->removeNode(*labelNode);
  }
  else
  {
    (*labelNode)->label = label;
  }
};

void Application::onFocesLabellerModelIsVisibleChanged()
{
  if (labellerModel->getIsVisible())
  {
    nodes->addForcesVisualizerNode(
        std::make_shared<ForcesVisualizerNode>(forcesLabeller));
  }
  else
  {
    nodes->removeForcesVisualizerNode();
  }
}

int Application::parseLayerCount()
{
  int layerCount = 4;
  if (parser.isSet("layers"))
  {
    bool gotLayerCount = true;
    layerCount = parser.value("layers").toInt(&gotLayerCount);
    if (!gotLayerCount)
    {
      layerCount = 4;
      qWarning() << "Problem parsing layer count from"
                 << parser.value("layers");
    }
  }

  return layerCount;
}

<commit_msg>Check whether the given layers parameter is in a valid range.<commit_after>#include "./application.h"
#include <QQmlContext>
#include <QStateMachine>
#include <QDebug>
#include <vector>
#include "./window.h"
#include "./scene.h"
#include "./scene_controller.h"
#include "./nodes.h"
#include "./nodes_controller.h"
#include "./label_node.h"
#include "./input/invoke_manager.h"
#include "./input/signal_manager.h"
#include "./input/scxml_importer.h"
#include "./mouse_shape_controller.h"
#include "./labeller_model.h"
#include "./placement_labeller_model.h"
#include "./labels_model.h"
#include "./camera_positions_model.h"
#include "./labelling/labels.h"
#include "./labelling_coordinator.h"
#include "./labelling_controller.h"
#include "./picking_controller.h"
#include "./forces_visualizer_node.h"
#include "./camera_node.h"
#include "./default_scene_creator.h"
#include "./video_recorder.h"
#include "./video_recorder_controller.h"
#include "./texture_mapper_manager.h"
#include "./texture_mapper_manager_controller.h"
#include "./utils/memory.h"
#include "./utils/path_helper.h"
#include "./recording_automation.h"
#include "./recording_automation_controller.h"

Application::Application(int &argc, char **argv) : application(argc, argv)
{
  application.setApplicationName("voly-labeller");
  application.setApplicationVersion("0.0.1");
  application.setOrganizationName("LBI");

  setupCommandLineParser();
  parser.process(application);
  invokeManager = std::make_shared<InvokeManager>();

  nodes = std::make_shared<Nodes>();
  nodesController = std::make_shared<NodesController>(nodes);

  labels = std::make_shared<Labels>();
  forcesLabeller = std::make_shared<Forces::Labeller>(labels);

  int layerCount = parseLayerCount();

  auto labellingCoordinator = std::make_shared<LabellingCoordinator>(
      layerCount, forcesLabeller, labels, nodes);

  bool synchronousCapturing = parser.isSet("offline");
  const float offlineFPS = 24;
  videoRecorder =
      std::make_shared<VideoRecorder>(synchronousCapturing, offlineFPS);
  videoRecorderController =
      std::make_unique<VideoRecorderController>(videoRecorder);
  recordingAutomation = std::make_shared<RecordingAutomation>(
      labellingCoordinator, nodes, videoRecorder);
  if (parser.isSet("screenshot"))
    recordingAutomation->takeScreenshotOfPositionAndExit(
        parser.value("screenshot").toStdString());

  recordingAutomationController =
      std::make_unique<RecordingAutomationController>(recordingAutomation);

  const int postProcessingTextureSize = 512;
  textureMapperManager =
      std::make_shared<TextureMapperManager>(postProcessingTextureSize);
  textureMapperManagerController =
      std::make_unique<TextureMapperManagerController>(textureMapperManager);
  scene = std::make_shared<Scene>(layerCount, invokeManager, nodes, labels,
                                  labellingCoordinator, textureMapperManager,
                                  recordingAutomation);

  float offlineRenderingFrameTime =
      parser.isSet("offline") ? 1.0f / offlineFPS : 0.0f;
  window =
      std::make_unique<Window>(scene, videoRecorder, offlineRenderingFrameTime);

  sceneController = std::make_unique<SceneController>(scene);
  labellerModel = std::make_unique<LabellerModel>(forcesLabeller);
  placementLabellerModel =
      std::make_unique<PlacementLabellerModel>(labellingCoordinator);
  cameraPositionsModel = std::make_unique<CameraPositionsModel>(nodes);
  mouseShapeController = std::make_unique<MouseShapeController>();
  pickingController = std::make_shared<PickingController>(scene);
  labelsModel = std::make_unique<LabelsModel>(labels, pickingController);
  labellingController =
      std::make_unique<LabellingController>(labellingCoordinator);
}

Application::~Application()
{
}

int Application::execute()
{
  qInfo() << "Application start";

  auto unsubscribeLabelChanges = labels->subscribe(
      std::bind(&Application::onLabelChangedUpdateLabelNodes, this,
                std::placeholders::_1, std::placeholders::_2));

  setupWindow();

  connect(labellerModel.get(), &LabellerModel::isVisibleChanged, this,
          &Application::onFocesLabellerModelIsVisibleChanged);

  window->setSource(QUrl("qrc:ui.qml"));

  forcesLabeller->resize(window->size().width(), window->size().height());

  nodes->setOnNodeAdded(
      [this](std::shared_ptr<Node> node) { this->onNodeAdded(node); });

  nodes->getCameraNode()->setOnCameraPositionsChanged(
      [this](std::vector<CameraPosition> cameraPositions) {
        this->cameraPositionsModel->update(cameraPositions);
      });

  if (parser.positionalArguments().size())
  {
    auto absolutePath = QDir(parser.positionalArguments()[0]).absolutePath();
    auto filename = absolutePathToProjectRelativePath(absolutePath);
    qInfo() << "import scene:" << filename;
    nodesController->addSceneNodesFrom(filename);
  }
  else
  {
    DefaultSceneCreator sceneCreator(nodes, labels);
    sceneCreator.create();
  }

  createAndStartStateMachine();

  window->show();

  auto resultCode = application.exec();

  unsubscribeLabelChanges();

  return resultCode;
}

void Application::setupCommandLineParser()
{
  QGuiApplication::setApplicationName("voly-labeller");
  QGuiApplication::setApplicationVersion("0.1");

  parser.setApplicationDescription(
      "Multiple labelling implementations for volume rendered medical data");
  parser.addHelpOption();
  parser.addVersionOption();
  parser.addPositionalArgument(
      "scene", QCoreApplication::translate("main", "Scene file to load."));
  QCommandLineOption offlineRenderingOption("offline",
                                            "Enables offline rendering");
  parser.addOption(offlineRenderingOption);

  QCommandLineOption layersOption("layers", "Number of layers. Default is 4",
                                  "layerCount", "4");
  parser.addOption(layersOption);

  QCommandLineOption screenshotOption(
      QStringList() << "s"
                    << "screenshot",
      "Takes a screenshot of the given camera position", "Camera Position");
  parser.addOption(screenshotOption);
}

void Application::setupWindow()
{
  window->setResizeMode(QQuickView::SizeRootObjectToView);
  auto context = window->rootContext();
  auto assetsPath =
      QUrl::fromLocalFile(absolutePathOfProjectRelativePath(QString("assets")));
  context->setContextProperty("assetsPath", assetsPath);
  auto projectRootPath =
      QUrl::fromLocalFile(absolutePathOfProjectRelativePath(QString(".")));
  context->setContextProperty("projectRootPath", projectRootPath);

  context->setContextProperty("window", window.get());
  context->setContextProperty("nodes", nodesController.get());
  context->setContextProperty("bufferTextures",
                              textureMapperManagerController.get());
  context->setContextProperty("scene", sceneController.get());
  context->setContextProperty("labeller", labellerModel.get());
  context->setContextProperty("placement", placementLabellerModel.get());
  context->setContextProperty("cameraPositions", cameraPositionsModel.get());
  context->setContextProperty("labels", labelsModel.get());
  context->setContextProperty("labelling", labellingController.get());
  context->setContextProperty("videoRecorder", videoRecorderController.get());
  context->setContextProperty("automation",
                              recordingAutomationController.get());
}

void Application::createAndStartStateMachine()
{
  auto signalManager = std::shared_ptr<SignalManager>(new SignalManager());
  ScxmlImporter importer(QUrl::fromLocalFile("config/states.xml"),
                         invokeManager, signalManager);

  invokeManager->addHandler(window.get());
  invokeManager->addHandler("mouseShape", mouseShapeController.get());
  invokeManager->addHandler("picking", pickingController.get());
  invokeManager->addHandler("scene", sceneController.get());
  signalManager->addSender("KeyboardEventSender", window.get());
  signalManager->addSender("window", window.get());
  signalManager->addSender("labels", labelsModel.get());

  stateMachine = importer.import();

  // just for printCurrentState slot for debugging
  window->stateMachine = stateMachine;

  stateMachine->start();
}

void Application::onNodeAdded(std::shared_ptr<Node> node)
{
  std::shared_ptr<LabelNode> labelNode =
      std::dynamic_pointer_cast<LabelNode>(node);
  if (labelNode.get())
  {
    labelNode->anchorSize = nodesController->getAnchorSize();
    labels->add(labelNode->label);
  }

  std::shared_ptr<CameraNode> cameraNode =
      std::dynamic_pointer_cast<CameraNode>(node);
  if (cameraNode.get())
  {
    cameraNode->setOnCameraPositionsChanged(
        [this](std::vector<CameraPosition> cameraPositions) {
          this->cameraPositionsModel->update(cameraPositions);
        });
  }
}

void Application::onLabelChangedUpdateLabelNodes(Labels::Action action,
                                                 const Label &label)
{
  auto labelNodes = nodes->getLabelNodes();
  auto labelNode = std::find_if(labelNodes.begin(), labelNodes.end(),
                                [label](std::shared_ptr<LabelNode> labelNode) {
                                  return labelNode->label.id == label.id;
                                });

  if (labelNode == labelNodes.end())
  {
    nodes->addNode(std::make_shared<LabelNode>(label));
  }
  else if (action == Labels::Action::Delete)
  {
    nodes->removeNode(*labelNode);
  }
  else
  {
    (*labelNode)->label = label;
  }
};

void Application::onFocesLabellerModelIsVisibleChanged()
{
  if (labellerModel->getIsVisible())
  {
    nodes->addForcesVisualizerNode(
        std::make_shared<ForcesVisualizerNode>(forcesLabeller));
  }
  else
  {
    nodes->removeForcesVisualizerNode();
  }
}

int Application::parseLayerCount()
{
  int layerCount = 4;
  if (parser.isSet("layers"))
  {
    bool gotLayerCount = true;
    layerCount = parser.value("layers").toInt(&gotLayerCount);
    if (!gotLayerCount)
    {
      layerCount = 4;
      qWarning() << "Problem parsing layer count from"
                 << parser.value("layers");
    }

    if (layerCount < 1 || layerCount > 6)
      qFatal("Layer count must be between 1 and 6");
  }

  return layerCount;
}

<|endoftext|>


<commit_before>// Read an INI file into easy-to-access name/value pairs.
// this code is based on https://github.com/Blandinium/inih/blob/master/cpp/INIReader.cpp 61bf1b3  on Dec 18, 2014

#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <iostream>
#include <fstream>

#include "ini.h"
#include "INIFile.h"

#include <SmurffCpp/Utils/Error.h>

INIFile::INIFile()
   : m_error(0)
{
}

INIFile::~INIFile()
{
}

void INIFile::open(const std::string& filename)
{
   m_filePath = filename;
   m_error = ini_parse(filename.c_str(), ValueHandler, this);
   THROWERROR_ASSERT_MSG(!m_error, "Error opening file: " + filename);
}

void INIFile::create(const std::string& filename)
{
   m_filePath = filename;

   std::ofstream file;
   file.open(filename, std::ios::trunc);
   THROWERROR_ASSERT_MSG(file.is_open(), "Error opening file: " + filename);
   file.close();
}

int INIFile::getParseError() const
{
   return m_error;
}

std::string INIFile::get(const std::string& section, const std::string& name, const std::string& default_value) const
{
   std::string key = MakeKey(section, name);
   auto valuesIt = m_values.find(key);
   if (valuesIt == m_values.end())
      return default_value;
   else
      return valuesIt->second;
}

int INIFile::getInteger(const std::string& section, const std::string& name, int default_value) const
{
   std::string valstr = get(section, name, "");
   const char* value = valstr.c_str();
   char* end;
   // This parses "1234" (decimal) and also "0x4D2" (hex)
   long n = strtol(value, &end, 0);
   return end > value ? n : default_value;
}

double INIFile::getReal(const std::string& section, const std::string& name, double default_value) const
{
   std::string valstr = get(section, name, "");
   const char* value = valstr.c_str();
   char* end;
   double n = strtod(value, &end);
   return end > value ? n : default_value;
}

bool INIFile::getBoolean(const std::string& section, const std::string& name, bool default_value) const
{
   std::string valstr = get(section, name, "");
   // Convert to lower case to make string comparisons case-insensitive
   std::transform(valstr.begin(), valstr.end(), valstr.begin(), ::tolower);
   if (valstr == "true" || valstr == "yes" || valstr == "on" || valstr == "1")
      return true;
   else if (valstr == "false" || valstr == "no" || valstr == "off" || valstr == "0")
      return false;
   else
      return default_value;
}

std::string INIFile::get(const std::string& section, const std::string& name) const
{
   std::string key = MakeKey(section, name);
   auto valuesIt = m_values.find(key);
   if (valuesIt == m_values.end())
   {
      THROWERROR("section: " + section + " name:" + name + " not found");
   }
   else
   {
      return valuesIt->second;
   }
}

std::pair<bool, std::string> INIFile::tryGet(const std::string& section, const std::string& name) const
{
   std::string key = MakeKey(section, name);
   auto valuesIt = m_values.find(key);
   if (valuesIt == m_values.end())
      return std::make_pair(false, std::string());
   else
      return std::make_pair(true, valuesIt->second);
}

const std::set<std::string>& INIFile::getSections() const
{
   return m_sections;
}

bool INIFile::hasSection(const std::string &name) const
{
   return m_sections.find(name) != m_sections.end();
}

std::map<std::string, std::vector<std::string> >::const_iterator INIFile::getFields(const std::string& section) const
{
   auto fieldSetIt = m_fields.find(section);
   if (fieldSetIt == m_fields.end())
      THROWERROR("section: " + section + " not found");
   return fieldSetIt;
}

std::string INIFile::MakeKey(const std::string& section, const std::string& name)
{
   return section + "=" + name;
}

int INIFile::ValueHandler(void* user, const char* section, const char* name, const char* value)
{
   INIFile* reader = (INIFile*)user;

   reader->insertItem(section, name, value);

   return 1;
}

int INIFile::insertItem(const std::string& section, const std::string& name, const std::string& value)
{
   // Insert the section in the sections set
   m_sections.insert(section);

   // Add the value to the lookup map
   std::string key = MakeKey(section, name);

   auto valuesIt = m_values.find(key);
   if (valuesIt == m_values.end())
   {
      m_values.emplace(key, value);

      //if value was not in the lookup map - we need to add it in list of m_fields as well
      //we store fields in original order as vector so the only efficient way to make sure that values are unique
      //is to use m_values as a lookup first

      //create entry for new section if required
      auto fieldSetIt = m_fields.find(section);
      if (fieldSetIt == m_fields.end())
      {
         auto item = m_fields.emplace(section, std::vector<std::string>());
         fieldSetIt = item.first;
      }

      //add field name
      fieldSetIt->second.push_back(name);
   }
   else
   {
      std::cout << "Warning: duplicate key: '" << name << "' in section: '" << section << "'" << std::endl;
   }

   return 1;
}

bool INIFile::empty() const
{
   return m_values.empty() && m_sections.empty() && m_fields.empty();
}

void INIFile::appendItem(const std::string& section, const std::string& tag, const std::string& value)
{
   THROWERROR_ASSERT_MSG(section.size(), "Empty section in INI file");
   m_writeBuffer.push_back(std::make_pair(tag, value));

   insertItem(section, tag, value);
}

void INIFile::flush()
{
   std::ofstream file;
   file.open(m_filePath, std::ios::app);
   THROWERROR_ASSERT_MSG(file.is_open(), "Error opening file: " + m_filePath);

   for (auto& item : m_writeBuffer)
   {
      file << item.first << " = " << item.second << std::endl;
   }

   file.close();

   m_writeBuffer.clear();
}

void INIFile::removeItem(const std::string& section, const std::string& tag)
{
   //create a key
   std::string key = MakeKey(section, tag);

   //try erase value from values map
   auto valuesIt = m_values.find(key);
   if (valuesIt != m_values.end())
      m_values.erase(valuesIt);

   //try find section in field groups
   auto fieldsGroupIt = m_fields.find(section);
   if (fieldsGroupIt != m_fields.end())
   {
      //try find field in field group
      for (auto fieldIt = fieldsGroupIt->second.begin(); fieldIt != fieldsGroupIt->second.end(); ++fieldIt)
      {
         //erase field from section
         if (*fieldIt == tag)
         {
            fieldsGroupIt->second.erase(fieldIt);
            break;
         }
      }

      //check if section is now empty
      if (fieldsGroupIt->second.empty())
      {
         //try erase section from sections map
         auto sectionsIt = m_sections.find(fieldsGroupIt->first);
         if (sectionsIt != m_sections.end())
            m_sections.erase(sectionsIt);

         //erase section from field groups
         m_fields.erase(fieldsGroupIt);
      }
   }
}

void INIFile::appendComment(const std::string& comment)
{
   //flush everything that is buffered before comment is written directly to file
   flush();

   std::ofstream file;
   file.open(m_filePath, std::ios::app);
   THROWERROR_ASSERT_MSG(file.is_open(), "Error opening file: " + m_filePath);
   file << "#" << comment << std::endl;
   file.close();
}

void INIFile::startSection(const std::string& section)
{
   //flush everything that is buffered before section header is written directly to file
   flush();

   std::ofstream file;
   file.open(m_filePath, std::ios::app);
   THROWERROR_ASSERT_MSG(file.is_open(), "Error opening file: " + m_filePath);
   file << std::endl << "[" << section << "]" << std::endl;
   file.close();

   m_sections.insert(section);
}

void INIFile::endSection()
{
   //header of section on startSecion is written to file without buffering
   //before starting new section - we need to flush all current buffered content to the file
   flush();
}
<commit_msg>FIX: remove unneeded c-headers causing problems on MacOs<commit_after>// Read an INI file into easy-to-access name/value pairs.
// this code is based on https://github.com/Blandinium/inih/blob/master/cpp/INIReader.cpp 61bf1b3  on Dec 18, 2014

#include <iostream>
#include <fstream>
#include <algorithm>

#include "ini.h"
#include "INIFile.h"

#include <SmurffCpp/Utils/Error.h>

INIFile::INIFile()
   : m_error(0)
{
}

INIFile::~INIFile()
{
}

void INIFile::open(const std::string& filename)
{
   m_filePath = filename;
   m_error = ini_parse(filename.c_str(), ValueHandler, this);
   THROWERROR_ASSERT_MSG(!m_error, "Error opening file: " + filename);
}

void INIFile::create(const std::string& filename)
{
   m_filePath = filename;

   std::ofstream file;
   file.open(filename, std::ios::trunc);
   THROWERROR_ASSERT_MSG(file.is_open(), "Error opening file: " + filename);
   file.close();
}

int INIFile::getParseError() const
{
   return m_error;
}

std::string INIFile::get(const std::string& section, const std::string& name, const std::string& default_value) const
{
   std::string key = MakeKey(section, name);
   auto valuesIt = m_values.find(key);
   if (valuesIt == m_values.end())
      return default_value;
   else
      return valuesIt->second;
}

int INIFile::getInteger(const std::string& section, const std::string& name, int default_value) const
{
   std::string valstr = get(section, name, "");
   const char* value = valstr.c_str();
   char* end;
   // This parses "1234" (decimal) and also "0x4D2" (hex)
   long n = strtol(value, &end, 0);
   return end > value ? n : default_value;
}

double INIFile::getReal(const std::string& section, const std::string& name, double default_value) const
{
   std::string valstr = get(section, name, "");
   const char* value = valstr.c_str();
   char* end;
   double n = strtod(value, &end);
   return end > value ? n : default_value;
}

bool INIFile::getBoolean(const std::string& section, const std::string& name, bool default_value) const
{
   std::string valstr = get(section, name, "");
   // Convert to lower case to make string comparisons case-insensitive
   std::transform(valstr.begin(), valstr.end(), valstr.begin(), ::tolower);
   if (valstr == "true" || valstr == "yes" || valstr == "on" || valstr == "1")
      return true;
   else if (valstr == "false" || valstr == "no" || valstr == "off" || valstr == "0")
      return false;
   else
      return default_value;
}

std::string INIFile::get(const std::string& section, const std::string& name) const
{
   std::string key = MakeKey(section, name);
   auto valuesIt = m_values.find(key);
   if (valuesIt == m_values.end())
   {
      THROWERROR("section: " + section + " name:" + name + " not found");
   }
   else
   {
      return valuesIt->second;
   }
}

std::pair<bool, std::string> INIFile::tryGet(const std::string& section, const std::string& name) const
{
   std::string key = MakeKey(section, name);
   auto valuesIt = m_values.find(key);
   if (valuesIt == m_values.end())
      return std::make_pair(false, std::string());
   else
      return std::make_pair(true, valuesIt->second);
}

const std::set<std::string>& INIFile::getSections() const
{
   return m_sections;
}

bool INIFile::hasSection(const std::string &name) const
{
   return m_sections.find(name) != m_sections.end();
}

std::map<std::string, std::vector<std::string> >::const_iterator INIFile::getFields(const std::string& section) const
{
   auto fieldSetIt = m_fields.find(section);
   if (fieldSetIt == m_fields.end())
      THROWERROR("section: " + section + " not found");
   return fieldSetIt;
}

std::string INIFile::MakeKey(const std::string& section, const std::string& name)
{
   return section + "=" + name;
}

int INIFile::ValueHandler(void* user, const char* section, const char* name, const char* value)
{
   INIFile* reader = (INIFile*)user;

   reader->insertItem(section, name, value);

   return 1;
}

int INIFile::insertItem(const std::string& section, const std::string& name, const std::string& value)
{
   // Insert the section in the sections set
   m_sections.insert(section);

   // Add the value to the lookup map
   std::string key = MakeKey(section, name);

   auto valuesIt = m_values.find(key);
   if (valuesIt == m_values.end())
   {
      m_values.emplace(key, value);

      //if value was not in the lookup map - we need to add it in list of m_fields as well
      //we store fields in original order as vector so the only efficient way to make sure that values are unique
      //is to use m_values as a lookup first

      //create entry for new section if required
      auto fieldSetIt = m_fields.find(section);
      if (fieldSetIt == m_fields.end())
      {
         auto item = m_fields.emplace(section, std::vector<std::string>());
         fieldSetIt = item.first;
      }

      //add field name
      fieldSetIt->second.push_back(name);
   }
   else
   {
      std::cout << "Warning: duplicate key: '" << name << "' in section: '" << section << "'" << std::endl;
   }

   return 1;
}

bool INIFile::empty() const
{
   return m_values.empty() && m_sections.empty() && m_fields.empty();
}

void INIFile::appendItem(const std::string& section, const std::string& tag, const std::string& value)
{
   THROWERROR_ASSERT_MSG(section.size(), "Empty section in INI file");
   m_writeBuffer.push_back(std::make_pair(tag, value));

   insertItem(section, tag, value);
}

void INIFile::flush()
{
   std::ofstream file;
   file.open(m_filePath, std::ios::app);
   THROWERROR_ASSERT_MSG(file.is_open(), "Error opening file: " + m_filePath);

   for (auto& item : m_writeBuffer)
   {
      file << item.first << " = " << item.second << std::endl;
   }

   file.close();

   m_writeBuffer.clear();
}

void INIFile::removeItem(const std::string& section, const std::string& tag)
{
   //create a key
   std::string key = MakeKey(section, tag);

   //try erase value from values map
   auto valuesIt = m_values.find(key);
   if (valuesIt != m_values.end())
      m_values.erase(valuesIt);

   //try find section in field groups
   auto fieldsGroupIt = m_fields.find(section);
   if (fieldsGroupIt != m_fields.end())
   {
      //try find field in field group
      for (auto fieldIt = fieldsGroupIt->second.begin(); fieldIt != fieldsGroupIt->second.end(); ++fieldIt)
      {
         //erase field from section
         if (*fieldIt == tag)
         {
            fieldsGroupIt->second.erase(fieldIt);
            break;
         }
      }

      //check if section is now empty
      if (fieldsGroupIt->second.empty())
      {
         //try erase section from sections map
         auto sectionsIt = m_sections.find(fieldsGroupIt->first);
         if (sectionsIt != m_sections.end())
            m_sections.erase(sectionsIt);

         //erase section from field groups
         m_fields.erase(fieldsGroupIt);
      }
   }
}

void INIFile::appendComment(const std::string& comment)
{
   //flush everything that is buffered before comment is written directly to file
   flush();

   std::ofstream file;
   file.open(m_filePath, std::ios::app);
   THROWERROR_ASSERT_MSG(file.is_open(), "Error opening file: " + m_filePath);
   file << "#" << comment << std::endl;
   file.close();
}

void INIFile::startSection(const std::string& section)
{
   //flush everything that is buffered before section header is written directly to file
   flush();

   std::ofstream file;
   file.open(m_filePath, std::ios::app);
   THROWERROR_ASSERT_MSG(file.is_open(), "Error opening file: " + m_filePath);
   file << std::endl << "[" << section << "]" << std::endl;
   file.close();

   m_sections.insert(section);
}

void INIFile::endSection()
{
   //header of section on startSecion is written to file without buffering
   //before starting new section - we need to flush all current buffered content to the file
   flush();
}
<|endoftext|>


<commit_before>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2014 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

#include "StandardExpressionVisualizations.h"

#include "../OOVisualizationException.h"

#include "VisualizationBase/src/items/Static.h"
#include "VisualizationBase/src/items/NodeWrapper.h"

#define BEGIN_STANDARD_EXPRESSION_VISUALIZATION_BASE(apiSpecification, className, nodeType)									\
ITEM_COMMON_DEFINITIONS(className, "item")																									\
																																							\
className::className(::Visualization::Item* parent, NodeType* node, const StyleType* style)									\
	: Super{parent, node, style}{}																												\
																																							\
void className::determineChildren()																												\
{																																							\
	int index = 0;																																		\

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

#define BEGIN_STANDARD_EXPRESSION_VISUALIZATION(apiSpecification, className, nodeType)											\
BEGIN_STANDARD_EXPRESSION_VISUALIZATION_BASE(apiSpecification, className, nodeType)												\
	const ::OOVisualization::OperatorStyle* opStyle = style();																			\
	layout()->setStyle( &opStyle->layout());																									\

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

#define BEGIN_STANDARD_ENUMERATION_EXPRESSION_VISUALIZATION(apiSpecification, className, nodeType, enumeration)		\
BEGIN_STANDARD_EXPRESSION_VISUALIZATION_BASE(apiSpecification, className, nodeType)												\
																																							\
	const ::OOVisualization::OperatorStyle* opStyle = &style()->op( (int) node()->enumeration() );							\
	layout()->setStyle( &opStyle->layout());																									\

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

#define BEGIN_STANDARD_FLAG_EXPRESSION_VISUALIZATION(apiSpecification, className, nodeType, flag)							\
BEGIN_STANDARD_EXPRESSION_VISUALIZATION_BASE(apiSpecification, className, nodeType)												\
																																							\
	int f = node()->flag();																															\
	if (!f) throw new ::OOVisualization::OOVisualizationException{"Visualization does not have a flag set."};			\
	int i = 0;																																			\
	while ( !(f&1) ) {++i; f >>= 1;}																												\
	if (f!=1) throw new ::OOVisualization::OOVisualizationException{"Visualization has more than 1 flag set."};			\
	const ::OOVisualization::OperatorStyle* opStyle = &style()->op( i );																\
	layout()->setStyle( &opStyle->layout());
//********************************************************************************************************************

#define OPERAND(name)																																\
layout()->synchronizeMid(name##_, node()->name(), index);																				\
if (name##_) ++index;																																\

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

#define WRAPPED_OPERAND(name, wrapId)																											\
layout()->synchronizeMid<::Visualization::Item, ::Visualization::NodeWrapper>														\
									(name##_, node()->name(), &opStyle->operand##wrapId##Wrapper(), index);							\
if (name##_) {																																			\
	++index;																																				\
	name##_->setStyle( &opStyle->operand##wrapId##Wrapper() );				 															\
}																																							\

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

#define PREINPOSTFIX(name, condition, styleAttribute)																						\
layout()->synchronizeMid(name##_, condition, &opStyle->styleAttribute(), index);													\
if (name##_)																																			\
{																																							\
	++index;																																				\
	name##_->setStyle( &opStyle->styleAttribute());																							\
}																																							\

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

#define END_STANDARD_EXPRESSION_VISUALIZATION }
#define PREFIX(condition) PREINPOSTFIX(prefix, condition, preSymbol)
#define INFIX(condition) PREINPOSTFIX(infix, condition, inSymbol)
#define INFIX2(condition) PREINPOSTFIX(infix2, condition, in2Symbol)
#define POSTFIX(condition) PREINPOSTFIX(postfix, condition, postSymbol)

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

namespace OOVisualization {
#include "StandardExpressionDefinitions.h"
}

#undef BEGIN_STANDARD_EXPRESSION_VISUALIZATION_BASE
#undef BEGIN_STANDARD_EXPRESSION_VISUALIZATION
#undef BEGIN_STANDARD_ENUMERATION_EXPRESSION_VISUALIZATION
#undef BEGIN_STANDARD_FLAG_EXPRESSION_VISUALIZATION
#undef END_STANDARD_EXPRESSION_VISUALIZATION
#undef PREINPOSTFIX
#undef PREFIX
#undef INFIX
#undef INFIX2
#undef POSTFIX
#undef OPERAND
#undef WRAPPED_OPERAND
<commit_msg>fix missing macro rename<commit_after>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2014 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

#include "StandardExpressionVisualizations.h"

#include "../OOVisualizationException.h"

#include "VisualizationBase/src/items/Static.h"
#include "VisualizationBase/src/items/NodeWrapper.h"

#define BEGIN_STANDARD_EXPRESSION_VISUALIZATION_BASE(apiSpecification, className, nodeType)									\
DEFINE_ITEM_COMMON(className, "item")																									\
																																							\
className::className(::Visualization::Item* parent, NodeType* node, const StyleType* style)									\
	: Super{parent, node, style}{}																												\
																																							\
void className::determineChildren()																												\
{																																							\
	int index = 0;																																		\

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

#define BEGIN_STANDARD_EXPRESSION_VISUALIZATION(apiSpecification, className, nodeType)											\
BEGIN_STANDARD_EXPRESSION_VISUALIZATION_BASE(apiSpecification, className, nodeType)												\
	const ::OOVisualization::OperatorStyle* opStyle = style();																			\
	layout()->setStyle( &opStyle->layout());																									\

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

#define BEGIN_STANDARD_ENUMERATION_EXPRESSION_VISUALIZATION(apiSpecification, className, nodeType, enumeration)		\
BEGIN_STANDARD_EXPRESSION_VISUALIZATION_BASE(apiSpecification, className, nodeType)												\
																																							\
	const ::OOVisualization::OperatorStyle* opStyle = &style()->op( (int) node()->enumeration() );							\
	layout()->setStyle( &opStyle->layout());																									\

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

#define BEGIN_STANDARD_FLAG_EXPRESSION_VISUALIZATION(apiSpecification, className, nodeType, flag)							\
BEGIN_STANDARD_EXPRESSION_VISUALIZATION_BASE(apiSpecification, className, nodeType)												\
																																							\
	int f = node()->flag();																															\
	if (!f) throw new ::OOVisualization::OOVisualizationException{"Visualization does not have a flag set."};			\
	int i = 0;																																			\
	while ( !(f&1) ) {++i; f >>= 1;}																												\
	if (f!=1) throw new ::OOVisualization::OOVisualizationException{"Visualization has more than 1 flag set."};			\
	const ::OOVisualization::OperatorStyle* opStyle = &style()->op( i );																\
	layout()->setStyle( &opStyle->layout());
//********************************************************************************************************************

#define OPERAND(name)																																\
layout()->synchronizeMid(name##_, node()->name(), index);																				\
if (name##_) ++index;																																\

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

#define WRAPPED_OPERAND(name, wrapId)																											\
layout()->synchronizeMid<::Visualization::Item, ::Visualization::NodeWrapper>														\
									(name##_, node()->name(), &opStyle->operand##wrapId##Wrapper(), index);							\
if (name##_) {																																			\
	++index;																																				\
	name##_->setStyle( &opStyle->operand##wrapId##Wrapper() );				 															\
}																																							\

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

#define PREINPOSTFIX(name, condition, styleAttribute)																						\
layout()->synchronizeMid(name##_, condition, &opStyle->styleAttribute(), index);													\
if (name##_)																																			\
{																																							\
	++index;																																				\
	name##_->setStyle( &opStyle->styleAttribute());																							\
}																																							\

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

#define END_STANDARD_EXPRESSION_VISUALIZATION }
#define PREFIX(condition) PREINPOSTFIX(prefix, condition, preSymbol)
#define INFIX(condition) PREINPOSTFIX(infix, condition, inSymbol)
#define INFIX2(condition) PREINPOSTFIX(infix2, condition, in2Symbol)
#define POSTFIX(condition) PREINPOSTFIX(postfix, condition, postSymbol)

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

namespace OOVisualization {
#include "StandardExpressionDefinitions.h"
}

#undef BEGIN_STANDARD_EXPRESSION_VISUALIZATION_BASE
#undef BEGIN_STANDARD_EXPRESSION_VISUALIZATION
#undef BEGIN_STANDARD_ENUMERATION_EXPRESSION_VISUALIZATION
#undef BEGIN_STANDARD_FLAG_EXPRESSION_VISUALIZATION
#undef END_STANDARD_EXPRESSION_VISUALIZATION
#undef PREINPOSTFIX
#undef PREFIX
#undef INFIX
#undef INFIX2
#undef POSTFIX
#undef OPERAND
#undef WRAPPED_OPERAND
<|endoftext|>


<commit_before>/**
 * @file sssp_implementation.hxx
 * @author Muhammad Osama (mosama@ucdavis.edu)
 * @brief Single-Source Shortest Path algorithm.
 * @version 0.1
 * @date 2020-10-05
 *
 * @copyright Copyright (c) 2020
 *
 */
#pragma once

#include <gunrock/applications/application.hxx>

namespace gunrock {
namespace sssp {

template <typename vertex_t>
struct param_t {
  vertex_t single_source;
  param_t(vertex_t _single_source) : single_source(_single_source) {}
};

template <typename vertex_t, typename weight_t>
struct result_t {
  weight_t* distances;
  vertex_t* predecessors;
  result_t(weight_t* _distances, vertex_t* _predecessors)
      : distances(_distances), predecessors(_predecessors) {}
};

template <typename graph_t, typename param_type, typename result_type>
struct problem_t : gunrock::problem_t<graph_t> {
  param_type param;
  result_type result;

  problem_t(graph_t& G,
            param_type& _param,
            result_type& _result,
            std::shared_ptr<cuda::multi_context_t> _context)
      : gunrock::problem_t<graph_t>(G, _context),
        param(_param),
        result(_result) {}

  using vertex_t = typename graph_t::vertex_type;
  using edge_t = typename graph_t::edge_type;
  using weight_t = typename graph_t::weight_type;

  thrust::device_vector<vertex_t> visited;

  void init() {
    auto g = this->get_graph();
    auto n_vertices = g.get_number_of_vertices();
    visited.resize(n_vertices);
    thrust::fill(thrust::cuda::par.on(context->get_context(0)->stream()), visited.begin(), visited.end(), -1);
  }

  void reset() {
    auto g = this->get_graph();
    auto n_vertices = g.get_number_of_vertices();

    auto d_distances = thrust::device_pointer_cast(this->result.distances);
    thrust::fill(thrust::cuda::par.on(this->context->get_context(0)->stream()), d_distances + 0, d_distances + n_vertices,
                 std::numeric_limits<weight_t>::max());

    thrust::fill(thrust::cuda::par.on(this->context->get_context(0)->stream()), d_distances + this->param.single_source,
                 d_distances + this->param.single_source + 1, 0);

    thrust::fill(thrust::cuda::par.on(this->context->get_context(0)->stream()), visited.begin(), visited.end(),
                 -1);  // This does need to be reset in between runs though
  }
};

template <typename problem_t>
struct enactor_t : gunrock::enactor_t<problem_t> {
  // Use Base class constructor -- does this work? does it handle copy
  // constructor?
  using gunrock::enactor_t<problem_t>::enactor_t;

  using vertex_t = typename problem_t::vertex_t;
  using edge_t = typename problem_t::edge_t;
  using weight_t = typename problem_t::weight_t;

  void prepare_frontier(frontier_t<vertex_t>* f,
                        cuda::multi_context_t& context) override {
    auto P = this->get_problem();
    f->push_back(P->param.single_source);
  }

  void loop(cuda::multi_context_t& context) override {
    // Data slice
    auto E = this->get_enactor();
    auto P = this->get_problem();
    auto G = P->get_graph();

    auto single_source = P->param.single_source;
    auto distances = P->result.distances;
    auto visited = P->visited.data().get();

    auto iteration = this->iteration;

    auto shortest_path = [distances, single_source] __host__ __device__(
                             vertex_t const& source,    // ... source
                             vertex_t const& neighbor,  // neighbor
                             edge_t const& edge,        // edge
                             weight_t const& weight     // weight (tuple).
                             ) -> bool {
      weight_t source_distance = distances[source];  // use cached::load
      weight_t distance_to_neighbor = source_distance + weight;

      // Check if the destination node has been claimed as someone's child
      weight_t recover_distance =
          math::atomic::min(&(distances[neighbor]), distance_to_neighbor);

      return (distance_to_neighbor < recover_distance);
    };

    auto remove_completed_paths = [G, visited, iteration] __host__ __device__(
                                      vertex_t const& vertex) -> bool {
      if (visited[vertex] == iteration)
        return false;

      visited[vertex] = iteration;
      return G.get_number_of_neighbors(vertex) > 0;
    };

    // Execute advance operator on the provided lambda
    operators::advance::execute<operators::advance_type_t::vertex_to_vertex,
                                operators::advance_direction_t::forward,
                                operators::load_balance_t::block_mapped>(
        G, E, shortest_path, context);

    // Execute filter operator on the provided lambda
    operators::filter::execute<operators::filter_algorithm_t::predicated>(
        G, E, remove_completed_paths, context);
  }

};  // struct enactor_t

template <typename graph_t>
float run(graph_t& G,
          typename graph_t::vertex_type& single_source,  // Parameter
          typename graph_t::weight_type* distances,      // Output
          typename graph_t::vertex_type* predecessors    // Output
) {
  // <user-defined>
  using vertex_t = typename graph_t::vertex_type;
  using weight_t = typename graph_t::weight_type;

  using param_type = param_t<vertex_t>;
  using result_type = result_t<vertex_t, weight_t>;

  param_type param(single_source);
  result_type result(distances, predecessors);
  // </user-defined>

  // <boiler-plate>
  auto multi_context =
      std::shared_ptr<cuda::multi_context_t>(new cuda::multi_context_t(0));

  using problem_type = problem_t<graph_t, param_type, result_type>;
  using enactor_type = enactor_t<problem_type>;

  problem_type problem(G, param, result, multi_context);
  problem.init();
  problem.reset();

  enactor_type enactor(&problem, multi_context);
  return enactor.enact();
  // </boiler-plate>
}

}  // namespace sssp
}  // namespace gunrock<commit_msg>cleaning up<commit_after>/**
 * @file sssp_implementation.hxx
 * @author Muhammad Osama (mosama@ucdavis.edu)
 * @brief Single-Source Shortest Path algorithm.
 * @version 0.1
 * @date 2020-10-05
 *
 * @copyright Copyright (c) 2020
 *
 */
#pragma once

#include <gunrock/applications/application.hxx>

namespace gunrock {
namespace sssp {

template <typename vertex_t>
struct param_t {
  vertex_t single_source;
  param_t(vertex_t _single_source) : single_source(_single_source) {}
};

template <typename vertex_t, typename weight_t>
struct result_t {
  weight_t* distances;
  vertex_t* predecessors;
  result_t(weight_t* _distances, vertex_t* _predecessors)
      : distances(_distances), predecessors(_predecessors) {}
};

template <typename graph_t, typename param_type, typename result_type>
struct problem_t : gunrock::problem_t<graph_t> {
  param_type param;
  result_type result;

  problem_t(graph_t& G,
            param_type& _param,
            result_type& _result,
            std::shared_ptr<cuda::multi_context_t> _context)
      : gunrock::problem_t<graph_t>(G, _context),
        param(_param),
        result(_result) {}

  using vertex_t = typename graph_t::vertex_type;
  using edge_t = typename graph_t::edge_type;
  using weight_t = typename graph_t::weight_type;

  thrust::device_vector<vertex_t> visited;

  void init() {
    auto g = this->get_graph();
    auto n_vertices = g.get_number_of_vertices();
    visited.resize(n_vertices);
    thrust::fill(thrust::device, visited.begin(), visited.end(), -1);
  }

  void reset() {
    auto g = this->get_graph();
    auto n_vertices = g.get_number_of_vertices();

    auto d_distances = thrust::device_pointer_cast(this->result.distances);
    thrust::fill(thrust::device, d_distances + 0, d_distances + n_vertices,
                 std::numeric_limits<weight_t>::max());

    thrust::fill(thrust::device, d_distances + this->param.single_source,
                 d_distances + this->param.single_source + 1, 0);

    thrust::fill(thrust::device, visited.begin(), visited.end(),
                 -1);  // This does need to be reset in between runs though
  }
};

template <typename problem_t>
struct enactor_t : gunrock::enactor_t<problem_t> {
  // Use Base class constructor -- does this work? does it handle copy
  // constructor?
  using gunrock::enactor_t<problem_t>::enactor_t;

  using vertex_t = typename problem_t::vertex_t;
  using edge_t = typename problem_t::edge_t;
  using weight_t = typename problem_t::weight_t;

  void prepare_frontier(frontier_t<vertex_t>* f,
                        cuda::multi_context_t& context) override {
    auto P = this->get_problem();
    f->push_back(P->param.single_source);
  }

  void loop(cuda::multi_context_t& context) override {
    // Data slice
    auto E = this->get_enactor();
    auto P = this->get_problem();
    auto G = P->get_graph();

    auto single_source = P->param.single_source;
    auto distances = P->result.distances;
    auto visited = P->visited.data().get();

    auto iteration = this->iteration;

    auto shortest_path = [distances, single_source] __host__ __device__(
                             vertex_t const& source,    // ... source
                             vertex_t const& neighbor,  // neighbor
                             edge_t const& edge,        // edge
                             weight_t const& weight     // weight (tuple).
                             ) -> bool {
      weight_t source_distance = distances[source];  // use cached::load
      weight_t distance_to_neighbor = source_distance + weight;

      // Check if the destination node has been claimed as someone's child
      weight_t recover_distance =
          math::atomic::min(&(distances[neighbor]), distance_to_neighbor);

      return (distance_to_neighbor < recover_distance);
    };

    auto remove_completed_paths = [G, visited, iteration] __host__ __device__(
                                      vertex_t const& vertex) -> bool {
      if (visited[vertex] == iteration)
        return false;

      visited[vertex] = iteration;
      return G.get_number_of_neighbors(vertex) > 0;
    };

    // Execute advance operator on the provided lambda
    operators::advance::execute<operators::advance_type_t::vertex_to_vertex,
                                operators::advance_direction_t::forward,
                                operators::load_balance_t::block_mapped>(
        G, E, shortest_path, context);

    // Execute filter operator on the provided lambda
    operators::filter::execute<operators::filter_algorithm_t::predicated>(
        G, E, remove_completed_paths, context);
  }

};  // struct enactor_t

template <typename graph_t>
float run(graph_t& G,
          typename graph_t::vertex_type& single_source,  // Parameter
          typename graph_t::weight_type* distances,      // Output
          typename graph_t::vertex_type* predecessors    // Output
) {
  // <user-defined>
  using vertex_t = typename graph_t::vertex_type;
  using weight_t = typename graph_t::weight_type;

  using param_type = param_t<vertex_t>;
  using result_type = result_t<vertex_t, weight_t>;

  param_type param(single_source);
  result_type result(distances, predecessors);
  // </user-defined>

  // <boiler-plate>
  auto multi_context =
      std::shared_ptr<cuda::multi_context_t>(new cuda::multi_context_t(0));

  using problem_type = problem_t<graph_t, param_type, result_type>;
  using enactor_type = enactor_t<problem_type>;

  problem_type problem(G, param, result, multi_context);
  problem.init();
  problem.reset();

  enactor_type enactor(&problem, multi_context);
  return enactor.enact();
  // </boiler-plate>
}

}  // namespace sssp
}  // namespace gunrock<|endoftext|>


<commit_before>/*
  MusicXML Library
  Copyright (C) Grame 2006-2013

  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.

  Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France
  research@grame.fr
*/

#include "versions.h"

namespace MusicXML2
{
//______________________________________________________________________________
float   versions::libVersion()        { return 3.19f; }
const char* versions::libVersionStr()     { return "3.19"; }

float   versions::xml2guidoVersion()    { return 3.0f; }
const char* versions::xml2guidoVersionStr()   { return "3.0"; }

float   versions::xml2lilypondVersion()   { return 0.92f; }
const char* versions::xml2lilypondVersionStr()    { return "0.92"; }

float   versions::xml2brailleVersion()   { return 0.03f; }
const char* versions::xml2brailleVersionStr()    { return "0.03"; }

}

<commit_msg>Increment xml2guidoVersion to 3.1<commit_after>/*
  MusicXML Library
  Copyright (C) Grame 2006-2013

  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.

  Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France
  research@grame.fr
*/

#include "versions.h"

namespace MusicXML2
{
//______________________________________________________________________________
float   versions::libVersion()        { return 3.19f; }
const char* versions::libVersionStr()     { return "3.19"; }

float   versions::xml2guidoVersion()    { return 3.1f; }
const char* versions::xml2guidoVersionStr()   { return "3.1"; }

float   versions::xml2lilypondVersion()   { return 0.92f; }
const char* versions::xml2lilypondVersionStr()    { return "0.92"; }

float   versions::xml2brailleVersion()   { return 0.03f; }
const char* versions::xml2brailleVersionStr()    { return "0.03"; }

}

<|endoftext|>


<commit_before>// Unit Test (I/O utility)

#include <gtest/gtest.h>
#include <stdexcept>

#include <vector>
#include <map>
#include <sstream>
#include "io.H"
using namespace nmlib;

TEST(io,vector){
  std::stringstream str1, str2;
  std::vector<double> xx;

  str1 << "3  +11.1  2.22e1  3.33e+1";
  str1 >> xx;
  EXPECT_EQ(xx.size(),3);
  for(size_t i=0; i<xx.size(); i++) EXPECT_NEAR(xx[i], (i+1)*11.1, 1.e-8);

  xx.push_back(44.4);
  str2 << xx;
  EXPECT_EQ(str2.str(),"4\n11.1\n22.2\n33.3\n44.4\n");
}

TEST(io,map){
  std::stringstream str1, str2;
  std::map<int,double> xx;

  str1 << "3  11  +11.1  22  222e-1  33  3.33e+1";
  str1 >> xx;
  EXPECT_EQ(xx.size(),3);
  int k=0;
  for(std::map<int,double>::const_iterator i=xx.begin(); i!=xx.end(); i++){
    k++;
    EXPECT_EQ(i->first, k*11);
    EXPECT_NEAR(i->second, k*11.1, 1.e-8);
  }

  xx[44]=44.4;
  str2 << xx;
  EXPECT_EQ(str2.str(),"4\n11\t11.1\n22\t22.2\n33\t33.3\n44\t44.4\n");
}

TEST(io,string){
  std::string s="12.3 45.6";
  double x;
  x=0;    str2any(s,x);        EXPECT_NEAR(x,12.3,1.e-8);
  x=0;  x=str2any<double>(s);  EXPECT_NEAR(x,12.3,1.e-8);

  char s1[80]="45.6";
  x=0;    str2any(s1,x);        EXPECT_NEAR(x,45.6,1.e-8);
  x=0;  x=str2any<double>(s1);  EXPECT_NEAR(x,45.6,1.e-8);

  s = "3 11 11.1 22 22.2 33 33.3";
  std::map<int,double> xx = str2any<std::map<int,double> >(s);
  EXPECT_EQ(xx.size(),3);
  int k=0;
  for(std::map<int,double>::const_iterator i=xx.begin(); i!=xx.end(); i++){
    k++;
    EXPECT_EQ(i->first, k*11);
    EXPECT_NEAR(i->second, k*11.1, 1.e-8);
  }

  EXPECT_EQ(any2str(xx), "3\n11\t11.1\n22\t22.2\n33\t33.3\n");

  s="!@#$";
  EXPECT_THROW(str2any(s,x), std::runtime_error);
  s = "3 11 11.1 22 22.2 33 ";
  EXPECT_THROW(str2any(s,xx), std::runtime_error);
  s = "3 11 11.1a 22 22.2 33 33.3";
  EXPECT_THROW(str2any(s,xx), std::runtime_error);
}
<commit_msg>Added unit test for user class <--> string conversion<commit_after>// Unit Test (I/O utility)

#include <gtest/gtest.h>
#include <stdexcept>

#include <vector>
#include <map>
#include <sstream>
#include "io.H"
using namespace nmlib;

class Dummy{
public:
  double r,c;
};
std::istream& operator>>(std::istream& str,       Dummy& x){ str >> x.r >> x.c; return str; }
std::ostream& operator<<(std::ostream& str, const Dummy& x){ str << x.r << '\t' << x.c << '\t'; return str; }

TEST(io,vector){
  std::stringstream str1, str2;
  std::vector<double> xx;

  str1 << "3  +11.1  2.22e1  3.33e+1";
  str1 >> xx;
  EXPECT_EQ(xx.size(),3);
  for(size_t i=0; i<xx.size(); i++) EXPECT_NEAR(xx[i], (i+1)*11.1, 1.e-8);

  xx.push_back(44.4);
  str2 << xx;
  EXPECT_EQ(str2.str(),"4\n11.1\n22.2\n33.3\n44.4\n");
}

TEST(io,map){
  std::stringstream str1, str2;
  std::map<int,double> xx;

  str1 << "3  11  +11.1  22  222e-1  33  3.33e+1";
  str1 >> xx;
  EXPECT_EQ(xx.size(),3);
  int k=0;
  for(std::map<int,double>::const_iterator i=xx.begin(); i!=xx.end(); i++){
    k++;
    EXPECT_EQ(i->first, k*11);
    EXPECT_NEAR(i->second, k*11.1, 1.e-8);
  }

  xx[44]=44.4;
  str2 << xx;
  EXPECT_EQ(str2.str(),"4\n11\t11.1\n22\t22.2\n33\t33.3\n44\t44.4\n");
}

TEST(io,string){
  std::string s="12.3 45.6";
  double x;
  x=0;    str2any(s,x);        EXPECT_NEAR(x,12.3,1.e-8);
  x=0;  x=str2any<double>(s);  EXPECT_NEAR(x,12.3,1.e-8);

  char s1[80]="45.6";
  x=0;    str2any(s1,x);        EXPECT_NEAR(x,45.6,1.e-8);
  x=0;  x=str2any<double>(s1);  EXPECT_NEAR(x,45.6,1.e-8);

  s = "3 11 11.1 22 22.2 33 33.3";
  std::map<int,double> xx = str2any<std::map<int,double> >(s);
  EXPECT_EQ(xx.size(),3);
  int k=0;
  for(std::map<int,double>::const_iterator i=xx.begin(); i!=xx.end(); i++){
    k++;
    EXPECT_EQ(i->first, k*11);
    EXPECT_NEAR(i->second, k*11.1, 1.e-8);
  }

  EXPECT_EQ(any2str(xx), "3\n11\t11.1\n22\t22.2\n33\t33.3\n");

  s="!@#$";
  EXPECT_THROW(str2any(s,x), std::runtime_error);
  s = "3 11 11.1 22 22.2 33 ";
  EXPECT_THROW(str2any(s,xx), std::runtime_error);
  s = "3 11 11.1a 22 22.2 33 33.3";
  EXPECT_THROW(str2any(s,xx), std::runtime_error);
}

TEST(io,userclass){
  std::string s="11 22";
  Dummy x;

  x=str2any<Dummy>(s);
  EXPECT_EQ(any2str(x),"11\t22\t");

  x=str2any<Dummy>(s);
  EXPECT_EQ(any2str(x,3),"1.100e+01\t2.200e+01\t");  // precision=3
}
<|endoftext|>


<commit_before><commit_msg>Initialize WebViewPlugin with animationNeeded_ true, to avoid painting too early.<commit_after><|endoftext|>