<commit_before>#ifndef STAN_MATH_REV_SCAL_FUNCTOR_PARALLEL_REDUCE_SUM_HPP
#define STAN_MATH_REV_SCAL_FUNCTOR_PARALLEL_REDUCE_SUM_HPP

#include <stan/math/prim/meta/return_type.hpp>
#include <stan/math/rev/mat/fun/typedefs.hpp>

#include <boost/iterator/counting_iterator.hpp>

#include <tbb/task_arena.h>
#include <tbb/parallel_reduce.h>
#include <tbb/blocked_range.h>

#include <iostream>
#include <iterator>
#include <vector>

namespace stan {
namespace math {

namespace internal {

template <class ReduceFunction, class InputIt, class T, class Arg1>
struct parallel_reduce_sum_impl<ReduceFunction, InputIt, T, Arg1, var> {
  using ops_partials_t
      = operands_and_partials<std::vector<Arg1>, const std::vector<int>>;

  struct recursive_reducer {
    InputIt first_;
    std::vector<Arg1>& varg1_;
    const std::vector<int>& idata1_;
    ops_partials_t terms_partials_;
    double terms_sum_;
    typedef typename std::iterator_traits<InputIt>::value_type elem_t;

    recursive_reducer(InputIt first, const T& init, std::vector<Arg1>& varg1,
                      const std::vector<int>& idata1)
        : first_(first),
          varg1_(varg1),
          idata1_(idata1),
          terms_partials_(varg1_, idata1_),
          terms_sum_(init.val()) {}

    recursive_reducer(recursive_reducer& other, tbb::split)
        : first_(other.first_),
          varg1_(other.varg1_),
          idata1_(other.idata1_),
          terms_partials_(varg1_, idata1_),
          terms_sum_(0.0) {}

    void operator()(const tbb::blocked_range<size_t>& r) {
      if (r.empty())
        return;

      auto start = first_;
      std::advance(start, r.begin());
      auto end = first_;
      std::advance(end, r.end());

      try {
        start_nested();

        // elem_t should better be a non-var!!! Otherwise we interfere
        // with the outer AD tree as we mess with the adjoints (and
        // right now we discard that it is a var if it would be)
        std::vector<elem_t> sub_slice(start, end);

        // create a deep copy of arg1 which is not tied to the outer
        // AD tree
        // todo: these copies can be put onto a thread-local storage
        // object such that we only create these once per thread which
        // should significantly boost performance as many copies are
        // avoided... this comes at the cost that the adjoints have to
        // be zeroed "manually"
        std::vector<Arg1> varg1;
        varg1.reserve(varg1_.size());

        for (Arg1& elem : varg1_)
          varg1.emplace_back(var(new vari(elem.val(), false)));

        T sub_sum_v = ReduceFunction()(r.begin(), r.end() - 1, sub_slice, varg1,
                                       idata1_);

        sub_sum_v.grad();

        terms_sum_ += sub_sum_v.val();

        for (std::size_t i = 0; i != varg1.size(); ++i)
          terms_partials_.edge1_.partials_[i] += varg1[i].adj();

      } catch (const std::exception& e) {
        recover_memory_nested();
        throw;
      }
      recover_memory_nested();
    }

    void join(const recursive_reducer& child) {
      terms_sum_ += child.terms_sum_;

      for (std::size_t i = 0; i != varg1_.size(); ++i)
        terms_partials_.edge1_.partials_[i]
            += child.terms_partials_.edge1_.partials_[i];
    }
  };

  T operator()(InputIt first, InputIt last, T init, std::size_t grainsize,
               std::vector<Arg1>& varg1, const std::vector<int>& idata) const {
    const std::size_t num_jobs = std::distance(first, last);
    recursive_reducer worker(first, init, varg1, idata);
    tbb::parallel_reduce(
        tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker);
    return worker.terms_partials_.build(worker.terms_sum_);
  }
};
}  // namespace internal

}  // namespace math
}  // namespace stan

#endif
<commit_msg>simplify how values are copied<commit_after>#ifndef STAN_MATH_REV_SCAL_FUNCTOR_PARALLEL_REDUCE_SUM_HPP
#define STAN_MATH_REV_SCAL_FUNCTOR_PARALLEL_REDUCE_SUM_HPP

#include <stan/math/prim/meta/return_type.hpp>
#include <stan/math/rev/mat/fun/typedefs.hpp>

#include <boost/iterator/counting_iterator.hpp>

#include <tbb/task_arena.h>
#include <tbb/parallel_reduce.h>
#include <tbb/blocked_range.h>

#include <iostream>
#include <iterator>
#include <vector>

namespace stan {
namespace math {

namespace internal {

template <class ReduceFunction, class InputIt, class T, class Arg1>
struct parallel_reduce_sum_impl<ReduceFunction, InputIt, T, Arg1, var> {
  using ops_partials_t
      = operands_and_partials<std::vector<Arg1>, const std::vector<int>>;

  struct recursive_reducer {
    InputIt first_;
    std::vector<Arg1>& varg1_;
    const std::vector<int>& idata1_;
    ops_partials_t terms_partials_;
    double terms_sum_;
    typedef typename std::iterator_traits<InputIt>::value_type elem_t;

    recursive_reducer(InputIt first, const T& init, std::vector<Arg1>& varg1,
                      const std::vector<int>& idata1)
        : first_(first),
          varg1_(varg1),
          idata1_(idata1),
          terms_partials_(varg1_, idata1_),
          terms_sum_(init.val()) {}

    recursive_reducer(recursive_reducer& other, tbb::split)
        : first_(other.first_),
          varg1_(other.varg1_),
          idata1_(other.idata1_),
          terms_partials_(varg1_, idata1_),
          terms_sum_(0.0) {}

    void operator()(const tbb::blocked_range<size_t>& r) {
      if (r.empty())
        return;

      auto start = first_;
      std::advance(start, r.begin());
      auto end = first_;
      std::advance(end, r.end());

      try {
        start_nested();

        // elem_t should better be a non-var!!! Otherwise we interfere
        // with the outer AD tree as we mess with the adjoints (and
        // right now we discard that it is a var if it would be)
        std::vector<elem_t> sub_slice(start, end);

        // create a deep copy of arg1 which is not tied to the outer
        // AD tree
        // todo: these copies can be put onto a thread-local storage
        // object such that we only create these once per thread which
        // should significantly boost performance as many copies are
        // avoided... this comes at the cost that the adjoints have to
        // be zeroed "manually"
        /* using the var_nochain_stack_ tape avoids up-propagation of chain
        std::vector<Arg1> varg1;
        varg1.reserve(varg1_.size());

        for (Arg1& elem : varg1_)
          varg1.emplace_back(var(new vari(elem.val(), false)));
        */

        // but this should actually do the same if we simply
        // instantiate the var from a double representation
        std::vector<double> varg1_d = value_of(varg1_);
        std::vector<Arg1> varg1(varg1_d.begin(), varg1_d.end());

        T sub_sum_v = ReduceFunction()(r.begin(), r.end() - 1, sub_slice, varg1,
                                       idata1_);

        sub_sum_v.grad();

        terms_sum_ += sub_sum_v.val();

        for (std::size_t i = 0; i != varg1.size(); ++i)
          terms_partials_.edge1_.partials_[i] += varg1[i].adj();

      } catch (const std::exception& e) {
        recover_memory_nested();
        throw;
      }
      recover_memory_nested();
    }

    void join(const recursive_reducer& child) {
      terms_sum_ += child.terms_sum_;

      for (std::size_t i = 0; i != varg1_.size(); ++i)
        terms_partials_.edge1_.partials_[i]
            += child.terms_partials_.edge1_.partials_[i];
    }
  };

  T operator()(InputIt first, InputIt last, T init, std::size_t grainsize,
               std::vector<Arg1>& varg1, const std::vector<int>& idata) const {
    const std::size_t num_jobs = std::distance(first, last);
    recursive_reducer worker(first, init, varg1, idata);
    tbb::parallel_reduce(
        tbb::blocked_range<std::size_t>(0, num_jobs, grainsize), worker);
    return worker.terms_partials_.build(worker.terms_sum_);
  }
};
}  // namespace internal

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


<commit_before>#include <iostream.h>
#include <string.h>
using namespace std;

class Container
{
	union
	{
		string str;
		int val;
	};
	bool is_val;

	Container(string str);
	Container(int val);

	Container chain(int val);
	operator string();
};

Container::Container(string str) : str(str), is_val(false)
{

}
Container::Container(int val) : val(val), is_val(true)
{

}

Container Container:chain(int val)
{
	if(this->val > val)
		return Container("Hello");
	else
		return Container(val+1);
}

Container chain(int val)
{
	return Container(val);
}

int main()
{
	cout<<chain(2).chain(1)<<endl;
}
<commit_msg>Fixed chaining_main.cpp after debugging<commit_after>#include <iostream>
#include <string>
#include <cassert>
using namespace std;

class Container
{
private:
	string str;
	int val;
	bool is_string;

public:
	Container(string str);
	Container(int val);

	Container chain(int val);
	operator string();
};

Container::Container(string str) : str(str), is_string(true)
{

}

Container::Container(int val) : val(val), is_string(false)
{

}

Container Container::chain(int val)
{
	assert(!is_string);
	if(this->val > val)
	{
		return Container("Hello");
	}
	else
	{
		return Container(val+1);
	}
}

Container::operator string()
{
	assert(is_string);
	return str;
}

Container chain(int val)
{
	return Container(val);
}

void foo(string str)
{
	cout<<str<<endl;
}

int main()
{
	foo(chain(2).chain(1));
}
<|endoftext|>


<commit_before>#include "unittest/gtest.hpp"
#include "unittest/server_test_helper.hpp"
#include "buffer_cache/large_buf.hpp"

namespace unittest {

struct large_buf_tester_t : public server_test_helper_t {
protected:
    static int64_t leaf_bytes(cache_t *cache) {
        return cache->get_block_size().value() - sizeof(large_buf_leaf);
    }

