<commit_before>/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include "util/sstream.h"
#include "kernel/instantiate.h"
#include "kernel/inductive/inductive.h"
#include "library/util.h"
#include "library/constants.h"
#include "library/normalize.h"
#include "library/aux_recursors.h"
#include "compiler/util.h"
#include "compiler/compiler_step_visitor.h"

namespace lean {
static expr * g_neutral_expr     = nullptr;
static expr * g_unreachable_expr = nullptr;
class erase_irrelevant_fn : public compiler_step_visitor {

    virtual expr visit_constant(expr const & e) override {
        /* Erase universe level information */
        return mk_constant(const_name(e));
    }

    /* We keep only the major and minor premises in cases_on applications. */
    expr visit_cases_on(expr const & fn, buffer<expr> & args) {
        name const & rec_name       = const_name(fn);
        name const & I_name         = rec_name.get_prefix();
        unsigned nparams            = *inductive::get_num_params(env(), I_name);
        unsigned nminors            = *inductive::get_num_minor_premises(env(), I_name);
        unsigned nindices           = *inductive::get_num_indices(env(), I_name);
        unsigned arity              = nparams + 1 /* typeformer/motive */ + nindices + 1 /* major premise */ + nminors;
        lean_assert(args.size() >= arity);
        for (unsigned i = nparams + 1 + nindices; i < args.size(); i++) {
            args[i] = visit(args[i]);
        }
        expr new_fn = visit(fn);
        return mk_app(new_fn, args.size() - nparams - 1 - nindices, args.data() + nparams + 1 + nindices);
    }

    /* We keep only the major and minor premises in rec applications.
       This method also converts the rec into cases_on */
    expr visit_rec(expr const & fn, buffer<expr> & args) {
        name const & rec_name       = const_name(fn);
        name const & I_name         = rec_name.get_prefix();
        /* This preprocessing step assumes that recursive recursors have already been eliminated */
        lean_assert(!is_recursive_datatype(env(), I_name));
        unsigned nparams            = *inductive::get_num_params(env(), I_name);
        unsigned nminors            = *inductive::get_num_minor_premises(env(), I_name);
        unsigned nindices           = *inductive::get_num_indices(env(), I_name);
        unsigned arity              = nparams + 1 /* typeformer/motive */ + nminors + nindices + 1 /* major premise */;
        lean_assert(args.size() >= arity);
        buffer<expr> new_args;
        expr new_fn = mk_constant(name(I_name, "cases_on"));
        /* add major */
        new_args.push_back(visit(args[nparams + 1 + nminors + nindices]));
        /* add minors */
        for (unsigned i = 0; i < nminors; i++)
            new_args.push_back(visit(args[nparams + 1 + i]));
        return add_args(mk_app(new_fn, new_args), arity, args);
    }

    expr add_args(expr e, unsigned start_idx, buffer<expr> const & args) {
        for (unsigned i = start_idx; i < args.size(); i++)
            e = mk_app(e, args[i]);
        return beta_reduce(e);
    }

    /* Remove eq.rec applications since they are just "type-casting" operations. */
    expr visit_eq_rec(buffer<expr> & args) {
        lean_assert(args.size() >= 6);
        expr major = visit(args[3]);
        return add_args(major, 6, args);
    }

    expr consume_lambdas(type_context::tmp_locals & locals, expr e) {
        while (true) {
            if (is_lambda(e)) {
                expr local = locals.push_local_from_binding(e);
                e = instantiate(binding_body(e), local);
            } else {
                return beta_reduce(e);
            }
        }
    }

    /* We can eliminate no_confusion applications, they do not add any relevant information to the environment */
    expr visit_no_confusion(expr const & fn, buffer<expr> const & args) {
        lean_assert(is_constant(fn));
        name const & no_confusion_name = const_name(fn);
        name const & I_name            = no_confusion_name.get_prefix();
        unsigned nparams               = *inductive::get_num_params(env(), I_name);
        unsigned nindices              = *inductive::get_num_indices(env(), I_name);
        unsigned basic_arity           = nparams + nindices + 1 /* motive */ + 2 /* lhs/rhs */ + 1 /* equality */;
        lean_assert(args.size() >= basic_arity);
        expr lhs                       = ctx().whnf(args[nparams + nindices + 1]);
        expr rhs                       = ctx().whnf(args[nparams + nindices + 2]);
        optional<name> lhs_constructor = is_constructor_app(env(), lhs);
        optional<name> rhs_constructor = is_constructor_app(env(), rhs);
        if (!lhs_constructor || !rhs_constructor)
            throw exception(sstream() << "code generation failed, unsupported occurrence of '" << no_confusion_name << "', constructors expected");
        if (lhs_constructor != rhs_constructor)
            return *g_unreachable_expr;
        lean_assert(args.size() >= basic_arity + 1);
        expr major = args[nparams + nindices + 4];
        type_context::tmp_locals locals(ctx());
        major = consume_lambdas(locals, major);
        major = visit(major);
        major = locals.mk_lambda(major);
        expr r = major;

        unsigned c_data_sz = get_constructor_arity(env(), *lhs_constructor) - nparams;
        for (unsigned i = 0; i < c_data_sz; i++)
            r = mk_app(r, *g_neutral_expr); // add dummy proofs
        /* add remaining arguments */
        return add_args(r, nparams + nindices + 5, args);
    }

    /* Treat subtype.tag as the identity function */
    virtual expr visit_subtype_tag(buffer<expr> const & args) {
        lean_assert(args.size() >= 4);
        expr r = visit(args[2]);
        return add_args(r, 4, args);
    }

    /* Eliminate subtype.rec */
    virtual expr visit_subtype_rec(buffer<expr> const & args) {
        lean_assert(args.size() >= 5);
        expr minor = visit(args[3]);
        expr major = visit(args[4]);
        expr r     = mk_app(minor, major, *g_neutral_expr);
        return add_args(r, 5, args);
    }

    /* subtype.elt_of is also compiled as the identity function */
    virtual expr visit_subtype_elt_of(buffer<expr> const & args) {
        lean_assert(args.size() >= 3);
        expr r = visit(args[2]);
        return add_args(r, 3, args);
    }

    virtual expr visit_app(expr const & e) override {
        buffer<expr> args;
        expr const & fn = get_app_args(e, args);
        if (is_lambda(fn)) {
            return visit(beta_reduce(e));
        } else if (is_constant(fn)) {
            name const & n = const_name(fn);
            if (n == get_eq_rec_name()) {
                return visit_eq_rec(args);
            } else if (n == get_subtype_rec_name()) {
                return visit_subtype_rec(args);
            } else if (is_cases_on_recursor(env(), n)) {
                return visit_cases_on(fn, args);
            } else if (inductive::is_elim_rule(env(), n)) {
                return visit_rec(fn, args);
            } else if (is_no_confusion(env(), n)) {
                return visit_no_confusion(fn, args);
            } else if (n == get_subtype_tag_name()) {
                return visit_subtype_tag(args);
            } else if (n == get_subtype_elt_of_name()) {
                return visit_subtype_elt_of(args);
            }
        }
        return compiler_step_visitor::visit_app(e);
    }

public:
    erase_irrelevant_fn(environment const & env):compiler_step_visitor(env) {}
};

expr erase_irrelevant(environment const & env, expr const & e) {
    return erase_irrelevant_fn(env)(e);
}

bool is_neutral_expr(expr const & e) {
    return e == *g_neutral_expr;
}

bool is_unreachable_expr(expr const & e) {
    return e == *g_unreachable_expr;
}

void initialize_erase_irrelevant() {
    g_neutral_expr     = new expr(mk_constant("_neutral_"));
    g_unreachable_expr = new expr(mk_constant("_unreachable_"));
}

void finalize_erase_irrelevant() {
    delete g_neutral_expr;
    delete g_unreachable_expr;
}
}
<commit_msg>chore(compiler/erase_irrelevant): compilation warnings<commit_after>/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include "util/sstream.h"
#include "kernel/instantiate.h"
#include "kernel/inductive/inductive.h"
#include "library/util.h"
#include "library/constants.h"
#include "library/normalize.h"
#include "library/aux_recursors.h"
#include "compiler/util.h"
#include "compiler/compiler_step_visitor.h"

namespace lean {
static expr * g_neutral_expr     = nullptr;
static expr * g_unreachable_expr = nullptr;
class erase_irrelevant_fn : public compiler_step_visitor {

    virtual expr visit_constant(expr const & e) override {
        /* Erase universe level information */
        return mk_constant(const_name(e));
    }

    /* We keep only the major and minor premises in cases_on applications. */
    expr visit_cases_on(expr const & fn, buffer<expr> & args) {
        name const & rec_name       = const_name(fn);
        name const & I_name         = rec_name.get_prefix();
        unsigned nparams            = *inductive::get_num_params(env(), I_name);
        DEBUG_CODE(unsigned nminors = *inductive::get_num_minor_premises(env(), I_name););
        unsigned nindices           = *inductive::get_num_indices(env(), I_name);
        DEBUG_CODE(unsigned arity   = nparams + 1 /* typeformer/motive */ + nindices + 1 /* major premise */ + nminors;);
        lean_assert(args.size() >= arity);
        for (unsigned i = nparams + 1 + nindices; i < args.size(); i++) {
            args[i] = visit(args[i]);
        }
        expr new_fn = visit(fn);
        return mk_app(new_fn, args.size() - nparams - 1 - nindices, args.data() + nparams + 1 + nindices);
    }

