text:
/**
 * Copyright (c) 2016, Adrien Devresse <adrien.devresse@epfl.ch>
 *
 * Boost Software License - Version 1.0
 *
 * 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 <future>
#include <mutex>
#include <thread>

#include <boost/test/floating_point_comparison.hpp>

#include <boost/chrono.hpp>
#include <boost/random.hpp>

#include <hadoken/format/format.hpp>

#include <hadoken/executor/simple_thread_executor.hpp>
#include <hadoken/executor/system_executor.hpp>
#include <hadoken/executor/thread_pool_executor.hpp>

using namespace boost::chrono;

typedef system_clock::time_point tp;
typedef system_clock cl;

template <typename Executor>
std::size_t executor_test(std::size_t n_exec, const std::string& executor_name) {

    tp t1, t2;

    int val = 0;

    std::plus<int> add;

    Executor executor;

    t1 = cl::now();

    for (std::size_t i = 0; i < n_exec; ++i) {

        std::packaged_task<int(int, int)> task(add);
        auto f = task.get_future();

        executor.execute([&]() { task(40, 2); });

        val += f.get();
    }

    t2 = cl::now();

    std::cout << executor_name << ": " << double(boost::chrono::duration_cast<microseconds>(t2 - t1).count()) / n_exec
              << std::endl;

    return val;
}

template <typename Executor>
std::size_t executor_test_twoway(std::size_t n_exec, const std::string& executor_name) {

    tp t1, t2;

    int val = 0;

    std::plus<int> add;

    Executor executor;

    t1 = cl::now();

    for (std::size_t i = 0; i < n_exec; ++i) {

        auto f = executor.twoway_execute(std::function<int()>([&add, i]() { return add(i, i); }));

        val += f.get();
    }

    t2 = cl::now();

    std::cout << executor_name << ": " << double(boost::chrono::duration_cast<microseconds>(t2 - t1).count()) / n_exec
              << std::endl;

    return val;
}

int main() {

    const std::size_t n_exec = 20000;
    std::size_t junk = 0;

    hadoken::format::scat(std::cout, "test executors for ", n_exec, " iterations ");

    junk += executor_test<hadoken::thread_pool_executor>(n_exec, "pool_executor");

    junk += executor_test<hadoken::simple_thread_executor>(n_exec, "simple_executor");

    junk += executor_test<hadoken::system_executor>(n_exec, "system_executor");

    junk += executor_test_twoway<hadoken::thread_pool_executor>(n_exec, "pool_executor_twoway");

    std::cout << "end junk " << junk << std::endl;
}

ext: cpp

max_stars_repo_name: adevress/hadoken

max_issues_repo_name: mrexodia/hadoken

max_forks_repo_name: mrexodia/hadoken


text:
//
// Copyright (c) 2018-2019 Vinnie Falco (vinnie dot falco at gmail 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)
//
// Official repository: https://github.com/vinniefalco/BeastLounge
//

#include "dispatcher.hpp"
#include "listener.hpp"
#include "logger.hpp"
#include "server.hpp"
#include "service.hpp"
#include "system_channel.hpp"
#include "utility.hpp"
#include <boost/beast/_experimental/json/assign_string.hpp>
#include <boost/beast/_experimental/json/assign_vector.hpp>
#include <boost/beast/_experimental/json/parse_file.hpp>
#include <boost/beast/_experimental/json/parser.hpp>
#include <boost/asio/basic_waitable_timer.hpp>
#include <boost/asio/basic_signal_set.hpp>
#include <boost/assert.hpp>
#include <boost/make_unique.hpp>
#include <boost/throw_exception.hpp>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

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

extern
void
make_chat_service(server&);

extern
void
make_ident_service(server&);

extern
std::unique_ptr<dispatcher>
make_dispatcher(server& srv);

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

namespace boost {
namespace beast {
namespace json {

template<>
struct value_exchange<net::ip::address>
{
    static
    void
    assign(
        net::ip::address& t,
        json::value const& jv,
        error_code& ec)
    {
        if(! jv.is_string())
        {
            ec = json::error::expected_string;
            return;
        }
        t = net::ip::make_address(
            jv.as_string().c_str(), ec);
    }
};

} // json
} // beast
} // boost

void
assign(
    logger_config& cfg,
    json::value const& jv,
    beast::error_code& ec)
{
    auto& jo = jv["log"];
    if(! jo.is_object())
    {
        ec = json::error::expected_object;
        return;
    }
    jo["path"].assign(cfg.path, ec);
    if(ec)
        return;
}

void
assign(
    listener_config& cfg,
    json::value const& jv,
    beast::error_code& ec)
{
    if(! jv.is_object())
    {
        ec = json::error::expected_object;
        return;
    }
    jv["name"].assign(cfg.name, ec);
    if(ec)
        return;
    jv["address"].assign(cfg.address, ec);
    if(ec)
        return;
    jv["port_num"].assign(cfg.port_num, ec);
    if(ec)
        return;
}

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

namespace {

struct server_config
{
    unsigned num_threads = 1;
    std::string doc_root;

    void
    assign(
        json::value const& jv,
        beast::error_code& ec)
    {
        if(! jv.is_object())
        {
            ec = json::error::expected_object;
            return;
        }
        jv["threads"].assign(num_threads, ec);
        if(ec)
            return;
        if(num_threads < 1)
            num_threads = 1;
        jv["doc-root"].assign(doc_root, ec);
        if(ec)
            return;
    }
};

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

class server_impl_base : public server
{
public:
    net::io_context ioc_;

    // This function is in a base class because `server_impl`
    // needs to call it from the ctor-initializer list, which
    // would be undefined if the member function was in the
    // derived class.

    executor_type
    make_executor() override
    {
    #ifdef LOUNGE_USE_SYSTEM_EXECUTOR
        return net::make_strand(
            net::system_executor{});
    #else
        return net::make_strand(
            ioc_.get_executor());
    #endif
    }
};

class server_impl
    : public server_impl_base
{
    using clock_type = std::chrono::steady_clock;
    using time_point = clock_type::time_point;

    server_config cfg_;
    std::shared_ptr<logger> log_;
    std::vector<std::unique_ptr<service>> services_;
    net::basic_waitable_timer<
        clock_type,
        boost::asio::wait_traits<clock_type>,
        executor_type> timer_;
    asio::basic_signal_set<executor_type> signals_;
    std::condition_variable cv_;
    std::mutex mutex_;
    time_point shutdown_time_;
    bool running_ = false;
    bool stop_ = false;

    std::unique_ptr<::dispatcher> dispatcher_;
    ::system_channel system_channel_;

    static
    std::chrono::steady_clock::time_point
    never() noexcept
    {
        return (time_point::max)();
    }

public:
    explicit
    server_impl(
        server_config cfg,
        std::shared_ptr<logger> log)
        : cfg_(std::move(cfg))
        , log_(std::move(log))
        , timer_(this->make_executor())
        , signals_(
            timer_.get_executor(),
            SIGINT,
            SIGTERM)
        , dispatcher_(make_dispatcher(*this))
        , shutdown_time_(never())
    {
        timer_.expires_at(never());

        // Register RPC commands
        auto& d = this->dispatcher();
        d.insert("shutdown", &server_impl::rpc_shutdown, this);
        d.insert("stop", &server_impl::rpc_stop, this);
    }

    ~server_impl()
    {
        BOOST_ASSERT(services_.empty());
    }

    void
    insert(std::unique_ptr<service> sp) override
    {
        if(running_)
            throw std::logic_error(
                "server already running");

        services_.emplace_back(std::move(sp));
    }

    void
    run() override
    {
        if(running_)
            throw std::logic_error(
                "server already running");

        running_ = true;

        // Start all agents
        for(auto const& sp : services_)
            sp->on_start();

        // Capture SIGINT and SIGTERM to perform a clean shutdown
        signals_.async_wait(
            bind_front(this, &server_impl::on_signal));

    #ifndef LOUNGE_USE_SYSTEM_EXECUTOR
        std::vector<std::thread> vt;
        while(vt.size() < cfg_.num_threads)
            vt.emplace_back(
                [this]
                {
                    this->ioc_.run();
                });
    #endif
        // Block the main thread until stop() is called
        {
            std::unique_lock<std::mutex> lock(mutex_);
            cv_.wait(lock, [this]{ return stop_; });
        }

        // Notify all agents to stop
        auto agents = std::move(services_);
        for(auto const& sp : agents)
            sp->on_stop();

        // services must be kept alive until after
        // all executor threads are joined.

        // If we get here, then the server has
        // stopped, so join the threads before
        // destroying them.

    #ifdef LOUNGE_USE_SYSTEM_EXECUTOR
        net::system_executor{}.context().join();
    #else
        for(auto& t : vt)
            t.join();
    #endif
    }

    //--------------------------------------------------------------------------
    //
    // shutdown / stop
    //
    //--------------------------------------------------------------------------

    void
    rpc_shutdown(
        user&, rpc_request&)
    {
        shutdown(std::chrono::seconds(60));
    }

    void
    rpc_stop(
        user&, rpc_request&)
    {
        stop();
    }

    bool
    is_shutting_down() override
    {
        return false;
    }

    void
    shutdown(std::chrono::seconds cooldown) override
    {
        // Get on the strand
        if(! timer_.get_executor().running_in_this_thread())
            return net::post(
                timer_.get_executor(),
                beast::bind_front_handler(
                    &server_impl::shutdown,
                    this,
                    cooldown));

        // Only callable once
        if(timer_.expiry() != never())
            return;

        shutdown_time_ = clock_type::now() + cooldown;
        on_timer();
    }

    void
    notify_shutdown()
    {
    }

    void
    on_timer(beast::error_code ec = {})
    {
        if(ec == net::error::operation_aborted)
            return;

        auto const remain =
            ::ceil<std::chrono::seconds>(
                shutdown_time_ - clock_type::now());

        // Countdown finished?
        if(remain.count() <= 0)
        {
            stop();
            return;
        }

        std::chrono::seconds amount(remain.count());
        if(amount.count() > 10)
            amount = std::chrono::seconds(10);

        // Notify users of impending shutdown
        json::value jv;
        jv["verb"] = "say";
        jv["channel"] = system_channel_.cid();
        jv["name"] = system_channel_.name();
        jv["message"] = "Server is shutting down in " +
            std::to_string(remain.count()) + " seconds";

        system_channel_.send(jv);
        timer_.expires_after(amount);
        timer_.async_wait(bind_front(
            this, &server_impl::on_timer));
    }

    void
    on_signal(beast::error_code ec, int signum)
    {
        if(ec == net::error::operation_aborted)
            return;

        log_->cerr() <<
            "server_impl::on_signal: #" <<
            signum << ", " << ec.message() << "\n";
        if(timer_.expiry() == never())
        {
            // Capture signals again
            signals_.async_wait(
                bind_front(this, &server_impl::on_signal));

            this->shutdown(std::chrono::seconds(30));
        }
        else
        {
            // second time hard stop
            stop();
        }
    }

    void
    stop()
    {
        // Get on the strand
        if(! timer_.get_executor().running_in_this_thread())
            return net::post(
                timer_.get_executor(),
                bind_front(this, &server_impl::stop));

        // Only callable once
        if(stop_)
            return;

        // Set stop_ and unblock the main thread
        {
            std::lock_guard<std::mutex> lock(mutex_);
            stop_ = true;
            cv_.notify_all();
        }

        // Cancel our outstanding I/O
        timer_.cancel();
        beast::error_code ec;
        signals_.cancel(ec);
    }

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

    beast::string_view
    doc_root() const override
    {
        return cfg_.doc_root;
    }

    logger&
    log() noexcept override
    {
        return *log_;
    }

    ::dispatcher&
    dispatcher() override
    {
        return *dispatcher_;
    }

    ::system_channel&
    system_channel() override
    {
        return system_channel_;
    }
};

} // (anon)

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

std::unique_ptr<server>
make_server(
    char const* config_path,
    std::unique_ptr<logger> log)
{
    beast::error_code ec;
    // Read the JSON configuration file
    json::value jv;
    {
        json::parser p;
        json::parse_file(config_path, p, ec);
        if(ec)
        {
            log->cerr() <<
                "json::parse_file: " << ec.message() << "\n";
            return nullptr;
        }
        jv = p.release();
    }

    // Read the log configuration
    {
        logger_config cfg;
        jv.assign(cfg, ec);
        if(ec)
        {
            log->cerr() <<
                "logger_config: " << ec.message() << "\n";
            return nullptr;
        }
        if(! log->open(std::move(cfg)))
            return false;
    }

    // Read the server configuration
    std::unique_ptr<server_impl> srv;
    {
        auto& jo = jv["server"];
        if(! jo.is_object())
        {
            ec = json::error::expected_object;
            log->cerr() <<
                "server_config: " << ec.message() << "\n";
            return nullptr;
        }
        server_config cfg;
        jo.assign(cfg, ec);
        if(ec)
        {
            log->cerr() <<
                "server_config: " << ec.message() << "\n";
            return nullptr;
        }

        // Create the server
        srv = boost::make_unique<server_impl>(
            std::move(cfg),
            std::move(log));
    }

    // Add services
    make_chat_service(*srv);
    make_ident_service(*srv);

    // Create listeners
    {
        auto& ja = jv["listeners"];
        if(! ja.is_array())
        {
            ec = json::error::expected_array;
            return nullptr;
        }
        for(auto& e : ja.as_array())
        {
            listener_config cfg;
            e.assign(cfg, ec);
            if(ec)
            {
                srv->log().cerr() <<
                    "listener_config: " << ec.message() << "\n";
                return nullptr;
            }
            if(! run_listener(*srv, std::move(cfg)))
                return nullptr;
        }
    }

    return srv;
}

max_stars_repo_name: djarek/BeastLounge

max_issues_repo_name: djarek/BeastLounge

max_forks_repo_name: djarek/BeastLounge


text:
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <curl/curl.h>
#include <iostream>
#include <picosha2.h>
#include <sstream>

#include "log.hpp"
#include "primerScheme.hpp"

namespace pt = boost::property_tree;

// ARTIC_MANIFEST_URL contains all the metadata for the ARTIC Network primer schemes.
const std::string ARTIC_MANIFEST_URL = "https://raw.githubusercontent.com/artic-network/primer-schemes/master/schemes_manifest.json";
const std::string SCHEME_EXT = ".primer.bed";
const std::string REF_EXT = ".reference.fasta";

// write2stream is used by curl to download to a stream.
size_t write2stream(char* ptr, size_t size, size_t nmemb, void* userdata)
{
    std::stringstream* stream = (std::stringstream*)userdata;
    size_t count = size * nmemb;
    stream->write(ptr, count);
    return count;
}

// write2disk is used by curl to download to disk.
size_t write2disk(void* ptr, size_t size, size_t nmemb, FILE* stream)
{
    size_t count = fwrite(ptr, size, nmemb, stream);
    return count;
}

// downloadJSON will download a JSON file from a URL and load it as a JSON object.
void downloadJSON(const std::string& url, pt::ptree& jsonTree)
{

    // set up curl to write to a stream
    CURL* curl = curl_easy_init();
    if (!curl)
        throw std::runtime_error("could not init curl for file download");
    std::stringstream stream;
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write2stream);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &stream);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3L);

    // download the manifest to stream
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    auto res = curl_easy_perform(curl);
    if (res != 0)
        throw std::runtime_error("could not download ARTIC manifest: " + std::to_string(res));
    curl_easy_cleanup(curl);

    // deserialize from curl stream
    pt::read_json(stream, jsonTree);
    return;
}

// downloadFile will download a file from a URL and save it on disk.
void downloadFile(const std::string& url, const std::string& fname)
{
    CURL* curl = curl_easy_init();
    if (!curl)
        throw std::runtime_error("could not init curl for file download");
    FILE* fp = fopen(fname.c_str(), "wb");
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write2disk);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3L);
    auto res = curl_easy_perform(curl);
    if (res != 0)
        throw std::runtime_error("could not download file: " + url + " (" + std::to_string(res) + ")");
    curl_easy_cleanup(curl);
    fclose(fp);
}

// DownloadScheme will download a specified primer scheme and the reference sequence.
// if 0 is provided as a version, or an unknown version provided, the latest scheme version will be used.
void artic::DownloadScheme(SchemeArgs& args)
{
    LOG_TRACE("\trequested scheme:\t{}", args.schemeName);
    if (args.schemeVersion == 0)
    {
        LOG_TRACE("\trequested version:\tlatest");
    }
    else
    {
        LOG_TRACE("\trequested version:\t{}", args.schemeVersion);
    }
    LOG_TRACE("fetching manifest file");
    LOG_TRACE("\tARTIC manifest URL:\t{}", ARTIC_MANIFEST_URL);
    pt::ptree manifest;
    downloadJSON(ARTIC_MANIFEST_URL, manifest);
    LOG_TRACE("\tARTIC repository DOI:\t{}", manifest.get<std::string>("latest_doi"));

    // grab the schemes as a subtree and then check each for the requested scheme (via the alias field)
    LOG_TRACE("finding primer scheme");
    std::vector<std::string> checkedAliases;
    std::pair<std::string, std::string> primer_url;
    std::pair<std::string, std::string> reference_url;
    pt::ptree& schemes = manifest.get_child("schemes");
    for (const auto& scheme : schemes)
    {
        for (const auto& alias : scheme.second.get_child("aliases"))
        {
            checkedAliases.push_back(alias.second.data());
            if (!boost::iequals(checkedAliases.back(), args.schemeName))
                continue;

            // check available versions and get the primer_url
            LOG_TRACE("\tfound requested scheme:\t{} (using alias {})", scheme.first, args.schemeName);
            unsigned int latestVersion = scheme.second.get<unsigned int>("latest_version");
            if (args.schemeVersion > latestVersion)
            {
                LOG_WARN("\trequested version not found (v{}), using latest version instead (v{})", args.schemeVersion, latestVersion);
                args.schemeVersion = latestVersion;
            }
            if (args.schemeVersion == 0)
                args.schemeVersion = latestVersion;
            primer_url.first = scheme.second.get_child("primer_urls").get<std::string>(std::to_string(args.schemeVersion));
            primer_url.second = scheme.second.get_child("primer_sha256_checksums").get<std::string>(std::to_string(args.schemeVersion));
            reference_url.first = scheme.second.get_child("reference_urls").get<std::string>(std::to_string(args.schemeVersion));
            reference_url.second = scheme.second.get_child("reference_sha256_checksums").get<std::string>(std::to_string(args.schemeVersion));
        }
    }

    // check that a scheme was found
    if (primer_url.first.empty() || reference_url.first.empty())
    {
        LOG_WARN("\tscheme not found:\t{}", args.schemeName);
        LOG_WARN("listing available scheme aliases (case insensitive)", args.schemeName);
        for (const auto& i : checkedAliases)
            LOG_WARN("\t- {}", i);
        throw std::runtime_error("no primer scheme available for " + args.schemeName);
    }

    // create filenames
    std::stringstream fp;
    if (args.outDir.size() != 0)
    {
        if (!boost::filesystem::is_directory(args.outDir) || !boost::filesystem::exists(args.outDir))
            boost::filesystem::create_directories(args.outDir);
        fp << args.outDir << "/";
    }
    fp << args.schemeName << ".v" << args.schemeVersion;
    auto f1 = fp.str() + SCHEME_EXT;
    auto f2 = fp.str() + REF_EXT;

    // download files
    LOG_TRACE("downloading primer scheme")
    downloadFile(primer_url.first, f1);
    downloadFile(reference_url.first, f2);
    LOG_TRACE("\tsaving primers to:\t{}", f1);
    LOG_TRACE("\tsaving reference to:\t{}", f2);

    // check integrity
    LOG_TRACE("comparing checksums")
    std::ifstream f1Check(f1, std::ios::binary);
    std::vector<unsigned char> s1(picosha2::k_digest_size);
    picosha2::hash256(f1Check, s1.begin(), s1.end());
    std::string f1h;
    picosha2::bytes_to_hex_string(s1.begin(), s1.end(), f1h);
    LOG_TRACE("\tsha256 for primers:\t{}", f1h);
    if (f1h != primer_url.second)
        throw std::runtime_error("hash for download does not match manifest: " + primer_url.second);
    std::ifstream f2Check(f2, std::ios::binary);
    std::vector<unsigned char> s2(picosha2::k_digest_size);
    picosha2::hash256(f2Check, s2.begin(), s2.end());
    std::string f2h;
    picosha2::bytes_to_hex_string(s2.begin(), s2.end(), f2h);
    LOG_TRACE("\tsha256 for reference:\t{}", f2h);
    if (f2h != reference_url.second)
        throw std::runtime_error("hash for download does not match manifest: " + reference_url.second);

    // pass back the downloaded scheme via the args struct
    args.schemeFile = f1;
    args.refSeqFile = f2;
}


text:
/**
 * Copyright 2007-2021 IMP Inventors. All rights reserved.
 */

