text:
#include <boost/test/unit_test.hpp>
#include <warpcoil/cpp/message_splitter.hpp>
#include "test_streams.hpp"
#include "checkpoint.hpp"

BOOST_AUTO_TEST_CASE(message_splitter_wait_for_request_single)
{
    warpcoil::async_read_dummy_stream stream;
    warpcoil::cpp::message_splitter<warpcoil::async_read_dummy_stream> splitter(stream);
    BOOST_REQUIRE(!stream.respond);
    warpcoil::checkpoint got_request;
    splitter.wait_for_request(
        [&got_request](Si::error_or<std::tuple<warpcoil::request_id, std::string>> const request)
        {
            got_request.enter();
            BOOST_CHECK_EQUAL(123u, std::get<0>(request.get()));
            BOOST_CHECK_EQUAL("Method", std::get<1>(request.get()));
        });
    BOOST_REQUIRE(stream.respond);
    std::array<std::uint8_t, 16> const request = {
        {0, 0, 0, 0, 0, 0, 0, 0, 123, 6, 'M', 'e', 't', 'h', 'o', 'd'}};
    got_request.enable();
    Si::exchange(stream.respond, nullptr)(Si::make_memory_range(request));
    got_request.require_crossed();
    BOOST_REQUIRE(!stream.respond);
}

BOOST_AUTO_TEST_CASE(message_splitter_wait_for_request_and_response)
{
    warpcoil::async_read_dummy_stream stream;
    warpcoil::cpp::message_splitter<warpcoil::async_read_dummy_stream> splitter(stream);
    BOOST_REQUIRE(!stream.respond);
    warpcoil::checkpoint got_request;
    splitter.wait_for_request(
        [&got_request](Si::error_or<std::tuple<warpcoil::request_id, std::string>> const request)
        {
            got_request.enter();
            BOOST_CHECK_EQUAL(123u, std::get<0>(request.get()));
            BOOST_CHECK_EQUAL("Method", std::get<1>(request.get()));
        });
    BOOST_REQUIRE(stream.respond);
    warpcoil::checkpoint got_response;
    splitter.wait_for_response([&got_response](Si::error_or<warpcoil::request_id> const request)
                               {
                                   got_response.enter();
                                   BOOST_CHECK_EQUAL(99u, request.get());
                               });
    std::array<std::uint8_t, 16 + 9> const input = {
        {0, 0, 0, 0, 0, 0, 0, 0, 123, 6, 'M', 'e', 't', 'h', 'o', 'd', 1, 0, 0, 0, 0, 0, 0, 0, 99}};
    got_request.enable();
    got_response.enable();
    Si::exchange(stream.respond, nullptr)(Si::make_memory_range(input));
    got_request.require_crossed();
    got_response.require_crossed();
    BOOST_REQUIRE(!stream.respond);
}

BOOST_AUTO_TEST_CASE(message_splitter_wait_for_request_and_response_single_bytes)
{
    warpcoil::async_read_dummy_stream stream;
    warpcoil::cpp::message_splitter<warpcoil::async_read_dummy_stream> splitter(stream);
    BOOST_REQUIRE(!stream.respond);
    warpcoil::checkpoint got_request;
    splitter.wait_for_request(
        [&got_request](Si::error_or<std::tuple<warpcoil::request_id, std::string>> const request)
        {
            got_request.enter();
            BOOST_CHECK_EQUAL(123u, std::get<0>(request.get()));
            BOOST_CHECK_EQUAL("Method", std::get<1>(request.get()));
        });
    BOOST_REQUIRE(stream.respond);
    warpcoil::checkpoint got_response;
    splitter.wait_for_response([&got_response](Si::error_or<warpcoil::request_id> const request)
                               {
                                   got_response.enter();
                                   BOOST_CHECK_EQUAL(99u, request.get());
                               });
    const size_t request_size = 16;
    std::array<std::uint8_t, request_size + 9> const input = {
        {0, 0, 0, 0, 0, 0, 0, 0, 123, 6, 'M', 'e', 't', 'h', 'o', 'd', 1, 0, 0, 0, 0, 0, 0, 0, 99}};
    for (size_t i = 0; i < input.size(); ++i)
    {
        if (i == (request_size - 1))
        {
            got_request.enable();
        }
        if (i == (input.size() - 1))
        {
            got_response.enable();
        }
        Si::exchange(stream.respond,
                     nullptr)(Si::make_memory_range(input.data() + i, input.data() + i + 1));
        if (i == (request_size - 1))
        {
            got_request.require_crossed();
        }
        if (i == (input.size() - 1))
        {
            BOOST_REQUIRE(!stream.respond);
            got_response.require_crossed();
        }
        else
        {
            BOOST_REQUIRE(stream.respond);
        }
    }
}

max_stars_repo_name: TyRoXx/warpcoil

max_issues_repo_name: TyRoXx/warpcoil

max_forks_repo_name: TyRoXx/warpcoil


text:
#include "mod_passauth/provider.hpp"

#include <algorithm>
#include <iterator>
#include <iostream>
#include <sstream>

#include <boost/foreach.hpp>
#include <boost/scope_exit.hpp>
#include <boost/make_shared.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

#include "apr_errno.h"
#include "apr_strings.h"
#include "apr_uri.h"

#include "mod_passauth/log.hpp"

namespace mod_passauth {
namespace detail {

static int check_time(request_rec *r, char *szbegintime, char *szendtime)
{
	apr_time_t time;
	time = apr_time_now();
	long long begintime;
	long long endtime;
    /*将微妙转换成秒，时间戳精确到秒就可以*/
    long long secondtime = time / 1000000;
	begintime = atoll(szbegintime);
	endtime = atoll(szendtime);
	//apr_status_t rv = apr_time_exp_lt(&ts, time);
	if (begintime > secondtime) {
		ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
		             "PassAuth check_time faied: begin time  is %s", szbegintime);
		return 1;
	}
	if (endtime < secondtime) {
		ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
		             "PassAuth check_time faied: end time  is %s", szendtime);
		return 1;
	}

	return 0;
}

bool App::isIpAllowed(int role_id, const char *ip) const {
  std::map<int, PerRoleACLRule>::const_iterator rule_itr = per_role_acl_rules_.find(role_id);
  if (rule_itr == per_role_acl_rules_.end()) {
    return false;
  }
  apr_pool_t *p = NULL;
  apr_status_t rv = apr_pool_create(&p, pool_);
  if (rv != APR_SUCCESS) {
    throw std::runtime_error("acl App ctor: create apr_pool failed");
  }
  BOOST_SCOPE_EXIT((p)) {
    apr_pool_destroy(p);
  }BOOST_SCOPE_EXIT_END

  apr_sockaddr_t *sa = NULL;
  rv = apr_sockaddr_info_get(&sa, ip, APR_INET, 0, 0, p);
  if (rv != APR_SUCCESS) {
    std::ostringstream oss;
    oss << "acl_localdb detail::App::isIpAllowed: apr_sockaddr_info_get() failed: ip=" << ip;
    throw std::runtime_error(oss.str());
  }
  bool allow = false;
  BOOST_FOREACH(apr_ipsubnet_t *ip_subnet, rule_itr->second.allow_ipsubnets) {
    allow = apr_ipsubnet_test(ip_subnet, sa);
    if (allow) {
      break;
    }
  }
  return allow;
}

bool App::isTimeAllowed(int role_id, apr_time_t time) const {
  std::map<int, PerRoleACLRule>::const_iterator rule_itr = per_role_acl_rules_.find(role_id);
  if (rule_itr == per_role_acl_rules_.end()) {
    return false;
  }
  apr_time_exp_t tm;
  apr_status_t rv = apr_time_exp_lt(&tm, time);
  if (rv != APR_SUCCESS) {
    std::ostringstream oss;
    oss << "acl_localdb detail::App::isTimeAllowed: apr_time_exp_t() failed: time=" << time;
    throw std::runtime_error(oss.str());
  }
  int allow_time_begin_hhmm = rule_itr->second.allow_time_begin_hhmm;
  int allow_time_end_hhmm = rule_itr->second.allow_time_end_hhmm;
  int hhmm = tm.tm_hour * 100 + tm.tm_min;
  if (allow_time_begin_hhmm <= allow_time_end_hhmm) {
    return (hhmm >= allow_time_begin_hhmm) && (hhmm <= allow_time_end_hhmm);
  } else {
    return (hhmm >= allow_time_begin_hhmm) || (hhmm <= allow_time_end_hhmm);
  }
}

void AUTHRulesProvider::load(std::string usertoken) {
  const DBConfig& config = db_reloader_.config();
  SQLite::Database db(config.db_path, SQLite::OPEN_READONLY, config.sqlite_busy_timeout_ms);
  db.setBusyTimeout(config.sqlite_busy_timeout_ms);
  db.exec(config.sqlite_journal_mode);
  loadAppsFromDB(db, usertoken);
}

void AUTHRulesProvider::loadAuthsFromDB(SQLite::Database& db, std::string usertoken) {
  SQLite::Statement query(db, "select UserEmail, UserCN, AllowTimeBegin, AllowTimeEnd, PasswdSessionId, UserState from UserAuth where Username = ?");
  query.bind(1, usertoken);
  while (query.executeStep()) {
    boost::shared_ptr<PassAuth> passauth = boost::make_shared<PassAuth>();

    const std::string useremail = query.getColumn(0);
    const std::string usercn = query.getColumn(1);
    const std::string allowtimebegin = query.getColumn(2);
    const std::string allowtimeend = query.getColumn(3);
    const std::string pwdsessionid = query.getColumn(4);
    int state = query.getColumn(5);
    passauth->state = state;
    passauth->useremail = useremail;
    passauth->usercn = usercn;
    passauth->allowtimebegin = allowtimebegin;
    passauth->allowtimeend = allowtimeend;
    passauth->pwdsessionid = pwdsessionid;
  }
}

bool AUTHRulesProvider::isAllowedToAccessAuth(apr_time_t time, std::string pwdtoken) const {
  apr_pool_t *p = NULL;
  apr_status_t rv = apr_pool_create(&p, NULL);
  if (rv != APR_SUCCESS) {
    throw std::runtime_error("ACLRulesProvider::isAllowedToAccessApp: create apr_pool failed");
  }
  BOOST_SCOPE_EXIT((p)) {
    apr_pool_destroy(p);
  }BOOST_SCOPE_EXIT_END

  apr_uri_t parsed_proxy_uri;
  apr_uri_parse(p, url, &parsed_proxy_uri);

  boost::shared_ptr<App> app;
  apps_indexd_by_fixed_ip::const_iterator apps_itr
    = apps_[protocol].get<0>().find(parsed_proxy_uri.hostname);
  if (apps_itr != apps_[protocol].get<0>().end()) {
    BOOST_FOREACH(const boost::shared_ptr<App>& this_app, apps_itr->second) {
      if (this_app->isUrlMatchRegex(url)) {
        app = this_app;
        break;
      }
    }
  }

  if (!app) {
    BOOST_FOREACH(const boost::shared_ptr<App>& this_app, apps_[protocol].get<1>()) {
      if (this_app->isUrlMatchRegex(url)) {
        app = this_app;
        break;
      }
    }
  }

  if (!app) {
    LOG(LOG_NOTICE, NULL, "url(%s) matches NO apps", url);
    return false;
  }

  char ctime_buf[APR_CTIME_LEN] = {0};
  apr_ctime(ctime_buf, time);
  BOOST_FOREACH(int role_id, user_roles) {
    if (app->allow_roles.find(role_id) != app->allow_roles.end()) {
      if (!app->isTimeAllowed(role_id, time)) {
        LOG(LOG_NOTICE, NULL, "access time(%s) check failed for role_id(%d)", ctime_buf, role_id);
        continue;
      }
      if (!app->isIpAllowed(role_id, user_ip)) {
        LOG(LOG_NOTICE, NULL, "source IP(%s) check failed for role_id(%d)", user_ip, role_id);
        continue;
      }
      return true;
    } else {
      LOG(LOG_NOTICE, NULL, "url(%s) matches app(%s), but role_id(%d) is NOT allowed", url, app->app_name.c_str(), role_id);
    }
  }
  LOG(LOG_NOTICE, NULL, "url(%s) matches app(%s) but failed in matching any ACL rules", url, app->app_name.c_str());
  return false;
}

} /* namespace detail */
} /* namespace mod_passauth */

ext: cpp


