<commit_before>/* parsing.hh -- parsers
 *
 * Copyright (C) 2018 Camille Scott
 * All rights reserved.
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#ifndef PARSING_HH
#define PARSING_HH

#include <string>
#include <utility>
#include <vector>

#include "oxli/read_parsers.hh"
#include "utils/stringutils.h"

using namespace oxli;
using namespace oxli:: read_parsers;

using namespace utils;

namespace boink {

using std::string;
using std::vector;
using std::pair;

struct ReadBundle {

    bool has_left;
    bool has_right;

    Read left;
    Read right;

};

bool check_char(const char c, const string against) {
    for (auto ag : against) {
        if (c == ag) {
            return true;
        }
    }
    return false;
}

pair<string, string> split_on_first(const string& name,
                                    const string delims=" \t") {
    string left = "";
    string right = "";
    for (size_t i = 0; i < name.length(); ++i) {
        const char c = name[i];
        if (left == "") {
            if (check_char(c, delims)) {
                left = name.substr(0, i);
            }
        } else {
            if (!check_char(c, delims)) {
                right = name.substr(i, name.length());
                break;
            }
        }
    }
    if (left == "") {
        left = name;
    }

    return std::make_pair(left, right);
}

bool check_is_pair(const string& left, const string& right) {
    auto left_split = split_on_first(left);
    auto right_split = split_on_first(right);

    if (StringUtils::endsWith(left_split.first, "/1") &&
        StringUtils::endsWith(right_split.first, "/2")) {

        auto left_sub = split_on_first(left_split.first, "/");
        auto right_sub = split_on_first(right_split.first, "/");

        if (left_sub.first != ""  && left_sub.first == right_sub.first) {
            return true;
        }
    } else if (left_split.first == right_split.first &&
               StringUtils::endsWith(left_split.second, "1:") &&
               StringUtils::endsWith(right_split.second, "2:")) {
        return true;
    } else if (left_split.first == right_split.first &&
               StringUtils::endsWith(left_split.second, "/1") &&
               StringUtils::endsWith(right_split.second, "/2")) {
        auto left_sub = split_on_first(left_split.second, "/");
        auto right_sub = split_on_first(right_split.second, "/");

        if (left_sub.first != "" && left_sub.first == right_sub.first) {
            return true;
        }
    }
    return false;
}

bool check_is_left(const string& name) {
    auto split = split_on_first(name);
    if (StringUtils::endsWith(split.first, "/1") ||
        StringUtils::endsWith(split.second, "1:") ||
        StringUtils::endsWith(split.second, "/1")) {
        return true;
    }
    return false;
}

bool check_is_right(const string& name) {
    auto split = split_on_first(name);
    if (StringUtils::endsWith(split.first, "/2") ||
        StringUtils::endsWith(split.second, "2:") ||
        StringUtils::endsWith(split.second, "/2")) {
        return true;
    }
    return false;
}

void filter_length(ReadBundle& bundle, uint32_t length) {
    if (bundle.left.sequence.length() < length) {
        bundle.has_left = false;
    }
    if (bundle.right.sequence.length() < length) {
        bundle.has_right = false;
    }
}

template <class ParserType = FastxReader>
class SplitPairedReader {

    ReadParserPtr<ParserType> left_parser;
    ReadParserPtr<ParserType> right_parser;
    uint32_t _min_length;
    bool     _force_name_match;
    uint64_t _n_reads;

    SplitPairedReader(const string &left,
                 const string &right,
                 uint32_t min_length=0,
                 bool force_name_match=false)
        : _min_length(min_length),
          _force_name_match(force_name_match) {

        left_parser = get_parser<ParserType>(left);
        right_parser = get_parser<ParserType>(right);
    }

    bool is_complete() const {
        if (left_parser->is_complete() != right_parser->is_complete()) {
            throw BoinkException("Mismatched split paired files.");
        }
        return left_parser->is_complete();
    }

    ReadBundle next() {
        ReadBundle result;
        try {
            result.left = this->left_parser->get_next_read();
            result.right = this->right_parser->get_next_read();
        } catch (NoMoreReadsAvailable) {
            result.has_left = false;
            result.has_right = false;
            return result;
        }

        result.left.set_clean_seq();
        result.right.set_clean_seq();
        result.has_left = true;
        result.has_right = true;

        if (this->_force_name_match) {
            if (!check_is_pair(result.left.name, result.right.name)) {
                throw BoinkException("Unpaired reads");
            }
        }

        if (this->_min_length > 0) {
            filter_length(result, this->_min_length);
        }

        return result;
    }
};

}

#endif
<commit_msg>ADd public dec<commit_after>/* parsing.hh -- parsers
 *
 * Copyright (C) 2018 Camille Scott
 * All rights reserved.
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#ifndef PARSING_HH
#define PARSING_HH

#include <string>
#include <utility>
#include <vector>

#include "oxli/read_parsers.hh"
#include "utils/stringutils.h"

#include "boink/boink.hh"

using namespace oxli;
using namespace oxli:: read_parsers;

using namespace utils;

namespace boink {

using std::string;
using std::vector;
using std::pair;

struct ReadBundle {

    bool has_left;
    bool has_right;

    Read left;
    Read right;

};

bool check_char(const char c, const string against) {
    for (auto ag : against) {
        if (c == ag) {
            return true;
        }
    }
    return false;
}

pair<string, string> split_on_first(const string& name,
                                    const string delims=" \t") {
    string left = "";
    string right = "";
    for (size_t i = 0; i < name.length(); ++i) {
        const char c = name[i];
        if (left == "") {
            if (check_char(c, delims)) {
                left = name.substr(0, i);
            }
        } else {
            if (!check_char(c, delims)) {
                right = name.substr(i, name.length());
                break;
            }
        }
    }
    if (left == "") {
        left = name;
    }

    return std::make_pair(left, right);
}

bool check_is_pair(const string& left, const string& right) {
    auto left_split = split_on_first(left);
    auto right_split = split_on_first(right);

    if (StringUtils::endsWith(left_split.first, "/1") &&
        StringUtils::endsWith(right_split.first, "/2")) {

        auto left_sub = split_on_first(left_split.first, "/");
        auto right_sub = split_on_first(right_split.first, "/");

        if (left_sub.first != ""  && left_sub.first == right_sub.first) {
            return true;
        }
    } else if (left_split.first == right_split.first &&
               StringUtils::endsWith(left_split.second, "1:") &&
               StringUtils::endsWith(right_split.second, "2:")) {
        return true;
    } else if (left_split.first == right_split.first &&
               StringUtils::endsWith(left_split.second, "/1") &&
               StringUtils::endsWith(right_split.second, "/2")) {
        auto left_sub = split_on_first(left_split.second, "/");
        auto right_sub = split_on_first(right_split.second, "/");

        if (left_sub.first != "" && left_sub.first == right_sub.first) {
            return true;
        }
    }
    return false;
}

bool check_is_left(const string& name) {
    auto split = split_on_first(name);
    if (StringUtils::endsWith(split.first, "/1") ||
        StringUtils::endsWith(split.second, "1:") ||
        StringUtils::endsWith(split.second, "/1")) {
        return true;
    }
    return false;
}

bool check_is_right(const string& name) {
    auto split = split_on_first(name);
    if (StringUtils::endsWith(split.first, "/2") ||
        StringUtils::endsWith(split.second, "2:") ||
        StringUtils::endsWith(split.second, "/2")) {
        return true;
    }
    return false;
}

void filter_length(ReadBundle& bundle, uint32_t length) {
    if (bundle.left.sequence.length() < length) {
        bundle.has_left = false;
    }
    if (bundle.right.sequence.length() < length) {
        bundle.has_right = false;
    }
}

template <class ParserType = FastxReader>
class SplitPairedReader {

    ReadParserPtr<ParserType> left_parser;
    ReadParserPtr<ParserType> right_parser;
    uint32_t _min_length;
    bool     _force_name_match;
    uint64_t _n_reads;

public:

    SplitPairedReader(const string &left,
                 const string &right,
                 uint32_t min_length=0,
                 bool force_name_match=false)
        : _min_length(min_length),
          _force_name_match(force_name_match) {

        left_parser = get_parser<ParserType>(left);
        right_parser = get_parser<ParserType>(right);
    }

    bool is_complete() const {
        if (left_parser->is_complete() != right_parser->is_complete()) {
            throw BoinkException("Mismatched split paired files.");
        }
        return left_parser->is_complete();
    }

    ReadBundle next() {
        ReadBundle result;
        try {
            result.left = this->left_parser->get_next_read();
            result.right = this->right_parser->get_next_read();
        } catch (NoMoreReadsAvailable) {
            result.has_left = false;
            result.has_right = false;
            return result;
        }

        result.left.set_clean_seq();
        result.right.set_clean_seq();
        result.has_left = true;
        result.has_right = true;

        if (this->_force_name_match) {
            if (!check_is_pair(result.left.name, result.right.name)) {
                throw BoinkException("Unpaired reads");
            }
        }

        if (this->_min_length > 0) {
            filter_length(result, this->_min_length);
        }

        return result;
    }
};

}

#endif
<|endoftext|>


<commit_before>#ifdef  CLPP_CONTEXT_IPP
	#error "multiple inclusions of the same implementation file"
#else
#define CLPP_CONTEXT_IPP

#ifndef CLPP_CONTEXT_HPP
	#error "header file has not been included; maybe it isn't required anymore?"
	#include "clpp/context.hpp"
#endif

#include "utility/to_underlying.hpp"

//#include <iostream>
#include <iterator>
#include <algorithm>

namespace cl {
	//====================================================================================
	// Copy-Assignment
	//====================================================================================

	auto Context::operator=(const Context & rhs) -> Context & {
        if (this != &rhs) {
            detail::Object<cl_type>::operator=(rhs);
        }
        return *this;
	}

	//====================================================================================
	// Special Constructors
	//====================================================================================

	template<typename DeviceIterator, typename Function, typename T>
	Context::Context(
		ContextProperties const& properties,
		DeviceIterator firstDevice,
		DeviceIterator lastDevice,
		Function callback,
		T* user_data
	){
		struct callback_data {
			Function callback;
			T* user_data;
		};
		auto cbWrapper = new callback_data{callback, user_data};
		auto ids       = std::vector<cl_device_id>{};
		ids.reserve(std::distance(firstDevice, lastDevice));
		std::transform(firstDevice, lastDevice, std::back_inserter(ids),
			[](auto device) {
				return device.get();
			});
		auto error  = cl_int{CL_INVALID_VALUE};
		auto contex = clCreateContext(
			properties.data().data(),
			ids.size(), ids.data(),
			[](
				const char * error_info,
				const void * private_info,
				size_t cb,
				void * user_data
			) {
				auto temp = reinterpret_cast<callback_data*>(user_data);
				auto errorString = std::string{error_info};
				auto privateData = std::vector<char>{
					reinterpret_cast<const char*>(private_info),
					reinterpret_cast<const char*>(private_info) + cb};
				auto userData    = temp->user_data;
				temp->callback(errorString, privateData, userData);
				delete temp;
			},
			std::addressof(cbWrapper),
			std::addressof(error)
		);
		if (detail::error::handle(error)) {
			m_object = contex;
		}
	}

	template<typename DeviceIterator>
	Context::Context(
		ContextProperties const& properties,
		DeviceIterator firstDevice,
		DeviceIterator lastDevice
	){
		auto ids = std::vector<cl_device_id>{};
		ids.reserve(std::distance(firstDevice, lastDevice));
		std::transform(firstDevice, lastDevice, ids.begin(),
			[](auto device) {
				return device.get();
			});
		auto error  = cl_int{CL_INVALID_VALUE};
		auto contex = clCreateContext(
			properties.data().data(),
			ids.size(), ids.data(),
			nullptr, nullptr,
			std::addressof(error)
		);
		if (detail::error::handle(error)) {
			m_object = contex;
		}
	}

	template<typename Function, typename T>
	Context::Context(
		ContextProperties const& properties,
		DeviceType type,
		Function callback,
		T* user_data
	){
		struct callback_data {
			Function callback;
			T* user_data;
		};
		auto cbWrapper = new callback_data{callback, user_data};
		auto error  = cl_int{CL_INVALID_VALUE};
		auto contex = clCreateContextFromType(
			properties.data().data(),
			static_cast<std::underlying_type<DeviceType>::type>(type),
			[](
				const char * error_info,
				const void * private_info,
				size_t cb,
				void * user_data
			) {
				auto temp = reinterpret_cast<callback_data*>(user_data);
				auto errorString = std::string{error_info};
				auto privateData = std::vector<char>{
					reinterpret_cast<const char*>(private_info),
					reinterpret_cast<const char*>(private_info) + cb};
				auto userData    = temp->user_data;
				temp->callback(errorString, privateData, userData);
				delete temp;
			},
			std::addressof(cbWrapper),
			std::addressof(error)
		);
		if (detail::error::handle(error)) {
			m_object = contex;
		}
	}

	Context::Context(
		ContextProperties const& properties,
		DeviceType type
	){
		auto error  = cl_int{CL_INVALID_VALUE};
		auto contex = clCreateContextFromType(
			properties.data().data(),
			static_cast<std::underlying_type<DeviceType>::type>(type),
			nullptr, nullptr,
			std::addressof(error)
		);
		if (detail::error::handle(error)) {
			m_object = contex;
		}
	}

	//================================================================================
	// Create Command Queue Objects
	//================================================================================

	auto Context::createCommandQueue(Device const& device) const -> CommandQueue {
		auto error   = cl_int{CL_INVALID_VALUE};
		auto queueId = clCreateCommandQueueWithProperties(
			get(), device.get(), nullptr, std::addressof(error));
		detail::error::handle(error);
		return {queueId};
	}

	//================================================================================
	// Create Memory Objects
	//================================================================================

	template<typename T>
	auto Context::createBuffer(
		size_t size,
		DeviceAccess deviceAccess,
		HostAccess hostAccess
	) const
		-> Buffer<T>
	{
		using namespace utility;
		auto error = cl_int{CL_INVALID_VALUE};
		auto flags = to_underlying(deviceAccess) | to_underlying(hostAccess);
		auto sizeInBytes = size * sizeof(T);
		auto id    = clCreateBuffer(get(), flags, sizeInBytes, nullptr, std::addressof(error));
		detail::error::handle(error);
		return {id};
	}

	template<typename T, typename InputIterator>
	auto Context::createBuffer(
		InputIterator first,
		InputIterator last,
		TransferMode transferMode,
		DeviceAccess deviceAccess,
		HostAccess hostAccess
	) const
		-> Buffer<T>
	{
		using namespace utility;
		auto error = cl_int{CL_INVALID_VALUE};
		auto flags = to_underlying(transferMode)
		           | to_underlying(deviceAccess)
		           | to_underlying(hostAccess);
		auto sizeInBytes = std::distance(first, last) * sizeof(T);
		auto id    = clCreateBuffer(get(), flags, sizeInBytes, (void *) &*first, std::addressof(error));
		detail::error::handle(error);
		return {id};
	}

	template<typename T, typename InputRange, typename>
	auto Context::createBuffer(
		InputRange const& range,
		TransferMode transferMode,
		DeviceAccess deviceAccess,
		HostAccess hostAccess
	) const
		-> Buffer<T>
	{
		return createBuffer<T>(range.begin(), range.end(), transferMode, deviceAccess, hostAccess);
	}

	//================================================================================
	// Create Program Objects
	//================================================================================

	auto Context::createProgramWithSource(std::string const& source) const -> Program {
		auto error     = cl_int{CL_INVALID_VALUE};
		auto cStr      = source.c_str();
		auto programId = clCreateProgramWithSource(
			get(), 1, std::addressof(cStr), nullptr, std::addressof(error));
		detail::error::handle(error);
		return {programId};
	}

	//====================================================================================
	// Information access helper methods.
	//====================================================================================

	auto Context::getReferenceCount() const -> cl_uint {
		return getInfo<cl_uint>(CL_CONTEXT_REFERENCE_COUNT);
	}

	auto Context::getNumDevices() const -> cl_uint {
		return getInfo<cl_uint>(CL_CONTEXT_NUM_DEVICES);
	}

	auto Context::getDevices() const -> std::vector<Device> {
		const auto device_ids = getInfoVector<cl_device_id>(CL_CONTEXT_DEVICES);
		      auto devices    = std::vector<Device>{};
		for (auto&& device_id : device_ids) {
			devices.emplace_back(device_id);
		}
		return devices;
	}

	auto Context::getProperties() const -> ContextProperties {
		return {getInfoVector<cl_context_properties>(CL_CONTEXT_PROPERTIES)};
	}

}

#endif
<commit_msg>added experimental hotfix for leak in clCreateContext wrapper<commit_after>#ifdef  CLPP_CONTEXT_IPP
	#error "multiple inclusions of the same implementation file"
#else
#define CLPP_CONTEXT_IPP

#ifndef CLPP_CONTEXT_HPP
	#error "header file has not been included; maybe it isn't required anymore?"
	#include "clpp/context.hpp"
#endif

#include "utility/to_underlying.hpp"

//#include <iostream>
#include <iterator>
#include <algorithm>

namespace cl {
	//====================================================================================
	// Copy-Assignment
	//====================================================================================

	auto Context::operator=(const Context & rhs) -> Context & {
        if (this != &rhs) {
            detail::Object<cl_type>::operator=(rhs);
        }
        return *this;
	}

	//====================================================================================
	// Special Constructors
	//====================================================================================

	template<typename DeviceIterator, typename Function, typename T>
	Context::Context(
		ContextProperties const& properties,
		DeviceIterator firstDevice,
		DeviceIterator lastDevice,
		Function callback,
		T* user_data
	){
		struct callback_data {
			Function callback;
			T* user_data;
		};
		auto cbWrapper = new callback_data{callback, user_data};
		auto ids       = std::vector<cl_device_id>{};
		ids.reserve(std::distance(firstDevice, lastDevice));
		std::transform(firstDevice, lastDevice, std::back_inserter(ids),
			[](auto device) {
				return device.get();
			});
		auto error  = cl_int{CL_INVALID_VALUE};
		auto contex = clCreateContext(
			properties.data().data(),
			ids.size(), ids.data(),
			[](
				const char * error_info,
				const void * private_info,
				size_t cb,
				void * user_data
			) {
				auto temp = reinterpret_cast<callback_data*>(user_data);
				auto errorString = std::string{error_info};
				auto privateData = std::vector<char>{
					reinterpret_cast<const char*>(private_info),
					reinterpret_cast<const char*>(private_info) + cb};
				auto userData    = temp->user_data;
				temp->callback(errorString, privateData, userData);
				delete temp;
			},
			std::addressof(cbWrapper),
			std::addressof(error)
		);
		if (detail::error::handle(error)) {
			m_object = contex;
			delete cbWrapper; // can be safely deleted as the callback requiring this
			                  // instance will never be called since clCreateContext
			                  // ran successfully at this point of computation.
			                  // TODO: need to check if this is really true at all!
		}
	}

	template<typename DeviceIterator>
	Context::Context(
		ContextProperties const& properties,
		DeviceIterator firstDevice,
		DeviceIterator lastDevice
	){
		auto ids = std::vector<cl_device_id>{};
		ids.reserve(std::distance(firstDevice, lastDevice));
		std::transform(firstDevice, lastDevice, ids.begin(),
			[](auto device) {
				return device.get();
			});
		auto error  = cl_int{CL_INVALID_VALUE};
		auto contex = clCreateContext(
			properties.data().data(),
			ids.size(), ids.data(),
			nullptr, nullptr,
			std::addressof(error)
		);
		if (detail::error::handle(error)) {
			m_object = contex;
		}
	}

	template<typename Function, typename T>
	Context::Context(
		ContextProperties const& properties,
		DeviceType type,
		Function callback,
		T* user_data
	){
		struct callback_data {
			Function callback;
			T* user_data;
		};
		auto cbWrapper = new callback_data{callback, user_data};
		auto error  = cl_int{CL_INVALID_VALUE};
		auto contex = clCreateContextFromType(
			properties.data().data(),
			static_cast<std::underlying_type<DeviceType>::type>(type),
			[](
				const char * error_info,
				const void * private_info,
				size_t cb,
				void * user_data
			) {
				auto temp = reinterpret_cast<callback_data*>(user_data);
				auto errorString = std::string{error_info};
				auto privateData = std::vector<char>{
					reinterpret_cast<const char*>(private_info),
					reinterpret_cast<const char*>(private_info) + cb};
				auto userData    = temp->user_data;
				temp->callback(errorString, privateData, userData);
				delete temp;
			},
			std::addressof(cbWrapper),
			std::addressof(error)
		);
		if (detail::error::handle(error)) {
			m_object = contex;
		}
	}

	Context::Context(
		ContextProperties const& properties,
		DeviceType type
	){
		auto error  = cl_int{CL_INVALID_VALUE};
		auto contex = clCreateContextFromType(
			properties.data().data(),
			static_cast<std::underlying_type<DeviceType>::type>(type),
			nullptr, nullptr,
			std::addressof(error)
		);
		if (detail::error::handle(error)) {
			m_object = contex;
		}
	}

	//================================================================================
	// Create Command Queue Objects
	//================================================================================

	auto Context::createCommandQueue(Device const& device) const -> CommandQueue {
		auto error   = cl_int{CL_INVALID_VALUE};
		auto queueId = clCreateCommandQueueWithProperties(
			get(), device.get(), nullptr, std::addressof(error));
		detail::error::handle(error);
		return {queueId};
	}

	//================================================================================
	// Create Memory Objects
	//================================================================================

	template<typename T>
	auto Context::createBuffer(
		size_t size,
		DeviceAccess deviceAccess,
		HostAccess hostAccess
	) const
		-> Buffer<T>
	{
		using namespace utility;
		auto error = cl_int{CL_INVALID_VALUE};
		auto flags = to_underlying(deviceAccess) | to_underlying(hostAccess);
		auto sizeInBytes = size * sizeof(T);
		auto id    = clCreateBuffer(get(), flags, sizeInBytes, nullptr, std::addressof(error));
		detail::error::handle(error);
		return {id};
	}

	template<typename T, typename InputIterator>
	auto Context::createBuffer(
		InputIterator first,
		InputIterator last,
		TransferMode transferMode,
		DeviceAccess deviceAccess,
		HostAccess hostAccess
	) const
		-> Buffer<T>
	{
		using namespace utility;
		auto error = cl_int{CL_INVALID_VALUE};
		auto flags = to_underlying(transferMode)
		           | to_underlying(deviceAccess)
		           | to_underlying(hostAccess);
		auto sizeInBytes = std::distance(first, last) * sizeof(T);
		auto id    = clCreateBuffer(get(), flags, sizeInBytes, (void *) &*first, std::addressof(error));
		detail::error::handle(error);
		return {id};
	}

	template<typename T, typename InputRange, typename>
	auto Context::createBuffer(
		InputRange const& range,
		TransferMode transferMode,
		DeviceAccess deviceAccess,
		HostAccess hostAccess
	) const
		-> Buffer<T>
	{
		return createBuffer<T>(range.begin(), range.end(), transferMode, deviceAccess, hostAccess);
	}

	//================================================================================
	// Create Program Objects
	//================================================================================

	auto Context::createProgramWithSource(std::string const& source) const -> Program {
		auto error     = cl_int{CL_INVALID_VALUE};
		auto cStr      = source.c_str();
		auto programId = clCreateProgramWithSource(
			get(), 1, std::addressof(cStr), nullptr, std::addressof(error));
		detail::error::handle(error);
		return {programId};
	}

	//====================================================================================
	// Information access helper methods.
	//====================================================================================

	auto Context::getReferenceCount() const -> cl_uint {
		return getInfo<cl_uint>(CL_CONTEXT_REFERENCE_COUNT);
	}

	auto Context::getNumDevices() const -> cl_uint {
		return getInfo<cl_uint>(CL_CONTEXT_NUM_DEVICES);
	}

	auto Context::getDevices() const -> std::vector<Device> {
		const auto device_ids = getInfoVector<cl_device_id>(CL_CONTEXT_DEVICES);
		      auto devices    = std::vector<Device>{};
		for (auto&& device_id : device_ids) {
			devices.emplace_back(device_id);
		}
		return devices;
	}

	auto Context::getProperties() const -> ContextProperties {
		return {getInfoVector<cl_context_properties>(CL_CONTEXT_PROPERTIES)};
	}

}

#endif
<|endoftext|>


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

#ifndef WORD_SPOTTER_CONFIG_THIRD_HPP
#define WORD_SPOTTER_CONFIG_THIRD_HPP

namespace third {

//#define CRBM_PMP_1    //One layer of CRBM with Probabilistic Max Pooling (C1)
#define CRBM_PMP_2      //Two layers of CRBM with Probabilistic Max Pooling (C1/C2)
//#define CRBM_PMP_3    //Three layers of CRBM with Probabilistic Max Pooling (C1/C2/C3)

//#define CRBM_MP_1  //One layers of CRBM with Max Pooling after each layer (C1)
//#define CRBM_MP_2  //Two layers of CRBM with Max Pooling after each layer (C1/C2)
//#define CRBM_MP_3  //Three layers of CRBM with Max Pooling after each layer (C1/C2/C3)

constexpr const std::size_t height = 40;        //Should not be changed
constexpr const std::size_t width = 220;        //Should not be changed

constexpr const std::size_t patch_height = 40;  //Should not be changed
constexpr const std::size_t patch_width = 20;

constexpr const std::size_t epochs = 50;
constexpr const std::size_t patch_stride = 4;

constexpr const std::size_t NF1 = 9;
constexpr const std::size_t K1 = 24;
constexpr const std::size_t C1 = 2;
constexpr const std::size_t B1 = 25;
constexpr const dll::unit_type HT1 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT1 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM1 = dll::sparsity_method::LEE;

constexpr const std::size_t NF2 = 3;
constexpr const std::size_t K2 = 24;
constexpr const std::size_t C2 = 2;
constexpr const std::size_t B2 = 25;
constexpr const dll::unit_type HT2 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT2 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM2 = dll::sparsity_method::LEE;

constexpr const std::size_t NF3 = 3;
constexpr const std::size_t K3 = 48;
constexpr const std::size_t C3 = 2;
constexpr const std::size_t B3 = 25;
constexpr const dll::unit_type HT3 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT3 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM3 = dll::sparsity_method::NONE;

const auto rate_0 = [](double& value){ value = 0.25 * value; };
const auto rate_1 = [](double& value){ value = 0.25 * value; };
const auto rate_2 = [](double& value){ value = 1.0 * value; };

const auto momentum_0 = [](double& ini, double& fin){ ini = 0.88; fin = 0.88;};
const auto momentum_1 = [](double& ini, double& fin){ ini = 0.88; fin = 0.88;};
const auto momentum_2 = [](double& ini, double& fin){ ini = 1.0 * ini; fin = 1.0 * fin;};

const auto wd_l1_0 = [](double& value){ value = 1.0 * value; };
const auto wd_l1_1 = [](double& value){ value = 1.0 * value; };
const auto wd_l1_2 = [](double& value){ value = 1.0 * value; };

const auto wd_l2_0 = [](double& value){ value = 1.0 * value; };
const auto wd_l2_1 = [](double& value){ value = 1.0 * value; };
const auto wd_l2_2 = [](double& value){ value = 1.0 * value; };

const auto pbias_0 = [](double& value){ value = 1.0 * value; };
const auto pbias_1 = [](double& value){ value = 1.0 * value; };
const auto pbias_2 = [](double& value){ value = 1.0 * value; };

const auto pbias_lambda_0 = [](double& value){ value = 2.0 * value; };
const auto pbias_lambda_1 = [](double& value){ value = 2.0 * value; };
const auto pbias_lambda_2 = [](double& value){ value = 1.0 * value; };

} // end of namespace third

#endif
<commit_msg>Update defaults<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2015.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef WORD_SPOTTER_CONFIG_THIRD_HPP
#define WORD_SPOTTER_CONFIG_THIRD_HPP

namespace third {

//#define CRBM_PMP_1    //One layer of CRBM with Probabilistic Max Pooling (C1)
#define CRBM_PMP_2      //Two layers of CRBM with Probabilistic Max Pooling (C1/C2)
//#define CRBM_PMP_3    //Three layers of CRBM with Probabilistic Max Pooling (C1/C2/C3)

//#define CRBM_MP_1  //One layers of CRBM with Max Pooling after each layer (C1)
//#define CRBM_MP_2  //Two layers of CRBM with Max Pooling after each layer (C1/C2)
//#define CRBM_MP_3  //Three layers of CRBM with Max Pooling after each layer (C1/C2/C3)

constexpr const std::size_t height = 40;        //Should not be changed
constexpr const std::size_t width = 220;        //Should not be changed

constexpr const std::size_t patch_height = 40;  //Should not be changed
constexpr const std::size_t patch_width = 20;

constexpr const std::size_t epochs = 50;
constexpr const std::size_t patch_stride = 3;

constexpr const std::size_t NF1 = 9;
constexpr const std::size_t K1 = 24;
constexpr const std::size_t C1 = 2;
constexpr const std::size_t B1 = 25;
constexpr const dll::unit_type HT1 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT1 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM1 = dll::sparsity_method::LEE;

constexpr const std::size_t NF2 = 3;
constexpr const std::size_t K2 = 24;
constexpr const std::size_t C2 = 2;
constexpr const std::size_t B2 = 25;
constexpr const dll::unit_type HT2 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT2 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM2 = dll::sparsity_method::LEE;

constexpr const std::size_t NF3 = 3;
constexpr const std::size_t K3 = 48;
constexpr const std::size_t C3 = 2;
constexpr const std::size_t B3 = 25;
constexpr const dll::unit_type HT3 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT3 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM3 = dll::sparsity_method::NONE;

const auto rate_0 = [](double& value){ value = 0.25 * value; };
const auto rate_1 = [](double& value){ value = 0.25 * value; };
const auto rate_2 = [](double& value){ value = 1.0 * value; };

const auto momentum_0 = [](double& ini, double& fin){ ini = 0.88; fin = 0.88;};
const auto momentum_1 = [](double& ini, double& fin){ ini = 0.88; fin = 0.88;};
const auto momentum_2 = [](double& ini, double& fin){ ini = 1.0 * ini; fin = 1.0 * fin;};

const auto wd_l1_0 = [](double& value){ value = 1.0 * value; };
const auto wd_l1_1 = [](double& value){ value = 1.0 * value; };
const auto wd_l1_2 = [](double& value){ value = 1.0 * value; };

const auto wd_l2_0 = [](double& value){ value = 1.0 * value; };
const auto wd_l2_1 = [](double& value){ value = 1.0 * value; };
const auto wd_l2_2 = [](double& value){ value = 1.0 * value; };

const auto pbias_0 = [](double& value){ value = 1.0 * value; };
const auto pbias_1 = [](double& value){ value = 1.0 * value; };
const auto pbias_2 = [](double& value){ value = 1.0 * value; };

const auto pbias_lambda_0 = [](double& value){ value = 2.0 * value; };
const auto pbias_lambda_1 = [](double& value){ value = 2.0 * value; };
const auto pbias_lambda_2 = [](double& value){ value = 1.0 * value; };

} // end of namespace third

#endif
<|endoftext|>


<commit_before>/**
 * @file meta.hpp
 *
 * Meta-programming facilities.
 */