#include <boost/lexical_cast.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <math.h>
#include <ctime>
#include <exception>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

#include "RMF/FileConstHandle.h"
#include "RMF/FileHandle.h"
#include "RMF/ID.h"
#include "RMF/NodeConstHandle.h"
#include "RMF/NodeHandle.h"
#include "RMF/Vector.h"
#include "RMF/decorator/physics.h"
#include "RMF/decorator/shape.h"
#include "RMF/enums.h"
#include "RMF/types.h"
#include "RMF/utility.h"
#include "common.h"

namespace {
std::string description("Generate a new file that interpolates an old one.");

#define RMF_INTERPOLATE(factory, attribute, noise, normalize, D)   \
  {                                                                \
    RMF_VECTOR<D> c0 = factory##cf0.get(input0).get_##attribute(); \
    RMF_VECTOR<D> c1 = factory##cf1.get(input1).get_##attribute(); \
    RMF_VECTOR<D> result;                                          \
    double mag2 = 0.0;                                             \
    for (unsigned int i = 0; i < D; ++i) {                         \
      result[i] = (1.0 - frac) * c0[i] + frac * c1[i] + noise();   \
      mag2 += result[i] * result[i];                               \
    }                                                              \
    if (normalize) {                                               \
      for (unsigned int i = 0; i < D; ++i) {                       \
        result[i] /= std::sqrt(mag2);                              \
      }                                                            \
    }                                                              \
    factory##f.get(output).set_##attribute(result);                \
  }

#define RMF_INTERPOLATE_LIST(factory, attribute, noise)                     \
  {                                                                         \
    RMF::Vector3s c0 = factory##cf0.get(input0).get_##attribute();          \
    RMF::Vector3s c1 = factory##cf1.get(input1).get_##attribute();          \
    RMF::Vector3s result(3, RMF::Vector3());                                \
    for (unsigned int i = 0; i < c0.size(); ++i) {                          \
      for (unsigned int j = 0; j < 3; ++j) {                                \
        result[i][j] = (1.0 - frac) * c0[i][j] + frac * c1[i][j] + noise(); \
      }                                                                     \
    }                                                                       \
    factory##f.get(output).set_##attribute(result);                         \
  }

void interpolate_frame(
    double frac, boost::variate_generator<boost::mt19937&,
                                          boost::normal_distribution<> >& noise,
    boost::variate_generator<boost::mt19937&, boost::normal_distribution<> >&
        angle_noise,
    RMF::decorator::IntermediateParticleFactory ipcf0,
    RMF::decorator::IntermediateParticleFactory ipcf1,
    RMF::decorator::IntermediateParticleFactory ipf,
    RMF::decorator::BallFactory bcf0, RMF::decorator::BallFactory bcf1,
    RMF::decorator::BallFactory bf, RMF::decorator::ReferenceFrameFactory rfcf0,
    RMF::decorator::ReferenceFrameFactory rfcf1,
    RMF::decorator::ReferenceFrameFactory rff,
    RMF::decorator::CylinderFactory ccf0, RMF::decorator::CylinderFactory ccf1,
    RMF::decorator::CylinderFactory cf, RMF::NodeConstHandle input0,
    RMF::NodeConstHandle input1, RMF::NodeHandle output) {
  if (ipcf0.get_is(input0)) {
    RMF_INTERPOLATE(ip, coordinates, noise, false, 3);
  }
  if (bcf0.get_is(input0)) {
    RMF_INTERPOLATE(b, coordinates, noise, false, 3);
  }
  if (rfcf0.get_is(input0)) {
    RMF_INTERPOLATE(rf, translation, noise, false, 3);
    RMF_INTERPOLATE(rf, rotation, angle_noise, true, 4);
  }
  if (ccf0.get_is(input0)) {
    RMF_INTERPOLATE_LIST(c, coordinates_list, noise);
  }
  RMF::NodeConstHandles ic0 = input0.get_children();
  RMF::NodeConstHandles ic1 = input1.get_children();
  RMF::NodeHandles oc = output.get_children();
  for (unsigned int i = 0; i < ic0.size(); ++i) {
    interpolate_frame(frac, noise, angle_noise, ipcf0, ipcf1, ipf, bcf0, bcf1,
                      bf, rfcf0, rfcf1, rff, ccf0, ccf1, cf, ic0[i], ic1[i],
                      oc[i]);
  }
}

void interpolate_frames(int num, double noise, double angle_noise,
                        RMF::FileConstHandle input_file0,
                        RMF::FileConstHandle input_file1,
                        RMF::FileHandle output_file) {
  RMF::decorator::IntermediateParticleFactory ipcf0(input_file0);
  RMF::decorator::IntermediateParticleFactory ipcf1(input_file1);
  RMF::decorator::IntermediateParticleFactory ipf(output_file);
  RMF::decorator::BallFactory bcf0(input_file0);
  RMF::decorator::BallFactory bcf1(input_file1);
  RMF::decorator::BallFactory bf(output_file);
  RMF::decorator::CylinderFactory ccf0(input_file0);
  RMF::decorator::CylinderFactory ccf1(input_file1);
  RMF::decorator::CylinderFactory cf(output_file);
  RMF::decorator::ReferenceFrameFactory rfcf0(input_file0);
  RMF::decorator::ReferenceFrameFactory rfcf1(input_file1);
  RMF::decorator::ReferenceFrameFactory rff(output_file);
  // boost::random_device seed_gen;
  boost::mt19937 rng;
  // rng.seed(seed_gen());
  rng.seed(static_cast<boost::uint64_t>(std::time(NULL)));
  boost::normal_distribution<> nd(0.0, noise);
  boost::variate_generator<boost::mt19937&, boost::normal_distribution<> >
      normal_random(rng, nd);
  boost::normal_distribution<> a_nd(0.0, angle_noise);
  boost::variate_generator<boost::mt19937&, boost::normal_distribution<> >
      angle_normal_random(rng, a_nd);
  for (int i = 0; i < num; ++i) {
    output_file.add_frame("interpolated", RMF::FRAME);
    double frac = static_cast<double>(i + 1) / static_cast<double>(num + 1);
    std::cout << "fraction is " << frac << " at "
              << output_file.get_current_frame() << " from "
              << input_file0.get_current_frame() << " and "
              << input_file1.get_current_frame() << std::endl;
    interpolate_frame(frac, normal_random, angle_normal_random, ipcf0, ipcf1,
                      ipf, bcf0, bcf1, bf, rfcf0, rfcf1, rff, ccf0, ccf1, cf,
                      input_file0.get_root_node(), input_file1.get_root_node(),
                      output_file.get_root_node());
  }
}
}