text:
#define BOOST_TEST_MODULE whatwg_dom_test_module
#include <boost/test/unit_test.hpp>

max_stars_repo_name: wordring/wordring

max_issues_repo_name: wordring/libwordring

max_forks_repo_name: wordring/libwordring


text: #include <boost/log/utility/manipulators/add_value.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef MLT_UTILS_LINEAR_ALGEBRA_HPP
#define MLT_UTILS_LINEAR_ALGEBRA_HPP

#include <algorithm>
#include <limits>

#include <Eigen/Core>
#include <Eigen/SVD>

#include "../defs.hpp"

namespace mlt {
namespace utils {
namespace linear_algebra {
	// Moore-Penrose pseudoinverse
	inline auto pseudo_inverse(MatrixXdRef x) {
		auto svd = x.jacobiSvd(ComputeThinU | ComputeThinV);

		auto tolerance = numeric_limits<double>::epsilon() * max(x.rows(), x.cols()) * svd.singularValues().maxCoeff();

		return (svd.matrixV() * svd.singularValues().unaryExpr([=](double s) { return (s < tolerance) ? 0 : 1 / s; }).eval().asDiagonal() * svd.matrixU().transpose()).eval();
	}

	inline auto covariance(MatrixXdRef x, MatrixXdRef y) {
		assert(x.cols() == y.cols());
		const auto num_observations = static_cast<double>(x.cols());
		return ((x.colwise() - (x.rowwise().sum() / num_observations)) * (y.colwise() - (y.rowwise().sum() / num_observations)).transpose() / num_observations).eval();
	}

	inline auto linear_transformation(MatrixXdRef x, MatrixXdRef w) {
		return (w * x).eval();
	}

	inline auto linear_transformation(MatrixXdRef x, MatrixXdRef w, VectorXdRef b) {
		return ((w * x).colwise() + b).eval();
	}
}
}
}
#endif

max_stars_repo_name: fedeallocati/MachineLearningToolkit

max_issues_repo_name: fedeallocati/MachineLearningToolkit

max_forks_repo_name: fedeallocati/MachineLearningToolkit


text:
#include "Planning.hpp"
#include "PDDLPlannerInterface.hpp"
#include "planners/Lama.hpp"
#include "planners/Bfsf.hpp"
#include "planners/Uniform.hpp"
#include "planners/Randward.hpp"
#include "planners/Cedalion.hpp"
#include "planners/ArvandHerd.hpp"
#include "planners/FastDownward.hpp"

#include <boost/assign/list_of.hpp>
#include <boost/assign.hpp>
#include <base-logging/Logging.hpp>

namespace pddl_planner
{

size_t Planning::DEFAULT_TIMEOUT_IN_S = 3600;

Planning::Planning()
{
    mPlanners =
         {
                    {"LAMA", dynamic_cast<pddl_planner::PDDLPlannerInterface*>(new pddl_planner::lama::Planner())},
                    {"BFSF", new pddl_planner::bfsf::Planner()},
                    {"UNIFORM", new pddl_planner::uniform::Planner()},
                    {"CEDALION", new pddl_planner::cedalion::Planner()},
                    {"RANDWARD", new pddl_planner::randward::Planner()},
                    {"ARVANDHERD", new pddl_planner::arvandherd::Planner()},
                    {"FDSS1", new pddl_planner::fast_downward::Planner("sas_plan", "seq-sat-fdss-1")},
                    {"FDSS2", new pddl_planner::fast_downward::Planner("sas_plan", "seq-sat-fdss-2")},
                    {"LAMA2011", new pddl_planner::fast_downward::Planner("sas_plan", "seq-sat-lama-2011")},
                    {"FDAUTOTUNE2", new pddl_planner::fast_downward::Planner("sas_plan", "seq-sat-fd-autotune-2")},
                    {"FDAUTOTUNE1", new pddl_planner::fast_downward::Planner("sas_plan", "seq-sat-fd-autotune-1")}
        };
}

Planning::~Planning()
{
    PlannerMap::iterator it = mPlanners.begin();
    for(; it != mPlanners.end(); ++it)
    {
        delete it->second;
        it->second = NULL;
    }
}

std::set<std::string> Planning::getAvailablePlanners() const
{
    std::set<std::string> result;
    PlannerMap::const_iterator it = mPlanners.begin();
    for(; it != mPlanners.end(); ++it)
    {
        PDDLPlannerInterface* planner = it->second;
        if(planner->isAvailable())
        {
            result.insert(it->first);
        }
    }
    return result;
}

void Planning::registerPlanner(PDDLPlannerInterface* planner)
{
    if(!planner)
    {
        throw std::runtime_error("pddl_planner::Planning: planner object is null!");
    }

    std::string name = planner->getName();

    try {
        getPlanner(name);
        throw std::runtime_error("pddl_planner::Planning: planner with name '" + name + "' is already registered");
    } catch(const std::runtime_error& )
    {
        mPlanners[name] = planner;
    }
}

PDDLPlannerInterface* Planning::getPlanner(const std::string& name) const
{
    std::map<std::string, PDDLPlannerInterface*>::const_iterator it = mPlanners.find(name);
    if(it != mPlanners.end())
    {
        return it->second;
    }
    throw std::runtime_error("pddl_planner::Planning: planner with name '" + name + "' does not exist");
}

PlannerList Planning::getRegisteredPlanners() const
{
    PlannerList planners;
    PlannerMap::const_iterator cit = mPlanners.begin();
    for(; cit != mPlanners.end(); ++cit)
    {
        planners.push_back(cit->second);
    }

    return planners;
}

void Planning::setActionDescription(const std::string& action, const std::string& description)
{
    mActionDescriptions[action] = description;
}

void Planning::setDomainDescription(const std::string& domain, const std::string& description)
{
    mDomainDescriptions[domain] = description;
}

std::string Planning::getActionDescriptions() const
{
    std::string actionDescriptions;
    ActionDescriptions::const_iterator it = mActionDescriptions.begin();
    for(; it != mActionDescriptions.end(); ++it)
    {
        actionDescriptions += it->second + "\n";
    }
    return actionDescriptions;
}

std::string Planning::getDomainDescriptions() const
{
    std::string domainDescriptions;
    DomainDescriptions::const_iterator it = mDomainDescriptions.begin();
    for(; it != mDomainDescriptions.end(); ++it)
    {
        domainDescriptions += it->second + "\n";
    }
    return domainDescriptions;
}

void run_planner(const std::string & plannerName, const std::string& problem, const std::string& actionDescriptions, const std::string& domainDescriptions, Planning * planning, double timeout)
{
    PDDLPlannerInterface* planner;
    {
        boost::unique_lock<boost::mutex> scoped_lock(planning->mPlannerMutex);
        planner = planning->getPlanner(plannerName);
    }
    pddl_planner::PlanCandidates planCandidates = planner->plan(problem, actionDescriptions, domainDescriptions, timeout);
    boost::unique_lock<boost::mutex> scoped_lock(planning->mResultMutex);
    planning->mPlanResultList.push_back(std::pair<PlannerName, PlanCandidates> (plannerName, planCandidates));
}

PlanResultList Planning::plan(const std::string& problem, const std::set<std::string>& planners, bool sequential, double timeout)
{
    std::string actionDescriptions = getActionDescriptions();
    std::string domainDescriptions = getDomainDescriptions();
    LOG_DEBUG_S << (sequential ? "Sequential " : "") << "Planning requested: " << std::endl
        << "-DOMAIN-" << std::endl << domainDescriptions
        << "-PROBLEM-" << std::endl << problem;

    if(sequential)
    {
        long size;
        char* buf;
        char* dirname_ptr;
        size = pathconf(".", _PC_PATH_MAX);
        if ((buf = (char *)malloc((size_t)size)) == NULL)
        {
            fprintf(stderr, "Error allocating buffer memory.\n%s\n", strerror(errno));
            exit(1);
        }
        dirname_ptr = getcwd(buf, (size_t)size);

        for(std::set<std::string>::const_iterator it = planners.begin(); planners.end() != it; ++it)
        {
            std::string planner_name = (*it);
            PDDLPlannerInterface* planner = getPlanner(planner_name);

            PlanCandidates planCandidates = planner->plan(problem, actionDescriptions, domainDescriptions, timeout);

            std::pair<PlannerName, PlanCandidates> solution(planner_name, planCandidates);
            mPlanResultList.push_back(solution);
        }

        if(dirname_ptr)
        {
            free(dirname_ptr);
        }
    }
    else
    {
        std::set<std::string>::const_iterator it = planners.begin();
        for(; it != planners.end(); ++it)
        {
            mPlanRunners.push_back(new boost::thread(run_planner, (*it), problem, actionDescriptions, domainDescriptions, this, timeout));
        }
        std::vector<boost::thread *>::iterator itt = mPlanRunners.begin();
        for(; itt != mPlanRunners.end(); ++itt)
        {
            (*itt)->join();
            delete (*itt);
        }
    }
    return mPlanResultList;
}

PlanCandidates Planning::plan(const std::string& problem, const std::string& plannerName, double timeout)
{
    LOG_DEBUG_S << "Planning requested: " << std::endl
        << "-DOMAIN-" << std::endl << getDomainDescriptions()
        << "-PROBLEM-" << std::endl << problem;
    PDDLPlannerInterface* planner = getPlanner(plannerName);
    return planner->plan(problem, getActionDescriptions(), getDomainDescriptions(), timeout);
}

PlanResultList Planning::plan(const representation::Problem& problem, const std::set<std::string>& planners, bool sequential, double timeout)
{
    setDomainDescription(problem.domain.name, problem.domain.toLISP());
    return plan(problem.toLISP(), planners, sequential, timeout);
}

PlanResultList Planning::plan(const representation::Domain& domain, const representation::Problem& problem, const std::set<std::string>& planners, bool sequential, double timeout)
{
    setDomainDescription(domain.name, domain.toLISP());
    return plan(problem.toLISP(), planners, sequential, timeout);
}

PlanCandidates Planning::plan(const representation::Problem& problem, const std::string& plannerName, double timeout)
{
    setDomainDescription(problem.domain.name, problem.domain.toLISP());
    return plan(problem.toLISP(), plannerName, timeout);
}

PlanCandidates Planning::plan(const representation::Domain& domain, const representation::Problem& problem, const std::string& plannerName, double timeout)
{
    setDomainDescription(domain.name, domain.toLISP());
    return plan(problem.toLISP(), plannerName, timeout);
}

}


text:
#include <iostream>
#include <string>

#include <boost/io/quoted.hpp>

int main() {
  std::string buffer;
  std::getline(std::cin, buffer);
  std::cout << boost::io::quoted(buffer, '\\', '"') << '\n';
}

/*
* Input: C:\Program Files
* Output: "C:\\Program Files"
*
* Input: {"name":"UMU618","male":true}
* Output: "{\"name\":\"UMU618\",\"male\":true}"
*/


text:
// WARNING! leaf/preload.hpp is deprecated!
// WARNING! leaf/preload.hpp is deprecated!
// WARNING! leaf/preload.hpp is deprecated!

#ifndef BOOST_LEAF_PRELOAD_HPP_INCLUDED
#define BOOST_LEAF_PRELOAD_HPP_INCLUDED

// Copyright (c) 2018-2020 Emil Dotchevski and Reverge Studios, Inc.

// 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 <boost/leaf/on_error.hpp>

namespace boost { namespace leaf {

	template <class... Item>
	BOOST_LEAF_NODISCARD BOOST_LEAF_CONSTEXPR inline leaf_detail::preloaded<typename leaf_detail::deduce_item_type<Item>::type...> preload( Item && ... i )
	{
		return leaf_detail::preloaded<typename leaf_detail::deduce_item_type<Item>::type...>(std::forward<Item>(i)...);
	}

	template <class... Item>
	BOOST_LEAF_NODISCARD BOOST_LEAF_CONSTEXPR inline leaf_detail::preloaded<typename leaf_detail::deduce_item_type<Item>::type...> defer( Item && ... i )
	{
		return leaf_detail::preloaded<typename leaf_detail::deduce_item_type<Item>::type...>(std::forward<Item>(i)...);
	}

} }

#endif


text:
/*
 * Copyright 2021 MusicScience37 (Kenta Kabashima)
 *
 * 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.
 */
/*!
 * \file
 * \brief Test of euclidean_distance class.
 */
#include "num_collect/interp/kernel/euclidean_distance.h"

#include <Eigen/Core>
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers_floating.hpp>

