<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

namespace etl {

#ifdef ETL_VECTORIZE_FULL

//VECTORIZE_FULL enables VECTORIZE_EXPR
#ifndef ETL_VECTORIZE_EXPR
#define ETL_VECTORIZE_EXPR
#endif

//VECTORIZE_FULL enables VECTORIZE_IMPL
#ifndef ETL_VECTORIZE_IMPL
#define ETL_VECTORIZE_IMPL
#endif

#endif //ETL_VECTORIZE_FULL

//Flag to enable auto-vectorization of expressions
#ifdef ETL_VECTORIZE_EXPR
constexpr bool vectorize_expr = true;
#else
constexpr bool vectorize_expr   = false;                               ///< Boolean flag indicating if the expression are automatically vectorized
#endif

//Flag to enable vectorized implementation of algorithms
#ifdef ETL_VECTORIZE_IMPL
constexpr bool vectorize_impl = true;
#else
constexpr bool vectorize_impl   = false;                               ///< Boolean flag indicating if the implementations are automatically vectorized
#endif

//Flag to allow conv_valid_multi to use FFT
#ifdef ETL_CONV_VALID_FFT
constexpr bool conv_valid_fft = true;
#else
constexpr bool conv_valid_fft   = false;                               ///< Boolean flag indicating if temporaries are created
#endif

//Select the number of threads
#ifdef ETL_PARALLEL_THREADS
constexpr std::size_t threads = ETL_PARALLEL_THREADS;
#else
const std::size_t threads             = std::thread::hardware_concurrency(); ///< Number of threads
#endif

//Indicate that ETL should run in parallel
#ifdef ETL_PARALLEL
constexpr bool is_parallel = true;
#else
constexpr bool is_parallel = false;                               ///< Boolean flag indicating if expressions and implementations are parallelized (alpha)
#endif

#ifdef ETL_MKL_MODE

//MKL mode enables BLAS mode
#ifndef ETL_BLAS_MODE
#define ETL_BLAS_MODE
#endif

constexpr bool is_mkl_enabled = true;
constexpr bool has_fast_fft   = true;

#else

constexpr bool is_mkl_enabled              = false; ///< Boolean flag indicating if MKL is enabled
constexpr bool has_fast_fft                = false; ///< Boolean flag indicating if a fast FFT implementation is available

#endif

//Flag to enable the use of CBLAS library
#ifdef ETL_BLAS_MODE
constexpr bool is_cblas_enabled = true;
#else
constexpr bool is_cblas_enabled            = false; ///< Boolean flag indicating if CBLAS is available
#endif

//Flag to indicate that blas is multithreaded
#ifdef ETL_BLAS_THREADS
constexpr bool is_blas_parallel = true;
#else
constexpr bool is_blas_parallel            = false; ///< Boolean flag indicating if CBLAS is running parallel
#endif

#ifdef ETL_CUDA
static_assert(false, "ETL_CUDA should never be set directly");
#endif

#ifdef ETL_CUBLAS_MODE
constexpr bool is_cublas_enabled = true;
#define ETL_CUDA
#else
constexpr bool is_cublas_enabled           = false; ///< Boolean flag indicating if CUBLAS is available
#endif

#ifdef ETL_CUFFT_MODE
#define ETL_CUDA
constexpr bool is_cufft_enabled = true;
#else
constexpr bool is_cufft_enabled            = false; ///< Boolean flag indicating if CUFFT is available
#endif

#ifdef ETL_CUDNN_MODE
constexpr bool is_cudnn_enabled = true;
#define ETL_CUDA
#else
constexpr bool is_cudnn_enabled            = false; ///< Boolean flag indicating if CUDNN is available
#endif

//Flag to perform elementwise multiplication by default (operator*)
//instead of matrix(vector) multiplication
#ifdef ETL_ELEMENT_WISE_MULTIPLICATION
constexpr bool is_element_wise_mul_default = true;
#else
constexpr bool is_element_wise_mul_default = false; ///< Boolean flag indicating if multiplication of two expression means matrix multiplication (false) or element-wise multiplication (true)
#endif

//Flag to prevent division to be done by multiplication
#ifdef ETL_STRICT_DIV
constexpr bool is_div_strict = true;
#else
constexpr bool is_div_strict               = false; ///< Boolean flag indicating if division can be done by multiplication (false) or not (true)
#endif

// Flag to disable streaming operations
#ifdef ETL_NO_STREAMING
constexpr bool streaming = false;
#else
constexpr bool streaming = true;
#endif

// Flag to disable padding operations
#ifdef ETL_NO_PADDING
constexpr bool padding = false;
#else
constexpr bool padding = true;
#endif

// Flag to disable padding implementations
#ifdef ETL_NO_PADDING_IMPL
constexpr bool padding_impl = false;
#else
constexpr bool padding_impl = true;
#endif

// Flag to set the cache size
#ifdef ETL_CACHE_SIZE
constexpr size_t cache_size = ETL_CACHE_SIZE;
#else
constexpr size_t cache_size = 3 * 1024 * 1024;
#endif

//Flag to disable unrolling of non-vectorized loops
#ifdef ETL_NO_UNROLL_NON_VECT
constexpr bool unroll_normal_loops = false;
#else
constexpr bool unroll_normal_loops         = true;  ///< Boolean flag indicating if normal loops are getting unrolled
#endif

//Flag to configure the maximum workspace size for ETL
#ifdef ETL_MAX_WORKSPACE
constexpr std::size_t max_workspace = ETL_MAX_WORKSPACE;
#else
constexpr std::size_t max_workspace = 2UL * 1024 * 1024 * 1024; ///< The max workspace we allocate for ETL (2GiB by default)
#endif

//Flag to configure the maximum workspace size for CUDA
#ifdef ETL_CUDNN_MAX_WORKSPACE
constexpr std::size_t cudnn_max_workspace = ETL_CUDNN_MAX_WORKSPACE;
#else
constexpr std::size_t cudnn_max_workspace = 2UL * 1024 * 1024 * 1024; ///< The max workspace we allocate for CUDNN (2GiB by default)
#endif

/*!
 * \brief Vectorization mode
 */
enum class vector_mode_t {
    NONE,  ///< No vectorization is available
    SSE3,  ///< SSE3 is the max vectorization available
    AVX,   ///< AVX is the max vectorization available
    AVX512 ///< AVX-512F is the max vectorization available
};

#ifdef __AVX512F__
constexpr vector_mode_t vector_mode = vector_mode_t::AVX512;
#elif defined(__AVX__)
constexpr vector_mode_t vector_mode        = vector_mode_t::AVX;
#elif defined(__SSE3__)
constexpr vector_mode_t vector_mode = vector_mode_t::SSE3;
#else
constexpr vector_mode_t vector_mode = vector_mode_t::NONE; ///< The vector mode in use
#endif

#ifdef __AVX512F__
constexpr bool avx512_enabled = true;
#else
constexpr bool avx512_enabled              = false; ///< Indicates if AVX512F is available
#endif

#ifdef __AVX__
constexpr bool avx_enabled = true;
#else
constexpr bool avx_enabled                 = false; ///< Indicates if AVX is available
#endif

#ifdef __SSE3__
constexpr bool sse3_enabled = true;
#else
constexpr bool sse3_enabled                = false; ///< Indicates if sse3 is available
#endif

#ifdef __INTEL_COMPILER
constexpr bool intel_compiler = true;
#else
constexpr bool intel_compiler              = false; ///< Indicates if the project is compiled with intel
#endif

} //end of namespace etl
<commit_msg>New variable<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

namespace etl {

#ifdef ETL_VECTORIZE_FULL

//VECTORIZE_FULL enables VECTORIZE_EXPR
#ifndef ETL_VECTORIZE_EXPR
#define ETL_VECTORIZE_EXPR
#endif

//VECTORIZE_FULL enables VECTORIZE_IMPL
#ifndef ETL_VECTORIZE_IMPL
#define ETL_VECTORIZE_IMPL
#endif

#endif //ETL_VECTORIZE_FULL

//Flag to enable auto-vectorization of expressions
#ifdef ETL_VECTORIZE_EXPR
constexpr bool vectorize_expr = true;
#else
constexpr bool vectorize_expr   = false;                               ///< Boolean flag indicating if the expression are automatically vectorized
#endif

//Flag to enable vectorized implementation of algorithms
#ifdef ETL_VECTORIZE_IMPL
constexpr bool vectorize_impl = true;
#else
constexpr bool vectorize_impl   = false;                               ///< Boolean flag indicating if the implementations are automatically vectorized
#endif

//Flag to allow conv_valid_multi to use FFT
#ifdef ETL_CONV_VALID_FFT
constexpr bool conv_valid_fft = true;
#else
constexpr bool conv_valid_fft   = false;                               ///< Boolean flag indicating if temporaries are created
#endif

//Select the number of threads
#ifdef ETL_PARALLEL_THREADS
constexpr std::size_t threads = ETL_PARALLEL_THREADS;
#else
const std::size_t threads             = std::thread::hardware_concurrency(); ///< Number of threads
#endif

//Indicate that ETL should run in parallel
#ifdef ETL_PARALLEL
constexpr bool is_parallel = true;
#else
constexpr bool is_parallel = false;                               ///< Boolean flag indicating if expressions and implementations are parallelized (alpha)
#endif

#ifdef ETL_MKL_MODE

//MKL mode enables BLAS mode
#ifndef ETL_BLAS_MODE
#define ETL_BLAS_MODE
#endif

constexpr bool is_mkl_enabled = true;
constexpr bool has_fast_fft   = true;

#else

constexpr bool is_mkl_enabled              = false; ///< Boolean flag indicating if MKL is enabled
constexpr bool has_fast_fft                = false; ///< Boolean flag indicating if a fast FFT implementation is available

#endif

//Flag to enable the use of CBLAS library
#ifdef ETL_BLAS_MODE
constexpr bool is_cblas_enabled = true;
#else
constexpr bool is_cblas_enabled            = false; ///< Boolean flag indicating if CBLAS is available
#endif

//Flag to indicate that blas is multithreaded
#ifdef ETL_BLAS_THREADS
constexpr bool is_blas_parallel = true;
#else
constexpr bool is_blas_parallel            = false; ///< Boolean flag indicating if CBLAS is running parallel
#endif

#ifdef ETL_CUDA
static_assert(false, "ETL_CUDA should never be set directly");
#endif

#ifdef ETL_CUBLAS_MODE
constexpr bool is_cublas_enabled = true;
#define ETL_CUDA
#else
constexpr bool is_cublas_enabled           = false; ///< Boolean flag indicating if CUBLAS is available
#endif

#ifdef ETL_CUFFT_MODE
#define ETL_CUDA
constexpr bool is_cufft_enabled = true;
#else
constexpr bool is_cufft_enabled            = false; ///< Boolean flag indicating if CUFFT is available
#endif

#ifdef ETL_CUDNN_MODE
constexpr bool is_cudnn_enabled = true;
#define ETL_CUDA
#else
constexpr bool is_cudnn_enabled            = false; ///< Boolean flag indicating if CUDNN is available
#endif

//Flag to perform elementwise multiplication by default (operator*)
//instead of matrix(vector) multiplication
#ifdef ETL_ELEMENT_WISE_MULTIPLICATION
constexpr bool is_element_wise_mul_default = true;
#else
constexpr bool is_element_wise_mul_default = false; ///< Boolean flag indicating if multiplication of two expression means matrix multiplication (false) or element-wise multiplication (true)
#endif

//Flag to prevent division to be done by multiplication
#ifdef ETL_STRICT_DIV
constexpr bool is_div_strict = true;
#else
constexpr bool is_div_strict               = false; ///< Boolean flag indicating if division can be done by multiplication (false) or not (true)
#endif

// Flag to disable streaming operations
#ifdef ETL_NO_STREAMING
constexpr bool streaming = false;
#else
constexpr bool streaming = true;
#endif

// Flag to disable padding operations
#ifdef ETL_NO_PADDING
constexpr bool padding = false;
#else
constexpr bool padding = true;
#endif

// Flag to disable padding implementations
#ifdef ETL_NO_PADDING_IMPL
constexpr bool padding_impl = false;
#else
constexpr bool padding_impl = true;
#endif

// Flag to set the cache size
#ifdef ETL_CACHE_SIZE
constexpr size_t cache_size = ETL_CACHE_SIZE;
#else
constexpr size_t cache_size = 3 * 1024 * 1024;
#endif

//Flag to disable unrolling of non-vectorized loops
#ifdef ETL_NO_UNROLL_NON_VECT
constexpr bool unroll_normal_loops = false;
#else
constexpr bool unroll_normal_loops         = true;  ///< Boolean flag indicating if normal loops are getting unrolled
#endif

//Flag to configure the maximum workspace size for ETL
#ifdef ETL_MAX_WORKSPACE
constexpr std::size_t max_workspace = ETL_MAX_WORKSPACE;
#else
constexpr std::size_t max_workspace = 2UL * 1024 * 1024 * 1024; ///< The max workspace we allocate for ETL (2GiB by default)
#endif

//Flag to configure the maximum workspace size for CUDA
#ifdef ETL_CUDNN_MAX_WORKSPACE
constexpr std::size_t cudnn_max_workspace = ETL_CUDNN_MAX_WORKSPACE;
#else
constexpr std::size_t cudnn_max_workspace = 2UL * 1024 * 1024 * 1024; ///< The max workspace we allocate for CUDNN (2GiB by default)
#endif

/*!
 * \brief Vectorization mode
 */
enum class vector_mode_t {
    NONE,  ///< No vectorization is available
    SSE3,  ///< SSE3 is the max vectorization available
    AVX,   ///< AVX is the max vectorization available
    AVX512 ///< AVX-512F is the max vectorization available
};

#ifdef __AVX512F__
constexpr vector_mode_t vector_mode = vector_mode_t::AVX512;
#elif defined(__AVX__)
constexpr vector_mode_t vector_mode        = vector_mode_t::AVX;
#elif defined(__SSE3__)
constexpr vector_mode_t vector_mode = vector_mode_t::SSE3;
#else
constexpr vector_mode_t vector_mode = vector_mode_t::NONE; ///< The vector mode in use
#endif

#ifdef __AVX512F__
constexpr bool avx512_enabled = true;
#else
constexpr bool avx512_enabled              = false; ///< Indicates if AVX512F is available
#endif

#ifdef __AVX__
constexpr bool avx_enabled = true;
#else
constexpr bool avx_enabled                 = false; ///< Indicates if AVX is available
#endif

#ifdef __SSE3__
constexpr bool sse3_enabled = true;
#else
constexpr bool sse3_enabled                = false; ///< Indicates if sse3 is available
#endif

constexpr bool vec_enabled = avx512_enabled || avx_enabled || sse3_enabled; ///< Indicates if any vectorization is available

#ifdef __INTEL_COMPILER
constexpr bool intel_compiler = true;
#else
constexpr bool intel_compiler              = false; ///< Indicates if the project is compiled with intel
#endif

} //end of namespace etl
<|endoftext|>


