<commit_before>/*
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/test/unit_test.hpp>
#include "utils/fb_utilities.hh"
#include "locator/network_topology_strategy.hh"
#include "tests/test-utils.hh"
#include "core/sstring.hh"
#include "log.hh"
#include <vector>
#include <string>
#include <map>
#include <iostream>
#include <sstream>

static logging::logger nlogger("NetworkTopologyStrategyLogger");

using namespace locator;

struct ring_point {
    double point;
    inet_address host;
};

void print_natural_endpoints(double point, const std::vector<inet_address> v) {
    nlogger.debug("Natural endpoints for a token {}:", point);
    std::string str;
    std::ostringstream strm(str);

    for (auto& addr : v) {
        strm<<addr<<" ";
    }

    nlogger.debug("{}", strm.str());
}

void strategy_sanity_check(
    abstract_replication_strategy* ars_ptr,
    const std::map<sstring, sstring>& options) {

    network_topology_strategy* nts_ptr =
        dynamic_cast<network_topology_strategy*>(ars_ptr);

    //
    // Check that both total and per-DC RFs in options match the corresponding
    // value in the strategy object.
    //
    size_t total_rf = 0;
    for (auto& val : options) {
        size_t rf = std::stol(val.second);
        BOOST_CHECK(nts_ptr->get_replication_factor(val.first) == rf);

        total_rf += rf;
    }

    BOOST_CHECK(ars_ptr->get_replication_factor() == total_rf);
}

void endpoints_check(
    abstract_replication_strategy* ars_ptr,
    std::vector<inet_address>& endpoints) {

    // Check the total RF
    BOOST_CHECK(endpoints.size() == ars_ptr->get_replication_factor());

    // Check the uniqueness
    std::unordered_set<inet_address> ep_set(endpoints.begin(), endpoints.end());
    BOOST_CHECK(endpoints.size() == ep_set.size());

    // Check the per-DC RF
    auto& snitch = i_endpoint_snitch::get_local_snitch_ptr();
    std::unordered_map<sstring, size_t> dc_rf;
    for (auto ep : endpoints) {
        sstring dc = snitch->get_datacenter(ep);

        auto rf = dc_rf.find(dc);
        if (rf == dc_rf.end()) {
            dc_rf[dc] = 1;
        } else {
            rf->second++;
        }
    }

    network_topology_strategy* nts_ptr =
        dynamic_cast<network_topology_strategy*>(ars_ptr);
    for (auto& rf : dc_rf) {
        BOOST_CHECK(rf.second == nts_ptr->get_replication_factor(rf.first));
    }
}

auto d2t = [](double d) {
    unsigned long l = net::hton(static_cast<unsigned long>(d*(std::numeric_limits<unsigned long>::max())));
    std::array<char, 8> a;
    memcpy(a.data(), &l, 8);
    return a;
};

/**
 * Check the get_natural_endpoints() output for tokens between every two
 * adjacent ring points.
 * @param ring_points ring description
 * @param options strategy options
 * @param ars_ptr strategy object
 */
void full_ring_check(const std::vector<ring_point>& ring_points,
                     const std::map<sstring, sstring>& options,
                     abstract_replication_strategy* ars_ptr) {
    strategy_sanity_check(ars_ptr, options);

    for (auto& rp : ring_points) {
        double cur_point1 = rp.point - 0.5;
        token t1({dht::token::kind::key,
             {(int8_t*)d2t(cur_point1 / ring_points.size()).data(), 8}});
        uint64_t cache_hit_count = ars_ptr->get_cache_hits_count();
        auto endpoints1 = ars_ptr->get_natural_endpoints(t1);

        endpoints_check(ars_ptr, endpoints1);
        // validate that the result hasn't been taken from the cache
        BOOST_CHECK(cache_hit_count == ars_ptr->get_cache_hits_count());

        print_natural_endpoints(cur_point1, endpoints1);

        //
        // Check a different endpoint in the same range as t1 and validate that
        // the endpoints has been taken from the cache and that the output is
        // identical to the one not taken from the cache.
        //
        cache_hit_count = ars_ptr->get_cache_hits_count();
        double cur_point2 = rp.point - 0.2;
        token t2({dht::token::kind::key,
             {(int8_t*)d2t(cur_point2 / ring_points.size()).data(), 8}});
        auto endpoints2 = ars_ptr->get_natural_endpoints(t2);

        endpoints_check(ars_ptr, endpoints2);
        BOOST_CHECK(cache_hit_count + 1 == ars_ptr->get_cache_hits_count());
        BOOST_CHECK(endpoints1 == endpoints2);
    }
}

future<> simple_test() {
    utils::fb_utilities::set_broadcast_address(gms::inet_address("localhost"));
    utils::fb_utilities::set_broadcast_rpc_address(gms::inet_address("localhost"));

    // Create the RackInferringSnitch
    return i_endpoint_snitch::create_snitch("RackInferringSnitch").then(
        [] {

        lw_shared_ptr<token_metadata> tm = make_lw_shared<token_metadata>();
        std::vector<ring_point> ring_points = {
            { 1.0,  inet_address("192.100.10.1") },
            { 2.0,  inet_address("192.101.10.1") },
            { 3.0,  inet_address("192.102.10.1") },
            { 4.0,  inet_address("192.100.20.1") },
            { 5.0,  inet_address("192.101.20.1") },
            { 6.0,  inet_address("192.102.20.1") },
            { 7.0,  inet_address("192.100.30.1") },
            { 8.0,  inet_address("192.101.30.1") },
            { 9.0,  inet_address("192.102.30.1") },
            { 10.0, inet_address("192.102.40.1") },
            { 11.0, inet_address("192.102.40.2") }
        };
        // Initialize the token_metadata
        for (unsigned i = 0; i < ring_points.size(); i++) {
            tm->update_normal_token(
                {dht::token::kind::key,
                 {(int8_t*)d2t(ring_points[i].point / ring_points.size()).data(), 8}
                },
                ring_points[i].host);
        }

        /////////////////////////////////////
        // Create the replication strategy
        std::map<sstring, sstring> options323 = {
            {"100", "3"},
            {"101", "2"},
            {"102", "3"}
        };

        auto ars_uptr = abstract_replication_strategy::create_replication_strategy(
            "test keyspace", "NetworkTopologyStrategy", *tm, options323);

        auto ars_ptr = ars_uptr.get();

        full_ring_check(ring_points, options323, ars_ptr);

        ///////////////
        // Create the replication strategy
        std::map<sstring, sstring> options320 = {
            {"100", "3"},
            {"101", "2"},
            {"102", "0"}
        };

        ars_uptr = abstract_replication_strategy::create_replication_strategy(
            "test keyspace", "NetworkTopologyStrategy", *tm, options320);

        ars_ptr = ars_uptr.get();

        full_ring_check(ring_points, options320, ars_ptr);

        //
        // Check cache invalidation: invalidate the cache and run a full ring
        // check once again. If cache is not properly invalidated one of the
        // points will be taken from the cache when it shouldn't and the
        // corresponding check will fail.
        //
        tm->invalidate_cached_rings();
        full_ring_check(ring_points, options320, ars_ptr);

        return i_endpoint_snitch::stop_snitch();
    });
}

future<> heavy_origin_test() {
    utils::fb_utilities::set_broadcast_address(gms::inet_address("localhost"));
    utils::fb_utilities::set_broadcast_rpc_address(gms::inet_address("localhost"));

    // Create the RackInferringSnitch
    return i_endpoint_snitch::create_snitch("RackInferringSnitch").then(
        [] {
        std::vector<int> dc_racks = {2, 4, 8};
        std::vector<int> dc_endpoints = {128, 256, 512};
        std::vector<int> dc_replication = {2, 6, 6};

        lw_shared_ptr<token_metadata> tm = make_lw_shared<token_metadata>();
        std::map<sstring, sstring> config_options;
        std::unordered_map<inet_address, std::unordered_set<token>> tokens;
        std::vector<ring_point> ring_points;

        size_t total_eps = 0;
        for (size_t dc = 0; dc < dc_racks.size(); ++dc) {
            for (int rack = 0; rack < dc_racks[dc]; ++rack) {
                total_eps += dc_endpoints[dc]/dc_racks[dc];
            }
        }

        int total_rf = 0;
        double token_point = 1.0;
        for (size_t dc = 0; dc < dc_racks.size(); ++dc) {
            total_rf += dc_replication[dc];
            config_options.emplace(to_sstring(dc),
                                   to_sstring(dc_replication[dc]));
            for (int rack = 0; rack < dc_racks[dc]; ++rack) {
                for (int ep = 1; ep <= dc_endpoints[dc]/dc_racks[dc]; ++ep) {

                    // 10.dc.rack.ep
                    int32_t ip = 0x0a000000 + ((int8_t)dc << 16) +
                                 ((int8_t)rack << 8) + (int8_t)ep;
                    inet_address address(ip);
                    ring_point rp = {token_point, address};

                    ring_points.emplace_back(rp);
                    tokens[address].emplace(token{dht::token::kind::key,
                            {(int8_t*)d2t(token_point / total_eps).data(), 8}});

                    nlogger.debug("adding node {} at {}", address, token_point);

                    token_point++;
                }
            }
        }

        tm->update_normal_tokens(tokens);

        auto ars_uptr = abstract_replication_strategy::create_replication_strategy(
            "test keyspace", "NetworkTopologyStrategy", *tm, config_options);

        auto ars_ptr = ars_uptr.get();

        full_ring_check(ring_points, config_options, ars_ptr);

        return i_endpoint_snitch::stop_snitch();
    });
}

SEASTAR_TEST_CASE(NetworkTopologyStrategy_simple) {
    return simple_test();
}