#ifndef CPPSTDX_META__
#define CPPSTDX_META__

#include <cppstdx/config.hpp>
#include <type_traits>

namespace cppstdx {

namespace meta {

using ::std::size_t;
using ::std::integral_constant;

//===============================================
//
//   types
//
//===============================================

template<typename T>
struct type_ {
    using type = T;
};

template<typename A>
using get_type = typename A::type;

struct nil_{};

template<bool V>
using bool_ = integral_constant<bool, V>;

using true_  = bool_<true>;
using false_ = bool_<false>;

template<char  V> using char_  = integral_constant<char,  V>;
template<int   V> using int_   = integral_constant<int,   V>;
template<long  V> using long_  = integral_constant<long,  V>;
template<short V> using short_ = integral_constant<short, V>;

template<unsigned char  V> using uchar_  = integral_constant<unsigned char,  V>;
template<unsigned int   V> using uint_   = integral_constant<unsigned int,   V>;
template<unsigned long  V> using ulong_  = integral_constant<unsigned long,  V>;
template<unsigned short V> using ushort_ = integral_constant<unsigned short, V>;

template<size_t V> using size_ = integral_constant<size_t, V>;

template<class A>
using value_type_of = typename A::value_type;

// pair

template<typename T1, typename T2>
struct pair_ {
    using first_type = T1;
    using second_type = T2;
};

template<class A> struct first;
template<class A> struct second;

template<class A> using first_t  = typename first<A>::type;
template<class A> using second_t = typename second<A>::type;

template<typename T1, typename T2>
struct first<pair_<T1, T2>> {
    using type = T1;
};

template<typename T1, typename T2>
struct second<pair_<T1, T2>> {
    using type = T2;
};

//===============================================
//
//   basic functions
//
//===============================================

template<typename A> using id = A;
template<typename A> using identity = A;

// arithmetic functions

template<typename A>
using negate = integral_constant<value_type_of<A>, -A::value>;

template<typename A>
using complement = integral_constant<value_type_of<A>, ~A::value>;

template<typename A>
using next = integral_constant<value_type_of<A>, A::value+1>;

template<typename A>
using prev = integral_constant<value_type_of<A>, A::value-1>;

template<typename A, typename B>
using plus = integral_constant<value_type_of<A>, A::value + B::value>;

template<typename A, typename B>
using minus = integral_constant<value_type_of<A>, A::value - B::value>;

template<typename A, typename B>
using mul = integral_constant<value_type_of<A>, A::value * B::value>;

template<typename A, typename B>
using div = integral_constant<value_type_of<A>, A::value / B::value>;

template<typename A, typename B>
using mod = integral_constant<value_type_of<A>, A::value % B::value>;

template<typename A, typename B> using multiplies = mul<A, B>;
template<typename A, typename B> using divides = div<A, B>;
template<typename A, typename B> using modulo = mod<A, B>;

// comparison functions

template<typename A, typename B> using eq = bool_<(A::value == B::value)>;
template<typename A, typename B> using ne = bool_<(A::value != B::value)>;
template<typename A, typename B> using gt = bool_<(A::value >  B::value)>;
template<typename A, typename B> using ge = bool_<(A::value >= B::value)>;
template<typename A, typename B> using lt = bool_<(A::value <  B::value)>;
template<typename A, typename B> using le = bool_<(A::value <= B::value)>;

template<typename A, typename B> using equal_to      = eq<A, B>;
template<typename A, typename B> using not_equal_to  = ne<A, B>;
template<typename A, typename B> using greater       = gt<A, B>;
template<typename A, typename B> using greater_equal = ge<A, B>;
template<typename A, typename B> using less          = lt<A, B>;
template<typename A, typename B> using less_equal    = le<A, B>;

// logical functions

template<typename A> using not_ = bool_<!A::value>;
template<typename A, typename B> using xor_ = bool_<A::value != B::value>;

namespace details {

template<bool Av, typename B>
struct and_helper : public bool_<B::value> {};

template<typename B>
struct and_helper<false, B> : public bool_<false> {};

template<bool Av, typename B>
struct or_helper : public bool_<true> {};

template<typename B>
struct or_helper<false, B> : public bool_<B::value> {};

}

template<typename A, typename B> using and_ = details::and_helper<A::value, B>;
template<typename A, typename B> using or_  = details::or_helper<A::value, B>;

//===============================================
//
//   variadic reduction
//
//===============================================

namespace details {

// sum

template<typename A, typename... Rest>
struct sum_impl : public plus<A, sum_impl<Rest...>> {};

template<typename A>
struct sum_impl<A> : public id<A> {};

// prod

template<typename A, typename... Rest>
struct prod_impl : public mul<A, prod_impl<Rest...>> {};

template<typename A>
struct prod_impl<A> : public id<A> {};

// max

template<typename A, typename B>
using _max = integral_constant<
        value_type_of<A>, (A::value > B::value ? A::value : B::value)>;

template<typename A, typename... Rest>
struct max_impl : public _max<A, max_impl<Rest...>> {};

template<typename A>
struct max_impl<A> : public id<A> {};

// min

template<typename A, typename B>
using _min = integral_constant<
        value_type_of<A>, (A::value < B::value ? A::value : B::value)>;

template<typename A, typename... Rest>
struct min_impl : public _min<A, min_impl<Rest...>> {};

template<typename A>
struct min_impl<A> : public id<A> {};

// all

template<bool a, typename... Rest> struct all_helper;

template<typename... Rest>
struct all_helper<false, Rest...> : public bool_<false> {};

template<typename A, typename... Rest>
struct all_helper<true, A, Rest...> : public all_helper<A::value, Rest...> {};

template<typename A>
struct all_helper<true, A> : public bool_<A::value> {};

template<>
struct all_helper<true> : public std::true_type {};

template<typename... Args> struct all_impl;

template<typename A, typename... Rest>
struct all_impl<A, Rest...> : public all_helper<A::value, Rest...> {};

template<>
struct all_impl<> : public bool_<true> {};

// any

template<bool a, typename... Rest> struct any_helper;

template<typename... Rest>
struct any_helper<true, Rest...> : public bool_<true> {};

template<typename A, typename... Rest>
struct any_helper<false, A, Rest...> : public any_helper<A::value, Rest...> {};

template<typename A>
struct any_helper<false, A> : public bool_<A::value> {};

template<>
struct any_helper<false> : public bool_<false> {};

template<typename... Args> struct any_impl;

template<typename A, typename... Rest>
struct any_impl<A, Rest...> : public any_helper<A::value, Rest...> {};

template<>
struct any_impl<> : public bool_<false> {};

// generic count_if

template<template<typename> class Pred, typename... Args>
struct count_if_impl;

template<template<typename> class Pred, typename X, typename... Rest>
struct count_if_impl<Pred, X, Rest...> : public size_<
    (Pred<X>::value ? 1 : 0) +
    count_if_impl<Pred, Rest...>::value> {};

template<template<typename> class Pred, typename X>
struct count_if_impl<Pred, X> : public size_<Pred<X>::value ? 1 : 0> {};

template<template<typename> class Pred>
struct count_if_impl<Pred> : public size_<0> {};

} // end namespace details

template<typename... Args>
using sum = details::sum_impl<Args...>;

template<typename... Args>
using prod = details::prod_impl<Args...>;

template<typename... Args>
using max = details::max_impl<Args...>;

template<typename... Args>
using min = details::min_impl<Args...>;

template<typename... Args>
using count_true = details::count_if_impl<id, Args...>;

template<typename... Args>
using count_false = details::count_if_impl<not_, Args...>;

template<typename... Args>
using all = details::all_impl<Args...>;

template<typename... Args>
using any = details::any_impl<Args...>;

} // end namespace meta
} // end namespace cppstdx