TEST_CASE("num_collect::interp::kernel::euclidean_distance") {
    using num_collect::interp::kernel::euclidean_distance;

    SECTION("calculate distance of double") {
        const auto dist = euclidean_distance<double>();
        constexpr double var1 = 1.234;
        constexpr double var2 = 3.1415;
        constexpr double expected = var2 - var1;
        REQUIRE_THAT(dist(var1, var2), Catch::Matchers::WithinRel(expected));
        REQUIRE_THAT(dist(var2, var1), Catch::Matchers::WithinRel(expected));
    }

    SECTION("calculate distance of vectors") {
        const auto dist = euclidean_distance<Eigen::Vector3d>();
        const auto var1 = Eigen::Vector3d(1.234, 2.345, 3.456);
        const auto var2 = Eigen::Vector3d(1.357, 2.468, 3.579);
        const double expected = (var1 - var2).norm();
        REQUIRE_THAT(dist(var1, var2), Catch::Matchers::WithinRel(expected));
        REQUIRE_THAT(dist(var2, var1), Catch::Matchers::WithinRel(expected));
    }
}


text:
//
//  main.cpp
//
//  Created by r. on 08/05/14
//

// Compile with something like
//
//	g++ $STANDARD main.cpp ../test/multivector_AWT.cpp $INCLUDES $LIBPATHS $LINKLIBS $COMPFLAG
//
// where
//
//	$STANDARD = -std=c++11
//	$INCLUDES = -I/usr/lib64/mpi/gcc/openmpi/include/
//	$LIBPATHS = -L/usr/lib64/mpi/gcc/openmpi/lib64/
//	$LINKLIBS = -lmpi -lmpi_cxx -lboost_mpi-mt -lboost_serialization-mt
//	$COMPFLAG = -D_GLIBCXX_USE_NANOSLEEP -O1

#include <boost/mpi.hpp>
#include <iostream>

#include "../include/stopwatch.hpp"
namespace stopwatch
{
	std::map<std::string, StopWatch> watches;
}

// From some linked file
extern void test();

// Entry point
int main()
{
	#ifdef BOOST_MPI_HPP
	boost::mpi::environment mpienv;

	test();

	// Report
	{
		using namespace std;
		boost::mpi::communicator world;
		for (unsigned int r = 0; r != world.size(); ++r)
		{
			cout.flush(); world.barrier();
			if (r != world.rank()) continue;

			cout << "Proc #" << r << ":" << endl;
			stopwatch::StopWatch::report(stopwatch::watches);
		}
	}
	#else
	test();
	stopwatch::StopWatch::report(stopwatch::watches);
	#endif

    return EXIT_SUCCESS;
}

max_stars_repo_name: numpde/parabolic

max_issues_repo_name: numpde/parabolic

max_forks_repo_name: numpde/parabolic


text:
//==================================================================================================
/*!

  Copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#include <boost/simd/function/scalar/is_inf.hpp>
#include <scalar_test.hpp>
#include <boost/simd/detail/dispatch/meta/as_integer.hpp>
#include <boost/simd/constant/inf.hpp>
#include <boost/simd/constant/minf.hpp>
#include <boost/simd/constant/mone.hpp>
#include <boost/simd/constant/nan.hpp>
#include <boost/simd/constant/one.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/constant/half.hpp>
#include <boost/simd/constant/quarter.hpp>
#include <boost/simd/constant/two.hpp>
#include <boost/simd/logical.hpp>

STF_CASE_TPL (" is_inf real",  STF_IEEE_TYPES)
{
  namespace bs = boost::simd;
  namespace bd = boost::dispatch;
  using bs::is_inf;
  using r_t = decltype(is_inf(T()));

  // return type conformity test
  STF_TYPE_IS(r_t, bs::logical<T>);

  // specific values tests
#ifndef BOOST_SIMD_NO_INVALIDS
  STF_EQUAL(is_inf(bs::Inf<T>()), r_t(true));
  STF_EQUAL(is_inf(bs::Minf<T>()), r_t(true));
  STF_EQUAL(is_inf(bs::Nan<T>()), r_t(false));
#endif
  STF_EQUAL(is_inf(-bs::Zero<T>()), r_t(false));
  STF_EQUAL(is_inf(bs::Half<T>()), r_t(false));
  STF_EQUAL(is_inf(bs::Mone<T>()), r_t(false));
  STF_EQUAL(is_inf(bs::One<T>()), r_t(false));
  STF_EQUAL(is_inf(bs::Quarter<T>()), r_t(false));
  STF_EQUAL(is_inf(bs::Two<T>()), r_t(false));
  STF_EQUAL(is_inf(bs::Zero<T>()), r_t(false));
}

STF_CASE_TPL (" is_inf signed_int",  STF_SIGNED_INTEGRAL_TYPES)
{
  namespace bs = boost::simd;
  namespace bd = boost::dispatch;
  using bs::is_inf;
  using r_t = decltype(is_inf(T()));

  // return type conformity test
  STF_TYPE_IS(r_t, bs::logical<T>);

  // specific values tests
  STF_EQUAL(is_inf(bs::Mone<T>()), r_t(false));
  STF_EQUAL(is_inf(bs::One<T>()), r_t(false));
  STF_EQUAL(is_inf(bs::Two<T>()), r_t(false));
  STF_EQUAL(is_inf(bs::Zero<T>()), r_t(false));
}

STF_CASE_TPL (" is_inf unsigned_int",  STF_UNSIGNED_INTEGRAL_TYPES)
{
  namespace bs = boost::simd;
  namespace bd = boost::dispatch;
  using bs::is_inf;
  using r_t = decltype(is_inf(T()));

  // return type conformity test
  STF_TYPE_IS(r_t, bs::logical<T>);

  // specific values tests
  STF_EQUAL(is_inf(bs::One<T>()), r_t(false));
  STF_EQUAL(is_inf(bs::Two<T>()), r_t(false));
  STF_EQUAL(is_inf(bs::Zero<T>()), r_t(false));
}

STF_CASE ( "is_inf bool")
{
  namespace bs = boost::simd;
  namespace bd = boost::dispatch;
  using bs::is_inf;
  using r_t = decltype(is_inf(bool()));

  // return type conformity test
  STF_TYPE_IS(r_t, bool);

  // specific values tests
  STF_EQUAL(is_inf(true), false);
  STF_EQUAL(is_inf(false), false);
}


text:
#include "SGFitLeastSquares.h"
#include <Eigen/Eigen>
#include <Eigen/nnls.h>

namespace Probulator
{
	SgBasis sgFitLeastSquares(const SgBasis& basis, const std::vector<RadianceSample>& samples)
	{
		using namespace Eigen;
		SgBasis result = basis;

		MatrixXf A;
		A.resize(samples.size(), basis.size());
		for (u64 sampleIt = 0; sampleIt < samples.size(); ++sampleIt)
		{
			for (u64 lobeIt = 0; lobeIt < basis.size(); ++lobeIt)
			{
				A(sampleIt, lobeIt) = sgEvaluate(basis[lobeIt].p, basis[lobeIt].lambda, samples[sampleIt].direction);
			}
		}

		for (u32 channelIt = 0; channelIt < 3; ++channelIt)
		{
			VectorXf b;
			b.resize(samples.size());
			for (u64 sampleIt = 0; sampleIt < samples.size(); ++sampleIt)
			{
				b[sampleIt] = samples[sampleIt].value[channelIt];
			}

			VectorXf x = A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b);
			for (u64 lobeIt = 0; lobeIt < basis.size(); ++lobeIt)
			{
				result[lobeIt].mu[channelIt] = x[lobeIt];
			}
		}

		return result;
	}

	// Non-negative version of least squares
	SgBasis sgFitNNLeastSquares(const SgBasis& basis, const std::vector<RadianceSample>& samples)
	{
		using namespace Eigen;
		SgBasis result = basis;

		MatrixXf A;
		A.resize(samples.size(), basis.size());
		for (u64 sampleIt = 0; sampleIt < samples.size(); ++sampleIt)
		{
			for (u64 lobeIt = 0; lobeIt < basis.size(); ++lobeIt)
			{
				A(sampleIt, lobeIt) = sgEvaluate(basis[lobeIt].p, basis[lobeIt].lambda, samples[sampleIt].direction);
			}
		}

		NNLS<MatrixXf> nnlssolver(A);
		for (u32 channelIt = 0; channelIt < 3; ++channelIt)
		{
			VectorXf b;
			b.resize(samples.size());
			for (u64 sampleIt = 0; sampleIt < samples.size(); ++sampleIt)
			{
				b[sampleIt] = samples[sampleIt].value[channelIt];
			}

			// -- run the solver
			nnlssolver.solve(b);
			VectorXf x = nnlssolver.x();

			for (u64 lobeIt = 0; lobeIt < basis.size(); ++lobeIt)
			{
				result[lobeIt].mu[channelIt] = x[lobeIt];
			}
		}

		return result;
	}
}

max_stars_repo_name: kayru/Probulator

max_issues_repo_name: kayru/Probulator

max_forks_repo_name: kayru/Probulator


text:
/*
Test RS code over binary extension field
*/

#include <iostream>
#include <fstream>
#include <vector>
#include <boost/program_options.hpp>
#include "../include/PFE.hpp"
#include "../include/EFE.hpp"
#include "../include/DFT.hpp"
#include "../include/helpers.hpp"
#include "../include/GF2M.hpp"
//#include "../include/encodedecode.hpp"
#include "../include/ReedSolomon.hpp"
#include <string>
#include <fstream>
#include <streambuf>
#include <random>
#include <chrono>

using namespace std;

// define static variables

typedef GF2 pfe;
template<> polynomial<pfe> EFE<pfe>::prim_poly = polynomial<pfe>();
template<> unsigned EFE<pfe>::m = 30;

int main(int ac, char* av[])
{

// randomness
random_device r;
default_random_engine gen(r());
uniform_int_distribution<int> randbit(0, 1);
uniform_int_distribution<int> randint(0, 16383);

// parameters
const unsigned M = 50000;
//const unsigned Q = 127;
//const unsigned P = 129;
const unsigned Q = 127;
const unsigned P = 337;
const unsigned n = P*Q; // 2^14 - 1
//const unsigned k = 13926; // k = 0.85*n
const unsigned k = 36379; // k = 0.85*n

///// GF2M definitions
/*
const unsigned prim_poly = 16553;
const unsigned m = 14;
typedef GF2M<unsigned,m,prim_poly> gf;
// efe a = efe(34); // 32 + 2 = 100010 = x + x^5
gf fa = gf(66,0); // 64 + 2 = 1000010 = x + x^5
*/

const uint_least64_t prim_poly = 4399239010919;
const unsigned m = 42;
typedef GF2M<uint_least64_t,m,prim_poly> gf;
// efe a = efe(34); // 32 + 2 = 100010 = x + x^5
gf fa = gf(1935755,0); // 64 + 2 = 1000010 = x + x^5

cout << "primitive polynomial: " << bitset<64>(prim_poly) << endl;
cout << "                      " << bitset<64>( ((uint_least64_t)1 << m) ) << endl;
cout << "order of a: " << fa.order() << endl;

DFT_FFT<gf> dftgf(n,fa,P,Q); // Fourier transform for the outer code
// Does the DFT work?
vector<gf> ct_ = vector<gf>(n);
for(gf& el:ct_)
	el = gf(randint(gen),0); // random vector
ct_[3] = gf(0);
vector<gf> C_, hatc_;
cout << ct_.size() << " " << ct_[0] << endl;
dftgf.dft(ct_,C_);
dftgf.idft(hatc_,C_);
if(hatc_ == ct_)
	cout << "DFT works!" << endl;
else
	cout << "DFT failed." << endl;

RScode<gf,DFT_FFT<gf>> outercode(n,k,fa,dftgf);

///// EFE version

/*
typedef EFE<pfe> gf;
typedef EFE<pfe> efe;
EFE<pfe>::m = 14;
// initialize the primitive polynomial
// x^14 + x^7 + x^5 + x^3 + 1
pfe ppvv[m+1] = {1,0,0,1,0,1,0,1,0,0,0,0,0,0,1}; // for m=14
vector<pfe> ppv(ppvv, ppvv+m+1);
EFE<pfe>::prim_poly = polynomial<pfe>(ppv);
// initialize the element of order n, the Fourier kernel
pfe aa[m] = {0,1,0,0,0,0,1,0,0,0,0,0,0,0}; // element of order 2^14-1
vector<pfe> avv(aa, aa+m); //
efe a = efe(avv); // this is an element of order n
DFT_FFT<gf> dftefe(n,a,P,Q); // Fourier transform for the outer code

RScode<gf,DFT_FFT<efe>> outercode(n,k,a,dftefe);
*/

///// test the outer code

// generate information

vector<gf> infvec(outercode.k); // information vector;
for(gf& el: infvec)
	el = gf(randbit(gen));

// encode

vector<gf> c; // outer codeword
outercode.RSencode(infvec,c);

// disturb

float errorprob = 0.01;
float erasureprob = 0.1;
bernoulli_distribution bern(errorprob);
bernoulli_distribution eras(erasureprob);

int errctr = 0;
int eractr = 0;
for(gf& s : c){
	if( bern(gen) ){
		// generated random efe
		//vector<pfe> rsymbol(m);
		//for(pfe& el : rsymbol)
		//	el = pfe( randbit(gen) );
		//s = efe(rsymbol);
		s = gf(randint(gen));
		//cout << rsymbol << endl;
		errctr++;
	} else if( eras(gen) ){
		s = gf();
		eractr++;
	}
}

cout << "inserted " << errctr << " errors and " << eractr << " erasures" << endl;
cout << "should be able to correct " << (n - k) / 2 << " errors" << endl;

// decoding

auto t1 = chrono::high_resolution_clock::now();
vector<gf> infvecrec;
pair<unsigned,unsigned> erctroc = outercode.RS_decode_spec(infvecrec,c);
auto t2 = chrono::high_resolution_clock::now();
cout << "decoding took "
     << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
     << " milliseconds\n";

cout << "outer code: " << erctroc.first << " errasures, " << erctroc.second << " errors corrected"<< endl;

if( infvec ==  infvecrec)
	cout << "I did correct all errors!" << endl;
else
	cout << "I couldn't correct all errors!" << endl;

}


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#include "runtime/small_file_mgr.h"