SEASTAR_TEST_CASE(NetworkTopologyStrategy_heavy) {
    return heavy_origin_test();
}
<commit_msg>tests: network_topology_strategy_test: peel off redundant parentheses around token initializer<commit_after>/*
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/test/unit_test.hpp>
#include "utils/fb_utilities.hh"
#include "locator/network_topology_strategy.hh"
#include "tests/test-utils.hh"
#include "core/sstring.hh"
#include "log.hh"
#include <vector>
#include <string>
#include <map>
#include <iostream>
#include <sstream>

static logging::logger nlogger("NetworkTopologyStrategyLogger");

using namespace locator;

struct ring_point {
    double point;
    inet_address host;
};

void print_natural_endpoints(double point, const std::vector<inet_address> v) {
    nlogger.debug("Natural endpoints for a token {}:", point);
    std::string str;
    std::ostringstream strm(str);

    for (auto& addr : v) {
        strm<<addr<<" ";
    }

    nlogger.debug("{}", strm.str());
}

void strategy_sanity_check(
    abstract_replication_strategy* ars_ptr,
    const std::map<sstring, sstring>& options) {

    network_topology_strategy* nts_ptr =
        dynamic_cast<network_topology_strategy*>(ars_ptr);

    //
    // Check that both total and per-DC RFs in options match the corresponding
    // value in the strategy object.
    //
    size_t total_rf = 0;
    for (auto& val : options) {
        size_t rf = std::stol(val.second);
        BOOST_CHECK(nts_ptr->get_replication_factor(val.first) == rf);

        total_rf += rf;
    }

    BOOST_CHECK(ars_ptr->get_replication_factor() == total_rf);
}

void endpoints_check(
    abstract_replication_strategy* ars_ptr,
    std::vector<inet_address>& endpoints) {

    // Check the total RF
    BOOST_CHECK(endpoints.size() == ars_ptr->get_replication_factor());

    // Check the uniqueness
    std::unordered_set<inet_address> ep_set(endpoints.begin(), endpoints.end());
    BOOST_CHECK(endpoints.size() == ep_set.size());

    // Check the per-DC RF
    auto& snitch = i_endpoint_snitch::get_local_snitch_ptr();
    std::unordered_map<sstring, size_t> dc_rf;
    for (auto ep : endpoints) {
        sstring dc = snitch->get_datacenter(ep);

        auto rf = dc_rf.find(dc);
        if (rf == dc_rf.end()) {
            dc_rf[dc] = 1;
        } else {
            rf->second++;
        }
    }

    network_topology_strategy* nts_ptr =
        dynamic_cast<network_topology_strategy*>(ars_ptr);
    for (auto& rf : dc_rf) {
        BOOST_CHECK(rf.second == nts_ptr->get_replication_factor(rf.first));
    }
}

auto d2t = [](double d) {
    unsigned long l = net::hton(static_cast<unsigned long>(d*(std::numeric_limits<unsigned long>::max())));
    std::array<char, 8> a;
    memcpy(a.data(), &l, 8);
    return a;
};

/**
 * Check the get_natural_endpoints() output for tokens between every two
 * adjacent ring points.
 * @param ring_points ring description
 * @param options strategy options
 * @param ars_ptr strategy object
 */
void full_ring_check(const std::vector<ring_point>& ring_points,
                     const std::map<sstring, sstring>& options,
                     abstract_replication_strategy* ars_ptr) {
    strategy_sanity_check(ars_ptr, options);

    for (auto& rp : ring_points) {
        double cur_point1 = rp.point - 0.5;
        token t1{dht::token::kind::key,
             {(int8_t*)d2t(cur_point1 / ring_points.size()).data(), 8}};
        uint64_t cache_hit_count = ars_ptr->get_cache_hits_count();
        auto endpoints1 = ars_ptr->get_natural_endpoints(t1);

        endpoints_check(ars_ptr, endpoints1);
        // validate that the result hasn't been taken from the cache
        BOOST_CHECK(cache_hit_count == ars_ptr->get_cache_hits_count());

        print_natural_endpoints(cur_point1, endpoints1);

        //
        // Check a different endpoint in the same range as t1 and validate that
        // the endpoints has been taken from the cache and that the output is
        // identical to the one not taken from the cache.
        //
        cache_hit_count = ars_ptr->get_cache_hits_count();
        double cur_point2 = rp.point - 0.2;
        token t2{dht::token::kind::key,
             {(int8_t*)d2t(cur_point2 / ring_points.size()).data(), 8}};
        auto endpoints2 = ars_ptr->get_natural_endpoints(t2);

        endpoints_check(ars_ptr, endpoints2);
        BOOST_CHECK(cache_hit_count + 1 == ars_ptr->get_cache_hits_count());
        BOOST_CHECK(endpoints1 == endpoints2);
    }
}

future<> simple_test() {
    utils::fb_utilities::set_broadcast_address(gms::inet_address("localhost"));
    utils::fb_utilities::set_broadcast_rpc_address(gms::inet_address("localhost"));

    // Create the RackInferringSnitch
    return i_endpoint_snitch::create_snitch("RackInferringSnitch").then(
        [] {

        lw_shared_ptr<token_metadata> tm = make_lw_shared<token_metadata>();
        std::vector<ring_point> ring_points = {
            { 1.0,  inet_address("192.100.10.1") },
            { 2.0,  inet_address("192.101.10.1") },
            { 3.0,  inet_address("192.102.10.1") },
            { 4.0,  inet_address("192.100.20.1") },
            { 5.0,  inet_address("192.101.20.1") },
            { 6.0,  inet_address("192.102.20.1") },
            { 7.0,  inet_address("192.100.30.1") },
            { 8.0,  inet_address("192.101.30.1") },
            { 9.0,  inet_address("192.102.30.1") },
            { 10.0, inet_address("192.102.40.1") },
            { 11.0, inet_address("192.102.40.2") }
        };
        // Initialize the token_metadata
        for (unsigned i = 0; i < ring_points.size(); i++) {
            tm->update_normal_token(
                {dht::token::kind::key,
                 {(int8_t*)d2t(ring_points[i].point / ring_points.size()).data(), 8}
                },
                ring_points[i].host);
        }

        /////////////////////////////////////
        // Create the replication strategy
        std::map<sstring, sstring> options323 = {
            {"100", "3"},
            {"101", "2"},
            {"102", "3"}
        };

        auto ars_uptr = abstract_replication_strategy::create_replication_strategy(
            "test keyspace", "NetworkTopologyStrategy", *tm, options323);

        auto ars_ptr = ars_uptr.get();

        full_ring_check(ring_points, options323, ars_ptr);

        ///////////////
        // Create the replication strategy
        std::map<sstring, sstring> options320 = {
            {"100", "3"},
            {"101", "2"},
            {"102", "0"}
        };

        ars_uptr = abstract_replication_strategy::create_replication_strategy(
            "test keyspace", "NetworkTopologyStrategy", *tm, options320);

        ars_ptr = ars_uptr.get();

        full_ring_check(ring_points, options320, ars_ptr);

        //
        // Check cache invalidation: invalidate the cache and run a full ring
        // check once again. If cache is not properly invalidated one of the
        // points will be taken from the cache when it shouldn't and the
        // corresponding check will fail.
        //
        tm->invalidate_cached_rings();
        full_ring_check(ring_points, options320, ars_ptr);

        return i_endpoint_snitch::stop_snitch();
    });
}

future<> heavy_origin_test() {
    utils::fb_utilities::set_broadcast_address(gms::inet_address("localhost"));
    utils::fb_utilities::set_broadcast_rpc_address(gms::inet_address("localhost"));

    // Create the RackInferringSnitch
    return i_endpoint_snitch::create_snitch("RackInferringSnitch").then(
        [] {
        std::vector<int> dc_racks = {2, 4, 8};
        std::vector<int> dc_endpoints = {128, 256, 512};
        std::vector<int> dc_replication = {2, 6, 6};

        lw_shared_ptr<token_metadata> tm = make_lw_shared<token_metadata>();
        std::map<sstring, sstring> config_options;
        std::unordered_map<inet_address, std::unordered_set<token>> tokens;
        std::vector<ring_point> ring_points;

        size_t total_eps = 0;
        for (size_t dc = 0; dc < dc_racks.size(); ++dc) {
            for (int rack = 0; rack < dc_racks[dc]; ++rack) {
                total_eps += dc_endpoints[dc]/dc_racks[dc];
            }
        }

        int total_rf = 0;
        double token_point = 1.0;
        for (size_t dc = 0; dc < dc_racks.size(); ++dc) {
            total_rf += dc_replication[dc];
            config_options.emplace(to_sstring(dc),
                                   to_sstring(dc_replication[dc]));
            for (int rack = 0; rack < dc_racks[dc]; ++rack) {
                for (int ep = 1; ep <= dc_endpoints[dc]/dc_racks[dc]; ++ep) {

                    // 10.dc.rack.ep
                    int32_t ip = 0x0a000000 + ((int8_t)dc << 16) +
                                 ((int8_t)rack << 8) + (int8_t)ep;
                    inet_address address(ip);
                    ring_point rp = {token_point, address};

                    ring_points.emplace_back(rp);
                    tokens[address].emplace(token{dht::token::kind::key,
                            {(int8_t*)d2t(token_point / total_eps).data(), 8}});

                    nlogger.debug("adding node {} at {}", address, token_point);

                    token_point++;
                }
            }
        }

        tm->update_normal_tokens(tokens);

        auto ars_uptr = abstract_replication_strategy::create_replication_strategy(
            "test keyspace", "NetworkTopologyStrategy", *tm, config_options);

        auto ars_ptr = ars_uptr.get();

        full_ring_check(ring_points, config_options, ars_ptr);

        return i_endpoint_snitch::stop_snitch();
    });
}

SEASTAR_TEST_CASE(NetworkTopologyStrategy_simple) {
    return simple_test();
}

SEASTAR_TEST_CASE(NetworkTopologyStrategy_heavy) {
    return heavy_origin_test();
}
<|endoftext|>


<commit_before>#include <shogun/lib/config.h>
#ifdef HAVE_EIGEN3