    void run_tests(thread_saver_t& saver, cache_t *cache) {
        {
            TRACEPOINT;
            // This is expected to pass.
            run_unprepend_shift_babytest(saver, cache, 4 * leaf_bytes(cache), leaf_bytes(cache) - 1);
        }
        {
            TRACEPOINT;
            // This is expected to fail (because our code is expected
            // to be broken), at the time of writing the test.
            run_unprepend_shift_babytest(saver, cache, 4 * leaf_bytes(cache), leaf_bytes(cache));
        }
    }

private:
    void run_unprepend_shift_babytest(thread_saver_t& saver, cache_t *cache, int64_t initial_size, int64_t unprepend_amount) {
        int64_t leaf_size = leaf_bytes(cache);

        const int num_root_ref_inlined = 2;

        // Sanity check test parameters.
        ASSERT_LT(unprepend_amount, initial_size);
        ASSERT_LT(num_root_ref_inlined * leaf_size, initial_size - unprepend_amount);
        ASSERT_LE(initial_size, leaf_size * (leaf_size / sizeof(block_id_t)));

        repli_timestamp time = current_time();

        boost::shared_ptr<transactor_t> txor(new transactor_t(saver, cache, rwi_write, 0, time));

        union {
            large_buf_ref ref;
            char ref_bytes[sizeof(large_buf_ref) + num_root_ref_inlined * sizeof(block_id_t)];
        };

        std::vector<char> chars(initial_size);
        for (int64_t i = 0; i < initial_size; ++i) {
            // 23 is relatively prime to leaf_size, which should be 4080.
            chars[i] = 'A' + (i % 23);
        }

        {
            large_buf_t lb(txor, &ref, lbref_limit_t(sizeof(ref_bytes)), rwi_write);
            lb.allocate(initial_size);
            lb.fill_at(0, chars.data(), initial_size);
        }

        ASSERT_EQ(0, ref.offset);
        ASSERT_EQ(initial_size, ref.size);

        {
            large_buf_t lb(txor, &ref, lbref_limit_t(sizeof(ref_bytes)), rwi_write);
            co_acquire_large_buf_for_unprepend(saver, &lb, unprepend_amount);
            int refsize_adjustment_out;
            lb.unprepend(unprepend_amount, &refsize_adjustment_out);
            ASSERT_EQ(0, refsize_adjustment_out);
        }

        chars.erase(chars.begin(), chars.begin() + unprepend_amount);

        // Makes sure that unprepend unshifts the way we expect.  We
        // expect things to be shifted largely to the left.
        ASSERT_EQ(unprepend_amount % leaf_size, ref.offset);
        ASSERT_EQ(initial_size - unprepend_amount, ref.size);

        {
            large_buf_t lb(txor, &ref, lbref_limit_t(sizeof(ref_bytes)), rwi_read);
            co_acquire_large_buf(saver, &lb);

            std::vector<char> chars_out(initial_size - unprepend_amount);
            lb.read_at(0, chars_out.data(), initial_size - unprepend_amount);

            ASSERT_TRUE(chars == chars_out);
        }
    }
};

TEST(LargeBufTest, all_tests) {
    large_buf_tester_t().run();
}

}  // namespace unittest
<commit_msg>Fix compilation in release mode with unit tests enabled<commit_after>#include "unittest/gtest.hpp"
#include "unittest/server_test_helper.hpp"
#include "buffer_cache/large_buf.hpp"

namespace unittest {

struct large_buf_tester_t : public server_test_helper_t {
protected:
    static int64_t leaf_bytes(cache_t *cache) {
        return cache->get_block_size().value() - sizeof(large_buf_leaf);
    }

    void run_tests(thread_saver_t& saver, cache_t *cache) {
        {
#ifndef NDEBUG
            TRACEPOINT;
#endif
            // This is expected to pass.
            run_unprepend_shift_babytest(saver, cache, 4 * leaf_bytes(cache), leaf_bytes(cache) - 1);
        }
        {
#ifndef NDEBUG
            TRACEPOINT;
#endif
            // This is expected to fail (because our code is expected
            // to be broken), at the time of writing the test.
            run_unprepend_shift_babytest(saver, cache, 4 * leaf_bytes(cache), leaf_bytes(cache));
        }
    }

private:
    void run_unprepend_shift_babytest(thread_saver_t& saver, cache_t *cache, int64_t initial_size, int64_t unprepend_amount) {
        int64_t leaf_size = leaf_bytes(cache);

        const int num_root_ref_inlined = 2;

        // Sanity check test parameters.
        ASSERT_LT(unprepend_amount, initial_size);
        ASSERT_LT(num_root_ref_inlined * leaf_size, initial_size - unprepend_amount);
        ASSERT_LE(initial_size, leaf_size * (leaf_size / sizeof(block_id_t)));

        repli_timestamp time = current_time();

        boost::shared_ptr<transactor_t> txor(new transactor_t(saver, cache, rwi_write, 0, time));

        union {
            large_buf_ref ref;
            char ref_bytes[sizeof(large_buf_ref) + num_root_ref_inlined * sizeof(block_id_t)];
        };

        std::vector<char> chars(initial_size);
        for (int64_t i = 0; i < initial_size; ++i) {
            // 23 is relatively prime to leaf_size, which should be 4080.
            chars[i] = 'A' + (i % 23);
        }

        {
            large_buf_t lb(txor, &ref, lbref_limit_t(sizeof(ref_bytes)), rwi_write);
            lb.allocate(initial_size);
            lb.fill_at(0, chars.data(), initial_size);
        }

        ASSERT_EQ(0, ref.offset);
        ASSERT_EQ(initial_size, ref.size);

        {
            large_buf_t lb(txor, &ref, lbref_limit_t(sizeof(ref_bytes)), rwi_write);
            co_acquire_large_buf_for_unprepend(saver, &lb, unprepend_amount);
            int refsize_adjustment_out;
            lb.unprepend(unprepend_amount, &refsize_adjustment_out);
            ASSERT_EQ(0, refsize_adjustment_out);
        }

        chars.erase(chars.begin(), chars.begin() + unprepend_amount);

        // Makes sure that unprepend unshifts the way we expect.  We
        // expect things to be shifted largely to the left.
        ASSERT_EQ(unprepend_amount % leaf_size, ref.offset);
        ASSERT_EQ(initial_size - unprepend_amount, ref.size);

        {
            large_buf_t lb(txor, &ref, lbref_limit_t(sizeof(ref_bytes)), rwi_read);
            co_acquire_large_buf(saver, &lb);

            std::vector<char> chars_out(initial_size - unprepend_amount);
            lb.read_at(0, chars_out.data(), initial_size - unprepend_amount);

            ASSERT_TRUE(chars == chars_out);
        }
    }
};

TEST(LargeBufTest, all_tests) {
    large_buf_tester_t().run();
}

}  // namespace unittest
<|endoftext|>


<commit_before>/*
 * Copyright 2007-2020 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * 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.
 *
 * 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
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#pragma once

#include <utility>

/**
 * A generic object which is owned by somebody who doesn't know how to
 * dispose it; to do this, a function pointer for disposing it is
 * provided.  Some implementations may do "delete this", but others
 * may be allocated from a custom allocator and may need different
 * ways to dispose it.
 */
class DisposablePointer {
public:
	using DisposeFunction = void(*)(void *ptr) noexcept;

private:
	void *ptr = nullptr;

	DisposeFunction dispose;

public:
	DisposablePointer() = default;
	DisposablePointer(std::nullptr_t) noexcept {}

	DisposablePointer(void *_ptr, DisposeFunction _dispose) noexcept
		:ptr(_ptr), dispose(_dispose) {}

	DisposablePointer(DisposablePointer &&src) noexcept
		:ptr(std::exchange(src.ptr, nullptr)), dispose(src.dispose) {}

	~DisposablePointer() noexcept {
		if (ptr != nullptr)
			dispose(ptr);
	}

	DisposablePointer &operator=(DisposablePointer &&other) noexcept {
		using std::swap;
		swap(ptr, other.ptr);
		swap(dispose, other.dispose);
		return *this;
	}

	operator bool() const noexcept {
		return ptr != nullptr;
	}

	void *get() const noexcept {
		return ptr;
	}
};

template<typename T>
class TypedDisposablePointer : public DisposablePointer {
public:
	template<typename... Args>
	TypedDisposablePointer(Args&&... args) noexcept
		:DisposablePointer(std::forward<Args>(args)...) {}

	TypedDisposablePointer(void *_ptr, DisposeFunction _dispose) noexcept;

	TypedDisposablePointer(T *_ptr, DisposeFunction _dispose) noexcept
		:DisposablePointer(_ptr, _dispose) {}

	T *get() const noexcept {
		return (T *)DisposablePointer::get();
	}

	T *operator->() const noexcept {
		return get();
	}

	T &operator*() const noexcept {
		return *get();
	}
};

inline DisposablePointer
ToNopPointer(void *ptr) noexcept
{
	return {ptr, [](void *) noexcept {}};
}

template<typename T>
TypedDisposablePointer<T>
ToDeletePointer(T *ptr) noexcept
{
	return {ptr, [](void *p) noexcept {
		T *t = (T *)p;
		delete t;
	}};
}

template<typename T>
TypedDisposablePointer<T>
ToDestructPointer(T *ptr) noexcept
{
	return {ptr, [](void *p) noexcept {
		T *t = (T *)p;
		t->~T();
	}};
}
<commit_msg>util/DisposablePointer: add reset()<commit_after>/*
 * Copyright 2007-2020 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * 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.
 *
 * 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
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#pragma once

#include <utility>

/**
 * A generic object which is owned by somebody who doesn't know how to
 * dispose it; to do this, a function pointer for disposing it is
 * provided.  Some implementations may do "delete this", but others
 * may be allocated from a custom allocator and may need different
 * ways to dispose it.
 */
class DisposablePointer {
public:
	using DisposeFunction = void(*)(void *ptr) noexcept;

private:
	void *ptr = nullptr;

	DisposeFunction dispose;

public:
	DisposablePointer() = default;
	DisposablePointer(std::nullptr_t) noexcept {}

	DisposablePointer(void *_ptr, DisposeFunction _dispose) noexcept
		:ptr(_ptr), dispose(_dispose) {}

	DisposablePointer(DisposablePointer &&src) noexcept
		:ptr(std::exchange(src.ptr, nullptr)), dispose(src.dispose) {}

	~DisposablePointer() noexcept {
		if (ptr != nullptr)
			dispose(ptr);
	}

	DisposablePointer &operator=(DisposablePointer &&other) noexcept {
		using std::swap;
		swap(ptr, other.ptr);
		swap(dispose, other.dispose);
		return *this;
	}

	operator bool() const noexcept {
		return ptr != nullptr;
	}

	void *get() const noexcept {
		return ptr;
	}

	void reset() noexcept {
		if (ptr != nullptr)
			dispose(std::exchange(ptr, nullptr));
	}
};

template<typename T>
class TypedDisposablePointer : public DisposablePointer {
public:
	template<typename... Args>
	TypedDisposablePointer(Args&&... args) noexcept
		:DisposablePointer(std::forward<Args>(args)...) {}

	TypedDisposablePointer(void *_ptr, DisposeFunction _dispose) noexcept;

	TypedDisposablePointer(T *_ptr, DisposeFunction _dispose) noexcept
		:DisposablePointer(_ptr, _dispose) {}

	T *get() const noexcept {
		return (T *)DisposablePointer::get();
	}

	T *operator->() const noexcept {
		return get();
	}

	T &operator*() const noexcept {
		return *get();
	}
};

inline DisposablePointer
ToNopPointer(void *ptr) noexcept
{
	return {ptr, [](void *) noexcept {}};
}

template<typename T>
TypedDisposablePointer<T>
ToDeletePointer(T *ptr) noexcept
{
	return {ptr, [](void *p) noexcept {
		T *t = (T *)p;
		delete t;
	}};
}

template<typename T>
TypedDisposablePointer<T>
ToDestructPointer(T *ptr) noexcept
{
	return {ptr, [](void *p) noexcept {
		T *t = (T *)p;
		t->~T();
	}};
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Patrick P. Frey
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
/// \brief Macros, classes and functions supporting error handling
/// \file errorUtils.hpp
#ifndef _STRUS_PATTERN_ERROR_UTILITIES_HPP_INCLUDED
#define _STRUS_PATTERN_ERROR_UTILITIES_HPP_INCLUDED
#include <stdexcept>
#include "internationalization.hpp"

#define THIS_COMPONENT_NAME	"strus pattern"
#define THIS_COMPONENT_ID	StrusComponentPattern

/// \brief strus toplevel namespace
namespace strus
{

#define CATCH_ERROR_MAP( contextExplainText, errorBuffer)\
	catch (const std::bad_alloc&)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseOutOfMem), _TXT("memory allocation error in %s"), THIS_COMPONENT_NAME);\
	}\
	catch (const std::runtime_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseRuntimeError), contextExplainText, err.what());\
	}\
	catch (const std::logic_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseLogicError), _TXT("logic error in %s: %s"), THIS_COMPONENT_NAME, err.what());\
	}\
	catch (const std::exception& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseUncaughtException), _TXT("uncaught exception in %s: %s"), THIS_COMPONENT_NAME, err.what());\
	}