    /* We keep only the major and minor premises in rec applications.
       This method also converts the rec into cases_on */
    expr visit_rec(expr const & fn, buffer<expr> & args) {
        name const & rec_name       = const_name(fn);
        name const & I_name         = rec_name.get_prefix();
        /* This preprocessing step assumes that recursive recursors have already been eliminated */
        lean_assert(!is_recursive_datatype(env(), I_name));
        unsigned nparams            = *inductive::get_num_params(env(), I_name);
        unsigned nminors            = *inductive::get_num_minor_premises(env(), I_name);
        unsigned nindices           = *inductive::get_num_indices(env(), I_name);
        unsigned arity              = nparams + 1 /* typeformer/motive */ + nminors + nindices + 1 /* major premise */;
        lean_assert(args.size() >= arity);
        buffer<expr> new_args;
        expr new_fn = mk_constant(name(I_name, "cases_on"));
        /* add major */
        new_args.push_back(visit(args[nparams + 1 + nminors + nindices]));
        /* add minors */
        for (unsigned i = 0; i < nminors; i++)
            new_args.push_back(visit(args[nparams + 1 + i]));
        return add_args(mk_app(new_fn, new_args), arity, args);
    }

    expr add_args(expr e, unsigned start_idx, buffer<expr> const & args) {
        for (unsigned i = start_idx; i < args.size(); i++)
            e = mk_app(e, args[i]);
        return beta_reduce(e);
    }

    /* Remove eq.rec applications since they are just "type-casting" operations. */
    expr visit_eq_rec(buffer<expr> & args) {
        lean_assert(args.size() >= 6);
        expr major = visit(args[3]);
        return add_args(major, 6, args);
    }

    expr consume_lambdas(type_context::tmp_locals & locals, expr e) {
        while (true) {
            if (is_lambda(e)) {
                expr local = locals.push_local_from_binding(e);
                e = instantiate(binding_body(e), local);
            } else {
                return beta_reduce(e);
            }
        }
    }

    /* We can eliminate no_confusion applications, they do not add any relevant information to the environment */
    expr visit_no_confusion(expr const & fn, buffer<expr> const & args) {
        lean_assert(is_constant(fn));
        name const & no_confusion_name  = const_name(fn);
        name const & I_name             = no_confusion_name.get_prefix();
        unsigned nparams                = *inductive::get_num_params(env(), I_name);
        unsigned nindices               = *inductive::get_num_indices(env(), I_name);
        DEBUG_CODE(unsigned basic_arity = nparams + nindices + 1 /* motive */ + 2 /* lhs/rhs */ + 1 /* equality */;);
        lean_assert(args.size() >= basic_arity);
        expr lhs                        = ctx().whnf(args[nparams + nindices + 1]);
        expr rhs                        = ctx().whnf(args[nparams + nindices + 2]);
        optional<name> lhs_constructor  = is_constructor_app(env(), lhs);
        optional<name> rhs_constructor  = is_constructor_app(env(), rhs);
        if (!lhs_constructor || !rhs_constructor)
            throw exception(sstream() << "code generation failed, unsupported occurrence of '" << no_confusion_name << "', constructors expected");
        if (lhs_constructor != rhs_constructor)
            return *g_unreachable_expr;
        lean_assert(args.size() >= basic_arity + 1);
        expr major = args[nparams + nindices + 4];
        type_context::tmp_locals locals(ctx());
        major = consume_lambdas(locals, major);
        major = visit(major);
        major = locals.mk_lambda(major);
        expr r = major;

        unsigned c_data_sz = get_constructor_arity(env(), *lhs_constructor) - nparams;
        for (unsigned i = 0; i < c_data_sz; i++)
            r = mk_app(r, *g_neutral_expr); // add dummy proofs
        /* add remaining arguments */
        return add_args(r, nparams + nindices + 5, args);
    }

    /* Treat subtype.tag as the identity function */
    virtual expr visit_subtype_tag(buffer<expr> const & args) {
        lean_assert(args.size() >= 4);
        expr r = visit(args[2]);
        return add_args(r, 4, args);
    }

    /* Eliminate subtype.rec */
    virtual expr visit_subtype_rec(buffer<expr> const & args) {
        lean_assert(args.size() >= 5);
        expr minor = visit(args[3]);
        expr major = visit(args[4]);
        expr r     = mk_app(minor, major, *g_neutral_expr);
        return add_args(r, 5, args);
    }

    /* subtype.elt_of is also compiled as the identity function */
    virtual expr visit_subtype_elt_of(buffer<expr> const & args) {
        lean_assert(args.size() >= 3);
        expr r = visit(args[2]);
        return add_args(r, 3, args);
    }

    virtual expr visit_app(expr const & e) override {
        buffer<expr> args;
        expr const & fn = get_app_args(e, args);
        if (is_lambda(fn)) {
            return visit(beta_reduce(e));
        } else if (is_constant(fn)) {
            name const & n = const_name(fn);
            if (n == get_eq_rec_name()) {
                return visit_eq_rec(args);
            } else if (n == get_subtype_rec_name()) {
                return visit_subtype_rec(args);
            } else if (is_cases_on_recursor(env(), n)) {
                return visit_cases_on(fn, args);
            } else if (inductive::is_elim_rule(env(), n)) {
                return visit_rec(fn, args);
            } else if (is_no_confusion(env(), n)) {
                return visit_no_confusion(fn, args);
            } else if (n == get_subtype_tag_name()) {
                return visit_subtype_tag(args);
            } else if (n == get_subtype_elt_of_name()) {
                return visit_subtype_elt_of(args);
            }
        }
        return compiler_step_visitor::visit_app(e);
    }

public:
    erase_irrelevant_fn(environment const & env):compiler_step_visitor(env) {}
};

expr erase_irrelevant(environment const & env, expr const & e) {
    return erase_irrelevant_fn(env)(e);
}

bool is_neutral_expr(expr const & e) {
    return e == *g_neutral_expr;
}

bool is_unreachable_expr(expr const & e) {
    return e == *g_unreachable_expr;
}

void initialize_erase_irrelevant() {
    g_neutral_expr     = new expr(mk_constant("_neutral_"));
    g_unreachable_expr = new expr(mk_constant("_unreachable_"));
}

void finalize_erase_irrelevant() {
    delete g_neutral_expr;
    delete g_unreachable_expr;
}
}
<|endoftext|>


<commit_before>
#include <gmock/gmock.h>

#include <fiblib/Fibonacci.h>

class fibonacci_test: public testing::Test
{
public:
};

TEST_F(fibonacci_test, CheckSomeResults)
{
    fiblib::Fibonacci fib;

    EXPECT_EQ( 0, fib( 0));
    EXPECT_EQ( 1, fib( 1));
    EXPECT_EQ( 1, fib( 2));
    EXPECT_EQ(21, fib( 8));
    // ...
}
<commit_msg>Fix signed-unsigned-warning in test<commit_after>
#include <gmock/gmock.h>

#include <fiblib/Fibonacci.h>

class fibonacci_test: public testing::Test
{
public:
};

TEST_F(fibonacci_test, CheckSomeResults)
{
    fiblib::Fibonacci fib;

    EXPECT_EQ((unsigned int) 0, fib(0));
    EXPECT_EQ((unsigned int) 1, fib(1));
    EXPECT_EQ((unsigned int) 1, fib(2));
    EXPECT_EQ((unsigned int)21, fib(8));
    // ...
}
<|endoftext|>


<commit_before>/*!
    \file named_condition_variable.cpp
    \brief Named condition variable synchronization primitive implementation
    \author Ivan Shynkarenka
    \date 04.10.2016
    \copyright MIT License
*/

#include "threads/named_condition_variable.h"

#include "errors/exceptions.h"
#include "errors/fatal.h"

#include <algorithm>

#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
#include "system/shared_type.h"
#include <pthread.h>
#elif defined(_WIN32) || defined(_WIN64)
#include "system/shared_type.h"
#include <windows.h>
#undef max
#undef min
#endif

namespace CppCommon {

//! @cond INTERNALS

class NamedConditionVariable::Impl
{
public:
    Impl(const std::string& name) : _name(name)
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
        , _shared(name)
#elif defined(_WIN32) || defined(_WIN64)
        , _shared(name)
#endif
    {
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
        // Only the owner should initializate a named condition variable
        if (_shared.owner())
        {
            pthread_mutexattr_t mutex_attribute;
            int result = pthread_mutexattr_init(&mutex_attribute);
            if (result != 0)
                throwex SystemException("Failed to initialize a mutex attribute for the named condition variable!", result);
            result = pthread_mutexattr_setpshared(&mutex_attribute, PTHREAD_PROCESS_SHARED);
            if (result != 0)
                throwex SystemException("Failed to set a mutex process shared attribute for the named condition variable!", result);
            result = pthread_mutex_init(&_shared->mutex, &mutex_attribute);
            if (result != 0)
                throwex SystemException("Failed to initialize a mutex for the named condition variable!", result);
            result = pthread_mutexattr_destroy(&mutex_attribute);
            if (result != 0)
                throwex SystemException("Failed to destroy a mutex attribute for the named condition variable!", result);

            pthread_condattr_t cond_attribute;
            result = pthread_condattr_init(&cond_attribute);
            if (result != 0)
                throwex SystemException("Failed to initialize a conditional variable attribute for the named condition variable!", result);
            result = pthread_condattr_setpshared(&cond_attribute, PTHREAD_PROCESS_SHARED);
            if (result != 0)
                throwex SystemException("Failed to set a conditional variable process shared attribute for the named condition variable!", result);
            result = pthread_cond_init(&_shared->cond, &cond_attribute);
            if (result != 0)
                throwex SystemException("Failed to initialize a conditional variable for the named condition variable!", result);
            result = pthread_condattr_destroy(&cond_attribute);
            if (result != 0)
                throwex SystemException("Failed to destroy a conditional variable attribute for the named condition variable!", result);
        }
#elif defined(_WIN32) || defined(_WIN64)
        // Owner of the condition variable should initialize its value
        if (_shared.owner())
            *_shared = 0;
        _mutex = CreateMutexA(nullptr, FALSE, (name + "-mutex").c_str());
        if (_mutex == nullptr)
            throwex SystemException("Failed to create or open a named mutex for the named condition variable!");
        _semaphore = CreateSemaphoreA(nullptr, 0, std::numeric_limits<LONG>::max(), (name + "-semaphore").c_str());
        if (_semaphore == nullptr)
            throwex SystemException("Failed to create or open a named semaphore for the named condition variable!");
#endif
    }