int main(int argc, char** argv) {
  try {
    RMF_ADD_INPUT_FILE("rmf");
    RMF_ADD_OUTPUT_FILE("rmf");
    int num_frames = 0;
    double noise = 0, angle_noise = 0;
    int max_frames = -1;
    options.add_options()(
        "number-interpolated", boost::program_options::value<int>(&num_frames),
        "How many frames to insert between each original frame")(
        "coordinate_noise", boost::program_options::value<double>(&noise),
        "How much (gaussian) noise to add to each generated coordinate.")(
        "angular_noise", boost::program_options::value<double>(&angle_noise),
        "How much (gaussian) noise to add to each generated quaternion.")(
        "frame_limit", boost::program_options::value<int>(&max_frames),
        "Limits how many frames are output, for testing.");
    process_options(argc, argv);
    RMF::FileConstHandle irh0 = RMF::open_rmf_file_read_only(input);
    RMF::FileConstHandle irh1 = RMF::open_rmf_file_read_only(input);
    RMF::FileHandle orh = RMF::create_rmf_file(output);
    orh.set_producer("rmf_interpolate");
    orh.set_description(std::string("Interpolation between frames of ") +
                        input);
    RMF::clone_hierarchy(irh0, orh);
    RMF::clone_static_frame(irh0, orh);
    for (unsigned int j = 0; j < irh0.get_number_of_frames() - 1; ++j) {
      std::cout << "Processing frame " << j << std::endl;
      irh0.set_current_frame(RMF::FrameID(j));
      irh1.set_current_frame(RMF::FrameID(j + 1));
      orh.add_frame(irh0.get_name(RMF::FrameID(j)), RMF::FRAME);
      RMF::clone_loaded_frame(irh0, orh);
      if (j + 1 < irh0.get_number_of_frames()) {
        interpolate_frames(num_frames, noise, angle_noise, irh0, irh1, orh);
      }
      if (max_frames > 0 &&
          orh.get_number_of_frames() > static_cast<unsigned int>(max_frames)) {
        return 1;
      }
    }
    irh0.set_current_frame(RMF::FrameID(irh0.get_number_of_frames() - 1));
    RMF::clone_loaded_frame(irh0, orh);

    return 0;
  }
  catch (const std::exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
  }
}

