text:
#include "simple_timer.h"
#include <iostream>
#include <boost/thread.hpp>
#include <boost/chrono.hpp>

SimpleTimer::SimpleTimer(uint64_t interval)
    : m_lastTime(0), m_interval(interval) {
    if (interval == 0) {
        zeroInterval = true;
    }
}

bool SimpleTimer::check() {
    if (zeroInterval) {
        return true;
    }
    uint64_t currentTime = getCurrentMillis();
    uint64_t delta       = (currentTime - m_lastTime);
    if (delta >= m_interval) {
        m_lastTime = currentTime;
        return true;
    } else {
        return false;
    }
}

// Sleep until timer expires
void SimpleTimer::wait() {
    if (zeroInterval) {
        return;
    }
    uint64_t currentTime = getCurrentMillis();
    uint64_t delta       = (currentTime - m_lastTime);
    uint64_t timeRemaining = m_interval - delta;

    if (timeRemaining > 0) {
        boost::this_thread::sleep_for(boost::chrono::milliseconds(timeRemaining));
    }
    m_lastTime = getCurrentMillis();
}

void SimpleTimer::reset() {
    // Reset the last time value so the next check will be true
    m_lastTime = 0;
}

max_stars_repo_name: telemetryjet/tjet-cli

max_issues_repo_name: telemetryjet/tjet-cli

max_forks_repo_name: telemetryjet/tjet-cli


text:
///
/// Copyright (c) 2009-2014 Nous Xiong (348944179 at qq dot com)
///
/// Distributed under the Boost Software License, Version 1.0. (See accompanying
/// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
///
/// See https://github.com/nousxiong/gce for latest version.
///

#ifndef GCE_ACTOR_NONBLOCKING_ACTOR_HPP
#define GCE_ACTOR_NONBLOCKING_ACTOR_HPP

#include <gce/actor/config.hpp>
#include <gce/actor/basic_actor.hpp>
#include <gce/actor/detail/cache_pool.hpp>
#include <gce/actor/detail/pack.hpp>
#include <boost/lockfree/queue.hpp>
#include <deque>
#include <vector>
#include <utility>

namespace gce
{
class context;
struct attributes;

class nonblocking_actor
  : public basic_actor
{
  typedef basic_actor base_type;

public:
  nonblocking_actor(context& ctx, std::size_t index);
  ~nonblocking_actor();

public:
  inline void send(aid_t recver, message const& m)
  {
    base_type::pri_send(recver, m);
  }

  inline void send(svcid_t recver, message const& m)
  {
    base_type::pri_send_svc(recver, m);
  }

  inline void relay(aid_t des, message& m)
  {
    base_type::pri_relay(des, m);
  }

  inline void relay(svcid_t des, message& m)
  {
    base_type::pri_relay_svc(des, m);
  }

  inline response_t request(aid_t recver, message const& m)
  {
    response_t res(base_type::new_request(), get_aid(), recver);
    base_type::pri_request(res, recver, m);
    return res;
  }

  inline response_t request(svcid_t recver, message const& m)
  {
    response_t res(base_type::new_request(), get_aid(), recver);
    base_type::pri_request_svc(res, recver, m);
    return res;
  }

  inline void reply(aid_t recver, message const& m)
  {
    base_type::pri_reply(recver, m);
  }

  inline void link(aid_t target)
  {
    base_type::pri_link(target);
  }

  inline void monitor(aid_t target)
  {
    base_type::pri_monitor(target);
  }

  aid_t recv(message&, match_list_t const& match_list = match_list_t());
  aid_t recv(response_t, message&);

public:
  /// internal use
  void on_recv(detail::pack&, base_type::send_hint);

  void register_service(match_t name, aid_t svc, std::size_t cache_queue_index);
  void deregister_service(match_t name, aid_t svc, std::size_t cache_queue_index);

  void register_socket(ctxid_pair_t, aid_t skt, std::size_t cache_queue_index);
  void deregister_socket(ctxid_pair_t ctxid_pr, aid_t skt, std::size_t cache_queue_index);

private:
  void release_pack();
  void move_pack();
  void handle_recv(detail::pack&);

private:
  /// Ensure start from a new cache line.
  byte_t pad0_[GCE_CACHE_LINE_SIZE];

  struct cache_queue
  {
    cache_queue()
      : index_base_(0)
      , head_(0)
      , garbage_tail_(u64_nil)
    {
    }

    cache_queue(cache_queue const& other)
      : que_(other.que_)
      , index_base_(other.index_base_)
      , head_(other.head_)
      , garbage_tail_(
          other.garbage_tail_.load(boost::memory_order_relaxed)
          )
    {
    }

    cache_queue& operator=(cache_queue const& rhs)
    {
      if (this != &rhs)
      {
        que_ = rhs.que_;
        index_base_ = rhs.index_base_;
        head_ = rhs.head_;
        garbage_tail_.store(
          rhs.garbage_tail_.load(boost::memory_order_relaxed),
          boost::memory_order_relaxed
          );
      }
      return *this;
    }

    /// Ensure start from a new cache line.
    byte_t pad0_[GCE_CACHE_LINE_SIZE];

    GCE_CACHE_ALIGNED_VAR(std::deque<detail::pack>, que_)
    GCE_CACHE_ALIGNED_VAR(boost::uint64_t, index_base_)
    GCE_CACHE_ALIGNED_VAR(boost::uint64_t, head_)
    GCE_CACHE_ALIGNED_VAR(boost::atomic<boost::uint64_t>, garbage_tail_)
  };

  GCE_CACHE_ALIGNED_VAR(std::vector<cache_queue>, cache_queue_list_)
  GCE_CACHE_ALIGNED_VAR(boost::lockfree::queue<detail::pack*>, pack_queue_)

  // local
  detail::cache_pool cac_pool_;
  std::vector<detail::pack*> gc_;
};
}

#endif /// GCE_ACTOR_NONBLOCKING_ACTOR_HPP

ext: hpp

max_stars_repo_name: nousxiong/gce

max_issues_repo_name: txwdyzcb/gce

max_forks_repo_name: txwdyzcb/gce


text:
#include <fc/log/console_appender.hpp>

#include <iomanip>
#include <mutex>
#include <sstream>

#ifndef WIN32
#include <unistd.h>
#endif
#include <boost/thread/mutex.hpp>

#include <fmt/format.h>

#include <fc/exception/exception.hpp>
#include <fc/log/log_message.hpp>
#include <fc/string.hpp>
#include <fc/variant.hpp>
#include <fc/reflect/variant.hpp>

#define COLOR_CONSOLE 1
#include "console_defines.h"

namespace fc {

class console_appender::impl {
public:
    config       cfg;
    boost::mutex log_mutex;
    color::type  lc[log_level::off + 1];
    bool         use_syslog_header{getenv("JOURNAL_STREAM")};
#ifdef WIN32
    HANDLE console_handle;
#endif
};

console_appender::console_appender(const variant& args)
    : my(new impl) {
    configure(args.as<config>());
}

console_appender::console_appender(const config& cfg)
    : my(new impl) {
    configure(cfg);
}

console_appender::console_appender()
    : my(new impl) {}

void
console_appender::configure(const config& console_appender_config) {
    try {
#ifdef WIN32
        my->console_handle = INVALID_HANDLE_VALUE;
#endif
        my->cfg = console_appender_config;
#ifdef WIN32
        if(my->cfg.stream = stream::std_error)
            my->console_handle = GetStdHandle(STD_ERROR_HANDLE);
        else if(my->cfg.stream = stream::std_out)
            my->console_handle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif

        for(int i = 0; i < log_level::off + 1; ++i)
            my->lc[i] = color::console_default;
        for(auto itr = my->cfg.level_colors.begin(); itr != my->cfg.level_colors.end(); ++itr)
            my->lc[itr->level] = itr->color;
    }
    FC_CAPTURE_AND_RETHROW((console_appender_config))
}

console_appender::~console_appender() {}

#ifdef WIN32
static WORD
#else
static const char*
#endif
get_console_color(console_appender::color::type t) {
    switch(t) {
    case console_appender::color::red:
        return CONSOLE_RED;
    case console_appender::color::green:
        return CONSOLE_GREEN;
    case console_appender::color::brown:
        return CONSOLE_BROWN;
    case console_appender::color::blue:
        return CONSOLE_BLUE;
    case console_appender::color::magenta:
        return CONSOLE_MAGENTA;
    case console_appender::color::cyan:
        return CONSOLE_CYAN;
    case console_appender::color::white:
        return CONSOLE_WHITE;
    case console_appender::color::console_default:
    default:
        return CONSOLE_DEFAULT;
    }
}

string
fixed_size(size_t s, const string& str) {
    if(str.size() == s)
        return str;
    if(str.size() > s)
        return str.substr(0, s);
    string tmp = str;
    tmp.append(s - str.size(), ' ');
    return tmp;
}

void
console_appender::log(const log_message& m) {
    FILE* out = stream::std_error ? stderr : stdout;

    auto& context = m.context;
    auto  line    = fmt::memory_buffer();

    if(my->use_syslog_header) {
        switch(context.level) {
        case log_level::error: {
            fmt::format_to(line, "<3>");
            break;
        }
        case log_level::warn: {
            fmt::format_to(line, "<4>");
            break;
        }
        case log_level::info: {
            fmt::format_to(line, "<6>");
            break;
        }
        case log_level::debug: {
            fmt::format_to(line, "<7>");
            break;
        }
        }  // switch
    }
    fmt::format_to(line, "{:<5} {} {:<9} {:<28} ",
        context.level.to_string(),
        (std::string)time_point::now(),
        context.thread_name,
        fmt::format("{}:{}", context.file.substr(0, 22), context.line));

    // strip all leading scopes...
    if(!context.method.empty()) {
        auto p = context.method.find_last_of(':');
        if(p == std::string::npos) {
            p = 0;
        }
        else {
            p++;
        }

        fmt::format_to(line, "{:<20}", context.method.substr(p, 20));
    }

    fmt::format_to(line, "] {}", fc::format_string(m.format, m.args));

    {
        std::unique_lock<boost::mutex> lock(my->log_mutex);

        print(fmt::to_string(line), my->lc[context.level]);
        fprintf(out, "\n");

        if(my->cfg.flush) {
            fflush(out);
        }
    }
}

void
console_appender::print(const std::string& text, color::type text_color) {
    FILE* out = stream::std_error ? stderr : stdout;

#ifdef WIN32
    if(my->console_handle != INVALID_HANDLE_VALUE)
        SetConsoleTextAttribute(my->console_handle, get_console_color(text_color));
#else
    if(isatty(fileno(out)))
        fprintf(out, "%s", get_console_color(text_color));
#endif

    if(text.size())
        fprintf(out, "%s", text.c_str());  //fmt_str.c_str() );

#ifdef WIN32
    if(my->console_handle != INVALID_HANDLE_VALUE)
        SetConsoleTextAttribute(my->console_handle, CONSOLE_DEFAULT);
#else
    if(isatty(fileno(out)))
        fprintf(out, "%s", CONSOLE_DEFAULT);
#endif

    if(my->cfg.flush)
        fflush(out);
}

}  // namespace fc

ext: cpp

max_stars_repo_name: Laighno/evt

max_issues_repo_name: Zhang-Zexi/evt

max_forks_repo_name: Zhang-Zexi/evt


text: #include <boost/chrono/io_v1/chrono_io.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


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

/* Author: Robert Haschke
   Desc:   PropertyMap stores variables of stages
*/

#include <moveit/task_constructor/properties.h>
#include <boost/format.hpp>
#include <functional>
#include <ros/console.h>

namespace moveit {
namespace task_constructor {

const std::string LOGNAME = "Properties";

class PropertyTypeRegistry
{
	struct Entry
	{
		std::string name_;
		PropertySerializerBase::SerializeFunction serialize_;
		PropertySerializerBase::DeserializeFunction deserialize_;
	};
	Entry dummy_;

	// map from type_info to corresponding converter functions
	typedef std::map<std::type_index, Entry> RegistryMap;
	RegistryMap types_;
	// map from type names (type.name or ROS msg name) to entry in types_
	using TypeNameMap = std::map<std::string, RegistryMap::iterator>;
	TypeNameMap names_;

public:
	PropertyTypeRegistry()
	  : dummy_{ "", PropertySerializerBase::dummySerialize, PropertySerializerBase::dummyDeserialize } {}
	inline bool insert(const std::type_index& type_index, const std::string& type_name,
	                   PropertySerializerBase::SerializeFunction serialize,
	                   PropertySerializerBase::DeserializeFunction deserialize);