#endif
<commit_msg>introduce cond_to_size to simplify the counting functions<commit_after>/**
 * @file meta.hpp
 *
 * Meta-programming facilities.
 */

#ifndef CPPSTDX_META__
#define CPPSTDX_META__

#include <cppstdx/config.hpp>
#include <type_traits>

namespace cppstdx {

namespace meta {

using ::std::size_t;
using ::std::integral_constant;

//===============================================
//
//   types
//
//===============================================

template<typename T>
struct type_ {
    using type = T;
};

template<typename A>
using get_type = typename A::type;

struct nil_{};

template<bool V>
using bool_ = integral_constant<bool, V>;

using true_  = bool_<true>;
using false_ = bool_<false>;

template<char  V> using char_  = integral_constant<char,  V>;
template<int   V> using int_   = integral_constant<int,   V>;
template<long  V> using long_  = integral_constant<long,  V>;
template<short V> using short_ = integral_constant<short, V>;

template<unsigned char  V> using uchar_  = integral_constant<unsigned char,  V>;
template<unsigned int   V> using uint_   = integral_constant<unsigned int,   V>;
template<unsigned long  V> using ulong_  = integral_constant<unsigned long,  V>;
template<unsigned short V> using ushort_ = integral_constant<unsigned short, V>;

template<size_t V> using size_ = integral_constant<size_t, V>;

template<class A>
using value_type_of = typename A::value_type;

// pair

template<typename T1, typename T2>
struct pair_ {
    using first_type = T1;
    using second_type = T2;
};

template<class A> struct first;
template<class A> struct second;

template<class A> using first_t  = typename first<A>::type;
template<class A> using second_t = typename second<A>::type;

template<typename T1, typename T2>
struct first<pair_<T1, T2>> {
    using type = T1;
};

template<typename T1, typename T2>
struct second<pair_<T1, T2>> {
    using type = T2;
};

//===============================================
//
//   basic functions
//
//===============================================

template<typename A> using id = A;
template<typename A> using identity = A;

// arithmetic functions

template<typename A>
using negate = integral_constant<value_type_of<A>, -A::value>;

template<typename A>
using complement = integral_constant<value_type_of<A>, ~A::value>;

template<typename A>
using next = integral_constant<value_type_of<A>, A::value+1>;

template<typename A>
using prev = integral_constant<value_type_of<A>, A::value-1>;

template<typename A, typename B>
using plus = integral_constant<value_type_of<A>, A::value + B::value>;

template<typename A, typename B>
using minus = integral_constant<value_type_of<A>, A::value - B::value>;

template<typename A, typename B>
using mul = integral_constant<value_type_of<A>, A::value * B::value>;

template<typename A, typename B>
using div = integral_constant<value_type_of<A>, A::value / B::value>;

template<typename A, typename B>
using mod = integral_constant<value_type_of<A>, A::value % B::value>;

template<typename A, typename B> using multiplies = mul<A, B>;
template<typename A, typename B> using divides = div<A, B>;
template<typename A, typename B> using modulo = mod<A, B>;

// comparison functions

template<typename A, typename B> using eq = bool_<(A::value == B::value)>;
template<typename A, typename B> using ne = bool_<(A::value != B::value)>;
template<typename A, typename B> using gt = bool_<(A::value >  B::value)>;
template<typename A, typename B> using ge = bool_<(A::value >= B::value)>;
template<typename A, typename B> using lt = bool_<(A::value <  B::value)>;
template<typename A, typename B> using le = bool_<(A::value <= B::value)>;

template<typename A, typename B> using equal_to      = eq<A, B>;
template<typename A, typename B> using not_equal_to  = ne<A, B>;
template<typename A, typename B> using greater       = gt<A, B>;
template<typename A, typename B> using greater_equal = ge<A, B>;
template<typename A, typename B> using less          = lt<A, B>;
template<typename A, typename B> using less_equal    = le<A, B>;

// logical functions

template<typename A> using not_ = bool_<!A::value>;
template<typename A, typename B> using xor_ = bool_<A::value != B::value>;

namespace details {

template<bool Av, typename B>
struct and_helper : public bool_<B::value> {};

template<typename B>
struct and_helper<false, B> : public bool_<false> {};

template<bool Av, typename B>
struct or_helper : public bool_<true> {};

template<typename B>
struct or_helper<false, B> : public bool_<B::value> {};

}

template<typename A, typename B> using and_ = details::and_helper<A::value, B>;
template<typename A, typename B> using or_  = details::or_helper<A::value, B>;

//===============================================
//
//   variadic reduction
//
//===============================================

namespace details {

// sum

template<typename A, typename... Rest>
struct sum_impl : public plus<A, sum_impl<Rest...>> {};

template<typename A>
struct sum_impl<A> : public id<A> {};

// prod

template<typename A, typename... Rest>
struct prod_impl : public mul<A, prod_impl<Rest...>> {};

template<typename A>
struct prod_impl<A> : public id<A> {};

// max

template<typename A, typename B>
using _max = integral_constant<
        value_type_of<A>, (A::value > B::value ? A::value : B::value)>;

template<typename A, typename... Rest>
struct max_impl : public _max<A, max_impl<Rest...>> {};

template<typename A>
struct max_impl<A> : public id<A> {};

// min

template<typename A, typename B>
using _min = integral_constant<
        value_type_of<A>, (A::value < B::value ? A::value : B::value)>;

template<typename A, typename... Rest>
struct min_impl : public _min<A, min_impl<Rest...>> {};

template<typename A>
struct min_impl<A> : public id<A> {};

// all

template<bool a, typename... Rest> struct all_helper;

template<typename... Rest>
struct all_helper<false, Rest...> : public bool_<false> {};

template<typename A, typename... Rest>
struct all_helper<true, A, Rest...> : public all_helper<A::value, Rest...> {};

template<typename A>
struct all_helper<true, A> : public bool_<A::value> {};

template<>
struct all_helper<true> : public std::true_type {};

template<typename... Args> struct all_impl;

template<typename A, typename... Rest>
struct all_impl<A, Rest...> : public all_helper<A::value, Rest...> {};

template<>
struct all_impl<> : public bool_<true> {};

// any

template<bool a, typename... Rest> struct any_helper;

template<typename... Rest>
struct any_helper<true, Rest...> : public bool_<true> {};

template<typename A, typename... Rest>
struct any_helper<false, A, Rest...> : public any_helper<A::value, Rest...> {};

template<typename A>
struct any_helper<false, A> : public bool_<A::value> {};

template<>
struct any_helper<false> : public bool_<false> {};

template<typename... Args> struct any_impl;

template<typename A, typename... Rest>
struct any_impl<A, Rest...> : public any_helper<A::value, Rest...> {};

template<>
struct any_impl<> : public bool_<false> {};

// generic count_if

template<typename A>
struct cond_to_size : public size_<(A::value ? 1 : 0)> {};

template<template<typename> class Pred, typename... Args>
struct count_if_impl;

template<template<typename> class Pred, typename X, typename... Rest>
struct count_if_impl<Pred, X, Rest...> : public plus<
    cond_to_size<Pred<X>>,
    count_if_impl<Pred, Rest...>> {};

template<template<typename> class Pred, typename X>
struct count_if_impl<Pred, X> : public cond_to_size<Pred<X>> {};

template<template<typename> class Pred>
struct count_if_impl<Pred> : public size_<0> {};

} // end namespace details

template<typename... Args>
using sum = details::sum_impl<Args...>;

template<typename... Args>
using prod = details::prod_impl<Args...>;

template<typename... Args>
using max = details::max_impl<Args...>;

template<typename... Args>
using min = details::min_impl<Args...>;

template<typename... Args>
using count_true = details::count_if_impl<id, Args...>;

template<typename... Args>
using count_false = details::count_if_impl<not_, Args...>;

template<typename... Args>
using all = details::all_impl<Args...>;

template<typename... Args>
using any = details::any_impl<Args...>;

} // end namespace meta
} // end namespace cppstdx