max_stars_repo_name: salilab/rmf

max_issues_repo_name: salilab/rmf

max_forks_repo_name: salilab/rmf


text: #include <boost/asio/buffers_iterator.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


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
//==============================================================================
#ifndef BOOST_SIMD_MEMORY_FUNCTIONS_PACK_STORE_HPP_INCLUDED
#define BOOST_SIMD_MEMORY_FUNCTIONS_PACK_STORE_HPP_INCLUDED

#include <boost/simd/include/functions/store.hpp>
#include <boost/dispatch/functor/preprocessor/call.hpp>
#include <boost/simd/include/functions/evaluate.hpp>
#include <boost/simd/memory/iterator_category.hpp>
#include <boost/simd/sdk/simd/pack/forward.hpp>
#include <boost/dispatch/dsl/semantic_of.hpp>
#include <boost/dispatch/attributes.hpp>

namespace boost { namespace simd { namespace ext
{
  /// INTERNAL ONLY pack store with offset
  BOOST_DISPATCH_IMPLEMENT          ( store_
                                    , tag::cpu_
                                    , (A0)(A1)(A2)
                                    , ((ast_<A0, boost::simd::domain>))
                                      (iterator_< scalar_< fundamental_<A1> > >)
                                      (scalar_< integer_<A2> >)
                                    )
  {
    typedef void result_type;

    BOOST_FORCEINLINE result_type
    operator()(A0 const& a0, A1 a1, A2 const& a2) const
    {
      boost::simd::store(evaluate(a0),a1,a2);
    }
  };