#include <shogun/labels/RegressionLabels.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/regression/GaussianProcessRegression.h>
#include <shogun/regression/gp/ExactInferenceMethod.h>
#include <shogun/regression/gp/ZeroMean.h>
#include <shogun/regression/gp/GaussianLikelihood.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(GaussianProcessRegression,apply_regression)
{
	/* create some easy regression data: 1d noisy sine wave */
	index_t n=3;

	SGMatrix<float64_t> X(1, n);
	SGMatrix<float64_t> X_test(1, n);
	SGVector<float64_t> Y(n);

	X[0]=0;
	X[1]=1.1;
	X[2]=2.2;

	X_test[0]=0.3;
	X_test[1]=1.3;
	X_test[2]=2.5;

	for (index_t i=0; i<n; ++i)
	{
		Y[i]=CMath::sin(X(0, i));
	}

	/* shogun representation */
	CDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);
	CDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);
	CRegressionLabels* label_train=new CRegressionLabels(Y);

	/* specity GPR with exact inference */
	float64_t sigma=1;
	float64_t shogun_sigma=sigma*sigma*2;
	CGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);
	CZeroMean* mean=new CZeroMean();
	CGaussianLikelihood* lik=new CGaussianLikelihood();
	lik->set_sigma(1);
	CExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,
			mean, label_train, lik);
	CGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,
			feat_train, label_train);

	/* perform inference */
	gpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);
	CRegressionLabels* predictions=gpr->apply_regression(feat_test);

	/* do some checks against gpml toolbox*/

	/* m =

   0.221198406887592
   0.537437461176145
   0.431605035301329 */
	SGVector<float64_t> prediction_vector=predictions->get_labels();
	EXPECT_LE(CMath::abs(prediction_vector[0]-0.221198406887592), 10E-15);
	EXPECT_LE(CMath::abs(prediction_vector[1]-0.537437461176145), 10E-15);
	EXPECT_LE(CMath::abs(prediction_vector[2]-0.431605035301329), 10E-15);

	SG_UNREF(predictions);
	SG_UNREF(gpr);
}

TEST(GaussianProcessRegression,apply_regression_larger_test)
{
	/* create some easy regression data: 1d noisy sine wave */
	index_t n=3;
	index_t n_test=5;

	SGMatrix<float64_t> X(1, n);
	SGMatrix<float64_t> X_test(1, n_test);
	SGVector<float64_t> Y(n);

	X[0]=0;
	X[1]=1.1;
	X[2]=2.2;

	X_test[0]=0.3;
	X_test[1]=1.3;
	X_test[2]=2.5;
	X_test[2]=2.7;
	X_test[2]=3.1;

	for (index_t i=0; i<n; ++i)
	{
		Y[i]=CMath::sin(X(0, i));
	}

	/* shogun representation */
	CDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);
	CDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);
	CRegressionLabels* label_train=new CRegressionLabels(Y);

	/* specity GPR with exact inference */
	float64_t sigma=1;
	float64_t shogun_sigma=sigma*sigma*2;
	CGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);
	CZeroMean* mean=new CZeroMean();
	CGaussianLikelihood* lik=new CGaussianLikelihood();
	lik->set_sigma(1);
	CExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,
			mean, label_train, lik);
	CGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,
			feat_train, label_train);

	/* perform inference */
	gpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);
	CRegressionLabels* predictions=gpr->apply_regression(feat_test);

	/* do some checks against gpml toolbox*/

	/* m =

   0.221198406887592
   0.537437461176145
   0.431605035301329
   0.373048041692408
   0.253688340068952 */
	SGVector<float64_t> prediction_vector=predictions->get_labels();
//	EXPECT_LE(CMath::abs(prediction_vector[0]-0.221198406887592), 10E-15);
//	EXPECT_LE(CMath::abs(prediction_vector[1]-0.537437461176145), 10E-15);
//	EXPECT_LE(CMath::abs(prediction_vector[2]-0.431605035301329), 10E-15);
//	EXPECT_LE(CMath::abs(prediction_vector[2]-0.373048041692408), 10E-15);
//	EXPECT_LE(CMath::abs(prediction_vector[2]-0.253688340068952), 10E-15);

	SG_UNREF(predictions);
	SG_UNREF(gpr);
}

TEST(GaussianProcessRegression, get_mean_vector)
{
	/* create some easy regression data: 1d noisy sine wave */
	index_t n=3;

	SGMatrix<float64_t> X(1, n);
	SGMatrix<float64_t> X_test(1, n);
	SGVector<float64_t> Y(n);

	X[0]=0;
	X[1]=1.1;
	X[2]=2.2;

	X_test[0]=0.3;
	X_test[1]=1.3;
	X_test[2]=2.5;

	for (index_t i=0; i<n; ++i)
	{
		Y[i]=CMath::sin(X(0, i));
	}

	/* shogun representation */
	CDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);
	CDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);
	CRegressionLabels* label_train=new CRegressionLabels(Y);

	/* specity GPR with exact inference */
	float64_t sigma=1;
	float64_t shogun_sigma=sigma*sigma*2;
	CGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);
	CZeroMean* mean=new CZeroMean();
	CGaussianLikelihood* lik=new CGaussianLikelihood();
	lik->set_sigma(1);
	CExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,
			mean, label_train, lik);
	CGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,
			feat_train, label_train);

	/* perform inference */
	gpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);
	CRegressionLabels* predictions=gpr->apply_regression(feat_test);

	/* do some checks against gpml toolbox*/

	/* m =

   0.221198406887592
   0.537437461176145
   0.431605035301329 */
	SGVector<float64_t> mean_vector=gpr->get_mean_vector();
	EXPECT_LE(CMath::abs(mean_vector[0]-0.221198406887592), 10E-15);
	EXPECT_LE(CMath::abs(mean_vector[1]-0.537437461176145), 10E-15);
	EXPECT_LE(CMath::abs(mean_vector[2]-0.431605035301329), 10E-15);

	SG_UNREF(predictions);
	SG_UNREF(gpr);
}

TEST(GaussianProcessRegression, get_covariance_vector)
{
	/* create some easy regression data: 1d noisy sine wave */
	index_t n=3;

	SGMatrix<float64_t> X(1, n);
	SGMatrix<float64_t> X_test(1, n);
	SGVector<float64_t> Y(n);

	X[0]=0;
	X[1]=1.1;
	X[2]=2.2;

	X_test[0]=0.3;
	X_test[1]=1.3;
	X_test[2]=2.5;

	for (index_t i=0; i<n; ++i)
	{
		Y[i]=CMath::sin(X(0, i));
	}

	/* shogun representation */
	CDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);
	CDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);
	CRegressionLabels* label_train=new CRegressionLabels(Y);

	/* specity GPR with exact inference */
	float64_t sigma=1;
	float64_t shogun_sigma=sigma*sigma*2;
	CGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);
	CZeroMean* mean=new CZeroMean();
	CGaussianLikelihood* lik=new CGaussianLikelihood();
	lik->set_sigma(1);
	CExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,
			mean, label_train, lik);
	CGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,
			feat_train, label_train);

	/* perform inference */
	gpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);
	CRegressionLabels* predictions=gpr->apply_regression(feat_test);

	/* do some checks against gpml toolbox*/

	/* s2 =

   1.426104216614624
   1.416896787316447
   1.535464779087576 */
	SGVector<float64_t> covariance_vector=gpr->get_covariance_vector();
	EXPECT_LE(CMath::abs(covariance_vector[0]-1.426104216614624), 10E-15);
	EXPECT_LE(CMath::abs(covariance_vector[1]-1.416896787316447), 10E-15);
	EXPECT_LE(CMath::abs(covariance_vector[2]-1.535464779087576), 10E-15);

	SG_UNREF(predictions);
	SG_UNREF(gpr);
}

#endif
<commit_msg>fixed memory errors and added asserts again<commit_after>#include <shogun/lib/config.h>
#ifdef HAVE_EIGEN3

#include <shogun/labels/RegressionLabels.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/regression/GaussianProcessRegression.h>
#include <shogun/regression/gp/ExactInferenceMethod.h>
#include <shogun/regression/gp/ZeroMean.h>
#include <shogun/regression/gp/GaussianLikelihood.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(GaussianProcessRegression,apply_regression)
{
	/* create some easy regression data: 1d noisy sine wave */
	index_t n=3;

	SGMatrix<float64_t> X(1, n);
	SGMatrix<float64_t> X_test(1, n);
	SGVector<float64_t> Y(n);

	X[0]=0;
	X[1]=1.1;
	X[2]=2.2;

	X_test[0]=0.3;
	X_test[1]=1.3;
	X_test[2]=2.5;

	for (index_t i=0; i<n; ++i)
	{
		Y[i]=CMath::sin(X(0, i));
	}

	/* shogun representation */
	CDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);
	CDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);
	CRegressionLabels* label_train=new CRegressionLabels(Y);

	/* specity GPR with exact inference */
	float64_t sigma=1;
	float64_t shogun_sigma=sigma*sigma*2;
	CGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);
	CZeroMean* mean=new CZeroMean();
	CGaussianLikelihood* lik=new CGaussianLikelihood();
	lik->set_sigma(1);
	CExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,
			mean, label_train, lik);
	CGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,
			feat_train, label_train);

	/* perform inference */
	gpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);
	CRegressionLabels* predictions=gpr->apply_regression(feat_test);

	/* do some checks against gpml toolbox*/

	/* m =

   0.221198406887592
   0.537437461176145
   0.431605035301329 */
	SGVector<float64_t> prediction_vector=predictions->get_labels();
	EXPECT_LE(CMath::abs(prediction_vector[0]-0.221198406887592), 10E-15);
	EXPECT_LE(CMath::abs(prediction_vector[1]-0.537437461176145), 10E-15);
	EXPECT_LE(CMath::abs(prediction_vector[2]-0.431605035301329), 10E-15);

	SG_UNREF(predictions);
	SG_UNREF(gpr);
}