#endif
<|endoftext|>


<commit_before>/*
Copyright (c) 2014-2016, Scott Zuyderduyn
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/

//----------------------------------------------------------------------------
// global.hpp
//
// Global defines and macros.
//
// Author: Scott D. Zuyderduyn, Ph.D. (scott.zuyderduyn@utoronto.ca)
//----------------------------------------------------------------------------

#pragma once
#ifndef ECUDA_GLOBAL_HPP
#define ECUDA_GLOBAL_HPP

#include <stdexcept>
#include <sstream>

///
/// \cond DEVELOPER_DOCUMENTATION
///
/// \endcond
///

// idea taken from the VTK-m project (https://gitlab.kitware.com/vtk/vtk-m)
// to suppress annoying warnings from the compiler about calling __host__
// code from a __host__ __device__ function
#ifdef __CUDACC__
#define ECUDA_SUPPRESS_HD_WARNINGS \
	#pragma hd_warning_disable
#else
#define ECUDA_SUPPRESS_HD_WARNINGS
#endif

#include "impl/host_emulation.hpp" // host-only replacements of CUDA C API functions
#include "cuda_error.hpp"          // specialized std::exception for ecuda/CUDA runtime errors

// Generic check for C++11 support
#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) // latter check works for GCC 4.6 because it has a bad __cplusplus flag
#define ECUDA_CPP11_AVAILABLE
#endif
// Windows check for C++11 support (Visual Studio 2013 and greater)
#if defined(_MSC_VER) && _MSC_VER >= 1800 // Visual Studio 2013
#define ECUDA_CPP11_AVAILABLE
#endif

///
/// Macro function that captures a CUDA error code and then does something
/// with it.  All calls to functions in the CUDA API that return an error code
/// should use this.
///
#ifdef __CUDACC__
// Macro function currently throws an ecuda::cuda_error exception containing a
// description of the problem error code.
#define CUDA_CALL(x) do { if((x)!=cudaSuccess) { std::ostringstream oss; oss << __FILE__; oss << ":"; oss << __LINE__; oss << " "; oss << cudaGetErrorString(cudaGetLastError()); throw ::ecuda::cuda_error(x,oss.str()); /*std::runtime_error(oss.str());*/ }} while(0);
#else
// cannot do CUDA calls when emulating with host only
#define CUDA_CALL(x) x
#endif