#include <stdint.h>
#include <stdio.h>
#include <sstream>

#include <boost/algorithm/string/predicate.hpp> // boost::algorithm::starts_with
#include <boost/algorithm/string/classification.hpp> // boost::is_any_of

#include "gutil/strings/split.h"

#include "common/status.h"
#include "env/env.h"
#include "gen_cpp/HeartbeatService.h"
#include "http/http_client.h"
#include "runtime/exec_env.h"
#include "util/doris_metrics.h"
#include "util/file_utils.h"
#include "util/md5.h"

namespace doris {

SmallFileMgr::SmallFileMgr(
        ExecEnv* env,
        const std::string& local_path) :
    _exec_env(env),
    _local_path(local_path) {
    REGISTER_GAUGE_DORIS_METRIC(small_file_cache_count, [this]() {
        std::lock_guard<std::mutex> l(_lock);
        return _file_cache.size();
    });
}

SmallFileMgr::~SmallFileMgr() {
}

Status SmallFileMgr::init() {
    RETURN_IF_ERROR(_load_local_files());
    return Status::OK();
}

Status SmallFileMgr::_load_local_files() {
    RETURN_IF_ERROR(FileUtils::create_dir(_local_path));

    auto scan_cb = [this] (const char* file) {
        if (is_dot_or_dotdot(file)) {
            return true;
        }
        auto st = _load_single_file(_local_path, file);
        if (!st.ok()) {
            LOG(WARNING) << "load small file failed: " << st.get_error_msg();
        }
        return true;
    };

    RETURN_IF_ERROR(Env::Default()->iterate_dir(_local_path, scan_cb));
    return Status::OK();
}

Status SmallFileMgr::_load_single_file(
        const std::string& path,
        const std::string& file_name) {
    // file name format should be like:
    // file_id.md5
    std::vector<std::string> parts = strings::Split(file_name, ".");
    if (parts.size() != 2) {
        return Status::InternalError("Not a valid file name: " + file_name);
    }
    int64_t file_id = std::stol(parts[0]);
    std::string md5 = parts[1];

    if (_file_cache.find(file_id) != _file_cache.end()) {
        return Status::InternalError("File with same id is already been loaded: " + file_id);
    }

    std::string file_md5;
    RETURN_IF_ERROR(FileUtils::md5sum(path + "/" + file_name, &file_md5));
    if (file_md5 != md5) {
        return Status::InternalError("Invalid md5 of file: " + file_name);
    }

    CacheEntry entry;
    entry.path = path + "/" + file_name;
    entry.md5 = file_md5;

    _file_cache.emplace(file_id, entry);
    return Status::OK();
}

Status SmallFileMgr::get_file(
        int64_t file_id,
        const std::string& md5,
        std::string* file_path) {

    std::unique_lock<std::mutex> l(_lock);
    // find in cache
    auto it = _file_cache.find(file_id);
    if (it != _file_cache.end()) {
        // find the cached file, check it
        CacheEntry& entry = it->second;
        Status st = _check_file(entry, md5);
        if (!st.ok()) {
            // check file failed, we should remove this cache and download it from FE again
            if (remove(entry.path.c_str()) != 0) {
                std::stringstream ss;
                ss << "failed to remove file: " << file_id << ", err: "<< std::strerror(errno);
                return Status::InternalError(ss.str());
            }
            _file_cache.erase(it);
        } else {
            // check ok, return the path
            *file_path = entry.path;
            return Status::OK();
        }
    }

    // file not found in cache. download it from FE
    RETURN_IF_ERROR(_download_file(file_id, md5, file_path));

    return Status::OK();
}

Status SmallFileMgr::_check_file(const CacheEntry& entry, const std::string& md5) {
    if (!FileUtils::check_exist(entry.path)) {
        return Status::InternalError("file not exist");
    }
    if (!boost::iequals(md5, entry.md5)) {
        return Status::InternalError("invalid MD5");
    }
    return Status::OK();
}

Status SmallFileMgr::_download_file(
        int64_t file_id,
        const std::string& md5,
        std::string* file_path) {

    std::stringstream ss;
    ss << _local_path << "/" << file_id << ".tmp";
    std::string tmp_file = ss.str();
    bool should_delete = true;
    auto fp_closer = [&tmp_file, &should_delete] (FILE* fp) {
        fclose(fp);
        if (should_delete) remove(tmp_file.c_str());
    };

    std::unique_ptr<FILE, decltype(fp_closer)> fp(fopen(tmp_file.c_str(), "w"), fp_closer);
    if (fp == nullptr) {
        LOG(WARNING) << "fail to open file, file=" << tmp_file;
        return Status::InternalError("fail to open file");
    }

    HttpClient client;

    std::stringstream url_ss;
    TMasterInfo* master_info = _exec_env->master_info();
    url_ss << master_info->network_address.hostname << ":" << master_info->http_port << "/api/get_small_file?"
        << "file_id=" << file_id << "&token=" << master_info->token;

    std::string url = url_ss.str();

    LOG(INFO) << "download file from: " << url;

    RETURN_IF_ERROR(client.init(url));
    Status status;
    Md5Digest digest;
    auto download_cb = [&status, &tmp_file, &fp, &digest] (const void* data, size_t length) {
        digest.update(data, length);
        auto res = fwrite(data, length, 1, fp.get());
        if (res != 1) {
            LOG(WARNING) << "fail to write data to file, file=" << tmp_file
                << ", error=" << ferror(fp.get());
            status = Status::InternalError("fail to write data when download");
            return false;
        }
        return true;
    };
    RETURN_IF_ERROR(client.execute(download_cb));
    RETURN_IF_ERROR(status);
    digest.digest();

    if (!boost::iequals(digest.hex(), md5)) {
        LOG(WARNING) << "file's checksum is not equal, download: " << digest.hex()
            << ", expected: " << md5 << ", file: " << file_id;
        return Status::InternalError("download with invalid md5");
    }

    // close this file
    should_delete = false;
    fp.reset();

    // rename temporary file to library file
    std::stringstream real_ss;
    real_ss << _local_path << "/" << file_id << "." << md5;
    std::string real_file_path = real_ss.str();
    auto ret = rename(tmp_file.c_str(), real_file_path.c_str());
    if (ret != 0) {
        char buf[64];
        LOG(WARNING) << "fail to rename file from=" << tmp_file << ", to=" << real_file_path
            << ", errno=" << errno << ", errmsg=" << strerror_r(errno, buf, 64);
        remove(tmp_file.c_str());
        remove(real_file_path.c_str());
        return Status::InternalError("fail to rename file");
    }

    // add to file cache
    CacheEntry entry;
    entry.path = real_file_path;
    entry.md5 = md5;
    _file_cache.emplace(file_id, entry);

    *file_path = real_file_path;

    LOG(INFO) << "finished to download file: " << file_path;
    return Status::OK();
}

} // end namespace doris

max_stars_repo_name: amosbird/incubator-doris


text:
//
// Created by mathis on 28/02/2020.
//

#ifndef DAFT_ENGINE_OBB_HPP
#define DAFT_ENGINE_OBB_HPP

#include <Eigen/Core>
#include <Eigen/Geometry>
#include <opengl_stuff.h>

#include <Utils/types.hpp>
#include <src/Utils/adapters.hpp>

/**
 * Oriented Bounding Box.
 * A Bounding Box that rotate with the affiliated object
 */
class Obb
{
  public:
    /** type of axis for obb planes */
    enum AxisType { X = 0, Y, Z };

    /** Default constructor.
     * creates an untransformed obb.
     */
    Obb() : m_aabb(), m_transform{Utils::Transform::Identity()} {}

    /** Constructor.
     *
     * @param aabb - AABB of the affiliated object.
     * @param transform - transformation of the object.
     */
    Obb( const Utils::Aabb& aabb, const Utils::Transform& transform ) :
        m_aabb{aabb},
        m_transform{transform} {}

    /** untransformed aabb min getter.
     *
     * @return aabb min.
     */
    glm::vec3 min() const { return toGlm( m_aabb.min() ); }

    /** untransformed aabb max getter.
     *
     * @return aabb max.
     */
    glm::vec3 max() const { return toGlm( m_aabb.max() ); }

    /** obb's position getter.
     *
     * @return position of OBB.
     */
    glm::vec3 position() const;

    /** util function for the axis of obb's planes.
     *
     * @param i - index of the axis (0, 1, 2)
     * @return
     */
    glm::vec3 axis( int i ) const;
    glm::vec3 axis( AxisType i ) const { return axis( int( i ) ); }

  private:
    Utils::Aabb m_aabb;
    Utils::Transform m_transform;
};

#endif // DAFT_ENGINE_OBB_HPP

max_stars_repo_name: DaftMat/Draft-Engine

max_issues_repo_name: DaftMat/Draft-Engine

max_forks_repo_name: DaftMat/Draft-Engine


text:
//
// Created by yche on 12/25/17.
//
#include <cstdlib>

#include <chrono>
#include <iostream>

#include <boost/program_options.hpp>

#include "../../yche_refactor/bflpmc_yche.h"
#include "../../yche_refactor/simrank.h"
#include "../../util/random_pair_generator.h"
#include "../../playground/pretty_print.h"