TEST(GaussianProcessRegression,apply_regression_larger_test)
{
	/* create some easy regression data: 1d noisy sine wave */
	index_t n=3;
	index_t n_test=5;

	SGMatrix<float64_t> X(1, n);
	SGMatrix<float64_t> X_test(1, n_test);
	SGVector<float64_t> Y(n);

	X[0]=0;
	X[1]=1.1;
	X[2]=2.2;

	X_test[0]=0.3;
	X_test[1]=1.3;
	X_test[2]=2.5;
	X_test[3]=2.7;
	X_test[4]=3.1;

	for (index_t i=0; i<n; ++i)
	{
		Y[i]=CMath::sin(X(0, i));
	}

	/* shogun representation */
	CDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);
	CDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);
	CRegressionLabels* label_train=new CRegressionLabels(Y);

	/* specity GPR with exact inference */
	float64_t sigma=1;
	float64_t shogun_sigma=sigma*sigma*2;
	CGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);
	CZeroMean* mean=new CZeroMean();
	CGaussianLikelihood* lik=new CGaussianLikelihood();
	lik->set_sigma(1);
	CExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,
			mean, label_train, lik);
	CGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,
			feat_train, label_train);

	/* perform inference */
	gpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);
	CRegressionLabels* predictions=gpr->apply_regression(feat_test);

	/* do some checks against gpml toolbox*/

	/* m =

   0.221198406887592
   0.537437461176145
   0.431605035301329
   0.373048041692408
   0.253688340068952 */
	SGVector<float64_t> prediction_vector=predictions->get_labels();
	EXPECT_LE(CMath::abs(prediction_vector[0]-0.221198406887592), 10E-15);
	EXPECT_LE(CMath::abs(prediction_vector[1]-0.537437461176145), 10E-15);
	EXPECT_LE(CMath::abs(prediction_vector[2]-0.431605035301329), 10E-15);
	EXPECT_LE(CMath::abs(prediction_vector[2]-0.373048041692408), 10E-15);
	EXPECT_LE(CMath::abs(prediction_vector[2]-0.253688340068952), 10E-15);

	SG_UNREF(predictions);
	SG_UNREF(gpr);
}

TEST(GaussianProcessRegression, get_mean_vector)
{
	/* create some easy regression data: 1d noisy sine wave */
	index_t n=3;

	SGMatrix<float64_t> X(1, n);
	SGMatrix<float64_t> X_test(1, n);
	SGVector<float64_t> Y(n);

	X[0]=0;
	X[1]=1.1;
	X[2]=2.2;

	X_test[0]=0.3;
	X_test[1]=1.3;
	X_test[2]=2.5;

	for (index_t i=0; i<n; ++i)
	{
		Y[i]=CMath::sin(X(0, i));
	}

	/* shogun representation */
	CDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);
	CDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);
	CRegressionLabels* label_train=new CRegressionLabels(Y);

	/* specity GPR with exact inference */
	float64_t sigma=1;
	float64_t shogun_sigma=sigma*sigma*2;
	CGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);
	CZeroMean* mean=new CZeroMean();
	CGaussianLikelihood* lik=new CGaussianLikelihood();
	lik->set_sigma(1);
	CExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,
			mean, label_train, lik);
	CGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,
			feat_train, label_train);

	/* perform inference */
	gpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);
	CRegressionLabels* predictions=gpr->apply_regression(feat_test);

	/* do some checks against gpml toolbox*/

	/* m =

   0.221198406887592
   0.537437461176145
   0.431605035301329 */
	SGVector<float64_t> mean_vector=gpr->get_mean_vector();
	EXPECT_LE(CMath::abs(mean_vector[0]-0.221198406887592), 10E-15);
	EXPECT_LE(CMath::abs(mean_vector[1]-0.537437461176145), 10E-15);
	EXPECT_LE(CMath::abs(mean_vector[2]-0.431605035301329), 10E-15);

	SG_UNREF(predictions);
	SG_UNREF(gpr);
}

TEST(GaussianProcessRegression, get_covariance_vector)
{
	/* create some easy regression data: 1d noisy sine wave */
	index_t n=3;

	SGMatrix<float64_t> X(1, n);
	SGMatrix<float64_t> X_test(1, n);
	SGVector<float64_t> Y(n);

	X[0]=0;
	X[1]=1.1;
	X[2]=2.2;

	X_test[0]=0.3;
	X_test[1]=1.3;
	X_test[2]=2.5;

	for (index_t i=0; i<n; ++i)
	{
		Y[i]=CMath::sin(X(0, i));
	}

	/* shogun representation */
	CDenseFeatures<float64_t>* feat_train=new CDenseFeatures<float64_t>(X);
	CDenseFeatures<float64_t>* feat_test=new CDenseFeatures<float64_t>(X_test);
	CRegressionLabels* label_train=new CRegressionLabels(Y);

	/* specity GPR with exact inference */
	float64_t sigma=1;
	float64_t shogun_sigma=sigma*sigma*2;
	CGaussianKernel* kernel=new CGaussianKernel(10, shogun_sigma);
	CZeroMean* mean=new CZeroMean();
	CGaussianLikelihood* lik=new CGaussianLikelihood();
	lik->set_sigma(1);
	CExactInferenceMethod* inf=new CExactInferenceMethod(kernel, feat_train,
			mean, label_train, lik);
	CGaussianProcessRegression* gpr=new CGaussianProcessRegression(inf,
			feat_train, label_train);

	/* perform inference */
	gpr->set_return_type(CGaussianProcessRegression::GP_RETURN_MEANS);
	CRegressionLabels* predictions=gpr->apply_regression(feat_test);

	/* do some checks against gpml toolbox*/

	/* s2 =

   1.426104216614624
   1.416896787316447
   1.535464779087576 */
	SGVector<float64_t> covariance_vector=gpr->get_covariance_vector();
	EXPECT_LE(CMath::abs(covariance_vector[0]-1.426104216614624), 10E-15);
	EXPECT_LE(CMath::abs(covariance_vector[1]-1.416896787316447), 10E-15);
	EXPECT_LE(CMath::abs(covariance_vector[2]-1.535464779087576), 10E-15);

	SG_UNREF(predictions);
	SG_UNREF(gpr);
}

#endif
<|endoftext|>


<commit_before>#include "tree.hh"
#include "tree-entry.hh"

namespace mimosa
{
  namespace git
  {
    Tree::Tree(git_repository * repo,
               const git_oid *  id)
      : tree_(nullptr)
    {
      git_tree_lookup(&tree_, repo, id);
    }

    Tree::Tree(git_repository *    repo,
               const git_oid *     id,
               const std::string & directory)
      : tree_(nullptr)
    {
      if (directory.empty()) {
        git_tree_lookup(&tree_, repo, id);
        return;
      }

      Tree      root(repo, id);
      TreeEntry entry;
      if (git_tree_entry_bypath(entry.ref(), root, directory.c_str()))
        return;

      if (git_tree_entry_type(entry) != GIT_OBJ_TREE)
        return;

      git_tree_lookup(&tree_, repo, git_tree_entry_id(entry));
    }

    Tree::~Tree()
    {
      git_tree_free(tree_);
    }
  }
}
<commit_msg>git::Tree: allow null id, to have a null tree<commit_after>#include "tree.hh"
#include "tree-entry.hh"

namespace mimosa
{
  namespace git
  {
    Tree::Tree(git_repository * repo,
               const git_oid *  id)
      : tree_(nullptr)
    {
      if (id)
        git_tree_lookup(&tree_, repo, id);
    }

    Tree::Tree(git_repository *    repo,
               const git_oid *     id,
               const std::string & directory)
      : tree_(nullptr)
    {
      if (directory.empty()) {
        git_tree_lookup(&tree_, repo, id);
        return;
      }

      Tree      root(repo, id);
      TreeEntry entry;
      if (git_tree_entry_bypath(entry.ref(), root, directory.c_str()))
        return;

      if (git_tree_entry_type(entry) != GIT_OBJ_TREE)
        return;

      git_tree_lookup(&tree_, repo, git_tree_entry_id(entry));
    }

    Tree::~Tree()
    {
      git_tree_free(tree_);
    }
  }
}
<|endoftext|>


<commit_before>#include "networkregistrationstub.h"

#include <QStringList>
#include <QDebug>

namespace Cellular
{

static NetworkRegistration::Mode currentMode = NetworkRegistration::Automatic;

AvailableOperator::AvailableOperator(const QString &mnc, const QString &mcc, const QString &name,
                                     AvailableOperator::Availability availability, QObject *parent) :
        QObject(parent)
{
    setMnc(mnc);
    setMcc(mcc);
    setName(name);
    setAvailability(availability);
}

AvailableOperator::~AvailableOperator()
{
}

void AvailableOperator::setMnc(const QString &mnc)
{
    currentMnc = mnc;
}

void AvailableOperator::setMcc(const QString &mcc)
{
    currentMcc = mcc;
}

void AvailableOperator::setName(const QString &name)
{
    currentName = name;
}

void AvailableOperator::setAvailability(AvailableOperator::Availability availability)
{
    currentAvailibility = availability;
}

QString AvailableOperator::mnc() const
{
    return currentMnc;
}

QString AvailableOperator::mcc() const
{
    return currentMcc;
}

QString AvailableOperator::name() const
{
    return currentName;
}

AvailableOperator::Availability AvailableOperator::availability() const
{
    return currentAvailibility;
}

NetworkRegistration::NetworkRegistration(QObject *parent) :
        QObject(parent),
        success(true),
        networkOperator(NULL)
{
}

NetworkRegistration::~NetworkRegistration()
{
    for(int i=0; i<operators.size(); ++i) {
        AvailableOperator *oper = operators.at(i);
        delete oper;
        oper = NULL;
    }
}

void NetworkRegistration::init(NetworkOperator *networkOperator)
{
    this->networkOperator = networkOperator;
}

NetworkRegistration::Mode NetworkRegistration::mode() const
{
    return currentMode;
}

void NetworkRegistration::selectOperator()
{
    currentMode = NetworkRegistration::Automatic;
    emit selectionCompleted(true, QString(""));
}

void NetworkRegistration::selectOperator(const QString &mnc, const QString &mcc)
{
    currentMode = NetworkRegistration::Manual;
    for(int i=0; i<operators.size(); ++i) {
        if(operators.at(i)->mnc() == mnc && operators.at(i)->mcc() == mcc) {
            operators.at(i)->setAvailability(AvailableOperator::Current);
            if(networkOperator != NULL) {
                networkOperator->setName(operators.at(i)->name());
                networkOperator->setMnc(operators.at(i)->mnc());
                networkOperator->setMcc(operators.at(i)->mcc());
            }
        }
        else
            operators.at(i)->setAvailability(AvailableOperator::Available);
    }

    emit selectionCompleted(true, QString(""));
}

void NetworkRegistration::queryAvailableOperators()
{
    for(int i=0; i<names.size(); ++i)
        this->addOperator(names.at(i), mncs.at(i), mccs.at(i), availabilities.at(i));

    if(success)
        emit availableOperators(true, operators, QString(""));
    else
        emit availableOperators(false, operators, QString("empty"));
}

void NetworkRegistration::addOperator(const QString &name, const QString &mnc, const QString &mcc, AvailableOperator::Availability availability)
{
    operators << new AvailableOperator(mnc, mcc, name, availability);
}

void NetworkRegistration::setQuerySuccess(bool success)
{
    this->success = success;
}

}
<commit_msg>remove needless lines<commit_after>#include "networkregistrationstub.h"