<commit_before>#include <iostream>
#include <proton/base.hpp>
#include <proton/ref.hpp>
#include <proton/detail/unit_test.hpp>
#include "pool_types.hpp"

using namespace std;
using namespace proton;

struct obj_test{
    string a;
    int b;
    obj_test()
    {}

    obj_test(const string& a1, int b1):a(a1),b(b1)
    {}

    virtual void output(ostream& s)const
    {
        s << a << ","<< b << std::endl;
    }
};

typedef ref_<obj_test> test;

struct obj_derived:obj_test{

    string c;

    obj_derived():obj_test()
    {}

    obj_derived(const string& a1, int b1, const string& c1):obj_test(a1,b1), c(c1)
    {}

    void output(ostream& s)const
    {
        s << a << ","<< b << "," << c << std::endl;
    }

    PROTON_COPY_DECL(obj_derived);
};

typedef ref_<obj_derived> derived;

typedef ref_<obj_derived> der;

struct obj_de{
    string a;
    int b;
    string c;
    PROTON_COPY_DECL_NV(obj_de);
};
typedef ref_<obj_de> de;

int ref_ut()
{
    std::cout << "-> ref_ut" << std::endl;

    test t("c",10);
    std::cout << t;

    derived d("a",1,"daf"), e(copy(d));
    std::cout << d << e;

    bool k1=false;
#if 0
    try{
        e=t;
    }
    catch(err&){
        k1=true;
    }
    PROTON_THROW_IF(!k1, "no cast err detected!");
#endif

    der f(alloc);
    f->a="abc"; f->b=2; f->c="def";
    std::cout << f->a << ", " << f->b << ", " << f->c << std::endl;

    de g(alloc);
    g->a="dkf"; g->b=3; g->c="dfe";
    de j(g), k(copy(g));
    std::cout << g->a << ", " << g->b << ", " << g->c << std::endl;
    std::cout << j->a << ", " << j->b << ", " << j->c << std::endl;
    std::cout << k->a << ", " << k->b << ", " << k->c << std::endl;

    return 0;
}

volatile int refc_count=0;

struct obj_refc_test{
    int a;
    obj_refc_test(int x):a(x)
    {
        refc_count++;
    }

    obj_refc_test():a(0)
    {
        refc_count++;
    }

    ~obj_refc_test()
    {
        refc_count--;
    }
};

typedef ref_<obj_refc_test> ref_test;

int ref_test_ut()
{
    std::cout << "-> ref_test_ut" << std::endl;
    {
        tvector(ref_test) as;
        for(int i=0; i<10;i++){
            ref_test a(2);
            as.push_back(a);
        }
        //std::cout << refc_count << std::endl;
        PROTON_THROW_IF(refc_count!=10, "bad refc_count");
        ref_test b;
        b=as[0];
        as.clear();
        //std::cout << refc_count << std::endl;
        PROTON_THROW_IF(refc_count!=1, "bad refc_count");
        reset(b);
        PROTON_THROW_IF(refc_count!=0, "bad refc_count");
    }
    //std::cout << "refc_count:"<<refc_count << std::endl;
    return 0;
}

int reset_ut()
{
    cout << "-> reset_ut" << endl;
    test t(alloc);
    PROTON_THROW_IF(is_null(t), "err");
    PROTON_THROW_IF(ref_count(t)!=1, "err");
    reset(t);
    PROTON_THROW_IF(is_valid(t), "err");
    PROTON_THROW_IF(ref_count(t)!=0, "err");
    PROTON_THROW_IF(&t.__o()!=NULL, "err");

    return 0;
}

int cast_ut()
{
    cout << "-> cast_ut" << endl;
    test a, c;
    derived b(alloc);
    a=b;
    c=cast<test>(b);
    return 0;
}

int main()
{
    proton::debug_level=1;
    proton::wait_on_err=0;
    std::vector<proton::detail::unittest_t> ut=
        {ref_ut, ref_test_ut, reset_ut, cast_ut};
    proton::detail::unittest_run(ut);
    return 0;
}

<commit_msg>add cast ut<commit_after>#include <iostream>
#include <proton/base.hpp>
#include <proton/ref.hpp>
#include <proton/detail/unit_test.hpp>
#include "pool_types.hpp"

using namespace std;
using namespace proton;

struct obj_test{
    string a;
    int b;
    obj_test()
    {}

    obj_test(const string& a1, int b1):a(a1),b(b1)
    {}

    PROTON_COPY_DECL(obj_test);

    virtual void output(ostream& s)const
    {
        s << a << ","<< b << std::endl;
    }
};

typedef ref_<obj_test> test;

struct obj_derived:obj_test{

    string c;

    obj_derived():obj_test()
    {}

    obj_derived(const string& a1, int b1, const string& c1):obj_test(a1,b1), c(c1)
    {}

    void output(ostream& s)const
    {
        s << a << ","<< b << "," << c << std::endl;
    }

    PROTON_COPY_DECL(obj_derived);
};

typedef ref_<obj_derived> derived;

typedef ref_<obj_derived> der;

struct obj_de{
    string a;
    int b;
    string c;
    PROTON_COPY_DECL_NV(obj_de);
};
typedef ref_<obj_de> de;

int ref_ut()
{
    std::cout << "-> ref_ut" << std::endl;

    test t("c",10);
    std::cout << t;

    derived d("a",1,"daf"), e(copy(d));
    std::cout << d << e;

    bool k1=false;
    try{
        e=cast<derived>(t);
    }
    catch(std::bad_cast&){
        k1=true;
    }
    PROTON_THROW_IF(!k1, "no cast err detected!");

    der f(alloc);
    f->a="abc"; f->b=2; f->c="def";
    std::cout << f->a << ", " << f->b << ", " << f->c << std::endl;

    de g(alloc);
    g->a="dkf"; g->b=3; g->c="dfe";
    de j(g), k(copy(g));
    std::cout << g->a << ", " << g->b << ", " << g->c << std::endl;
    std::cout << j->a << ", " << j->b << ", " << j->c << std::endl;
    std::cout << k->a << ", " << k->b << ", " << k->c << std::endl;

    return 0;
}

volatile int refc_count=0;

struct obj_refc_test{
    int a;
    obj_refc_test(int x):a(x)
    {
        refc_count++;
    }

    obj_refc_test():a(0)
    {
        refc_count++;
    }

    ~obj_refc_test()
    {
        refc_count--;
    }
};

typedef ref_<obj_refc_test> ref_test;

int ref_test_ut()
{
    std::cout << "-> ref_test_ut" << std::endl;
    {
        tvector(ref_test) as;
        for(int i=0; i<10;i++){
            ref_test a(2);
            as.push_back(a);
        }
        //std::cout << refc_count << std::endl;
        PROTON_THROW_IF(refc_count!=10, "bad refc_count");
        ref_test b;
        b=as[0];
        as.clear();
        //std::cout << refc_count << std::endl;
        PROTON_THROW_IF(refc_count!=1, "bad refc_count");
        reset(b);
        PROTON_THROW_IF(refc_count!=0, "bad refc_count");
    }
    //std::cout << "refc_count:"<<refc_count << std::endl;
    return 0;
}

int reset_ut()
{
    cout << "-> reset_ut" << endl;
    test t(alloc);
    PROTON_THROW_IF(is_null(t), "err");
    PROTON_THROW_IF(ref_count(t)!=1, "err");
    reset(t);
    PROTON_THROW_IF(is_valid(t), "err");
    PROTON_THROW_IF(ref_count(t)!=0, "err");
    PROTON_THROW_IF(&t.__o()!=NULL, "err");

    return 0;
}

int cast_ut()
{
    cout << "-> cast_ut" << endl;
    test a, c;
    derived b(alloc);
    a=b;
    c=cast<test>(b);
    return 0;
}

int main()
{
    proton::debug_level=1;
    proton::wait_on_err=0;
    std::vector<proton::detail::unittest_t> ut=
        {ref_ut, ref_test_ut, reset_ut, cast_ut};
    proton::detail::unittest_run(ut);
    return 0;
}

<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(VCPPDEFINITIONS_HEADER_GUARD_1357924680)
#define VCPPDEFINITIONS_HEADER_GUARD_1357924680

#pragma warning(disable: 4127 4251 4511 4512 4514 4702 4710 4711 4786 4097; error: 4150 4172 4238 4239 4715)

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT     __declspec(dllexport)
#define XALAN_PLATFORM_IMPORT     __declspec(dllimport)
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT

#define XALAN_NO_COVARIANT_RETURN_TYPE
#define XALAN_LSTRSUPPORT
#define XALAN_FULL_WCHAR_SUPPORT
#define XALAN_RTTI_AVAILABLE
#define XALAN_CANNOT_MUTATE_ANONYMOUS_OBJECT
#define XALAN_LITLE_ENDIAN

#endif	// VCPPDEFINITIONS_HEADER_GUARD_1357924680
<commit_msg>Enable CR/LF for platforms that use it.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(VCPPDEFINITIONS_HEADER_GUARD_1357924680)
#define VCPPDEFINITIONS_HEADER_GUARD_1357924680

#pragma warning(disable: 4127 4251 4511 4512 4514 4702 4710 4711 4786 4097; error: 4150 4172 4238 4239 4715)

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT     __declspec(dllexport)
#define XALAN_PLATFORM_IMPORT     __declspec(dllimport)
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT

#define XALAN_NO_COVARIANT_RETURN_TYPE
#define XALAN_LSTRSUPPORT
#define XALAN_FULL_WCHAR_SUPPORT
#define XALAN_RTTI_AVAILABLE
#define XALAN_LITLE_ENDIAN
#define XALAN_NEWLINE_IS_CRLF