  /// INTERNAL ONLY masked pack store with offset
  BOOST_DISPATCH_IMPLEMENT          ( store_
                                    , tag::cpu_
                                    , (A0)(A1)(A2)(A3)(X)(Tag)(Arity)
                                    , ((ast_<A0, boost::simd::domain>))
                                      (iterator_< scalar_< fundamental_<A1> > >)
                                      (scalar_< integer_<A2> >)
                                      ((expr_ < simd_< logical_<A3>, X >
                                              , Tag, Arity
                                              >
                                      ))
                                    )
  {
    typedef void result_type;

    BOOST_FORCEINLINE result_type
    operator()(A0 const& a0, A1 a1, A2 const& a2, const A3& a3) const
    {
      boost::simd::store(evaluate(a0),a1,a2,evaluate(a3));
    }
  };

  /// INTERNAL ONLY pack scatter
  BOOST_DISPATCH_IMPLEMENT          ( store_
                                    , tag::cpu_
                                    , (A0)(A1)(A2)(X)
                                    , ((ast_<A0, boost::simd::domain>))
                                      (iterator_< scalar_< fundamental_<A1> > >)
                                      ((simd_< integer_<A2>, X >))
                                    )
  {
    typedef void result_type;

    BOOST_FORCEINLINE result_type
    operator()(A0 const& a0, A1 a1, A2 const& a2) const
    {
      boost::simd::store(evaluate(a0),a1,a2);
    }
  };

  /// INTERNAL ONLY mask pack scatter
  BOOST_DISPATCH_IMPLEMENT          ( store_
                                    , tag::cpu_
                                    , (A0)(A1)(A2)(A3)(X)(Tag)(Arity)
                                    , ((ast_<A0, boost::simd::domain>))
                                      (iterator_< scalar_< fundamental_<A1> > >)
                                      ((simd_< integer_<A2>, X >))
                                      ((expr_ < simd_< logical_<A3>, X >
                                              , Tag, Arity
                                              >
                                      ))
                                    )
  {
    typedef void result_type;

    BOOST_FORCEINLINE result_type
    operator()(A0 const& a0, A1 a1, A2 const& a2, const A3& a3) const
    {
      boost::simd::store(evaluate(a0),a1,a2,evaluate(a3));
    }
  };

  /// INTERNAL ONLY pack store without offset
  BOOST_DISPATCH_IMPLEMENT          ( store_
                                    , tag::cpu_
                                    , (A0)(A1)
                                    , ((ast_<A0, boost::simd::domain>))
                                      (iterator_< scalar_< fundamental_<A1> > >)
                                    )
  {
    typedef void result_type;

    BOOST_FORCEINLINE result_type
    operator()(A0 const& a0, A1 a1) const
    {
      boost::simd::store(evaluate(a0),a1);
    }
  };

  /// INTERNAL ONLY mask pack store without offset
  BOOST_DISPATCH_IMPLEMENT          ( store_
                                    , tag::cpu_
                                    , (A0)(A1)(A2)(X)(Tag)(Arity)
                                    , ((ast_<A0, boost::simd::domain>))
                                      (iterator_< scalar_< fundamental_<A1> > >)
                                      ((expr_ < simd_< logical_<A2>, X >
                                              , Tag, Arity
                                              >
                                      ))
                                    )
  {
    typedef void result_type;

    BOOST_FORCEINLINE result_type
    operator()(A0 const& a0, A1 a1, A2 const& a2) const
    {
      boost::simd::store(evaluate(a0),a1,evaluate(a2));
    }
  };
} } }

#endif


text: #include <boost/type_traits/is_integral.hpp>


text:
// __BEGIN_LICENSE__
//  Copyright (c) 2006-2013, United States Government as represented by the
//  Administrator of the National Aeronautics and Space Administration. All
//  rights reserved.
//
//  The NASA Vision Workbench is 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.
// __END_LICENSE__