#include <QStringList>
#include <QDebug>

namespace Cellular
{

static NetworkRegistration::Mode currentMode = NetworkRegistration::Automatic;

AvailableOperator::AvailableOperator(const QString &mnc, const QString &mcc, const QString &name,
                                     AvailableOperator::Availability availability, QObject *parent) :
        QObject(parent)
{
    setMnc(mnc);
    setMcc(mcc);
    setName(name);
    setAvailability(availability);
}

AvailableOperator::~AvailableOperator()
{
}

void AvailableOperator::setMnc(const QString &mnc)
{
    currentMnc = mnc;
}

void AvailableOperator::setMcc(const QString &mcc)
{
    currentMcc = mcc;
}

void AvailableOperator::setName(const QString &name)
{
    currentName = name;
}

void AvailableOperator::setAvailability(AvailableOperator::Availability availability)
{
    currentAvailibility = availability;
}

QString AvailableOperator::mnc() const
{
    return currentMnc;
}

QString AvailableOperator::mcc() const
{
    return currentMcc;
}

QString AvailableOperator::name() const
{
    return currentName;
}

AvailableOperator::Availability AvailableOperator::availability() const
{
    return currentAvailibility;
}

NetworkRegistration::NetworkRegistration(QObject *parent) :
        QObject(parent),
        success(true),
        networkOperator(NULL)
{
}

NetworkRegistration::~NetworkRegistration()
{
    for(int i=0; i<operators.size(); ++i) {
        AvailableOperator *oper = operators.at(i);
        delete oper;
        oper = NULL;
    }
}

void NetworkRegistration::init(NetworkOperator *networkOperator)
{
    this->networkOperator = networkOperator;
}

NetworkRegistration::Mode NetworkRegistration::mode() const
{
    return currentMode;
}

void NetworkRegistration::selectOperator()
{
    currentMode = NetworkRegistration::Automatic;
    emit selectionCompleted(true, QString(""));
}

void NetworkRegistration::selectOperator(const QString &mnc, const QString &mcc)
{
    currentMode = NetworkRegistration::Manual;
    for(int i=0; i<operators.size(); ++i) {
        if(operators.at(i)->mnc() == mnc && operators.at(i)->mcc() == mcc) {
            operators.at(i)->setAvailability(AvailableOperator::Current);
            if(networkOperator != NULL) {
                networkOperator->setName(operators.at(i)->name());
                networkOperator->setMnc(operators.at(i)->mnc());
                networkOperator->setMcc(operators.at(i)->mcc());
            }
        }
        else
            operators.at(i)->setAvailability(AvailableOperator::Available);
    }

    emit selectionCompleted(true, QString(""));
}

void NetworkRegistration::queryAvailableOperators()
{
    if(success)
        emit availableOperators(true, operators, QString(""));
    else
        emit availableOperators(false, operators, QString("empty"));
}

void NetworkRegistration::addOperator(const QString &name, const QString &mnc, const QString &mcc, AvailableOperator::Availability availability)
{
    operators << new AvailableOperator(mnc, mcc, name, availability);
}

void NetworkRegistration::setQuerySuccess(bool success)
{
    this->success = success;
}

}
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_testshl2.hxx"

#include <stdio.h>
#include <stdlib.h>

#ifdef SOLARIS
#include <sys/time.h>
#endif

#ifdef WNT
// #define UNDER_WINDOWS_DEBUGGING
// Nice feature, to debug under windows, install msdev locally and use DebugBreak() to stop a new process at a point you want.
#ifdef UNDER_WINDOWS_DEBUGGING
#include <tools/presys.h>
#include <windows.h>
#include <tools/postsys.h>

#define VCL_NEED_BASETSD

#endif /* UNDER_WINDOWS_DEBUGGING */
#endif /* WNT */

#include <iostream>
#include <vector>

#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif

#include "filehelper.hxx"
#include "getopt.hxx"

// #include <osl/time.h>

using namespace std;

// -----------------------------------------------------------------------------

/**
 * display usage screen
 */

void usage()
{
    fprintf( stdout,
            "USAGE: testshl shlname [-boom][-verbose][-log][-his][-msg]\n" );
    exit(0);
}

// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
    static char* optionSet[] = {
        "-boom,     stop near error position, exception only",
        "-mode=s,   the output mode, emacs, xml, old. Default is -mode old",
        "-logPath=s, destination path for logging",
        "-tc=s@,    name(s) of testcase(s) to generate",
        "-h:s,      display help or help on option",
        "-help:s,   see -h",
        NULL
    };

    GetOpt opt( argv, optionSet );

    // someone indicates that he needs help
    if ( opt.hasOpt( "-h" ) || opt.hasOpt( "-help" ) )
    {
        opt.showUsage();
        // exit(0);
    }

    // get path for logging stuff..
    rtl::OString logPth;
    // ...if available
    if ( opt.hasOpt( "-logPth" ))
    {
        logPth = opt.getOpt( "-logPth" );
    }

    rtl::OString param;
    if ( ! opt.getParams().empty() ) {
        param = opt.getFirstParam();

        std::cout << "all non '-' Parameter values" << std::endl;

        vector<rtl::OString>& aVec = opt.getParams();
        for(vector<rtl::OString>::const_iterator it = aVec.begin();
            it != aVec.end();
            ++it)
        {
            std::cout << (*it).getStr() << std::endl;
        }
    }

    if ( opt.hasOpt("-tc"))
    {
        std::cout << "Parameter -tc" << std::endl;
        vector<rtl::OString>& aVec = opt.getOptVec( "-tc" );

        for(vector<rtl::OString>::const_iterator it = aVec.begin();
            it != aVec.end();
            ++it)
        {
            std::cout << (*it).getStr() << std::endl;
        }
    }

    return 0;
}

<commit_msg>INTEGRATION: CWS rpt23fix02 (1.3.24); FILE MERGED 2007/07/23 11:15:59 lla 1.3.24.1: #i79902# make demos buildable<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: test_getopt.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2007-08-03 10:17:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_testshl2.hxx"

#include <stdio.h>
#include <stdlib.h>

#ifdef SOLARIS
#include <sys/time.h>
#endif

#ifdef WNT
// #define UNDER_WINDOWS_DEBUGGING
// Nice feature, to debug under windows, install msdev locally and use DebugBreak() to stop a new process at a point you want.
#ifdef UNDER_WINDOWS_DEBUGGING
#include <tools/presys.h>
#include <windows.h>
#include <tools/postsys.h>

#define VCL_NEED_BASETSD

#endif /* UNDER_WINDOWS_DEBUGGING */
#endif /* WNT */

#include <iostream>
#include <vector>

#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif

#include "filehelper.hxx"
#include "getopt.hxx"

// #include <osl/time.h>

using namespace std;

// -----------------------------------------------------------------------------

/**
 * display usage screen
 */

void usage()
{
    fprintf( stdout,
            "USAGE: testshl shlname [-boom][-verbose][-log][-his][-msg]\n" );
    exit(0);
}

// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
    (void) argc;
    static char const* optionSet[] = {
        "-boom,     stop near error position, exception only",
        "-mode=s,   the output mode, emacs, xml, old. Default is -mode old",
        "-logPath=s, destination path for logging",
        "-tc=s@,    name(s) of testcase(s) to generate",
        "-h:s,      display help or help on option",
        "-help:s,   see -h",
        NULL
    };

    GetOpt opt( argv, optionSet );

    // someone indicates that he needs help
    if ( opt.hasOpt( "-h" ) || opt.hasOpt( "-help" ) )
    {
        opt.showUsage();
        // exit(0);
    }

    // get path for logging stuff..
    rtl::OString logPth;
    // ...if available
    if ( opt.hasOpt( "-logPth" ))
    {
        logPth = opt.getOpt( "-logPth" );
    }

    rtl::OString param;
    if ( ! opt.getParams().empty() ) {
        param = opt.getFirstParam();

        std::cout << "all non '-' Parameter values" << std::endl;

        vector<rtl::OString>& aVec = opt.getParams();
        for(vector<rtl::OString>::const_iterator it = aVec.begin();
            it != aVec.end();
            ++it)
        {
            std::cout << (*it).getStr() << std::endl;
        }
    }

    if ( opt.hasOpt("-tc"))
    {
        std::cout << "Parameter -tc" << std::endl;
        vector<rtl::OString>& aVec = opt.getOptVec( "-tc" );

        for(vector<rtl::OString>::const_iterator it = aVec.begin();
            it != aVec.end();
            ++it)
        {
            std::cout << (*it).getStr() << std::endl;
        }
    }

    return 0;
}

<|endoftext|>


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

#include "Logger.h"
#include "RefCounter.h"