#endif	// VCPPDEFINITIONS_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before><commit_msg>FIXED: buy15<commit_after><|endoftext|>


<commit_before><commit_msg>Use American spelling<commit_after><|endoftext|>


<commit_before><commit_msg>fix, memory leak<commit_after><|endoftext|>


<commit_before>#include <stdarg.h>
#include <assert.h>
#include <errno.h>
#include <db_cxx.h>

DbEnv::DbEnv (u_int32_t flags)
    : do_no_exceptions((flags&DB_CXX_NO_EXCEPTIONS)!=0),
      errcall(NULL)
{
    int ret = db_env_create(&the_env, flags & ~DB_CXX_NO_EXCEPTIONS);
    assert(ret==0); // should do an error.
    the_env->api1_internal = this;
}

DbEnv::DbEnv(DB_ENV *env, u_int32_t flags)
    : do_no_exceptions((flags&DB_CXX_NO_EXCEPTIONS)!=0), _error_stream(0)
{
    the_env = env;
    if (env == 0) {
	DB_ENV *new_env;
	int ret = db_env_create(&new_env, flags & ~DB_CXX_NO_EXCEPTIONS);
	assert(ret==0); // should do an error.
	the_env = new_env;
    }
    the_env->api1_internal = this;
}

// If still open, close it.  In most cases, the caller should call close explicitly so that they can catch the exceptions.
DbEnv::~DbEnv(void)
{
    if (the_env!=NULL) {
	(void)the_env->close(the_env, 0);
	the_env = 0;
    }
}

int DbEnv::close(u_int32_t flags) {
    int ret = EINVAL;
    if (the_env)
        ret = the_env->close(the_env, flags);
    the_env = 0; /* get rid of the env ref, so we don't touch it (even if we failed, or when the destructor is called) */
    return maybe_throw_error(ret);
}

int DbEnv::open(const char *home, u_int32_t flags, int mode) {
    int ret = the_env->open(the_env, home, flags, mode);
    return maybe_throw_error(ret);
}

int DbEnv::set_cachesize(u_int32_t gbytes, u_int32_t bytes, int ncache) {
    int ret = the_env->set_cachesize(the_env, gbytes, bytes, ncache);
    return maybe_throw_error(ret);
}

int DbEnv::set_flags(u_int32_t flags, int onoff) {
    int ret = the_env->set_flags(the_env, flags, onoff);
    return maybe_throw_error(ret);
}

#if DB_VERSION_MAJOR<4 || (DB_VERSION_MAJOR==4 && DB_VERSION_MINOR<=4)
int DbEnv::set_lk_max(u_int32_t flags) {
    int ret = the_env->set_lk_max(the_env, flags);
    return maybe_throw_error(ret);
}
#endif

int DbEnv::txn_begin(DbTxn *parenttxn, DbTxn **txnp, u_int32_t flags) {
    DB_TXN *txn;
    int ret = the_env->txn_begin(the_env, parenttxn->get_DB_TXN(), &txn, flags);
    if (ret==0) {
	*txnp = new DbTxn(txn);
    }
    return maybe_throw_error(ret);
}

int DbEnv::set_data_dir(const char *dir) {
    int ret = the_env->set_data_dir(the_env, dir);
    return maybe_throw_error(ret);
}

void DbEnv::set_errpfx(const char *errpfx) {
    the_env->set_errpfx(the_env, errpfx);
}

int DbEnv::maybe_throw_error(int err, DbEnv *env, int no_exceptions) throw (DbException) {
    if (err==0 || err==DB_NOTFOUND || err==DB_KEYEXIST || err==DB_KEYEMPTY) return err;
    if (no_exceptions) return err;
    if (err==DB_LOCK_DEADLOCK) {
	DbDeadlockException e(env);
	throw e;
    } else {
	DbException e(err);
	e.set_env(env);
	throw e;
    }
}

int DbEnv::maybe_throw_error(int err) throw (DbException) {
    return maybe_throw_error(err, this, do_no_exceptions);
}

extern "C" {
    void toku_do_error_all_cases(const DB_ENV * env, int error, int, int, const char *fmt, va_list ap);
};

void DbEnv::err(int error, const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    toku_do_error_all_cases(the_env, error, 1, 1, fmt, ap);
    va_end(ap);
}

void DbEnv::set_errfile(FILE *errfile) {
    the_env->set_errfile(the_env, errfile);
}

int DbEnv::get_flags(u_int32_t *flagsp) {
    int ret = the_env->get_flags(the_env, flagsp);
    return maybe_throw_error(ret);
}

extern "C" void toku_db_env_errcall_c(const DB_ENV *dbenv_c, const char *errpfx, const char *msg) {
    DbEnv *dbenv = (DbEnv *) dbenv_c->api1_internal;
    dbenv->errcall(dbenv, errpfx, msg);
}

void DbEnv::set_errcall(void (*db_errcall_fcn)(const DbEnv *, const char *, const char *)) {
    errcall = db_errcall_fcn;
    the_env->set_errcall(the_env, toku_db_env_errcall_c);
}

extern "C" void toku_db_env_error_stream_c(const DB_ENV *dbenv_c, const char *errpfx, const char *msg) {
    DbEnv *dbenv = (DbEnv *) dbenv_c->api1_internal;
    if (dbenv->_error_stream) {
        if (errpfx) *(dbenv->_error_stream) << errpfx;
        if (msg) *(dbenv->_error_stream) << ":" << msg << "\n";
    }
}

void DbEnv::set_error_stream(std::ostream *new_error_stream) {
    _error_stream = new_error_stream;
    the_env->set_errcall(the_env, toku_db_env_error_stream_c);
}

// locking not yet implemented

int DbEnv::set_lk_max_locks(u_int32_t max_locks) {
    int ret = the_env->set_lk_max_locks(the_env, max_locks);
    return maybe_throw_error(ret);
}

int DbEnv::set_lk_max_lockers(u_int32_t max_lockers) {
    return 0;
}

int DbEnv::set_lk_max_objects(u_int32_t max_objects) {
    return 0;
}
<commit_msg>Addresses #378 Propagate refactored error handling to C++ API.<commit_after>#include <stdarg.h>
#include <assert.h>
#include <errno.h>
#include "../newbrt/brttypes.h"
#include <db_cxx.h>

DbEnv::DbEnv (u_int32_t flags)
    : do_no_exceptions((flags&DB_CXX_NO_EXCEPTIONS)!=0),
      errcall(NULL)
{
    int ret = db_env_create(&the_env, flags & ~DB_CXX_NO_EXCEPTIONS);
    assert(ret==0); // should do an error.
    the_env->api1_internal = this;
}

DbEnv::DbEnv(DB_ENV *env, u_int32_t flags)
    : do_no_exceptions((flags&DB_CXX_NO_EXCEPTIONS)!=0), _error_stream(0)
{
    the_env = env;
    if (env == 0) {
	DB_ENV *new_env;
	int ret = db_env_create(&new_env, flags & ~DB_CXX_NO_EXCEPTIONS);
	assert(ret==0); // should do an error.
	the_env = new_env;
    }
    the_env->api1_internal = this;
}

// If still open, close it.  In most cases, the caller should call close explicitly so that they can catch the exceptions.
DbEnv::~DbEnv(void)
{
    if (the_env!=NULL) {
	(void)the_env->close(the_env, 0);
	the_env = 0;
    }
}

int DbEnv::close(u_int32_t flags) {
    int ret = EINVAL;
    if (the_env)
        ret = the_env->close(the_env, flags);
    the_env = 0; /* get rid of the env ref, so we don't touch it (even if we failed, or when the destructor is called) */
    return maybe_throw_error(ret);
}

int DbEnv::open(const char *home, u_int32_t flags, int mode) {
    int ret = the_env->open(the_env, home, flags, mode);
    return maybe_throw_error(ret);
}

int DbEnv::set_cachesize(u_int32_t gbytes, u_int32_t bytes, int ncache) {
    int ret = the_env->set_cachesize(the_env, gbytes, bytes, ncache);
    return maybe_throw_error(ret);
}

int DbEnv::set_flags(u_int32_t flags, int onoff) {
    int ret = the_env->set_flags(the_env, flags, onoff);
    return maybe_throw_error(ret);
}

#if DB_VERSION_MAJOR<4 || (DB_VERSION_MAJOR==4 && DB_VERSION_MINOR<=4)
int DbEnv::set_lk_max(u_int32_t flags) {
    int ret = the_env->set_lk_max(the_env, flags);
    return maybe_throw_error(ret);
}
#endif

int DbEnv::txn_begin(DbTxn *parenttxn, DbTxn **txnp, u_int32_t flags) {
    DB_TXN *txn;
    int ret = the_env->txn_begin(the_env, parenttxn->get_DB_TXN(), &txn, flags);
    if (ret==0) {
	*txnp = new DbTxn(txn);
    }
    return maybe_throw_error(ret);
}

int DbEnv::set_data_dir(const char *dir) {
    int ret = the_env->set_data_dir(the_env, dir);
    return maybe_throw_error(ret);
}

void DbEnv::set_errpfx(const char *errpfx) {
    the_env->set_errpfx(the_env, errpfx);
}

int DbEnv::maybe_throw_error(int err, DbEnv *env, int no_exceptions) throw (DbException) {
    if (err==0 || err==DB_NOTFOUND || err==DB_KEYEXIST || err==DB_KEYEMPTY) return err;
    if (no_exceptions) return err;
    if (err==DB_LOCK_DEADLOCK) {
	DbDeadlockException e(env);
	throw e;
    } else {
	DbException e(err);
	e.set_env(env);
	throw e;
    }
}

int DbEnv::maybe_throw_error(int err) throw (DbException) {
    return maybe_throw_error(err, this, do_no_exceptions);
}

extern "C" {
void toku_ydb_error_all_cases(const DB_ENV * env,
                              int error,
                              BOOL include_stderrstring,
                              BOOL use_stderr_if_nothing_else,
                              const char *fmt, va_list ap);
};

void DbEnv::err(int error, const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    toku_ydb_error_all_cases(the_env, error, TRUE, TRUE, fmt, ap);
    va_end(ap);
}

void DbEnv::set_errfile(FILE *errfile) {
    the_env->set_errfile(the_env, errfile);
}

int DbEnv::get_flags(u_int32_t *flagsp) {
    int ret = the_env->get_flags(the_env, flagsp);
    return maybe_throw_error(ret);
}

extern "C" void toku_db_env_errcall_c(const DB_ENV *dbenv_c, const char *errpfx, const char *msg) {
    DbEnv *dbenv = (DbEnv *) dbenv_c->api1_internal;
    dbenv->errcall(dbenv, errpfx, msg);
}

void DbEnv::set_errcall(void (*db_errcall_fcn)(const DbEnv *, const char *, const char *)) {
    errcall = db_errcall_fcn;
    the_env->set_errcall(the_env, toku_db_env_errcall_c);
}

extern "C" void toku_db_env_error_stream_c(const DB_ENV *dbenv_c, const char *errpfx, const char *msg) {
    DbEnv *dbenv = (DbEnv *) dbenv_c->api1_internal;
    if (dbenv->_error_stream) {
        if (errpfx) *(dbenv->_error_stream) << errpfx;
        if (msg) *(dbenv->_error_stream) << ":" << msg << "\n";
    }
}

void DbEnv::set_error_stream(std::ostream *new_error_stream) {
    _error_stream = new_error_stream;
    the_env->set_errcall(the_env, toku_db_env_error_stream_c);
}

// locking not yet implemented

int DbEnv::set_lk_max_locks(u_int32_t max_locks) {
    int ret = the_env->set_lk_max_locks(the_env, max_locks);
    return maybe_throw_error(ret);
}

int DbEnv::set_lk_max_lockers(u_int32_t max_lockers) {
    return 0;
}