#define S(x) #x
#define S_(x) S(x)
#define S__LINE__ S_(__LINE__)
///
/// String wrapper that adds the source file and line to a given error message.
///
#define EXCEPTION_MSG(x) "" __FILE__ ":" S__LINE__ " " x

///
/// Macro that performs a check for any outstanding CUDA errors.  This macro
/// should be declared after any CUDA API calls that do not return an error code
/// (e.g. after calling kernel functions). Calling this when a CUDA API call
/// has not been made is safe.
///
#ifdef __CUDACC__
#define CUDA_CHECK_ERRORS() do { cudaError_t error = cudaGetLastError(); if( error != cudaSuccess ) throw ::ecuda::cuda_error(error,std::string(cudaGetErrorString(error))); } while(0);
#else
// cannot check CUDA errors when emulating with host only
#define CUDA_CHECK_ERRORS() do {} while(0);
#endif

///
/// Macro that calls a CUDA kernel function, waits for completion, and throws
/// an ecuda::cuda_error exception if any errors are reported by cudaGetLastError().
///
#ifdef __CUDACC__
#define CUDA_CALL_KERNEL_AND_WAIT(...) do {\
		__VA_ARGS__;\
		{ cudaError_t error = cudaGetLastError(); if( error != cudaSuccess ) throw ::ecuda::cuda_error(error,std::string(cudaGetErrorString(error))); }\
		cudaDeviceSynchronize();\
		{ cudaError_t error = cudaGetLastError(); if( error != cudaSuccess ) throw ::ecuda::cuda_error(error,std::string(cudaGetErrorString(error))); }\
	} while(0);