	const Entry& entry(const std::type_index& type_index) const {
		auto it = types_.find(type_index);
		if (it == types_.end()) {
			ROS_ERROR_STREAM_NAMED(LOGNAME, "Unregistered type: " << type_index.name());
			return dummy_;
		}
		return it->second;
	}
	const Entry& entry(const std::string& type_name) const {
		auto it = names_.find(type_name);
		if (it == names_.end())
			return dummy_;
		return it->second->second;
	}
};
static PropertyTypeRegistry REGISTRY_SINGLETON;

bool PropertyTypeRegistry::insert(const std::type_index& type_index, const std::string& type_name,
                                  PropertySerializerBase::SerializeFunction serialize,
                                  PropertySerializerBase::DeserializeFunction deserialize) {
	if (type_index == std::type_index(typeid(boost::any)))
		return false;

	auto it_inserted = types_.insert(std::make_pair(type_index, Entry{ type_name, serialize, deserialize }));
	if (!it_inserted.second)
		return false;  // was already registered before

	if (!type_name.empty())  // register type_name too?
		names_.insert(std::make_pair(type_name, it_inserted.first));

	return true;
}

bool PropertySerializerBase::insert(const std::type_index& type_index, const std::string& type_name,
                                    PropertySerializerBase::SerializeFunction serialize,
                                    PropertySerializerBase::DeserializeFunction deserialize) {
	return REGISTRY_SINGLETON.insert(type_index, type_name, serialize, deserialize);
}

Property::Property(const type_info& type_info, const std::string& description, const boost::any& default_value)
  : description_(description), type_info_(type_info), default_(default_value), value_(), initialized_from_(-1) {
	// default value's type should match declared type by construction
	assert(default_.empty() || default_.type() == type_info_ || type_info_ == typeid(boost::any));
	reset();
}

Property::Property() : Property(typeid(boost::any), "", boost::any()) {}

void Property::setValue(const boost::any& value) {
	setCurrentValue(value);
	default_ = value_;
	initialized_from_ = 0;
}

void Property::setCurrentValue(const boost::any& value) {
	if (!value.empty() && type_info_ != typeid(boost::any) && value.type() != type_info_)
		throw Property::type_error(value.type().name(), type_info_.name());

	value_ = value;
	initialized_from_ = 1;  // manually initialized TODO: use enums
}

void Property::setDefaultValue(const boost::any& value) {
	if (!value.empty() && type_info_ != typeid(boost::any) && value.type() != type_info_)
		throw Property::type_error(value.type().name(), type_info_.name());

	default_ = value;
}

void Property::reset() {
	if (initialized_from_ == 0)  // TODO: use enum
		return;  // keep manually set values
	boost::any().swap(value_);
	initialized_from_ = -1;  // set to max value
}

std::string Property::serialize(const boost::any& value) {
	if (value.empty())
		return "";
	return REGISTRY_SINGLETON.entry(value.type()).serialize_(value);
}

boost::any Property::deserialize(const std::string& type_name, const std::string& wire) {
	if (type_name != Property::typeName(typeid(std::string)) && wire.empty())
		return boost::any();
	else
		return REGISTRY_SINGLETON.entry(type_name).deserialize_(wire);
}

std::string Property::typeName() const {
	if (value().empty())
		return typeName(type_info_);
	else
		return typeName(value().type());
}

std::string Property::typeName(const type_info& type_info) {
	if (type_info == typeid(boost::any))
		return "";
	else
		return REGISTRY_SINGLETON.entry(type_info).name_;
}

bool Property::initsFrom(Property::SourceFlags source) const {
	return source & source_flags_;
}

Property& Property::configureInitFrom(SourceFlags source, const Property::InitializerFunction& f) {
	if (source != source_flags_ && initializer_)
		throw error("Property was already configured for initialization from another source id");

	source_flags_ = f ? source : SourceFlags();
	initializer_ = f;
	return *this;
}

Property& Property::configureInitFrom(SourceFlags source, const std::string& name) {
	return configureInitFrom(source, [name](const PropertyMap& other) { return fromName(other, name); });
}

Property& PropertyMap::declare(const std::string& name, const Property::type_info& type_info,
                               const std::string& description, const boost::any& default_value) {
	auto it_inserted = props_.insert(std::make_pair(name, Property(type_info, description, default_value)));
	// if name was already declared, the new declaration should match in type (except it was boost::any)
	if (!it_inserted.second && it_inserted.first->second.type_info_ != typeid(boost::any) &&
	    type_info != it_inserted.first->second.type_info_)
		throw Property::type_error(type_info.name(), it_inserted.first->second.type_info_.name());
	return it_inserted.first->second;
}

bool PropertyMap::hasProperty(const std::string& name) const {
	auto it = props_.find(name);
	return it != props_.end();
}

Property& PropertyMap::property(const std::string& name) {
	auto it = props_.find(name);
	if (it == props_.end())
		throw Property::undeclared(name);
	return it->second;
}

void PropertyMap::exposeTo(PropertyMap& other, const std::set<std::string>& properties) const {
	for (const std::string& name : properties)
		exposeTo(other, name, name);
}

void PropertyMap::exposeTo(PropertyMap& other, const std::string& name, const std::string& other_name) const {
	const Property& p = property(name);
	other.declare(other_name, p.type_info_, p.description_, p.default_);
}

void PropertyMap::configureInitFrom(Property::SourceFlags source, const std::set<std::string>& properties) {
	for (auto& pair : props_) {
		if (properties.empty() || properties.count(pair.first))
			try {
				pair.second.configureInitFrom(source, std::bind(&fromName, std::placeholders::_1, pair.first));
			} catch (Property::error& e) {
				e.setName(pair.first);
				throw;
			}
	}
}

template <>
void PropertyMap::set<boost::any>(const std::string& name, const boost::any& value) {
	auto range = props_.equal_range(name);
	if (range.first == range.second) {  // name is not yet declared
		if (value.empty())
			throw Property::undeclared(name, "trying to set undeclared property '" + name + "' with NULL value");
		auto it = props_.insert(range.first, std::make_pair(name, Property(value.type(), "", boost::any())));
		it->second.setValue(value);
	} else
		range.first->second.setValue(value);
}

void PropertyMap::setCurrent(const std::string& name, const boost::any& value) {
	property(name).setCurrentValue(value);
}

const boost::any& PropertyMap::get(const std::string& name) const {
	return property(name).value();
}

size_t PropertyMap::countDefined(const std::vector<std::string>& list) const {
	size_t count = 0u;
	for (const std::string& name : list) {
		if (!get(name).empty())
			++count;
	}
	return count;
}

void PropertyMap::reset() {
	for (auto& pair : props_)
		pair.second.reset();
}

void PropertyMap::performInitFrom(Property::SourceFlags source, const PropertyMap& other) {
	for (auto& pair : props_) {
		Property& p = pair.second;

		// don't override value previously set by higher-priority source
		// MANUAL > CURRENT > PARENT > INTERFACE
		if (p.initialized_from_ < source && p.defined())
			continue;
		// is the property configured for initialization from this source?
		if (!p.initsFrom(source))
			continue;

		boost::any value;
		try {
			value = p.initializer_(other);
		} catch (const Property::undeclared&) {
			// ignore undeclared
			continue;
		} catch (const Property::undefined&) {
		}

		ROS_DEBUG_STREAM_NAMED(LOGNAME, pair.first << ": " << p.initialized_from_ << " -> " << source << ": "
		                                           << Property::serialize(value));
		p.setCurrentValue(value);
		p.initialized_from_ = source;
	}
}

boost::any fromName(const PropertyMap& other, const std::string& other_name) {
	return other.get(other_name);
}

Property::error::error(const std::string& msg) : std::runtime_error(msg), msg_("Property: " + msg) {}

void Property::error::setName(const std::string& name) {
	property_name_ = name;
	// compose message from property name and runtime_errors' msg
	msg_ = "Property '" + name + "': " + std::runtime_error::what();
}

Property::undeclared::undeclared(const std::string& name, const std::string& msg) : Property::error(msg) {
	setName(name);
}

Property::undefined::undefined(const std::string& name, const std::string& msg) : Property::error(msg) {
	setName(name);
}

static boost::format TYPE_ERROR_FMT("type (%1%) doesn't match property's declared type (%2%)");
Property::type_error::type_error(const std::string& current_type, const std::string& declared_type)
  : Property::error(boost::str(TYPE_ERROR_FMT % current_type % declared_type)) {}

}  // namespace task_constructor
}  // namespace moveit


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#define NT2_UNIT_MODULE "nt2 combinatorial toolbox - primes/scalar Mode"

//////////////////////////////////////////////////////////////////////////////
// unit test behavior of combinatorial components in scalar mode
//////////////////////////////////////////////////////////////////////////////
/// created  by jt the 07/03/2011
///
#include <nt2/combinatorial/include/functions/primes.hpp>
#include <nt2/include/functions/min.hpp>
#include <nt2/include/functions/saturate.hpp>

#include <boost/type_traits/is_same.hpp>
#include <nt2/sdk/functor/meta/call.hpp>
#include <nt2/sdk/meta/as_integer.hpp>
#include <nt2/sdk/meta/as_floating.hpp>
#include <nt2/sdk/meta/as_signed.hpp>
#include <nt2/sdk/meta/upgrade.hpp>
#include <nt2/sdk/meta/downgrade.hpp>
#include <nt2/sdk/meta/scalar_of.hpp>
#include <boost/dispatch/meta/as_floating.hpp>
#include <boost/type_traits/common_type.hpp>
#include <nt2/sdk/unit/tests.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/memory/buffer.hpp>
#include <nt2/constant/constant.hpp>
#include <nt2/table.hpp>
#include <nt2/include/functions/tic.hpp>
#include <nt2/include/functions/toc.hpp>

NT2_TEST_CASE_TPL ( primes_integer__1_0,  (int32_t))//NT2_INTEGRAL_TYPES)
{

  using nt2::primes;
  using nt2::tag::primes_;
  typedef typename nt2::meta::as_integer<T>::type iT;
  typedef typename nt2::meta::call<primes_(T)>::type r_t;
  typedef typename nt2::meta::scalar_of<r_t>::type ssr_t;
  typedef typename nt2::meta::upgrade<T>::type u_t;

  T p[6] = {2, 3, 5, 7, 11, 13};
  nt2::table<T> myp = primes(T(15));
  // specific values tests
  NT2_DISPLAY(myp);
 for(size_t i=1; i <= 6; ++i)
   {
     NT2_TEST_EQUAL(p[i-1], myp(i));
   }

 nt2::table<T> myp1 = primes(T(100000));
 NT2_DISPLAY(primes(T(100)));
 nt2::table<T> myp9 = primes(T(9));
 NT2_DISPLAY(myp9);
}


text:
/*******************************************************************************
 * CLI - A simple command line interface.
 * Copyright (C) 2016-2021 Daniele Pallastrelli
 *
 * Boost Software License - Version 1.0 - August 17th, 2003
 *
 * Permission is hereby granted, free of charge, to any person or organization
 * obtaining a copy of the software and accompanying documentation covered by
 * this license (the "Software") to use, reproduce, display, distribute,
 * execute, and transmit the Software, and to prepare derivative works of the
 * Software, and to permit third-parties to whom the Software is furnished to
 * do so, all subject to the following:
 *
 * The copyright notices in the Software and this entire statement, including
 * the above license grant, this restriction and the following disclaimer,
 * must be included in all copies of the Software, in whole or in part, and
 * all derivative works of the Software, unless such copies or derivative
 * works are solely in the form of machine-executable object code generated by
 * a source language processor.
 *
 * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 ******************************************************************************/

#include <boost/test/unit_test.hpp>
#include "cli/detail/history.h"

using namespace cli;
using namespace cli::detail;

BOOST_AUTO_TEST_SUITE(HistorySuite)