int DbEnv::set_lk_max_objects(u_int32_t max_objects) {
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>added PowerRequestSystemRequired to prevent laptop from sleeping<commit_after><|endoftext|>


<commit_before><commit_msg>X86: Compute PCI config addresses correctly.<commit_after><|endoftext|>


<commit_before><commit_msg>base: Tag API variables in version.cc<commit_after><|endoftext|>


<commit_before><commit_msg>#60 : Implementation : logging for command execution<commit_after><|endoftext|>


<commit_before>#include <string.h>
#include <vector>
#include <stdio.h>
#include <rapidxml\rapidxml.hpp>
#include <Windows.h>
extern "C"
{
#include "Log4JParserC.h"
}

const char LogFragmentStart_[] = "<log4j:event";

const char TagEvent_[] = "log4j:event";
const size_t TagEventSize_ = sizeof TagEvent_ / sizeof TagEvent_[0] - 1U;

const char AttrLevel_[] = "level";
const size_t AttrLevelSize_ = sizeof AttrLevel_ / sizeof AttrLevel_[0] - 1U;

const char AttrLogger_[] = "logger";
const size_t AttrLoggerSize_ = sizeof AttrLogger_ / sizeof AttrLogger_[0] - 1U;

const char AttrThread_[] = "thread";
const size_t AttrThreadSize_ = sizeof AttrThread_ / sizeof AttrThread_[0] - 1U;

const char AttrTimestamp_[] = "timestamp";
const size_t AttrTimestampSize_ = sizeof AttrTimestamp_ / sizeof AttrTimestamp_[0] - 1U;

const char TagMessage_[] = "log4j:message";
const size_t TagMessageSize_ = sizeof TagMessage_ / sizeof TagMessage_[0] - 1U;

const char TagThrowable_[] = "log4j:throwable";
const size_t TagThrowableSize_ = sizeof TagThrowable_ / sizeof TagThrowable_[0] - 1U;

const char TagProperties_[] = "log4j:properties";
const size_t TagPropertiesSize_ = sizeof TagProperties_ / sizeof TagProperties_[0] - 1U;

const char TagData_[] = "log4j:data";
const size_t TagDataSize_ = sizeof TagData_ / sizeof TagData_[0] - 1U;

const char AttrDataName_[] = "name";
const size_t AttrDataNameSize_ = sizeof AttrDataName_ / sizeof AttrDataName_[0] - 1U;

const char AttrDataValue_[] = "value";
const size_t AttrDataValueSize_ = sizeof AttrDataValue_ / sizeof AttrDataValue_[0] - 1U;

static void GetAttributeValue_ (const rapidxml::xml_attribute<char> *source, const char **value, size_t *size);
static void GetNodeValue_ (rapidxml::xml_node<char> *source, const char **value, size_t *size);
static int64_t ParseTimestamp_ (const char *value, const size_t valueSize);

LOG4JPARSERC_API void __cdecl Log4JEventLevel (const Log4JEvent log4JEvent, const char **value, size_t *size)
{
    auto node = (const rapidxml::xml_node<char> *) log4JEvent;
    auto xml = node->first_attribute (AttrLevel_, AttrLevelSize_);
    GetAttributeValue_ (xml, value, size);
}

LOG4JPARSERC_API void __cdecl Log4JEventLogger (const Log4JEvent log4JEvent, const char **value, size_t *size)
{
    auto node = (const rapidxml::xml_node<char> *) log4JEvent;
    auto xml = node->first_attribute (AttrLogger_, AttrLoggerSize_);
    GetAttributeValue_ (xml, value, size);
}

LOG4JPARSERC_API void __cdecl Log4JEventThread (const Log4JEvent log4JEvent, const char **value, size_t *size)
{
    auto node = (const rapidxml::xml_node<char> *) log4JEvent;
    auto xml = node->first_attribute (AttrThread_, AttrThreadSize_);
    GetAttributeValue_ (xml, value, size);
}

LOG4JPARSERC_API int64_t __cdecl Log4JEventTimestamp (const Log4JEvent log4JEvent)
{
    auto node = (const rapidxml::xml_node<char> *) log4JEvent;
    auto xml = node->first_attribute (AttrTimestamp_, AttrTimestampSize_);
    auto result = ParseTimestamp_ (xml->value (), xml->value_size ());

    return result;
}

LOG4JPARSERC_API void __cdecl Log4JEventMessage (const Log4JEvent log4JEvent, const char **value, size_t *size)
{
    auto node = (rapidxml::xml_node<char> *) log4JEvent;
    auto xml = node->first_node (TagMessage_, TagMessageSize_);
    GetNodeValue_ (xml, value, size);
}

LOG4JPARSERC_API void __cdecl Log4JEventThrowable (const Log4JEvent log4JEvent, const char **value, size_t *size)
{
    auto node = (rapidxml::xml_node<char> *) log4JEvent;
    auto xml = node->first_node (TagThrowable_, TagThrowableSize_);
    GetNodeValue_ (xml, value, size);
}

LOG4JPARSERC_API size_t Log4JEventProperties (const Log4JEvent log4JEvent, size_t skip, Log4JEventProperty *properties, size_t propertiesSize)
{
    if (properties == nullptr)
    {
        propertiesSize = 0U;
    }
    size_t actualProperties = 0U;

    auto node = (rapidxml::xml_node<char> *) log4JEvent;
    auto propertiesNode = node->first_node (TagProperties_, TagPropertiesSize_);
    if (propertiesNode != nullptr)
    {
        auto dataNode = propertiesNode->first_node (TagData_, TagDataSize_);
        while (dataNode != nullptr)
        {
            ++actualProperties;

            if (skip != 0U)
            {
                --skip;
            }
            else if (propertiesSize != 0U)
            {
                auto name = dataNode->first_attribute (AttrDataName_, AttrDataNameSize_);
                GetAttributeValue_ (name, &properties->name, &properties->nameSize);

                auto value = dataNode->first_attribute (AttrDataValue_, AttrDataValueSize_);
                GetAttributeValue_ (value, &properties->value, &properties->valueSize);

                ++properties;
                --propertiesSize;
            }

            dataNode = dataNode->next_sibling (TagData_, TagDataSize_);
        }
    }

    return actualProperties;
}

void GetAttributeValue_ (const rapidxml::xml_attribute<char> *source, const char **value, size_t *size)
{
    if (source)
    {
        *value = source->value ();
        *size = source->value_size ();
    }
    else
    {
        *value = nullptr;
        *size = 0U;
    }
}

void GetNodeValue_ (rapidxml::xml_node<char> *source, const char **value, size_t *size)
{
    if (source)
    {
        auto firstChild = source->first_node ();
        if (!firstChild)
        {
            *value = source->value ();
            *size = source->value_size ();
        }
        else if (firstChild == source->last_node ())
        {
            *value = firstChild->value ();
            *size = firstChild->value_size ();
        }
        else
        {
            auto bufferLength = 0U;
            for (auto node = firstChild; node; node = node->next_sibling ())
            {
                bufferLength += node->value_size ();
            }

            auto bufferSize = bufferLength + 1;
            auto buffer = source->document ()->allocate_string (nullptr, bufferSize);
            buffer[bufferSize - 1] = '\0';

            auto concatHead = buffer;
            auto bufferFreeSize = bufferSize;
            for (auto node = firstChild; node; node = node->next_sibling ())
            {
                auto nodeValue = node->value ();
                auto nodeValueSize = node->value_size ();

                strncpy_s (concatHead, bufferFreeSize, nodeValue, nodeValueSize);
                auto copied = min (bufferFreeSize, nodeValueSize);

                bufferFreeSize -= copied;
                concatHead += copied;
            }

            source->remove_all_nodes ();
            source->value (buffer, bufferLength);

            *value = buffer;
            *size = bufferLength;
        }
    }
    else
    {
        *value = nullptr;
        *size = 0U;
    }
}

int64_t ParseTimestamp_ (const char *value, const size_t valueSize)
{
    int64_t result = 0L;

    for (size_t i = 0; i < valueSize; ++i)
    {
        int64_t digit = value[i] - '0';
        result = result * 10L + digit;
    }

    return result;
}

struct Log4JEventSource_
{
    std::vector<const rapidxml::xml_document<char> *> *Docs;
    char *OwnXmlString;
};

static Log4JStatus Log4JEventSourceInitXmlStringImpl (Log4JEventSource **self, char *xmlString, bool ownString)
{
    *self = nullptr;
    auto ownedStringPtr = ownString ? xmlString : nullptr;

    auto status = Log4JStatus::E_SUCCESS;

    auto nextPart = xmlString;
    auto docs = new std::vector<const rapidxml::xml_document<char> *> ();
    while (nextPart)
    {
        auto doc = new rapidxml::xml_document<char> ();
        docs->push_back (doc);
        try
        {
            doc->parse<rapidxml::parse_default> (nextPart);
            nextPart = nullptr;
        }
        catch (const rapidxml::parse_error &ex)
        {
            status = Log4JStatus::E_DOCUMENT_ERRORS;
            nextPart = strstr (ex.where<char> (), LogFragmentStart_);
        }
        catch (...)
        {
            for (auto docsIter = docs->begin (); docsIter != docs->end (); ++docsIter)
            {
                delete *docsIter;
            }
            throw;
        }
    }

    Log4JEventSource *result = (Log4JEventSource *) malloc (sizeof *result);
    if (result == nullptr)
    {
        for (auto docsIter = docs->begin (); docsIter != docs->end (); ++docsIter)
        {
            delete *docsIter;
        }
        *self = nullptr;
        return Log4JStatus::E_MEMORY_ERROR;
    }
    *result = { docs, ownedStringPtr };

    *self = result;

    return status;
}

LOG4JPARSERC_API Log4JStatus __cdecl Log4JEventSourceInitXmlString (Log4JEventSource **self, char *xmlString)
{
    return Log4JEventSourceInitXmlStringImpl (self, xmlString, false);
}

LOG4JPARSERC_API void __cdecl Log4JEventSourceDestroy (Log4JEventSource *self)
{
    auto docs = self->Docs;
    for (auto docsIter = docs->begin (); docsIter != docs->end (); ++docsIter)
    {
        delete *docsIter;
    }
    docs->clear ();
    delete docs;

    if (self->OwnXmlString)
    {
        free (self->OwnXmlString);
    }

    *self = { nullptr, nullptr };
    free (self);
}

static size_t IndexOfCurrentDocument (const std::vector<const rapidxml::xml_document<char> *> *docs, const rapidxml::xml_node<char> *node)
{
    auto currentDocument = node->document ();
    auto docsSize = docs->size ();
    for (size_t i = 0; i < docsSize; ++i)
    {
        if (docs->at (i) == currentDocument)
        {
            return i;
        }
    }

    return docsSize;
}

LOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourceFirst (const Log4JEventSource *self)
{
    auto node = self->Docs->front ()->first_node (TagEvent_, TagEventSize_);
    return node;
}

LOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourceNext (const Log4JEventSource *self, const Log4JEvent event)
{
    auto docs = self->Docs;
    auto node = (rapidxml::xml_node<char> *) event;

    auto nextNode = node->next_sibling (TagEvent_, TagEventSize_);
    if (!nextNode)
    {
        auto currentDocumentIndex = IndexOfCurrentDocument (self->Docs, node);
        auto nextDocumentIndex = currentDocumentIndex + 1;
        if (nextDocumentIndex < docs->size ())
        {
            nextNode = docs->at (nextDocumentIndex)->first_node (TagEvent_, TagEventSize_);
        }
    }

    return nextNode;
}

LOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourceLast (const Log4JEventSource *self)
{
    auto node = self->Docs->back ()->last_node (TagEvent_, TagEventSize_);
    return node;
}

LOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourcePrev (const Log4JEventSource *self, const Log4JEvent event)
{
    auto docs = self->Docs;
    auto node = (rapidxml::xml_node<char> *) event;

    auto prevNode = node->previous_sibling (TagEvent_, TagEventSize_);
    if (!prevNode)
    {
        auto currentDocumentIndex = IndexOfCurrentDocument (self->Docs, node);
        auto prevDocumentIndex = currentDocumentIndex - 1;
        // if currentDocumentIndex == 0 then prevDocumentIndex would overflow to SIZE_MAX
        if (prevDocumentIndex < docs->size ())
        {
            prevNode = docs->at (prevDocumentIndex)->first_node (TagEvent_, TagEventSize_);
        }
    }

    return prevNode;
}
<commit_msg>Fixed conversion from unsigned int to size_t when compiling to x64.<commit_after>#include <string.h>
#include <vector>
#include <stdio.h>
#include <rapidxml\rapidxml.hpp>
#include <Windows.h>
extern "C"
{
#include "Log4JParserC.h"
}

const char LogFragmentStart_[] = "<log4j:event";

const char TagEvent_[] = "log4j:event";
const size_t TagEventSize_ = sizeof TagEvent_ / sizeof TagEvent_[0] - 1U;

const char AttrLevel_[] = "level";
const size_t AttrLevelSize_ = sizeof AttrLevel_ / sizeof AttrLevel_[0] - 1U;

const char AttrLogger_[] = "logger";
const size_t AttrLoggerSize_ = sizeof AttrLogger_ / sizeof AttrLogger_[0] - 1U;

const char AttrThread_[] = "thread";
const size_t AttrThreadSize_ = sizeof AttrThread_ / sizeof AttrThread_[0] - 1U;

const char AttrTimestamp_[] = "timestamp";
const size_t AttrTimestampSize_ = sizeof AttrTimestamp_ / sizeof AttrTimestamp_[0] - 1U;

const char TagMessage_[] = "log4j:message";
const size_t TagMessageSize_ = sizeof TagMessage_ / sizeof TagMessage_[0] - 1U;

const char TagThrowable_[] = "log4j:throwable";
const size_t TagThrowableSize_ = sizeof TagThrowable_ / sizeof TagThrowable_[0] - 1U;

const char TagProperties_[] = "log4j:properties";
const size_t TagPropertiesSize_ = sizeof TagProperties_ / sizeof TagProperties_[0] - 1U;

const char TagData_[] = "log4j:data";
const size_t TagDataSize_ = sizeof TagData_ / sizeof TagData_[0] - 1U;

const char AttrDataName_[] = "name";
const size_t AttrDataNameSize_ = sizeof AttrDataName_ / sizeof AttrDataName_[0] - 1U;

const char AttrDataValue_[] = "value";
const size_t AttrDataValueSize_ = sizeof AttrDataValue_ / sizeof AttrDataValue_[0] - 1U;

static void GetAttributeValue_ (const rapidxml::xml_attribute<char> *source, const char **value, size_t *size);
static void GetNodeValue_ (rapidxml::xml_node<char> *source, const char **value, size_t *size);
static int64_t ParseTimestamp_ (const char *value, const size_t valueSize);

LOG4JPARSERC_API void __cdecl Log4JEventLevel (const Log4JEvent log4JEvent, const char **value, size_t *size)
{
    auto node = (const rapidxml::xml_node<char> *) log4JEvent;
    auto xml = node->first_attribute (AttrLevel_, AttrLevelSize_);
    GetAttributeValue_ (xml, value, size);
}

LOG4JPARSERC_API void __cdecl Log4JEventLogger (const Log4JEvent log4JEvent, const char **value, size_t *size)
{
    auto node = (const rapidxml::xml_node<char> *) log4JEvent;
    auto xml = node->first_attribute (AttrLogger_, AttrLoggerSize_);
    GetAttributeValue_ (xml, value, size);
}

LOG4JPARSERC_API void __cdecl Log4JEventThread (const Log4JEvent log4JEvent, const char **value, size_t *size)
{
    auto node = (const rapidxml::xml_node<char> *) log4JEvent;
    auto xml = node->first_attribute (AttrThread_, AttrThreadSize_);
    GetAttributeValue_ (xml, value, size);
}

LOG4JPARSERC_API int64_t __cdecl Log4JEventTimestamp (const Log4JEvent log4JEvent)
{
    auto node = (const rapidxml::xml_node<char> *) log4JEvent;
    auto xml = node->first_attribute (AttrTimestamp_, AttrTimestampSize_);
    auto result = ParseTimestamp_ (xml->value (), xml->value_size ());

    return result;
}

LOG4JPARSERC_API void __cdecl Log4JEventMessage (const Log4JEvent log4JEvent, const char **value, size_t *size)
{
    auto node = (rapidxml::xml_node<char> *) log4JEvent;
    auto xml = node->first_node (TagMessage_, TagMessageSize_);
    GetNodeValue_ (xml, value, size);
}

LOG4JPARSERC_API void __cdecl Log4JEventThrowable (const Log4JEvent log4JEvent, const char **value, size_t *size)
{
    auto node = (rapidxml::xml_node<char> *) log4JEvent;
    auto xml = node->first_node (TagThrowable_, TagThrowableSize_);
    GetNodeValue_ (xml, value, size);
}

LOG4JPARSERC_API size_t Log4JEventProperties (const Log4JEvent log4JEvent, size_t skip, Log4JEventProperty *properties, size_t propertiesSize)
{
    if (properties == nullptr)
    {
        propertiesSize = 0U;
    }
    size_t actualProperties = 0U;

    auto node = (rapidxml::xml_node<char> *) log4JEvent;
    auto propertiesNode = node->first_node (TagProperties_, TagPropertiesSize_);
    if (propertiesNode != nullptr)
    {
        auto dataNode = propertiesNode->first_node (TagData_, TagDataSize_);
        while (dataNode != nullptr)
        {
            ++actualProperties;

            if (skip != 0U)
            {
                --skip;
            }
            else if (propertiesSize != 0U)
            {
                auto name = dataNode->first_attribute (AttrDataName_, AttrDataNameSize_);
                GetAttributeValue_ (name, &properties->name, &properties->nameSize);

                auto value = dataNode->first_attribute (AttrDataValue_, AttrDataValueSize_);
                GetAttributeValue_ (value, &properties->value, &properties->valueSize);

                ++properties;
                --propertiesSize;
            }

            dataNode = dataNode->next_sibling (TagData_, TagDataSize_);
        }
    }

    return actualProperties;
}

void GetAttributeValue_ (const rapidxml::xml_attribute<char> *source, const char **value, size_t *size)
{
    if (source)
    {
        *value = source->value ();
        *size = source->value_size ();
    }
    else
    {
        *value = nullptr;
        *size = 0U;
    }
}

void GetNodeValue_ (rapidxml::xml_node<char> *source, const char **value, size_t *size)
{
    if (source)
    {
        auto firstChild = source->first_node ();
        if (!firstChild)
        {
            *value = source->value ();
            *size = source->value_size ();
        }
        else if (firstChild == source->last_node ())
        {
            *value = firstChild->value ();
            *size = firstChild->value_size ();
        }
        else
        {
            size_t bufferLength = 0U;
            for (auto node = firstChild; node; node = node->next_sibling ())
            {
                bufferLength += node->value_size ();
            }

            auto bufferSize = bufferLength + 1;
            auto buffer = source->document ()->allocate_string (nullptr, bufferSize);
            buffer[bufferSize - 1] = '\0';

            auto concatHead = buffer;
            auto bufferFreeSize = bufferSize;
            for (auto node = firstChild; node; node = node->next_sibling ())
            {
                auto nodeValue = node->value ();
                auto nodeValueSize = node->value_size ();

                strncpy_s (concatHead, bufferFreeSize, nodeValue, nodeValueSize);
                auto copied = min (bufferFreeSize, nodeValueSize);

                bufferFreeSize -= copied;
                concatHead += copied;
            }

            source->remove_all_nodes ();
            source->value (buffer, bufferLength);

            *value = buffer;
            *size = bufferLength;
        }
    }
    else
    {
        *value = nullptr;
        *size = 0U;
    }
}

int64_t ParseTimestamp_ (const char *value, const size_t valueSize)
{
    int64_t result = 0L;

    for (size_t i = 0; i < valueSize; ++i)
    {
        int64_t digit = value[i] - '0';
        result = result * 10L + digit;
    }

    return result;
}

struct Log4JEventSource_
{
    std::vector<const rapidxml::xml_document<char> *> *Docs;
    char *OwnXmlString;
};

static Log4JStatus Log4JEventSourceInitXmlStringImpl (Log4JEventSource **self, char *xmlString, bool ownString)
{
    *self = nullptr;
    auto ownedStringPtr = ownString ? xmlString : nullptr;

    auto status = Log4JStatus::E_SUCCESS;

    auto nextPart = xmlString;
    auto docs = new std::vector<const rapidxml::xml_document<char> *> ();
    while (nextPart)
    {
        auto doc = new rapidxml::xml_document<char> ();
        docs->push_back (doc);
        try
        {
            doc->parse<rapidxml::parse_default> (nextPart);
            nextPart = nullptr;
        }
        catch (const rapidxml::parse_error &ex)
        {
            status = Log4JStatus::E_DOCUMENT_ERRORS;
            nextPart = strstr (ex.where<char> (), LogFragmentStart_);
        }
        catch (...)
        {
            for (auto docsIter = docs->begin (); docsIter != docs->end (); ++docsIter)
            {
                delete *docsIter;
            }
            throw;
        }
    }

    Log4JEventSource *result = (Log4JEventSource *) malloc (sizeof *result);
    if (result == nullptr)
    {
        for (auto docsIter = docs->begin (); docsIter != docs->end (); ++docsIter)
        {
            delete *docsIter;
        }
        *self = nullptr;
        return Log4JStatus::E_MEMORY_ERROR;
    }
    *result = { docs, ownedStringPtr };

    *self = result;

    return status;
}

LOG4JPARSERC_API Log4JStatus __cdecl Log4JEventSourceInitXmlString (Log4JEventSource **self, char *xmlString)
{
    return Log4JEventSourceInitXmlStringImpl (self, xmlString, false);
}

LOG4JPARSERC_API void __cdecl Log4JEventSourceDestroy (Log4JEventSource *self)
{
    auto docs = self->Docs;
    for (auto docsIter = docs->begin (); docsIter != docs->end (); ++docsIter)
    {
        delete *docsIter;
    }
    docs->clear ();
    delete docs;

    if (self->OwnXmlString)
    {
        free (self->OwnXmlString);
    }

    *self = { nullptr, nullptr };
    free (self);
}

static size_t IndexOfCurrentDocument (const std::vector<const rapidxml::xml_document<char> *> *docs, const rapidxml::xml_node<char> *node)
{
    auto currentDocument = node->document ();
    auto docsSize = docs->size ();
    for (size_t i = 0; i < docsSize; ++i)
    {
        if (docs->at (i) == currentDocument)
        {
            return i;
        }
    }

    return docsSize;
}

LOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourceFirst (const Log4JEventSource *self)
{
    auto node = self->Docs->front ()->first_node (TagEvent_, TagEventSize_);
    return node;
}

LOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourceNext (const Log4JEventSource *self, const Log4JEvent event)
{
    auto docs = self->Docs;
    auto node = (rapidxml::xml_node<char> *) event;

    auto nextNode = node->next_sibling (TagEvent_, TagEventSize_);
    if (!nextNode)
    {
        auto currentDocumentIndex = IndexOfCurrentDocument (self->Docs, node);
        auto nextDocumentIndex = currentDocumentIndex + 1;
        if (nextDocumentIndex < docs->size ())
        {
            nextNode = docs->at (nextDocumentIndex)->first_node (TagEvent_, TagEventSize_);
        }
    }

    return nextNode;
}

LOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourceLast (const Log4JEventSource *self)
{
    auto node = self->Docs->back ()->last_node (TagEvent_, TagEventSize_);
    return node;
}

LOG4JPARSERC_API Log4JEvent __cdecl Log4JEventSourcePrev (const Log4JEventSource *self, const Log4JEvent event)
{
    auto docs = self->Docs;
    auto node = (rapidxml::xml_node<char> *) event;

    auto prevNode = node->previous_sibling (TagEvent_, TagEventSize_);
    if (!prevNode)
    {
        auto currentDocumentIndex = IndexOfCurrentDocument (self->Docs, node);
        auto prevDocumentIndex = currentDocumentIndex - 1;
        // if currentDocumentIndex == 0 then prevDocumentIndex would overflow to SIZE_MAX
        if (prevDocumentIndex < docs->size ())
        {
            prevNode = docs->at (prevDocumentIndex)->first_node (TagEvent_, TagEventSize_);
        }
    }

    return prevNode;
}
<|endoftext|>


<commit_before><commit_msg>getBaseParameter() in BotView::getDeskSize_impl()<commit_after><|endoftext|>


<commit_before><commit_msg>enhance readability<commit_after><|endoftext|>


<commit_before><commit_msg>New genesis block<commit_after><|endoftext|>


<commit_before><commit_msg>Update chainparams.cpp<commit_after><|endoftext|>


<commit_before><commit_msg>build: fix newer boost build with c++11<commit_after><|endoftext|>


<commit_before><commit_msg>Add debugging to CheckHardened<commit_after><|endoftext|>


<commit_before>#include "array.hpp"
//
//
//
bool array::is_positive()
{
    if(is_1d_array)
    {
        return gsl_vector_ispos(user_1d_array);
    }
    else if(is_2d_array)
    {
        return gsl_matrix_ispos(user_2d_array);
    }
}
<commit_msg>Delete array__is_positive.cpp<commit_after><|endoftext|>


<commit_before><commit_msg>Enable some code that compiles fine on linux now.  This code talks about the next merge and was written in September.<commit_after><|endoftext|>


<commit_before><commit_msg>WAL: Logs tweaked<commit_after><|endoftext|>


<commit_before><commit_msg>Cleanup the design of small tables<commit_after><|endoftext|>


<commit_before><commit_msg>fix windows build errors<commit_after><|endoftext|>


<commit_before><commit_msg>Fix (worrying) MSVC warning<commit_after><|endoftext|>


<commit_before><commit_msg>removed redundant workaround for https://bugreports.qt.io/browse/QTBUG-6504 in debug-mode<commit_after><|endoftext|>


<commit_before>#ifndef LIBICS3_ICS3_ANGLE_H_
#define LIBICS3_ICS3_ANGLE_H_

#include"ics3/check_invalid.hpp"

namespace ics {
  class ICS3;
  class Angle {
    friend ICS3; // for touch setRaw
  public:
    using rawType = uint16_t;
    using type = double;
    static constexpr Angle newDegree(type = 0.0);
    static constexpr Angle newRadian(type = 0.0);
    static constexpr Angle newSameUnit(const Angle&, type = 0.0);
    static constexpr Angle newCalibration(type, type = 0.0);
    static constexpr rawType MIN {3500};
    static constexpr rawType MID {7500};
    static constexpr rawType MAX {11500};
    static constexpr type PI {3.141592653589793};

    Angle(const Angle&) noexcept = default;
    Angle& operator=(const Angle&) noexcept;
    constexpr type get() const noexcept;
    constexpr operator type() const noexcept;
    void set(type);
    Angle& operator=(type);
    constexpr rawType getRaw() const noexcept;
    void setRaw(rawType);
  private:
    constexpr Angle(type, type); // non explicit, user cannot touch this
    static constexpr rawType castToRaw(type, type) noexcept;
    static constexpr rawType checkInvalidAngle(rawType);

    rawType rawData;
    const type rawCalibration;
  };

  constexpr Angle Angle::newDegree(type angle) {
    return Angle {800.0 / 27.0, angle};
  }

  constexpr Angle Angle::newRadian(type angle) {
    return Angle {16000.0 / 3.0 / PI, angle};
  }

  constexpr Angle Angle::newSameUnit(const Angle& unit, type angle) {
    return Angle {unit.rawCalibration, angle};
  }

  constexpr Angle Angle::newCalibration(type calibration, type angle) {
    return Angle {calibration, angle};
  }

  inline Angle& Angle::operator=(const Angle& rhs) noexcept {
    rawData = rhs.rawData;
    return *this;
  }

  constexpr Angle::type Angle::get() const noexcept {
    return (rawData - MID) / rawCalibration;
  }

  constexpr Angle::operator type() const noexcept {
    return get();
  }

  inline void Angle::set(type angle) {
    setRaw(castToRaw(rawCalibration, angle)); // throw std::out_of_range
  }

  inline Angle& Angle::operator=(type angle) {
    set(angle);
    return *this;
  }

  constexpr Angle::rawType Angle::getRaw() const noexcept {
    return rawData;
  }

  inline void Angle::setRaw(rawType raw) {
    rawData = checkInvalidAngle(raw); // throw std::out_of_range
  }

  constexpr Angle::Angle(type calibration, type angle)
  : rawData {checkInvalidAngle(castToRaw(calibration, angle))}, // throw std::out_of_range
    rawCalibration {calibration}
  {}

  constexpr Angle::rawType Angle::castToRaw(type calibration, type angle) noexcept {
    return (calibration * angle) + MID;
  }

  constexpr Angle::rawType Angle::checkInvalidAngle(rawType raw) {
    return checkInvalidRange(raw, MIN, MAX);
  }
}

#endif // LIBICS3_ICS3_ANGLE_H_
<commit_msg>Update factory method with no explicit constructor<commit_after>#ifndef LIBICS3_ICS3_ANGLE_H_
#define LIBICS3_ICS3_ANGLE_H_

#include"ics3/check_invalid.hpp"

namespace ics {
  class ICS3;
  class Angle {
    friend ICS3; // for touch setRaw
  public:
    using rawType = uint16_t;
    using type = double;
    static constexpr Angle newDegree(type = 0.0);
    static constexpr Angle newRadian(type = 0.0);
    static constexpr Angle newSameUnit(const Angle&, type = 0.0);
    static constexpr Angle newCalibration(type, type = 0.0);
    static constexpr rawType MIN {3500};
    static constexpr rawType MID {7500};
    static constexpr rawType MAX {11500};
    static constexpr type PI {3.141592653589793};

    Angle(const Angle&) noexcept = default;
    Angle& operator=(const Angle&) noexcept;
    constexpr type get() const noexcept;
    constexpr operator type() const noexcept;
    void set(type);
    Angle& operator=(type);
    constexpr rawType getRaw() const noexcept;
    void setRaw(rawType);
  private:
    constexpr Angle(type, type); // non explicit, user cannot touch this
    static constexpr rawType castToRaw(type, type) noexcept;
    static constexpr rawType checkInvalidAngle(rawType);

    rawType rawData;
    const type rawCalibration;
  };

  constexpr Angle Angle::newDegree(type angle) {
    return {800.0 / 27.0, angle};
  }

  constexpr Angle Angle::newRadian(type angle) {
    return {16000.0 / 3.0 / PI, angle};
  }

  constexpr Angle Angle::newSameUnit(const Angle& unit, type angle) {
    return {unit.rawCalibration, angle};
  }

  constexpr Angle Angle::newCalibration(type calibration, type angle) {
    return {calibration, angle};
  }

  inline Angle& Angle::operator=(const Angle& rhs) noexcept {
    rawData = rhs.rawData;
    return *this;
  }

  constexpr Angle::type Angle::get() const noexcept {
    return (rawData - MID) / rawCalibration;
  }

  constexpr Angle::operator type() const noexcept {
    return get();
  }

  inline void Angle::set(type angle) {
    setRaw(castToRaw(rawCalibration, angle)); // throw std::out_of_range
  }

  inline Angle& Angle::operator=(type angle) {
    set(angle);
    return *this;
  }

  constexpr Angle::rawType Angle::getRaw() const noexcept {
    return rawData;
  }

  inline void Angle::setRaw(rawType raw) {
    rawData = checkInvalidAngle(raw); // throw std::out_of_range
  }

  constexpr Angle::Angle(type calibration, type angle)
  : rawData {checkInvalidAngle(castToRaw(calibration, angle))}, // throw std::out_of_range
    rawCalibration {calibration}
  {}

  constexpr Angle::rawType Angle::castToRaw(type calibration, type angle) noexcept {
    return (calibration * angle) + MID;
  }

  constexpr Angle::rawType Angle::checkInvalidAngle(rawType raw) {
    return checkInvalidRange(raw, MIN, MAX);
  }
}

#endif // LIBICS3_ICS3_ANGLE_H_
<|endoftext|>


<commit_before>/*
 * Generator.cpp
 *
 *  Created on: 05.12.2012
 *      Author: cls
 */

#include "GraphGenerator.h"

namespace EnsembleClustering {

GraphGenerator::GraphGenerator() {
	// TODO Auto-generated constructor stub

}

GraphGenerator::~GraphGenerator() {
	// TODO Auto-generated destructor stub
}

// TODO: parallel? is insertEdge thread safe?

Graph GraphGenerator::makeErdosRenyiGraph(count n, double p) {
	Aux::RandomProbability randP;
	Graph G(n);
	G.forNodePairs([&](node u, node v){
		if (randP.generate() <= p) {
			G.insertEdge(u, v);
		}
	});

	return G;
}

Graph GraphGenerator::makeRandomGraph(count n, double p) {
	return this->makeErdosRenyiGraph(n, p);	// alias
}

Graph GraphGenerator::makeCircularGraph(count n) {
	// TODO: modernize
	Graph G(n);
	G.forNodes([&](node u){
		G.insertEdge(u, (u + 1) % n);
	});
	return G;
}

Graph GraphGenerator::makeCompleteGraph(count n) {
	// TODO: modernize
	Aux::RandomProbability randP;
	Graph G(n);
	G.forNodePairs([&](node u, node v){
		G.insertEdge(u, v);
	});
	return G;
}

Graph GraphGenerator::makeClusteredRandomGraph(count n, count k, double pin, double pout) {
	assert(pin >= pout);

	Graph G(n);
	Aux::RandomProbability randP;
	Aux::RandomInteger randInt(1, k);
	// assign nodes evenly to clusters
	Clustering zeta(n);
	G.forNodes([&](node v){
		cluster c = randInt.generate();
		zeta.addToCluster(c, v);
	});

//	assert (zeta.numberOfClusters() == k);

	G.forNodePairs([&](node u, node v){
		if (zeta.clusterOf(u) == zeta.clusterOf(v)) {
			if (randP.generate() <= pin) {
				G.insertEdge(u, v);
			}
		} else {
			if (randP.generate() <= pout) {
				G.insertEdge(u, v);
			}
		}
	});

	return G;
}

std::pair<Graph, Clustering> GraphGenerator::makeClusteredRandomGraphWithReferenceClustering(
		count n, count k, double pin, double pout) {
	assert(pin >= pout);

	Graph G(n);
	Aux::RandomProbability randP;
	Aux::RandomInteger randInt(1, k);
	// assign nodes evenly to clusters
	Clustering zeta(n);
	G.forNodes([&](node v){
		cluster c = randInt.generate();
		zeta.addToCluster(c, v);
	});

//	assert (zeta.numberOfClusters() == k);

	G.forNodePairs([&](node u, node v){
		if (zeta.clusterOf(u) == zeta.clusterOf(v)) {
			if (randP.generate() <= pin) {
				G.insertEdge(u, v);
			}
		} else {
			if (randP.generate() <= pout) {
				G.insertEdge(u, v);
			}
		}
	});

	return std::make_pair(G, zeta);
}

Graph GraphGenerator::makeClusteredRandomGraph(Clustering& zeta, double pin,
		double pout) {
	assert (pin >= pout);

	count n = zeta.numberOfNodes();
	Graph G(n);

	Aux::RandomProbability randP;
	G.forNodePairs([&](node u, node v){
		if (zeta.inSameCluster(u, v)) {
			if (randP.generate() <= pin) {
				G.insertEdge(u, v);
			}
		} else {
			if (randP.generate() <= pout) {
				G.insertEdge(u, v);
			}
		}
	});

	return G;
}

Graph GraphGenerator::makePreferentialAttachmentGraph(count n, count a) {
	// FIXME: infinite loop

	Graph G(n);

	// all nodes need to have at least degree 1 - create a path
	for (node v = 0; v < (n-1); ++v) {
		G.insertEdge(v, (v + 1));
	}

	count m = G.numberOfEdges(); // number of edges
	count r = 0;

	G.forNodes([&](node u) {
		TRACE("connecting node " << u);
		for (count i = 0; i < a; ++i) { // for all k new edges
			TRACE("2m = " << 2 * m);
			Aux::RandomInteger randInt(0, 2*m);	// TODO: n * k instantiations of RandomInteger are inefficient because random device reads from /dev/random
			r = randInt.generate();
			TRACE("r = " << r);
			for (node v = 0; v < n; ++v) {
				if (r <= G.degree(v)) {
					// select v
					G.insertEdge(u, v);
					TRACE("inserting edge (" << u << "," << v << ")");
					m += 1;
					r = 0;
					break;
				} else {
					TRACE("skipping node " << v);
				}
				r -= G.degree(v);
			}
		}
	});

	return G;
}

} /* namespace EnsembleClustering */
<commit_msg>resolved minor merge conflict<commit_after>/*
 * Generator.cpp
 *
 *  Created on: 05.12.2012
 *      Author: cls
 */

#include "GraphGenerator.h"

namespace EnsembleClustering {

GraphGenerator::GraphGenerator() {
	// TODO Auto-generated constructor stub

}

GraphGenerator::~GraphGenerator() {
	// TODO Auto-generated destructor stub
}

// TODO: parallel? is insertEdge thread safe?

Graph GraphGenerator::makeErdosRenyiGraph(count n, double p) {
	Aux::RandomProbability randP;
	Graph G(n);
	G.forNodePairs([&](node u, node v){
		if (randP.generate() <= p) {
			G.insertEdge(u, v);
		}
	});

	return G;
}

Graph GraphGenerator::makeRandomGraph(count n, double p) {
	return this->makeErdosRenyiGraph(n, p);	// alias
}

Graph GraphGenerator::makeCircularGraph(count n) {
	// TODO: modernize
	Graph G(n);
	G.forNodes([&](node u){
		G.insertEdge(u, (u + 1) % n);
	});
	return G;
}

Graph GraphGenerator::makeCompleteGraph(count n) {
	// TODO: modernize
	Aux::RandomProbability randP;
	Graph G(n);
	G.forNodePairs([&](node u, node v){
		G.insertEdge(u, v);
	});
	return G;
}

Graph GraphGenerator::makeClusteredRandomGraph(count n, count k, double pin, double pout) {
	assert(pin >= pout);

	Graph G(n);
	Aux::RandomProbability randP;
	Aux::RandomInteger randInt(1, k);
	// assign nodes evenly to clusters
	Clustering zeta(n);
	G.forNodes([&](node v){
		cluster c = randInt.generate();
		zeta.addToCluster(c, v);
	});

//	assert (zeta.numberOfClusters() == k);

	G.forNodePairs([&](node u, node v){
		if (zeta.clusterOf(u) == zeta.clusterOf(v)) {
			if (randP.generate() <= pin) {
				G.insertEdge(u, v);
			}
		} else {
			if (randP.generate() <= pout) {
				G.insertEdge(u, v);
			}
		}
	});

	return G;
}

std::pair<Graph, Clustering> GraphGenerator::makeClusteredRandomGraphWithReferenceClustering(
		count n, count k, double pin, double pout) {
	assert(pin >= pout);

	Graph G(n);
	Aux::RandomProbability randP;
	Aux::RandomInteger randInt(1, k);
	// assign nodes evenly to clusters
	Clustering zeta(n);
	G.forNodes([&](node v){
		cluster c = randInt.generate();
		zeta.addToCluster(c, v);
	});

	G.forNodePairs([&](node u, node v){
		if (zeta.clusterOf(u) == zeta.clusterOf(v)) {
			if (randP.generate() <= pin) {
				G.insertEdge(u, v);
			}
		} else {
			if (randP.generate() <= pout) {
				G.insertEdge(u, v);
			}
		}
	});

	return std::make_pair(G, zeta);
}

Graph GraphGenerator::makeClusteredRandomGraph(Clustering& zeta, double pin,
		double pout) {
	assert (pin >= pout);

	count n = zeta.numberOfNodes();
	Graph G(n);

	Aux::RandomProbability randP;
	G.forNodePairs([&](node u, node v){
		if (zeta.inSameCluster(u, v)) {
			if (randP.generate() <= pin) {
				G.insertEdge(u, v);
			}
		} else {
			if (randP.generate() <= pout) {
				G.insertEdge(u, v);
			}
		}
	});

	return G;
}

Graph GraphGenerator::makePreferentialAttachmentGraph(count n, count a) {
	// FIXME: infinite loop

	Graph G(n);

	// all nodes need to have at least degree 1 - create a path
	for (node v = 0; v < (n-1); ++v) {
		G.insertEdge(v, (v + 1));
	}

	count m = G.numberOfEdges(); // number of edges
	count r = 0;

	G.forNodes([&](node u) {
		TRACE("connecting node " << u);
		for (count i = 0; i < a; ++i) { // for all k new edges
			TRACE("2m = " << 2 * m);
			Aux::RandomInteger randInt(0, 2*m);	// TODO: n * k instantiations of RandomInteger are inefficient because random device reads from /dev/random
			r = randInt.generate();
			TRACE("r = " << r);
			for (node v = 0; v < n; ++v) {
				if (r <= G.degree(v)) {
					// select v
					G.insertEdge(u, v);
					TRACE("inserting edge (" << u << "," << v << ")");
					m += 1;
					r = 0;
					break;
				} else {
					TRACE("skipping node " << v);
				}
				r -= G.degree(v);
			}
		}
	});

	return G;
}

} /* namespace EnsembleClustering */
<|endoftext|>


<commit_before><commit_msg>Change usage of assert() in main Run loop<commit_after><|endoftext|>


<commit_before><commit_msg>Removed unnecessary commented code.<commit_after><|endoftext|>


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

#include <sstream>
#include <utility>
#include <babylon/babylon_version.h>
#include <babylon/core/delegates/delegate.h>
#include <babylon/core/logging.h>
#include <babylon/core/string.h>
#include <babylon/samples/sample_launcher.h>
#include <babylon/samples/samples_index.h>
#ifdef WITH_INSPECTOR
#include <babylon/inspector/inspector.h>
#endif

#if _MSC_VER
#include <windows.h>
#include <direct.h>
#include <filesystem>
#endif

struct ConsoleLogger {

  using log_message_t = SA::delegate<void(const BABYLON::LogMessage&)>;

  static void onLogMessage(const BABYLON::LogMessage& logMessage)
  {
    printf("%s\n", logMessage.toString().c_str());
#if _MSC_VER
    OutputDebugString(logMessage.toString().c_str());
#endif
  }

  static log_message_t logListenerDelegate;

}; // end of struct ConsoleLogger

ConsoleLogger::log_message_t ConsoleLogger::logListenerDelegate
  = SA::delegate<void(
    const BABYLON::LogMessage&)>::create<&ConsoleLogger::onLogMessage>();

/**
 * @brief Initializes the logging.
 */
void initializeLogging()
{
  static_assert(
    std::is_same<SA::delegate<void(const BABYLON::LogMessage&)>,
                 decltype(ConsoleLogger::logListenerDelegate)>::value,
    "!");
  // Intialize log levels
  std::vector<std::pair<unsigned int, std::string>> _logLevels;
  for (auto& logLevel : BABYLON::LogLevels::Levels) {
    unsigned int logType = logLevel.first;
    if ((logType != BABYLON::LogLevels::LEVEL_QUIET)
        && (logType != BABYLON::LogLevels::LEVEL_TRACE)) {
      _logLevels.emplace_back(logLevel);
    }
  }
  // Subscribe to channels
  for (auto& logLevel : _logLevels) {
    unsigned int logType = logLevel.first;
    if (logType != BABYLON::LogLevels::LEVEL_QUIET) {
      BABYLON::Logger::Instance().registerLogMessageListener(
        logType, ConsoleLogger::logListenerDelegate);
    }
  }
}

// a simple "Consumable value", i.e a value that is reset when it is consumed
template<typename T>
class ConsumableValue
{
public:
  ConsumableValue(std::optional<T> v = std::nullopt) : _value(v) {};
  bool hasValue() { return _value.has_value(); }
  void setValue(T value) { _value = value; }
  T consumeValue() { return std::exchange(_value, std::nullopt).value(); } // will throw if empty!
private:
   std::optional<T> _value;
};

/**
 * @brief Runs a sample with the specified name
 * @param samples list with available samples
 * @param sampleName name of the sample to run
 * @param showInspectorWindow whether or not to shoz the inspector window
 * @return exit code
 */
int runSample(const BABYLON::Samples::SamplesIndex& samples,
              const std::string& startSampleName, bool showInspectorWindow,
              long runTimeMillis = 0)
{
  // The inspector enables to switch to another sample via
  // the callback BABYLON::Inspector::OnSampleChanged
  // which will the content of "nextSample"
  ConsumableValue<std::string> nextSample(startSampleName);
  #ifdef WITH_INSPECTOR
  BABYLON::Inspector::OnSampleChanged = [&nextSample](const std::string & s) {
    nextSample.setValue(s);
  };
  #endif

  int exitcode = 0;
  // Create the sample launcher
  BABYLON::Samples::SampleLauncherOptions options;
  options.showInspectorWindow = showInspectorWindow;

  while (nextSample.hasValue())
  {
    std::string sampleName = nextSample.consumeValue();
    BABYLON::Samples::SampleLauncher sampleLauncher{options};
    if (sampleLauncher.intialize()) {
      // Create the renderable scene
      auto canvas = sampleLauncher.getRenderCanvas();
      auto scene  = samples.createRenderableScene(sampleName, canvas);
      sampleLauncher.setRenderableScene(scene);
      // Run the example: it will stop when a new sample was selected via the inspector
      exitcode = sampleLauncher.run([&nextSample]() { return nextSample.hasValue(); }, runTimeMillis);
    }
  }
  return exitcode;
}

/**
 * @brief The sample launcher.
 * @param l list samples if l > 0
 * @param v enable verbose mode if v > 0
 * @param sample name of the sample to run
 * @return exit code
 */
int sampleLauncherMain(int l, int v, int i, const char* sampleGroup,
                       const char* sample)
{
  using namespace BABYLON::Samples;
  SamplesIndex samples;
  int exitcode = 0;
  if (l > 0) {
    std::ostringstream oss;
    // Get sample names and category names
    auto sampleNames   = samples.getSampleNames();
    auto categoryNames = samples.getCategoryNames();
    oss << "Found " << sampleNames.size() << " in " << categoryNames.size()
        << " categories:\n";
    // Print categorized samples
    for (const auto& categoryName : categoryNames) {
      sampleNames = samples.getSampleNamesInCategory(categoryName);
      oss << "       |- ";
      if (sampleNames.size() < 10) {
        oss << " " << sampleNames.size();
      }
      else if (sampleNames.size() < 100) {
        oss << sampleNames.size();
      }
      oss << " sample(s) in category \"" << categoryName.c_str() << "\"\n";
      for (const auto& sampleName : sampleNames) {
        oss << "           |- " << sampleName.c_str() << "\n";
      }
    }
    printf("%s", oss.str().c_str());
  }
  else {
    if (v > 0) {
      // Enable console logging
      initializeLogging();
    }
    // Check for rendering of sample group
    const std::string categoryName{sampleGroup};
    if (!categoryName.empty()
        && (samples.categoryExists(categoryName) || categoryName == "All")) {
      std::vector<std::string> categoryNames;
      if (categoryName == "All") {
        categoryNames = samples.getCategoryNames();
      }
      else {
        categoryNames = {categoryName};
      }
      for (const auto& _categoryName : categoryNames) {
        const auto sampleNames
          = samples.getSampleNamesInCategory(_categoryName);
        for (const auto& sampleName : sampleNames) {
          exitcode = runSample(samples, sampleName, i > 0, 10000);
          if (exitcode == 0) {
            break;
          }
        }
      }
    }
    else {
      // Check for rendering of sample
      const std::string sampleName{sample};
      if (!samples.sampleExists(sampleName)) {
        printf("Sample with name \"%s\" does not exists.\n", sample);
        return 1;
      }
      if (!samples.isSampleEnabled(sampleName)) {
        printf("Sample with name \"%s\" is not enabled.\n", sample);
        return 1;
      }
      // Run the sample
      exitcode = runSample(samples, sampleName, i > 0);
    }
  }
  return exitcode;
}

#ifdef _MSC_VER
void ChdirToExePath(char *argv0)
{
  std::filesystem::path exeFolder = std::filesystem::weakly_canonical(std::filesystem::path(argv0)).parent_path();
#ifdef _WIN32
  _chdir(exeFolder.string().c_str());
#else
  chdir(exeFolder.string().c_str());
#endif
}
#endif // _MSC_VER

int main(int argc, char** argv)
{
#ifdef _MSC_VER
  ChdirToExePath(argv[0]);
#endif
  /** Program arguments definition **/
  struct arg_lit* list   = arg_lit0("lL", NULL, "list samples");
  struct arg_str* sample = arg_str0(
    "S", "sample", "<SAMPE>", "sample to launch (default is \"BasicScene\")");
  struct arg_str* sampleGroup = arg_str0(
    "G", "sample-group", "<SAMPE-GROUP>",
    "sample group to launch (sample-group \"All\" contains all samples)");
  struct arg_lit* verbose = arg_lit0("v", "verbose,debug", "verbose messages");
  struct arg_lit* inspector
    = arg_lit0("i", "inspector", "show inspector window");
  struct arg_lit* help = arg_lit0(NULL, "help", "print this help and exit");
  struct arg_lit* version
    = arg_lit0(NULL, "version", "print version information and exit");
  struct arg_end* end = arg_end(20);
  void* argtable[]
    = {list, sample, sampleGroup, verbose, inspector, help, version, end};
  const char* progname = "SampleLauncher";
  int nerrors;
  int exitcode = 0;

  /** Verify the argtable[] entries were allocated sucessfully **/
  if (arg_nullcheck(argtable) != 0) {
    /** NULL entries were detected, some allocations must have failed **/
    printf("%s: insufficient memory\n", progname);
    exitcode = 1;
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    return exitcode;
  }

  /** Set the default sample values prior to parsing **/
  sample->sval[0] = "BasicScene";

  /**  Set the default sample group prior to parsing */
  sampleGroup->sval[0] = "";

  /** Parse the command line as defined by argtable[] **/
  nerrors = arg_parse(argc, argv, argtable);

  /** Special case: '--help' takes precedence over error reporting **/
  if (help->count > 0) {
    printf("Usage: %s", progname);
    arg_print_syntax(stdout, argtable, "\n");
    printf(
      "This program acts as a sample launcher for demonstrating the usage of "
      "the BabylonCpp library\n");
    arg_print_glossary(stdout, argtable, "  %-35s %s\n");
    exitcode = 0;
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    return exitcode;
  }

  /** Special case: '--version' takes precedence error reporting **/
  if (version->count > 0) {
    printf("%s\n", BABYLONCPP_NAME_VERSION);
    exitcode = 0;
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    return exitcode;
  }

  /** If the parser returned any errors then display them and exit **/
  if (nerrors > 0) {
    /** Display the error details contained in the arg_end struct. **/
    arg_print_errors(stdout, end, progname);
    printf("Try '%s --help' for more information.\n", progname);
    exitcode = 1;
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    return exitcode;
  }

  /** Normal case: run sample **/
  exitcode = sampleLauncherMain(list->count, verbose->count, inspector->count,
                                sampleGroup->sval[0], sample->sval[0]);

  /** Deallocate each non-null entry in argtable[] **/
  arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));

  return exitcode;
}
<commit_msg>main.cpp / ConsoleLogger : add newlines in msvc console output<commit_after>#include <argtable3/argtable3.h>