#else
// cannot do CUDA calls when emulating with host only
#define CUDA_CALL_KERNEL_AND_WAIT(...) do {\
		__VA_ARGS__;\
	} while( 0 );
#endif

/** Replace nullptr with NULL if nvcc still doesn't support C++11. */
#ifndef ECUDA_CPP11_AVAILABLE
#define nullptr NULL
#endif

/** Allow noexcept and constexpr if C++11 supported. */
#ifdef ECUDA_CPP11_AVAILABLE
#if defined(_MSC_VER) && _MSC_VER == 1800 // Visual Studio 2013 has only partial C++11 support and doesn't know these
#define __NOEXCEPT__
#define __CONSTEXPR__
#else
#define __NOEXCEPT__ noexcept
#define ECUDA_NOEXCEPT_KEYWORD_ENABLED
#define __CONSTEXPR__ constexpr
#define ECUDA_CONSTEXPR_KEYWORD_ENABLED
#endif
#else
#define __NOEXCEPT__
#define __CONSTEXPR__
#endif

#ifdef __CUDACC__
#define __HOST__ __host__
#define __DEVICE__ __device__
#else
// strip all __host__ and __device__ declarations when using host only
#define __HOST__
#define __DEVICE__
#endif

//
// Quick implementation of compile-time assertions. If C++11 is available, then
// just use the new static_assert keyword.
//
// This approach was borrowed from the Eigen linear algebra template library
// (http://eigen.tuxfamily.org).
//
#ifdef ECUDA_CPP11_AVAILABLE
#define ECUDA_STATIC_ASSERT(x,msg) static_assert(x,#msg)
#else

namespace ecuda {

/// \cond DEVELOPER_DOCUMENTATION
namespace impl {

template<bool condition> struct static_assertion {};
template<> struct static_assertion<true>
{
	enum {
		CANNOT_USE_NONCONTIGUOUS_DEVICE_ITERATOR_AS_SOURCE_FOR_COPY,
		CANNOT_USE_NONCONTIGUOUS_DEVICE_ITERATOR_AS_DESTINATION_FOR_COPY,
		CANNOT_FILL_RANGE_REPRESENTED_BY_NONCONTIGUOUS_DEVICE_ITERATOR,
		CANNOT_LEXICOGRAPHICALLY_COMPARE_RANGE_REPRESENTED_BY_NONCONTIGUOUS_DEVICE_MEMORY,
		CANNOT_FIND_MAX_ELEMENT_IN_RANGE_REPRESENTED_BY_NONCONTIGUOUS_DEVICE_MEMORY,
		CANNOT_REVERSE_RANGE_REPRESENTED_BY_NONCONTIGUOUS_DEVICE_MEMORY,
		CANNOT_ACCUMULATE_RANGE_REPRESENTED_BY_NONCONTIGUOUS_DEVICE_MEMORY,
		CANNOT_CALCULATE_DISTANCE_OF_NONCONTIGUOUS_DEVICE_ITERATOR_FROM_HOST_CODE
	};
};

} // namespace impl
/// \endcond

} // namespace ecuda

#define ECUDA_STATIC_ASSERT(x,msg) if(ecuda::impl::static_assertion<static_cast<bool>(x)>::msg) {}
#endif

#endif
<commit_msg>added __constant__ macro __CONSTANT__<commit_after>/*
Copyright (c) 2014-2016, Scott Zuyderduyn
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/

//----------------------------------------------------------------------------
// global.hpp
//
// Global defines and macros.
//
// Author: Scott D. Zuyderduyn, Ph.D. (scott.zuyderduyn@utoronto.ca)
//----------------------------------------------------------------------------

#pragma once
#ifndef ECUDA_GLOBAL_HPP
#define ECUDA_GLOBAL_HPP

#include <stdexcept>
#include <sstream>

///
/// \cond DEVELOPER_DOCUMENTATION
///
/// \endcond
///

// idea taken from the VTK-m project (https://gitlab.kitware.com/vtk/vtk-m)
// to suppress annoying warnings from the compiler about calling __host__
// code from a __host__ __device__ function
#ifdef __CUDACC__
#define ECUDA_SUPPRESS_HD_WARNINGS \
	#pragma hd_warning_disable
#else
#define ECUDA_SUPPRESS_HD_WARNINGS
#endif

#include "impl/host_emulation.hpp" // host-only replacements of CUDA C API functions
#include "cuda_error.hpp"          // specialized std::exception for ecuda/CUDA runtime errors

// Generic check for C++11 support
#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) // latter check works for GCC 4.6 because it has a bad __cplusplus flag
#define ECUDA_CPP11_AVAILABLE
#endif
// Windows check for C++11 support (Visual Studio 2013 and greater)
#if defined(_MSC_VER) && _MSC_VER >= 1800 // Visual Studio 2013
#define ECUDA_CPP11_AVAILABLE
#endif

///
/// Macro function that captures a CUDA error code and then does something
/// with it.  All calls to functions in the CUDA API that return an error code
/// should use this.
///
#ifdef __CUDACC__
// Macro function currently throws an ecuda::cuda_error exception containing a
// description of the problem error code.
#define CUDA_CALL(x) do { if((x)!=cudaSuccess) { std::ostringstream oss; oss << __FILE__; oss << ":"; oss << __LINE__; oss << " "; oss << cudaGetErrorString(cudaGetLastError()); throw ::ecuda::cuda_error(x,oss.str()); /*std::runtime_error(oss.str());*/ }} while(0);
#else
// cannot do CUDA calls when emulating with host only
#define CUDA_CALL(x) x
#endif

#define S(x) #x
#define S_(x) S(x)
#define S__LINE__ S_(__LINE__)
///
/// String wrapper that adds the source file and line to a given error message.
///
#define EXCEPTION_MSG(x) "" __FILE__ ":" S__LINE__ " " x

///
/// Macro that performs a check for any outstanding CUDA errors.  This macro
/// should be declared after any CUDA API calls that do not return an error code
/// (e.g. after calling kernel functions). Calling this when a CUDA API call
/// has not been made is safe.
///
#ifdef __CUDACC__
#define CUDA_CHECK_ERRORS() do { cudaError_t error = cudaGetLastError(); if( error != cudaSuccess ) throw ::ecuda::cuda_error(error,std::string(cudaGetErrorString(error))); } while(0);
#else
// cannot check CUDA errors when emulating with host only
#define CUDA_CHECK_ERRORS() do {} while(0);
#endif

///
/// Macro that calls a CUDA kernel function, waits for completion, and throws
/// an ecuda::cuda_error exception if any errors are reported by cudaGetLastError().
///
#ifdef __CUDACC__
#define CUDA_CALL_KERNEL_AND_WAIT(...) do {\
		__VA_ARGS__;\
		{ cudaError_t error = cudaGetLastError(); if( error != cudaSuccess ) throw ::ecuda::cuda_error(error,std::string(cudaGetErrorString(error))); }\
		cudaDeviceSynchronize();\
		{ cudaError_t error = cudaGetLastError(); if( error != cudaSuccess ) throw ::ecuda::cuda_error(error,std::string(cudaGetErrorString(error))); }\
	} while(0);