namespace mitlm {

////////////////////////////////////////////////////////////////////////////////

_RefCounter RefCounter;

_RefCounter::~_RefCounter() {
    if (!_map.empty()) {
        Logger::Error(1, "-- RefCounter----------\n");
	unordered_map<unsigned long, int>::const_iterator it;
        for (it = _map.begin(); it != _map.end(); ++it)
            Logger::Error(1, "map[%p] = %i\n", (void *)it->first, it->second);
        Logger::Error(1, "-----------------------\n\n");
    }
}

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

#include "Logger.h"
#include "RefCounter.h"

namespace mitlm {

////////////////////////////////////////////////////////////////////////////////

_RefCounter RefCounter;

_RefCounter::~_RefCounter() {
    if (!_map.empty()) {
        Logger::Error(1, "-- RefCounter----------\n");
	unordered_map<const void*, int>::const_iterator it;
        for (it = _map.begin(); it != _map.end(); ++it)
            Logger::Error(1, "map[%p] = %i\n", (void *)it->first, it->second);
        Logger::Error(1, "-----------------------\n\n");
    }
}

}
<|endoftext|>


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

#include "util_debug.h"

#include <stdlib.h>

#include "util_logging.h"
#include "util_string.h"

CCL_NAMESPACE_BEGIN

DebugFlags::CPU::CPU()
  : avx2(true),
    avx(true),
    sse41(true),
    sse3(true),
    sse2(true)
{
	reset();
}

void DebugFlags::CPU::reset()
{
#define STRINGIFY(x) #x
#define CHECK_CPU_FLAGS(flag, env) \
	do { \
		flag = (getenv(env) == NULL); \
		if(!flag) { \
			VLOG(1) << "Disabling " << STRINGIFY(flag) << " instruction set."; \
		} \
	} while(0)

	CHECK_CPU_FLAGS(avx2, "CYCLES_CPU_NO_AVX2");
	CHECK_CPU_FLAGS(avx, "CYCLES_CPU_NO_AVX");
	CHECK_CPU_FLAGS(sse41, "CYCLES_CPU_NO_SSE41");
	CHECK_CPU_FLAGS(sse3, "CYCLES_CPU_NO_SSE3");
	CHECK_CPU_FLAGS(sse2, "CYCLES_CPU_NO_SSE2");

#undef STRINGIFY
#undef CHECK_CPU_FLAGS
}

DebugFlags::OpenCL::OpenCL()
  : device_type(DebugFlags::OpenCL::DEVICE_ALL),
    kernel_type(DebugFlags::OpenCL::KERNEL_DEFAULT),
    debug(false)
{
	reset();
}

void DebugFlags::OpenCL::reset()
{
	/* Initialize device type from environment variables. */
	device_type = DebugFlags::OpenCL::DEVICE_ALL;
	char *device = getenv("CYCLES_OPENCL_TEST");
	if(device) {
		if(strcmp(device, "NONE") == 0) {
			device_type = DebugFlags::OpenCL::DEVICE_NONE;
		}
		else if(strcmp(device, "ALL") == 0) {
			device_type = DebugFlags::OpenCL::DEVICE_ALL;
		}
		else if(strcmp(device, "DEFAULT") == 0) {
			device_type = DebugFlags::OpenCL::DEVICE_DEFAULT;
		}
		else if(strcmp(device, "CPU") == 0) {
			device_type = DebugFlags::OpenCL::DEVICE_CPU;
		}
		else if(strcmp(device, "GPU") == 0) {
			device_type = DebugFlags::OpenCL::DEVICE_GPU;
		}
		else if(strcmp(device, "ACCELERATOR") == 0) {
			device_type = DebugFlags::OpenCL::DEVICE_ACCELERATOR;
		}
	}
	/* Initialize kernel type from environment variables. */
	kernel_type = DebugFlags::OpenCL::KERNEL_DEFAULT;
	if(getenv("CYCLES_OPENCL_MEGA_KERNEL_TEST") != NULL) {
		kernel_type = DebugFlags::OpenCL::KERNEL_MEGA;
	}
	else if(getenv("CYCLES_OPENCL_SPLITKERNEL_TEST") != NULL) {
		kernel_type = DebugFlags::OpenCL::KERNEL_SPLIT;
	}
	/* Initialize other flags from environment variables. */
	debug = (getenv("CYCLES_OPENCL_DEBUG") != NULL);
}

DebugFlags::DebugFlags()
{
	/* Nothing for now. */
}

void DebugFlags::reset()
{
	cpu.reset();
	opencl.reset();
}

std::ostream& operator <<(std::ostream &os,
                          const DebugFlagsRef debug_flags)
{
	os << "CPU flags:\n"
	   << "  AVX2   : " << string_from_bool(debug_flags.cpu.avx2)  << "\n"
	   << "  AVX    : " << string_from_bool(debug_flags.cpu.avx)   << "\n"
	   << "  SSE4.1 : " << string_from_bool(debug_flags.cpu.sse41) << "\n"
	   << "  SSE3   : " << string_from_bool(debug_flags.cpu.sse3)  << "\n"
	   << "  SSE2   : " << string_from_bool(debug_flags.cpu.sse2)  << "\n";

	const char *opencl_device_type,
	           *opencl_kernel_type;
	switch(debug_flags.opencl.device_type) {
		case DebugFlags::OpenCL::DEVICE_NONE:
			opencl_device_type = "NONE";
			break;
		case DebugFlags::OpenCL::DEVICE_ALL:
			opencl_device_type = "ALL";
			break;
		case DebugFlags::OpenCL::DEVICE_DEFAULT:
			opencl_device_type = "DEFAULT";
			break;
		case DebugFlags::OpenCL::DEVICE_CPU:
			opencl_device_type = "CPU";
			break;
		case DebugFlags::OpenCL::DEVICE_GPU:
			opencl_device_type = "GPU";
			break;
		case DebugFlags::OpenCL::DEVICE_ACCELERATOR:
			opencl_device_type = "ACCELERATOR";
			break;
	}
	switch(debug_flags.opencl.kernel_type) {
		case DebugFlags::OpenCL::KERNEL_DEFAULT:
			opencl_kernel_type = "DEFAULT";
			break;
		case DebugFlags::OpenCL::KERNEL_MEGA:
			opencl_kernel_type = "MEGA";
			break;
		case DebugFlags::OpenCL::KERNEL_SPLIT:
			opencl_kernel_type = "SPLIT";
			break;
	}
	os << "OpenCL flags:\n"
	   << "  Device type : " << opencl_device_type << "\n"
	   << "  Kernel type : " << opencl_kernel_type << "\n"
	   << "  Debug       : " << string_from_bool(debug_flags.opencl.debug)
	   << "\n";
	return os;
}

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

#include "util_debug.h"

#include <stdlib.h>

#include "util_logging.h"
#include "util_string.h"

CCL_NAMESPACE_BEGIN

DebugFlags::CPU::CPU()
  : avx2(true),
    avx(true),
    sse41(true),
    sse3(true),
    sse2(true)
{
	reset();
}

void DebugFlags::CPU::reset()
{
#define STRINGIFY(x) #x
#define CHECK_CPU_FLAGS(flag, env) \
	do { \
		flag = (getenv(env) == NULL); \
		if(!flag) { \
			VLOG(1) << "Disabling " << STRINGIFY(flag) << " instruction set."; \
		} \
	} while(0)

	CHECK_CPU_FLAGS(avx2, "CYCLES_CPU_NO_AVX2");
	CHECK_CPU_FLAGS(avx, "CYCLES_CPU_NO_AVX");
	CHECK_CPU_FLAGS(sse41, "CYCLES_CPU_NO_SSE41");
	CHECK_CPU_FLAGS(sse3, "CYCLES_CPU_NO_SSE3");
	CHECK_CPU_FLAGS(sse2, "CYCLES_CPU_NO_SSE2");

#undef STRINGIFY
#undef CHECK_CPU_FLAGS
}

DebugFlags::OpenCL::OpenCL()
  : device_type(DebugFlags::OpenCL::DEVICE_ALL),
    kernel_type(DebugFlags::OpenCL::KERNEL_DEFAULT),
    debug(false)
{
	reset();
}

void DebugFlags::OpenCL::reset()
{
	/* Initialize device type from environment variables. */
	device_type = DebugFlags::OpenCL::DEVICE_ALL;
	char *device = getenv("CYCLES_OPENCL_TEST");
	if(device) {
		if(strcmp(device, "NONE") == 0) {
			device_type = DebugFlags::OpenCL::DEVICE_NONE;
		}
		else if(strcmp(device, "ALL") == 0) {
			device_type = DebugFlags::OpenCL::DEVICE_ALL;
		}
		else if(strcmp(device, "DEFAULT") == 0) {
			device_type = DebugFlags::OpenCL::DEVICE_DEFAULT;
		}
		else if(strcmp(device, "CPU") == 0) {
			device_type = DebugFlags::OpenCL::DEVICE_CPU;
		}
		else if(strcmp(device, "GPU") == 0) {
			device_type = DebugFlags::OpenCL::DEVICE_GPU;
		}
		else if(strcmp(device, "ACCELERATOR") == 0) {
			device_type = DebugFlags::OpenCL::DEVICE_ACCELERATOR;
		}
	}
	/* Initialize kernel type from environment variables. */
	kernel_type = DebugFlags::OpenCL::KERNEL_DEFAULT;
	if(getenv("CYCLES_OPENCL_MEGA_KERNEL_TEST") != NULL) {
		kernel_type = DebugFlags::OpenCL::KERNEL_MEGA;
	}
	else if(getenv("CYCLES_OPENCL_SPLIT_KERNEL_TEST") != NULL) {
		kernel_type = DebugFlags::OpenCL::KERNEL_SPLIT;
	}
	/* Initialize other flags from environment variables. */
	debug = (getenv("CYCLES_OPENCL_DEBUG") != NULL);
}

DebugFlags::DebugFlags()
{
	/* Nothing for now. */
}

void DebugFlags::reset()
{
	cpu.reset();
	opencl.reset();
}

std::ostream& operator <<(std::ostream &os,
                          const DebugFlagsRef debug_flags)
{
	os << "CPU flags:\n"
	   << "  AVX2   : " << string_from_bool(debug_flags.cpu.avx2)  << "\n"
	   << "  AVX    : " << string_from_bool(debug_flags.cpu.avx)   << "\n"
	   << "  SSE4.1 : " << string_from_bool(debug_flags.cpu.sse41) << "\n"
	   << "  SSE3   : " << string_from_bool(debug_flags.cpu.sse3)  << "\n"
	   << "  SSE2   : " << string_from_bool(debug_flags.cpu.sse2)  << "\n";

	const char *opencl_device_type,
	           *opencl_kernel_type;
	switch(debug_flags.opencl.device_type) {
		case DebugFlags::OpenCL::DEVICE_NONE:
			opencl_device_type = "NONE";
			break;
		case DebugFlags::OpenCL::DEVICE_ALL:
			opencl_device_type = "ALL";
			break;
		case DebugFlags::OpenCL::DEVICE_DEFAULT:
			opencl_device_type = "DEFAULT";
			break;
		case DebugFlags::OpenCL::DEVICE_CPU:
			opencl_device_type = "CPU";
			break;
		case DebugFlags::OpenCL::DEVICE_GPU:
			opencl_device_type = "GPU";
			break;
		case DebugFlags::OpenCL::DEVICE_ACCELERATOR:
			opencl_device_type = "ACCELERATOR";
			break;
	}
	switch(debug_flags.opencl.kernel_type) {
		case DebugFlags::OpenCL::KERNEL_DEFAULT:
			opencl_kernel_type = "DEFAULT";
			break;
		case DebugFlags::OpenCL::KERNEL_MEGA:
			opencl_kernel_type = "MEGA";
			break;
		case DebugFlags::OpenCL::KERNEL_SPLIT:
			opencl_kernel_type = "SPLIT";
			break;
	}
	os << "OpenCL flags:\n"
	   << "  Device type : " << opencl_device_type << "\n"
	   << "  Kernel type : " << opencl_kernel_type << "\n"
	   << "  Debug       : " << string_from_bool(debug_flags.opencl.debug)
	   << "\n";
	return os;
}

CCL_NAMESPACE_END
<|endoftext|>


<commit_before>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2017 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *          Alexandre Fernandez <nerf@boboop.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "Directory.h"

#include <cstring>
#include <stdexcept>
#include <system_error>

#ifdef _WIN32
# include <windows.h>
#else
# include <cerrno>
# include <sys/types.h>
# include <sys/stat.h>
#endif

namespace medialibrary
{

namespace utils
{

namespace fs
{

namespace
{
    const auto ERR_FS_OBJECT_ACCESS = "Error accessing file-system object at ";
}

bool isDirectory( const std::string& path )
{
#ifdef _WIN32
    auto attr = GetFileAttributes( path.c_str() );
    if ( attr == INVALID_FILE_ATTRIBUTES )
    {
        DWORD errVal = GetLastError();
        std::error_code ec( errVal, std::system_category() );
        throw std::system_error( ec, ERR_FS_OBJECT_ACCESS + path );
    }
    return attr & FILE_ATTRIBUTE_DIRECTORY;
#else
    struct stat s;
    if ( lstat( path.c_str(), &s ) != 0 )
        throw std::system_error( errno, std::system_category(), ERR_FS_OBJECT_ACCESS + path );
    return S_ISDIR( s.st_mode );
#endif
}

}

}

}<commit_msg>utils: Fix win32 build<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2017 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *          Alexandre Fernandez <nerf@boboop.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "Directory.h"

#include <cstring>
#include <stdexcept>
#include <system_error>

#ifdef _WIN32
# include <windows.h>
#else
# include <cerrno>
# include <sys/types.h>
# include <sys/stat.h>
#endif

namespace medialibrary
{

namespace utils
{

namespace fs
{

namespace
{
    const auto ERR_FS_OBJECT_ACCESS = "Error accessing file-system object at ";
}

bool isDirectory( const std::string& path )
{
#ifdef _WIN32
    auto wpath = charset::ToWide( path.c_str() );
    auto attr = GetFileAttributes( wpath.get() );
    if ( attr == INVALID_FILE_ATTRIBUTES )
    {
        DWORD errVal = GetLastError();
        std::error_code ec( errVal, std::system_category() );
        throw std::system_error( ec, ERR_FS_OBJECT_ACCESS + path );
    }
    return attr & FILE_ATTRIBUTE_DIRECTORY;
#else
    struct stat s;
    if ( lstat( path.c_str(), &s ) != 0 )
        throw std::system_error( errno, std::system_category(), ERR_FS_OBJECT_ACCESS + path );
    return S_ISDIR( s.st_mode );
#endif
}

}

}

}<|endoftext|>


<commit_before>
#include <ionCore.h>
#include <catch.hpp>

class Component
{};

class AComponent : public Component
{};

class BComponent : public Component
{};

class CComponent : public AComponent
{};

TEST_CASE("IEntity::AddComponent")
{
	IEntity<Component> * Entity = new IEntity<Component>();
	AComponent * A = new AComponent();
	BComponent * B = new BComponent();
	CComponent * C = new CComponent();
	AComponent * A2 = new CComponent();

	REQUIRE(A == Entity->AddComponent(A));
	REQUIRE(A == Entity->AddComponent(A));
	REQUIRE(B == Entity->AddComponent(B));
	REQUIRE(C == Entity->AddComponent(C));
	REQUIRE(A2 == Entity->AddComponent(A2));
}

TEST_CASE("IEntity::GetComponentCount")
{
	IEntity<Component> * Entity = new IEntity<Component>();
	AComponent * A = new AComponent();
	BComponent * B = new BComponent();
	CComponent * C = new CComponent();
	AComponent * A2 = new CComponent();

	REQUIRE(Entity->GetComponentCount<AComponent>() == 0);
	REQUIRE(Entity->GetComponentCount<BComponent>() == 0);
	REQUIRE(Entity->GetComponentCount<CComponent>() == 0);
	Entity->AddComponent(A);
	REQUIRE(Entity->GetComponentCount<AComponent>() == 1);
	REQUIRE(Entity->GetComponentCount<BComponent>() == 0);
	REQUIRE(Entity->GetComponentCount<CComponent>() == 0);
	Entity->AddComponent(A);
	REQUIRE(Entity->GetComponentCount<AComponent>() == 2);
	REQUIRE(Entity->GetComponentCount<BComponent>() == 0);
	REQUIRE(Entity->GetComponentCount<CComponent>() == 0);
	Entity->AddComponent(B);
	REQUIRE(Entity->GetComponentCount<AComponent>() == 2);
	REQUIRE(Entity->GetComponentCount<BComponent>() == 1);
	REQUIRE(Entity->GetComponentCount<CComponent>() == 0);
	Entity->AddComponent(C);
	REQUIRE(Entity->GetComponentCount<AComponent>() == 2);
	REQUIRE(Entity->GetComponentCount<BComponent>() == 1);
	REQUIRE(Entity->GetComponentCount<CComponent>() == 1);
	Entity->AddComponent(A2);
	REQUIRE(Entity->GetComponentCount<AComponent>() == 3);
	REQUIRE(Entity->GetComponentCount<BComponent>() == 1);
	REQUIRE(Entity->GetComponentCount<CComponent>() == 1);
}
<commit_msg>Finish ionComponent tests<commit_after>
#include <ionCore.h>
#include <catch.hpp>

class Component
{};

class AComponent : public Component
{
public:
	bool foo()
	{
		return true;
	}
};

class BComponent : public Component
{};

class CComponent : public AComponent
{};

TEST_CASE("IEntity::AddComponent")
{
	IEntity<Component> * Entity = new IEntity<Component>();
	AComponent * A = new AComponent();
	BComponent * B = new BComponent();
	CComponent * C = new CComponent();
	AComponent * A2 = new CComponent();

	REQUIRE(A == Entity->AddComponent(A));
	REQUIRE(A == Entity->AddComponent(A));
	REQUIRE(B == Entity->AddComponent(B));
	REQUIRE(C == Entity->AddComponent(C));
	REQUIRE(A2 == Entity->AddComponent(A2));
}

TEST_CASE("IEntity::GetComponentCount")
{
	IEntity<Component> * Entity = new IEntity<Component>();
	AComponent * A = new AComponent();
	BComponent * B = new BComponent();
	CComponent * C = new CComponent();
	AComponent * A2 = new CComponent();

	REQUIRE(Entity->GetComponentCount<AComponent>() == 0);
	REQUIRE(Entity->GetComponentCount<BComponent>() == 0);
	REQUIRE(Entity->GetComponentCount<CComponent>() == 0);
	Entity->AddComponent(A);
	REQUIRE(Entity->GetComponentCount<AComponent>() == 1);
	REQUIRE(Entity->GetComponentCount<BComponent>() == 0);
	REQUIRE(Entity->GetComponentCount<CComponent>() == 0);
	Entity->AddComponent(A);
	REQUIRE(Entity->GetComponentCount<AComponent>() == 2);
	REQUIRE(Entity->GetComponentCount<BComponent>() == 0);
	REQUIRE(Entity->GetComponentCount<CComponent>() == 0);
	Entity->AddComponent(B);
	REQUIRE(Entity->GetComponentCount<AComponent>() == 2);
	REQUIRE(Entity->GetComponentCount<BComponent>() == 1);
	REQUIRE(Entity->GetComponentCount<CComponent>() == 0);
	Entity->AddComponent(C);
	REQUIRE(Entity->GetComponentCount<AComponent>() == 2);
	REQUIRE(Entity->GetComponentCount<BComponent>() == 1);
	REQUIRE(Entity->GetComponentCount<CComponent>() == 1);
	Entity->AddComponent(A2);
	REQUIRE(Entity->GetComponentCount<AComponent>() == 3);
	REQUIRE(Entity->GetComponentCount<BComponent>() == 1);
	REQUIRE(Entity->GetComponentCount<CComponent>() == 1);
}

template <typename TComponent>
bool CheckRangeEquals(pair<typename multimap<Type, TComponent *>::iterator, typename multimap<Type, TComponent *>::iterator> const Iterators, std::initializer_list<TComponent *> const & List)
{
	auto it = Iterators.first;
	auto jt = List.begin();
	for (; it != Iterators.second && jt != List.end(); ++ it, ++ jt)
	{
		if (it->second != *jt)
			return false;
	}

	if (it != Iterators.second || jt != List.end())
		return false;

	return true;
}

TEST_CASE("IEntity::GetComponents")
{
	IEntity<Component> * Entity = new IEntity<Component>();
	AComponent * A = new AComponent();
	BComponent * B = new BComponent();
	CComponent * C = new CComponent();
	AComponent * A2 = new CComponent();

	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {}));
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {}));
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<CComponent>(), {}));
	Entity->AddComponent(A);
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {A}));
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {}));
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<CComponent>(), {}));
	Entity->AddComponent(A);
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {A, A}));
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {}));
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<CComponent>(), {}));
	Entity->AddComponent(B);
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {A, A}));
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {B}));
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<CComponent>(), {}));
	Entity->AddComponent(C);
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {A, A}));
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {B}));
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<CComponent>(), {C}));
	Entity->AddComponent(A2);
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {A, A, A2}));
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {B}));
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<CComponent>(), {C}));
}