/// \file ipfind.cc
///
/// Finds the interest points in an image and outputs them an Binary
/// (default) or ASCII format.  The ASCII format is compatible with
/// the popular Lowe-SIFT toolchain.
///

#include <vw/Core/System.h>
#include <vw/Math/BBox.h>
#include <vw/Math/Vector.h>
#include <vw/Image/AlgorithmFunctions.h>
#include <vw/Image/Algorithms.h>
#include <vw/Image/ImageIO.h>
#include <vw/Image/ImageMath.h>
#include <vw/Image/Manipulation.h>
#include <vw/Image/MaskViews.h>
#include <vw/Image/PerPixelViews.h>
#include <vw/FileIO/DiskImageView.h>
#include <vw/InterestPoint/Descriptor.h>
#include <vw/InterestPoint/Detector.h>
#include <vw/InterestPoint/IntegralDescriptor.h>
#include <vw/InterestPoint/IntegralDetector.h>
#include <vw/InterestPoint/IntegralInterestOperator.h>
#include <vw/InterestPoint/InterestData.h>

using namespace vw;
using namespace vw::ip;

#include <boost/program_options.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/foreach.hpp>
namespace po = boost::program_options;
namespace fs = boost::filesystem;

template <class ImageT, class ValueT>
void draw_line( ImageViewBase<ImageT>& image,
                ValueT const& value,
                Vector2i const& start,
                Vector2i const& end ) {

  BBox2i bound = bounding_box(image.impl());
  if ( !bound.contains( start ) ||
       !bound.contains( end ) )
    return;
  Vector2i delta = end - start;
  float inc_amt = 1/norm_2(delta);
  for ( float r=0; r<1.0; r+=inc_amt ) {
    int i = (int)(0.5 + start.x() + r*float(delta.x()) );
    int j = (int)(0.5 + start.y() + r*float(delta.y()) );
    image.impl()(i,j) = value;
  }
}

static void write_debug_image( std::string const& out_file_name,
                               std::string const& input_file_name,
                               InterestPointList const& ip ) {
  vw_out() << "Writing debug image: " << out_file_name << "\n";

  vw_out(InfoMessage,"interest_point") << "\t > Gathering statistics:\n";
  float min = 1e30, max = -1e30;
  for ( InterestPointList::const_iterator point = ip.begin();
        point != ip.end(); ++point ) {
    if ( point->interest > max )
      max = point->interest;
    if ( point->interest < min )
      min = point->interest;
  }
  float diff = max - min;

  vw_out(InfoMessage,"interest_point") << "\t > Drawing raster:\n";
  ImageView<PixelRGB<uint8> > oimage;
  boost::scoped_ptr<DiskImageResource> irsrc( DiskImageResource::open(input_file_name) );
  if ( irsrc->has_nodata_read() ) {
    oimage = pixel_cast_rescale<PixelRGB<uint8> >(apply_mask(normalize(create_mask(DiskImageView<PixelGray<float> >( *irsrc ),
                                                                                irsrc->nodata_read()))) * 0.5 );
  } else {
    oimage = pixel_cast_rescale<PixelRGB<uint8> >(normalize(DiskImageView<PixelGray<float> >( *irsrc )) * 0.5);
  }

  for ( InterestPointList::const_iterator point = ip.begin();
        point != ip.end(); ++point ) {
    float norm_i = (point->interest - min)/diff;
    PixelRGB<uint8> color(0,0,0);
    if ( norm_i < .5 ) {
      // Form of red
      color.r() = 255;
      color.g() = (uint8)(2*norm_i*255);
    } else {
      // Form of green
      color.g() = 255;
      color.r() = 255 - (uint8)(2*(norm_i-.5)*255);
    }

    // Marking point w/ Dot
    oimage(point->ix,point->iy) = color;

    // Circling point
    for (float a = 0; a < 6; a+=.392 ) {
      float a_d = a + .392;
      Vector2i start( int(2*point->scale*cos(a)+point->x),
                      int(2*point->scale*sin(a)+point->y) );
      Vector2i end( int(2*point->scale*cos(a_d)+point->x),
                    int(2*point->scale*sin(a_d)+point->y) );
      draw_line( oimage, color, start, end );
    }
  }

  boost::scoped_ptr<DiskImageResource> rsrc( DiskImageResource::create(out_file_name,
                                                                       oimage.format() ) );
  vw_out(InfoMessage,"interest_point") << "\t > Writing out image:\n";
  block_write_image( *rsrc, oimage,
                     TerminalProgressCallback( "tools.ipfind","\t : ") );
}