#else
// cannot do CUDA calls when emulating with host only
#define CUDA_CALL_KERNEL_AND_WAIT(...) do {\
		__VA_ARGS__;\
	} while( 0 );
#endif

/** Replace nullptr with NULL if nvcc still doesn't support C++11. */
#ifndef ECUDA_CPP11_AVAILABLE
#define nullptr NULL
#endif

/** Allow noexcept and constexpr if C++11 supported. */
#ifdef ECUDA_CPP11_AVAILABLE
#if defined(_MSC_VER) && _MSC_VER == 1800 // Visual Studio 2013 has only partial C++11 support and doesn't know these
#define __NOEXCEPT__
#define __CONSTEXPR__
#else
#define __NOEXCEPT__ noexcept
#define ECUDA_NOEXCEPT_KEYWORD_ENABLED
#define __CONSTEXPR__ constexpr
#define ECUDA_CONSTEXPR_KEYWORD_ENABLED
#endif
#else
#define __NOEXCEPT__
#define __CONSTEXPR__
#endif

#ifdef __CUDACC__
#define __HOST__ __host__
#define __DEVICE__ __device__
#define __CONSTANT__ __constant__
#else
// strip all __host__ and __device__ declarations when using host only
#define __HOST__
#define __DEVICE__
#define __CONSTANT__
#endif

//
// Quick implementation of compile-time assertions. If C++11 is available, then
// just use the new static_assert keyword.
//
// This approach was borrowed from the Eigen linear algebra template library
// (http://eigen.tuxfamily.org).
//
#ifdef ECUDA_CPP11_AVAILABLE
#define ECUDA_STATIC_ASSERT(x,msg) static_assert(x,#msg)
#else

namespace ecuda {

/// \cond DEVELOPER_DOCUMENTATION
namespace impl {

template<bool condition> struct static_assertion {};
template<> struct static_assertion<true>
{
	enum {
		CANNOT_USE_NONCONTIGUOUS_DEVICE_ITERATOR_AS_SOURCE_FOR_COPY,
		CANNOT_USE_NONCONTIGUOUS_DEVICE_ITERATOR_AS_DESTINATION_FOR_COPY,
		CANNOT_FILL_RANGE_REPRESENTED_BY_NONCONTIGUOUS_DEVICE_ITERATOR,
		CANNOT_LEXICOGRAPHICALLY_COMPARE_RANGE_REPRESENTED_BY_NONCONTIGUOUS_DEVICE_MEMORY,
		CANNOT_FIND_MAX_ELEMENT_IN_RANGE_REPRESENTED_BY_NONCONTIGUOUS_DEVICE_MEMORY,
		CANNOT_REVERSE_RANGE_REPRESENTED_BY_NONCONTIGUOUS_DEVICE_MEMORY,
		CANNOT_ACCUMULATE_RANGE_REPRESENTED_BY_NONCONTIGUOUS_DEVICE_MEMORY,
		CANNOT_CALCULATE_DISTANCE_OF_NONCONTIGUOUS_DEVICE_ITERATOR_FROM_HOST_CODE
	};
};

} // namespace impl
/// \endcond

} // namespace ecuda

#define ECUDA_STATIC_ASSERT(x,msg) if(ecuda::impl::static_assertion<static_cast<bool>(x)>::msg) {}
#endif

#endif
<|endoftext|>


<commit_before>#ifndef QRW_BOARD_HPP
#define QRW_BOARD_HPP

#include <SFML/System/Vector2.hpp>

namespace qrw
{
	class AbstractAlgorithm;
	class Path;
	class Coordinates;
	class Square;

	class Board
	{
		public:
			Board(int width, int height);
			~Board();

			Square* getSquare(int x, int y);
			Square* getSquare(sf::Vector2i pos);
			Square* getSquare(const Coordinates& coordinates);

			int getWidth();
			int getHeight();

			bool isOnBoard(Coordinates coordinates);

			/**
			 * @brief Call pathfinding algorithm to find path from start to end.
			 * @param start Coordinates of the start.
			 * @param end Coordinates of the end.
			 * @return Pointer to found path or nullptr if no path could be found.
			 */
			Path* findPath(const Coordinates& start, const Coordinates& end);

		private:
			Square** _squares;

			int _width;
			int _height;

			AbstractAlgorithm* _pathfinder;
	};
}

#endif
<commit_msg>Added shared pointer typedef to board.<commit_after>#ifndef QRW_BOARD_HPP
#define QRW_BOARD_HPP

#include <memory>

#include <SFML/System/Vector2.hpp>

namespace qrw
{
	class AbstractAlgorithm;
	class Path;
	class Coordinates;
	class Square;

	class Board
	{
		public:
			typedef std::shared_ptr<Board> Ptr;

			Board(int width, int height);
			~Board();

			Square* getSquare(int x, int y);
			Square* getSquare(sf::Vector2i pos);
			Square* getSquare(const Coordinates& coordinates);

			int getWidth();
			int getHeight();

			bool isOnBoard(Coordinates coordinates);

			/**
			 * @brief Call pathfinding algorithm to find path from start to end.
			 * @param start Coordinates of the start.
			 * @param end Coordinates of the end.
			 * @return Pointer to found path or nullptr if no path could be found.
			 */
			Path* findPath(const Coordinates& start, const Coordinates& end);

		private:
			Square** _squares;

			int _width;
			int _height;

			AbstractAlgorithm* _pathfinder;
	};
}

#endif
<|endoftext|>


<commit_before>/** \file jsonv/config.hpp
 *
 *  Copyright (c) 2014-2016 by Travis Gockel. All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
 *  as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
 *  version.
 *
 *  \author Travis Gockel (travis@gockelhut.com)
**/
#ifndef __JSONV_CONFIG_HPP_INCLUDED__
#define __JSONV_CONFIG_HPP_INCLUDED__

/** \def JSONV_USER_CONFIG
 *  \brief A user-defined configuration file to be included before all other JSON Voorhees content.
**/
#ifdef JSONV_USER_CONFIG
#   include JSONV_USER_CONFIG
#endif

#define JSONV_VERSION_MAJOR 1
#define JSONV_VERSION_MINOR 2
#define JSONV_VERSION_PATCH 0

/** \def JSONV_DEBUG
 *  \brief Was JSON Voorhees compiled in debug mode?
 *  This value must be the same between when the SO was built and when you are compiling. In general, this is not useful
 *  outside of library maintainers.
 *
 *  \warning
 *  Keep in mind this value is \e always defined. Use `#if JSONV_DEBUG`, \e not `#ifdef JSONV_DEBUG`.
**/
#ifndef JSONV_DEBUG
#   define JSONV_DEBUG 0
#endif

/** \def JSONV_SO
 *  \brief Are you using shared objects (DLLs in Windows)?
**/
#ifndef JSONV_SO
#   define JSONV_SO 1
#endif

/** \def JSONV_COMPILING
 *  \brief Is JSON Voorhees currently compiling?
 *  You probably do not want to set this by hand. It is set by the build system when the library is compiled.
**/
#ifndef JSONV_COMPILING
#   ifdef jsonv_EXPORTS
#      define JSONV_COMPILING 1
#   else
#      define JSONV_COMPILING 0
#   endif
#endif

/** \def JSONV_EXPORT
 *  If using shared objects, this class or function should be exported.
 *
 *  \def JSONV_IMPORT
 *  If using shared objects, this class or function should be imported.
 *
 *  \def JSONV_HIDDEN
 *  This symbol is only visible within the same shared object in which the translation unit will end up. Symbols which
 *  are "hidden" will \e not be put into the global offset table, which means code can be more optimal when it involves
 *  hidden symbols at the cost that nothing outside of the SO can access it.
**/
#if JSONV_SO
#   if defined(__GNUC__)
#       define JSONV_EXPORT          __attribute__((visibility("default")))
#       define JSONV_IMPORT
#       define JSONV_HIDDEN          __attribute__((visibility("hidden")))
#   elif defined(_MSC_VER)
#       if defined(_LIB)
#           define JSONV_EXPORT
#           define JSONV_IMPORT
#           define JSONV_HIDDEN
#       else
#           define JSONV_EXPORT      __declspec(dllexport)
#           define JSONV_IMPORT      __declspec(dllimport)
#           define JSONV_HIDDEN
#       endif
#   else
#       error "Unknown shared object semantics for this compiler."
#   endif
#else
#   define JSONV_EXPORT
#   define JSONV_IMPORT
#   define JSONV_HIDDEN
#endif

/** \def JSONV_PUBLIC
 *  \brief This function or class is part of the public API for JsonVoorhees.
 *  If you are including JsonVoorhees for another library, this will have import semantics (\c JSONV_IMPORT); if you are
 *  building JsonVoorhees, this will have export semantics (\c JSONV_EXPORT).
 *
 *  \def JSONV_LOCAL
 *  \brief This function or class is internal-use only.
 *  \see JSONV_HIDDEN
**/
#if JSONV_COMPILING
#   define JSONV_PUBLIC JSONV_EXPORT
#   define JSONV_LOCAL  JSONV_HIDDEN
#else
#   define JSONV_PUBLIC JSONV_IMPORT
#   define JSONV_LOCAL  JSONV_HIDDEN
#endif

/** \def JSONV_UNUSED
 *  \brief Note that you know the variable is unused, but make the compiler stop complaining about it.
**/
#ifndef JSONV_UNUSED
#   if defined(__GNUC__)
#       define JSONV_UNUSED __attribute__((unused))
#   else
#       define JSONV_UNUSED
#   endif
#endif