BOOST_AUTO_TEST_CASE(NotFull)
{
    History history(10);
    history.NewCommand("item1");
    history.NewCommand("item2");
    history.NewCommand("item3");
    history.NewCommand("item4");

    BOOST_CHECK_EQUAL(history.Next(), "");
    BOOST_CHECK_EQUAL(history.Previous(""), "item4");
    BOOST_CHECK_EQUAL(history.Next(), "");
    BOOST_CHECK_EQUAL(history.Previous(""), "item4");
    BOOST_CHECK_EQUAL(history.Previous("item4"), "item3");
    BOOST_CHECK_EQUAL(history.Previous("item3"), "item2");
    BOOST_CHECK_EQUAL(history.Previous("item2"), "item1");
    BOOST_CHECK_EQUAL(history.Previous("item1"), "item1");
}

BOOST_AUTO_TEST_CASE(Full)
{
    History history(3);
    history.NewCommand("item1");
    history.NewCommand("item2");
    history.NewCommand("item3");
    history.NewCommand("item4");

    BOOST_CHECK_EQUAL(history.Previous(""), "item4");
    BOOST_CHECK_EQUAL(history.Next(), "");
    BOOST_CHECK_EQUAL(history.Previous(""), "item4");
    BOOST_CHECK_EQUAL(history.Previous("item4"), "item3");
    BOOST_CHECK_EQUAL(history.Previous("item3"), "item3");
    BOOST_CHECK_EQUAL(history.Previous("item3"), "item3");
    BOOST_CHECK_EQUAL(history.Previous("item3"), "item3");
    BOOST_CHECK_EQUAL(history.Next(), "item4");
    BOOST_CHECK_EQUAL(history.Next(), "");
}

BOOST_AUTO_TEST_CASE(Insertion)
{
    History history(10);
    history.NewCommand("item1");
    history.NewCommand("item2");
    history.NewCommand("item3");
    history.NewCommand("item4");

    BOOST_CHECK_EQUAL(history.Previous(""), "item4");
    BOOST_CHECK_EQUAL(history.Previous("item4"), "item3");
    BOOST_CHECK_EQUAL(history.Previous("foo"), "item2");
    BOOST_CHECK_EQUAL(history.Next(), "foo");
    BOOST_CHECK_EQUAL(history.Next(), "item4");
    BOOST_CHECK_EQUAL(history.Previous("item4"), "foo");
    BOOST_CHECK_EQUAL(history.Previous("foo"), "item2");

    history.NewCommand("item5");

    BOOST_CHECK_EQUAL(history.Previous(""), "item5");
    BOOST_CHECK_EQUAL(history.Previous("item5"), "item4");
    BOOST_CHECK_EQUAL(history.Next(), "item5");
    BOOST_CHECK_EQUAL(history.Next(), "");
}

BOOST_AUTO_TEST_CASE(InsertionIgnoreRepeat)
{
    History history(10);

    history.NewCommand("item1");
    history.NewCommand("item2");
    history.NewCommand("item2");
    history.NewCommand("item1");
    history.NewCommand("item1");
    history.NewCommand("item3");
    history.NewCommand("item3");
    history.NewCommand("item3");
    history.NewCommand("item1");
    history.NewCommand("item1");
    history.NewCommand("item1");

    BOOST_CHECK_EQUAL(history.Previous(""), "item1");
    BOOST_CHECK_EQUAL(history.Previous("item1"), "item3");
    BOOST_CHECK_EQUAL(history.Previous("item3"), "item1");
    BOOST_CHECK_EQUAL(history.Previous("item1"), "item2");
    BOOST_CHECK_EQUAL(history.Previous("item2"), "item1");
    BOOST_CHECK_EQUAL(history.Next(), "item2");
    BOOST_CHECK_EQUAL(history.Next(), "item1");
    BOOST_CHECK_EQUAL(history.Next(), "item3");
    BOOST_CHECK_EQUAL(history.Next(), "item1");
}

BOOST_AUTO_TEST_CASE(Empty)
{
    History history(10);

    BOOST_CHECK_EQUAL(history.Next(), "");
    BOOST_CHECK_EQUAL(history.Previous(""), "");

    History history2(10);

    BOOST_CHECK_EQUAL(history2.Previous(""), "");
    BOOST_CHECK_EQUAL(history2.Next(), "");

    History history3(10);

    BOOST_CHECK_EQUAL(history3.Previous(""), "");
    history3.NewCommand("item1");
    BOOST_CHECK_EQUAL(history3.Next(), "");
    BOOST_CHECK_EQUAL(history3.Previous(""), "item1");
}