#include <sstream>
#include <utility>
#include <babylon/babylon_version.h>
#include <babylon/core/delegates/delegate.h>
#include <babylon/core/logging.h>
#include <babylon/core/string.h>
#include <babylon/samples/sample_launcher.h>
#include <babylon/samples/samples_index.h>
#ifdef WITH_INSPECTOR
#include <babylon/inspector/inspector.h>
#endif

#if _MSC_VER
#include <windows.h>
#include <direct.h>
#include <filesystem>
#endif

struct ConsoleLogger {

  using log_message_t = SA::delegate<void(const BABYLON::LogMessage&)>;

  static void onLogMessage(const BABYLON::LogMessage& logMessage)
  {
    printf("%s\n", logMessage.toString().c_str());
#if _MSC_VER
    std::string msg_n = logMessage.toString() + "\n";
    OutputDebugString(msg_n.c_str());
#endif
  }

  static log_message_t logListenerDelegate;

}; // end of struct ConsoleLogger

ConsoleLogger::log_message_t ConsoleLogger::logListenerDelegate
  = SA::delegate<void(
    const BABYLON::LogMessage&)>::create<&ConsoleLogger::onLogMessage>();

/**
 * @brief Initializes the logging.
 */
void initializeLogging()
{
  static_assert(
    std::is_same<SA::delegate<void(const BABYLON::LogMessage&)>,
                 decltype(ConsoleLogger::logListenerDelegate)>::value,
    "!");
  // Intialize log levels
  std::vector<std::pair<unsigned int, std::string>> _logLevels;
  for (auto& logLevel : BABYLON::LogLevels::Levels) {
    unsigned int logType = logLevel.first;
    if ((logType != BABYLON::LogLevels::LEVEL_QUIET)
        && (logType != BABYLON::LogLevels::LEVEL_TRACE)) {
      _logLevels.emplace_back(logLevel);
    }
  }
  // Subscribe to channels
  for (auto& logLevel : _logLevels) {
    unsigned int logType = logLevel.first;
    if (logType != BABYLON::LogLevels::LEVEL_QUIET) {
      BABYLON::Logger::Instance().registerLogMessageListener(
        logType, ConsoleLogger::logListenerDelegate);
    }
  }
}