#define CATCH_ERROR_ARG1_MAP( contextExplainText, ARG, errorBuffer)\
	catch (const std::bad_alloc&)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseOutOfMem), _TXT("memory allocation error in %s"), THIS_COMPONENT_NAME);\
	}\
	catch (const std::runtime_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseRuntimeError), contextExplainText, ARG, err.what());\
	}\
	catch (const std::logic_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseLogicError), _TXT("logic error in %s: %s"), THIS_COMPONENT_NAME, err.what());\
	}\
	catch (const std::exception& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseUncaughtException), _TXT("uncaught exception in %s: %s"), THIS_COMPONENT_NAME, err.what());\
	}

#define CATCH_ERROR_MAP_RETURN( contextExplainText, errorBuffer, errorReturnValue)\
	catch (const std::bad_alloc&)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseOutOfMem), _TXT("memory allocation error in %s"), THIS_COMPONENT_NAME);\
		return errorReturnValue;\
	}\
	catch (const std::runtime_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseRuntimeError), contextExplainText, err.what());\
		return errorReturnValue;\
	}\
	catch (const std::logic_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseLogicError), _TXT("logic error in %s: %s"), THIS_COMPONENT_NAME, err.what());\
		return errorReturnValue;\
	}\
	catch (const std::exception& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseUncaughtException), _TXT("uncaught exception in %s: %s"), THIS_COMPONENT_NAME, err.what());\
		return errorReturnValue;\
	}

#define CATCH_ERROR_ARG1_MAP_RETURN( contextExplainText, ARG, errorBuffer, errorReturnValue)\
	catch (const std::bad_alloc&)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseOutOfMem), _TXT("memory allocation error in %s"), THIS_COMPONENT_NAME);\
		return errorReturnValue;\
	}\
	catch (const std::runtime_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseRuntimeError), contextExplainText, ARG, err.what());\
		return errorReturnValue;\
	}\
	catch (const std::logic_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseLogicError), _TXT("logic error in %s: %s"), THIS_COMPONENT_NAME, err.what());\
		return errorReturnValue;\
	}\
	catch (const std::exception& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseUncaughtException), _TXT("uncaught exception in %s: %s"), THIS_COMPONENT_NAME, err.what());\
		return errorReturnValue;\
	}

}//namespace
#endif
<commit_msg>added missing include<commit_after>/*
 * Copyright (c) 2014 Patrick P. Frey
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
/// \brief Macros, classes and functions supporting error handling
/// \file errorUtils.hpp
#ifndef _STRUS_PATTERN_ERROR_UTILITIES_HPP_INCLUDED
#define _STRUS_PATTERN_ERROR_UTILITIES_HPP_INCLUDED
#include <stdexcept>
#include "strus/errorCodes.hpp"
#include "internationalization.hpp"

#define THIS_COMPONENT_NAME	"strus pattern"
#define THIS_COMPONENT_ID	StrusComponentPattern

/// \brief strus toplevel namespace
namespace strus
{

#define CATCH_ERROR_MAP( contextExplainText, errorBuffer)\
	catch (const std::bad_alloc&)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseOutOfMem), _TXT("memory allocation error in %s"), THIS_COMPONENT_NAME);\
	}\
	catch (const std::runtime_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseRuntimeError), contextExplainText, err.what());\
	}\
	catch (const std::logic_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseLogicError), _TXT("logic error in %s: %s"), THIS_COMPONENT_NAME, err.what());\
	}\
	catch (const std::exception& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseUncaughtException), _TXT("uncaught exception in %s: %s"), THIS_COMPONENT_NAME, err.what());\
	}

#define CATCH_ERROR_ARG1_MAP( contextExplainText, ARG, errorBuffer)\
	catch (const std::bad_alloc&)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseOutOfMem), _TXT("memory allocation error in %s"), THIS_COMPONENT_NAME);\
	}\
	catch (const std::runtime_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseRuntimeError), contextExplainText, ARG, err.what());\
	}\
	catch (const std::logic_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseLogicError), _TXT("logic error in %s: %s"), THIS_COMPONENT_NAME, err.what());\
	}\
	catch (const std::exception& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseUncaughtException), _TXT("uncaught exception in %s: %s"), THIS_COMPONENT_NAME, err.what());\
	}

#define CATCH_ERROR_MAP_RETURN( contextExplainText, errorBuffer, errorReturnValue)\
	catch (const std::bad_alloc&)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseOutOfMem), _TXT("memory allocation error in %s"), THIS_COMPONENT_NAME);\
		return errorReturnValue;\
	}\
	catch (const std::runtime_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseRuntimeError), contextExplainText, err.what());\
		return errorReturnValue;\
	}\
	catch (const std::logic_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseLogicError), _TXT("logic error in %s: %s"), THIS_COMPONENT_NAME, err.what());\
		return errorReturnValue;\
	}\
	catch (const std::exception& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseUncaughtException), _TXT("uncaught exception in %s: %s"), THIS_COMPONENT_NAME, err.what());\
		return errorReturnValue;\
	}

#define CATCH_ERROR_ARG1_MAP_RETURN( contextExplainText, ARG, errorBuffer, errorReturnValue)\
	catch (const std::bad_alloc&)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseOutOfMem), _TXT("memory allocation error in %s"), THIS_COMPONENT_NAME);\
		return errorReturnValue;\
	}\
	catch (const std::runtime_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseRuntimeError), contextExplainText, ARG, err.what());\
		return errorReturnValue;\
	}\
	catch (const std::logic_error& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseLogicError), _TXT("logic error in %s: %s"), THIS_COMPONENT_NAME, err.what());\
		return errorReturnValue;\
	}\
	catch (const std::exception& err)\
	{\
		(errorBuffer).report( *ErrorCode(THIS_COMPONENT_ID,ErrorOperationUnknown,ErrorCauseUncaughtException), _TXT("uncaught exception in %s: %s"), THIS_COMPONENT_NAME, err.what());\
		return errorReturnValue;\
	}

}//namespace
#endif
<|endoftext|>


<commit_before>/**
 * Clever programming language
 * Copyright (c) 2011-2012 Clever Team
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <cstdio>
#include <sstream>
#include "vm/opcode.h"
#include "compiler/value.h"

namespace clever {

/**
 * Dumps an opcode
 */
void Opcode::dump() const {
	::printf("(%04zu) | ", getOpNum());
	::printf("%-15s | ", getOpName(m_op_type));
	::printf("%-20s | ", dumpOp("op1", m_op1).c_str());
	::printf("%-20s | ", dumpOp("op2", m_op2).c_str());
	::printf("%-20s | ", dumpOp("result", m_result).c_str());
	::printf("Addr1: %04ld | ", getJmpAddr1());
	::printf("Addr2: %04ld\n", getJmpAddr2());
}

/**
 * Returns the opcode name
 */
const char* Opcode::getOpName(OpcodeType op) const {
#define CASE(x) case x: return #x

	switch (op) {
		CASE(OP_PRE_INC);
		CASE(OP_PRE_DEC);
		CASE(OP_POS_INC);
		CASE(OP_POS_DEC);
		CASE(OP_JMPNZ);
		CASE(OP_JMPZ);
		CASE(OP_JMP);
		CASE(OP_BREAK);
		CASE(OP_MCALL);
		CASE(OP_FCALL);
		CASE(OP_RETURN);
		CASE(OP_REGEX);
		CASE(OP_NOT);
		CASE(OP_BW_NOT);
		CASE(OP_PLUS);
		CASE(OP_DIV);
		CASE(OP_MULT);
		CASE(OP_MINUS);
		CASE(OP_MOD);
		CASE(OP_XOR);
		CASE(OP_BW_OR);
		CASE(OP_BW_AND);
		CASE(OP_GREATER);
		CASE(OP_LESS);
		CASE(OP_GE);
		CASE(OP_LE);
		CASE(OP_EQUAL);
		CASE(OP_NE);
		CASE(OP_LSHIFT);
		CASE(OP_RSHIFT);
		CASE(OP_ASSIGN);
		CASE(OP_AT);
		default:
			return "UNKNOWN";
	}
}

/**
 * Dumps an operand
 */
std::string Opcode::dumpOp(const char* const label, Value* const op) const {
	if (op) {
		std::ostringstream str;
		std::string name = op->getName() && op->isCallable() ?
			op->getName()->str() : op->toString();

		if (op->isVector()) {
			name = "vector";
		}

		str << op->refCount();

		return std::string(std::string(label) + ": " + name + " (#" + str.str() + ")");
	} else {
		return std::string(std::string(label) + ": UNUSED");
	}
}

/**
 * Returns the opcode handler by supplying its opcode type
 */
VM::opcode_handler Opcode::getHandlerByType(OpcodeType op_type) {
	switch (op_type) {
		case OP_PLUS:    return &VM::plus_handler;
		case OP_MINUS:   return &VM::minus_handler;
		case OP_DIV:     return &VM::div_handler;
		case OP_MULT:    return &VM::mult_handler;
		case OP_MOD:     return &VM::mod_handler;
		case OP_XOR:     return &VM::xor_handler;
		case OP_BW_OR:   return &VM::bw_or_handler;
		case OP_BW_AND:  return &VM::bw_and_handler;
		case OP_GREATER: return &VM::greater_handler;
		case OP_LESS:    return &VM::less_handler;
		case OP_GE:      return &VM::ge_handler;
		case OP_LE:      return &VM::le_handler;
		case OP_EQUAL:   return &VM::equal_handler;
		case OP_NE:      return &VM::ne_handler;
		case OP_LSHIFT:  return &VM::lshift_handler;
		case OP_RSHIFT:  return &VM::rshift_handler;
		case OP_PRE_INC: return &VM::inc_handler;
		case OP_POS_INC: return &VM::inc_handler;
		case OP_PRE_DEC: return &VM::dec_handler;
		case OP_POS_DEC: return &VM::dec_handler;
		case OP_NOT:     return &VM::not_handler;
		case OP_BW_NOT:  return &VM::bw_not_handler;
		default:	     return &VM::mcall_handler;
	}
}

} // clever
<commit_msg>- Fix crash when using -d option<commit_after>/**
 * Clever programming language
 * Copyright (c) 2011-2012 Clever Team
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <cstdio>
#include <sstream>
#include "vm/opcode.h"
#include "compiler/value.h"

namespace clever {

/**
 * Dumps an opcode
 */
void Opcode::dump() const {
	::printf("(%04zu) | ", getOpNum());
	::printf("%-15s | ", getOpName(m_op_type));
	::printf("%-20s | ", dumpOp("op1", m_op1).c_str());
	::printf("%-20s | ", dumpOp("op2", m_op2).c_str());
	::printf("%-20s | ", dumpOp("result", m_result).c_str());
	::printf("Addr1: %04ld | ", getJmpAddr1());
	::printf("Addr2: %04ld\n", getJmpAddr2());
}

/**
 * Returns the opcode name
 */