void test_BFLPMC(string data_name, double c, double epsilon, double delta, int pair_num, int round, double r_max) {
    // init graph
    string path = get_edge_list_path(data_name);
    GraphYche g(path);
    size_t n = static_cast<size_t>(g.n);
    cout << n << endl;

    // init bflpmc object
    auto bflpmc = BFLPMC(data_name, g, c, epsilon, delta, r_max);

#ifdef GROUND_TRUTH
    TruthSim ts(data_name, g, c, epsilon);
    auto max_err = 0.0;
#endif

#ifdef GROUND_TRUTH_STATISTICS
    auto above_eps_count = 0;
    auto above_point1_count = 0;
    auto above_point2_count = 0;
    auto above_point3_count = 0;
    auto above_point4_count = 0;
    auto above_point5_count = 0;
    auto above_point6_count = 0;
    for (auto i = 0u; i < n; i++) {
        for (auto j = i; j < n; j++) {
            if (ts.sim(i, j) > 0.01) { above_eps_count++; }
            if (ts.sim(i, j) > 0.1) { above_point1_count++; }
            if (ts.sim(i, j) > 0.2) { above_point2_count++; }
            if (ts.sim(i, j) > 0.3) { above_point3_count++; }
            if (ts.sim(i, j) > 0.4) { above_point4_count++; }
            if (ts.sim(i, j) > 0.5) { above_point5_count++; }
            if (ts.sim(i, j) > 0.6) { above_point6_count++; }
        }
    }
    cout << "above eps:" << above_eps_count << endl;
    cout << "above 0.1 :" << above_point1_count << endl;
    cout << "above 0.2 :" << above_point2_count << endl;
    cout << "above 0.3 :" << above_point3_count << endl;
    cout << "above 0.4 :" << above_point4_count << endl;
    cout << "above 0.5 :" << above_point5_count << endl;
    cout << "above 0.6 :" << above_point6_count << endl;
#endif

    auto sample_pairs = read_sample_pairs(data_name, pair_num, round);
    auto clock_start = clock();
    auto start = std::chrono::high_resolution_clock::now();
#pragma omp parallel
    {
        auto local_bflpmc = bflpmc;
//        auto local_bflpmc = BFLPMC(data_name, g, c, epsilon, delta);

#ifdef GROUND_TRUTH
#pragma omp for reduction(max:max_err) schedule(dynamic, 100)
#else
#pragma omp for schedule(dynamic, 100)
#endif
        for (auto pair_i = 0; pair_i < pair_num; pair_i++) {
            auto q = pair<uint32_t, uint32_t>(sample_pairs[pair_i].first, sample_pairs[pair_i].second);
#ifdef GROUND_TRUTH
            auto res = local_bflpmc.query_one2one(q);
            max_err = max(max_err, abs(ts.sim(q.first, q.second) - res));
            if (abs(ts.sim(q.first, q.second) - res) > 0.01) {
#pragma omp critical
                cout << sample_pairs[pair_i].first << "," << sample_pairs[pair_i].second << ","
                << ts.sim(q.first, q.second) << "," << res << endl;
            }
#else
            local_bflpmc.query_one2one(q);
#endif
        }
    };

    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> elapsed = end - start;

    auto clock_end = clock();
    cout << "total query cpu time:" << static_cast<double>(clock_end - clock_start) / CLOCKS_PER_SEC << "s" << endl;
#ifdef GROUND_TRUTH
    cout << "max err:" << max_err << endl;
#endif
    cout << format("total query cost: %s s") % elapsed.count() << endl; // record the pre-processing time
}

int main(int args, char *argv[]) {
    string data_name(argv[1]);
    double c = 0.6;
    double epsilon = 0.01;
    double delta = 0.01;

    int pair_num = atoi(argv[2]);
    int round_i = atoi(argv[3]);
    double r_max = atof(argv[4]);
    test_BFLPMC(data_name, c, epsilon, delta, pair_num, round_i, r_max);
}

max_stars_repo_name: RapidsAtHKUST/SimRank

max_issues_repo_name: RapidsAtHKUST/SimRank

max_forks_repo_name: RapidsAtHKUST/SimRank


text:
#include <Interpreters/InterpreterCreateUserQuery.h>
#include <Interpreters/Context.h>
#include <Interpreters/InterpreterSetRoleQuery.h>
#include <Parsers/ASTCreateUserQuery.h>
#include <Access/AccessControlManager.h>
#include <Access/User.h>
#include <Access/GenericRoleSet.h>
#include <Access/AccessRightsContext.h>
#include <boost/range/algorithm/copy.hpp>

namespace DB
{
namespace ErrorCodes
{
    extern const int SET_NON_GRANTED_ROLE;
}

BlockIO InterpreterCreateUserQuery::execute()
{
    const auto & query = query_ptr->as<const ASTCreateUserQuery &>();
    auto & access_control = context.getAccessControlManager();
    context.checkAccess(query.alter ? AccessType::ALTER_USER : AccessType::CREATE_USER);

    GenericRoleSet * default_roles_from_query = nullptr;
    GenericRoleSet temp_role_set;
    if (query.default_roles)
    {
        default_roles_from_query = &temp_role_set;
        *default_roles_from_query = GenericRoleSet{*query.default_roles, access_control};
        if (!query.alter && !default_roles_from_query->all)
        {
            for (const UUID & role : default_roles_from_query->getMatchingIDs())
                context.getAccessRights()->checkAdminOption(role);
        }
    }

    if (query.alter)
    {
        auto update_func = [&](const AccessEntityPtr & entity) -> AccessEntityPtr
        {
            auto updated_user = typeid_cast<std::shared_ptr<User>>(entity->clone());
            updateUserFromQuery(*updated_user, query, default_roles_from_query);
            return updated_user;
        };
        if (query.if_exists)
        {
            if (auto id = access_control.find<User>(query.name))
                access_control.tryUpdate(*id, update_func);
        }
        else
            access_control.update(access_control.getID<User>(query.name), update_func);
    }
    else
    {
        auto new_user = std::make_shared<User>();
        updateUserFromQuery(*new_user, query, default_roles_from_query);

        if (query.if_not_exists)
            access_control.tryInsert(new_user);
        else if (query.or_replace)
            access_control.insertOrReplace(new_user);
        else
            access_control.insert(new_user);
    }

    return {};
}

void InterpreterCreateUserQuery::updateUserFromQuery(User & user, const ASTCreateUserQuery & query, const GenericRoleSet * default_roles_from_query)
{
    if (query.alter)
    {
        if (!query.new_name.empty())
            user.setName(query.new_name);
    }
    else
        user.setName(query.name);

    if (query.authentication)
        user.authentication = *query.authentication;

    if (query.hosts)
        user.allowed_client_hosts = *query.hosts;
    if (query.remove_hosts)
        user.allowed_client_hosts.remove(*query.remove_hosts);
    if (query.add_hosts)
        user.allowed_client_hosts.add(*query.add_hosts);

    if (default_roles_from_query)
    {
        if (!query.alter && !default_roles_from_query->all)
            boost::range::copy(default_roles_from_query->getMatchingIDs(), std::inserter(user.granted_roles, user.granted_roles.end()));

        InterpreterSetRoleQuery::updateUserSetDefaultRoles(user, *default_roles_from_query);
    }

    if (query.profile)
        user.profile = *query.profile;
}

}

max_stars_repo_name: leonthecoder/ClickHouse

max_issues_repo_name: leonthecoder/ClickHouse

max_forks_repo_name: leonthecoder/ClickHouse


text:
//  Copyright John Maddock 2007.
//  Use, modification and distribution are subject to 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)

// Note that this file contains quickbook mark-up as well as code
// and comments, don't change any of the special comment mark-ups!

//[policy_ref_snip8

#include <boost/math/distributions/negative_binomial.hpp>

using namespace boost::math;
using namespace boost::math::policies;

typedef negative_binomial_distribution<
      double,
      policy<discrete_quantile<integer_round_nearest> >
   > dist_type;

// Lower quantile rounded up:
double x = quantile(dist_type(20, 0.3), 0.05);
// Upper quantile rounded down:
double y = quantile(complement(dist_type(20, 0.3), 0.05));

//]

#include <iostream>

int main()
{
   std::cout << x << " " << y << std::endl;
}

max_stars_repo_name: zyiacas/boost-doc-zh

max_issues_repo_name: sdfict/boost-doc-zh

max_forks_repo_name: sdfict/boost-doc-zh


text:
#include "SignatureGraph.hpp"
#include "color.hpp"
#include "filesystem.hpp"
#include "orderPairs.hpp"
using namespace ChanZuckerberg::ExpressionMatrix2;

#include <boost/algorithm/string.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/iteration_macros.hpp>
#include "boost_lexical_cast.hpp"
#include <boost/math/constants/constants.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#include "fstream.hpp"
#include "stdexcept.hpp"
#include "utility.hpp"

// Given the vertices, create the edges.
void SignatureGraph::createEdges(size_t lshBitCount)
{
    SignatureGraph& graph = *this;

    // Loop over all vertices.
    BitSet signature1(lshBitCount);
    BGL_FORALL_VERTICES(v0, graph, SignatureGraph) {
        const SignatureGraphVertex& vertex0 = graph[v0];
        const BitSetPointer signature0 = vertex0.signature;

        // For each zero bit, add an edge to the vertex
        // with the same bit set to 1.
        for(size_t bit=0; bit!=lshBitCount; bit++) {
            if(vertex0.signature.get(bit) == 0) {
                signature1 = signature0;
                signature1.set(bit);
                const auto it1 = vertexMap.find(signature1);
                if(it1 != vertexMap.end()) {
                    const vertex_descriptor v1 = it1->second;
                    add_edge(v0, v1, graph);
                }
            }
        }

    }
}

// Write out the signature graph in Graphviz format.
void SignatureGraph::writeGraphviz(const string& fileName) const
{
    ofstream s(fileName);
    writeGraphviz(s);
}
void SignatureGraph::writeGraphviz(ostream& s) const
{
    Writer writer(*this);
    boost::write_graphviz(s, *this, writer, writer, writer);
}
SignatureGraph::Writer::Writer(const SignatureGraph& graph) :
    graph(graph)
{
}

void SignatureGraph::Writer::operator()(std::ostream& s) const
{
    // s << "size=100 ratio=expand;\n";
    s << "node [shape=point];\n";
    // s << "edge [style=invis];n"; // len=10 penwidth=0.1
}

// Write out a vertex of the cell graph.
void SignatureGraph::Writer::operator()(std::ostream& s, vertex_descriptor v) const
{
    const SignatureGraphVertex& vertex = graph[v];
    const double vertexSize = 1.e-2 * sqrt(double(vertex.cellCount()));

    s << "[";
    s << "width=" << vertexSize;
    s << "]";
}

void SignatureGraph::Writer::operator()(std::ostream& s, edge_descriptor e) const
{
    const vertex_descriptor v0 = source(e, graph);
    const vertex_descriptor v1 = source(e, graph);
    const SignatureGraphVertex& vertex0 = graph[v0];
    const SignatureGraphVertex& vertex1 = graph[v0];
    double edgeWeight = double(vertex0.cellCount()) * double(vertex1.cellCount());

    s << "[weight=\"" << edgeWeight << "\"]";
}

// Use Graphviz to compute the graph layout and store it in the vertex positions.
void SignatureGraph::computeLayout()
{
    if(layoutWasComputed) {
        return;
    }

    using filesystem::remove;

    // Write the graph in Graphviz format.
    const string uuid = boost::uuids::to_string(boost::uuids::uuid(boost::uuids::random_generator()()));
    const string dotFileName = "/dev/shm/SignatureGraph-" + uuid + ".dot";
    writeGraphviz(dotFileName);

    // Run sfdp with output in Graphviz plain format.
    // See https://www.graphviz.org/doc/info/output.html#d:plain.
    const string dotPlainFileName = dotFileName + ".plain";
    const int systemReturnCode = ::system(("sfdp -O -Tplain " + dotFileName).c_str());
    const int sfdpReturnCode = WEXITSTATUS(systemReturnCode);   // Man page for system is not super clear on this.
    if(sfdpReturnCode!=0 && sfdpReturnCode!=1) {    // Sfdp returns 1 if built without triangulation library.
        remove(dotFileName);
        remove(dotPlainFileName);
        throw runtime_error("Error " +
            std::to_string(systemReturnCode) + " " +
            std::to_string(sfdpReturnCode) +
            " running sfdp.");
    }

    // Extract vertex positions from the output.
    ifstream file(dotPlainFileName);
    string line;
    vector<string> tokens;
    while(true) {

        // Get a line.
        getline(file, line);
        if(!file) {
            break;
        }

        // Parse it.
        boost::algorithm::split(tokens, line, boost::algorithm::is_any_of(" "));

        // Only parse lines that describe vertices.
        CZI_ASSERT(tokens.size() >= 1);
        if(tokens[0] != "node") {
            continue;
        }
        CZI_ASSERT(tokens.size() >= 4);

        // Extract the positions for this vertex.
        try {
            const vertex_descriptor v = lexical_cast<vertex_descriptor>(tokens[1]);
            SignatureGraphVertex& vertex = (*this)[v];
            vertex.position[0] = lexical_cast<double>(tokens[2]);
            vertex.position[1] = lexical_cast<double>(tokens[3]);
        } catch(std::exception& e) {
            const string message = "Error processing the following line of " + dotPlainFileName + ": " +  line + "\nError is: " + e.what();
            throw runtime_error(message);
        }
    }
    layoutWasComputed = true;

    // Remove the files we created.
    remove(dotFileName);
    remove(dotPlainFileName);
}