// a simple "Consumable value", i.e a value that is reset when it is consumed
template<typename T>
class ConsumableValue
{
public:
  ConsumableValue(std::optional<T> v = std::nullopt) : _value(v) {};
  bool hasValue() { return _value.has_value(); }
  void setValue(T value) { _value = value; }
  T consumeValue() { return std::exchange(_value, std::nullopt).value(); } // will throw if empty!
private:
   std::optional<T> _value;
};

/**
 * @brief Runs a sample with the specified name
 * @param samples list with available samples
 * @param sampleName name of the sample to run
 * @param showInspectorWindow whether or not to shoz the inspector window
 * @return exit code
 */
int runSample(const BABYLON::Samples::SamplesIndex& samples,
              const std::string& startSampleName, bool showInspectorWindow,
              long runTimeMillis = 0)
{
  // The inspector enables to switch to another sample via
  // the callback BABYLON::Inspector::OnSampleChanged
  // which will the content of "nextSample"
  ConsumableValue<std::string> nextSample(startSampleName);
  #ifdef WITH_INSPECTOR
  BABYLON::Inspector::OnSampleChanged = [&nextSample](const std::string & s) {
    nextSample.setValue(s);
  };
  #endif

  int exitcode = 0;
  // Create the sample launcher
  BABYLON::Samples::SampleLauncherOptions options;
  options.showInspectorWindow = showInspectorWindow;

  while (nextSample.hasValue())
  {
    std::string sampleName = nextSample.consumeValue();
    BABYLON::Samples::SampleLauncher sampleLauncher{options};
    if (sampleLauncher.intialize()) {
      // Create the renderable scene
      auto canvas = sampleLauncher.getRenderCanvas();
      auto scene  = samples.createRenderableScene(sampleName, canvas);
      sampleLauncher.setRenderableScene(scene);
      // Run the example: it will stop when a new sample was selected via the inspector
      exitcode = sampleLauncher.run([&nextSample]() { return nextSample.hasValue(); }, runTimeMillis);
    }
  }
  return exitcode;
}