const char* Opcode::getOpName(OpcodeType op) const {
#define CASE(x) case x: return #x

	switch (op) {
		CASE(OP_PRE_INC);
		CASE(OP_PRE_DEC);
		CASE(OP_POS_INC);
		CASE(OP_POS_DEC);
		CASE(OP_JMPNZ);
		CASE(OP_JMPZ);
		CASE(OP_JMP);
		CASE(OP_BREAK);
		CASE(OP_MCALL);
		CASE(OP_FCALL);
		CASE(OP_RETURN);
		CASE(OP_REGEX);
		CASE(OP_NOT);
		CASE(OP_BW_NOT);
		CASE(OP_PLUS);
		CASE(OP_DIV);
		CASE(OP_MULT);
		CASE(OP_MINUS);
		CASE(OP_MOD);
		CASE(OP_XOR);
		CASE(OP_BW_OR);
		CASE(OP_BW_AND);
		CASE(OP_GREATER);
		CASE(OP_LESS);
		CASE(OP_GE);
		CASE(OP_LE);
		CASE(OP_EQUAL);
		CASE(OP_NE);
		CASE(OP_LSHIFT);
		CASE(OP_RSHIFT);
		CASE(OP_ASSIGN);
		CASE(OP_AT);
		default:
			return "UNKNOWN";
	}
}

/**
 * Dumps an operand
 */
std::string Opcode::dumpOp(const char* const label, Value* const op) const {
	if (op) {
		std::ostringstream str;

		if (op->getName() && op->isCallable()) {
			std::string name = op->getName()->str();

			str << op->refCount();

			return std::string(std::string(label) + ": " + name + " (#" + str.str() + ")");
		} else {
			std::string name;

			if (op->isVector()) {
				if (op->getTypePtr() == NULL) {
					name = "ValueVector";
				} else {
					name = op->getTypePtr()->getName()->str();
				}
			} else {
				if (op->getTypePtr() == NULL) {
					name = "NULL";
				} else {
					name = op->toString().str();
				}
			}
			str << op->refCount();

			return std::string(std::string(label) + ": " + name + " (#" + str.str() + ")");
		}
	} else {
		return std::string(std::string(label) + ": UNUSED");
	}
}

/**
 * Returns the opcode handler by supplying its opcode type
 */
VM::opcode_handler Opcode::getHandlerByType(OpcodeType op_type) {
	switch (op_type) {
		case OP_PLUS:    return &VM::plus_handler;
		case OP_MINUS:   return &VM::minus_handler;
		case OP_DIV:     return &VM::div_handler;
		case OP_MULT:    return &VM::mult_handler;
		case OP_MOD:     return &VM::mod_handler;
		case OP_XOR:     return &VM::xor_handler;
		case OP_BW_OR:   return &VM::bw_or_handler;
		case OP_BW_AND:  return &VM::bw_and_handler;
		case OP_GREATER: return &VM::greater_handler;
		case OP_LESS:    return &VM::less_handler;
		case OP_GE:      return &VM::ge_handler;
		case OP_LE:      return &VM::le_handler;
		case OP_EQUAL:   return &VM::equal_handler;
		case OP_NE:      return &VM::ne_handler;
		case OP_LSHIFT:  return &VM::lshift_handler;
		case OP_RSHIFT:  return &VM::rshift_handler;
		case OP_PRE_INC: return &VM::inc_handler;
		case OP_POS_INC: return &VM::inc_handler;
		case OP_PRE_DEC: return &VM::dec_handler;
		case OP_POS_DEC: return &VM::dec_handler;
		case OP_NOT:     return &VM::not_handler;
		case OP_BW_NOT:  return &VM::bw_not_handler;
		default:	     return &VM::mcall_handler;
	}
}

} // clever
<|endoftext|>


<commit_before>#include "essentials.hpp"

#include "blackhole/filter/severity.hpp"
#include "blackhole/formatter/string.hpp"
#include "blackhole/handler/blocking.hpp"
#include "blackhole/handler/dev.hpp"
#include "blackhole/registry.hpp"
#include "blackhole/sink/asynchronous.hpp"
#include "blackhole/sink/console.hpp"
#include "blackhole/sink/file.hpp"
#include "blackhole/sink/null.hpp"
#include "blackhole/sink/socket/tcp.hpp"
#include "blackhole/sink/socket/udp.hpp"
#include "blackhole/sink/syslog.hpp"

namespace blackhole {
inline namespace v1 {

auto essentials(registry_t& registry) -> void {
    registry.add<filter::severity_t>();

    registry.add<formatter::string_t>();

    registry.add<sink::asynchronous_t>(registry);
    registry.add<sink::console_t>(registry);
    registry.add<sink::file_t>(registry);
    registry.add<sink::null_t>();
    registry.add<sink::socket::tcp_t>(registry);
    registry.add<sink::socket::udp_t>(registry);
    registry.add<sink::syslog_t>(registry);

    registry.add<handler::blocking_t>(registry);
    registry.add<handler::dev_t>(registry);
}

}  // namespace v1
}  // namespace blackhole
<commit_msg>refactor: drop dev handler from essentials<commit_after>#include "essentials.hpp"

#include "blackhole/filter/severity.hpp"
#include "blackhole/formatter/string.hpp"
#include "blackhole/handler/blocking.hpp"
#include "blackhole/handler/dev.hpp"
#include "blackhole/registry.hpp"
#include "blackhole/sink/asynchronous.hpp"
#include "blackhole/sink/console.hpp"
#include "blackhole/sink/file.hpp"
#include "blackhole/sink/null.hpp"
#include "blackhole/sink/socket/tcp.hpp"
#include "blackhole/sink/socket/udp.hpp"
#include "blackhole/sink/syslog.hpp"

namespace blackhole {
inline namespace v1 {

auto essentials(registry_t& registry) -> void {
    registry.add<filter::severity_t>();

    registry.add<formatter::string_t>();

    registry.add<sink::asynchronous_t>(registry);
    registry.add<sink::console_t>(registry);
    registry.add<sink::file_t>(registry);
    registry.add<sink::null_t>();
    registry.add<sink::socket::tcp_t>(registry);
    registry.add<sink::socket::udp_t>(registry);
    registry.add<sink::syslog_t>(registry);

    registry.add<handler::blocking_t>(registry);
    // registry.add<handler::dev_t>(registry);
}

}  // namespace v1
}  // namespace blackhole
<|endoftext|>


<commit_before>#include "essentials.hpp"

#include "blackhole/filter/severity.hpp"
#include "blackhole/formatter/string.hpp"
#include "blackhole/handler/blocking.hpp"
#include "blackhole/registry.hpp"
#include "blackhole/sink/asynchronous.hpp"
#include "blackhole/sink/console.hpp"
#include "blackhole/sink/file.hpp"
#include "blackhole/sink/null.hpp"
#include "blackhole/sink/socket/tcp.hpp"
#include "blackhole/sink/socket/udp.hpp"
#include "blackhole/sink/syslog.hpp"

namespace blackhole {
inline namespace v1 {

auto essentials(registry_t& registry) -> void {
    registry.add<filter::severity_t>();

    registry.add<formatter::string_t>();

    registry.add<sink::asynchronous_t>(registry);
    registry.add<sink::console_t>(registry);
    registry.add<sink::file_t>(registry);
    registry.add<sink::null_t>();
    registry.add<sink::socket::tcp_t>(registry);
    registry.add<sink::socket::udp_t>(registry);
    registry.add<sink::syslog_t>(registry);

    registry.add<handler::blocking_t>(registry);
}

}  // namespace v1
}  // namespace blackhole
<commit_msg>feat: register dev handler in the registry<commit_after>#include "essentials.hpp"

#include "blackhole/filter/severity.hpp"
#include "blackhole/formatter/string.hpp"
#include "blackhole/handler/blocking.hpp"
#include "blackhole/handler/dev.hpp"
#include "blackhole/registry.hpp"
#include "blackhole/sink/asynchronous.hpp"
#include "blackhole/sink/console.hpp"
#include "blackhole/sink/file.hpp"
#include "blackhole/sink/null.hpp"
#include "blackhole/sink/socket/tcp.hpp"
#include "blackhole/sink/socket/udp.hpp"
#include "blackhole/sink/syslog.hpp"

namespace blackhole {
inline namespace v1 {

auto essentials(registry_t& registry) -> void {
    registry.add<filter::severity_t>();

    registry.add<formatter::string_t>();

    registry.add<sink::asynchronous_t>(registry);
    registry.add<sink::console_t>(registry);
    registry.add<sink::file_t>(registry);
    registry.add<sink::null_t>();
    registry.add<sink::socket::tcp_t>(registry);
    registry.add<sink::socket::udp_t>(registry);
    registry.add<sink::syslog_t>(registry);

    registry.add<handler::blocking_t>(registry);
    registry.add<handler::dev_t>(registry);
}

}  // namespace v1
}  // namespace blackhole
<|endoftext|>


<commit_before>/*********************************************************************
 * tm700_demo_node.cpp
 *
 * Copyright 2016 Copyright 2016 Techman Robot Inc.
 *
 * 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.
 *********************************************************************
 *
 * Author: Yun-Hsuan Tsai
 */

#include <ros/ros.h>
#include <ros/console.h>

#include <moveit/move_group_interface/move_group.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit/robot_state/robot_state.h>
#include <moveit/robot_state/conversions.h>

#include <moveit_msgs/DisplayRobotState.h>
#include <moveit_msgs/DisplayTrajectory.h>

#include <moveit_msgs/AttachedCollisionObject.h>
#include <moveit_msgs/CollisionObject.h>

#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cmath>

#include "tm_msgs/SetIO.h"
//#include "tm_msgs/SetIORequest.h"
//#include "tm_msgs/SetIOResponse.h"

//get current joint values of TM5
void get_current_joint_values(moveit::planning_interface::MoveGroup& group,
                              moveit::planning_interface::MoveGroup::Plan& plan,
                                                            std::vector<double>& record_joint
                                                        ){
        //if(!ros::ok()) return false;
        bool success = false;

        std::vector<double> joint_value;
        joint_value = group.getCurrentJointValues();
    record_joint = group.getCurrentJointValues();

    ROS_INFO("In get_current_joint_values()");
        for(int i = 0; i<joint_value.size(); i++){
            joint_value[i] = joint_value[i]*180/M_PI;
            printf("Joint %d: %lf\n",i+1, joint_value[i]);
        }
}

bool try_move_to_named_target(moveit::planning_interface::MoveGroup& group,
                  moveit::planning_interface::MoveGroup::Plan& plan,
                  const std::string& target_name,
                  unsigned int max_try_times = 1
                 ) {
  if(!ros::ok()) return false;
  bool success = false;

  for(unsigned int i = 0; i < max_try_times; i++) {

    group.setNamedTarget(target_name);

    if(group.move()) {
      success = true;
      break;
    }
    else {
      if(!ros::ok()) break;
      sleep(1);
    }
  }
  return success;
}

bool try_move_to_joint_target(moveit::planning_interface::MoveGroup& group,
                  moveit::planning_interface::MoveGroup::Plan& plan,
                  const std::vector<double>& joint_target,
                  unsigned int max_try_times = 1
                 ) {
  if(!ros::ok()) return false;
  bool success = false;

  for(unsigned int i = 0; i < max_try_times; i++) {

    group.setJointValueTarget(joint_target);

    if(group.move()) {
      success = true;
      break;
    }
    else {
      if(!ros::ok()) break;
      sleep(1);
    }
  }
}