BOOST_AUTO_TEST_CASE(Copies)
{
    History history(10);

    const std::vector<std::string> v = { "item1", "item2", "item3" };
    history.LoadCommands(v);

    BOOST_CHECK_EQUAL(history.Previous(""), "item3");
    BOOST_CHECK_EQUAL(history.Previous("item3"), "item2");
    BOOST_CHECK_EQUAL(history.Previous("item2"), "item1");
    BOOST_CHECK_EQUAL(history.Previous("item1"), "item1");

    history.NewCommand("itemA");
    history.NewCommand("itemB");

    BOOST_CHECK_EQUAL(history.Previous(""), "itemB");
    BOOST_CHECK_EQUAL(history.Previous("itemB"), "itemA");
    BOOST_CHECK_EQUAL(history.Previous("itemA"), "item3");
    BOOST_CHECK_EQUAL(history.Previous("item3"), "item2");
    BOOST_CHECK_EQUAL(history.Previous("item2"), "item1");

    auto cmds = history.GetCommands();
    const std::vector<std::string> expected = { "itemA", "itemB" };
    BOOST_CHECK_EQUAL_COLLECTIONS(cmds.begin(), cmds.end(), expected.begin(), expected.end());

    History history1(3);

    const std::vector<std::string> v1 = { "item1", "item2", "item3" };
    history1.LoadCommands(v1);

    BOOST_CHECK_EQUAL(history1.Previous(""), "item3");
    BOOST_CHECK_EQUAL(history1.Previous("item3"), "item2");
    BOOST_CHECK_EQUAL(history1.Previous("item2"), "item2");

    history1.NewCommand("itemA");
    history1.NewCommand("itemB");

    BOOST_CHECK_EQUAL(history1.Previous(""), "itemB");
    BOOST_CHECK_EQUAL(history1.Previous("itemB"), "itemA");
    BOOST_CHECK_EQUAL(history1.Previous("itemA"), "itemA");

    auto cmds1 = history1.GetCommands();
    const std::vector<std::string> expected1 = { "itemA", "itemB" };
    BOOST_CHECK_EQUAL_COLLECTIONS(cmds1.begin(), cmds1.end(), expected1.begin(), expected1.end());

    History history2(3);

    history2.NewCommand("itemA");
    history2.NewCommand("itemB");
    history2.NewCommand("itemC");
    history2.NewCommand("itemD");
    history2.NewCommand("itemE");

    auto cmds2 = history2.GetCommands();
    const std::vector<std::string> expected2 = { "itemC", "itemD", "itemE" };
    BOOST_CHECK_EQUAL_COLLECTIONS(cmds2.begin(), cmds2.end(), expected2.begin(), expected2.end());
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: JonasProgrammer/cli

max_issues_repo_name: JonasProgrammer/cli

max_forks_repo_name: JonasProgrammer/cli


text:
// Copyright (c) 2015-2020 Daniel Cooke
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

#include "duplicate_allele_depth.hpp"

#include <algorithm>
#include <iterator>
#include <cassert>

#include <boost/variant.hpp>

#include "basics/mappable_reference_wrapper.hpp"
#include "core/types/allele.hpp"
#include "io/variant/vcf_record.hpp"
#include "io/variant/vcf_spec.hpp"
#include "utils/mappable_algorithms.hpp"
#include "utils/maths.hpp"
#include "../facets/samples.hpp"
#include "../facets/reads_summary.hpp"
#include "../facets/alleles.hpp"
#include "../facets/read_assignments.hpp"

namespace octopus { namespace csr {

const std::string DuplicateAlleleDepth::name_ = "DAD";

std::unique_ptr<Measure> DuplicateAlleleDepth::do_clone() const
{
    return std::make_unique<DuplicateAlleleDepth>(*this);
}

Measure::ValueType DuplicateAlleleDepth::get_value_type() const
{
    return std::size_t {};
}

namespace {

bool is_canonical(const VcfRecord::NucleotideSequence& allele) noexcept
{
    return !(allele == vcfspec::missingValue || allele == vcfspec::deleteMaskAllele);
}

bool has_called_alt_allele(const VcfRecord& call, const VcfRecord::SampleName& sample)
{
    if (!call.has_genotypes()) return true;
    const auto& genotype = get_genotype(call, sample);
    return std::any_of(std::cbegin(genotype), std::cend(genotype),
                       [&] (const auto& allele) { return allele != call.ref() && is_canonical(allele); });
}

bool other_segments_equal(const AlignedRead& lhs, const AlignedRead& rhs) noexcept
{
    if (lhs.has_other_segment()) {
        return rhs.has_other_segment() && lhs.next_segment() == rhs.next_segment();
    } else {
        return !rhs.has_other_segment();
    }
}

bool are_realigned_equal(const AlignedRead& lhs, const AlignedRead& rhs) noexcept
{
    return lhs.mapping_quality()    == rhs.mapping_quality()
           && lhs.name()            == rhs.name()
           && lhs.sequence()        == rhs.sequence()
           && lhs.base_qualities()  == rhs.base_qualities()
           && lhs.read_group()      == rhs.read_group()
           && lhs.flags()           == rhs.flags()
           && other_segments_equal(lhs, rhs);
}

bool is_duplicate(const AlignedRead& realigned_read, const std::vector<AlignedRead>& duplicate_reads)
{
    // Duplicate realigned reads may have different mapping position and cigar to the raw duplicate reads
    const auto is_duplicate = [&] (const auto& read) { return are_realigned_equal(read, realigned_read); };
    return std::find_if(std::cbegin(duplicate_reads), std::cend(duplicate_reads), is_duplicate) != std::cend(duplicate_reads);
}

} // namespace

Measure::ResultType DuplicateAlleleDepth::do_evaluate(const VcfRecord& call, const FacetMap& facets) const
{
    const auto& samples = get_value<Samples>(facets.at("Samples"));
    const auto& reads = get_value<ReadsSummary>(facets.at("ReadsSummary"));
    const auto& alleles = get_value<Alleles>(facets.at("Alleles"));
    const auto& assignments = get_value<ReadAssignments>(facets.at("ReadAssignments")).alleles;
    const auto num_alleles = call.alt().size() + 1;
    Array<Array<Optional<ValueType>>> result(samples.size(), Array<Optional<ValueType>>(num_alleles));
    for (std::size_t s {0}; s < samples.size(); ++s) {
        const auto sample_alleles = get(alleles, call, samples[s]);
        const auto& duplicate_reads = overlap_range(reads.at(samples[s]).duplicates, call);
        const auto& support = assignments.at(samples[s]);
        for (std::size_t a {0}; a < num_alleles; ++a) {
            if (sample_alleles[a] && support.count(*sample_alleles[a]) > 0) {
                if (!duplicate_reads.empty()) {
                    const auto compute_duplicate_support = [&] (const auto& allele) {
                        const auto& allele_support = support.at(allele);
                        std::size_t result {0};
                        for (const auto& duplicates : duplicate_reads) {
                            const auto is_duplicate_helper = [&] (const auto& read) { return is_duplicate(read, duplicates.reads); };
                            auto num_dups = std::count_if(std::cbegin(allele_support), std::cend(allele_support), is_duplicate_helper);
                            if (num_dups > 1) --num_dups; // One 'duplicate' read is not actually a duplicate
                            result += num_dups;
                        }
                        return result;
                    };
                    result[s][a] = compute_duplicate_support(*sample_alleles[a]);
                } else {
                    result[s][a] = std::size_t {0};
                }
            }
        }
    }
    return result;
}

Measure::ResultCardinality DuplicateAlleleDepth::do_cardinality() const noexcept
{
    return ResultCardinality::samples_and_alleles;
}

const std::string& DuplicateAlleleDepth::do_name() const
{
    return name_;
}

std::string DuplicateAlleleDepth::do_describe() const
{
    return "Number of realigned reads supporting ALT alleles identified as duplicates";
}

std::vector<std::string> DuplicateAlleleDepth::do_requirements() const
{

    return {"Samples", "ReadsSummary", "Alleles", "ReadAssignments"};
}

boost::optional<Measure::Aggregator> DuplicateAlleleDepth::do_aggregator() const noexcept
{
    return Measure::Aggregator::max_tail;
}

} // namespace csr
} // namespace octopus

max_stars_repo_name: roryk/octopus

max_issues_repo_name: roryk/octopus

max_forks_repo_name: roryk/octopus


text:
/**
 *    Copyright (C) 2016 MongoDB Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/platform/basic.h"

#include "mongo/db/pipeline/document_source_tee_consumer.h"

#include <boost/intrusive_ptr.hpp>
#include <boost/optional.hpp>
#include <vector>

#include "mongo/db/pipeline/document.h"
#include "mongo/db/pipeline/expression_context.h"

namespace mongo {

using boost::intrusive_ptr;

DocumentSourceTeeConsumer::DocumentSourceTeeConsumer(const intrusive_ptr<ExpressionContext>& expCtx,
                                                     size_t facetId,
                                                     const intrusive_ptr<TeeBuffer>& bufferSource)
    : DocumentSource(expCtx), _facetId(facetId), _bufferSource(bufferSource) {}

boost::intrusive_ptr<DocumentSourceTeeConsumer> DocumentSourceTeeConsumer::create(
    const boost::intrusive_ptr<ExpressionContext>& expCtx,
    size_t facetId,
    const boost::intrusive_ptr<TeeBuffer>& bufferSource) {
    return new DocumentSourceTeeConsumer(expCtx, facetId, bufferSource);
}

DocumentSource::GetNextResult DocumentSourceTeeConsumer::getNext() {
    pExpCtx->checkForInterrupt();
    return _bufferSource->getNext(_facetId);
}

void DocumentSourceTeeConsumer::dispose() {
    _bufferSource->dispose(_facetId);
}

Value DocumentSourceTeeConsumer::serialize(bool explain) const {
    // This stage will be inserted into the beginning of a pipeline, but should not show up in the
    // explain output.
    return Value();
}
}  // namespace mongo

max_stars_repo_name: SunguckLee/real-mongodb

max_issues_repo_name: SunguckLee/real-mongodb

max_forks_repo_name: SunguckLee/real-mongodb


text:
//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2009/04/18
//
//
//
// This file is part of Kosmos File System (KFS).
//
// 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.
//
//----------------------------------------------------------------------------

extern "C" {
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/time.h>
}

#include <cstdlib>
#include <cstring>
#include <istream>
#include <sstream>
#include <iostream>
#include <fstream>
#include <cerrno>
#include <cassert>
#include <boost/scoped_array.hpp>

#include "KfsToolsCommon.h"

using namespace std;
using boost::scoped_array;
using namespace KFS;
using namespace KFS::tools;

string
KFS::tools::getRemotePath(const std::string & host, const int & port, const std::string & path)
{
      ostringstream oss (ostringstream::out);

      oss << "'kfs://" << host << ":" << port;

      if (path.length() < 1 || path[0] != '/') oss << "/";

      oss << path << "'";

      return oss.str();
}

bool
KFS::tools::getInt(const string & fromString, int &toInt)
{
    if (fromString.length() < 1) return false;

    std::istringstream i ( fromString );

    int val;
    char c;

    if ( ! ( i >> val ) || i.get ( c ) )
    {
	return false;
    }

    toInt = val;
    return true;
}

void
KFS::tools::parseServer(const string & serverDesc, string & serverHost, int & serverPort)
{
    if (serverDesc.length() < 1) return;

    size_t idx = serverDesc.find(':');

    if (idx != string::npos)
    {
	serverHost = serverDesc.substr(0, idx);
	getInt(serverDesc.substr(idx + 1), serverPort);
    }
    else
    {
	serverHost = serverDesc;
    }
}

void
KFS::tools::getEnvServer(string & serverHost, int & serverPort)
{
    const char * envServer = getenv("KFS_SERVER_HOST");
    const char * envPort = getenv("KFS_SERVER_PORT");

    if (envServer)
    {
	parseServer(envServer, serverHost, serverPort);
    }

    if (envPort)
    {
	getInt(string(envPort), serverPort);
    }
}

bool
KFS::tools::parsePath(const string & pathDesc, string & serverHost,
		int & serverPort, string & filePath, bool & isRemote)
{
    if (pathDesc.length() < 1) return false;

    if (pathDesc.find("file://") == 0)
    {
	// Local path without 'file://' - 7 characters
	filePath = pathDesc.substr(7);

	if (filePath.length() < 1) filePath=".";

	isRemote = false;

	assert (filePath.length() > 0);

	return true;
    }
    else if (pathDesc.find("kfs://") != 0)
    {
	filePath = pathDesc;
	isRemote = false;

	assert (filePath.length() > 0);

	return true;
    }

    // Here pDesc contains only (optional) server:port and /path information

    size_t idx = pathDesc.find("/", 6);

    // No '/' found - something is wrong!
    // We don't require hostname and/or port to be provided, but we need
    // '/' to use as the beginning of the path!
    if (idx == string::npos) return false;

    // File path within KFS starts at '/' character
    filePath = pathDesc.substr(idx);
    idx -= 6;

    // In case there was no server specified (like in: 'kfs:///my_file.txt')
    // try to get its parameters from environment.
    getEnvServer(serverHost, serverPort);

    // But it might be specified, in which case we want to try to read it
    // from pathDesc - if it contains only host, port read from environment (if any)
    // is used.
    parseServer(pathDesc.substr(6, idx), serverHost, serverPort);

    isRemote = true;

    assert (filePath.length() > 0);
    assert (filePath[0] == '/');

    return true;
}

//
// Guts of the work to copy the file.
//

//
// BackupFile3 is not used?
//
// static int
// BackupFile3(KfsClientPtr kfsClient, string srcfilename, string kfsfilename)
// {
//     // 64MB buffers
//     const int bufsize = 1 << 26;
//     scoped_array<char> kfsBuf;
//     int kfsfd, nRead;
//     long long n = 0;
//     ifstream ifs;
//     int res;
//
//     assert (kfsClient != 0);
//
//     ifs.open(srcfilename.c_str(), ios_base::in);
//     if (!ifs) {
//         cout << "Unable to open: " << srcfilename << endl;
//         exit(-1);
//     }
//
//     kfsfd = kfsClient->Create(kfsfilename.c_str());
//     if (kfsfd < 0) {
//         cout << "Create " << kfsfilename << " failed: " << kfsfd << endl;
//         exit(-1);
//     }
//     kfsBuf.reset(new char[bufsize]);
//
//     while (!ifs.eof()) {
//         ifs.read(kfsBuf.get(), bufsize);
//
//         nRead = ifs.gcount();
//
//         if (nRead <= 0)
//             break;
//
//         res = kfsClient->Write(kfsfd, kfsBuf.get(), nRead);
//         if (res < 0) {
//             cout << "Write failed with error code: " << res << endl;
//             exit(-1);
//         }
//         n += nRead;
//         // cout << "Wrote: " << n << endl;
//     }
//     ifs.close();
//     kfsClient->Close(kfsfd);
//
//     return 0;
// }

static int
BackupFile2(KfsClientPtr kfsClient, string srcfilename, string kfsfilename)
{
    // 64MB buffers
    const int bufsize = 1 << 26;
    scoped_array<char> kfsBuf;
    int kfsfd, nRead;
    int srcFd;
    int res;

    assert (kfsClient != 0);

    if (srcfilename == "-")
        // dup stdin() and read from there
        srcFd = dup(0);
    else
        srcFd = open(srcfilename.c_str(), O_RDONLY);
    if (srcFd  < 0) {
        cout << "Unable to open: " << srcfilename << endl;
        exit(-1);
    }

    kfsfd = kfsClient->Create(kfsfilename.c_str());
    if (kfsfd < 0) {
        cout << "Create " << kfsfilename << " failed: " << kfsfd << endl;
        exit(-1);
    }
    kfsBuf.reset(new char[bufsize]);

    while (1) {
        nRead = read(srcFd, kfsBuf.get(), bufsize);

        if (nRead <= 0)
            break;

        res = kfsClient->Write(kfsfd, kfsBuf.get(), nRead);
        if (res < 0) {
            cout << "Write failed with error code: " << res << endl;
            exit(-1);
        }
    }
    close(srcFd);
    kfsClient->Close(kfsfd);

    return 0;
}

static bool
doMkdirs(KfsClientPtr kfsClient, const string & path)
{
    int res;

    assert (kfsClient != 0);

    res = kfsClient->Mkdirs(path.c_str());
    if ((res < 0) && (res != -EEXIST)) {
        cout << "Mkdir failed: " << ErrorCodeToStr(res) << endl;
        return false;
    }
    return true;
}

void
KFS::tools::MakeKfsLeafDir(KfsClientPtr kfsClient, const string &sourcePath, string &kfsPath)
{
    string leaf;
    string::size_type slash = sourcePath.rfind('/');

    if (!kfsClient)
    {
	cerr << "Error: No KFS client provided!\n";
	exit(-1);
    }

    // get everything after the last slash
    if (slash != string::npos) {
	leaf.assign(sourcePath, slash+1, string::npos);
    } else {
	leaf = sourcePath;
    }
    if (kfsPath[kfsPath.size()-1] != '/')
        kfsPath += "/";

    kfsPath += leaf;
    doMkdirs(kfsClient, kfsPath);
}

int
KFS::tools::BackupFile(KfsClientPtr kfsClient, const string &sourcePath, const string &kfsPath)
{
    string filename;
    string::size_type slash = sourcePath.rfind('/');

    if (!kfsClient)
    {
	cerr << "Error: No KFS client provided!\n";
	exit(-1);
    }

    // get everything after the last slash
    if (slash != string::npos) {
	filename.assign(sourcePath, slash+1, string::npos);
    } else {
	filename = sourcePath;
    }

    // for the dest side: if kfsPath is a dir, we are copying to
    // kfsPath with srcFilename; otherwise, kfsPath is a file (that
    // potentially exists) and we are ovewriting/creating it
    if (kfsClient->IsDirectory(kfsPath.c_str())) {
        string dst = kfsPath;

        if (dst[kfsPath.size() - 1] != '/')
            dst += "/";

        return BackupFile2(kfsClient, sourcePath, dst + filename);
    }

    // kfsPath is the filename that is being specified for the cp
    // target.  try to copy to there...
    return BackupFile2(kfsClient, sourcePath, kfsPath);
}

int
KFS::tools::BackupDir(KfsClientPtr kfsClient, const string &dirname, string &kfsdirname)
{
    string subdir, kfssubdir;
    DIR *dirp;
    struct dirent *fileInfo;

    if (!kfsClient)
    {
	cerr << "Error: No KFS client provided!\n";
	exit(-1);
    }

    if ((dirp = opendir(dirname.c_str())) == NULL) {
        perror("opendir: ");
        exit(-1);
    }

    if (!doMkdirs(kfsClient, kfsdirname)) {
        cout << "Unable to make kfs dir: " << kfsdirname << endl;
        closedir(dirp);
	return 1;
    }

    while ((fileInfo = readdir(dirp)) != NULL) {
        if (strcmp(fileInfo->d_name, ".") == 0)
            continue;
        if (strcmp(fileInfo->d_name, "..") == 0)
            continue;

        string name = dirname + "/" + fileInfo->d_name;
        struct stat buf;
        stat(name.c_str(), &buf);

        if (S_ISDIR(buf.st_mode)) {
	    subdir = dirname + "/" + fileInfo->d_name;
            kfssubdir = kfsdirname + "/" + fileInfo->d_name;
            BackupDir(kfsClient, subdir, kfssubdir);
        } else if (S_ISREG(buf.st_mode)) {
	    BackupFile2(kfsClient, dirname + "/" + fileInfo->d_name, kfsdirname + "/" + fileInfo->d_name);
        }
    }
    closedir(dirp);

    return 0;
}

//
// Guts of the work
//
static int
RestoreFile2(KfsClientPtr kfsClient, string kfsfilename, string localfilename)
{
    const int bufsize = 65536;
    char kfsBuf[bufsize];
    int kfsfd, n = 0, nRead, toRead;
    int localFd;

    assert (kfsClient != 0);

    kfsfd = kfsClient->Open(kfsfilename.c_str(), O_RDONLY);
    if (kfsfd < 0) {
        cout << "Open failed: " << endl;
        exit(-1);
    }

    if (localfilename == "-")
        // send to stdout
        localFd = dup(1);
    else
        localFd = open(localfilename.c_str(), O_WRONLY | O_CREAT, S_IRUSR|S_IWUSR);

    if (localFd < 0) {
        cout << "Unable to open: " << localfilename << endl;
        exit(-1);
    }

    while (1) {
        toRead = bufsize;

        nRead = kfsClient->Read(kfsfd, kfsBuf, toRead);
        if (nRead <= 0) {
	    // EOF
            break;
        }
        n += nRead;
        write(localFd, kfsBuf, nRead);
    }
    kfsClient->Close(kfsfd);
    close(localFd);
    return 0;
}

int
KFS::tools::RestoreFile(KfsClientPtr kfsClient, string &kfsPath, string &localPath)
{
    string filename;
    string::size_type slash = kfsPath.rfind('/');
    struct stat statInfo;
    string localParentDir;

    if (!kfsClient)
    {
	cerr << "Error: No KFS client provided!\n";
	exit(-1);
    }

    // get everything after the last slash
    if (slash != string::npos) {
	filename.assign(kfsPath, slash+1, string::npos);
    } else {
	filename = kfsPath;
    }

    // get the path in local FS.  If we what we is an existing file or
    // directory in local FS, localParentDir will point to it; if localPath is
    // non-existent, then we find the parent dir and check for its
    // existence.  That is, we are trying to handle cp kfs://file/a to
    // /path/b and we are checking for existence of "/path"
    localParentDir = localPath;

    if (stat(localPath.c_str(), &statInfo)) {
	slash = localPath.rfind('/');
	if (slash == string::npos)
	{
	    localParentDir = ".";
	    filename = localPath;
	}
	else
	{
	    localParentDir.assign(localPath, 0, slash);

	    // this is the target filename
	    filename.assign(localPath, slash + 1, string::npos);
	}

	stat(localParentDir.c_str(), &statInfo);
    }

    if (localPath == "-")
        statInfo.st_mode = S_IFREG;

    if (S_ISDIR(statInfo.st_mode)) {
	return RestoreFile2(kfsClient, kfsPath, localParentDir + "/" + filename);
    }

    if (S_ISREG(statInfo.st_mode)) {
	return RestoreFile2(kfsClient, kfsPath, localPath);
    }

    // need to make the local dir
    cout << "Local Path: " << localPath << " is non-existent!" << endl;
    return -1;
}

int
KFS::tools::RestoreDir(KfsClientPtr kfsClient, string &kfsdirname, string &dirname)
{
    string kfssubdir, subdir;
    int res, retval = 0;
    vector<KfsFileAttr> fileInfo;
    vector<KfsFileAttr>::size_type i;

    if (!kfsClient)
    {
	cerr << "Error: No KFS client provided!\n";
	exit(-1);
    }

    if ((res = kfsClient->ReaddirPlus(kfsdirname.c_str(), fileInfo)) < 0) {
        cout << "RestoreDir::ReaddirPlus(" <<  kfsdirname << ") failed: " << res << endl;
        return res;
    }

    struct stat statInfo;

    statInfo.st_mode = S_IFREG;

    if (stat(dirname.c_str(), &statInfo) < 0)
    {
	if (mkdir(dirname.c_str(), 0777))
	{
	    cout << "Could not create '" << dirname << "' directory.\n";
	    perror("mkdir: ");
	    return 1;
	}
    }
    else if (!S_ISDIR(statInfo.st_mode))
    {
	cout << "'" << dirname << "' exists and is not a firectory\n";
	return 1;
    }

    for (i = 0; i < fileInfo.size(); ++i) {
        if (fileInfo[i].isDirectory) {
            if ((fileInfo[i].filename == ".") ||
                (fileInfo[i].filename == ".."))
                continue;

	    subdir = dirname + "/" + fileInfo[i].filename;

	    kfssubdir = kfsdirname + "/" + fileInfo[i].filename.c_str();
            res = RestoreDir(kfsClient, kfssubdir, subdir);
            if (res < 0)
                retval = res;

        } else {
            res = RestoreFile2(kfsClient, kfsdirname + "/" + fileInfo[i].filename,
                               dirname + "/" + fileInfo[i].filename);
            if (res < 0)
                retval = res;
        }
    }
    return retval;
}

//
// Guts of the work to copy the file.
//
static int
CopyFile2(KfsClientPtr kfsClient, string srcfilename, string dstfilename)
{
    const int bufsize = 65536;
    char kfsBuf[bufsize];
    int srcfd, dstfd, nRead, toRead;
    long long n = 0;
    int res;

    assert (kfsClient != 0);

    srcfd = kfsClient->Open(srcfilename.c_str(), O_RDONLY);
    if (srcfd < 0) {
        cout << "Unable to open: " << srcfilename << endl;
        return srcfd;
    }

    dstfd = kfsClient->Create(dstfilename.c_str());
    if (dstfd < 0) {
        cout << "Create " << dstfilename << " failed: " << ErrorCodeToStr(dstfd) << endl;
        return dstfd;
    }

    while (1) {
	toRead = bufsize;
	nRead = kfsClient->Read(srcfd, kfsBuf, toRead);
	if (nRead <= 0)
	    break;

        // write it out
        res = kfsClient->Write(dstfd, kfsBuf, nRead);
        if (res < 0) {
            cout << "Write failed with error code: " << ErrorCodeToStr(res) << endl;
            return res;
        }
        n += nRead;
    }
    kfsClient->Close(srcfd);
    kfsClient->Close(dstfd);

    return 0;
}

int
KFS::tools::CopyFile(KfsClientPtr kfsClient, const string &srcPath, const string &dstPath)
{
    string filename;
    string::size_type slash = srcPath.rfind('/');

    if (!kfsClient)
    {
	cerr << "Error: No KFS client provided!\n";
	exit(-1);
    }

    // get everything after the last slash
    if (slash != string::npos) {
	filename.assign(srcPath, slash+1, string::npos);
    } else {
	filename = srcPath;
    }

    // for the dest side: if the dst is a dir, we are copying to
    // dstPath with srcFilename; otherwise, dst is a file (that
    // potenitally exists) and we are ovewriting/creating it
    if (kfsClient->IsDirectory(dstPath.c_str())) {
        string dst = dstPath;

        if (dst[dstPath.size() - 1] != '/')
            dst += "/";

        return CopyFile2(kfsClient, srcPath, dst + filename);
    }

    // dstPath is the filename that is being specified for the cp
    // target.  try to copy to there...
    return CopyFile2(kfsClient, srcPath, dstPath);
}

int
KFS::tools::CopyDir(KfsClientPtr kfsClient, const string & srcDirname, string dstDirname)
{
    vector<string> dirEntries;
    vector<string>::size_type i;
    int res;

    if (!kfsClient)
    {
	cerr << "Error: No KFS client provided!\n";
	exit(-1);
    }

    if ((res = kfsClient->Readdir(srcDirname.c_str(), dirEntries)) < 0)
    {
        cout << "Readdir(" << srcDirname << ") failed: " << res << endl;
        return res;
    }

    if (!doMkdirs(kfsClient, dstDirname))
    {
	cout << "Unable to make kfs dir: " << dstDirname << endl;
	return res;
    }

    for (i = 0; i < dirEntries.size(); ++i)
    {
        if ((dirEntries[i] == ".") || (dirEntries[i] == ".."))
            continue;

	string src = srcDirname + "/" + dirEntries[i];
	string dst = dstDirname + "/" + dirEntries[i];

        if (kfsClient->IsDirectory(src.c_str()))
	{
	    res = CopyDir(kfsClient, src, dst);
        }
	else
	{
	    res = CopyFile2(kfsClient, src, dst);
        }
    }

    return res;
}

static void
getTimeString(time_t time, char *buf, int bufLen)
{
    struct tm locTime;

    localtime_r(&time, &locTime);
    strftime(buf, bufLen, "%b %e %H:%M", &locTime);
}

static void
printFileInfo(const string &filename, time_t mtime, off_t filesize, bool humanReadable, bool timeInSecs)
{
    char timeBuf[256];

    if (timeInSecs) {
        ostringstream ost;

        ost << mtime;
        strncpy(timeBuf, ost.str().c_str(), 256);
    }
    else
    {
        getTimeString(mtime, timeBuf, 255);
    }

    timeBuf[255] = '\0';

    if (!humanReadable) {
        cout << filename << '\t' << timeBuf << '\t' << filesize << endl;
        return;
    }
    if (filesize < (1 << 20)) {
        cout << filename << '\t' << timeBuf << '\t' << (float) (filesize) / (1 << 10) << " K";
    }
    else if (filesize < (1 << 30)) {
        cout << filename << '\t' << timeBuf << '\t' << (float) (filesize) / (1 << 20) << " M";
    }
    else {
        cout << filename << '\t' << timeBuf << '\t' << (float) (filesize) / (1 << 30) << " G";
    }
    cout << endl;
}

static int
doDirList(KfsClientPtr kfsClient, string kfsdirname)
{
    string kfssubdir, subdir;
    int res;
    vector<string> entries;
    vector<string>::size_type i;

    if (kfsClient->IsFile(kfsdirname.c_str())) {
        cout << kfsdirname << endl;
        return 0;
    }

    if ((res = kfsClient->Readdir(kfsdirname.c_str(), entries)) < 0) {
        cout << "Readdir failed: " << ErrorCodeToStr(res) << endl;
        return res;
    }

    // we could provide info of whether the thing is a dir...but, later
    for (i = 0; i < entries.size(); ++i) {
        if ((entries[i] == ".") || (entries[i] == ".."))
            continue;
        cout << entries[i] << endl;
    }
    return 0;
}

static int
doDirListPlusAttr(KfsClientPtr kfsClient, string kfsdirname, bool humanReadable, bool timeInSecs)
{
    string kfssubdir, subdir;
    int res;
    vector<KfsFileAttr> fileInfo;
    vector<KfsFileAttr>::size_type i;

    if (kfsClient->IsFile(kfsdirname.c_str())) {
        struct stat statInfo;

        kfsClient->Stat(kfsdirname.c_str(), statInfo);
        printFileInfo(kfsdirname, statInfo.st_mtime, statInfo.st_size, humanReadable, timeInSecs);
        return 0;
    }
    if ((res = kfsClient->ReaddirPlus(kfsdirname.c_str(), fileInfo)) < 0) {
        cout << "doDirListPlusAttr::Readdir plus failed: " << ErrorCodeToStr(res) << endl;
        return res;
    }

    for (i = 0; i < fileInfo.size(); ++i) {
        if (fileInfo[i].isDirectory) {
            if ((fileInfo[i].filename == ".") ||
                (fileInfo[i].filename == ".."))
                continue;
            char timeBuf[256];

            getTimeString(fileInfo[i].mtime.tv_sec, timeBuf, 255);
	    timeBuf[255] = 0;

            cout << fileInfo[i].filename << "/" << '\t' << timeBuf << '\t' << "(dir)" << endl;
        } else {
            printFileInfo(fileInfo[i].filename, fileInfo[i].mtime.tv_sec,
                          fileInfo[i].fileSize, humanReadable, timeInSecs);
        }
    }
    return 0;
}

int
KFS::tools::DirList(KfsClientPtr kfsClient, string kfsdirname, bool longMode, bool humanReadable, bool timeInSecs)
{
    if (longMode)
        return doDirListPlusAttr(kfsClient, kfsdirname, humanReadable, timeInSecs);
    else
        return doDirList(kfsClient, kfsdirname);
}

ext: cc

max_stars_repo_name: saugeorg/kosmosfs

max_issues_repo_name: saugeorg/kosmosfs

max_forks_repo_name: saugeorg/kosmosfs


text:
//------------------------------------------------------------------------------
/*
    This file is part of Beast: https://github.com/vinniefalco/Beast
    Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>

    Permission to use, copy, modify, and/or distribute this software for any
    purpose  with  or without fee is hereby granted, provided that the above
    copyright notice and this permission notice appear in all copies.

    THE  SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF
    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

#ifndef BEAST_WEBSOCKET_TEARDOWN_HPP
#define BEAST_WEBSOCKET_TEARDOWN_HPP

#include <beast/websocket/error.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <type_traits>

namespace beast {
namespace websocket {

/** Tear down a connection.

    This tears down a connection. The implementation will call
    the overload of this function based on the `Stream` parameter
    used to consruct the socket. When `Stream` is a user defined
    type, and not a `boost::asio::ip::tcp::socket` or any
    `boost::asio::ssl::stream`, callers are responsible for
    providing a suitable overload of this function.

    @param socket The socket to tear down.

    @param ec Set to the error if any occurred.
*/
template<class Socket>
void
teardown(Socket& socket, error_code& ec) = delete;

/** Start tearing down a connection.

    This begins tearing down a connection asynchronously.
    The implementation will call the overload of this function
    based on the `Stream` parameter used to consruct the socket.
    When `Stream` is a user defined type, and not a
    `boost::asio::ip::tcp::socket` or any `boost::asio::ssl::stream`,
    callers are responsible for providing a suitable overload
    of this function.

    @param socket The socket to tear down.

    @param handler The handler to be called when the request completes.
    Copies will be made of the handler as required. The equivalent
    function signature of the handler must be:
    @code void handler(
        error_code const& error // result of operation
    ); @endcode
    Regardless of whether the asynchronous operation completes
    immediately or not, the handler will not be invoked from within
    this function. Invocation of the handler will be performed in a
    manner equivalent to using boost::asio::io_service::post().

*/
template<class AsyncSocket, class TeardownHandler>
void
async_teardown(AsyncSocket& socket, TeardownHandler&& handler) = delete;

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

/** Tear down a `boost::asio::ip::tcp::socket`.

    This tears down a connection. The implementation will call
    the overload of this function based on the `Stream` parameter
    used to consruct the socket. When `Stream` is a user defined
    type, and not a `boost::asio::ip::tcp::socket` or any
    `boost::asio::ssl::stream`, callers are responsible for
    providing a suitable overload of this function.

    @param socket The socket to tear down.

    @param ec Set to the error if any occurred.
*/
void
teardown(
    boost::asio::ip::tcp::socket& socket,
        error_code& ec);

/** Start tearing down a `boost::asio::ip::tcp::socket`.

    This begins tearing down a connection asynchronously.
    The implementation will call the overload of this function
    based on the `Stream` parameter used to consruct the socket.
    When `Stream` is a user defined type, and not a
    `boost::asio::ip::tcp::socket` or any `boost::asio::ssl::stream`,
    callers are responsible for providing a suitable overload
    of this function.

    @param socket The socket to tear down.

    @param handler The handler to be called when the request completes.
    Copies will be made of the handler as required. The equivalent
    function signature of the handler must be:
    @code void handler(
        error_code const& error // result of operation
    ); @endcode
    Regardless of whether the asynchronous operation completes
    immediately or not, the handler will not be invoked from within
    this function. Invocation of the handler will be performed in a
    manner equivalent to using boost::asio::io_service::post().

*/
template<class TeardownHandler>
void
async_teardown(
    boost::asio::ip::tcp::socket& socket,
        TeardownHandler&& handler);

} // websocket

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