/**
 * @brief The sample launcher.
 * @param l list samples if l > 0
 * @param v enable verbose mode if v > 0
 * @param sample name of the sample to run
 * @return exit code
 */
int sampleLauncherMain(int l, int v, int i, const char* sampleGroup,
                       const char* sample)
{
  using namespace BABYLON::Samples;
  SamplesIndex samples;
  int exitcode = 0;
  if (l > 0) {
    std::ostringstream oss;
    // Get sample names and category names
    auto sampleNames   = samples.getSampleNames();
    auto categoryNames = samples.getCategoryNames();
    oss << "Found " << sampleNames.size() << " in " << categoryNames.size()
        << " categories:\n";
    // Print categorized samples
    for (const auto& categoryName : categoryNames) {
      sampleNames = samples.getSampleNamesInCategory(categoryName);
      oss << "       |- ";
      if (sampleNames.size() < 10) {
        oss << " " << sampleNames.size();
      }
      else if (sampleNames.size() < 100) {
        oss << sampleNames.size();
      }
      oss << " sample(s) in category \"" << categoryName.c_str() << "\"\n";
      for (const auto& sampleName : sampleNames) {
        oss << "           |- " << sampleName.c_str() << "\n";
      }
    }
    printf("%s", oss.str().c_str());
  }
  else {
    if (v > 0) {
      // Enable console logging
      initializeLogging();
    }
    // Check for rendering of sample group
    const std::string categoryName{sampleGroup};
    if (!categoryName.empty()
        && (samples.categoryExists(categoryName) || categoryName == "All")) {
      std::vector<std::string> categoryNames;
      if (categoryName == "All") {
        categoryNames = samples.getCategoryNames();
      }
      else {
        categoryNames = {categoryName};
      }
      for (const auto& _categoryName : categoryNames) {
        const auto sampleNames
          = samples.getSampleNamesInCategory(_categoryName);
        for (const auto& sampleName : sampleNames) {
          exitcode = runSample(samples, sampleName, i > 0, 10000);
          if (exitcode == 0) {
            break;
          }
        }
      }
    }
    else {
      // Check for rendering of sample
      const std::string sampleName{sample};
      if (!samples.sampleExists(sampleName)) {
        printf("Sample with name \"%s\" does not exists.\n", sample);
        return 1;
      }
      if (!samples.isSampleEnabled(sampleName)) {
        printf("Sample with name \"%s\" is not enabled.\n", sample);
        return 1;
      }
      // Run the sample
      exitcode = runSample(samples, sampleName, i > 0);
    }
  }
  return exitcode;
}