TEST_CASE("IEntity::ExpectSingleComponent")
{
	IEntity<Component> * Entity = new IEntity<Component>();
	AComponent * A = new AComponent(), * ATest = nullptr;
	BComponent * B = new BComponent(), * BTest = nullptr;
	CComponent * C = new CComponent(), * CTest = nullptr;
	AComponent * A2 = new CComponent(), * A2Test = nullptr;

	REQUIRE(Entity->ExpectSingleComponent(ATest) == 0);
	REQUIRE(! ATest);
	REQUIRE(Entity->ExpectSingleComponent(BTest) == 0);
	REQUIRE(! BTest);
	REQUIRE(Entity->ExpectSingleComponent(CTest) == 0);
	REQUIRE(! CTest);

	Entity->AddComponent(A);

	REQUIRE(Entity->ExpectSingleComponent(ATest) == 1);
	REQUIRE(ATest == A);
	REQUIRE(Entity->ExpectSingleComponent(BTest) == 0);
	REQUIRE(! BTest);
	REQUIRE(Entity->ExpectSingleComponent(CTest) == 0);
	REQUIRE(! CTest);

	Entity->AddComponent(A);
	ATest = nullptr;

	REQUIRE(Entity->ExpectSingleComponent(ATest) == 2);
	REQUIRE(ATest == A);
	REQUIRE(Entity->ExpectSingleComponent(BTest) == 0);
	REQUIRE(! BTest);
	REQUIRE(Entity->ExpectSingleComponent(CTest) == 0);
	REQUIRE(! CTest);

	Entity->AddComponent(B);
	Entity->AddComponent(C);
	Entity->AddComponent(A2);
	ATest = nullptr;

	REQUIRE(Entity->ExpectSingleComponent(ATest) == 3);
	REQUIRE(ATest == A);
	REQUIRE(Entity->ExpectSingleComponent(BTest) == 1);
	REQUIRE(BTest == B);
	REQUIRE(Entity->ExpectSingleComponent(CTest) == 1);
	REQUIRE(CTest == C);
}