int main(int argc, char** argv) {
  std::vector<std::string> input_file_names;
  std::string interest_operator, descriptor_generator;
  float ip_gain;
  uint32 max_points;
  int tile_size, num_threads;
  ImageView<double> integral;
  bool no_orientation;

  const float IDEAL_LOG_THRESHOLD = .03;
  const float IDEAL_OBALOG_THRESHOLD = .07;
  const float IDEAL_HARRIS_THRESHOLD = 1.2e-5;

  po::options_description general_options("Options");
  general_options.add_options()
    ("help,h", "Display this help message")
    ("num-threads", po::value(&num_threads)->default_value(0), "Set the number of threads for interest point detection.  Setting the num_threads to zero causes ipfind to use the visionworkbench default number of threads.")
    ("tile-size,t", po::value(&tile_size), "Specify the tile size for processing interest points. (Useful when working with large images).")
    ("lowe,l", "Save the interest points in an ASCII data format that is compatible with the Lowe-SIFT toolchain.")
    ("normalize", "Normalize the input, use for images that have non standard values such as ISIS cube files.")
    ("debug-image,d", "Write out debug images.")

    // Interest point detector options
    ("interest-operator", po::value(&interest_operator)->default_value("OBALoG"), "Choose an interest point metric from [LoG, Harris, OBALoG]")
    ("gain,g", po::value(&ip_gain)->default_value(1.0), "Increasing this number will increase the gain at which interest points are detected.")
    ("max-points", po::value(&max_points)->default_value(0), "Set the maximum number of interest points you want returned.  The most \"interesting\" points are selected.")
    ("single-scale", "Turn off scale-invariant interest point detection.  This option only searches for interest points in the first octave of the scale space.")
    ("no-orientation", po::bool_switch(&no_orientation), "Shutoff rotational invariance")

    // Descriptor generator options
    ("descriptor-generator", po::value(&descriptor_generator)->default_value("sgrad"), "Choose a descriptor generator from [patch,pca,sgrad,sgrad2]");

  po::options_description hidden_options("");
  hidden_options.add_options()
    ("input-files", po::value(&input_file_names));

  po::options_description options("Allowed Options");
  options.add(general_options).add(hidden_options);

  po::positional_options_description p;
  p.add("input-files", -1);

  std::ostringstream usage;
  usage << "Usage: " << argv[0] << " [options] <filenames>..." << std::endl << std::endl;
  usage << general_options << std::endl;

  po::variables_map vm;
  try {
    po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );
    po::notify( vm );
  } catch (const po::error& e) {
    std::cout << "An error occured while parsing command line arguments.\n";
    std::cout << "\t" << e.what() << "\n\n";
    std::cout << usage.str();
    return 1;
  }

  if( vm.count("help") ) {
    vw_out() << usage.str();
    return 1;
  }

  if( input_file_names.size() < 1 ) {
    vw_out() << "Error: Must specify at least one input file!" << std::endl << std::endl;
    vw_out() << usage.str();
    return 1;
  }

  if ( num_threads > 0 )
    vw_settings().set_default_num_threads(num_threads);
  if ( vm.count("tile-size"))
    vw_settings().set_default_tile_size(tile_size);

  // Checking strings
  boost::to_lower( interest_operator );
  boost::to_lower( descriptor_generator );
  // Determine if interest_operator is legitimate
  if ( !( interest_operator == "harris" ||
          interest_operator == "log" ||
          interest_operator == "obalog" ) ) {
    vw_out() << "Unknown interest operator: " << interest_operator
             << ". Options are : [ Harris, LoG, OBALoG ]\n";
    exit(0);
  }
  // Determine if descriptor_generator is legitimate
  if ( !( descriptor_generator == "patch" ||
          descriptor_generator == "pca"   ||
          descriptor_generator == "sgrad" ||
          descriptor_generator == "sgrad2" ) ) {
    vw_out() << "Unkown descriptor generator: " << descriptor_generator
             << ". Options are : [ Patch, PCA, SGrad, SGrad2 ]\n";
    exit(0);
  }

  // Iterate over the input files and find interest points in each.
  for (size_t i = 0; i < input_file_names.size(); ++i) {

    vw_out() << "Finding interest points in \"" << input_file_names[i] << "\".\n";
    std::string file_prefix = fs::path(input_file_names[i]).replace_extension().string();
    boost::scoped_ptr<DiskImageResource> image_rsrc( DiskImageResource::open( input_file_names[i] ) );
    DiskImageView<PixelGray<float> > raw_image( *image_rsrc );
    ImageViewRef<PixelGray<float> > image = raw_image;
    if ( vm.count("normalize") && image_rsrc->has_nodata_read() )
      image = apply_mask(normalize(create_mask(raw_image,image_rsrc->nodata_read())));
    else if ( vm.count("normalize") )
      image = normalize(raw_image);

    // Potentially mask image on a no data value
    if ( image_rsrc->has_nodata_read() )
      vw_out(DebugMessage,"interest_point") << "Image has a nodata value: "
                                            << image_rsrc->nodata_read() << "\n";

    // The max points sent to IP Detector class is applied to each
    // tile of an image. In order to curb memory use we'll set the max
    // size for each tile smaller (proportional to the number of
    // tiles).
    int number_tiles = (image.cols()/vw_settings().default_tile_size()+1) *
      (image.rows()/vw_settings().default_tile_size()+1);
    uint32 tile_max_points = uint32(float(max_points)/float(number_tiles))*2; // A little over shoot
    // incase the tile is empty
    if ( max_points == 0 ) tile_max_points = 0; // No culling
    else if ( tile_max_points < 50 ) tile_max_points = 50;

    // Detecting Interest Points
    InterestPointList ip;
    if ( interest_operator == "harris" ) {
      // Harris threshold is inversely proportional to gain.
      HarrisInterestOperator interest_operator(IDEAL_HARRIS_THRESHOLD/ip_gain);
      if (!vm.count("single-scale")) {
        ScaledInterestPointDetector<HarrisInterestOperator> detector(interest_operator,
                                                                     tile_max_points);
        ip = detect_interest_points(image, detector);
      } else {
        InterestPointDetector<HarrisInterestOperator> detector(interest_operator,
                                                               tile_max_points);
        ip = detect_interest_points(image, detector);
      }
    } else if ( interest_operator == "log") {
      // Use a scale-space Laplacian of Gaussian feature detector. The
      // associated threshold is abs(interest) > interest_threshold.
      // LoG threshold is inversely proportional to gain..
      LogInterestOperator interest_operator(IDEAL_LOG_THRESHOLD/ip_gain);
      if (!vm.count("single-scale")) {
        ScaledInterestPointDetector<LogInterestOperator> detector(interest_operator,
                                                                  tile_max_points);
        ip = detect_interest_points(image, detector);
      } else {
        InterestPointDetector<LogInterestOperator> detector(interest_operator,
                                                            tile_max_points);
        ip = detect_interest_points(image, detector);
      }
    } else if ( interest_operator == "obalog") {
      // OBALoG threshold is inversely proportional to gain ..
      OBALoGInterestOperator interest_operator(IDEAL_OBALOG_THRESHOLD/ip_gain);
      IntegralInterestPointDetector<OBALoGInterestOperator> detector( interest_operator,
                                                                      tile_max_points );
      ip = detect_interest_points(image, detector);
    }

    // Removing Interest Points on nodata or within 1/px
    if ( image_rsrc->has_nodata_read() ) {
      ImageViewRef<PixelMask<PixelGray<float> > > image_mask =
        create_mask(raw_image,image_rsrc->nodata_read());
      BBox2i bound = bounding_box( image_mask );
      bound.contract(1);
      int before_size = ip.size();
      for ( InterestPointList::iterator point = ip.begin();
            point != ip.end(); ++point ) {

        // To Avoid out of index issues
        if ( !bound.contains( Vector2i(point->ix,
                                       point->iy ))) {
          point = ip.erase(point);
          point--;
          continue;
        }

        if ( !image_mask(point->ix,point->iy).valid() ||
             !image_mask(point->ix+1,point->iy+1).valid() ||
             !image_mask(point->ix+1,point->iy).valid() ||
             !image_mask(point->ix+1,point->iy-1).valid() ||
             !image_mask(point->ix,point->iy+1).valid() ||
             !image_mask(point->ix,point->iy-1).valid() ||
             !image_mask(point->ix-1,point->iy+1).valid() ||
             !image_mask(point->ix-1,point->iy).valid() ||
             !image_mask(point->ix-1,point->iy-1).valid() ) {
          point = ip.erase(point);
          point--;
          continue;
        }
      }
      vw_out(InfoMessage,"interest_point") << "Removed " << before_size-ip.size() << " points close to nodata.\n";
    }

    vw_out() << "\t Found " << ip.size() << " points.\n";

    // Additional Culling for the entire image
    if ( max_points > 0  && ip.size() > max_points ) {
      ip.sort();
      ip.resize(max_points);
      vw_out() << "\t Culled to " << ip.size() << " points.\n";
    }

    // Delete the orientation value if requested
    if ( no_orientation ) {
      BOOST_FOREACH( InterestPoint& i, ip ) {
        i.orientation = 0;
      }
    }

    // Generate descriptors for interest points.
    vw_out(InfoMessage) << "\tRunning " << descriptor_generator << " descriptor generator.\n";
    if (descriptor_generator == "patch") {
      PatchDescriptorGenerator descriptor;
      describe_interest_points( image, descriptor, ip );
    } else if (descriptor_generator == "pca") {
      PCASIFTDescriptorGenerator descriptor("pca_basis.exr", "pca_avg.exr");
      describe_interest_points( image, descriptor, ip );
    } else if (descriptor_generator == "sgrad") {
      SGradDescriptorGenerator descriptor;
      describe_interest_points( image, descriptor, ip );
    } else if (descriptor_generator == "sgrad2") {
      SGrad2DescriptorGenerator descriptor;
      describe_interest_points( image, descriptor, ip );
    }

    // If ASCII output was requested, write it out.  Otherwise stick
    // with binary output.
    if (vm.count("lowe"))
      write_lowe_ascii_ip_file(file_prefix + ".key", ip);
    else
      write_binary_ip_file(file_prefix + ".vwip", ip);

    // Write Debug image
    if (vm.count("debug-image"))
      write_debug_image( file_prefix + "_debug.jpg",
                         input_file_names[i],
                         ip );
  }

  return 0;
}