    ~Impl()
    {
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
        // Only the owner should destroy a named condition variable
        if (_shared.owner())
        {
            int result = pthread_mutex_destroy(&_shared->mutex);
            if (result != 0)
                fatality(SystemException("Failed to destroy a mutex for the named condition variable!", result));
            result = pthread_cond_destroy(&_shared->cond);
            if (result != 0)
                fatality(SystemException("Failed to destroy a conditional variable for the named condition variable!", result));
        }
#elif defined(_WIN32) || defined(_WIN64)
        if (!CloseHandle(_mutex))
            fatality(SystemException("Failed to close a named mutex for the named condition variable!"));
        if (!CloseHandle(_semaphore))
            fatality(SystemException("Failed to close a named semaphore for the named condition variable!"));
#endif
    }

    const std::string& name() const
    {
        return _name;
    }

    void NotifyOne()
    {
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
        int result = pthread_cond_signal(&_shared->cond);
        if (result != 0)
            throwex SystemException("Failed to signal a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64)
        // Lock the named mutex
        DWORD result = WaitForSingleObject(_mutex, INFINITE);
        if (result != WAIT_OBJECT_0)
            throwex SystemException("Failed to lock a named mutex for the named condition variable!");
        // Decrement shared waiters count
        --(*_shared);
        // Signal one waiter
        if (!ReleaseSemaphore(_semaphore, 1, nullptr))
            throwex SystemException("Failed to release one semaphore waiter for the named condition variable!");
        // Unlock the named mutex
        if (!ReleaseMutex(_mutex))
            throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
#endif
    }

    void NotifyAll()
    {
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
        int result = pthread_cond_broadcast(&_shared->cond);
        if (result != 0)
            throwex SystemException("Failed to broadcast a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64)
        // Lock the named mutex
        DWORD result = WaitForSingleObject(_mutex, INFINITE);
        if (result != WAIT_OBJECT_0)
            throwex SystemException("Failed to lock a named mutex for the named condition variable!");
        // Signal all waiters
        if (!ReleaseSemaphore(_semaphore, *_shared, nullptr))
            throwex SystemException("Failed to release all semaphore waiters for the named condition variable!");
        // Clear all shared waiters
        *_shared = 0;
        // Unlock the named mutex
        if (!ReleaseMutex(_mutex))
            throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
#endif
    }

    void Wait()
    {
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
        int result = pthread_cond_wait(&_shared->cond, &_shared->mutex);
        if (result != 0)
            throwex SystemException("Failed to waiting a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64)
        // Lock the named mutex
        DWORD result = WaitForSingleObject(_mutex, INFINITE);
        if (result != WAIT_OBJECT_0)
            throwex SystemException("Failed to lock a named mutex for the named condition variable!");
        // Increment shared waiters count
        ++(*_shared);
        // Unlock the named mutex
        if (!ReleaseMutex(_mutex))
            throwex SystemException("Failed to unlock a named mutex for the named condition variable!");

        // Wait for the named condition variable
        result = WaitForSingleObject(_semaphore, INFINITE);
        if (result != WAIT_OBJECT_0)
            throwex SystemException("Failed to wait a named condition variable!");
#endif
    }

    bool TryWaitFor(const Timespan& timespan)
    {
        if (timespan < 0)
            return false;
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
        struct timespec timeout;
        timeout.tv_sec = timespan.seconds();
        timeout.tv_nsec = timespan.nanoseconds() % 1000000000;
        int result = pthread_cond_timedwait(&_shared->cond, &_shared->mutex, &timeout);
        if ((result != 0) && (result != ETIMEDOUT))
            throwex SystemException("Failed to waiting a named condition variable for the given timeout!", result);
        return (result == 0);
#elif defined(_WIN32) || defined(_WIN64)
        // Lock the named mutex
        DWORD result = WaitForSingleObject(_mutex, INFINITE);
        if (result != WAIT_OBJECT_0)
            throwex SystemException("Failed to lock a named mutex for the named condition variable!");
        // Increment shared waiters count
        ++(*_shared);
        // Unlock the named mutex
        if (!ReleaseMutex(_mutex))
            throwex SystemException("Failed to unlock a named mutex for the named condition variable!");

        // Wait for the named condition variable
        result = WaitForSingleObject(_semaphore, (DWORD)std::max(0ll, timespan.milliseconds()));
        if ((result != WAIT_OBJECT_0) && (result != WAIT_TIMEOUT))
            throwex SystemException("Failed to try lock a named condition variable for the given timeout!");
        return (result == WAIT_OBJECT_0);
#endif
    }

private:
    std::string _name;
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
    // Shared condition variable structure
    struct CondVar
    {
        pthread_mutex_t mutex;
        pthread_cond_t cond;
    };

    // Shared condition variable structure wrapper
    SharedType<CondVar> _shared;
#elif defined(_WIN32) || defined(_WIN64)
    HANDLE _mutex;
    HANDLE _semaphore;
    SharedType<LONG> _shared;
#endif
};

//! @endcond

NamedConditionVariable::NamedConditionVariable(const std::string& name) : _pimpl(std::make_unique<Impl>(name))
{
}

NamedConditionVariable::NamedConditionVariable(NamedConditionVariable&& cv) noexcept : _pimpl(std::move(cv._pimpl))
{
}

NamedConditionVariable::~NamedConditionVariable()
{
}

NamedConditionVariable& NamedConditionVariable::operator=(NamedConditionVariable&& cv) noexcept
{
    _pimpl = std::move(cv._pimpl);
    return *this;
}

const std::string& NamedConditionVariable::name() const
{
    return _pimpl->name();
}

void NamedConditionVariable::NotifyOne()
{
    _pimpl->NotifyOne();
}

void NamedConditionVariable::NotifyAll()
{
    _pimpl->NotifyAll();
}

void NamedConditionVariable::Wait()
{
    _pimpl->Wait();
}

bool NamedConditionVariable::TryWaitFor(const Timespan& timespan)
{
    return _pimpl->TryWaitFor(timespan);
}

} // namespace CppCommon
<commit_msg>Fix Cygwin build<commit_after>/*!
    \file named_condition_variable.cpp
    \brief Named condition variable synchronization primitive implementation
    \author Ivan Shynkarenka
    \date 04.10.2016
    \copyright MIT License
*/

#include "threads/named_condition_variable.h"

#include "errors/exceptions.h"
#include "errors/fatal.h"

#include <algorithm>

#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
#include "system/shared_type.h"
#include <pthread.h>
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
#include "system/shared_type.h"
#include <windows.h>
#undef max
#undef min
#endif

namespace CppCommon {

//! @cond INTERNALS

class NamedConditionVariable::Impl
{
public:
    Impl(const std::string& name) : _name(name)
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        , _shared(name)
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
        , _shared(name)
#endif
    {
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        // Only the owner should initializate a named condition variable
        if (_shared.owner())
        {
            pthread_mutexattr_t mutex_attribute;
            int result = pthread_mutexattr_init(&mutex_attribute);
            if (result != 0)
                throwex SystemException("Failed to initialize a mutex attribute for the named condition variable!", result);
            result = pthread_mutexattr_setpshared(&mutex_attribute, PTHREAD_PROCESS_SHARED);
            if (result != 0)
                throwex SystemException("Failed to set a mutex process shared attribute for the named condition variable!", result);
            result = pthread_mutex_init(&_shared->mutex, &mutex_attribute);
            if (result != 0)
                throwex SystemException("Failed to initialize a mutex for the named condition variable!", result);
            result = pthread_mutexattr_destroy(&mutex_attribute);
            if (result != 0)
                throwex SystemException("Failed to destroy a mutex attribute for the named condition variable!", result);

            pthread_condattr_t cond_attribute;
            result = pthread_condattr_init(&cond_attribute);
            if (result != 0)
                throwex SystemException("Failed to initialize a conditional variable attribute for the named condition variable!", result);
            result = pthread_condattr_setpshared(&cond_attribute, PTHREAD_PROCESS_SHARED);
            if (result != 0)
                throwex SystemException("Failed to set a conditional variable process shared attribute for the named condition variable!", result);
            result = pthread_cond_init(&_shared->cond, &cond_attribute);
            if (result != 0)
                throwex SystemException("Failed to initialize a conditional variable for the named condition variable!", result);
            result = pthread_condattr_destroy(&cond_attribute);
            if (result != 0)
                throwex SystemException("Failed to destroy a conditional variable attribute for the named condition variable!", result);
        }
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
        // Owner of the condition variable should initialize its value
        if (_shared.owner())
            *_shared = 0;
        _mutex = CreateMutexA(nullptr, FALSE, (name + "-mutex").c_str());
        if (_mutex == nullptr)
            throwex SystemException("Failed to create or open a named mutex for the named condition variable!");
        _semaphore = CreateSemaphoreA(nullptr, 0, std::numeric_limits<LONG>::max(), (name + "-semaphore").c_str());
        if (_semaphore == nullptr)
            throwex SystemException("Failed to create or open a named semaphore for the named condition variable!");
#endif
    }

    ~Impl()
    {
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        // Only the owner should destroy a named condition variable
        if (_shared.owner())
        {
            int result = pthread_mutex_destroy(&_shared->mutex);
            if (result != 0)
                fatality(SystemException("Failed to destroy a mutex for the named condition variable!", result));
            result = pthread_cond_destroy(&_shared->cond);
            if (result != 0)
                fatality(SystemException("Failed to destroy a conditional variable for the named condition variable!", result));
        }
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
        if (!CloseHandle(_mutex))
            fatality(SystemException("Failed to close a named mutex for the named condition variable!"));
        if (!CloseHandle(_semaphore))
            fatality(SystemException("Failed to close a named semaphore for the named condition variable!"));
#endif
    }

    const std::string& name() const
    {
        return _name;
    }

    void NotifyOne()
    {
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        int result = pthread_cond_signal(&_shared->cond);
        if (result != 0)
            throwex SystemException("Failed to signal a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
        // Lock the named mutex
        DWORD result = WaitForSingleObject(_mutex, INFINITE);
        if (result != WAIT_OBJECT_0)
            throwex SystemException("Failed to lock a named mutex for the named condition variable!");
        // Decrement shared waiters count
        --(*_shared);
        // Signal one waiter
        if (!ReleaseSemaphore(_semaphore, 1, nullptr))
            throwex SystemException("Failed to release one semaphore waiter for the named condition variable!");
        // Unlock the named mutex
        if (!ReleaseMutex(_mutex))
            throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
#endif
    }

    void NotifyAll()
    {
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        int result = pthread_cond_broadcast(&_shared->cond);
        if (result != 0)
            throwex SystemException("Failed to broadcast a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
        // Lock the named mutex
        DWORD result = WaitForSingleObject(_mutex, INFINITE);
        if (result != WAIT_OBJECT_0)
            throwex SystemException("Failed to lock a named mutex for the named condition variable!");
        // Signal all waiters
        if (!ReleaseSemaphore(_semaphore, *_shared, nullptr))
            throwex SystemException("Failed to release all semaphore waiters for the named condition variable!");
        // Clear all shared waiters
        *_shared = 0;
        // Unlock the named mutex
        if (!ReleaseMutex(_mutex))
            throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
#endif
    }

    void Wait()
    {
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        int result = pthread_cond_wait(&_shared->cond, &_shared->mutex);
        if (result != 0)
            throwex SystemException("Failed to waiting a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
        // Lock the named mutex
        DWORD result = WaitForSingleObject(_mutex, INFINITE);
        if (result != WAIT_OBJECT_0)
            throwex SystemException("Failed to lock a named mutex for the named condition variable!");
        // Increment shared waiters count
        ++(*_shared);
        // Unlock the named mutex
        if (!ReleaseMutex(_mutex))
            throwex SystemException("Failed to unlock a named mutex for the named condition variable!");

        // Wait for the named condition variable
        result = WaitForSingleObject(_semaphore, INFINITE);
        if (result != WAIT_OBJECT_0)
            throwex SystemException("Failed to wait a named condition variable!");
#endif
    }

    bool TryWaitFor(const Timespan& timespan)
    {
        if (timespan < 0)
            return false;
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
        struct timespec timeout;
        timeout.tv_sec = timespan.seconds();
        timeout.tv_nsec = timespan.nanoseconds() % 1000000000;
        int result = pthread_cond_timedwait(&_shared->cond, &_shared->mutex, &timeout);
        if ((result != 0) && (result != ETIMEDOUT))
            throwex SystemException("Failed to waiting a named condition variable for the given timeout!", result);
        return (result == 0);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
        // Lock the named mutex
        DWORD result = WaitForSingleObject(_mutex, INFINITE);
        if (result != WAIT_OBJECT_0)
            throwex SystemException("Failed to lock a named mutex for the named condition variable!");
        // Increment shared waiters count
        ++(*_shared);
        // Unlock the named mutex
        if (!ReleaseMutex(_mutex))
            throwex SystemException("Failed to unlock a named mutex for the named condition variable!");

        // Wait for the named condition variable
        result = WaitForSingleObject(_semaphore, (DWORD)std::max(0ll, timespan.milliseconds()));
        if ((result != WAIT_OBJECT_0) && (result != WAIT_TIMEOUT))
            throwex SystemException("Failed to try lock a named condition variable for the given timeout!");
        return (result == WAIT_OBJECT_0);
#endif
    }

private:
    std::string _name;
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
    // Shared condition variable structure
    struct CondVar
    {
        pthread_mutex_t mutex;
        pthread_cond_t cond;
    };

    // Shared condition variable structure wrapper
    SharedType<CondVar> _shared;
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
    HANDLE _mutex;
    HANDLE _semaphore;
    SharedType<LONG> _shared;
#endif
};

//! @endcond

NamedConditionVariable::NamedConditionVariable(const std::string& name) : _pimpl(std::make_unique<Impl>(name))
{
}

NamedConditionVariable::NamedConditionVariable(NamedConditionVariable&& cv) noexcept : _pimpl(std::move(cv._pimpl))
{
}

NamedConditionVariable::~NamedConditionVariable()
{
}

NamedConditionVariable& NamedConditionVariable::operator=(NamedConditionVariable&& cv) noexcept
{
    _pimpl = std::move(cv._pimpl);
    return *this;
}

const std::string& NamedConditionVariable::name() const
{
    return _pimpl->name();
}

void NamedConditionVariable::NotifyOne()
{
    _pimpl->NotifyOne();
}

void NamedConditionVariable::NotifyAll()
{
    _pimpl->NotifyAll();
}

void NamedConditionVariable::Wait()
{
    _pimpl->Wait();
}

bool NamedConditionVariable::TryWaitFor(const Timespan& timespan)
{
    return _pimpl->TryWaitFor(timespan);
}

} // namespace CppCommon
<|endoftext|>


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

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

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

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <string>
#include "itkImage.h"
#include "itkExceptionObject.h"
#include "itkNumericTraits.h"
#include "itkImageRegionIterator.h"
#include "itkImageIOFactory.h"
#include "itkBrains2MaskImageIO.h"
#include "itkBrains2MaskImageIOFactory.h"
#include "stdlib.h"
#include <itksys/SystemTools.hxx>
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
//#include "itkFlipImageFilter.h"
#include "itkSpatialOrientationAdapter.h"
#include "vnl/vnl_sample.h"

int itkBrains2MaskTest(int ac, char *av[])
{
  typedef itk::Image<unsigned int,3> ImageType;
  typedef itk::ImageFileReader<ImageType> ImageReaderType;
  typedef itk::ImageFileWriter<ImageType> ImageWriterType;

  //
  // create a random image to write out.
  const ImageType::SizeType imageSize = {{4,4,4}};
  const ImageType::IndexType imageIndex = {{0,0,0}};

  ImageType::RegionType region;
  region.SetSize(imageSize);
  region.SetIndex(imageIndex);
  ImageType::Pointer img = ImageType::New();
  img->SetLargestPossibleRegion(region);
  img->SetBufferedRegion(region);
  img->SetRequestedRegion(region);
  img->Allocate();
  itk::SpatialOrientationAdapter<3>::DirectionType CORdir=itk::SpatialOrientationAdapter<3>().ToDirectionCosines(itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RIP);
  img->SetDirection(CORdir);

  vnl_sample_reseed(8775070);
  itk::ImageRegionIterator<ImageType> ri(img,region);
  try
    {
    unsigned int counter = 0;
    while(!ri.IsAtEnd())
      {
      unsigned int val
        = static_cast<unsigned int>(vnl_sample_uniform(0.0, 16384.0));
      val = val > 8192 ? 255 : 0;
      if(counter && counter % 8 == 0)
        std::cerr << val << std::endl;
      else
        std::cerr << val << " ";
      counter++;
      ri.Set(val);
      ++ri;
      }
    std::cerr << std::endl << std::endl;
    }
  catch(itk::ExceptionObject & ex)
    {
    ex.Print(std::cerr);
    return EXIT_FAILURE;
    }
  itk::ImageIOBase::Pointer io;
  io = itk::Brains2MaskImageIO::New();

  if(ac < 2)
    {
    std::cout << "Must specify directory containing Brains2Test.mask"
              << std::endl;
    return EXIT_FAILURE;
    }
  std::string fileName(av[1]);
  fileName = fileName + "/Brains2Test.mask";

  ImageWriterType::Pointer imageWriter = ImageWriterType::New();
  imageWriter->SetImageIO(io);
  imageWriter->SetFileName(fileName.c_str());
  imageWriter->SetInput(img);
  try
    {
    imageWriter->Write();
    }
  catch (itk::ExceptionObject &ex)
    {
    std::string message;
    message = "Problem found while writing image ";
    message += fileName;
    message += "\n";
    message += ex.GetLocation();
    message += "\n";
    message += ex.GetDescription();
    std::cerr << message << std::endl;
    itksys::SystemTools::RemoveFile(fileName.c_str());
    return EXIT_FAILURE;
    }
  ImageType::Pointer readImage;
  try
    {
    ImageReaderType::Pointer imageReader = ImageReaderType::New();
    imageReader->SetImageIO(io);
    imageReader->SetFileName(fileName.c_str());
    imageReader->Update();
    readImage = imageReader->GetOutput();
    }
  catch (itk::ExceptionObject& ex)
    {
    std::string message;
    message = "Problem found while reading image ";
    message += fileName;
    message += "\n";
    message += ex.GetLocation();
    message += "\n";
    message += ex.GetDescription();
    std::cerr << message << std::endl;
    itksys::SystemTools::RemoveFile(fileName.c_str());
    return EXIT_FAILURE;
    }
  ri.GoToBegin();
  itk::ImageRegionIterator<ImageType> ri2(readImage,region);
  try
    {
    unsigned int counter = 0;
    while(!ri.IsAtEnd() && !ri2.IsAtEnd())
      {
      unsigned int x = ri.Get();
      unsigned int y = ri2.Get();
      if(counter && counter % 8 == 0)
        std::cerr << y << std::endl;
      else
        std::cerr << y << " ";
      if(x != y)
        {
        std::cerr <<
          "Error comparing Input Image and File Image of Brains2 Mask" <<
          std::endl;
        return EXIT_FAILURE;
        }
      counter++;
      ++ri;
      ++ri2;
      }
    if(!ri.IsAtEnd() || !ri2.IsAtEnd())
      {
      std::cerr << "Error, inconsistent image sizes " << std::endl;
      return EXIT_FAILURE;
      }
    }
  catch(itk::ExceptionObject & ex)
    {
    ex.Print(std::cerr);
    return EXIT_FAILURE;
    }
  //
  // test the factory interface. This ImageIO class doesn't get
  // added to the list of Builtin factories, so add it explicitly, and
  // then try and open the mask file.
  itk::ObjectFactoryBase::RegisterFactory(itk::Brains2MaskImageIOFactory::New() );
  try
    {
    ImageReaderType::Pointer imageReader = ImageReaderType::New();
    imageReader->SetFileName(fileName.c_str());
    imageReader->Update();
    readImage = imageReader->GetOutput();
    }
  catch(itk::ExceptionObject & ex)
    {
    ex.Print(std::cerr);
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}
<commit_msg>COMP: SpatialOrientationAdapter is not a templated class anymore.<commit_after>/*=========================================================================

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

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

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <string>
#include "itkImage.h"
#include "itkExceptionObject.h"
#include "itkNumericTraits.h"
#include "itkImageRegionIterator.h"
#include "itkImageIOFactory.h"
#include "itkBrains2MaskImageIO.h"
#include "itkBrains2MaskImageIOFactory.h"
#include "stdlib.h"
#include <itksys/SystemTools.hxx>
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
//#include "itkFlipImageFilter.h"
#include "itkSpatialOrientationAdapter.h"
#include "vnl/vnl_sample.h"

int itkBrains2MaskTest(int ac, char *av[])
{
  typedef itk::Image<unsigned int,3> ImageType;
  typedef itk::ImageFileReader<ImageType> ImageReaderType;
  typedef itk::ImageFileWriter<ImageType> ImageWriterType;

  //
  // create a random image to write out.
  const ImageType::SizeType imageSize = {{4,4,4}};
  const ImageType::IndexType imageIndex = {{0,0,0}};

  ImageType::RegionType region;
  region.SetSize(imageSize);
  region.SetIndex(imageIndex);
  ImageType::Pointer img = ImageType::New();
  img->SetLargestPossibleRegion(region);
  img->SetBufferedRegion(region);
  img->SetRequestedRegion(region);
  img->Allocate();
  itk::SpatialOrientationAdapter::DirectionType CORdir=itk::SpatialOrientationAdapter().ToDirectionCosines(itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RIP);
  img->SetDirection(CORdir);

  vnl_sample_reseed(8775070);
  itk::ImageRegionIterator<ImageType> ri(img,region);
  try
    {
    unsigned int counter = 0;
    while(!ri.IsAtEnd())
      {
      unsigned int val
        = static_cast<unsigned int>(vnl_sample_uniform(0.0, 16384.0));
      val = val > 8192 ? 255 : 0;
      if(counter && counter % 8 == 0)
        std::cerr << val << std::endl;
      else
        std::cerr << val << " ";
      counter++;
      ri.Set(val);
      ++ri;
      }
    std::cerr << std::endl << std::endl;
    }
  catch(itk::ExceptionObject & ex)
    {
    ex.Print(std::cerr);
    return EXIT_FAILURE;
    }
  itk::ImageIOBase::Pointer io;
  io = itk::Brains2MaskImageIO::New();

  if(ac < 2)
    {
    std::cout << "Must specify directory containing Brains2Test.mask"
              << std::endl;
    return EXIT_FAILURE;
    }
  std::string fileName(av[1]);
  fileName = fileName + "/Brains2Test.mask";

  ImageWriterType::Pointer imageWriter = ImageWriterType::New();
  imageWriter->SetImageIO(io);
  imageWriter->SetFileName(fileName.c_str());
  imageWriter->SetInput(img);
  try
    {
    imageWriter->Write();
    }
  catch (itk::ExceptionObject &ex)
    {
    std::string message;
    message = "Problem found while writing image ";
    message += fileName;
    message += "\n";
    message += ex.GetLocation();
    message += "\n";
    message += ex.GetDescription();
    std::cerr << message << std::endl;
    itksys::SystemTools::RemoveFile(fileName.c_str());
    return EXIT_FAILURE;
    }
  ImageType::Pointer readImage;
  try
    {
    ImageReaderType::Pointer imageReader = ImageReaderType::New();
    imageReader->SetImageIO(io);
    imageReader->SetFileName(fileName.c_str());
    imageReader->Update();
    readImage = imageReader->GetOutput();
    }
  catch (itk::ExceptionObject& ex)
    {
    std::string message;
    message = "Problem found while reading image ";
    message += fileName;
    message += "\n";
    message += ex.GetLocation();
    message += "\n";
    message += ex.GetDescription();
    std::cerr << message << std::endl;
    itksys::SystemTools::RemoveFile(fileName.c_str());
    return EXIT_FAILURE;
    }
  ri.GoToBegin();
  itk::ImageRegionIterator<ImageType> ri2(readImage,region);
  try
    {
    unsigned int counter = 0;
    while(!ri.IsAtEnd() && !ri2.IsAtEnd())
      {
      unsigned int x = ri.Get();
      unsigned int y = ri2.Get();
      if(counter && counter % 8 == 0)
        std::cerr << y << std::endl;
      else
        std::cerr << y << " ";
      if(x != y)
        {
        std::cerr <<
          "Error comparing Input Image and File Image of Brains2 Mask" <<
          std::endl;
        return EXIT_FAILURE;
        }
      counter++;
      ++ri;
      ++ri2;
      }
    if(!ri.IsAtEnd() || !ri2.IsAtEnd())
      {
      std::cerr << "Error, inconsistent image sizes " << std::endl;
      return EXIT_FAILURE;
      }
    }
  catch(itk::ExceptionObject & ex)
    {
    ex.Print(std::cerr);
    return EXIT_FAILURE;
    }
  //
  // test the factory interface. This ImageIO class doesn't get
  // added to the list of Builtin factories, so add it explicitly, and
  // then try and open the mask file.
  itk::ObjectFactoryBase::RegisterFactory(itk::Brains2MaskImageIOFactory::New() );
  try
    {
    ImageReaderType::Pointer imageReader = ImageReaderType::New();
    imageReader->SetFileName(fileName.c_str());
    imageReader->Update();
    readImage = imageReader->GetOutput();
    }
  catch(itk::ExceptionObject & ex)
    {
    ex.Print(std::cerr);
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.

#include <algorithm>
#include "core/Setup.h"
#include "Audio.hpp"
#include "AudioDevice.hpp"
#include "Listener.hpp"
#include "alsa/ALSAAudioDevice.hpp"
#include "core/Engine.hpp"
#include "coreaudio/CAAudioDevice.hpp"
#include "dsound/DSAudioDevice.hpp"
#include "empty/EmptyAudioDevice.hpp"
#include "openal/OALAudioDevice.hpp"
#include "opensl/OSLAudioDevice.hpp"
#include "xaudio2/XA2AudioDevice.hpp"
#include "wasapi/WASAPIAudioDevice.hpp"
#include "utils/Log.hpp"

namespace ouzel
{
    namespace audio
    {
        Driver Audio::getDriver(const std::string& driver)
        {
            if (driver.empty() || driver == "default")
            {
                auto availableDrivers = Audio::getAvailableAudioDrivers();

                if (availableDrivers.find(Driver::WASAPI) != availableDrivers.end())
                    return Driver::WASAPI;
                else if (availableDrivers.find(Driver::COREAUDIO) != availableDrivers.end())
                    return Driver::COREAUDIO;
                else if (availableDrivers.find(Driver::ALSA) != availableDrivers.end())
                    return Driver::ALSA;
                else if (availableDrivers.find(Driver::OPENAL) != availableDrivers.end())
                    return Driver::OPENAL;
                else if (availableDrivers.find(Driver::XAUDIO2) != availableDrivers.end())
                    return Driver::XAUDIO2;
                else if (availableDrivers.find(Driver::DIRECTSOUND) != availableDrivers.end())
                    return Driver::DIRECTSOUND;
                else if (availableDrivers.find(Driver::OPENSL) != availableDrivers.end())
                    return Driver::OPENSL;
                else
                    return Driver::EMPTY;
            }
            else if (driver == "empty")
                return Driver::EMPTY;
            else if (driver == "openal")
                return Driver::OPENAL;
            else if (driver == "directsound")
                return Driver::DIRECTSOUND;
            else if (driver == "xaudio2")
                return Driver::XAUDIO2;
            else if (driver == "opensl")
                return Driver::OPENSL;
            else if (driver == "coreaudio")
                return Driver::COREAUDIO;
            else if (driver == "alsa")
                return Driver::ALSA;
            else if (driver == "wasapi")
                return Driver::WASAPI;
            else
                throw std::runtime_error("Invalid audio driver");
        }

        std::set<Driver> Audio::getAvailableAudioDrivers()
        {
            static std::set<Driver> availableDrivers;

            if (availableDrivers.empty())
            {
                availableDrivers.insert(Driver::EMPTY);

#if OUZEL_COMPILE_OPENAL
                availableDrivers.insert(Driver::OPENAL);
#endif
#if OUZEL_COMPILE_DIRECTSOUND
                availableDrivers.insert(Driver::DIRECTSOUND);
#endif
#if OUZEL_COMPILE_XAUDIO2
                availableDrivers.insert(Driver::XAUDIO2);
#endif
#if OUZEL_COMPILE_OPENSL
                availableDrivers.insert(Driver::OPENSL);
#endif
#if OUZEL_COMPILE_COREAUDIO
                availableDrivers.insert(Driver::COREAUDIO);
#endif
#if OUZEL_COMPILE_ALSA
                availableDrivers.insert(Driver::ALSA);
#endif
#if OUZEL_COMPILE_WASAPI
                availableDrivers.insert(Driver::WASAPI);
#endif
            }

            return availableDrivers;
        }

        static std::unique_ptr<AudioDevice> createAudioDevice(Driver driver,
                                                              const std::function<void(uint32_t frames, uint16_t channels, uint32_t sampleRate, std::vector<float>& samples)>& dataGetter,
                                                              bool debugAudio, Window* window)
        {
            switch (driver)
            {
#if OUZEL_COMPILE_OPENAL
                case Driver::OPENAL:
                    engine->log(Log::Level::INFO) << "Using OpenAL audio driver";
                    return std::unique_ptr<AudioDevice>(new OALAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_DIRECTSOUND
                case Driver::DIRECTSOUND:
                    engine->log(Log::Level::INFO) << "Using DirectSound audio driver";
                    return std::unique_ptr<AudioDevice>(new DSAudioDevice(512, 44100, 0, dataGetter, window));
#endif
#if OUZEL_COMPILE_XAUDIO2
                case Driver::XAUDIO2:
                    engine->log(Log::Level::INFO) << "Using XAudio 2 audio driver";
                    return std::unique_ptr<AudioDevice>(new XA2AudioDevice(512, 44100, 0, dataGetter, debugAudio));
#endif
#if OUZEL_COMPILE_OPENSL
                case Driver::OPENSL:
                    engine->log(Log::Level::INFO) << "Using OpenSL ES audio driver";
                    return std::unique_ptr<AudioDevice>(new OSLAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_COREAUDIO
                case Driver::COREAUDIO:
                    engine->log(Log::Level::INFO) << "Using CoreAudio audio driver";
                    return std::unique_ptr<AudioDevice>(new CAAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_ALSA
                case Driver::ALSA:
                    engine->log(Log::Level::INFO) << "Using ALSA audio driver";
                    return std::unique_ptr<AudioDevice>(new ALSAAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_WASAPI
                case Driver::WASAPI:
                    engine->log(Log::Level::INFO) << "Using WASAPI audio driver";
                    return std::unique_ptr<AudioDevice>(new WASAPIAudioDevice(512, 44100, 0, dataGetter));
#endif
                default:
                    engine->log(Log::Level::INFO) << "Not using audio driver";
                    (void)debugAudio;
                    (void)window;
                    return std::unique_ptr<AudioDevice>(new EmptyAudioDevice(512, 44100, 0, dataGetter));
            }
        }

        Audio::Audio(Driver driver, bool debugAudio, Window* window):
            device(createAudioDevice(driver,
                                     std::bind(&Audio::getData, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4),
                                     debugAudio, window)),
            mixer(device->getBufferSize(), device->getChannels(),
                  std::bind(&Audio::eventCallback, this, std::placeholders::_1)),
            masterMix(*this)
        {
            addCommand(std::unique_ptr<mixer::Command>(new mixer::SetMasterBusCommand(masterMix.getBusId())));
            device->start();
        }

        Audio::~Audio()
        {
        }

        void Audio::update()
        {
            // TODO: handle events from the audio device

            mixer.submitCommandBuffer(std::move(commandBuffer));
            commandBuffer = mixer::CommandBuffer();
        }

        void Audio::deleteObject(uintptr_t objectId)
        {
            addCommand(std::unique_ptr<mixer::Command>(new mixer::DeleteObjectCommand(objectId)));
        }

        uintptr_t Audio::initBus()
        {
            uintptr_t busId = mixer.getObjectId();
            addCommand(std::unique_ptr<mixer::Command>(new mixer::InitBusCommand(busId)));
            return busId;
        }

        uintptr_t Audio::initStream(uintptr_t sourceId)
        {
            uintptr_t streamId = mixer.getObjectId();
            addCommand(std::unique_ptr<mixer::Command>(new mixer::InitStreamCommand(streamId, sourceId)));
            return streamId;
        }

        uintptr_t Audio::initData(const std::function<std::unique_ptr<mixer::Data>()>& initFunction)
        {
            uintptr_t dataId = mixer.getObjectId();
            addCommand(std::unique_ptr<mixer::Command>(new mixer::InitDataCommand(dataId,
                                                                                initFunction)));
            return dataId;
        }

        uintptr_t Audio::initProcessor(std::unique_ptr<mixer::Processor>&& processor)
        {
            uintptr_t processorId = mixer.getObjectId();
            addCommand(std::unique_ptr<mixer::Command>(new mixer::InitProcessorCommand(processorId,
                                                                                std::forward<std::unique_ptr<mixer::Processor>>(processor))));
            return processorId;
        }

        void Audio::updateProcessor(uintptr_t processorId, const std::function<void(mixer::Processor*)>& updateFunction)
        {
            addCommand(std::unique_ptr<mixer::Command>(new mixer::UpdateProcessorCommand(processorId,
                                                                                updateFunction)));
        }

        void Audio::getData(uint32_t frames, uint16_t channels, uint32_t sampleRate, std::vector<float>& samples)
        {
            mixer.getSamples(frames, channels, sampleRate, samples);
        }

        void Audio::eventCallback(const mixer::Mixer::Event& event)
        {

        }
    } // namespace audio
} // namespace ouzel
<commit_msg>Rename the remaining getData methods to getSamples<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.

#include <algorithm>
#include "core/Setup.h"
#include "Audio.hpp"
#include "AudioDevice.hpp"
#include "Listener.hpp"
#include "alsa/ALSAAudioDevice.hpp"
#include "core/Engine.hpp"
#include "coreaudio/CAAudioDevice.hpp"
#include "dsound/DSAudioDevice.hpp"
#include "empty/EmptyAudioDevice.hpp"
#include "openal/OALAudioDevice.hpp"
#include "opensl/OSLAudioDevice.hpp"
#include "xaudio2/XA2AudioDevice.hpp"
#include "wasapi/WASAPIAudioDevice.hpp"
#include "utils/Log.hpp"

namespace ouzel
{
    namespace audio
    {
        Driver Audio::getDriver(const std::string& driver)
        {
            if (driver.empty() || driver == "default")
            {
                auto availableDrivers = Audio::getAvailableAudioDrivers();

                if (availableDrivers.find(Driver::WASAPI) != availableDrivers.end())
                    return Driver::WASAPI;
                else if (availableDrivers.find(Driver::COREAUDIO) != availableDrivers.end())
                    return Driver::COREAUDIO;
                else if (availableDrivers.find(Driver::ALSA) != availableDrivers.end())
                    return Driver::ALSA;
                else if (availableDrivers.find(Driver::OPENAL) != availableDrivers.end())
                    return Driver::OPENAL;
                else if (availableDrivers.find(Driver::XAUDIO2) != availableDrivers.end())
                    return Driver::XAUDIO2;
                else if (availableDrivers.find(Driver::DIRECTSOUND) != availableDrivers.end())
                    return Driver::DIRECTSOUND;
                else if (availableDrivers.find(Driver::OPENSL) != availableDrivers.end())
                    return Driver::OPENSL;
                else
                    return Driver::EMPTY;
            }
            else if (driver == "empty")
                return Driver::EMPTY;
            else if (driver == "openal")
                return Driver::OPENAL;
            else if (driver == "directsound")
                return Driver::DIRECTSOUND;
            else if (driver == "xaudio2")
                return Driver::XAUDIO2;
            else if (driver == "opensl")
                return Driver::OPENSL;
            else if (driver == "coreaudio")
                return Driver::COREAUDIO;
            else if (driver == "alsa")
                return Driver::ALSA;
            else if (driver == "wasapi")
                return Driver::WASAPI;
            else
                throw std::runtime_error("Invalid audio driver");
        }

        std::set<Driver> Audio::getAvailableAudioDrivers()
        {
            static std::set<Driver> availableDrivers;

            if (availableDrivers.empty())
            {
                availableDrivers.insert(Driver::EMPTY);

#if OUZEL_COMPILE_OPENAL
                availableDrivers.insert(Driver::OPENAL);
#endif
#if OUZEL_COMPILE_DIRECTSOUND
                availableDrivers.insert(Driver::DIRECTSOUND);
#endif
#if OUZEL_COMPILE_XAUDIO2
                availableDrivers.insert(Driver::XAUDIO2);
#endif
#if OUZEL_COMPILE_OPENSL
                availableDrivers.insert(Driver::OPENSL);
#endif
#if OUZEL_COMPILE_COREAUDIO
                availableDrivers.insert(Driver::COREAUDIO);
#endif
#if OUZEL_COMPILE_ALSA
                availableDrivers.insert(Driver::ALSA);
#endif
#if OUZEL_COMPILE_WASAPI
                availableDrivers.insert(Driver::WASAPI);
#endif
            }

            return availableDrivers;
        }

        static std::unique_ptr<AudioDevice> createAudioDevice(Driver driver,
                                                              const std::function<void(uint32_t frames, uint16_t channels, uint32_t sampleRate, std::vector<float>& samples)>& dataGetter,
                                                              bool debugAudio, Window* window)
        {
            switch (driver)
            {
#if OUZEL_COMPILE_OPENAL
                case Driver::OPENAL:
                    engine->log(Log::Level::INFO) << "Using OpenAL audio driver";
                    return std::unique_ptr<AudioDevice>(new OALAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_DIRECTSOUND
                case Driver::DIRECTSOUND:
                    engine->log(Log::Level::INFO) << "Using DirectSound audio driver";
                    return std::unique_ptr<AudioDevice>(new DSAudioDevice(512, 44100, 0, dataGetter, window));
#endif
#if OUZEL_COMPILE_XAUDIO2
                case Driver::XAUDIO2:
                    engine->log(Log::Level::INFO) << "Using XAudio 2 audio driver";
                    return std::unique_ptr<AudioDevice>(new XA2AudioDevice(512, 44100, 0, dataGetter, debugAudio));
#endif
#if OUZEL_COMPILE_OPENSL
                case Driver::OPENSL:
                    engine->log(Log::Level::INFO) << "Using OpenSL ES audio driver";
                    return std::unique_ptr<AudioDevice>(new OSLAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_COREAUDIO
                case Driver::COREAUDIO:
                    engine->log(Log::Level::INFO) << "Using CoreAudio audio driver";
                    return std::unique_ptr<AudioDevice>(new CAAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_ALSA
                case Driver::ALSA:
                    engine->log(Log::Level::INFO) << "Using ALSA audio driver";
                    return std::unique_ptr<AudioDevice>(new ALSAAudioDevice(512, 44100, 0, dataGetter));
#endif
#if OUZEL_COMPILE_WASAPI
                case Driver::WASAPI:
                    engine->log(Log::Level::INFO) << "Using WASAPI audio driver";
                    return std::unique_ptr<AudioDevice>(new WASAPIAudioDevice(512, 44100, 0, dataGetter));
#endif
                default:
                    engine->log(Log::Level::INFO) << "Not using audio driver";
                    (void)debugAudio;
                    (void)window;
                    return std::unique_ptr<AudioDevice>(new EmptyAudioDevice(512, 44100, 0, dataGetter));
            }
        }

        Audio::Audio(Driver driver, bool debugAudio, Window* window):
            device(createAudioDevice(driver,
                                     std::bind(&Audio::getSamples, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4),
                                     debugAudio, window)),
            mixer(device->getBufferSize(), device->getChannels(),
                  std::bind(&Audio::eventCallback, this, std::placeholders::_1)),
            masterMix(*this)
        {
            addCommand(std::unique_ptr<mixer::Command>(new mixer::SetMasterBusCommand(masterMix.getBusId())));
            device->start();
        }

        Audio::~Audio()
        {
        }

        void Audio::update()
        {
            // TODO: handle events from the audio device

            mixer.submitCommandBuffer(std::move(commandBuffer));
            commandBuffer = mixer::CommandBuffer();
        }

        void Audio::deleteObject(uintptr_t objectId)
        {
            addCommand(std::unique_ptr<mixer::Command>(new mixer::DeleteObjectCommand(objectId)));
        }

        uintptr_t Audio::initBus()
        {
            uintptr_t busId = mixer.getObjectId();
            addCommand(std::unique_ptr<mixer::Command>(new mixer::InitBusCommand(busId)));
            return busId;
        }

        uintptr_t Audio::initStream(uintptr_t sourceId)
        {
            uintptr_t streamId = mixer.getObjectId();
            addCommand(std::unique_ptr<mixer::Command>(new mixer::InitStreamCommand(streamId, sourceId)));
            return streamId;
        }

        uintptr_t Audio::initData(const std::function<std::unique_ptr<mixer::Data>()>& initFunction)
        {
            uintptr_t dataId = mixer.getObjectId();
            addCommand(std::unique_ptr<mixer::Command>(new mixer::InitDataCommand(dataId,
                                                                                initFunction)));
            return dataId;
        }

        uintptr_t Audio::initProcessor(std::unique_ptr<mixer::Processor>&& processor)
        {
            uintptr_t processorId = mixer.getObjectId();
            addCommand(std::unique_ptr<mixer::Command>(new mixer::InitProcessorCommand(processorId,
                                                                                std::forward<std::unique_ptr<mixer::Processor>>(processor))));
            return processorId;
        }

        void Audio::updateProcessor(uintptr_t processorId, const std::function<void(mixer::Processor*)>& updateFunction)
        {
            addCommand(std::unique_ptr<mixer::Command>(new mixer::UpdateProcessorCommand(processorId,
                                                                                updateFunction)));
        }

        void Audio::getSamples(uint32_t frames, uint16_t channels, uint32_t sampleRate, std::vector<float>& samples)
        {
            mixer.getSamples(frames, channels, sampleRate, samples);
        }

        void Audio::eventCallback(const mixer::Mixer::Event& event)
        {

        }
    } // namespace audio
} // namespace ouzel
<|endoftext|>


<commit_before>// Copyright (c) 2018 ASMlover. 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// 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 <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include "scanner.h"

static bool had_error{};

static void report(
    int line, const std::string& where, const std::string& message) {
  std::cerr
    << "[line " << line << "] ERROR " << where << ": "
    << message << std::endl;
  had_error = true;
}

static void error(int line, const std::string& message) {
  report(line, "", message);
}

static void print_tokens(const std::string& source) {
  Scanner s(source);
  auto tokens = s.scan_tokens();
  for (auto& t : tokens)
    std::cout << t.repr() << std::endl;
}

static void repl(void) {
  std::string line;
  for (;;) {
    std::cout << ">>> ";

    if (!std::getline(std::cin, line) || line == "exit") {
      std::cout << std::endl;
      break;
    }

    // interpret(line);
    print_tokens(line);
    had_error = false;
  }
}

static std::string read_file(const std::string& path) {
  std::ifstream fp(path);

  if (fp.is_open()) {
    std::stringstream ss;
    ss << fp.rdbuf();
    return ss.str();
  }
  return "";
}

static void run(const std::string& source) {
}

static void run_file(const std::string& path) {
  auto bytes = read_file(path);
  // run(bytes);

  print_tokens(bytes);

  if (had_error)
    std::exit(1);
}

int main(int argc, char* argv[]) {
  (void)argc, (void)argv;

  if (argc < 2) {
    repl();
  }
  else if (argc == 2) {
    run_file(argv[1]);
  }
  else {
    std::cerr << "USAGE: loxpp {script}" << std::endl;
    std::exit(1);
  }

  return 0;
}
<commit_msg>:construction: chore(lox): updated the lox starting<commit_after>// Copyright (c) 2018 ASMlover. 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// 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 <cstdlib>
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include "error_reporter.h"
#include "scanner.h"
#include "parser.h"
#include "ast_printer.h"
#include "interpreter.h"

static ErrorReporter err_reporter;
static std::shared_ptr<Interpreter> interp = std::make_shared<Interpreter>(err_reporter);

static void run(const std::string& source) {
  Scanner s(source);
  auto tokens = s.scan_tokens();
  // for (auto& t : tokens)
  //   std::cout << t.repr() << std::endl;

  // Parser p(tokens);
  // auto expr = p.parse();
  // std::cout << std::make_shared<AstPrinter>()->as_string(expr) << std::endl;

  // auto interp = std::make_shared<Interpreter>(err_reporter);
  // interp->interpret(expr);

  Parser p(tokens);
  auto stmts = p.parse_stmt();

  // auto interp = std::make_shared<Interpreter>(err_reporter);
  interp->interpret(stmts);

  if (err_reporter.had_error())
    std::abort();
}

static void repl(void) {
  std::string line;
  for (;;) {
    std::cout << ">>> ";

    if (!std::getline(std::cin, line) || line == "exit") {
      std::cout << std::endl;
      break;
    }

    run(line);
  }
}

static std::string read_file(const std::string& path) {
  std::ifstream fp(path);

  if (fp.is_open()) {
    std::stringstream ss;
    ss << fp.rdbuf();
    return ss.str();
  }
  return "";
}

static void run_file(const std::string& path) {
  auto bytes = read_file(path);
  run(bytes);
}

int main(int argc, char* argv[]) {
  (void)argc, (void)argv;

  if (argc < 2) {
    repl();
  }
  else if (argc == 2) {
    run_file(argv[1]);
  }
  else {
    std::cerr << "USAGE: loxpp {script}" << std::endl;
    std::exit(1);
  }

  return 0;
}
<|endoftext|>


<commit_before>/* **********************************************************************************************
Homework: #7
Author: Dak Washbrook
Due: Sun. March 20, 2016

Title: Complex Number
Assignment: Create a class called Complex for performing arithmetic with complex numbers. Write a
program to test your class.

Complex numbers have the form:
realPart + imaginaryPart * i

Use double variables to represent the private data of the class. Provide a constructor that
enables an object of this class to be initialized when it is declared. The constructor should
contain default values in case no initializers are provided. Provide public member functions that
perform the following tasks:

a) Adding two complex numbers: The real parts added together and the imaginary parts are
added together.

b) Subtracting two complex numbers: The real parts subtracted together and the imaginary
parts are subtracted together.

c) Printing Complex numbers in the form (a , b), where a is the real part and b is the
imaginary part.

(Do not use operator overloading for this assignment.)
********************************************************************************************** */

#include <iostream>

using namespace std;

class Complex {

private:
	// Declare the Real Number
	double real;

	// Declare the Imaginary Number
	double imaginary;

public:
	/**
	* Complex constructor.
	*
	* @param double real			Initializer for the Real Number
	* @param double imaginary		Initializer for the Imaginary Number
	*/
	Complex(double real = 0.0, double imaginary = 0.0) {
		// Store the Real Number
		this->real = real;

		// Store the Imaginary Number
		this->imaginary = imaginary;
	}

	/**
	* Add this Complex to with another Complex and return the newComplex.
	*
	* @param Complex num2			Complex to be added to this Complex
	* @return Complex newComplex	returns the newComplex number after adding.
	*/
	Complex add(Complex num2) {
		double newReal = this->real + num2.getReal();
		double newImaginary = this->imaginary + num2.getImaginary();
		Complex newComplex(newReal, newImaginary);
		return newComplex;
	}

	/**
	* Subtract another Complex from this Complex and return the new Complex.
	*
	* @param Complex num2			Complex to be subtracted from this Complex
	* @return Complex newComplex	returns the newComplex number after subtracting.
	*/
	Complex subtract(Complex num2) {
		double newReal = this->real - num2.getReal();
		double newImaginary = this->imaginary - num2.getImaginary();
		Complex newComplex(newReal, newImaginary);
		return newComplex;
	}

	/**
	* Print this Complex Number as (a, b). Where a is the real number and b is the imaginary part.
	*/
	void print() {
		cout << "(" << this->real << ", " << this->imaginary << ")" << endl;
	}

	/**
	* Accessor function for this real number.
	*
	* @return double real
	*/
	double getReal() {
		return this->real;
	}

	/**
	* Accessor function for this real number.
	*
	* @return double imaginary
	*/
	double getImaginary() {
		return this->imaginary;
	}

};

int main() {

	while (true) {
		/**
		* Declare the real and imaginary doubles for the first and second complex numbers.
		*/
		double firstReal, firstImaginary;
		double secondReal, secondImaginary;

		/**
		* Declare the choice integer for the action the user want's to make.
		*/
		int choice;

		do {
			// Request the first real number.
			cout << "Enter the first real number: ";
			cin >> firstReal;

			// Request the first imaginary number.
			cout << "Enter the first imaginary number: ";
			cin >> firstImaginary;

			// Request the second real number.
			cout << "Enter the second real number: ";
			cin >> secondReal;

			// Request the second imaginary number.
			cout << "Enter the second imaginary number: ";
			cin >> secondImaginary;

			/**
			* Create the Complex objects for the first and second complex numbers.
			*/
			Complex first(firstReal, firstImaginary);
			Complex second(secondReal, secondImaginary);
			cout << "Complex Numbers are now stored." << endl << endl;

			/**
			* Do while loop for the choices of how to manipulate the Complex numbers.
			*/
			do {
				cout << "Select an option to manipulate the Complex Numbers: " << endl;
				cout << "1. Add" << endl;
				cout << "2. Subtract" << endl;
				cout << "3. New Numbers" << endl;
				cout << "4. End Program." << endl;
				cin >> choice;
				// If the choice is out of range, continue.
				if (choice < 1 || choice > 4) {
					cout << "INVALID CHOICE" << endl;
					continue;
				}

				// Declare what will be the new Complex number.
				Complex newComplex;

				// Switch statement to run the action that the user chooses.
				switch (choice) {
				case 1:
					newComplex = first.add(second);
					newComplex.print();
					break;
				case 2:
					newComplex = first.subtract(second);
					newComplex.print();
					break;
				case 3:
					goto store;
					break;
				default:
					goto stop;
					break;
				}

			} while (true);
		store:
			continue;
		} while (true);
	stop:
		break;
	}

	cout << endl;

	return 0;

}
<commit_msg>Update Homework-7.cpp<commit_after>/* **********************************************************************************************
Homework: #7
Author: Dak Washbrook
Due: Sun. March 20, 2016

Title: Complex Number
Assignment: Create a class called Complex for performing arithmetic with complex numbers. Write a
program to test your class.

Complex numbers have the form:
realPart + imaginaryPart * i

Use double variables to represent the private data of the class. Provide a constructor that
enables an object of this class to be initialized when it is declared. The constructor should
contain default values in case no initializers are provided. Provide public member functions that
perform the following tasks:

a) Adding two complex numbers: The real parts added together and the imaginary parts are
added together.

b) Subtracting two complex numbers: The real parts subtracted together and the imaginary
parts are subtracted together.

c) Printing Complex numbers in the form (a , b), where a is the real part and b is the
imaginary part.

(Do not use operator overloading for this assignment.)
********************************************************************************************** */

#include <iostream>

using namespace std;

class Complex {

private:
	// Declare the Real Number
	double real;

	// Declare the Imaginary Number
	double imaginary;

public:
	/**
	* Complex constructor.
	*
	* @param double real			Initializer for the Real Number
	* @param double imaginary		Initializer for the Imaginary Number
	*/
	Complex(double real = 0.0, double imaginary = 0.0) {
		// Store the Real Number
		this->real = real;

		// Store the Imaginary Number
		this->imaginary = imaginary;
	}

	/**
	* Add this Complex to with another Complex and return the newComplex.
	*
	* @param Complex num2			Complex to be added to this Complex
	* @return Complex newComplex	returns the newComplex number after adding.
	*/
	Complex add(Complex num2) {
		double newReal = this->real + num2.getReal();
		double newImaginary = this->imaginary + num2.getImaginary();
		Complex newComplex(newReal, newImaginary);
		return newComplex;
	}

	/**
	* Subtract another Complex from this Complex and return the new Complex.
	*
	* @param Complex num2			Complex to be subtracted from this Complex
	* @return Complex newComplex	returns the newComplex number after subtracting.
	*/
	Complex subtract(Complex num2) {
		double newReal = this->real - num2.getReal();
		double newImaginary = this->imaginary - num2.getImaginary();
		Complex newComplex(newReal, newImaginary);
		return newComplex;
	}

	/**
	* Print this Complex Number as (a, b). Where a is the real number and b is the imaginary part.
	*/
	void print() {
		cout << endl << "The new imaginary number is: (" << this->real << ", " << this->imaginary << ")" << endl << endl;
	}

	/**
	* Accessor function for this real number.
	*
	* @return double real
	*/
	double getReal() {
		return this->real;
	}

	/**
	* Accessor function for this real number.
	*
	* @return double imaginary
	*/
	double getImaginary() {
		return this->imaginary;
	}

};

int main() {

	while (true) {
		/**
		* Declare the real and imaginary doubles for the first and second complex numbers.
		*/
		double firstReal, firstImaginary;
		double secondReal, secondImaginary;

		/**
		* Declare the choice integer for the action the user want's to make.
		*/
		int choice;

		do {
			// Request the first real number.
			cout << "Enter the first real number: ";
			cin >> firstReal;

			// Request the first imaginary number.
			cout << "Enter the first imaginary number: ";
			cin >> firstImaginary;

			// Request the second real number.
			cout << "Enter the second real number: ";
			cin >> secondReal;

			// Request the second imaginary number.
			cout << "Enter the second imaginary number: ";
			cin >> secondImaginary;

			/**
			* Create the Complex objects for the first and second complex numbers.
			*/
			Complex first(firstReal, firstImaginary);
			Complex second(secondReal, secondImaginary);
			cout << "Complex Numbers are now stored." << endl << endl;

			/**
			* Do while loop for the choices of how to manipulate the Complex numbers.
			*/
			do {
				cout << "Select an option to manipulate the Complex Numbers: " << endl;
				cout << "1. Add" << endl;
				cout << "2. Subtract" << endl;
				cout << "3. New Numbers" << endl;
				cout << "4. End Program." << endl;
				cin >> choice;
				// If the choice is out of range, continue.
				if (choice < 1 || choice > 4) {
					cout << "INVALID CHOICE" << endl;
					continue;
				}

				// Declare what will be the new Complex number.
				Complex newComplex;

				// Switch statement to run the action that the user chooses.
				switch (choice) {
				case 1:
					newComplex = first.add(second);
					newComplex.print();
					break;
				case 2:
					newComplex = first.subtract(second);
					newComplex.print();
					break;
				case 3:
					goto store;
					break;
				default:
					goto stop;
					break;
				}

			} while (true);
		store:
			continue;
		} while (true);
	stop:
		break;
	}

	cout << endl;

	return 0;

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: implementationentry.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 10:33:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CPPUHELPER_IMPLEMENATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;

namespace cppu {

sal_Bool component_writeInfoHelper(
    void *, void *pRegistryKey , const struct ImplementationEntry entries[] )
{
    sal_Bool bRet = sal_False;
    try
    {
        if( pRegistryKey )
        {
            for( sal_Int32 i = 0; entries[i].create ; i ++ )
            {
                OUStringBuffer buf( 124 );
                buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("/") );
                buf.append( entries[i].getImplementationName() );
                buf.appendAscii(RTL_CONSTASCII_STRINGPARAM( "/UNO/SERVICES" ) );
                Reference< XRegistryKey > xNewKey(
                    reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( buf.makeStringAndClear()  ) );

                Sequence< OUString > seq = entries[i].getSupportedServiceNames();
                const OUString *pArray = seq.getConstArray();
                for ( sal_Int32 nPos = 0 ; nPos < seq.getLength(); nPos ++ )
                    xNewKey->createKey( pArray[nPos] );
            }
            bRet = sal_True;
        }
    }
    catch ( InvalidRegistryException & )
    {
        OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
    }
    return bRet;
}

void * component_getFactoryHelper(
    const sal_Char * pImplName, void *, void *,
    const struct ImplementationEntry entries[] )
{

      void * pRet = 0;
    Reference< XSingleComponentFactory > xFactory;

    for( sal_Int32 i = 0 ; entries[i].create ; i ++ )
    {
        OUString implName = entries[i].getImplementationName();
        if( 0 == implName.compareToAscii( pImplName ) )
        {
            xFactory = entries[i].createFactory(
                entries[i].create,
                implName,
                entries[i].getSupportedServiceNames(),
                entries[i].moduleCounter );
        }
    }

    if( xFactory.is() )
    {
        xFactory->acquire();
        pRet = xFactory.get();
    }
    return pRet;
}

}
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.14); FILE MERGED 2006/09/01 17:23:17 kaib 1.3.14.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: implementationentry.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 12:41:06 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_cppuhelper.hxx"
#ifndef _CPPUHELPER_IMPLEMENATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;

namespace cppu {

sal_Bool component_writeInfoHelper(
    void *, void *pRegistryKey , const struct ImplementationEntry entries[] )
{
    sal_Bool bRet = sal_False;
    try
    {
        if( pRegistryKey )
        {
            for( sal_Int32 i = 0; entries[i].create ; i ++ )
            {
                OUStringBuffer buf( 124 );
                buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("/") );
                buf.append( entries[i].getImplementationName() );
                buf.appendAscii(RTL_CONSTASCII_STRINGPARAM( "/UNO/SERVICES" ) );
                Reference< XRegistryKey > xNewKey(
                    reinterpret_cast< XRegistryKey * >( pRegistryKey )->createKey( buf.makeStringAndClear()  ) );

                Sequence< OUString > seq = entries[i].getSupportedServiceNames();
                const OUString *pArray = seq.getConstArray();
                for ( sal_Int32 nPos = 0 ; nPos < seq.getLength(); nPos ++ )
                    xNewKey->createKey( pArray[nPos] );
            }
            bRet = sal_True;
        }
    }
    catch ( InvalidRegistryException & )
    {
        OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
    }
    return bRet;
}

void * component_getFactoryHelper(
    const sal_Char * pImplName, void *, void *,
    const struct ImplementationEntry entries[] )
{

      void * pRet = 0;
    Reference< XSingleComponentFactory > xFactory;

    for( sal_Int32 i = 0 ; entries[i].create ; i ++ )
    {
        OUString implName = entries[i].getImplementationName();
        if( 0 == implName.compareToAscii( pImplName ) )
        {
            xFactory = entries[i].createFactory(
                entries[i].create,
                implName,
                entries[i].getSupportedServiceNames(),
                entries[i].moduleCounter );
        }
    }

    if( xFactory.is() )
    {
        xFactory->acquire();
        pRet = xFactory.get();
    }
    return pRet;
}

}
<|endoftext|>