// Write out the signature graph in Graphviz format.
void SignatureGraph::writeSvg(
    const string& fileName,
    SvgParameters& svgParameters)
{
    ofstream s(fileName);
    writeSvg(s, svgParameters);
}
void SignatureGraph::writeSvg(
    ostream& s,
    SvgParameters& svgParameters)
{
    // Make sure the layout was computed.
    computeLayout();

    // Compute minimum and maximum of the vertices coordinates,
    // and the maximum number of cells.
    double xMin = std::numeric_limits<double>::max();
    double xMax = std::numeric_limits<double>::min();
    double yMin = xMin;
    double yMax = xMax;
    CellId maxCellCount = 0;
    const SignatureGraph& graph = *this;
    BGL_FORALL_VERTICES(v, graph, SignatureGraph) {
        const SignatureGraphVertex& vertex = graph[v];
        const double x = vertex.position[0];
        const double y = vertex.position[1];
        xMin = min(xMin, x);
        xMax = max(xMax, x);
        yMin = min(yMin, y);
        yMax = max(yMax, y);
        maxCellCount = max(maxCellCount, CellId(vertex.cellCount()));
    }

    // Center and size of the square bounding box containing all the vertices.
    const double xBoundingBoxCenter = (xMin + xMax) / 2.;
    const double yBoundingBoxCenter = (yMin + yMax) / 2.;
    const double xBoundingBoxSize = xMax - xMin;
    const double yBoundingBoxSize = yMax - yMin;
    const double boundingBoxSize = max(xBoundingBoxSize, yBoundingBoxSize);

    // Viewbox parameters.
    const double xViewBoxCenter = xBoundingBoxCenter - svgParameters.xShift;
    const double yViewBoxCenter = yBoundingBoxCenter - svgParameters.yShift;
    const double viewBoxSize = 1.05 * boundingBoxSize / svgParameters.zoomFactor;
    const double xMinViewBox = xViewBoxCenter - viewBoxSize/2.;
    const double yMinViewBox = yViewBoxCenter - viewBoxSize/2.;

    // Fill in the rest of the SvgParameters.
    svgParameters.xCenter = xViewBoxCenter;
    svgParameters.yCenter = yViewBoxCenter;
    svgParameters.halfViewBoxSize = viewBoxSize / 2.;
    svgParameters.pixelSize = viewBoxSize / svgParameters.svgSizePixels;

    // Compute a table of vertices ordered by decreasing number of cells.
    vector< pair<vertex_descriptor, CellId> > sortedVertices;
    BGL_FORALL_VERTICES(v, graph, SignatureGraph) {
        const SignatureGraphVertex& vertex = graph[v];
        sortedVertices.push_back(make_pair(v, vertex.cellCount()));
    }
    sort(sortedVertices.begin(), sortedVertices.end(), OrderPairsBySecondGreater< pair<vertex_descriptor, CellId> >());

    // Start the svg object.
    s <<
        "<svg id=svgObject "
        "style='border:solid DarkBlue;margin:2;' "
        "width='" << svgParameters.svgSizePixels << "' "
        "height='" << svgParameters.svgSizePixels << "' "
        "viewBox='" << xMinViewBox << " " << yMinViewBox << " " << viewBoxSize << " " << viewBoxSize << "'"
        ">";

    // Draw the edges before the vertices, to avoid obscuring the vertices.
    if(!svgParameters.hideEdges) {
        s << "<g id=edges>";
        const double unscaledEdgeThickness = 5.e-4 * boundingBoxSize;
        BGL_FORALL_EDGES(e, graph, SignatureGraph) {
            const vertex_descriptor v1 = source(e, graph);
            const vertex_descriptor v2 = target(e, graph);
            const SignatureGraphVertex& vertex1 = graph[v1];
            const SignatureGraphVertex& vertex2 = graph[v2];
            s << "<line x1='" << vertex1.position[0] << "' y1='" << vertex1.position[1] << "'";
            s << " x2='" << vertex2.position[0] << "' y2='" << vertex2.position[1] << "'";

            s << " style='stroke:black;stroke-width:" <<
                unscaledEdgeThickness * svgParameters.edgeThicknessFactor << "' />";
        }
        s << "</g>";
    }

    // Write the vertices in order of decreasing size.
    // This way we mitigate obscuring of vertices by other vertices.
    s << "<g id=vertices>"; // fill-opacity='0.5'
    const double largestVertexUnscaledRadius = 0.03 * boundingBoxSize;
    for(const auto& p: sortedVertices) {
        const vertex_descriptor v = p.first;
        const SignatureGraphVertex& vertex = graph[v];
        const double x = vertex.position[0];
        const double y = vertex.position[1];
        const double vertexRadius =
            largestVertexUnscaledRadius *
            sqrt(double(vertex.cellCount())/double(maxCellCount));

        if(vertex.colors.size() < 2) {

            // Draw the vertex as a circle.
            const string vertexColor = vertex.colors.empty() ? string("black") : vertex.colors.front().first;
            s << "<circle cx='0' cy='0' r='" <<
                vertexRadius << "' stroke='none' fill='" << vertexColor << "'"
                " transform='translate(" << x << " " << y << ") scale(" << svgParameters.vertexSizeFactor << ")'"
                "></circle>";

        } else {

            // Draw the vertex as a pie chart.
            double totalAngle = 0.;
            for(const auto& p: vertex.colors) {
                const string& color = p.first;
                const double angle = p.second * 2. * boost::math::constants::pi<double>();
                const double angle0 = totalAngle;
                const double angle1 = angle0 + angle;
                s << "<path d='M 0 0 L " << vertexRadius*cos(angle0) << " " << vertexRadius*sin(angle0) << " A " <<
                    vertexRadius << " " << vertexRadius << " 0 " <<
                    ((angle>boost::math::constants::pi<double>()) ? 1 : 0) << " 1 " <<
                    vertexRadius*cos(angle1) << " " << vertexRadius*sin(angle1) <<
                    " Z' stroke='none' fill='" << color << "'"
                    " transform='translate(" << x << " " << y << ") scale(" << svgParameters.vertexSizeFactor << ")'"
                    "></path>";

                totalAngle = angle1;
            }
        }
    }
    s << "</g>";

    // End the svg object.
    s << "</svg>";
}


text:
/*
 * cg.cpp
 *
 *  Created on: Feb 22, 2013
 *      Author: Joao Cunha <joao.cunha@ua.pt>
 */

#include "cg.h"

#include <iostream>

#include <Eigen/Core>

using namespace std;

namespace libgp
{

CG::CG()
{
}

CG::~CG()
{
}

void CG::maximize(GaussianProcess* gp, size_t n, bool verbose)
{
	const double INT = 0.1; // don't reevaluate within 0.1 of the limit of the current bracket
	const double EXT = 3.0; // extrapolate maximum 3 times the current step-size
	const int MAX = 20;		// max 20 function evaluations per line search
	const double RATIO = 10;	// maximum allowed slope ratio
	const double SIG = 0.1, RHO = SIG/2;
	/* SIG and RHO are the constants controlling the Wolfe-
	   Powell conditions. SIG is the maximum allowed absolute ratio between
	   previous and new slopes (derivatives in the search direction), thus setting
	   SIG to low (positive) values forces higher precision in the line-searches.
	   RHO is the minimum allowed fraction of the expected (from the slope at the
	   initial point in the linesearch). Constants must satisfy 0 < RHO < SIG < 1.
	   Tuning of SIG (depending on the nature of the function to be optimized) may
	  speed up the minimization; it is probably not worth playing much with RHO.
	*/

	/* The code falls naturally into 3 parts, after the initial line search is
	   started in the direction of steepest descent. 1) we first enter a while loop
	   which uses point 1 (p1) and (p2) to compute an extrapolation (p3), until we
	   have extrapolated far enough (Wolfe-Powell conditions). 2) if necessary, we
	   enter the second loop which takes p2, p3 and p4 chooses the subinterval
	   containing a (local) minimum, and interpolates it, unil an acceptable point
	   is found (Wolfe-Powell conditions). Note, that points are always maintained
	   in order p0 <= p1 <= p2 < p3 < p4. 3) compute a new search direction using
	   conjugate gradients (Polack-Ribiere flavour), or revert to steepest if there
	   was a problem in the previous line-search. Return the best value so far, if
	   two consecutive line-searches fail, or whenever we run out of function
	   evaluations or line-searches. During extrapolation, the "f" function may fail
	   either with an error or returning Nan or Inf, and maxmize should handle this
	   gracefully.
	*/

	bool ls_failed = false;									//prev line-search failed
	double f0 = -gp->log_likelihood();						//initial negative marginal log likelihood
	Eigen::VectorXd df0 = -gp->log_likelihood_gradient();	//initial gradient
	Eigen::VectorXd X = gp->covf().get_loghyper();			//hyper parameters

	if(verbose) cout << f0 << endl;

	Eigen::VectorXd s = -df0;								//initial search direction
	double d0 = -s.dot(s);									//initial slope
	double x3 = 1/(1-d0);

	double f3 = 0;
	double d3 = 0;
	Eigen::VectorXd df3 = df0;

	double x2 = 0, x4 = 0;
	double f2 = 0, f4 = 0;
	double d2 = 0, d4 = 0;

	for (unsigned int i = 0; i < n; ++i)
	{
		//copy current values
		Eigen::VectorXd X0 = X;
		double F0 = f0;
		Eigen::VectorXd dF0 = df0;
		unsigned int M = min(MAX, (int)(n-i));

		while(1)											//keep extrapolating until necessary
		{
			x2 = 0;
			f2 = f0;
			d2 = d0;
			f3 = f0;
			df3 = df0;
			double success = false;

			while( !success && M>0)
			{
				M --;
				i++;
				gp->covf().set_loghyper(X+s*x3);
				f3 = -gp->log_likelihood();
				df3 = -gp->log_likelihood_gradient();

				if(verbose) cout << f3 << endl;

				bool nanFound = false;
				//test NaN and Inf's
				for (int j = 0; j < df3.rows(); ++j)
				{
					if(isnan(df3(j)))
					{
						nanFound = true;
						break;
					}
				}
				if(!isnan(f3) && !isinf(f3) && !nanFound)
					success = true;
				else
				{
					x3 = (x2+x3)/2; 						// if fail, bissect and try again
				}
			}
			//keep best values
			if(f3 < F0)
			{
				X0 = X+s*x3;
				F0 = f3;
				dF0 = df3;
			}

			d3 = df3.dot(s);								// new slope

			if( (d3 > SIG*d0) || (f3 >  f0+x3*RHO*d0) || M == 0) // are we done extrapolating?
			{
				break;
			}

			double x1 = x2; double f1 = f2; double d1 = d2;	// move point 2 to point 1
			x2 = x3; f2 = f3; d2 = d3;						// move point 3 to point 2
			double A = 6*(f1-f2) + 3*(d2+d1)*(x2-x1);				// make cubic extrapolation
			double B = 3*(f2-f1) - (2*d1+d2)*(x2-x1);
			x3 = x1-d1*(x2-x1)*(x2-x1)/(B+sqrt(B*B -A*d1*(x2-x1)));
			if(isnan(x3) || x3 < 0 || x3 > x2*EXT)			// num prob | wrong sign | beyond extrapolation limit
				x3 = EXT*x2;
			else if(x3 < x2+INT*(x2-x1))					// too close to previous point
				x3 = x2+INT*(x2-x1);
		}

		while( ( (abs(d3) > -SIG*d0) || (f3 > f0+x3*RHO*d0) ) && (M > 0))	// keep interpolating
		{
			if( (d3 > 0) || (f3 > f0+x3*RHO*d0) )			// choose subinterval
			{												// move point 3 to point 4
				x4 = x3;
				f4 = f3;
				d4 = d3;
			}
			else
			{
				x2 = x3;									//move point 3 to point 2
				f2 = f3;
				d2 = d3;
			}

			if(f4 > f0)
				x3 = x2 - (0.5*d2*(x4-x2)*(x4-x2))/(f4-f2-d2*(x4-x2));	// quadratic interpolation
			else
			{
				double A = 6*(f2-f4)/(x4-x2)+3*(d4+d2);
				double B = 3*(f4-f2)-(2*d2+d4)*(x4-x2);
				x3 = x2+sqrt(B*B-A*d2*(x4-x2)*(x4-x2) -B)/A;
			}

			if(isnan(x3) || isinf(x3))
				x3 = (x2+x4)/2;

			x3 = std::max(std::min(x3, x4-INT*(x4-x2)), x2+INT*(x4-x2));

			gp->covf().set_loghyper(X+s*x3);
			f3 = -gp->log_likelihood();
			df3 = -gp->log_likelihood_gradient();

			if(f3 < F0)												// keep best values
			{
				X0 = X+s*x3;
				F0 = f3;
				dF0 = df3;
			}

			if(verbose) cout << F0 << endl;

			M--;
			i++;
			d3 = df3.dot(s);										// new slope
		}

		if( (abs(d3) < -SIG*d0) && (f3 < f0+x3*RHO*d0))
		{
			X = X+s*x3;
			f0 = f3;
			s = (df3.dot(df3)-df0.dot(df3)) / (df0.dot(df0))*s - df3;	// Polack-Ribiere CG direction
			df0 = df3;													// swap derivatives
			d3 = d0; d0 = df0.dot(s);
			if(verbose) cout << f0 << endl;
			if(d0 > 0)													// new slope must be negative
			{															// otherwise use steepest direction
				s = -df0;
				d0 = -s.dot(s);
			}

			x3 = x3 * std::min(RATIO, d3/(d0-std::numeric_limits< double >::min()));	// slope ratio but max RATIO
			ls_failed = false;																// this line search did not fail
		}
		else
		{														// restore best point so far
			X = X0;
			f0 = F0;
			df0 = dF0;

			if(verbose) cout << f0 << endl;

			if(ls_failed || i >= n)								// line search failed twice in a row
				break;											// or we ran out of time, so we give up

			s = -df0;
			d0 = -s.dot(s);										// try steepest
			x3 = 1/(1-d0);
			ls_failed = true;									// this line search failed
		}

	}
	gp->covf().set_loghyper(X);
}

}