ext: cc

max_stars_repo_name: mdhancher/visionworkbench

max_issues_repo_name: maxsu/visionworkbench

max_forks_repo_name: maxsu/visionworkbench


text:
/*
 * Copyright (c) 2019 Opticks Team. All Rights Reserved.
 *
 * This file is part of Opticks
 * (see https://bitbucket.org/simoncblyth/opticks).
 *
 * 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.
 */

#pragma once
// started from /usr/local/env/boost/basio/example/cpp03/tutorial/daytime6/server.cpp

#include <ctime>
#include <iostream>
#include <string>
#include <iomanip>

#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>

#include <boost/log/trivial.hpp>
#define LOG BOOST_LOG_TRIVIAL
// trace/debug/info/warning/error/fatal

#include "stdio.h"

//#define VERBOSE 1

template <class Delegate>
class udp_server
{
    boost::asio::ip::udp::socket    m_socket;
    boost::asio::ip::udp::endpoint  m_remote_endpoint;
    boost::array<char,1024>         m_recv_buffer;
    Delegate*                       m_delegate  ;
    boost::asio::io_service&        m_delegate_io_service ;

public:
    udp_server(
           boost::asio::io_service& io_service,
           Delegate*                delegate,
           boost::asio::io_service& delegate_io_service,
           int port
           )
    :
       m_socket(io_service, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), port)),
       m_delegate(delegate),
       m_delegate_io_service(delegate_io_service)

    {
#ifdef VERBOSE
        std::cout
             << std::setw(20) << boost::this_thread::get_id()
             << " udp_server::udp_server on port " << port <<  std::endl;
#endif
        start_receive();
    }

    void send(std::string addr, unsigned short port, std::string msg);
    //
    // problem with initiating a dialog is knowning
    // what remote endpoint to sendto
    // remote_endpoint starts as 0.0.0.0:0
    // and after receiving a msg becomes smth like
    // 10.0.2.5:49970
    //

private:
    void start_receive();
    void handle_receive(const boost::system::error_code& error, std::size_t bytes_transferred );
    void handle_send(boost::shared_ptr<std::string> /*message*/, const boost::system::error_code& /*error*/, std::size_t /*bytes_transferred*/);
    void dump(std::size_t nbytes );

};

template <typename Delegate>
void udp_server<Delegate>::start_receive()
{
#ifdef VERBOSE
    std::cout
         << std::setw(20) << boost::this_thread::get_id()
         << " udp_server::start_receive " << std::endl;
#endif
    m_socket.async_receive_from(
                            boost::asio::buffer(m_recv_buffer),
                            m_remote_endpoint,
                            boost::bind(
                                        &udp_server<Delegate>::handle_receive,
                                        this,
                                        boost::asio::placeholders::error,
                                        boost::asio::placeholders::bytes_transferred
                                       )
                           );

#ifdef VERBOSE
    std::cout
         << std::setw(20) << boost::this_thread::get_id()
         << " udp_server::start_receive DONE  "
         << std::endl;
#endif
}

template <typename Delegate>
void udp_server<Delegate>::handle_receive(const boost::system::error_code& error, std::size_t nbytes)
{
    if (!error || error == boost::asio::error::message_size)
    {
        dump(nbytes);

        // shared_ptr should keep objects alive beyond the scope without just leaking
        // and avoid having to cleanup ?
        unsigned short port = m_remote_endpoint.port();
        boost::shared_ptr<std::string> addr(new std::string(m_remote_endpoint.address().to_string()));
        boost::shared_ptr<std::string> msg(new std::string(m_recv_buffer.begin(), m_recv_buffer.begin() + nbytes));

#ifdef VERBOSE
        std::cout
             << std::setw(20) << boost::this_thread::get_id()
             << " udp_server::handle_receive "
             << " addr [" << *addr << "] "
             << " port [" << port << "] "
             << " msg [" << *msg << "] "
             << std::endl;
#endif

        // msg back to the delegate, typically passing from work thread to main thread
        m_delegate_io_service.post(
                        boost::bind(
                                &Delegate::on_msg,
                                m_delegate,
                                *addr,
                                port,
                                *msg
                                ));

        std::time_t now = std::time(0);
        boost::shared_ptr<std::string> message(new std::string(std::ctime(&now)));

        m_socket.async_send_to(
                               boost::asio::buffer(*message),
                               m_remote_endpoint,
                               boost::bind(
                                           &udp_server<Delegate>::handle_send,
                                           this,
                                           message,
                                           boost::asio::placeholders::error,
                                           boost::asio::placeholders::bytes_transferred
                                          )
                              );
        start_receive();
    }
}

template <typename Delegate>
void udp_server<Delegate>::send(std::string addr, unsigned short port, std::string msg )
{
    boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::address::from_string(addr), port);
    boost::shared_ptr<std::string> message(new std::string(msg));

#ifdef VERBOSE
    LOG(debug)
         << " udp_server::send "
         << " endpoint " << endpoint
         << " message " << *message
         << std::endl;
#endif

    m_socket.async_send_to(
                    boost::asio::buffer(*message),
                    endpoint,
                    boost::bind(
                             &udp_server<Delegate>::handle_send,
                             this,
                             message,
                             boost::asio::placeholders::error,
                             boost::asio::placeholders::bytes_transferred
                             ));
}

template <typename Delegate>
void udp_server<Delegate>::handle_send(
           boost::shared_ptr<std::string> message,
           const boost::system::error_code& error,
           std::size_t nbytes)
{
#ifdef VERBOSE
    std::cout
         << std::setw(20) << boost::this_thread::get_id()
         << " udp_server::handle_send "
         << " nbytes " << nbytes
         << " msg " << message
         << " *msg " << *message
         << std::endl;
#endif
}

template <typename Delegate>
void udp_server<Delegate>::dump(std::size_t nbytes )
{
#ifdef VERBOSE
    std::cout
         << std::setw(20) << boost::this_thread::get_id()
         << " udp_server::dump "
         << " nbytes " << nbytes
         << std::endl;

    printf("udp_server::dump %lu\n", nbytes);
    for(unsigned int i=0;i<nbytes;i++) printf("%c",m_recv_buffer[i]);
    printf("\n");
#endif

}

max_stars_repo_name: hanswenzel/opticks

max_issues_repo_name: hanswenzel/opticks

max_forks_repo_name: hanswenzel/opticks