namespace wsproto_helpers {

// Calls to teardown and async_teardown must be made from
// a namespace that does not contain any overloads of these
// functions. The wsproto_helpers namespace is defined here
// for that purpose.

template<class Socket>
inline
void
call_teardown(Socket& socket, websocket::error_code& ec)
{
    using websocket::teardown;
    teardown(socket, ec);
}

template<class Socket, class TeardownHandler>
inline
void
call_async_teardown(Socket& socket, TeardownHandler&& handler)
{
    using websocket::async_teardown;
    async_teardown(socket,
        std::forward<TeardownHandler>(handler));
}

} // websocket_helpers

} // beast

#include <beast/websocket/impl/teardown.ipp>

#endif


text:
/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2012, Willow Garage, Inc.
 *  Copyright (c) 2014-, Open Perception, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the copyright holder(s) nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <gtest/gtest.h>

#include <boost/thread.hpp>

#include <pcl/sample_consensus/msac.h>
#include <pcl/sample_consensus/lmeds.h>
#include <pcl/sample_consensus/rmsac.h>
#include <pcl/sample_consensus/mlesac.h>
#include <pcl/sample_consensus/ransac.h>
#include <pcl/sample_consensus/rransac.h>
#include <pcl/sample_consensus/sac_model_sphere.h>