#ifdef _MSC_VER
void ChdirToExePath(char *argv0)
{
  std::filesystem::path exeFolder = std::filesystem::weakly_canonical(std::filesystem::path(argv0)).parent_path();
#ifdef _WIN32
  _chdir(exeFolder.string().c_str());
#else
  chdir(exeFolder.string().c_str());
#endif
}
#endif // _MSC_VER

int main(int argc, char** argv)
{
#ifdef _MSC_VER
  ChdirToExePath(argv[0]);
#endif
  /** Program arguments definition **/
  struct arg_lit* list   = arg_lit0("lL", NULL, "list samples");
  struct arg_str* sample = arg_str0(
    "S", "sample", "<SAMPE>", "sample to launch (default is \"BasicScene\")");
  struct arg_str* sampleGroup = arg_str0(
    "G", "sample-group", "<SAMPE-GROUP>",
    "sample group to launch (sample-group \"All\" contains all samples)");
  struct arg_lit* verbose = arg_lit0("v", "verbose,debug", "verbose messages");
  struct arg_lit* inspector
    = arg_lit0("i", "inspector", "show inspector window");
  struct arg_lit* help = arg_lit0(NULL, "help", "print this help and exit");
  struct arg_lit* version
    = arg_lit0(NULL, "version", "print version information and exit");
  struct arg_end* end = arg_end(20);
  void* argtable[]
    = {list, sample, sampleGroup, verbose, inspector, help, version, end};
  const char* progname = "SampleLauncher";
  int nerrors;
  int exitcode = 0;

  /** Verify the argtable[] entries were allocated sucessfully **/
  if (arg_nullcheck(argtable) != 0) {
    /** NULL entries were detected, some allocations must have failed **/
    printf("%s: insufficient memory\n", progname);
    exitcode = 1;
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    return exitcode;
  }

  /** Set the default sample values prior to parsing **/
  sample->sval[0] = "BasicScene";

  /**  Set the default sample group prior to parsing */
  sampleGroup->sval[0] = "";

  /** Parse the command line as defined by argtable[] **/
  nerrors = arg_parse(argc, argv, argtable);

  /** Special case: '--help' takes precedence over error reporting **/
  if (help->count > 0) {
    printf("Usage: %s", progname);
    arg_print_syntax(stdout, argtable, "\n");
    printf(
      "This program acts as a sample launcher for demonstrating the usage of "
      "the BabylonCpp library\n");
    arg_print_glossary(stdout, argtable, "  %-35s %s\n");
    exitcode = 0;
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    return exitcode;
  }

  /** Special case: '--version' takes precedence error reporting **/
  if (version->count > 0) {
    printf("%s\n", BABYLONCPP_NAME_VERSION);
    exitcode = 0;
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    return exitcode;
  }

  /** If the parser returned any errors then display them and exit **/
  if (nerrors > 0) {
    /** Display the error details contained in the arg_end struct. **/
    arg_print_errors(stdout, end, progname);
    printf("Try '%s --help' for more information.\n", progname);
    exitcode = 1;
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    return exitcode;
  }

  /** Normal case: run sample **/
  exitcode = sampleLauncherMain(list->count, verbose->count, inspector->count,
                                sampleGroup->sval[0], sample->sval[0]);

  /** Deallocate each non-null entry in argtable[] **/
  arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));

  return exitcode;
}
<|endoftext|>


<commit_before><commit_msg>Fix bug where pieces would stop falling<commit_after><|endoftext|>


<commit_before><commit_msg>fix shape edges computation<commit_after><|endoftext|>


<commit_before><commit_msg>Try to add set default target triple<commit_after><|endoftext|>