/** \def JSONV_NO_RETURN
 *  \brief Mark that a given function will never return control to the caller, either by exiting or throwing an
 *  exception.
**/
#ifndef JSONV_NO_RETURN
#   if defined(__GNUC__)
#       define JSONV_NO_RETURN __attribute__((noreturn))
#   else
#       define JSONV_NO_RETURN
#   endif
#endif

/** \def JSONV_ALWAYS_INLINE
 *  \brief Always inline the function this decorates, no matter what the compiler might think is best.
**/
#ifndef JSONV_ALWAYS_INLINE
#   if defined(__GNUC__)
#       define JSONV_ALWAYS_INLINE __attribute__((always_inline))
#   else
#       define JSONV_ALWAYS_INLINE
#   endif
#endif

/** \def JSONV_INTEGER_ALTERNATES_LIST
 *  \brief An item list of types to also consider as an integer.
 *  This mostly exists to help resolve the C-induced type ambiguity for the literal \c 0. It most prefers to be an
 *  \c int, but might also become a \c long or a pointer type.
**/
#ifndef JSONV_INTEGER_ALTERNATES_LIST
#   define JSONV_INTEGER_ALTERNATES_LIST(item) \
        item(int)                              \
        item(unsigned int)                     \
        item(unsigned long)                    \
        item(unsigned long long)
#endif

/** \def JSONV_COMPILER_SUPPORTS_TEMPLATE_TEMPLATES
 *  Does the compiler properly support template templates? Most compilers do, MSVC does not.
**/
#ifndef JSONV_COMPILER_SUPPORTS_TEMPLATE_TEMPLATES
#   ifdef _MSC_VER
#       define JSONV_COMPILER_SUPPORTS_TEMPLATE_TEMPLATES 0
#   else
#       define JSONV_COMPILER_SUPPORTS_TEMPLATE_TEMPLATES 1
#   endif
#endif

#endif/*__JSONV_CONFIG_HPP_INCLUDED__*/
<commit_msg>Move version to 1.3.0.<commit_after>/** \file jsonv/config.hpp
 *
 *  Copyright (c) 2014-2016 by Travis Gockel. All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
 *  as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
 *  version.
 *
 *  \author Travis Gockel (travis@gockelhut.com)
**/
#ifndef __JSONV_CONFIG_HPP_INCLUDED__
#define __JSONV_CONFIG_HPP_INCLUDED__

/** \def JSONV_USER_CONFIG
 *  \brief A user-defined configuration file to be included before all other JSON Voorhees content.
**/
#ifdef JSONV_USER_CONFIG
#   include JSONV_USER_CONFIG
#endif

#define JSONV_VERSION_MAJOR 1
#define JSONV_VERSION_MINOR 3
#define JSONV_VERSION_PATCH 0

/** \def JSONV_DEBUG
 *  \brief Was JSON Voorhees compiled in debug mode?
 *  This value must be the same between when the SO was built and when you are compiling. In general, this is not useful
 *  outside of library maintainers.
 *
 *  \warning
 *  Keep in mind this value is \e always defined. Use `#if JSONV_DEBUG`, \e not `#ifdef JSONV_DEBUG`.
**/
#ifndef JSONV_DEBUG
#   define JSONV_DEBUG 0
#endif

/** \def JSONV_SO
 *  \brief Are you using shared objects (DLLs in Windows)?
**/
#ifndef JSONV_SO
#   define JSONV_SO 1
#endif

/** \def JSONV_COMPILING
 *  \brief Is JSON Voorhees currently compiling?
 *  You probably do not want to set this by hand. It is set by the build system when the library is compiled.
**/
#ifndef JSONV_COMPILING
#   ifdef jsonv_EXPORTS
#      define JSONV_COMPILING 1
#   else
#      define JSONV_COMPILING 0
#   endif
#endif

/** \def JSONV_EXPORT
 *  If using shared objects, this class or function should be exported.
 *
 *  \def JSONV_IMPORT
 *  If using shared objects, this class or function should be imported.
 *
 *  \def JSONV_HIDDEN
 *  This symbol is only visible within the same shared object in which the translation unit will end up. Symbols which
 *  are "hidden" will \e not be put into the global offset table, which means code can be more optimal when it involves
 *  hidden symbols at the cost that nothing outside of the SO can access it.
**/
#if JSONV_SO
#   if defined(__GNUC__)
#       define JSONV_EXPORT          __attribute__((visibility("default")))
#       define JSONV_IMPORT
#       define JSONV_HIDDEN          __attribute__((visibility("hidden")))
#   elif defined(_MSC_VER)
#       if defined(_LIB)
#           define JSONV_EXPORT
#           define JSONV_IMPORT
#           define JSONV_HIDDEN
#       else
#           define JSONV_EXPORT      __declspec(dllexport)
#           define JSONV_IMPORT      __declspec(dllimport)
#           define JSONV_HIDDEN
#       endif
#   else
#       error "Unknown shared object semantics for this compiler."
#   endif
#else
#   define JSONV_EXPORT
#   define JSONV_IMPORT
#   define JSONV_HIDDEN
#endif

/** \def JSONV_PUBLIC
 *  \brief This function or class is part of the public API for JsonVoorhees.
 *  If you are including JsonVoorhees for another library, this will have import semantics (\c JSONV_IMPORT); if you are
 *  building JsonVoorhees, this will have export semantics (\c JSONV_EXPORT).
 *
 *  \def JSONV_LOCAL
 *  \brief This function or class is internal-use only.
 *  \see JSONV_HIDDEN
**/
#if JSONV_COMPILING
#   define JSONV_PUBLIC JSONV_EXPORT
#   define JSONV_LOCAL  JSONV_HIDDEN
#else
#   define JSONV_PUBLIC JSONV_IMPORT
#   define JSONV_LOCAL  JSONV_HIDDEN
#endif

/** \def JSONV_UNUSED
 *  \brief Note that you know the variable is unused, but make the compiler stop complaining about it.
**/
#ifndef JSONV_UNUSED
#   if defined(__GNUC__)
#       define JSONV_UNUSED __attribute__((unused))
#   else
#       define JSONV_UNUSED
#   endif
#endif

/** \def JSONV_NO_RETURN
 *  \brief Mark that a given function will never return control to the caller, either by exiting or throwing an
 *  exception.
**/
#ifndef JSONV_NO_RETURN
#   if defined(__GNUC__)
#       define JSONV_NO_RETURN __attribute__((noreturn))
#   else
#       define JSONV_NO_RETURN
#   endif
#endif

/** \def JSONV_ALWAYS_INLINE
 *  \brief Always inline the function this decorates, no matter what the compiler might think is best.
**/
#ifndef JSONV_ALWAYS_INLINE
#   if defined(__GNUC__)
#       define JSONV_ALWAYS_INLINE __attribute__((always_inline))
#   else
#       define JSONV_ALWAYS_INLINE
#   endif
#endif

/** \def JSONV_INTEGER_ALTERNATES_LIST
 *  \brief An item list of types to also consider as an integer.
 *  This mostly exists to help resolve the C-induced type ambiguity for the literal \c 0. It most prefers to be an
 *  \c int, but might also become a \c long or a pointer type.
**/
#ifndef JSONV_INTEGER_ALTERNATES_LIST
#   define JSONV_INTEGER_ALTERNATES_LIST(item) \
        item(int)                              \
        item(unsigned int)                     \
        item(unsigned long)                    \
        item(unsigned long long)
#endif

/** \def JSONV_COMPILER_SUPPORTS_TEMPLATE_TEMPLATES
 *  Does the compiler properly support template templates? Most compilers do, MSVC does not.
**/
#ifndef JSONV_COMPILER_SUPPORTS_TEMPLATE_TEMPLATES
#   ifdef _MSC_VER
#       define JSONV_COMPILER_SUPPORTS_TEMPLATE_TEMPLATES 0
#   else
#       define JSONV_COMPILER_SUPPORTS_TEMPLATE_TEMPLATES 1
#   endif
#endif

#endif/*__JSONV_CONFIG_HPP_INCLUDED__*/
<|endoftext|>


<commit_before>#include "consoleui.h"
#include "servicelayer.h"
#include <iostream>

using namespace std;

ConsoleUI::ConsoleUI()
{

}

void ConsoleUI::run()
{

       cout << " ================================" << endl;
       cout << " Press 1 for sorting" << endl;
       cout << " Press 2 for listing" << endl;
       cout << " Press 3 for search"  << endl;
       cout << " ================================" << endl;

       int choice = 0;
       cin >> choice;

       bool error = false;

       while (!error)
       {
            switch (choice)
            {
            case 1:

            case 2:
                showData();

            case 3:
            //serve.search();

            default:
                cout << "error!" << endl;
                error = true;
            }
       }

}

void ConsoleUI::showData()
{

}
<commit_msg>lykkja til að endurtaka<commit_after>#include "consoleui.h"
#include "servicelayer.h"
#include <iostream>

using namespace std;

ConsoleUI::ConsoleUI()
{

}

void ConsoleUI::run()
{
    bool run = true;
    while (run)
    {
       cout << " ================================" << endl;
       cout << " Press 1 for sorting" << endl;
       cout << " Press 2 for listing" << endl;
       cout << " Press 3 for search"  << endl;
       cout << " Press 4 to exit"     << endl;
       cout << " ================================" << endl;

       int choice = 0;
       cin >> choice;

       bool error = false;

       while (error)
       {
            switch (choice)
            {
            case 1:

            case 2:
                showData();

            case 3:
            //serve.search();

            case 4:
                run = false;
            default:
                cout << "error!" << endl;
                error = true;
            }
       }

    }

}

void ConsoleUI::showData()
{

}
<|endoftext|>