int main(int argc, char **argv)
{

  ros::init(argc, argv, "tm700_demo_test");
  ros::NodeHandle node_handle;
  ros::ServiceClient set_io_client = node_handle.serviceClient<tm_msgs::SetIO>("tm_driver/set_io");
  tm_msgs::SetIO io_srv;
  io_srv.request.fun = 2;//tm_msgs::SetIORequest::FUN_SET_EE_DIGITAL_OUT;
  io_srv.request.ch = 0;
  io_srv.request.value = 0.0;

  // start a background "spinner", so our node can process ROS messages
  //  - this lets us know when the move is completed
  ros::AsyncSpinner spinner(1);
  spinner.start();

  sleep(1);

  // Setup
  // ^^^^^
  // The :move_group_interface:`MoveGroup` class can be easily
  // setup using just the name
  // of the group you would like to control and plan for.
  moveit::planning_interface::MoveGroup group("manipulator");
  // We will use the :planning_scene_interface:`PlanningSceneInterface`
  // class to deal directly with the world.
  moveit::planning_interface::PlanningSceneInterface planning_scene_interface;
  // (Optional) Create a publisher for visualizing plans in Rviz.
  //ros::Publisher display_publisher = node_handle.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true);
  //moveit_msgs::DisplayTrajectory display_trajectory;

  // Getting Basic Information
  // ^^^^^^^^^^^^^^^^^^^^^^^^^
  // We can print the name of the reference frame for this robot.
  ROS_INFO("Reference frame: %s", group.getPlanningFrame().c_str());
  // We can also print the name of the end-effector link for this group.
  ROS_INFO("Reference frame: %s", group.getEndEffectorLink().c_str());

  moveit::planning_interface::MoveGroup::Plan my_plan;

  set_io_client.call(io_srv);

  group.setPlanningTime(30.0);

  //try_move_to_named_target(group, my_plan, "home", 100);

  std::vector<double> joint_target_1;
  std::vector<double> joint_target_2;

    std::vector<double> record_joint_1;
    std::vector<double> record_joint_2;
    std::vector<double> record_joint_3;

  double joint_value = 0;

  joint_target_1.assign(6, 0.0f);
  joint_target_1[0] = 0.0174533*( 30.0);
  joint_target_1[1] = 0.0174533*( 15.0);
  joint_target_1[2] = 0.0174533*(105.0);
  joint_target_1[3] = 0.0174533*(-30.0);
  joint_target_1[4] = 0.0174533*( 90.0);
  joint_target_1[5] = 0.0174533*( 30.0);

  joint_target_2.assign(6, 0.0f);
  joint_target_2[0] = 0.0174533*(-30.0);
  joint_target_2[1] = 0.0174533*(-15.0);
  joint_target_2[2] = 0.0174533*( 90.0);
  joint_target_2[3] = 0.0174533*(-75.0);
  joint_target_2[4] = 0.0174533*(120.0);

  int step = 0;
  int flag = 0;

  while (ros::ok()) {
    switch (5) {

     case 0: //gripper off
       io_srv.request.fun = 2;
       io_srv.request.ch = 0;
       io_srv.request.value = 0.0;

       if (set_io_client.call(io_srv))
         ROS_INFO("Set IO success");
       else
         ROS_WARN("Failed to call service set_io");
       break;

     case 1: //move to ready
       ROS_INFO("move...");
       //try_move_to_named_target(group, my_plan, "ready", 100);
       break;

     case 2: //light on
   /*
       io_srv.request.fun = 2;
       io_srv.request.ch = 3;
       io_srv.request.value = 1.0;
   */
       if (set_io_client.call(io_srv))
         ROS_INFO("Set IO success");
       else
         ROS_WARN("Failed to call service set_io");
       break;

     case 3: //wait 3 sec
       sleep(3);
       break;

    case 4: //light off
      io_srv.request.fun = 2;
      io_srv.request.ch = 3;
      io_srv.request.value = 0.0;
      if (set_io_client.call(io_srv))
        ROS_INFO("Set IO success");
      else
        ROS_WARN("Failed to call service set_io");
      break;

    case 5: //move 1
      //ROS_INFO("move...");
      //try_move_to_joint_target(group, my_plan, joint_target_1, 100);
      ROS_INFO("Teaching Pose 1...");
    while(flag == 0){
      printf("Finish Teaching? Yes: 1, No:0\n");
      scanf("%d", &flag);
      get_current_joint_values(group, my_plan, record_joint_1);
    }
    flag = 0;

    ROS_INFO("Teaching Pose 2...");
    while(flag == 0){
      printf("Finish Teaching? Yes: 1, No:0\n");
      scanf("%d", &flag);
      get_current_joint_values(group, my_plan, record_joint_2);
    }
    flag = 0;

    ROS_INFO("Teaching Pose 3...");
    while(flag == 0){
      printf("Finish Teaching? Yes: 1, No:0\n");
      scanf("%d", &flag);
      get_current_joint_values(group, my_plan, record_joint_3);
    }

    //ROS_INFO("Teaching Pose 1...");
      for(int i = 0; i<record_joint_1.size(); i++){
          joint_value = record_joint_1[i]*180/M_PI;
          printf("Joint %d: degree: %lf, rad: %lf\n", i+1, joint_value, record_joint_1[i]);
      }

    while(ros::ok()){
      try_move_to_named_target(group, my_plan, "home", 100);
      //wait 3 seconds
      sleep(3);
      try_move_to_joint_target(group, my_plan, record_joint_1, 100);
      sleep(3);
      try_move_to_joint_target(group, my_plan, record_joint_2, 100);
      sleep(3);
      try_move_to_joint_target(group, my_plan, record_joint_3, 100);
      sleep(3);
    }

      break;

    case 6: //gripper on
      io_srv.request.fun = 2;
      io_srv.request.ch = 0;
      io_srv.request.value = 1.0;
      if (set_io_client.call(io_srv))
        ROS_INFO("Set IO success");
      else
        ROS_WARN("Failed to call service set_io");
      break;

    case 7: //wait 1 sec
      sleep(1);
      break;

    case 8: //move 2...
      ROS_INFO("move...");
      //try_move_to_joint_target(group, my_plan, joint_target_2, 100);
      break;
    }
    step = (step + 1) % 9;
  }
  return 0;
}<commit_msg>update local tm700_demo_test.cpp<commit_after>/*********************************************************************
 * tm700_demo_node.cpp
 *
 * Copyright 2016 Copyright 2016 Techman Robot Inc.
 *
 * 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.
 *********************************************************************
 *
 * Author: Yun-Hsuan Tsai
 */

#include <ros/ros.h>
#include <ros/console.h>

#include <moveit/move_group_interface/move_group.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit/robot_state/robot_state.h>
#include <moveit/robot_state/conversions.h>

#include <moveit_msgs/DisplayRobotState.h>
#include <moveit_msgs/DisplayTrajectory.h>

#include <moveit_msgs/AttachedCollisionObject.h>
#include <moveit_msgs/CollisionObject.h>

#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cmath>

#include "tm_msgs/SetIO.h"
//#include "tm_msgs/SetIORequest.h"
//#include "tm_msgs/SetIOResponse.h"

//get current joint values of TM5
void get_current_joint_values(moveit::planning_interface::MoveGroup& group,
                              moveit::planning_interface::MoveGroup::Plan& plan,
<<<<<<< HEAD
                                                            std::vector<double>& record_joint
                                                        ){
        //if(!ros::ok()) return false;
        bool success = false;

        std::vector<double> joint_value;
        joint_value = group.getCurrentJointValues();
    record_joint = group.getCurrentJointValues();

    ROS_INFO("In get_current_joint_values()");
        for(int i = 0; i<joint_value.size(); i++){
            joint_value[i] = joint_value[i]*180/M_PI;
            printf("Joint %d: %lf\n",i+1, joint_value[i]);
        }
=======
															std::vector<double>& record_joint
														){
		//if(!ros::ok()) return false;
		bool success = false;

		std::vector<double> joint_value;
		joint_value = group.getCurrentJointValues();
    record_joint = group.getCurrentJointValues();

    ROS_INFO("In get_current_joint_values()");
		for(int i = 0; i<joint_value.size(); i++){
			joint_value[i] = joint_value[i]*180/M_PI;
			printf("Joint %d: %lf\n",i+1, joint_value[i]);
		}
>>>>>>> e5e86088216a75c4dc8ce5dc610f4fea4bd2b763
}

bool try_move_to_named_target(moveit::planning_interface::MoveGroup& group,
                  moveit::planning_interface::MoveGroup::Plan& plan,
                  const std::string& target_name,
                  unsigned int max_try_times = 1
                 ) {
  if(!ros::ok()) return false;
  bool success = false;

  for(unsigned int i = 0; i < max_try_times; i++) {

    group.setNamedTarget(target_name);

    if(group.move()) {
      success = true;
      break;
    }
    else {
      if(!ros::ok()) break;
      sleep(1);
    }
  }
  return success;
}

bool try_move_to_joint_target(moveit::planning_interface::MoveGroup& group,
                  moveit::planning_interface::MoveGroup::Plan& plan,
                  const std::vector<double>& joint_target,
                  unsigned int max_try_times = 1
                 ) {
  if(!ros::ok()) return false;
  bool success = false;

  for(unsigned int i = 0; i < max_try_times; i++) {

    group.setJointValueTarget(joint_target);

    if(group.move()) {
      success = true;
      break;
    }
    else {
      if(!ros::ok()) break;
      sleep(1);
    }
  }
}