using namespace pcl;

typedef SampleConsensusModelSphere<PointXYZ>::Ptr SampleConsensusModelSpherePtr;

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST (SampleConsensus, Base)
{
  PointCloud<PointXYZ>::Ptr cloud (new PointCloud<PointXYZ>);

  // Create a shared sphere model pointer directly
  SampleConsensusModelSpherePtr model (new SampleConsensusModelSphere<PointXYZ> (cloud));

  // Create the RANSAC object
  RandomSampleConsensus<PointXYZ> sac (model, 0.03);

  // Basic tests
  ASSERT_EQ (0.03, sac.getDistanceThreshold ());
  sac.setDistanceThreshold (0.03);
  ASSERT_EQ (0.03, sac.getDistanceThreshold ());

  sac.setProbability (0.99);
  ASSERT_EQ (0.99, sac.getProbability ());

  sac.setMaxIterations (10000);
  ASSERT_EQ (10000, sac.getMaxIterations ());
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Test if RANSAC finishes within a second.
TEST (SampleConsensus, InfiniteLoop)
{
  const unsigned point_count = 100;
  PointCloud<PointXYZ> cloud;
  cloud.points.resize (point_count);
  for (unsigned idx = 0; idx < point_count; ++idx)
  {
    cloud.points[idx].x = static_cast<float> (idx);
    cloud.points[idx].y = 0.0;
    cloud.points[idx].z = 0.0;
  }

  boost::posix_time::time_duration delay (0, 0, 1, 0);
  boost::function<bool ()> sac_function;
  SampleConsensusModelSpherePtr model (new SampleConsensusModelSphere<PointXYZ> (cloud.makeShared ()));

  // Create the RANSAC object
  RandomSampleConsensus<PointXYZ> ransac (model, 0.03);
  sac_function = boost::bind (&RandomSampleConsensus<PointXYZ>::computeModel, &ransac, 0);
  boost::thread thread1 (sac_function);
  ASSERT_TRUE (thread1.timed_join (delay));

  // Create the LMSAC object
  LeastMedianSquares<PointXYZ> lmsac (model, 0.03);
  sac_function = boost::bind (&LeastMedianSquares<PointXYZ>::computeModel, &lmsac, 0);
  boost::thread thread2 (sac_function);
  ASSERT_TRUE (thread2.timed_join (delay));

  // Create the MSAC object
  MEstimatorSampleConsensus<PointXYZ> mesac (model, 0.03);
  sac_function = boost::bind (&MEstimatorSampleConsensus<PointXYZ>::computeModel, &mesac, 0);
  boost::thread thread3 (sac_function);
  ASSERT_TRUE (thread3.timed_join (delay));

  // Create the RRSAC object
  RandomizedRandomSampleConsensus<PointXYZ> rrsac (model, 0.03);
  sac_function = boost::bind (&RandomizedRandomSampleConsensus<PointXYZ>::computeModel, &rrsac, 0);
  boost::thread thread4 (sac_function);
  ASSERT_TRUE (thread4.timed_join (delay));

  // Create the RMSAC object
  RandomizedMEstimatorSampleConsensus<PointXYZ> rmsac (model, 0.03);
  sac_function = boost::bind (&RandomizedMEstimatorSampleConsensus<PointXYZ>::computeModel, &rmsac, 0);
  boost::thread thread5 (sac_function);
  ASSERT_TRUE (thread5.timed_join (delay));

  // Create the MLESAC object
  MaximumLikelihoodSampleConsensus<PointXYZ> mlesac (model, 0.03);
  sac_function = boost::bind (&MaximumLikelihoodSampleConsensus<PointXYZ>::computeModel, &mlesac, 0);
  boost::thread thread6 (sac_function);
  ASSERT_TRUE (thread6.timed_join (delay));
}

int
main (int argc, char** argv)
{
  testing::InitGoogleTest (&argc, argv);
  return (RUN_ALL_TESTS ());
}


text:
// -----------------------------------------------------------------------
// RTToolbox - DKFZ radiotherapy quantitative evaluation library
//
// Copyright (c) German Cancer Research Center (DKFZ),
// Software development for Integrated Diagnostics and Therapy (SIDT).
// ALL RIGHTS RESERVED.
// See rttbCopyright.txt or
// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE.  See the above copyright notices for more information.
//
//------------------------------------------------------------------------

#include <iostream>
#include "litCheckMacros.h"
#include <boost/filesystem.hpp>

/*! @brief VoxelizerToolTest4.
Test incorrect commands with a wrong structfile, referencefile and a wrong struct.
if the command return one, the program could not run to the end.
return zero the command is correct
*/
namespace rttb
{
	namespace testing
	{
		//path to the current running directory. VoxelizerTool is in the same directory (Debug/Release)
		extern const char* _callingAppPath;
		int VoxelizerToolIncorrectCommandsTest(int argc, char* argv[])
		{
			PREPARE_DEFAULT_TEST_REPORTING;

			std::string voxelizerToolExe;
			std::string structFile;
			std::string invalidStructFile;
			std::string invalidReferenceFile;
			std::string referenceFile;
			std::string structureName;
			std::string invalidStructureName;

			if (argc > 7)
			{
				voxelizerToolExe = argv[1];
				structFile = argv[2];
				invalidStructFile = argv[3];
				referenceFile = argv[4];
				invalidReferenceFile = argv[5];
				structureName = argv[6];
				invalidStructureName = argv[7];
			}

			boost::filesystem::path callingPath(_callingAppPath);
			std::string voxelizerToolExeWithPath = callingPath.parent_path().string() + "/" + voxelizerToolExe;

			std::string tooFewArgumentsCommand = voxelizerToolExeWithPath;
			tooFewArgumentsCommand += " -s " + invalidStructFile;
			tooFewArgumentsCommand += " -r " + referenceFile;
			std::cout << "Command line call: " + tooFewArgumentsCommand << std::endl;
			CHECK_EQUAL(system(tooFewArgumentsCommand.c_str()) != 0, true);

			tooFewArgumentsCommand = voxelizerToolExeWithPath;
			tooFewArgumentsCommand += " -s " + invalidStructFile;
			tooFewArgumentsCommand += " -e " + structureName;
			std::cout << "Command line call: " + tooFewArgumentsCommand << std::endl;
			CHECK_EQUAL(system(tooFewArgumentsCommand.c_str()) != 0, true);

			tooFewArgumentsCommand = voxelizerToolExeWithPath;
			std::cout << "Command line call: " + tooFewArgumentsCommand << std::endl;
			CHECK_EQUAL(system(tooFewArgumentsCommand.c_str()) != 0, true);

			std::string noOutputEndingCommand = voxelizerToolExeWithPath;
			noOutputEndingCommand += " -s " + invalidStructFile;
			noOutputEndingCommand += " -r " + referenceFile;
			noOutputEndingCommand += " -e " + structureName;
			noOutputEndingCommand += " -o bla";
			std::cout << "Command line call: " + noOutputEndingCommand << std::endl;
			CHECK_EQUAL(system(noOutputEndingCommand.c_str()) != 0, true);

			std::string structCommand = voxelizerToolExeWithPath;
			structCommand += " -s " + invalidStructFile;
			structCommand += " -r " + referenceFile;
			structCommand += " -e " + structureName;
			std::cout << "Command line call: " + structCommand << std::endl;
			CHECK_EQUAL(system(structCommand.c_str()) != 0, true);

			std::string referenceCommand = voxelizerToolExeWithPath;
			referenceCommand += " -s " + structFile;
			referenceCommand += " -r " + invalidReferenceFile;
			referenceCommand += " -e " + structureName;
			std::cout << "Command line call: " + referenceCommand << std::endl;
			CHECK_EQUAL(system(referenceCommand.c_str()) != 0, true);

			std::string structureNameCommand = voxelizerToolExeWithPath;
			structureNameCommand += " -s " + structFile;
			structureNameCommand += " -r " + referenceFile;
			structureNameCommand += +" -e " + invalidStructureName;
			std::cout << "Command line call: " + structureNameCommand << std::endl;
			CHECK_EQUAL(system(structureNameCommand.c_str()), 0);

			std::string referenceLoadingStyleCommand = voxelizerToolExeWithPath;
			referenceLoadingStyleCommand += " -s " + structFile;
			referenceLoadingStyleCommand += " -r " + referenceFile;
			referenceLoadingStyleCommand += +" -e " + invalidStructureName;
			referenceLoadingStyleCommand += +" -y nonsense";
			std::cout << "Command line call: " + referenceLoadingStyleCommand << std::endl;
			CHECK_EQUAL(system(referenceLoadingStyleCommand.c_str()) != 0, true);

			RETURN_AND_REPORT_TEST_SUCCESS;
		}

	}
}

max_stars_repo_name: MIC-DKFZ/RTTB

max_issues_repo_name: MIC-DKFZ/RTTB

max_forks_repo_name: MIC-DKFZ/RTTB


text:
/*
 * Copyright 2012 Karsten Ahnert
 * Copyright 2012 Mario Mulansky
 *
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or
 * copy at http://www.boost.org/LICENSE_1_0.txt)
 */

#include <iostream>
#include <fstream>
#include <utility>
#include "time.h"

#include <boost/numeric/odeint.hpp>
#include <boost/phoenix/phoenix.hpp>
#include <boost/numeric/mtl/mtl.hpp>

#include <boost/numeric/odeint/external/mtl4/implicit_euler_mtl4.hpp>

using namespace std;
using namespace boost::numeric::odeint;

namespace phoenix = boost::phoenix;

typedef mtl::dense_vector< double > vec_mtl4;
typedef mtl::compressed2D< double > mat_mtl4;

typedef boost::numeric::ublas::vector< double > vec_ublas;
typedef boost::numeric::ublas::matrix< double > mat_ublas;

// two systems defined 1 & 2 both are mostly sparse with the number of element variable
struct system1_mtl4
{

    void operator()( const vec_mtl4 &x , vec_mtl4 &dxdt , double t )
    {
        int size = mtl::size(x);

        dxdt[ 0 ] = -0.06*x[0];

        for (int i =1; i< size ; ++i){

            dxdt[ i ] = 4.2*x[i-1]-2.2*x[i]*x[i];
        }

    }
};

struct jacobi1_mtl4
{
    void operator()( const vec_mtl4 &x , mat_mtl4 &J , const double &t )
    {
        int size = mtl::size(x);
        mtl::matrix::inserter<mat_mtl4> ins(J);

        ins[0][0]=-0.06;

        for (int i =1; i< size ; ++i)
        {
            ins[i][i-1] = + 4.2;
            ins[i][i] = -4.2*x[i];
        }
    }
};

struct system1_ublas
{

    void operator()( const vec_ublas &x , vec_ublas &dxdt , double t )
    {
        int size = x.size();

        dxdt[ 0 ] = -0.06*x[0];

        for (int i =1; i< size ; ++i){

            dxdt[ i ] = 4.2*x[i-1]-2.2*x[i]*x[i];
        }

    }
};

struct jacobi1_ublas
{
    void operator()( const vec_ublas &x , mat_ublas &J , const double &t )
    {
        int size = x.size();
// mtl::matrix::inserter<mat_mtl4> ins(J);

        J(0,0)=-0.06;

        for (int i =1; i< size ; ++i){
//ins[i][0]=120.0*x[i];
            J(i,i-1) = + 4.2;
            J(i,i) = -4.2*x[i];

        }
    }
};

struct system2_mtl4
{

    void operator()( const vec_mtl4 &x , vec_mtl4 &dxdt , double t )
    {
        int size = mtl::size(x);

        for (int i =0; i< size/5 ; i+=5){

            dxdt[ i ] = -0.5*x[i];
            dxdt[i+1]= +25*x[i+1]*x[i+2]-740*x[i+3]*x[i+3]+4.2e-2*x[i];
            dxdt[i+2]= +25*x[i]*x[i]-740*x[i+3]*x[i+3];
            dxdt[i+3]= -25*x[i+1]*x[i+2]+740*x[i+3]*x[i+3];
            dxdt[i+4] = 0.250*x[i]*x[i+1]-44.5*x[i+3];

        }

    }
};

struct jacobi2_mtl4
{
    void operator()( const vec_mtl4 &x , mat_mtl4 &J , const double &t )
    {
        int size = mtl::size(x);
        mtl::matrix::inserter<mat_mtl4> ins(J);

        for (int i =0; i< size/5 ; i+=5){

            ins[ i ][i] = -0.5;
            ins[i+1][i+1]=25*x[i+2];
            ins[i+1][i+2] = 25*x[i+1];
            ins[i+1][i+3] = -740*2*x[i+3];
            ins[i+1][i] =+4.2e-2;

            ins[i+2][i]= 50*x[i];
            ins[i+2][i+3]= -740*2*x[i+3];
            ins[i+3][i+1] = -25*x[i+2];
            ins[i+3][i+2] = -25*x[i+1];
            ins[i+3][i+3] = +740*2*x[i+3];
            ins[i+4][i] = 0.25*x[i+1];
            ins[i+4][i+1] =0.25*x[i];
            ins[i+4][i+3]=-44.5;

        }
    }
};

struct system2_ublas
{

    void operator()( const vec_ublas &x , vec_ublas &dxdt , double t )
    {
        int size = x.size();
        for (int i =0; i< size/5 ; i+=5){

            dxdt[ i ] = -4.2e-2*x[i];
            dxdt[i+1]= +25*x[i+1]*x[i+2]-740*x[i+3]*x[i+3]+4.2e-2*x[i];
            dxdt[i+2]= +25*x[i]*x[i]-740*x[i+3]*x[i+3];
            dxdt[i+3]= -25*x[i+1]*x[i+2]+740*x[i+3]*x[i+3];
            dxdt[i+4] = 0.250*x[i]*x[i+1]-44.5*x[i+3];

        }

    }
};

struct jacobi2_ublas
{
    void operator()( const vec_ublas &x , mat_ublas &J , const double &t )
    {
        int size = x.size();

        for (int i =0; i< size/5 ; i+=5){

            J(i ,i) = -4.2e-2;
            J(i+1,i+1)=25*x[i+2];
            J(i+1,i+2) = 25*x[i+1];
            J(i+1,i+3) = -740*2*x[i+3];
            J(i+1,i) =+4.2e-2;

            J(i+2,i)= 50*x[i];
            J(i+2,i+3)= -740*2*x[i+3];
            J(i+3,i+1) = -25*x[i+2];
            J(i+3,i+2) = -25*x[i+1];
            J(i+3,i+3) = +740*2*x[i+3];
            J(i+4,i) = 0.25*x[i+1];
            J(i+4,i+1) =0.25*x[i];
            J(i+4,i+3)=-44.5;

        }

    }
};

void testRidiculouslyMassiveArray( int size )
{
    typedef boost::numeric::odeint::implicit_euler_mtl4 < double > mtl4stepper;
    typedef boost::numeric::odeint::implicit_euler< double > booststepper;

    vec_mtl4 x(size , 0.0);
    x[0]=1;

    double dt = 0.02;
    double endtime = 10.0;

    clock_t tstart_mtl4 = clock();
    size_t num_of_steps_mtl4 = integrate_const(
        mtl4stepper() ,
        make_pair( system1_mtl4() , jacobi1_mtl4() ) ,
        x , 0.0 , endtime , dt  );
    clock_t tend_mtl4 = clock() ;

    clog << x[0] << endl;
    clog << num_of_steps_mtl4 << " time elapsed: " << (double)(tend_mtl4-tstart_mtl4 )/CLOCKS_PER_SEC << endl;

    vec_ublas x_ublas(size , 0.0);
    x_ublas[0]=1;

    clock_t tstart_boost = clock();
    size_t num_of_steps_ublas = integrate_const(
        booststepper() ,
        make_pair( system1_ublas() , jacobi1_ublas() ) ,
        x_ublas , 0.0 , endtime , dt  );
    clock_t tend_boost = clock() ;

    clog << x_ublas[0] << endl;
    clog << num_of_steps_ublas << " time elapsed: " << (double)(tend_boost-tstart_boost)/CLOCKS_PER_SEC<< endl;

    clog << "dt_ublas/dt_mtl4 = " << (double)( tend_boost-tstart_boost )/( tend_mtl4-tstart_mtl4 ) << endl << endl;
    return ;
}

void testRidiculouslyMassiveArray2( int size )
{
    typedef boost::numeric::odeint::implicit_euler_mtl4 < double > mtl4stepper;
    typedef boost::numeric::odeint::implicit_euler< double > booststepper;

    vec_mtl4 x(size , 0.0);
    x[0]=100;

    double dt = 0.01;
    double endtime = 10.0;

    clock_t tstart_mtl4 = clock();
    size_t num_of_steps_mtl4 = integrate_const(
        mtl4stepper() ,
        make_pair( system1_mtl4() , jacobi1_mtl4() ) ,
        x , 0.0 , endtime , dt );

    clock_t tend_mtl4 = clock() ;

    clog << x[0] << endl;
    clog << num_of_steps_mtl4 << " time elapsed: " << (double)(tend_mtl4-tstart_mtl4 )/CLOCKS_PER_SEC << endl;

    vec_ublas x_ublas(size , 0.0);
    x_ublas[0]=100;

    clock_t tstart_boost = clock();
    size_t num_of_steps_ublas = integrate_const(
        booststepper() ,
        make_pair( system1_ublas() , jacobi1_ublas() ) ,
        x_ublas , 0.0 , endtime , dt  );

    clock_t tend_boost = clock() ;

    clog << x_ublas[0] << endl;
    clog << num_of_steps_ublas << " time elapsed: " << (double)(tend_boost-tstart_boost)/CLOCKS_PER_SEC<< endl;

    clog << "dt_ublas/dt_mtl4 = " << (double)( tend_boost-tstart_boost )/( tend_mtl4-tstart_mtl4 ) << endl << endl;
    return ;
}

int main( int argc , char **argv )
{
    std::vector< size_t > length;
    length.push_back( 8 );
    length.push_back( 16 );
    length.push_back( 32 );
    length.push_back( 64 );
    length.push_back( 128 );
    length.push_back( 256 );

    for( size_t i=0 ; i<length.size() ; ++i )
    {
        clog << "Testing with size " << length[i] << endl;
        testRidiculouslyMassiveArray( length[i] );
    }
    clog << endl << endl;

    for( size_t i=0 ; i<length.size() ; ++i )
    {
        clog << "Testing with size " << length[i] << endl;
        testRidiculouslyMassiveArray2( length[i] );
    }
}


text:
/*! \file */
#include "tile_worker.h"
#include <fstream>
#include <boost/filesystem.hpp>
#include <signal.h>
#include "helpers.h"
#include "write_geometry.h"
using namespace std;
extern bool verbose;

typedef std::pair<double,double> xy_pair;
namespace std {
	template<>
	struct hash<xy_pair> {
		size_t operator()(const xy_pair &xy) const {
			return std::hash<double>()(xy.first) ^ std::hash<double>()(xy.second);
		}
	};
}

// Connect disconnected linestrings within a MultiLinestring
void ReorderMultiLinestring(MultiLinestring &input, MultiLinestring &output) {
	// create a map of the start/end points of each linestring
	// (we should be able to do std::map<Point,unsigned>, but that errors)
	std::unordered_map<xy_pair,unsigned> startPoints;
	std::unordered_map<xy_pair,unsigned> endPoints;
	for (unsigned i=0; i<input.size(); i++) {
		startPoints[xy_pair(input[i][0].x(),input[i][0].y())] = i;
		endPoints[xy_pair(input[i][input[i].size()-1].x(),input[i][input[i].size()-1].y())] = i;
	}

	// then for each linestring:
	// [skip if it's already been handled]
	// 1. create an output linestring from it
	// 2. look to see if there's another linestring which starts at our end point, or terminates at our start point
	// 3. if there is, then append it, remove from the map, and repeat from 2
	std::vector<bool> added(input.size(), false);
	for (unsigned i=0; i<input.size(); i++) {
		if (added[i]) continue;
		Linestring ls = std::move(input[i]);
		added[i] = true;
		while (true) {
			Point lastPoint = ls[ls.size()-1];
			auto foundStart = startPoints.find(xy_pair(lastPoint.x(),lastPoint.y()));
			if (foundStart != startPoints.end()) {
				unsigned idx = foundStart->second;
				if (!added[idx] && input[idx].size()+ls.size()<6000) {
					ls.insert(ls.end(), input[idx].begin()+1, input[idx].end());
					added[idx] = true;
					continue;
				}
			}

			Point firstPoint = ls[0];
			auto foundEnd = endPoints.find(xy_pair(firstPoint.x(),firstPoint.y()));
			if (foundEnd != endPoints.end()) {
				unsigned idx = foundEnd->second;
				if (!added[idx] && input[idx].size()+ls.size()<6000) {
					ls.insert(ls.begin(), input[idx].begin(), input[idx].end()-1);
					added[idx] = true;
					continue;
				}
			}

			break;
		}
		output.resize(output.size()+1);
		output[output.size()-1] = std::move(ls);
	}
}

// Merge two multilinestrings by simply appending
// (the constituent parts will be matched up in subsequent call to ReorderMultiLinestring)
void MergeIntersecting(MultiLinestring &input, MultiLinestring &to_merge) {
	for (auto ls : to_merge) input.emplace_back(ls);
}

// Merge two multipolygons by doing intersection checks for each constituent polygon
void MergeIntersecting(MultiPolygon &input, MultiPolygon &to_merge) {
	if (boost::geometry::intersects(input, to_merge)) {
		for (std::size_t i=0; i<input.size(); i++) {
			if (boost::geometry::intersects(input[i], to_merge)) {
				MultiPolygon union_result;
				boost::geometry::union_(input[i], to_merge, union_result);
				for (auto output : union_result) input.emplace_back(output);
				input.erase(input.begin() + i);
				return;
			}
		}
	}
	for (auto output : to_merge) input.emplace_back(output);
}

template <typename T>
void CheckNextObjectAndMerge(OSMStore &osmStore, OutputObjectsConstIt &jt, OutputObjectsConstIt ooSameLayerEnd,
	const TileBbox &bbox, T &g) {

	// If a object is a linestring/polygon that is followed by
	// other linestrings/polygons with the same attributes,
	// the following objects are merged into the first object, by taking union of geometries.
	OutputObjectRef oo = *jt;
	OutputObjectRef ooNext;
	if(jt+1 != ooSameLayerEnd) ooNext = *(jt+1);

	OutputGeometryType gt = oo->geomType;
	while (jt+1 != ooSameLayerEnd &&
			ooNext->geomType == gt &&
			ooNext->z_order == oo->z_order &&
			ooNext->attributes == oo->attributes) {
		jt++;
		oo = *jt;
		if(jt+1 != ooSameLayerEnd) ooNext = *(jt+1);
		else ooNext.reset();

		try {
			T to_merge = boost::get<T>(buildWayGeometry(osmStore, *oo, bbox));
			MergeIntersecting(g, to_merge);
		} catch (std::out_of_range &err) { cerr << "Geometry out of range " << gt << ": " << static_cast<int>(oo->objectID) <<"," << err.what() << endl;
		} catch (boost::bad_get &err) { cerr << "Type error while processing " << gt << ": " << static_cast<int>(oo->objectID) << endl;
		} catch (geom::inconsistent_turns_exception &err) { cerr << "Inconsistent turns error while processing " << gt << ": " << static_cast<int>(oo->objectID) << endl;
		}
	}
}

void ProcessObjects(OSMStore &osmStore, OutputObjectsConstIt ooSameLayerBegin, OutputObjectsConstIt ooSameLayerEnd,
	class SharedData &sharedData, double simplifyLevel, double filterArea, bool combinePolygons, unsigned zoom, const TileBbox &bbox,
	vector_tile::Tile_Layer *vtLayer, vector<string> &keyList, vector<vector_tile::Tile_Value> &valueList) {

	for (auto jt = ooSameLayerBegin; jt != ooSameLayerEnd; ++jt) {
		OutputObjectRef oo = *jt;
		if (zoom < oo->minZoom) { continue; }

		if (oo->geomType == POINT_) {
			vector_tile::Tile_Feature *featurePtr = vtLayer->add_features();
			LatpLon pos = buildNodeGeometry(osmStore, *oo, bbox);
			featurePtr->add_geometry(9);					// moveTo, repeat x1
			pair<int,int> xy = bbox.scaleLatpLon(pos.latp/10000000.0, pos.lon/10000000.0);
			featurePtr->add_geometry((xy.first  << 1) ^ (xy.first  >> 31));
			featurePtr->add_geometry((xy.second << 1) ^ (xy.second >> 31));
			featurePtr->set_type(vector_tile::Tile_GeomType_POINT);

			oo->writeAttributes(&keyList, &valueList, featurePtr, zoom);
			if (sharedData.config.includeID) { featurePtr->set_id(oo->objectID); }
		} else {
			Geometry g;
			try {
				g = buildWayGeometry(osmStore, *oo, bbox);
			} catch (std::out_of_range &err) {
				if (verbose) cerr << "Error while processing geometry " << oo->geomType << "," << static_cast<int>(oo->objectID) <<"," << err.what() << endl;
				continue;
			}

			if (oo->geomType == POLYGON_ && filterArea > 0.0) {
				if (geom::area(g)<filterArea) continue;
			}

			//This may increment the jt iterator
			if (oo->geomType == LINESTRING_ && zoom < sharedData.config.combineBelow) {
				CheckNextObjectAndMerge(osmStore, jt, ooSameLayerEnd, bbox, boost::get<MultiLinestring>(g));
				MultiLinestring reordered;
				ReorderMultiLinestring(boost::get<MultiLinestring>(g), reordered);
				g = move(reordered);
				oo = *jt;
			} else if (oo->geomType == POLYGON_ && combinePolygons) {
				CheckNextObjectAndMerge(osmStore, jt, ooSameLayerEnd, bbox, boost::get<MultiPolygon>(g));
				oo = *jt;
			}

			vector_tile::Tile_Feature *featurePtr = vtLayer->add_features();
			WriteGeometryVisitor w(&bbox, featurePtr, simplifyLevel);
			boost::apply_visitor(w, g);
			if (featurePtr->geometry_size()==0) { vtLayer->mutable_features()->RemoveLast(); continue; }
			oo->writeAttributes(&keyList, &valueList, featurePtr, zoom);
			if (sharedData.config.includeID) { featurePtr->set_id(oo->objectID); }

		}
	}
}

vector_tile::Tile_Layer* findLayerByName(vector_tile::Tile &tile, std::string &layerName, vector<string> &keyList, vector<vector_tile::Tile_Value> &valueList) {
	for (unsigned i=0; i<tile.layers_size(); i++) {
		if (tile.layers(i).name()!=layerName) continue;
		// we already have this layer, so copy the key/value lists, and return it
		for (unsigned j=0; j<tile.layers(i).keys_size(); j++) keyList.emplace_back(tile.layers(i).keys(j));
		for (unsigned j=0; j<tile.layers(i).values_size(); j++) valueList.emplace_back(tile.layers(i).values(j));
		return tile.mutable_layers(i);
	}
	// not found, so add new layer
	return tile.add_layers();
}

void ProcessLayer(OSMStore &osmStore,
    TileCoordinates index, uint zoom, std::vector<OutputObjectRef> const &data, vector_tile::Tile &tile,
	const TileBbox &bbox, const std::vector<uint> &ltx, SharedData &sharedData)
{
	vector<string> keyList;
	vector<vector_tile::Tile_Value> valueList;
	std::string layerName = sharedData.layers.layers[ltx.at(0)].name;
	vector_tile::Tile_Layer *vtLayer = sharedData.mergeSqlite ? findLayerByName(tile, layerName, keyList, valueList) : tile.add_layers();

	//TileCoordinate tileX = index.x;
	TileCoordinate tileY = index.y;

	// Loop through sub-layers
	std::time_t start = std::time(0);
	for (auto mt = ltx.begin(); mt != ltx.end(); ++mt) {
		uint layerNum = *mt;
		const LayerDef &ld = sharedData.layers.layers[layerNum];
		if (zoom<ld.minzoom || zoom>ld.maxzoom) { continue; }
		double simplifyLevel = 0.0, filterArea = 0.0, latp = 0.0;
		if (zoom < ld.simplifyBelow || zoom < ld.filterBelow) {
			latp = (tiley2latp(tileY, zoom) + tiley2latp(tileY+1, zoom)) / 2;
		}
		if (zoom < ld.simplifyBelow) {
			if (ld.simplifyLength > 0) {
				simplifyLevel = meter2degp(ld.simplifyLength, latp);
			} else {
				simplifyLevel = ld.simplifyLevel;
			}
			simplifyLevel *= pow(ld.simplifyRatio, (ld.simplifyBelow-1) - zoom);
		}
		if (zoom < ld.filterBelow) {
			filterArea = meter2degp(ld.filterArea, latp) * pow(2.0, (ld.filterBelow-1) - zoom);
		}

		auto ooListSameLayer = GetObjectsAtSubLayer(data, layerNum);
		// Loop through output objects
		ProcessObjects(osmStore, ooListSameLayer.first, ooListSameLayer.second, sharedData,
			simplifyLevel, filterArea, zoom < ld.combinePolygonsBelow, zoom, bbox, vtLayer, keyList, valueList);
	}
	if (verbose && std::time(0)-start>3) {
		std::cout << "Layer " << layerName << " at " << zoom << "/" << index.x << "/" << index.y << " took " << (std::time(0)-start) << " seconds" << std::endl;
	}

	// If there are any objects, then add tags
	if (vtLayer->features_size()>0) {
		vtLayer->set_name(layerName);
		vtLayer->set_version(sharedData.config.mvtVersion);
		vtLayer->set_extent(bbox.hires ? 8192 : 4096);
		for (uint j=vtLayer->keys_size(); j<keyList.size(); j++) {
			vtLayer->add_keys(keyList[j]);
		}
		for (uint j=vtLayer->values_size(); j<valueList.size(); j++) {
			vector_tile::Tile_Value *v = vtLayer->add_values();
			*v = valueList[j];
		}
	} else {
		tile.mutable_layers()->RemoveLast();
	}
}

bool signalStop=false;
void handleUserSignal(int signum) {
	std::cout << "User requested break in processing" << std::endl;
	signalStop=true;
}

bool outputProc(boost::asio::thread_pool &pool, SharedData &sharedData, OSMStore &osmStore, std::vector<OutputObjectRef> const &data, TileCoordinates coordinates, uint zoom)
{
	// Create tile
	vector_tile::Tile tile;
	TileBbox bbox(coordinates, zoom, sharedData.config.highResolution && zoom==sharedData.config.endZoom);
	if (sharedData.config.clippingBoxFromJSON && (sharedData.config.maxLon<=bbox.minLon
		|| sharedData.config.minLon>=bbox.maxLon || sharedData.config.maxLat<=bbox.minLat
		|| sharedData.config.minLat>=bbox.maxLat)) { return true; }

	// Read existing tile if merging
	if (sharedData.mergeSqlite) {
		std::string rawTile;
		if (sharedData.mbtiles.readTileAndUncompress(rawTile, zoom, bbox.index.x, bbox.index.y, sharedData.config.compress, sharedData.config.gzip)) {
			tile.ParseFromString(rawTile);
		}
	}

	// Loop through layers
#ifndef _WIN32
	signal(SIGUSR1, handleUserSignal);
#endif
	signalStop=false;

	for (auto lt = sharedData.layers.layerOrder.begin(); lt != sharedData.layers.layerOrder.end(); ++lt) {
		if (signalStop) break;
		ProcessLayer(osmStore, coordinates, zoom, data, tile, bbox, *lt, sharedData);
	}

	// Write to file or sqlite
	string outputdata, compressed;
	if (sharedData.sqlite) {
		// Write to sqlite
		tile.SerializeToString(&outputdata);
		if (sharedData.config.compress) { compressed = compress_string(outputdata, Z_DEFAULT_COMPRESSION, sharedData.config.gzip); }
		sharedData.mbtiles.saveTile(zoom, bbox.index.x, bbox.index.y, sharedData.config.compress ? &compressed : &outputdata);

	} else {
		// Write to file
		stringstream dirname, filename;
		dirname  << sharedData.outputFile << "/" << zoom << "/" << bbox.index.x;
		filename << sharedData.outputFile << "/" << zoom << "/" << bbox.index.x << "/" << bbox.index.y << ".pbf";
		boost::filesystem::create_directories(dirname.str());
		fstream outfile(filename.str(), ios::out | ios::trunc | ios::binary);
		if (sharedData.config.compress) {
			tile.SerializeToString(&outputdata);
			outfile << compress_string(outputdata, Z_DEFAULT_COMPRESSION, sharedData.config.gzip);
		} else {
			if (!tile.SerializeToOstream(&outfile)) { cerr << "Couldn't write to " << filename.str() << endl; return false; }
		}
		outfile.close();
	}

	return true;
}

max_stars_repo_name: faizol/tilemaker

max_issues_repo_name: faizol/tilemaker

max_forks_repo_name: faizol/tilemaker