ext: cc

max_stars_repo_name: ecbaum/ugpm

max_issues_repo_name: Bellout/libgp

max_forks_repo_name: Bellout/libgp


text:
//
//	License type: BSD 3-Clause License
//	License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
//
//	Created by Stephane Bourque on 2021-03-04.
//	Arilia Wireless Inc.
//

#include <cstdlib>
#include <boost/algorithm/string.hpp>

#include "Poco/Util/Application.h"
#include "Poco/Util/ServerApplication.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Util/HelpFormatter.h"
#include "Poco/Environment.h"
#include "Poco/Path.h"

#include "uCentralRESTAPIServer.h"
#include "uCentralWebSocketServer.h"
#include "uStorageService.h"
#include "uDeviceRegistry.h"
#include "uAuthService.h"
#include "uCommandManager.h"
#include "base64util.h"
#include "uFileUploader.h"
#include "CommandChannel.h"
#include "utils.h"

#ifndef SMALL_BUILD
#include "kafka_service.h"
#endif

#include "uCentral.h"

namespace uCentral {

	Daemon App;

    Daemon * instance() { return &App; }

    void MyErrorHandler::exception(const Poco::Exception & E) {
        Poco::Thread * CurrentThread = Poco::Thread::current();
		App.logger().log(E);
		App.logger().error(Poco::format("Exception occurred in %s",CurrentThread->getName()));
    }

    void MyErrorHandler::exception(const std::exception & E) {
        Poco::Thread * CurrentThread = Poco::Thread::current();
		App.logger().warning(Poco::format("std::exception on %s",CurrentThread->getName()));
    }

    void MyErrorHandler::exception() {
        Poco::Thread * CurrentThread = Poco::Thread::current();
		App.logger().warning(Poco::format("exception on %s",CurrentThread->getName()));
    }

	void Daemon::Exit(int Reason) {
		std::exit(Reason);
	}

	void Daemon::initialize(Application &self) {

		Poco::Net::initializeSSL();

        std::string Location = Poco::Environment::get("UCENTRAL_CONFIG",".");
        Poco::Path ConfigFile;

        ConfigFile = ConfigFileName_.empty() ? Location + "/ucentral.properties" : ConfigFileName_;

        if(!ConfigFile.isFile())
        {
            std::cerr << "uCentral: Configuration " << ConfigFile.toString() << " does not seem to exist. Please set UCENTRAL_CONFIG env variable the path of the ucentral.properties file." << std::endl;
            std::exit(Poco::Util::Application::EXIT_CONFIG);
        }

        static const char * LogFilePathKey = "logging.channels.c2.path";

        loadConfiguration(ConfigFile.toString());

        if(LogDir_.empty()) {
            std::string OriginalLogFileValue = config().getString(LogFilePathKey);
            std::string RealLogFileValue = Poco::Path::expand(OriginalLogFileValue);
            config().setString(LogFilePathKey, RealLogFileValue);
        } else {
            config().setString(LogFilePathKey, LogDir_);
        }

		std::string KeyFile = Poco::Path::expand(config().getString("ucentral.service.key"));

		AppKey_ = Poco::SharedPtr<Poco::Crypto::RSAKey>(new Poco::Crypto::RSAKey("", KeyFile, ""));

        addSubsystem(uCentral::Storage::Service::instance());
        addSubsystem(uCentral::Auth::Service::instance());
        addSubsystem(uCentral::DeviceRegistry::Service::instance());
#ifndef SMALL_BUILD
		addSubsystem(uCentral::Kafka::Service::instance());
#endif
        addSubsystem(uCentral::RESTAPI::Service::instance());
        addSubsystem(uCentral::WebSocket::Service::instance());
        addSubsystem(uCentral::CommandManager::Service::instance());
        addSubsystem(uCentral::uFileUploader::Service::instance());
		addSubsystem(uCentral::CommandChannel::Service::instance());

        ServerApplication::initialize(self);

        logger().information("Starting...");

        if(!DebugMode_)
            DebugMode_ = config().getBool("ucentral.system.debug",false);

        ID_ = config().getInt64("ucentral.system.id",1);

        // add your own initialization code here
        AutoProvisioning_ = config().getBool("ucentral.autoprovisioning",false);

        // DeviceTypeIdentifications_
        std::vector<std::string>    Keys;
        config().keys("ucentral.autoprovisioning.type",Keys);
        for(const auto & i:Keys)
        {
            std::string Line = config().getString("ucentral.autoprovisioning.type."+i);
            auto P1 = Line.find_first_of(':');
            auto Type = Line.substr(0, P1);
            auto List = Line.substr(P1+1);

            std::vector<std::string>    Tokens = uCentral::Utils::Split(List);

            auto Entry = DeviceTypeIdentifications_[Type];

            Entry.insert(Entry.end(),Tokens.begin(),Tokens.end());
        }
    }

    std::string Daemon::IdentifyDevice(const std::string & Id ) const {
        for(const auto &[Type,List]:DeviceTypeIdentifications_)
        {
            for(const auto & i : List)
            {
                if(Id.find(i)!=std::string::npos)
                    return Type;
            }
        }
        return "AP_Default";
    }

    void Daemon::uninitialize() {
        // add your own uninitialization code here
        ServerApplication::uninitialize();
    }

    void Daemon::reinitialize(Poco::Util::Application &self) {
        ServerApplication::reinitialize(self);
        // add your own reinitialization code here
    }

    void Daemon::defineOptions(Poco::Util::OptionSet &options) {
        ServerApplication::defineOptions(options);

        options.addOption(
                Poco::Util::Option("help", "", "display help information on command line arguments")
                        .required(false)
                        .repeatable(false)
                        .callback(Poco::Util::OptionCallback<Daemon>(this, &Daemon::handleHelp)));

        options.addOption(
                Poco::Util::Option("file", "", "specify the configuration file")
                        .required(false)
                        .repeatable(false)
                        .argument("file")
                        .callback(Poco::Util::OptionCallback<Daemon>(this, &Daemon::handleConfig)));

        options.addOption(
                Poco::Util::Option("debug", "", "to run in debug, set to true")
                        .required(false)
                        .repeatable(false)
                        .callback(Poco::Util::OptionCallback<Daemon>(this, &Daemon::handleDebug)));

        options.addOption(
                Poco::Util::Option("logs", "", "specify the log directory and file (i.e. dir/file.log)")
                        .required(false)
                        .repeatable(false)
                        .argument("dir")
                        .callback(Poco::Util::OptionCallback<Daemon>(this, &Daemon::handleLogs)));

		options.addOption(
			Poco::Util::Option("version", "", "get the version and quit.")
				.required(false)
				.repeatable(false)
				.callback(Poco::Util::OptionCallback<Daemon>(this, &Daemon::handleVersion)));

	}

	std::string Daemon::Version() {
		std::string V = APP_VERSION;
		std::string B = BUILD_NUMBER;
		return V + "(" + B +  ")";
	}

    void Daemon::handleHelp(const std::string &name, const std::string &value) {
        HelpRequested_ = true;
        displayHelp();
        stopOptionsProcessing();
    }

	void Daemon::handleVersion(const std::string &name, const std::string &value) {
		HelpRequested_ = true;
		std::cout << Version() << std::endl;
		stopOptionsProcessing();
	}

	void Daemon::handleDebug(const std::string &name, const std::string &value) {
        if(value == "true")
            DebugMode_ = true ;
    }

    void Daemon::handleLogs(const std::string &name, const std::string &value) {
        LogDir_ = value;
    }

    void Daemon::handleConfig(const std::string &name, const std::string &value) {
        ConfigFileName_ = value;
    }

    void Daemon::displayHelp() {
        Poco::Util::HelpFormatter helpFormatter(options());
        helpFormatter.setCommand(commandName());
        helpFormatter.setUsage("OPTIONS");
        helpFormatter.setHeader("A uCentral gateway implementation for TIP.");
        helpFormatter.format(std::cout);
    }

    std::string Daemon::CreateUUID() {
        return UUIDGenerator_.create().toString();
    }

	bool Daemon::SetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level) {
		try {
			auto P = Poco::Logger::parseLevel(Level);
			auto Sub = boost::algorithm::to_lower_copy(SubSystem);
			if (Sub == "ufileuploader")
				uCentral::uFileUploader::Service().Logger().setLevel(P);
			else if (Sub == "websocket")
				uCentral::WebSocket::Service().Logger().setLevel(P);
			else if (Sub == "storage")
				uCentral::Storage::Service().Logger().setLevel(P);
			else if (Sub == "restapi")
				uCentral::RESTAPI::Service().Logger().setLevel(P);
			else if (Sub == "commandmanager")
				uCentral::CommandManager::Service().Logger().setLevel(P);
			else if (Sub == "auth")
				uCentral::Auth::Service().Logger().setLevel(P);
			else if (Sub == "deviceregistry")
				uCentral::DeviceRegistry::Service().Logger().setLevel(P);
			else if (Sub == "all") {
				uCentral::Auth::Service().Logger().setLevel(P);
				uCentral::uFileUploader::Service().Logger().setLevel(P);
				uCentral::WebSocket::Service().Logger().setLevel(P);
				uCentral::Storage::Service().Logger().setLevel(P);
				uCentral::RESTAPI::Service().Logger().setLevel(P);
				uCentral::CommandManager::Service().Logger().setLevel(P);
				uCentral::DeviceRegistry::Service().Logger().setLevel(P);
			} else
				return false;
			return true;
		} catch (const Poco::Exception & E) {

		}
		return false;
	}

    int Daemon::main(const ArgVec &args) {

        Poco::ErrorHandler::set(&AppErrorHandler_);

        if (!HelpRequested_) {
            Poco::Logger &logger = Poco::Logger::get("uCentral");
			logger.notice(Poco::format("Starting uCentral version %s.",Version()));
            uCentral::Storage::Start();
            uCentral::Auth::Start();
            uCentral::DeviceRegistry::Start();
            uCentral::RESTAPI::Start();
            uCentral::WebSocket::Start();
            uCentral::CommandManager::Start();
            uCentral::uFileUploader::Start();
			uCentral::CommandChannel::Start();

//			std::string f{"devices.db"};
//			uCentral::Storage::AttachFileToCommand(f);

#ifndef SMALL_BUILD
			uCentral::Kafka::Start();
#endif
			if(Poco::Net::Socket::supportsIPv6()) {
				logger.information("System supports IPv6.");
			}
			else
				logger.information("System does NOT suppord IPv6.");
            App.waitForTerminationRequest();

#ifndef SMALL_BUILD
			uCentral::Kafka::Stop();
#endif

			uCentral::CommandChannel::Stop();
            uCentral::uFileUploader::Stop();
            uCentral::CommandManager::Stop();
            uCentral::WebSocket::Stop();
            uCentral::RESTAPI::Stop();
            uCentral::DeviceRegistry::Stop();
            uCentral::Auth::Stop();
            uCentral::Storage::Stop();
			logger.notice("Stopped ucentral...");
        }

        return Application::EXIT_OK;
    }

    namespace ServiceConfig {

        uint64_t GetInt(const std::string &Key,uint64_t Default) {
            return (uint64_t) App.config().getInt64(Key,Default);
        }

        uint64_t GetInt(const std::string &Key) {
            return App.config().getInt(Key);
        }

        uint64_t GetBool(const std::string &Key,bool Default) {
            return App.config().getBool(Key,Default);
        }

        uint64_t GetBool(const std::string &Key) {
            return App.config().getBool(Key);
        }

        std::string GetString(const std::string &Key,const std::string & Default) {
            std::string R = App.config().getString(Key, Default);
            return Poco::Path::expand(R);
        }

        std::string GetString(const std::string &Key) {
            std::string R = App.config().getString(Key);
            return Poco::Path::expand(R);
        }
    }
}