int main(int argc, char **argv)
{

  ros::init(argc, argv, "tm700_demo_test");
  ros::NodeHandle node_handle;
  ros::ServiceClient set_io_client = node_handle.serviceClient<tm_msgs::SetIO>("tm_driver/set_io");
  tm_msgs::SetIO io_srv;
  io_srv.request.fun = 2;//tm_msgs::SetIORequest::FUN_SET_EE_DIGITAL_OUT;
  io_srv.request.ch = 0;
  io_srv.request.value = 0.0;

  // start a background "spinner", so our node can process ROS messages
  //  - this lets us know when the move is completed
  ros::AsyncSpinner spinner(1);
  spinner.start();

  sleep(1);

  // Setup
  // ^^^^^
  // The :move_group_interface:`MoveGroup` class can be easily
  // setup using just the name
  // of the group you would like to control and plan for.
  moveit::planning_interface::MoveGroup group("manipulator");
  // We will use the :planning_scene_interface:`PlanningSceneInterface`
  // class to deal directly with the world.
  moveit::planning_interface::PlanningSceneInterface planning_scene_interface;
  // (Optional) Create a publisher for visualizing plans in Rviz.
  //ros::Publisher display_publisher = node_handle.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true);
  //moveit_msgs::DisplayTrajectory display_trajectory;

  // Getting Basic Information
  // ^^^^^^^^^^^^^^^^^^^^^^^^^
  // We can print the name of the reference frame for this robot.
  ROS_INFO("Reference frame: %s", group.getPlanningFrame().c_str());
  // We can also print the name of the end-effector link for this group.
  ROS_INFO("Reference frame: %s", group.getEndEffectorLink().c_str());

  moveit::planning_interface::MoveGroup::Plan my_plan;

  set_io_client.call(io_srv);

  group.setPlanningTime(30.0);

  //try_move_to_named_target(group, my_plan, "home", 100);

  std::vector<double> joint_target_1;
  std::vector<double> joint_target_2;

<<<<<<< HEAD
    std::vector<double> record_joint_1;
    std::vector<double> record_joint_2;
    std::vector<double> record_joint_3;
=======
	std::vector<double> record_joint_1;
	std::vector<double> record_joint_2;
	std::vector<double> record_joint_3;
>>>>>>> e5e86088216a75c4dc8ce5dc610f4fea4bd2b763

  double joint_value = 0;

  joint_target_1.assign(6, 0.0f);
  joint_target_1[0] = 0.0174533*( 30.0);
  joint_target_1[1] = 0.0174533*( 15.0);
  joint_target_1[2] = 0.0174533*(105.0);
  joint_target_1[3] = 0.0174533*(-30.0);
  joint_target_1[4] = 0.0174533*( 90.0);
  joint_target_1[5] = 0.0174533*( 30.0);

  joint_target_2.assign(6, 0.0f);
  joint_target_2[0] = 0.0174533*(-30.0);
  joint_target_2[1] = 0.0174533*(-15.0);
  joint_target_2[2] = 0.0174533*( 90.0);
  joint_target_2[3] = 0.0174533*(-75.0);
  joint_target_2[4] = 0.0174533*(120.0);

  int step = 0;
  int flag = 0;

  while (ros::ok()) {
    switch (5) {

     case 0: //gripper off
<<<<<<< HEAD
       io_srv.request.fun = 2;
       io_srv.request.ch = 0;
       io_srv.request.value = 0.0;

       if (set_io_client.call(io_srv))
         ROS_INFO("Set IO success");
       else
         ROS_WARN("Failed to call service set_io");
       break;

     case 1: //move to ready
       ROS_INFO("move...");
       //try_move_to_named_target(group, my_plan, "ready", 100);
       break;

     case 2: //light on
   /*
       io_srv.request.fun = 2;
       io_srv.request.ch = 3;
       io_srv.request.value = 1.0;
   */
       if (set_io_client.call(io_srv))
         ROS_INFO("Set IO success");
       else
         ROS_WARN("Failed to call service set_io");
       break;

     case 3: //wait 3 sec
       sleep(3);
       break;

    case 4: //light off
      io_srv.request.fun = 2;
      io_srv.request.ch = 3;
      io_srv.request.value = 0.0;
      if (set_io_client.call(io_srv))
        ROS_INFO("Set IO success");
      else
        ROS_WARN("Failed to call service set_io");
      break;

    case 5: //move 1
      //ROS_INFO("move...");
      //try_move_to_joint_target(group, my_plan, joint_target_1, 100);
      ROS_INFO("Teaching Pose 1...");
=======
	   io_srv.request.fun = 2;
	   io_srv.request.ch = 0;
	   io_srv.request.value = 0.0;

	   if (set_io_client.call(io_srv))
	     ROS_INFO("Set IO success");
	   else
	     ROS_WARN("Failed to call service set_io");
	   break;

     case 1: //move to ready
	   ROS_INFO("move...");
	   //try_move_to_named_target(group, my_plan, "ready", 100);
	   break;

     case 2: //light on
   /*
	   io_srv.request.fun = 2;
	   io_srv.request.ch = 3;
	   io_srv.request.value = 1.0;
   */
	   if (set_io_client.call(io_srv))
	     ROS_INFO("Set IO success");
	   else
	     ROS_WARN("Failed to call service set_io");
	   break;

     case 3: //wait 3 sec
	   sleep(3);
	   break;

    case 4: //light off
	  io_srv.request.fun = 2;
	  io_srv.request.ch = 3;
	  io_srv.request.value = 0.0;
	  if (set_io_client.call(io_srv))
	    ROS_INFO("Set IO success");
	  else
	    ROS_WARN("Failed to call service set_io");
	  break;

    case 5: //move 1
	  //ROS_INFO("move...");
	  //try_move_to_joint_target(group, my_plan, joint_target_1, 100);
	  ROS_INFO("Teaching Pose 1...");
>>>>>>> e5e86088216a75c4dc8ce5dc610f4fea4bd2b763
    while(flag == 0){
      printf("Finish Teaching? Yes: 1, No:0\n");
      scanf("%d", &flag);
      get_current_joint_values(group, my_plan, record_joint_1);
    }
    flag = 0;

    ROS_INFO("Teaching Pose 2...");
    while(flag == 0){
      printf("Finish Teaching? Yes: 1, No:0\n");
      scanf("%d", &flag);
      get_current_joint_values(group, my_plan, record_joint_2);
    }
    flag = 0;

    ROS_INFO("Teaching Pose 3...");
    while(flag == 0){
      printf("Finish Teaching? Yes: 1, No:0\n");
      scanf("%d", &flag);
      get_current_joint_values(group, my_plan, record_joint_3);
    }

    //ROS_INFO("Teaching Pose 1...");
<<<<<<< HEAD
      for(int i = 0; i<record_joint_1.size(); i++){
          joint_value = record_joint_1[i]*180/M_PI;
          printf("Joint %d: degree: %lf, rad: %lf\n", i+1, joint_value, record_joint_1[i]);
      }
=======
	  for(int i = 0; i<record_joint_1.size(); i++){
		  joint_value = record_joint_1[i]*180/M_PI;
		  printf("Joint %d: degree: %lf, rad: %lf\n", i+1, joint_value, record_joint_1[i]);
	  }
>>>>>>> e5e86088216a75c4dc8ce5dc610f4fea4bd2b763

    while(ros::ok()){
      try_move_to_named_target(group, my_plan, "home", 100);
      //wait 3 seconds
      sleep(3);
      try_move_to_joint_target(group, my_plan, record_joint_1, 100);
      sleep(3);
      try_move_to_joint_target(group, my_plan, record_joint_2, 100);
      sleep(3);
      try_move_to_joint_target(group, my_plan, record_joint_3, 100);
      sleep(3);
    }

<<<<<<< HEAD
      break;

    case 6: //gripper on
      io_srv.request.fun = 2;
      io_srv.request.ch = 0;
      io_srv.request.value = 1.0;
      if (set_io_client.call(io_srv))
        ROS_INFO("Set IO success");
      else
        ROS_WARN("Failed to call service set_io");
      break;

    case 7: //wait 1 sec
      sleep(1);
      break;

    case 8: //move 2...
      ROS_INFO("move...");
      //try_move_to_joint_target(group, my_plan, joint_target_2, 100);
      break;
=======
	  break;

    case 6: //gripper on
	  io_srv.request.fun = 2;
	  io_srv.request.ch = 0;
	  io_srv.request.value = 1.0;
	  if (set_io_client.call(io_srv))
	    ROS_INFO("Set IO success");
	  else
	    ROS_WARN("Failed to call service set_io");
	  break;

    case 7: //wait 1 sec
	  sleep(1);
	  break;

    case 8: //move 2...
	  ROS_INFO("move...");
	  //try_move_to_joint_target(group, my_plan, joint_target_2, 100);
	  break;
>>>>>>> e5e86088216a75c4dc8ce5dc610f4fea4bd2b763
    }
    step = (step + 1) % 9;
  }
  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;

/*
int n=4, W=5;
int w[4] = {2,1,3,2};
int v[4] = {3,2,4,2};
*/

int n=100, W=1000;
int w[100] = {63,25,30,46,1,8,27,82,19,53,88,52,8,35,90,44,64,6,79,5,2,6,80,73,45,35,65,20,4,32,29,30,49,67,25,86,79,31,46,7,34,42,92,11,62,95,29,2,53,81,74,93,1,65,46,18,3,13,22,75,28,53,38,35,31,36,43,40,10,72,42,27,32,32,10,92,82,41,25,93,24,71,62,20,37,9,79,58,24,26,36,81,64,49,46,87,64,20,31,60};
int v[100] = {53,9,65,12,56,50,80,45,80,71,97,21,63,29,40,94,50,23,1,76,34,87,11,41,58,83,67,89,65,11,44,78,81,53,58,87,12,95,5,47,91,52,99,26,60,78,90,82,92,23,76,67,66,76,47,23,91,82,59,12,3,95,13,95,15,95,67,45,22,34,53,67,23,90,62,25,14,35,19,7,69,100,15,53,19,60,5,21,34,61,75,71,65,67,8,42,40,2,20,46};

int dp[100][100];

int search(int i, int rem_w) {
  if (dp[i][rem_w]!=-1) return dp[i][rem_w];

  if (i >= n)   return 0;
  if (w[i] > rem_w) return search(i+1, rem_w);
  return dp[i][rem_w] = max(search(i+1, rem_w-w[i]) + v[i], search(i+1, rem_w));
}

void solve() {
  cout << search(0, W) << endl;
}

int main(int argc, char const *argv[]) {
  memset(dp, -1, sizeof(dp));
  solve();
}
<commit_msg>fix bug for large data set<commit_after>#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;

#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)

/*
int n=4, W=5;
int w[4] = {2,1,3,2};
int v[4] = {3,2,4,2};
*/

int n=100, W=1000;
int w[100] = {63,25,30,46,1,8,27,82,19,53,88,52,8,35,90,44,64,6,79,5,2,6,80,73,45,35,65,20,4,32,29,30,49,67,25,86,79,31,46,7,34,42,92,11,62,95,29,2,53,81,74,93,1,65,46,18,3,13,22,75,28,53,38,35,31,36,43,40,10,72,42,27,32,32,10,92,82,41,25,93,24,71,62,20,37,9,79,58,24,26,36,81,64,49,46,87,64,20,31,60};
int v[100] = {53,9,65,12,56,50,80,45,80,71,97,21,63,29,40,94,50,23,1,76,34,87,11,41,58,83,67,89,65,11,44,78,81,53,58,87,12,95,5,47,91,52,99,26,60,78,90,82,92,23,76,67,66,76,47,23,91,82,59,12,3,95,13,95,15,95,67,45,22,34,53,67,23,90,62,25,14,35,19,7,69,100,15,53,19,60,5,21,34,61,75,71,65,67,8,42,40,2,20,46};

long dp[100][1001];
long search(int i, int rem_w) {
  if (i >= n) return 0;

  if (dp[i][rem_w]!=-1) return dp[i][rem_w];

  if (w[i] > rem_w) return search(i+1, rem_w);
  return dp[i][rem_w] = max(search(i+1, rem_w-w[i]) + v[i], search(i+1, rem_w));
}

void solve() {
  memset(dp, -1, sizeof(dp));
  cout << search(0, W) << endl;
}

int main(int argc, char const *argv[]) {
  solve();
}
<|endoftext|>


<commit_before>//
//  main.cpp
//  wPackage
//
//  Created by Adawat Chanchua on 7/3/2560 BE.
//  Copyright © 2560 Adawat Chanchua. All rights reserved.
//

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
// Lib in the Wonderland
#include "Util.hpp"

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
// C/C++ lib

#include <stdio.h>
#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <vector>
#include <fstream>

using namespace std;

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
// Rapid JSON lib

#include "rapidjson.h"
#include "document.h"

using namespace rapidjson;

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
// Function declaration

void executeCommand(Value& commandCollection, Value& platformConf, string packageName, string projectPath, string subCommand);

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
// Constants
const string VERSION = "0.0.0.2";
const string CONF = "conf.json";
const string WONDER_MODULE = "wonder_modules";

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
int main(int argc, const char * argv[]) {

    /***********************************************
     Params order note (From argc, argv convention):
     [0] File path
     [1] Package name
     [2] wonder_config
     [3] subCommand
     ***********************************************/

    // Check package name existence
    if (argc <= 1) {

        cout << "package name NOT found!" << endl;
        return -1;
    }

    string packageName = argv[1];

    // Check wonder_config existence
    if (argc <= 2) {

        cout << "wonderconf NOT found!" << endl;
        return -1;
    }

    // Parse wonderconf to JSON document
    string wonderConfPath = argv[2];

    // Parse sub command (Optional)
    string subCommand;

    if (argc > 3) {

        subCommand = argv[3];
    }

    // Check is wonderconf exist
    string wonderconfLs = execute(string("ls ") + wonderConfPath);

    // Conf NOT exist
    if (wonderconfLs.empty()) {

        cout << "wonderconf.json is NOT exist!" << endl;
        return -1;
    }

    // Read wonderconf
    string wonderConfStr = execute(string("cat ") + string("./") + wonderConfPath);

    Document wonderConf;
    wonderConf.Parse<0>(wonderConfStr.c_str());

    // Get dependencies object
    if (!wonderConf.HasMember("dependencies")) {

        cout << "wonderconf does NOT have dependencies!" << endl;
        return -1;
    }

    Value& dependencies = wonderConf["dependencies"];

    // Check is conf exist
    string confPath = string("./") + string(WONDER_MODULE) + string("/") + packageName + string("/") + string(CONF);

    string confLs = execute(string("ls ") + confPath);

    // Conf NOT exist
    if (confLs.empty()) {

        cout << "conf.json is NOT exist!" << endl;
        return -1;
    }

    // Read conf
    string confStr = execute(string("cat ") + confPath);

    // Parse conf to JSON document
    Document conf;
    conf.Parse(confStr.c_str());

    // Execute command
    rapidjson::Value::MemberIterator depIt;
    for (depIt = dependencies.MemberBegin(); depIt != dependencies.MemberEnd(); ++depIt) {

        // Get platform name
        string platformName = depIt->name.GetString();
        Value& platformConf = dependencies[platformName.c_str()];

        if (!platformConf.HasMember("projectPath")) {

            cout << "projectPath does NOT specified for " << platformName << endl;
            continue;
        }

        string projectPath = platformConf["projectPath"].GetString();

        // Get command from platform name
        if (!conf.HasMember(platformName.c_str())) {

            cout << platformName << " does NOT exist." << endl;
            continue;
        }

        Value& commands = conf[platformName.c_str()];

        // Execute commands
        for (SizeType i=0; i < commands.Size(); ++i) {

            executeCommand(commands[i], platformConf, packageName, projectPath, subCommand);
        }
    }

    return 0;
}

void executeCommand(Value& commandCollection, Value& platformConf, string packageName, string projectPath, string subCommand) {

    string command = commandCollection["command"].GetString();

    // Specify mode
    const int MODE_NORMAL = 0;
    const int MODE_REVERSE_COPY = 1;

    int operMode = MODE_NORMAL;

    if (subCommand.compare("-reverse_copy") == 0)
        operMode = MODE_REVERSE_COPY;

    bool isCopyCommand = command.compare("copy") == 0;

    if (command.compare("copy") == 0 &&
        (operMode == MODE_NORMAL || operMode == MODE_REVERSE_COPY)) {

        string src = commandCollection["src"].GetString();
        string dst = commandCollection["dst"].GetString();

        // Set absolute paths by mode
        string srcAbs;
        string dstAbs;

        switch (operMode) {
            case MODE_REVERSE_COPY:

                srcAbs = projectPath + dst;
                dstAbs = string("./") + string(WONDER_MODULE) + string("/") + packageName + string("/") + src;
                break;
            case MODE_NORMAL:
            default:

                srcAbs = string("./") + string(WONDER_MODULE) + string("/") + packageName + string("/") + src;
                dstAbs = projectPath + dst;
                break;
        }

        string cmd = string("cp -Rf ") + srcAbs + string(" ") + dstAbs;
        cout << "cmd: " << cmd << endl;
        string exeResult = execute(cmd);

        cout << exeResult << endl;
    }
    else if (command.compare("exec") == 0 && operMode == MODE_NORMAL) {

        string parm = commandCollection["parm"].GetString();

        string exeResult = execute(parm);

        cout << exeResult << endl;
    }
    else if (command.compare("settings.gradle") == 0) {

        if (commandCollection.HasMember("upsert")) {

            // Supported settings.gradle format
            //   include ':app', ':wondertoolkit'

            // Vars
            string insertModule = commandCollection["upsert"].GetString();
            string settingGradleSubPath = "";

            if (platformConf.HasMember("settingGradleSubPath"))
                settingGradleSubPath = platformConf["settingGradleSubPath"].GetString();

            // Read settings.gradle file
            string settingsGradlePath = projectPath + settingGradleSubPath + string("settings.gradle");

            cout << "settings.gradle path: " << settingsGradlePath << endl;

            string settingsGradleStr = execute(string("cat ") + string("./") + settingsGradlePath);

            // Gradle header
            vector<char>header;

            // Get all module (As token)
            vector<string> modules;
            vector<char> tmpModule;

            enum STATE {
                STATE_SEEK_HEAD = 0,
                STATE_SEEK,
                STATE_READ,
                STATE_END,
            };

            int currState = STATE_SEEK_HEAD;

            // Read character 1 by 1, to get all modules (The characters between single quote)
            for (int i=0; i<settingsGradleStr.length(); ++i) {

                char curr = settingsGradleStr[i];

                if (currState == STATE_SEEK_HEAD) {

                    if (curr == '\'')
                        currState = STATE_READ;
                    else if (curr != ' ')
                        header.push_back(curr);
                }
                else if (currState == STATE_SEEK) {

                    if (curr == '\'')
                        currState = STATE_READ;
                }
                else if (currState == STATE_READ) {

                    if (curr == '\'')
                        currState = STATE_END;
                    else if (curr != ':') {

                        tmpModule.push_back(curr);
                    }
                }

                if (currState == STATE_END) {

                    // Convert vector to string
                    std::string tStr(tmpModule.begin(), tmpModule.end());

                    // Add token
                    modules.push_back(tStr);

                    // Clear tmp
                    tmpModule.clear();

                    // Go seek
                    currState = STATE_SEEK;
                }
            }

            // Token matching
            bool isInsert = true;
            for (int i=0; i<modules.size(); ++i) {

                string currModule = modules[i];

                // If the given module is matched =>
                //     Do not insert & break matching
                if (currModule.compare(insertModule) == 0) {

                    isInsert = false;
                    break;
                }
            }

            // Check to insert module
            if (isInsert) {

                // Convert header to string
                std::string headerStr(header.begin(), header.end());

                // Out string
                string outStr = headerStr + string(" ");

                modules.push_back(insertModule);

                // Convert module to file
                for (int i=0; i<modules.size(); ++i) {

                    string currModule = modules[i];

                    outStr = outStr + string("':") + currModule + string("'");

                    if (i < modules.size() - 1)
                        outStr = outStr + string(", ");
                }

                // Remove file
                remove(settingsGradlePath.c_str());

                // Create file again
                ofstream gradleFile;
                gradleFile.open (settingsGradlePath);

                if (gradleFile.is_open()) {

                    gradleFile << outStr << endl;
                    gradleFile.close();
                }
            }
        }
    }
}
<commit_msg>package's copy command has "clean" option (clean = delete before copy)<commit_after>//
//  main.cpp
//  wPackage
//
//  Created by Adawat Chanchua on 7/3/2560 BE.
//  Copyright © 2560 Adawat Chanchua. All rights reserved.
//

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
// Lib in the Wonderland
#include "Util.hpp"

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
// C/C++ lib

#include <stdio.h>
#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <vector>
#include <fstream>

using namespace std;

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
// Rapid JSON lib

#include "rapidjson.h"
#include "document.h"

using namespace rapidjson;

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
// Function declaration

void executeCommand(Value& commandCollection, Value& platformConf, string packageName, string projectPath, string subCommand);

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
// Constants
const string VERSION = "0.0.0.2";
const string CONF = "conf.json";
const string WONDER_MODULE = "wonder_modules";

// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
int main(int argc, const char * argv[]) {

    /***********************************************
     Params order note (From argc, argv convention):
     [0] File path
     [1] Package name
     [2] wonder_config
     [3] subCommand
     ***********************************************/

    // Check package name existence
    if (argc <= 1) {

        cout << "package name NOT found!" << endl;
        return -1;
    }

    string packageName = argv[1];

    // Check wonder_config existence
    if (argc <= 2) {

        cout << "wonderconf NOT found!" << endl;
        return -1;
    }

    // Parse wonderconf to JSON document
    string wonderConfPath = argv[2];

    // Parse sub command (Optional)
    string subCommand;

    if (argc > 3) {

        subCommand = argv[3];
    }

    // Check is wonderconf exist
    string wonderconfLs = execute(string("ls ") + wonderConfPath);

    // Conf NOT exist
    if (wonderconfLs.empty()) {

        cout << "wonderconf.json is NOT exist!" << endl;
        return -1;
    }

    // Read wonderconf
    string wonderConfStr = execute(string("cat ") + string("./") + wonderConfPath);

    Document wonderConf;
    wonderConf.Parse<0>(wonderConfStr.c_str());

    // Get dependencies object
    if (!wonderConf.HasMember("dependencies")) {

        cout << "wonderconf does NOT have dependencies!" << endl;
        return -1;
    }

    Value& dependencies = wonderConf["dependencies"];

    // Check is conf exist
    string confPath = string("./") + string(WONDER_MODULE) + string("/") + packageName + string("/") + string(CONF);

    string confLs = execute(string("ls ") + confPath);

    // Conf NOT exist
    if (confLs.empty()) {

        cout << "conf.json is NOT exist!" << endl;
        return -1;
    }

    // Read conf
    string confStr = execute(string("cat ") + confPath);

    // Parse conf to JSON document
    Document conf;
    conf.Parse(confStr.c_str());

    // Execute command
    rapidjson::Value::MemberIterator depIt;
    for (depIt = dependencies.MemberBegin(); depIt != dependencies.MemberEnd(); ++depIt) {

        // Get platform name
        string platformName = depIt->name.GetString();
        Value& platformConf = dependencies[platformName.c_str()];

        if (!platformConf.HasMember("projectPath")) {

            cout << "projectPath does NOT specified for " << platformName << endl;
            continue;
        }

        string projectPath = platformConf["projectPath"].GetString();

        // Get command from platform name
        if (!conf.HasMember(platformName.c_str())) {

            cout << platformName << " does NOT exist." << endl;
            continue;
        }

        Value& commands = conf[platformName.c_str()];

        // Execute commands
        for (SizeType i=0; i < commands.Size(); ++i) {

            executeCommand(commands[i], platformConf, packageName, projectPath, subCommand);
        }
    }

    return 0;
}

void executeCommand(Value& commandCollection, Value& platformConf, string packageName, string projectPath, string subCommand) {

    string command = commandCollection["command"].GetString();

    // Specify mode
    const int MODE_NORMAL = 0;
    const int MODE_REVERSE_COPY = 1;

    int operMode = MODE_NORMAL;

    if (subCommand.compare("-reverse_copy") == 0)
        operMode = MODE_REVERSE_COPY;

    if (command.compare("copy") == 0 &&
        (operMode == MODE_NORMAL || operMode == MODE_REVERSE_COPY)) {

        string src = commandCollection["src"].GetString();
        string dst = commandCollection["dst"].GetString();

        // Set absolute paths by mode
        string srcAbs;
        string dstAbs;

        switch (operMode) {
            case MODE_REVERSE_COPY:

                srcAbs = projectPath + dst;
                dstAbs = string("./") + string(WONDER_MODULE) + string("/") + packageName + string("/") + src;
                break;
            case MODE_NORMAL:
            default:

                srcAbs = string("./") + string(WONDER_MODULE) + string("/") + packageName + string("/") + src;
                dstAbs = projectPath + dst;
                break;
        }

        bool isClean = false;

        if (commandCollection.HasMember("clean"))
            isClean = string(commandCollection["clean"].GetString()).compare("true") == 0;

        if (isClean) {

            string cmd = string("rm -rf " + dstAbs);
            cout << "clean cmd: " << cmd << endl;
            cout << execute(cmd);
        }

        string cmd = string("cp -Rf ") + srcAbs + string(" ") + dstAbs;
        cout << "cmd: " << cmd << endl;
        string exeResult = execute(cmd);

        cout << exeResult << endl;
    }
    else if (command.compare("exec") == 0 && operMode == MODE_NORMAL) {

        string parm = commandCollection["parm"].GetString();

        string exeResult = execute(parm);

        cout << exeResult << endl;
    }
    else if (command.compare("settings.gradle") == 0) {

        if (commandCollection.HasMember("upsert")) {

            // Supported settings.gradle format
            //   include ':app', ':wondertoolkit'

            // Vars
            string insertModule = commandCollection["upsert"].GetString();
            string settingGradleSubPath = "";

            if (platformConf.HasMember("settingGradleSubPath"))
                settingGradleSubPath = platformConf["settingGradleSubPath"].GetString();

            // Read settings.gradle file
            string settingsGradlePath = projectPath + settingGradleSubPath + string("settings.gradle");

            cout << "settings.gradle path: " << settingsGradlePath << endl;

            string settingsGradleStr = execute(string("cat ") + string("./") + settingsGradlePath);

            // Gradle header
            vector<char>header;

            // Get all module (As token)
            vector<string> modules;
            vector<char> tmpModule;

            enum STATE {
                STATE_SEEK_HEAD = 0,
                STATE_SEEK,
                STATE_READ,
                STATE_END,
            };

            int currState = STATE_SEEK_HEAD;

            // Read character 1 by 1, to get all modules (The characters between single quote)
            for (int i=0; i<settingsGradleStr.length(); ++i) {

                char curr = settingsGradleStr[i];

                if (currState == STATE_SEEK_HEAD) {

                    if (curr == '\'')
                        currState = STATE_READ;
                    else if (curr != ' ')
                        header.push_back(curr);
                }
                else if (currState == STATE_SEEK) {

                    if (curr == '\'')
                        currState = STATE_READ;
                }
                else if (currState == STATE_READ) {

                    if (curr == '\'')
                        currState = STATE_END;
                    else if (curr != ':') {

                        tmpModule.push_back(curr);
                    }
                }

                if (currState == STATE_END) {

                    // Convert vector to string
                    std::string tStr(tmpModule.begin(), tmpModule.end());

                    // Add token
                    modules.push_back(tStr);

                    // Clear tmp
                    tmpModule.clear();

                    // Go seek
                    currState = STATE_SEEK;
                }
            }

            // Token matching
            bool isInsert = true;
            for (int i=0; i<modules.size(); ++i) {

                string currModule = modules[i];

                // If the given module is matched =>
                //     Do not insert & break matching
                if (currModule.compare(insertModule) == 0) {

                    isInsert = false;
                    break;
                }
            }

            // Check to insert module
            if (isInsert) {

                // Convert header to string
                std::string headerStr(header.begin(), header.end());

                // Out string
                string outStr = headerStr + string(" ");

                modules.push_back(insertModule);

                // Convert module to file
                for (int i=0; i<modules.size(); ++i) {

                    string currModule = modules[i];

                    outStr = outStr + string("':") + currModule + string("'");

                    if (i < modules.size() - 1)
                        outStr = outStr + string(", ");
                }

                // Remove file
                remove(settingsGradlePath.c_str());

                // Create file again
                ofstream gradleFile;
                gradleFile.open (settingsGradlePath);

                if (gradleFile.is_open()) {

                    gradleFile << outStr << endl;
                    gradleFile.close();
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>#include <OpenCL/opencl.h>

#define PV_USE_OPENCL

#include "../src/arch/opencl/CLDevice.hpp"
#include "../src/arch/opencl/CLKernel.hpp"
#include "../src/arch/opencl/CLBuffer.hpp"
#include "../src/utils/Timer.hpp"
#include "../src/utils/cl_random.h"

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

#define DEVICE 1

#define NX 256
#define NY 256
#define NXL 16
#define NYL 8

int check_results(uint4 * rnd_state, uint4 * rnd_state2, int count);
void c_rand(uint4 * rnd_state, int count);

int main(int argc, char * argv[])
{
   unsigned int nxl, nyl;

   PV::Timer timer;

   int argid  = 0;
   int query  = 0;
   int device = DEVICE;
   int status = CL_SUCCESS;

   int nWarm = 10, nLoops = 100;

   if (argc > 1) {
      device = atoi(argv[1]);
   }

   PV::CLKernel * kernel;
   PV::CLDevice * cld = new PV::CLDevice(device);

   // query and print information about the devices found
   //
   if (query) cld->query_device_info();

   if (device == 0) {
      nxl = NXL;
      nyl = NYL;
   }
   else {
      nxl = 1;
      nyl = 1;
   }

   kernel = cld->createKernel("kernels/test_cl_random.cl", "cl_rand");

   const size_t mem_size = NX*NY*sizeof(uint4);

   uint4 * rnd_state  = cl_random_init(NX*NY);
   uint4 * rnd_state2 = cl_random_init(NX*NY);

   assert(rnd_state  != NULL);
   assert(rnd_state2 != NULL);

   // create device buffer
   //
   PV::CLBuffer * d_rnd_state = cld->createBuffer(CL_MEM_COPY_HOST_PTR, mem_size, rnd_state);

   status |= kernel->setKernelArg(argid++, NX);
   status |= kernel->setKernelArg(argid++, NY);
   status |= kernel->setKernelArg(argid++, 1);
   status |= kernel->setKernelArg(argid++, 0);
   status |= kernel->setKernelArg(argid++, d_rnd_state);

   printf("Executing on device...");
   kernel->run(NX*NY, nxl*nyl);

   // Check results for accuracy
   //
   printf("\nChecking results...");
   d_rnd_state->copyFromDevice();
   status = check_results(rnd_state, rnd_state2, NX*NY);
   if (status != CL_SUCCESS) {
      exit(status);
   }

   printf(" CORRECT\n");

   for (int n = 0; n < nWarm; n++) {
      kernel->run(NX*NY, nxl*nyl);
   }

   printf("Timing %d loops on device... ", nLoops);
   timer.start();
   for (int n = 0; n < nLoops; n++) {
      kernel->run(NX*NY, nxl*nyl);
   }
   status |= kernel->finish();
   timer.stop();
   timer.elapsed_time();

   printf("Timing %d loops on host..... ", nLoops);
   timer.start();
   for (int n = 0; n < nLoops; n++) {
      c_rand(rnd_state2, NX*NY);
   }
   timer.stop();
   timer.elapsed_time();

   // Shutdown and cleanup
   //
   //   clReleaseMemObject(d_rnd_state);
   delete cld;

   printf("Finished...\n");

   return status;
}

int check_results(uint4 * rnd_state, uint4 * rnd_state2, int count)
{
   uint4 state;

   for (int k = 0; k < count; k++) {
      state = cl_random_get(rnd_state2[k]);
      if (state.s0 != rnd_state[k].s0) {
         printf("check_results: results differ at k==%d, rnd_state==%d, rnd_state2==%d\n",
                k, state.s0, rnd_state[k].s0);
         return 1;
      }
   }
   return 0;
}

void c_rand(uint4 * rnd_state, int count)
{
   for (int k = 0; k < count; k++) {
      rnd_state[k] = cl_random_get(rnd_state[k]);
   }
}
<commit_msg>Added include of pv_uint4.h<commit_after>#include <OpenCL/opencl.h>

#undef PV_USE_OPENCL

#include "../src/arch/opencl/CLDevice.hpp"
#include "../src/arch/opencl/CLKernel.hpp"
#include "../src/arch/opencl/CLBuffer.hpp"
#include "../src/arch/opencl/pv_uint4.h"
#include "../src/utils/Timer.hpp"
#include "../src/utils/cl_random.h"

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

#define DEVICE 1

#define NX 256
#define NY 256
#define NXL 16
#define NYL 8

int check_results(uint4 * rnd_state, uint4 * rnd_state2, int count);
void c_rand(uint4 * rnd_state, int count);

int main(int argc, char * argv[])
{
   unsigned int nxl, nyl;

   PV::Timer timer;

   int argid  = 0;
   int query  = 0;
   int device = DEVICE;
   int status = CL_SUCCESS;

   int nWarm = 10, nLoops = 100;

   if (argc > 1) {
      device = atoi(argv[1]);
   }

   PV::CLKernel * kernel;
   PV::CLDevice * cld = new PV::CLDevice(device);

   // query and print information about the devices found
   //
   if (query) cld->query_device_info();

   if (device == 0) {
      nxl = NXL;
      nyl = NYL;
   }
   else {
      nxl = 1;
      nyl = 1;
   }

   kernel = cld->createKernel("kernels/test_cl_random.cl", "cl_rand");

   const size_t mem_size = NX*NY*sizeof(uint4);

   uint4 * rnd_state  = cl_random_init(NX*NY);
   uint4 * rnd_state2 = cl_random_init(NX*NY);

   assert(rnd_state  != NULL);
   assert(rnd_state2 != NULL);

   // create device buffer
   //
   PV::CLBuffer * d_rnd_state = cld->createBuffer(CL_MEM_COPY_HOST_PTR, mem_size, rnd_state);

   status |= kernel->setKernelArg(argid++, NX);
   status |= kernel->setKernelArg(argid++, NY);
   status |= kernel->setKernelArg(argid++, 1);
   status |= kernel->setKernelArg(argid++, 0);
   status |= kernel->setKernelArg(argid++, d_rnd_state);

   printf("Executing on device...");
   kernel->run(NX*NY, nxl*nyl);

   // Check results for accuracy
   //
   printf("\nChecking results...");
   d_rnd_state->copyFromDevice();
   status = check_results(rnd_state, rnd_state2, NX*NY);
   if (status != CL_SUCCESS) {
      exit(status);
   }

   printf(" CORRECT\n");

   for (int n = 0; n < nWarm; n++) {
      kernel->run(NX*NY, nxl*nyl);
   }

   printf("Timing %d loops on device... ", nLoops);
   timer.start();
   for (int n = 0; n < nLoops; n++) {
      kernel->run(NX*NY, nxl*nyl);
   }
   status |= kernel->finish();
   timer.stop();
   timer.elapsed_time();

   printf("Timing %d loops on host..... ", nLoops);
   timer.start();
   for (int n = 0; n < nLoops; n++) {
      c_rand(rnd_state2, NX*NY);
   }
   timer.stop();
   timer.elapsed_time();

   // Shutdown and cleanup
   //
   //   clReleaseMemObject(d_rnd_state);
   delete cld;

   printf("Finished...\n");

   return status;
}

int check_results(uint4 * rnd_state, uint4 * rnd_state2, int count)
{
   uint4 state;

   for (int k = 0; k < count; k++) {
      state = cl_random_get(rnd_state2[k]);
      if (state.s0 != rnd_state[k].s0) {
         printf("check_results: results differ at k==%d, rnd_state==%d, rnd_state2==%d\n",
                k, state.s0, rnd_state[k].s0);
         return 1;
      }
   }
   return 0;
}

void c_rand(uint4 * rnd_state, int count)
{
   for (int k = 0; k < count; k++) {
      rnd_state[k] = cl_random_get(rnd_state[k]);
   }
}
<|endoftext|>