TEST_CASE("IEntity::RequireSingleComponent")
{
	IEntity<Component> * Entity = new IEntity<Component>();
	AComponent * ATest = nullptr;
	BComponent * BTest = nullptr;

	REQUIRE(Entity->GetComponentCount<AComponent>() == 0);
	ATest = Entity->RequireSingleComponent<AComponent>();
	REQUIRE(ATest);
	REQUIRE(ATest->foo());
	REQUIRE(Entity->GetComponentCount<AComponent>() == 1);
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {ATest}));
	REQUIRE(ATest == Entity->RequireSingleComponent<AComponent>());
	REQUIRE(Entity->GetComponentCount<AComponent>() == 1);
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {ATest}));

	REQUIRE(Entity->GetComponentCount<BComponent>() == 0);
	BTest = Entity->RequireSingleComponent<BComponent>();
	REQUIRE(BTest);
	REQUIRE(Entity->GetComponentCount<AComponent>() == 1);
	REQUIRE(Entity->GetComponentCount<BComponent>() == 1);
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {ATest}));
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {BTest}));
	REQUIRE(BTest == Entity->RequireSingleComponent<BComponent>());
	REQUIRE(Entity->GetComponentCount<AComponent>() == 1);
	REQUIRE(Entity->GetComponentCount<BComponent>() == 1);
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<AComponent>(), {ATest}));
	REQUIRE(CheckRangeEquals<Component>(Entity->GetComponents<BComponent>(), {BTest}));
}
<|endoftext|>


<commit_before>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//

#include <iostream>
#include <stdio.h>
#include "nameserver/logdb.h"

namespace baidu {
namespace bfs {

void DumpMarker(char* path) {
    FILE* fp = fopen(path, "r");
    MarkerEntry mark;
    std::string data;
    int64_t v;
    while (true) {
        int ret = LogDB::ReadOne(fp, &data);
        if (ret == 0)  break;
        if (ret < 0) {
            std::cerr << "DumpMarker failed while reading" << std::endl;
            return;
        }
        LogDB::DecodeMarker(data, &mark);
        memcpy(&v, &(mark.value[0]), 8);
        std::cout << mark.key << "\t->\t" << v << " ---- " << mark.value << std::endl;
    }
    fclose(fp);
}

void DumpLog(char* path) {
    FILE* fp = fopen(path, "r");
    std::string data;
    int64_t i = 0;
    while (true) {
        int ret = LogDB::ReadOne(fp, &data);
        if(ret == 0) break;
        if(ret < 0 ) {
            std::cerr << "DumpLog failed while reading" << std::endl;
            return;
        }
        std::cout << i << "\t->\t" << data << std::endl;
        ++i;
    }
    fclose(fp);
}

void DumpIdx(char* path) {
    FILE* fp = fopen(path, "r");
    char buf[16];
    int64_t index, offset;
    while (true) {
        int ret = fread(buf, 1, 16, fp);
        if (ret == 0) break;
        if (ret < 0) {
            std::cerr << "DumpIdx failed while reading" << std::endl;
            return;
        }
        memcpy(&index, buf, 8);
        memcpy(&offset, buf + 8, 8);
        std::cout << index << "\t->\t" << offset << std::endl;
    }
    fclose(fp);
}

} // namespace bfs
} // namespace baidu

int main(int argc, char* argv[]) {
    std::string path(argv[1]);
    if (path.find(".mak") != std::string::npos || "marker.tmp" == path) {
        baidu::bfs::DumpMarker(argv[1]);
    } else if (path.find(".log") != std::string::npos) {
        baidu::bfs::DumpLog(argv[1]);
    } else if (path.find(".idx") != std::string::npos) {
        baidu::bfs::DumpIdx(argv[1]);
    }
}
<commit_msg>add performance test in logdb_dump<commit_after>// Copyright (c) 2016, Baidu.com, Inc. All Rights Reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//

#include <iostream>
#include <stdio.h>

#include <common/timer.h>
#include <common/thread.h>
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
#include "nameserver/logdb.h"

namespace baidu {
namespace bfs {

void DumpMarker(char* path) {
    FILE* fp = fopen(path, "r");
    MarkerEntry mark;
    std::string data;
    int64_t v;
    while (true) {
        int ret = LogDB::ReadOne(fp, &data);
        if (ret == 0)  break;
        if (ret < 0) {
            std::cerr << "DumpMarker failed while reading" << std::endl;
            return;
        }
        LogDB::DecodeMarker(data, &mark);
        memcpy(&v, &(mark.value[0]), 8);
        std::cout << mark.key << "\t->\t" << v << " ---- " << mark.value << std::endl;
    }
    fclose(fp);
}

void DumpLog(char* path) {
    FILE* fp = fopen(path, "r");
    std::string data;
    int64_t i = 0;
    while (true) {
        int ret = LogDB::ReadOne(fp, &data);
        if(ret == 0) break;
        if(ret < 0 ) {
            std::cerr << "DumpLog failed while reading" << std::endl;
            return;
        }
        std::cout << i << "\t->\t" << data << std::endl;
        ++i;
    }
    fclose(fp);
}

void DumpIdx(char* path) {
    FILE* fp = fopen(path, "r");
    char buf[16];
    int64_t index, offset;
    while (true) {
        int ret = fread(buf, 1, 16, fp);
        if (ret == 0) break;
        if (ret < 0) {
            std::cerr << "DumpIdx failed while reading" << std::endl;
            return;
        }
        memcpy(&index, buf, 8);
        memcpy(&offset, buf + 8, 8);
        std::cout << index << "\t->\t" << offset << std::endl;
    }
    fclose(fp);
}

void WriteHelper(int start, int end, const std::string& str, LogDB* logdb) {
    for (int i = start; i < end; ++i) {
        logdb->Write(i, str);
    }
    std::cerr << common::timer::get_micros() << std::endl;
}

void ReadHelper(int start, int end, const std::string& str, LogDB* logdb) {
    std::string res;
    for (int i = start; i < end; ++i) {
        logdb->Read(i, &res);
        assert(res == str);
    }
    std::cerr << common::timer::get_micros() << std::endl;
}

void Test(int n, int l) {
    LogDB* logdb;
    LogDB::Open("./dbtest", DBOption(), &logdb);

    int64_t start = common::timer::get_micros();
    std::string str(l, 'a');
    WriteHelper(0, n, str, logdb);
    int64_t now = common::timer::get_micros();
    double rate = double(n) / double(now - start);
    std::cerr << rate * 1000000.0 << std::endl;

    start = common::timer::get_micros();
    common::Thread w;
    w.Start(boost::bind(&WriteHelper, n, n + n, str, logdb));
    common::Thread r;
    r.Start(boost::bind(&ReadHelper, 0, n, str, logdb));
    w.Join();
    r.Join();
    now = common::timer::get_micros();
    rate = double(n) / double(now - start);
    std::cerr << rate * 1000000.0 << std::endl;

    //system("rm -rf ./dbtest");
}

} // namespace bfs
} // namespace baidu

int main(int argc, char* argv[]) {
    std::string path(argv[1]);
    if (path.find(".mak") != std::string::npos || "marker.tmp" == path) {
        baidu::bfs::DumpMarker(argv[1]);
    } else if (path.find(".log") != std::string::npos) {
        baidu::bfs::DumpLog(argv[1]);
    } else if (path.find(".idx") != std::string::npos) {
        baidu::bfs::DumpIdx(argv[1]);
    } else if (path == "test") {
        std::string n(argv[2]);
        std::string l(argv[3]);
        baidu::bfs::Test(boost::lexical_cast<int>(n), boost::lexical_cast<int>(l));
    }
}
<|endoftext|>