int main(int argc, char **argv) {
	try {
		return uCentral::App.run(argc, argv);
	} catch (Poco::Exception &exc) {
		std::cerr << exc.displayText() << std::endl;
		return Poco::Util::Application::EXIT_SOFTWARE;
	}
}

// end of namespace


text:
#ifndef FASTSIM_SETTINGS_HPP_
#define FASTSIM_SETTINGS_HPP_

#include <boost/lexical_cast.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>

namespace fastsim {
  class Settings {
  public:
    // parse a xml file to instantiate the map & the robot
    Settings(const std::string& xml_file);
    boost::shared_ptr<Map> map() { return _map; }
    boost::shared_ptr<Robot> robot() { return _robot; }
    bool display() const { return _display; }
  protected:
    boost::shared_ptr<Map> _map;
    boost::shared_ptr<Robot> _robot;
    bool _display;

    template<typename R>
    R _get_a(const boost::property_tree::ptree& v, const char *a) const {
      std::string s("<xmlattr>.");
      return v.get<R>(s + std::string(a));
    }
    bool _get_a_bool(const boost::property_tree::ptree& v,
		     const char* a) const {
      std::string s("<xmlattr>.");
      std::string r = v.get<std::string>(s + std::string(a));
      if (r == "true")
	return true;
      return false;
    }

  };
}

#endif

max_stars_repo_name: alexander-hagg/phdexperiments

max_issues_repo_name: alexander-hagg/phdexperiments

max_forks_repo_name: alexander-hagg/phdexperiments


text:
/* ============================================================================
 * Copyright (c) 2010, Michael A. Jackson (BlueQuartz Software)
 * 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 Michael A. Jackson 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 HOLDER 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 "InitializationFunctions.h"
//-- C Includes
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

//-- Boost Includes
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real.hpp>
#include <boost/random/variate_generator.hpp>

//-- EMMMPM Lib Includes
#include "EMMPMLib/Core/EMMPM.h"
#include "EMMPMLib/Common/MSVCDefines.h"
#include "EMMPMLib/Common/EMMPM_Math.h"
#include "EMMPMLib/Common/EMTime.h"

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
InitializationFunction::InitializationFunction()
{

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
InitializationFunction::~InitializationFunction()
{

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void InitializationFunction::initialize(EMMPM_Data::Pointer data)
{

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
BasicInitialization::BasicInitialization()
{

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
BasicInitialization::~BasicInitialization()
{

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void BasicInitialization::initialize(EMMPM_Data::Pointer data)
{
  //FIXME: This needs to be adapted for vector images (dims > 1)
  unsigned int i, k, l;
  real_t mu, sigma;
  char msgbuff[256];
  unsigned int rows = data->rows;
  unsigned int cols = data->columns;
  unsigned int classes = data->classes;
  unsigned char* y = data->y;
  size_t total;

  rows = data->rows;
  cols = data->columns;
  total = data->rows * data->columns;

  memset(msgbuff, 0, 256);

  /* Initialization of parameter estimation */
  mu = 0;
  sigma = 0;
  for (i = 0; i < total; i++) {
      mu += y[i];
  }

  mu /= (rows * cols);

  for (i = 0; i < total; i++) {
      sigma += (y[i] - mu) * (y[i] - mu);
  }

  sigma /= (rows * cols);
  sigma = sqrt((real_t)sigma);

  if (classes % 2 == 0)
  {
    for (k = 0; k < classes / 2; k++)
    {
        data->mean[classes / 2 + k] = mu + (k + 1) * sigma / 2;
        data->mean[classes / 2 - 1 - k] = mu - (k + 1) * sigma / 2;
    }
  }
  else
  {
    data->mean[classes / 2] = mu;
    for (k = 0; k < classes / 2; k++)
    {
      data->mean[classes / 2 + 1 + k] = mu + (k + 1) * sigma / 2;
      data->mean[classes / 2 - 1 - k] = mu - (k + 1) * sigma / 2;
    }
  }

  for (l = 0; l < classes; l++)
  {
    data->variance[l] = 20.0;
  }
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
UserDefinedAreasInitialization::UserDefinedAreasInitialization()
{

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
UserDefinedAreasInitialization::~UserDefinedAreasInitialization()
{

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void UserDefinedAreasInitialization::initialize(EMMPM_Data::Pointer data)
{

  unsigned int i, j;
  size_t index;
  int c, l;
  real_t mu, sigma;
  unsigned int rows = data->rows;
  unsigned int cols = data->columns;
  char msgbuff[256];
  unsigned char* y = data->y;
  //  unsigned char** xt = data->xt;
  rows = data->rows;
  cols = data->columns;

  sigma = 0;
  mu = 0;

  if (data->dims != 1)
  {
    printf("User Defined Initialization ONLY works with GrayScale images and not vector images.\n  %s(%d)", __FILE__, __LINE__);
    exit(1);
  }

  memset(msgbuff, 0, 256);

  for (c = 0; c < data->classes; c++)
  {
    int x1 = data->initCoords[c][0];
    int y1 = data->initCoords[c][1];
    int x2 = data->initCoords[c][2];
    int y2 = data->initCoords[c][3];
    mu = 0;
    snprintf(msgbuff, 256, "m[%d] Coords: %d %d %d %d", c, x1, y1, x2, y2);
    for (i = data->initCoords[c][1]; i < data->initCoords[c][3]; i++)
    {
      for (j = data->initCoords[c][0]; j < data->initCoords[c][2]; j++)
      {
        index = (cols * i) + j;
        mu += y[index];
      }
    }

    mu /= (y2 - y1) * (x2 - x1);
    data->mean[c] = mu;
    snprintf(msgbuff, 256, "m[%d]=%f", c, mu);
  }

  for (l = 0; l < data->classes; l++)
  {
    data->variance[l] = 20.0;
  }

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
XtArrayInitialization::XtArrayInitialization()
{

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
XtArrayInitialization::~XtArrayInitialization()
{

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void XtArrayInitialization::initialize(EMMPM_Data::Pointer data)
{
  size_t total;

  total = data->rows * data->columns;

  const float rangeMin = 0.0f;
  const float rangeMax = 1.0f;
  typedef boost::uniform_real<> NumberDistribution;
  typedef boost::mt19937 RandomNumberGenerator;
  typedef boost::variate_generator<RandomNumberGenerator&,
                                   NumberDistribution> Generator;

  NumberDistribution distribution(rangeMin, rangeMax);
  RandomNumberGenerator generator;
  Generator numberGenerator(generator, distribution);
  generator.seed(EMMPM_getMilliSeconds()); // seed with the current time

  /* Initialize classification of each pixel randomly with a uniform disribution */
  for (size_t i = 0; i < total; i++)
  {
      data->xt[i] = numberGenerator() * data->classes;
  }

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
GradientVariablesInitialization::GradientVariablesInitialization()
{

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
GradientVariablesInitialization::~GradientVariablesInitialization()
{

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void GradientVariablesInitialization::initialize(EMMPM_Data::Pointer data)
{
  size_t ijd, ij, ijd1;

  size_t nsCols = data->columns - 1;
  size_t nsRows = data->rows;
  size_t ewCols = data->columns;
  size_t ewRows = data->rows - 1;
  size_t swCols = data->columns - 1;
  size_t swRows = data->rows - 1;
  size_t nwCols = data->columns - 1;
  size_t nwRows = data->rows - 1;

  int dims = data->dims;
  real_t x;

  /* Allocate for edge images */

  data->ns = (real_t*)malloc(nsCols * nsRows * sizeof(real_t));
  if (data->ns == NULL) { return; }
  data->ew = (real_t*)malloc(ewCols * ewRows * sizeof(real_t));
  if (data->ew == NULL) { return; }
  data->sw = (real_t*)malloc(swCols * swRows * sizeof(real_t));
  if (data->sw == NULL) { return; }
  data->nw = (real_t*)malloc(nwCols * nwRows * sizeof(real_t));
  if (data->nw == NULL) { return; }

  /* Do edge detection for gradient penalty*/
  for (uint32_t i = 0; i < data->rows; i++)
  {
    for (uint32_t j = 0; j < nwCols; j++)
    {
      x = 0;
      for (int32_t d = 0; d < dims; d++)
      {
        ijd = (dims * nwCols * i) + (dims * j) + d;
        ijd1 = (dims * nwCols * (i)) + (dims * (j + 1)) + d;
        x += (data->y[ijd] - data->y[ijd1]) * (data->y[ijd] - data->y[ijd1]);
      }
      ij = (nwCols * i) + j;
      data->ns[ij] = data->beta_e * atan((10 - sqrt(x)) / 5);
    }
  }
  for (uint32_t i = 0; i < nwRows; i++)
  {
    for (uint32_t j = 0; j < data->columns; j++)
    {
      x = 0;
      for (int32_t d = 0; d < dims; d++)
      {
        ijd = (dims * data->columns * i) + (dims * j) + d;
        ijd1 = (dims * data->columns * (i + 1)) + (dims * (j)) + d;
        x += (data->y[ijd] - data->y[ijd1]) * (data->y[ijd] - data->y[ijd1]);
      }
      ij = (data->columns * i) + j;
      data->ew[ij] = data->beta_e * atan((10 - sqrt(x)) / 5);
    }
  }
  nwCols = data->columns - 1;
  nwRows = data->rows - 1;
  for (uint32_t i = 0; i < nwRows; i++)
  {
    for (uint32_t j = 0; j < nwCols; j++)
    {
      x = 0;
      for (uint32_t d = 0; d < data->dims; d++)
      {
        ijd = (dims * data->columns * i) + (dims * j) + d;
        ijd1 = (dims * data->columns * (i + 1)) + (dims * (j + 1)) + d;
        x += (data->y[ijd] - data->y[ijd1]) * (data->y[ijd] - data->y[ijd1]);
      }
      ij = (nwCols * i) + j;
      data->sw[ij] = data->beta_e * atan((10 - sqrt(0.5 * x)) / 5);
      x = 0;
      for (uint32_t d = 0; d < data->dims; d++)
      {
        ijd = (dims * data->columns * (i + 1)) + (dims * (j)) + d;
        ijd1 = (dims * data->columns * (i)) + (dims * (j + 1)) + d;
        x += (data->y[ijd] - data->y[ijd1]) * (data->y[ijd] - data->y[ijd1]);
      }
      ij = (nwCols * i) + j;
      data->nw[ij] = data->beta_e * atan((10 - sqrt(0.5 * x)) / 5);
    }
  }

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
CurvatureInitialization::CurvatureInitialization()
{

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
CurvatureInitialization::~CurvatureInitialization()
{

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void CurvatureInitialization::initialize(EMMPM_Data::Pointer data)
{

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void CurvatureInitialization::initCurvatureVariables(EMMPM_Data::Pointer data)
{
  int l, lij;
  unsigned int i, j;

  data->ccost = (real_t*)malloc(data->classes * data->rows * data->columns * sizeof(real_t));
  if (data->ccost == NULL) { return; }

  /* Initialize Curve Costs to zero */
  for (l = 0; l < data->classes; l++)
  {
    for (i = 0; i < data->rows; i++)
    {
      for (j = 0; j < data->columns; j++)
      {
        {
          lij = (data->columns * data->rows * l) + (data->columns * i) + j;
          data->ccost[lij] = 0;
        }
      }
    }
  }
}

max_stars_repo_name: BlueQuartzSoftware/emmpm

max_issues_repo_name: BlueQuartzSoftware/emmpm

max_forks_repo_name: BlueQuartzSoftware/emmpm