text:
#include "bliobject_test.h"
#include "test_tools.h"
#include <bliobject.h>
#include <blieng.h>
#include <algorithm>
#include <string>
#include <boost/scoped_ptr.hpp>
#include "test_tools.h"

CPPUNIT_TEST_SUITE_REGISTRATION( BliObjectTest );

using blieng::BliObject;
using blieng::BliAny;

void BliObjectTest::setUp()
{
    mock_io_start();
}

void BliObjectTest::tearDown()
{
    mock_io_stop();
}

void BliObjectTest::values()
{
    BliObject *obj = new BliObject();

    CPPUNIT_ASSERT(!obj->isValue("test1"));

    obj->setValue("test1", (int)42);
    CPPUNIT_ASSERT(obj->isValue("test1"));

    blieng::BliAny res = obj->getValue("test1");
    CPPUNIT_ASSERT(!res.empty());
    CPPUNIT_ASSERT(res.cast<int>() == (int)42);

    CPPUNIT_ASSERT_THROW(res.cast<std::string>(), cdiggins::anyimpl::bad_any_cast);
}

void BliObjectTest::getValuesLimits()
{
    BliObject *obj = new BliObject();
    obj->setValue("test_int", (int)42);
    obj->setValue("test_int_min", (int)-42);
    obj->setValue("test_uint", (unsigned int)42);
    obj->setValue("test_double", (double)4.22);
    obj->setValue("test_char", (char)3);
    obj->setValue("test_char_min", (char)-1);
    obj->setValue("test_long", (long)123235);
    obj->setValue("test_long_long", (long long)1234567890123L);

    CPPUNIT_ASSERT(obj->getIntValue("test_int") == 42);
    CPPUNIT_ASSERT(obj->getIntValue("test_int_min") == -42);

    CPPUNIT_ASSERT(obj->getIntValue("test_uint") == 42);
    CPPUNIT_ASSERT(obj->getIntValue("test_double") == 4);
    CPPUNIT_ASSERT(obj->getDoubleValue("test_double") == 4.22);

    CPPUNIT_ASSERT(obj->getIntValue("test_char") == 3);
    CPPUNIT_ASSERT(obj->getIntValue("test_char_min") == -1);

    CPPUNIT_ASSERT(obj->getIntValue("test_long") == 123235);

    CPPUNIT_ASSERT_THROW(
        obj->getIntValue("test_long_long"),
        std::string);
}

void BliObjectTest::getValues()
{
    BliObject *obj = new BliObject();
    obj->setValue("test_int", (int)-42);
    obj->setValue("test_uint", (unsigned int)42);
    obj->setValue("test_double", (double)4.22);
    obj->setValue("test_string", std::string("test42"));
    obj->setValue("test_bool1", true);
    obj->setValue("test_bool2", false);

    CPPUNIT_ASSERT(obj->getIntValue("test_int") == -42 );
    CPPUNIT_ASSERT_THROW(
        obj->getUIntValue("test_int"),
        std::string);
    CPPUNIT_ASSERT( obj->getUIntValue("test_uint") == 42 );
    CPPUNIT_ASSERT( obj->getIntValue("test_uint") == 42 );
    CPPUNIT_ASSERT( obj->getDoubleValue("test_double") == 4.22 );
    CPPUNIT_ASSERT( obj->getIntValue("test_double") == 4 );
    CPPUNIT_ASSERT( obj->getStringValue("test_string") == "test42" );
    CPPUNIT_ASSERT( obj->getBoolValue("test_bool1") );
    CPPUNIT_ASSERT( !obj->getBoolValue("test_bool2") );
    CPPUNIT_ASSERT_THROW(
        obj->getBoolValue("test_int"),
        std::string);
    CPPUNIT_ASSERT_THROW(
        obj->getStringValue("test_int"),
        std::string);

    {
        std::stringstream buffer;
        boost::scoped_ptr<cerr_redirect> cd(new cerr_redirect(buffer.rdbuf()));
        CPPUNIT_ASSERT_THROW( obj->getValue("test_nothing"), std::string);
        std::string outp = buffer.str();

        CPPUNIT_ASSERT(
            outp.find("Error, key not found: test_nothing")
            != std::string::npos);
    }

    CPPUNIT_ASSERT( *obj->getValueType("test_int") == typeid(int) );
    CPPUNIT_ASSERT( *obj->getValueType("test_uint") == typeid(unsigned int) );
    CPPUNIT_ASSERT( *obj->getValueType("test_double") == typeid(double) );
    CPPUNIT_ASSERT( *obj->getValueType("test_string") == typeid(std::string) );
    CPPUNIT_ASSERT( *obj->getValueType("test_bool1") == typeid(bool) );
    CPPUNIT_ASSERT( *obj->getValueType("test_bool2") == typeid(bool) );

    std::vector<std::string> keys = obj->getKeys();

    CPPUNIT_ASSERT(
        std::find(keys.begin(), keys.end(), "test_int")
        != keys.end());
    CPPUNIT_ASSERT(
        std::find(keys.begin(), keys.end(), "test_uint")
        != keys.end());
    CPPUNIT_ASSERT(
        std::find(keys.begin(), keys.end(), "test_double")
        != keys.end());
    CPPUNIT_ASSERT(
        std::find(keys.begin(), keys.end(), "test_string")
        != keys.end());
    CPPUNIT_ASSERT(
        std::find(keys.begin(), keys.end(), "test_bool1")
        != keys.end());
    CPPUNIT_ASSERT(
        std::find(keys.begin(), keys.end(), "test_bool2")
        != keys.end());
    CPPUNIT_ASSERT(
        std::find(keys.begin(), keys.end(), "test_dummy")
        == keys.end());
}

void BliObjectTest::toString()
{
    BliObject *obj = new BliObject();
    obj->setValue("test1", (unsigned int)42);
    obj->setValue("test2", (unsigned int)99);
    obj->setValue("test3", (int)-55);
    obj->setValue("test4", std::string("hello"));
    obj->setValue("test5", 5.99);
    obj->setValue("test6", true);

    std::string s = obj->toString();
    CPPUNIT_ASSERT( s.find("test1: 42") != std::string::npos );
    CPPUNIT_ASSERT( s.find("test2: 99") != std::string::npos );
    CPPUNIT_ASSERT( s.find("test3: -55") != std::string::npos );
    CPPUNIT_ASSERT( s.find("test4: hello") != std::string::npos );
    CPPUNIT_ASSERT( s.find("test5: 5.99") != std::string::npos );
    CPPUNIT_ASSERT( s.find("test6: true") != std::string::npos );
    CPPUNIT_ASSERT( s.find("test9") == std::string::npos );
}

void BliObjectTest::percentageString()
{
    CPPUNIT_ASSERT(blieng::percentageString(0.1) == "10%");
// Unfortunately Ubuntu 12.04 has bug in glibc which causes these to fail on i386
#ifndef __i386__
    CPPUNIT_ASSERT(blieng::percentageString(0.12) == "12%");

    CPPUNIT_ASSERT(blieng::percentageString(0.01) == "1%");
    CPPUNIT_ASSERT(blieng::percentageString(0.012) == "1%");
    CPPUNIT_ASSERT(blieng::percentageString(1.0) == "100%");
    CPPUNIT_ASSERT(blieng::percentageString(1.23) == "123%");

    CPPUNIT_ASSERT(blieng::percentageString(0.12345678) == "12%");
    CPPUNIT_ASSERT(blieng::percentageString(0.12345678, 1) == "12.3%");
    CPPUNIT_ASSERT(blieng::percentageString(0.12345678, 2) == "12.34%");
    CPPUNIT_ASSERT(blieng::percentageString(0.12345678, 3) == "12.345%");
    CPPUNIT_ASSERT(blieng::percentageString(0.12345678, 4) == "12.3456%");

    CPPUNIT_ASSERT(blieng::percentageString(12345678) == "1234567800%");
    CPPUNIT_ASSERT(blieng::percentageString(123456.78) == "12345678%");
    CPPUNIT_ASSERT(blieng::percentageString(123456.78901234567) == "12345678%");
    CPPUNIT_ASSERT(blieng::percentageString(123456.78901234567, 1) == "12345678.9%");
    CPPUNIT_ASSERT(blieng::percentageString(123456.78901234567, 2) == "12345678.90%");
    CPPUNIT_ASSERT(blieng::percentageString(123456.78901234567, 3) == "12345678.901%");
    CPPUNIT_ASSERT(blieng::percentageString(123456.78901234567, 5) == "12345678.90123%");

    CPPUNIT_ASSERT(blieng::percentageString(-0.1) == "-10%");
    CPPUNIT_ASSERT(blieng::percentageString(-0.012) == "-1%");
    CPPUNIT_ASSERT(blieng::percentageString(-0.12345678) == "-12%");
    CPPUNIT_ASSERT(blieng::percentageString(-0.12345678, 1) == "-12.3%");
    CPPUNIT_ASSERT(blieng::percentageString(-0.12345678, 2) == "-12.34%");
    CPPUNIT_ASSERT(blieng::percentageString(-0.12345678, 4) == "-12.3456%");
#endif
}

void BliObjectTest::assign()
{
    BliObject *obj1 = new BliObject();
    obj1->setValue("test1", (unsigned int)42);
    obj1->setValue("test2", (int)-5);

    BliObject *obj2 = new BliObject();
    CPPUNIT_ASSERT( obj1->isValue("test1") );
    CPPUNIT_ASSERT( obj1->isValue("test2") );
    CPPUNIT_ASSERT( !obj2->isValue("test1") );
    CPPUNIT_ASSERT( !obj2->isValue("test2") );

    obj2->assignObject(obj1);
    CPPUNIT_ASSERT( obj1->isValue("test1") );
    CPPUNIT_ASSERT( obj1->isValue("test2") );
    CPPUNIT_ASSERT( obj2->isValue("test1") );
    CPPUNIT_ASSERT( obj2->isValue("test2") );

    CPPUNIT_ASSERT( obj1->getIntValue("test1") == obj2->getIntValue("test1") );
    CPPUNIT_ASSERT( obj1->getIntValue("test2") == obj2->getIntValue("test2") );

    obj2->setValue("test2", (int)-4);

    CPPUNIT_ASSERT( obj1->getIntValue("test2") != obj2->getIntValue("test2") );
}

void BliObjectTest::random()
{
    int a = BliObject::getRandomInt(0, 100);
    int b = BliObject::getRandomInt(0, 100);
    int cnt = 10;
    while (a == b && cnt > 0) {
        b = BliObject::getRandomInt(0, 100);
        cnt--;
    }

    CPPUNIT_ASSERT( cnt > 0 );
    CPPUNIT_ASSERT( a != b );
    CPPUNIT_ASSERT( (0 <= a) && (a <= 100));
    CPPUNIT_ASSERT( (0 <= b) && (b <= 100));

    double da = BliObject::getRandomInt(0, 1);
    double db = BliObject::getRandomInt(0, 1);
    cnt = 10;
    while (da == db && cnt > 0) {
        db = BliObject::getRandomInt(0, 100);
        cnt--;
    }

    CPPUNIT_ASSERT( cnt > 0 );
    CPPUNIT_ASSERT( da != db );

    int min = 200;
    int max = -1;
    cnt = 2000;
    while (cnt > 0) {
        a = BliObject::getRandomInt(0, 100);
        if (a > max) max = a;
        if (a < min) min = a;
        cnt--;
    }
    // In fact this can fail, but probably will not...
    CPPUNIT_ASSERT( min <= 2 );
    CPPUNIT_ASSERT( max >= 98 );

    bool b1 = BliObject::getRandomBoolean();
    bool b2 = BliObject::getRandomBoolean();
    cnt = 10;
    while (b1 == b2 && cnt > 0) {
        b2 = BliObject::getRandomBoolean();
        cnt--;
    }
}

void BliObjectTest::incdec()
{
    BliObject *obj = new BliObject();

    obj->setValue("test1", (unsigned int)42);
    obj->setValue("test2", (int)-55);
    obj->setValue("test3", 5.99);

    obj->setValue("test1-max", (unsigned int)43);
    obj->setValue("test3-max", (unsigned int)10);

    CPPUNIT_ASSERT( obj->increase("test1") );
    CPPUNIT_ASSERT( obj->increase("test2") );
    CPPUNIT_ASSERT( obj->increase("test3") );

    CPPUNIT_ASSERT( obj->getUIntValue("test1") == 43 );
    CPPUNIT_ASSERT( obj->getIntValue("test2") == -54 );
    CPPUNIT_ASSERT( obj->getDoubleValue("test3") == 6.99 );

    CPPUNIT_ASSERT( !obj->increase("test1") );
    CPPUNIT_ASSERT( obj->increase("test2") );
    CPPUNIT_ASSERT( obj->increase("test3") );

    CPPUNIT_ASSERT( obj->getUIntValue("test1") == 43 );
    CPPUNIT_ASSERT( obj->getIntValue("test2") == -53 );
    CPPUNIT_ASSERT( obj->getDoubleValue("test3") == 7.99 );

    CPPUNIT_ASSERT( obj->increase("test3") );
    CPPUNIT_ASSERT( obj->getDoubleValue("test3") == 8.99 );

    CPPUNIT_ASSERT( obj->increase("test3") );
    CPPUNIT_ASSERT( obj->getDoubleValue("test3") == 9.99 );

    CPPUNIT_ASSERT( !obj->increase("test3") );
    CPPUNIT_ASSERT( obj->getDoubleValue("test3") == 9.99 );

    CPPUNIT_ASSERT( obj->decrease("test1") );
    CPPUNIT_ASSERT( obj->decrease("test2") );
    CPPUNIT_ASSERT( obj->decrease("test3") );

    CPPUNIT_ASSERT( obj->getUIntValue("test1") == 42 );
    CPPUNIT_ASSERT( obj->getIntValue("test2") == -54 );
    CPPUNIT_ASSERT( obj->getDoubleValue("test3") == 8.99 );
}

void BliObjectTest::bliany()
{
    BliAny tmp1((unsigned int)1);
    BliAny tmp2(2.3);
    BliAny tmp3(std::string("res"));
    BliAny tmp4(true);
    BliAny tmp5(false);
    BliAny tmp6(-1);

    CPPUNIT_ASSERT( tmp1.asUInt() == 1);
    CPPUNIT_ASSERT( tmp1.asNumber() == 1);
    CPPUNIT_ASSERT( tmp2.asDouble() == 2.3);
    CPPUNIT_ASSERT( tmp2.asNumber() == 2);
    CPPUNIT_ASSERT( tmp3.asString() == "res");
    CPPUNIT_ASSERT( tmp4.asBool() );
    CPPUNIT_ASSERT( !tmp5.asBool() );
    CPPUNIT_ASSERT( tmp6.asInt() == -1 );
    CPPUNIT_ASSERT( tmp6.asNumber() == -1 );

    CPPUNIT_ASSERT_THROW( tmp1.asDouble(), std::string );
    CPPUNIT_ASSERT_THROW( tmp2.asInt(), std::string );
}

void BliObjectTest::serialize()
{
    BliObject *obj = new BliObject();
    obj->setValue("test_int", (int)42);
    obj->setValue("test_int_min", (int)-42);
    obj->setValue("test_uint", (unsigned int)42);
    obj->setValue("test_double", (double)4.22);
    obj->setValue("test_char", (char)3);
    obj->setValue("test_char_min", (char)-1);
    obj->setValue("test_long", (long)123235);
    obj->setValue("test_long_long", (long long)1234567890123L);

    std::string res = obj->serialize();

    CPPUNIT_ASSERT( res != "" );

    BliObject *obj2 = new BliObject();
    CPPUNIT_ASSERT(obj->isValue("test_int"));
    CPPUNIT_ASSERT(!obj2->isValue("test_int"));

    obj2->deserialize(res);
    CPPUNIT_ASSERT(obj2->isValue("test_int"));
    CPPUNIT_ASSERT_EQUAL(obj2->getIntValue("test_int"), (int)42);
    CPPUNIT_ASSERT_EQUAL(obj2->getCharValue("test_char"), (char)3);
    CPPUNIT_ASSERT_EQUAL(obj2->getCharValue("test_char_min"), (char)-1);
    CPPUNIT_ASSERT_EQUAL(obj2->getDoubleValue("test_double"), (double)4.22);
    CPPUNIT_ASSERT_EQUAL(obj2->getLongLongValue("test_long_long"), (long long)1234567890123L);

    std::string res2 = obj->serialize("Random");
    CPPUNIT_ASSERT(obj->serializedType(res) == "BliObject");
    CPPUNIT_ASSERT(BliObject::serializedType(res) == "BliObject");
    CPPUNIT_ASSERT(obj->serializedType(res2) == "Random");
}

void BliObjectTest::compress()
{
    std::string original = "inadub792b91beaaaaaaaaaaaaaaabbbbbbbbbbbbbbbb";
    char *comp = nullptr;
    unsigned int len;
    std::tie(
        comp,
        len) = blieng::compress(original.c_str(), original.size());

    CPPUNIT_ASSERT(comp != nullptr);
    CPPUNIT_ASSERT(len > 0);
    CPPUNIT_ASSERT(len < original.size());
    CPPUNIT_ASSERT(!blieng::isCompressed(original.c_str(), original.size()));
    CPPUNIT_ASSERT(blieng::isCompressed(comp, len));

    char *uncomp = nullptr;
    unsigned int uncomp_len;
    std::tie(
        uncomp,
        uncomp_len) = blieng::decompress(comp, len);

    CPPUNIT_ASSERT(uncomp != nullptr);
    CPPUNIT_ASSERT(uncomp_len > 0);
    CPPUNIT_ASSERT(uncomp_len == original.size());
    CPPUNIT_ASSERT(std::string(uncomp, uncomp_len) == original);

    CPPUNIT_ASSERT(blieng::isCompressed(comp, len));
    CPPUNIT_ASSERT(!blieng::isCompressed(uncomp, uncomp_len));

    delete [] uncomp;
    delete [] comp;
}

void BliObjectTest::uuid()
{
    blieng::BliObject tmp1;

    for (unsigned int i = 0; i < 100; ++i) {
        blieng::BliObject tmp2;
        CPPUNIT_ASSERT( tmp1.uuid() != tmp2.uuid() );
    }
}

max_stars_repo_name: jroivas/blieng

max_issues_repo_name: jroivas/blieng

max_forks_repo_name: jroivas/blieng


text:
/*
Copyright 2012-2015 Glen Joseph Fernandes
(glenjofe@gmail.com)

Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_SMART_PTR_MAKE_UNIQUE_HPP
#define BOOST_SMART_PTR_MAKE_UNIQUE_HPP

#include <boost/config.hpp>
#include <memory>
#include <utility>

namespace boost {
namespace detail {

template<class T>
struct up_if_object {
    typedef std::unique_ptr<T> type;
};

template<class T>
struct up_if_object<T[]> { };

template<class T, std::size_t N>
struct up_if_object<T[N]> { };

template<class T>
struct up_if_array { };

template<class T>
struct up_if_array<T[]> {
    typedef std::unique_ptr<T[]> type;
};

template<class T>
struct up_remove_reference {
    typedef T type;
};

template<class T>
struct up_remove_reference<T&> {
    typedef T type;
};

template<class T>
struct up_remove_reference<T&&> {
    typedef T type;
};

template<class T>
struct up_element { };

template<class T>
struct up_element<T[]> {
    typedef T type;
};

} /* detail */

template<class T>
inline typename detail::up_if_object<T>::type
make_unique()
{
    return std::unique_ptr<T>(new T());
}

#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template<class T, class... Args>
inline typename detail::up_if_object<T>::type
make_unique(Args&&... args)
{
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
#endif

template<class T>
inline typename detail::up_if_object<T>::type
make_unique(typename detail::up_remove_reference<T>::type&& value)
{
    return std::unique_ptr<T>(new T(std::move(value)));
}

template<class T>
inline typename detail::up_if_object<T>::type
make_unique_noinit()
{
    return std::unique_ptr<T>(new T);
}

template<class T>
inline typename detail::up_if_array<T>::type
make_unique(std::size_t size)
{
    return std::unique_ptr<T>(new typename
        detail::up_element<T>::type[size]());
}

template<class T>
inline typename detail::up_if_array<T>::type
make_unique_noinit(std::size_t size)
{
    return std::unique_ptr<T>(new typename
        detail::up_element<T>::type[size]);
}

} /* boost */

#endif

ext: hpp

max_stars_repo_name: RusDavies/indigo

max_issues_repo_name: RusDavies/indigo

max_forks_repo_name: RusDavies/indigo


text:
// Copyright (c) 2018 Baidu, Inc. All Rights Reserved.
//
// 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.

#include "query_privilege_manager.h"
#include <boost/algorithm/string.hpp>

namespace baikaldb {
void QueryPrivilegeManager::get_user_info(const pb::QueryRequest* request,
                                     pb::QueryResponse* response) {
    PrivilegeManager* manager = PrivilegeManager::get_instance();
    BAIDU_SCOPED_LOCK(manager->_user_mutex);
    if (!request->has_user_name()) {
         for (auto& user_info : manager->_user_privilege) {
             auto privilege = response->add_user_privilege();
             *privilege = user_info.second;
         }
    } else {
        std::string user_name = request->user_name();
        if (manager->_user_privilege.find(user_name) != manager->_user_privilege.end()) {
            auto privilege = response->add_user_privilege();
            *privilege = manager->_user_privilege[user_name];
        } else {
            response->set_errcode(pb::INPUT_PARAM_ERROR);
            response->set_errmsg("username not exist");
        }
    }
}

void QueryPrivilegeManager::get_flatten_privilege(const pb::QueryRequest* request,
                                             pb::QueryResponse* response) {
    PrivilegeManager* manager = PrivilegeManager::get_instance();
    BAIDU_SCOPED_LOCK(manager->_user_mutex);
    std::string user_name = request->user_name();
    boost::trim(user_name);
    std::string namespace_name = request->namespace_name();
    boost::trim(namespace_name);
    std::map<std::string, std::multimap<std::string, pb::QueryUserPrivilege>> namespace_privileges;
    if (user_name.size() == 0 && namespace_name.size() == 0) {
        for (auto& privilege_info : manager->_user_privilege) {
            construct_query_response_for_privilege(privilege_info.second, namespace_privileges);
        }
    }
    if (user_name.size() != 0
            && manager->_user_privilege.find(user_name) != manager->_user_privilege.end()) {
        construct_query_response_for_privilege(manager->_user_privilege[user_name], namespace_privileges);
    }
    if (namespace_name.size() != 0) {
        for (auto& privilege_info : manager->_user_privilege) {
            if (privilege_info.second.namespace_name() != namespace_name) {
                continue;
            }
            construct_query_response_for_privilege(privilege_info.second, namespace_privileges);
        }
    }
    for (auto& namespace_privilege : namespace_privileges) {
        for (auto& user_privilege : namespace_privilege.second) {
            pb::QueryUserPrivilege* privilege_info = response->add_flatten_privileges();
            *privilege_info = user_privilege.second;
        }
    }
}
void QueryPrivilegeManager::construct_query_response_for_privilege(const pb::UserPrivilege& user_privilege,
        std::map<std::string, std::multimap<std::string, pb::QueryUserPrivilege>>& namespace_privileges) {
    std::string namespace_name =  user_privilege.namespace_name();
    std::string username = user_privilege.username();
    for (auto& privilege_database : user_privilege.privilege_database()) {
        pb::QueryUserPrivilege flatten_privilege;
        flatten_privilege.set_username(username);
        flatten_privilege.set_namespace_name(namespace_name);
        flatten_privilege.set_table_rw(privilege_database.database_rw());
        flatten_privilege.set_privilege(privilege_database.database() + ".*");
        std::multimap<std::string, pb::QueryUserPrivilege> user_privilege_map;
        if (namespace_privileges.find(namespace_name) != namespace_privileges.end()) {
            user_privilege_map = namespace_privileges[namespace_name];
        }
        user_privilege_map.insert(std::pair<std::string, pb::QueryUserPrivilege>(username, flatten_privilege));
        namespace_privileges[namespace_name] = user_privilege_map;
    }
    for (auto& privilege_table : user_privilege.privilege_table()) {
        pb::QueryUserPrivilege flatten_privilege;
        flatten_privilege.set_username(username);
        flatten_privilege.set_namespace_name(namespace_name);
        flatten_privilege.set_table_rw(privilege_table.table_rw());
        flatten_privilege.set_privilege(privilege_table.database() + "." + privilege_table.table_name());
        std::multimap<std::string, pb::QueryUserPrivilege> user_privilege_map;
        if (namespace_privileges.find(namespace_name) != namespace_privileges.end()) {
            user_privilege_map = namespace_privileges[namespace_name];
        }
        user_privilege_map.insert(std::pair<std::string, pb::QueryUserPrivilege>(username, flatten_privilege));
        namespace_privileges[namespace_name] = user_privilege_map;
    }
}
}// namespace

/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */

ext: cpp

max_stars_repo_name: xiaoqing-yuanfang/BaikalDB

max_issues_repo_name: MinHaoSun/BaikalDB

max_forks_repo_name: MinHaoSun/BaikalDB


text:
#include <dlib/global_optimization.h>
#include <dlib/matrix.h>
#include <dlib/svm.h>

#include <plot.h>

#include <iostream>
#include <random>
#include <vector>

using SampleType = dlib::matrix<double, 1, 1>;
using Samples = std::vector<SampleType>;
using Labels = std::vector<SampleType>;

Samples LinSpace(double s, double e, size_t n) {
  Samples x_values(n);
  double step = (e - s) / n;
  double v = s;
  for (size_t i = 0; i < n; ++i) {
    x_values[i](0, 0) = v;
    v += step;
  }
  x_values[n - 1] = e;

  return x_values;
}

std::pair<Samples, Labels> GenerateData(size_t num_samples, size_t seed) {
  Samples x_values(num_samples);
  Labels y_values(num_samples);

  std::mt19937 re(seed);
  std::normal_distribution<double> dist;

  for (size_t i = 0; i < num_samples; ++i) {
    auto x_val = dist(re);
    x_values[i](0, 0) = x_val;

    auto y_val = std::cos(M_PI * x_val) + (dist(re) * 0.3);
    y_values[i](0, 0) = y_val;
  }
  return {x_values, y_values};
}

int main(int /*argc*/, char** /*argv*/) {
  using namespace dlib;

  // Generate data
  Samples samples;
  Labels labels;
  std::tie(samples, labels) = GenerateData(1000, 435635);

  auto mm = std::minmax_element(
      samples.begin(), samples.end(),
      [](const auto& a, const auto& b) { return a(0, 0) < b(0, 0); });
  std::pair<double, double> x_minmax{*mm.first, *mm.second};

  // Normalize data
  vector_normalizer<SampleType> x_normalizer;
  x_normalizer.train(samples);
  std::for_each(samples.begin(), samples.end(), x_normalizer);

  vector_normalizer<SampleType> y_normalizer;
  y_normalizer.train(labels);
  std::for_each(labels.begin(), labels.end(), y_normalizer);

  std::vector<double> raw_labels(labels.size());
  for (size_t i = 0; i < labels.size(); ++i) {
    raw_labels[i] = labels[i](0, 0);
  }

  // Randomize data
  randomize_samples(samples, raw_labels);

  // Define cross validation function
  auto CrossValidationScore = [&](const double gamma, const double c,
                                  const double degree_in) {
    auto degree = std::floor(degree_in);
    using KernelType = dlib::polynomial_kernel<SampleType>;
    dlib::svr_trainer<KernelType> trainer;
    trainer.set_kernel(KernelType(gamma, c, degree));

    std::cout << "gamma: " << std::setw(11) << gamma << "  c: " << std::setw(11)
              << c << "  degree: " << std::setw(11) << degree;
    std::cout.flush();

    dlib::matrix<double> result = dlib::cross_validate_regression_trainer(
        trainer, samples, raw_labels, 10);
    std::cout << std::setw(11) << "  MSE: " << result(0, 0) << std::setw(11)
              << "  MAE: " << result(0, 2) << std::endl;

    return result(0, 0);
  };

  // Search for the best parameters
  auto result = find_min_global(
      CrossValidationScore,
      {0.01, 1e-8, 5},  // minimum values for gamma, c, and degree
      {0.1, 1, 15},     // maximum values for gamma, c, and degree
      max_function_calls(50));

  double gamma = result.x(0);
  double c = result.x(1);
  double degree = result.x(2);

  std::cout << " best cross validation score: " << result.y << std::endl;
  std::cout << " best gamma: " << gamma << "   best c: " << c
            << "    best degree: " << degree << std::endl;

  // Train model
  using KernelType = dlib::polynomial_kernel<SampleType>;
  dlib::svr_trainer<KernelType> trainer;
  trainer.set_kernel(KernelType(gamma, c, degree));
  auto descision_func = trainer.train(samples, raw_labels);

  // Plot perdictions
  auto new_samples = LinSpace(x_minmax.first, x_minmax.second, 50);
  std::for_each(new_samples.begin(), new_samples.end(), x_normalizer);

  std::vector<double> predictions(new_samples.size());
  std::transform(new_samples.begin(), new_samples.end(), predictions.begin(),
                 descision_func);

  plotcpp::Plot plt;
  plt.SetTerminal("png");
  plt.SetOutput("plot.png");
  plt.SetTitle("SVM Polynomial kernel regression");
  plt.SetXLabel("x");
  plt.SetYLabel("y");
  plt.SetAutoscale();
  plt.GnuplotCommand("set grid");

  std::vector<double> x_coords(samples.size());
  std::transform(samples.begin(), samples.end(), x_coords.begin(),
                 [](auto& m) { return m(0, 0); });

  std::vector<double> x_pred_coords(new_samples.size());
  std::transform(new_samples.begin(), new_samples.end(), x_pred_coords.begin(),
                 [](auto& m) { return m(0, 0); });

  plt.Draw2D(plotcpp::Points(x_coords.begin(), x_coords.end(),
                             raw_labels.begin(), "orig", "lc rgb 'black' pt 7"),
             plotcpp::Lines(x_pred_coords.begin(), x_pred_coords.end(),
                            predictions.begin(), "pred", "lc rgb 'red' lw 2"));
  plt.Flush();

  return 0;
}

ext: cc


text:
/*
**  Copyright (C) 2020 SoftBank Robotics Europe
**  See COPYING for the license
*/

#pragma once

#ifndef QIPYTHON_COMMON_HPP
#define QIPYTHON_COMMON_HPP

#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
#include <pybind11/stl.h>
#include <qipython/pytypes.hpp>
#include <ka/errorhandling.hpp>
#include <ka/functional.hpp>
#include <future>
#include <thread>

namespace qi
{
namespace py
{

/// Returns the instance of the bound method if it exists, otherwise returns
/// a `None` object.
///
/// @pre `obj` is not a null object.
/// @pre The GIL is locked.
/// @post the returned value is not a null object (it evaluates to true).
inline pybind11::object getMethodSelf(const pybind11::function& func)
{
  QI_ASSERT_TRUE(func);
  if (PyMethod_Check(func.ptr()))
    return pybind11::reinterpret_borrow<pybind11::object>(
      PyMethod_GET_SELF(func.ptr()));
  return pybind11::none();
}

/// Casts a value into a Python object, throwing an exception if the conversion
/// fails.
///
/// @pre The GIL is locked.
/// @post the returned value is not a null object (it evaluates to true).
// See https://github.com/pybind/pybind11/issues/2336
// Casting does not throw if the type is unregistered, so we throw explicitly in
// case of an error.
// TODO: Remove this function and its uses when the issue is fixed.
template<typename T, typename... Extra,
  ka::EnableIf<!std::is_base_of<pybind11::handle, ka::RemoveCvRef<T>>::value,
               int> = 0>
pybind11::object castToPyObject(T&& t, Extra&&... extra)
{
  auto obj = pybind11::cast(std::forward<T>(t), std::forward<Extra>(extra)...);
  if (PyErr_Occurred())
    throw pybind11::error_already_set();
  QI_ASSERT_TRUE(obj);
  return obj;
}

/// Extracts a keyword argument out of a dictionary of keywords arguments.
///
/// If the argument is not in the dictionary, does nothing and returns an empty
/// optional.
///
/// If the argument is is the dictionary, it is removed from it and its value is
/// then cast to a value of type `T` and an optional of this value is returned.
///
/// If the argument has value `None`, an empty optional is returned unless
/// `allowNone` is set to true, in which case the `None` value will be cast to
/// a value of type `T`.
///
/// @pre The GIL is locked.
/// @warning If the value of the argument cannot be cast to type `T`, an
///          exception is thrown but the argument is still removed from the
///          dictionary.
template <typename T>
boost::optional<T> extractKeywordArg(pybind11::dict kwargs,
                                     const char* argName,
                                     bool allowNone = false)
{
  if (!kwargs.contains(argName))
    return {};

  const pybind11::object pyArg = kwargs[argName];
  PyDict_DelItemString(kwargs.ptr(), argName);

  if (pyArg.is_none() && !allowNone)
    return {};

  return pyArg.cast<T>();
}

/// A deleter that deletes the pointer outside of the GIL.
///
/// Useful for types that might deadlock on destruction if they keep the GIL
/// locked.
struct DeleteOutsideGIL
{
  template<typename T>
  void operator()(T* ptr) const
  {
    pybind11::gil_scoped_release unlock;
    delete ptr;
  }
};

/// Delay the destruction of an object to a thread.
struct DeleteInOtherThread
{
  template<typename T>
  void operator()(T* ptr) const
  {
    pybind11::gil_scoped_release unlock;
    auto fut = std::async(std::launch::async, [](std::unique_ptr<T>) {},
                          std::unique_ptr<T>(ptr));
    QI_IGNORE_UNUSED(fut);
  }
};

} // namespace py
} // namespace qi

namespace pybind11
{
namespace detail
{
  template <>
  struct type_caster<qi::AnyReference>
  {
  public:
    PYBIND11_TYPE_CASTER(qi::AnyReference, _("qi_python.AnyReference"));

    // Python -> C++
    bool load(handle src, bool /* enable implicit conversions */)
    {
      QI_ASSERT_TRUE(src);
      value = ka::invoke_catch(ka::compose(
                                 [&](const std::string&) {
                                   currentObject = {};
                                   return qi::AnyReference{};
                                 },
                                 ka::exception_message_t()),
                               [&] {
                                 currentObject =
                                   reinterpret_borrow<object>(src);
                                 return qi::py::unwrapAsRef(currentObject);
                               });
      return value.isValid();
    }

    // C++ -> Python
    static handle cast(qi::AnyReference src,
                       return_value_policy /* policy */,
                       handle /* parent */)
    {
      return qi::py::unwrapValue(src).release();
    }

    object currentObject;
  };

  template <>
  struct type_caster<qi::AnyValue>
  {
  public:
    PYBIND11_TYPE_CASTER(qi::AnyValue, _("qi_python.AnyValue"));

    using RefCaster = type_caster<qi::AnyReference>;

    // Python -> C++
    bool load(handle src, bool enableImplicitConv)
    {
      QI_ASSERT_TRUE(src);
      RefCaster refCaster;
      refCaster.load(src, enableImplicitConv);
      value.reset(std::move(refCaster));
      return value.isValid();
    }

    // C++ -> Python
    static handle cast(qi::AnyValue src,
                       return_value_policy policy,
                       handle parent)
    {
      return RefCaster::cast(src.asReference(), policy, parent);
    }
  };

  template <typename T>
  struct type_caster<boost::optional<T>> : optional_caster<boost::optional<T>>
  {};

} // namespace detail
} // namespace pybind11

PYBIND11_DECLARE_HOLDER_TYPE(T, boost::shared_ptr<T>);

#endif // QIPYTHON_COMMON_HPP

max_stars_repo_name: Maelic/libqi-python

max_issues_repo_name: Maelic/libqi-python

max_forks_repo_name: Maelic/libqi-python


text:
// Copyright 2005-2014 Daniel James.
// 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)

//  Based on Peter Dimov's proposal
//  http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2005/n1756.pdf
//  issue 6.18.
//
//  This also contains public domain code from MurmurHash. From the
//  MurmurHash header:

// MurmurHash3 was written by Austin Appleby, and is placed in the public
// domain. The author hereby disclaims copyright to this source code.

#if !defined(BOOST_FUNCTIONAL_HASH_HASH_HPP)
#define BOOST_FUNCTIONAL_HASH_HASH_HPP

#include <boost/container_hash/detail/hash_float.hpp>
#include <boost/container_hash/hash_fwd.hpp>
#include <boost/core/enable_if.hpp>
#include <boost/cstdint.hpp>
#include <boost/limits.hpp>
#include <boost/type_traits/is_enum.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <functional>
#include <string>

#if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
#include <boost/type_traits/is_pointer.hpp>
#endif

#if !defined(BOOST_NO_CXX11_HDR_TYPEINDEX)
#include <typeindex>
#endif

#if !defined(BOOST_NO_CXX11_HDR_SYSTEM_ERROR)
#include <system_error>
#endif

#if defined(BOOST_MSVC)
#pragma warning(push)

#if BOOST_MSVC >= 1400
#pragma warning(disable : 6295) // Ill-defined for-loop : 'unsigned int' values
                                // are always of range '0' to '4294967295'.
                                // Loop executes infinitely.
#endif

#endif

#if BOOST_WORKAROUND(__GNUC__, < 3) && !defined(__SGI_STL_PORT) &&             \
    !defined(_STLPORT_VERSION)
#define BOOST_HASH_CHAR_TRAITS string_char_traits
#else
#define BOOST_HASH_CHAR_TRAITS char_traits
#endif

#if defined(_MSC_VER)
#define BOOST_FUNCTIONAL_HASH_ROTL32(x, r) _rotl(x, r)
#else
#define BOOST_FUNCTIONAL_HASH_ROTL32(x, r) (x << r) | (x >> (32 - r))
#endif

// Detect whether standard library has C++17 headers

#if !defined(BOOST_HASH_CXX17)
#if defined(BOOST_MSVC)
#if defined(_HAS_CXX17) && _HAS_CXX17
#define BOOST_HASH_CXX17 1
#endif
#elif defined(__cplusplus) && __cplusplus >= 201703
#define BOOST_HASH_CXX17 1
#endif
#endif

#if !defined(BOOST_HASH_CXX17)
#define BOOST_HASH_CXX17 0
#endif

#if BOOST_HASH_CXX17 && defined(__has_include)
#if !defined(BOOST_HASH_HAS_STRING_VIEW) && __has_include(<string_view>)
#define BOOST_HASH_HAS_STRING_VIEW 1
#endif
#if !defined(BOOST_HASH_HAS_OPTIONAL) && __has_include(<optional>)
#define BOOST_HASH_HAS_OPTIONAL 1
#endif
#if !defined(BOOST_HASH_HAS_VARIANT) && __has_include(<variant>)
#define BOOST_HASH_HAS_VARIANT 1
#endif
#endif

#if !defined(BOOST_HASH_HAS_STRING_VIEW)
#define BOOST_HASH_HAS_STRING_VIEW 0
#endif

#if !defined(BOOST_HASH_HAS_OPTIONAL)
#define BOOST_HASH_HAS_OPTIONAL 0
#endif

#if !defined(BOOST_HASH_HAS_VARIANT)
#define BOOST_HASH_HAS_VARIANT 0
#endif

#if BOOST_HASH_HAS_STRING_VIEW
#include <string_view>
#endif

#if BOOST_HASH_HAS_OPTIONAL
#include <optional>
#endif

#if BOOST_HASH_HAS_VARIANT
#include <variant>
#endif

namespace boost
{
namespace hash_detail
{
#if defined(_HAS_AUTO_PTR_ETC) && !_HAS_AUTO_PTR_ETC
template <typename T>
struct hash_base
{
    typedef T argument_type;
    typedef std::size_t result_type;
};
#else
template <typename T>
struct hash_base : std::unary_function<T, std::size_t>
{
};
#endif

struct enable_hash_value
{
    typedef std::size_t type;
};

template <typename T>
struct basic_numbers
{
};
template <typename T>
struct long_numbers;
template <typename T>
struct ulong_numbers;
template <typename T>
struct float_numbers
{
};

template <>
struct basic_numbers<bool> : boost::hash_detail::enable_hash_value
{
};
template <>
struct basic_numbers<char> : boost::hash_detail::enable_hash_value
{
};
template <>
struct basic_numbers<unsigned char> : boost::hash_detail::enable_hash_value
{
};
template <>
struct basic_numbers<signed char> : boost::hash_detail::enable_hash_value
{
};
template <>
struct basic_numbers<short> : boost::hash_detail::enable_hash_value
{
};
template <>
struct basic_numbers<unsigned short> : boost::hash_detail::enable_hash_value
{
};
template <>
struct basic_numbers<int> : boost::hash_detail::enable_hash_value
{
};
template <>
struct basic_numbers<unsigned int> : boost::hash_detail::enable_hash_value
{
};
template <>
struct basic_numbers<long> : boost::hash_detail::enable_hash_value
{
};
template <>
struct basic_numbers<unsigned long> : boost::hash_detail::enable_hash_value
{
};

#if !defined(BOOST_NO_INTRINSIC_WCHAR_T)
template <>
struct basic_numbers<wchar_t> : boost::hash_detail::enable_hash_value
{
};
#endif

#if !defined(BOOST_NO_CXX11_CHAR16_T)
template <>
struct basic_numbers<char16_t> : boost::hash_detail::enable_hash_value
{
};
#endif

#if !defined(BOOST_NO_CXX11_CHAR32_T)
template <>
struct basic_numbers<char32_t> : boost::hash_detail::enable_hash_value
{
};
#endif

// long_numbers is defined like this to allow for separate
// specialization for long_long and int128_type, in case
// they conflict.
template <typename T>
struct long_numbers2
{
};
template <typename T>
struct ulong_numbers2
{
};
template <typename T>
struct long_numbers : long_numbers2<T>
{
};
template <typename T>
struct ulong_numbers : ulong_numbers2<T>
{
};

#if !defined(BOOST_NO_LONG_LONG)
template <>
struct long_numbers<boost::long_long_type>
    : boost::hash_detail::enable_hash_value
{
};
template <>
struct ulong_numbers<boost::ulong_long_type>
    : boost::hash_detail::enable_hash_value
{
};
#endif

#if defined(BOOST_HAS_INT128)
template <>
struct long_numbers2<boost::int128_type> : boost::hash_detail::enable_hash_value
{
};
template <>
struct ulong_numbers2<boost::uint128_type>
    : boost::hash_detail::enable_hash_value
{
};
#endif

template <>
struct float_numbers<float> : boost::hash_detail::enable_hash_value
{
};
template <>
struct float_numbers<double> : boost::hash_detail::enable_hash_value
{
};
template <>
struct float_numbers<long double> : boost::hash_detail::enable_hash_value
{
};
} // namespace hash_detail

template <typename T>
typename boost::hash_detail::basic_numbers<T>::type hash_value(T);
template <typename T>
typename boost::hash_detail::long_numbers<T>::type hash_value(T);
template <typename T>
typename boost::hash_detail::ulong_numbers<T>::type hash_value(T);

template <typename T>
typename boost::enable_if<boost::is_enum<T>, std::size_t>::type hash_value(T);

#if !BOOST_WORKAROUND(__DMC__, <= 0x848)
template <class T>
std::size_t hash_value(T* const&);
#else
template <class T>
std::size_t hash_value(T*);
#endif

#if !defined(BOOST_NO_FUNCTION_TEMPLATE_ORDERING)
template <class T, unsigned N>
std::size_t hash_value(const T (&x)[N]);

template <class T, unsigned N>
std::size_t hash_value(T (&x)[N]);
#endif

template <class Ch, class A>
std::size_t hash_value(
    std::basic_string<Ch, std::BOOST_HASH_CHAR_TRAITS<Ch>, A> const&);

#if BOOST_HASH_HAS_STRING_VIEW
template <class Ch>
std::size_t hash_value(
    std::basic_string_view<Ch, std::BOOST_HASH_CHAR_TRAITS<Ch>> const&);
#endif

template <typename T>
typename boost::hash_detail::float_numbers<T>::type hash_value(T);

#if BOOST_HASH_HAS_OPTIONAL
template <typename T>
std::size_t hash_value(std::optional<T> const&);
#endif

#if BOOST_HASH_HAS_VARIANT
std::size_t hash_value(std::monostate);
template <typename... Types>
std::size_t hash_value(std::variant<Types...> const&);
#endif

#if !defined(BOOST_NO_CXX11_HDR_TYPEINDEX)
std::size_t hash_value(std::type_index);
#endif

#if !defined(BOOST_NO_CXX11_HDR_SYSTEM_ERROR)
std::size_t hash_value(std::error_code const&);
std::size_t hash_value(std::error_condition const&);
#endif

// Implementation

namespace hash_detail
{
template <class T>
inline std::size_t hash_value_signed(T val)
{
    const unsigned int size_t_bits = std::numeric_limits<std::size_t>::digits;
    // ceiling(std::numeric_limits<T>::digits / size_t_bits) - 1
    const int length =
        (std::numeric_limits<T>::digits - 1) / static_cast<int>(size_t_bits);

    std::size_t seed = 0;
    T positive = val < 0 ? -1 - val : val;

    // Hopefully, this loop can be unrolled.
    for (unsigned int i = length * size_t_bits; i > 0; i -= size_t_bits)
    {
        seed ^= (std::size_t)(positive >> i) + (seed << 6) + (seed >> 2);
    }
    seed ^= (std::size_t)val + (seed << 6) + (seed >> 2);

    return seed;
}

template <class T>
inline std::size_t hash_value_unsigned(T val)
{
    const unsigned int size_t_bits = std::numeric_limits<std::size_t>::digits;
    // ceiling(std::numeric_limits<T>::digits / size_t_bits) - 1
    const int length =
        (std::numeric_limits<T>::digits - 1) / static_cast<int>(size_t_bits);

    std::size_t seed = 0;

    // Hopefully, this loop can be unrolled.
    for (unsigned int i = length * size_t_bits; i > 0; i -= size_t_bits)
    {
        seed ^= (std::size_t)(val >> i) + (seed << 6) + (seed >> 2);
    }
    seed ^= (std::size_t)val + (seed << 6) + (seed >> 2);

    return seed;
}

template <typename SizeT>
inline void hash_combine_impl(SizeT& seed, SizeT value)
{
    seed ^= value + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}

inline void hash_combine_impl(boost::uint32_t& h1, boost::uint32_t k1)
{
    const uint32_t c1 = 0xcc9e2d51;
    const uint32_t c2 = 0x1b873593;

    k1 *= c1;
    k1 = BOOST_FUNCTIONAL_HASH_ROTL32(k1, 15);
    k1 *= c2;

    h1 ^= k1;
    h1 = BOOST_FUNCTIONAL_HASH_ROTL32(h1, 13);
    h1 = h1 * 5 + 0xe6546b64;
}

// Don't define 64-bit hash combine on platforms without 64 bit integers,
// and also not for 32-bit gcc as it warns about the 64-bit constant.
#if !defined(BOOST_NO_INT64_T) &&                                              \
    !(defined(__GNUC__) && ULONG_MAX == 0xffffffff)

inline void hash_combine_impl(boost::uint64_t& h, boost::uint64_t k)
{
    const boost::uint64_t m = UINT64_C(0xc6a4a7935bd1e995);
    const int r = 47;

    k *= m;
    k ^= k >> r;
    k *= m;

    h ^= k;
    h *= m;

    // Completely arbitrary number, to prevent 0's
    // from hashing to 0.
    h += 0xe6546b64;
}

#endif // BOOST_NO_INT64_T
} // namespace hash_detail

template <typename T>
typename boost::hash_detail::basic_numbers<T>::type hash_value(T v)
{
    return static_cast<std::size_t>(v);
}

template <typename T>
typename boost::hash_detail::long_numbers<T>::type hash_value(T v)
{
    return hash_detail::hash_value_signed(v);
}

template <typename T>
typename boost::hash_detail::ulong_numbers<T>::type hash_value(T v)
{
    return hash_detail::hash_value_unsigned(v);
}

template <typename T>
typename boost::enable_if<boost::is_enum<T>, std::size_t>::type hash_value(T v)
{
    return static_cast<std::size_t>(v);
}

// Implementation by Alberto Barbati and Dave Harris.
#if !BOOST_WORKAROUND(__DMC__, <= 0x848)
template <class T>
std::size_t hash_value(T* const& v)
#else
template <class T>
std::size_t hash_value(T* v)
#endif
{
#if defined(__VMS) && __INITIAL_POINTER_SIZE == 64
    // for some reason ptrdiff_t on OpenVMS compiler with
    // 64 bit is not 64 bit !!!
    std::size_t x =
        static_cast<std::size_t>(reinterpret_cast<long long int>(v));
#else
    std::size_t x =
        static_cast<std::size_t>(reinterpret_cast<std::ptrdiff_t>(v));
#endif
    return x + (x >> 3);
}

#if defined(BOOST_MSVC)
#pragma warning(push)
#if BOOST_MSVC <= 1400
#pragma warning(disable : 4267) // 'argument' : conversion from 'size_t' to
                                // 'unsigned int', possible loss of data
                                // A misguided attempt to detect 64-bit
                                // incompatability.
#endif
#endif

template <class T>
inline void hash_combine(std::size_t& seed, T const& v)
{
    boost::hash<T> hasher;
    return boost::hash_detail::hash_combine_impl(seed, hasher(v));
}

#if defined(BOOST_MSVC)
#pragma warning(pop)
#endif

template <class It>
inline std::size_t hash_range(It first, It last)
{
    std::size_t seed = 0;

    for (; first != last; ++first)
    {
        hash_combine(seed, *first);
    }

    return seed;
}

template <class It>
inline void hash_range(std::size_t& seed, It first, It last)
{
    for (; first != last; ++first)
    {
        hash_combine(seed, *first);
    }
}

#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x551))
template <class T>
inline std::size_t hash_range(T* first, T* last)
{
    std::size_t seed = 0;

    for (; first != last; ++first)
    {
        boost::hash<T> hasher;
        seed ^= hasher(*first) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
    }

    return seed;
}

template <class T>
inline void hash_range(std::size_t& seed, T* first, T* last)
{
    for (; first != last; ++first)
    {
        boost::hash<T> hasher;
        seed ^= hasher(*first) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
    }
}
#endif

#if !defined(BOOST_NO_FUNCTION_TEMPLATE_ORDERING)
template <class T, unsigned N>
inline std::size_t hash_value(const T (&x)[N])
{
    return hash_range(x, x + N);
}

template <class T, unsigned N>
inline std::size_t hash_value(T (&x)[N])
{
    return hash_range(x, x + N);
}
#endif

template <class Ch, class A>
inline std::size_t hash_value(
    std::basic_string<Ch, std::BOOST_HASH_CHAR_TRAITS<Ch>, A> const& v)
{
    return hash_range(v.begin(), v.end());
}

#if BOOST_HASH_HAS_STRING_VIEW
template <class Ch>
inline std::size_t hash_value(
    std::basic_string_view<Ch, std::BOOST_HASH_CHAR_TRAITS<Ch>> const& v)
{
    return hash_range(v.begin(), v.end());
}
#endif

template <typename T>
typename boost::hash_detail::float_numbers<T>::type hash_value(T v)
{
    return boost::hash_detail::float_hash_value(v);
}

#if BOOST_HASH_HAS_OPTIONAL
template <typename T>
inline std::size_t hash_value(std::optional<T> const& v)
{
    if (!v)
    {
        // Arbitray value for empty optional.
        return 0x12345678;
    }
    else
    {
        boost::hash<T> hf;
        return hf(*v);
    }
}
#endif

#if BOOST_HASH_HAS_VARIANT
inline std::size_t hash_value(std::monostate)
{
    return 0x87654321;
}

template <typename... Types>
inline std::size_t hash_value(std::variant<Types...> const& v)
{
    std::size_t seed = 0;
    hash_combine(seed, v.index());
    std::visit([&seed](auto&& x) { hash_combine(seed, x); }, v);
    return seed;
}
#endif

#if !defined(BOOST_NO_CXX11_HDR_TYPEINDEX)
inline std::size_t hash_value(std::type_index v)
{
    return v.hash_code();
}
#endif

#if !defined(BOOST_NO_CXX11_HDR_SYSTEM_ERROR)
inline std::size_t hash_value(std::error_code const& v)
{
    std::size_t seed = 0;
    hash_combine(seed, v.value());
    hash_combine(seed, &v.category());
    return seed;
}

inline std::size_t hash_value(std::error_condition const& v)
{
    std::size_t seed = 0;
    hash_combine(seed, v.value());
    hash_combine(seed, &v.category());
    return seed;
}
#endif

//
// boost::hash
//

// Define the specializations required by the standard. The general purpose
// boost::hash is defined later in extensions.hpp if
// BOOST_HASH_NO_EXTENSIONS is not defined.

// BOOST_HASH_SPECIALIZE - define a specialization for a type which is
// passed by copy.
//
// BOOST_HASH_SPECIALIZE_REF - define a specialization for a type which is
// passed by const reference.
//
// These are undefined later.

#define BOOST_HASH_SPECIALIZE(type)                                            \
    template <>                                                                \
    struct hash<type> : public boost::hash_detail::hash_base<type>             \
    {                                                                          \
        std::size_t operator()(type v) const                                   \
        {                                                                      \
            return boost::hash_value(v);                                       \
        }                                                                      \
    };

#define BOOST_HASH_SPECIALIZE_REF(type)                                        \
    template <>                                                                \
    struct hash<type> : public boost::hash_detail::hash_base<type>             \
    {                                                                          \
        std::size_t operator()(type const& v) const                            \
        {                                                                      \
            return boost::hash_value(v);                                       \
        }                                                                      \
    };

#define BOOST_HASH_SPECIALIZE_TEMPLATE_REF(type)                               \
    struct hash<type> : public boost::hash_detail::hash_base<type>             \
    {                                                                          \
        std::size_t operator()(type const& v) const                            \
        {                                                                      \
            return boost::hash_value(v);                                       \
        }                                                                      \
    };

BOOST_HASH_SPECIALIZE(bool)
BOOST_HASH_SPECIALIZE(char)
BOOST_HASH_SPECIALIZE(signed char)
BOOST_HASH_SPECIALIZE(unsigned char)
#if !defined(BOOST_NO_INTRINSIC_WCHAR_T)
BOOST_HASH_SPECIALIZE(wchar_t)
#endif
#if !defined(BOOST_NO_CXX11_CHAR16_T)
BOOST_HASH_SPECIALIZE(char16_t)
#endif
#if !defined(BOOST_NO_CXX11_CHAR32_T)
BOOST_HASH_SPECIALIZE(char32_t)
#endif
BOOST_HASH_SPECIALIZE(short)
BOOST_HASH_SPECIALIZE(unsigned short)
BOOST_HASH_SPECIALIZE(int)
BOOST_HASH_SPECIALIZE(unsigned int)
BOOST_HASH_SPECIALIZE(long)
BOOST_HASH_SPECIALIZE(unsigned long)

BOOST_HASH_SPECIALIZE(float)
BOOST_HASH_SPECIALIZE(double)
BOOST_HASH_SPECIALIZE(long double)

BOOST_HASH_SPECIALIZE_REF(std::string)
#if !defined(BOOST_NO_STD_WSTRING) && !defined(BOOST_NO_INTRINSIC_WCHAR_T)
BOOST_HASH_SPECIALIZE_REF(std::wstring)
#endif
#if !defined(BOOST_NO_CXX11_CHAR16_T)
BOOST_HASH_SPECIALIZE_REF(std::basic_string<char16_t>)
#endif
#if !defined(BOOST_NO_CXX11_CHAR32_T)
BOOST_HASH_SPECIALIZE_REF(std::basic_string<char32_t>)
#endif

#if BOOST_HASH_HAS_STRING_VIEW
BOOST_HASH_SPECIALIZE_REF(std::string_view)
#if !defined(BOOST_NO_STD_WSTRING) && !defined(BOOST_NO_INTRINSIC_WCHAR_T)
BOOST_HASH_SPECIALIZE_REF(std::wstring_view)
#endif
#if !defined(BOOST_NO_CXX11_CHAR16_T)
BOOST_HASH_SPECIALIZE_REF(std::basic_string_view<char16_t>)
#endif
#if !defined(BOOST_NO_CXX11_CHAR32_T)
BOOST_HASH_SPECIALIZE_REF(std::basic_string_view<char32_t>)
#endif
#endif

#if !defined(BOOST_NO_LONG_LONG)
BOOST_HASH_SPECIALIZE(boost::long_long_type)
BOOST_HASH_SPECIALIZE(boost::ulong_long_type)
#endif

#if defined(BOOST_HAS_INT128)
BOOST_HASH_SPECIALIZE(boost::int128_type)
BOOST_HASH_SPECIALIZE(boost::uint128_type)
#endif

#if BOOST_HASH_HAS_OPTIONAL
template <typename T>
BOOST_HASH_SPECIALIZE_TEMPLATE_REF(std::optional<T>)
#endif

#if !defined(BOOST_HASH_HAS_VARIANT)
template <typename... T>
BOOST_HASH_SPECIALIZE_TEMPLATE_REF(std::variant<T...>)
BOOST_HASH_SPECIALIZE(std::monostate)
#endif

#if !defined(BOOST_NO_CXX11_HDR_TYPEINDEX)
    BOOST_HASH_SPECIALIZE(std::type_index)
#endif

#undef BOOST_HASH_SPECIALIZE
#undef BOOST_HASH_SPECIALIZE_REF
#undef BOOST_HASH_SPECIALIZE_TEMPLATE_REF

// Specializing boost::hash for pointers.

#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)

        template <class T>
        struct hash<T*> : public boost::hash_detail::hash_base<T*>
{
    std::size_t operator()(T* v) const
    {
#if !BOOST_WORKAROUND(__SUNPRO_CC, <= 0x590)
        return boost::hash_value(v);
#else
        std::size_t x =
            static_cast<std::size_t>(reinterpret_cast<std::ptrdiff_t>(v));

        return x + (x >> 3);
#endif
    }
};

#else

// For compilers without partial specialization, we define a
// boost::hash for all remaining types. But hash_impl is only defined
// for pointers in 'extensions.hpp' - so when BOOST_HASH_NO_EXTENSIONS
// is defined there will still be a compile error for types not supported
// in the standard.

namespace hash_detail
{
template <bool IsPointer>
struct hash_impl;

template <>
struct hash_impl<true>
{
    template <class T>
    struct inner : public boost::hash_detail::hash_base<T>
    {
        std::size_t operator()(T val) const
        {
#if !BOOST_WORKAROUND(__SUNPRO_CC, <= 590)
            return boost::hash_value(val);
#else
            std::size_t x =
                static_cast<std::size_t>(reinterpret_cast<std::ptrdiff_t>(val));

            return x + (x >> 3);
#endif
        }
    };
};
} // namespace hash_detail

template <class T>
struct hash : public boost::hash_detail::hash_impl<
                  boost::is_pointer<T>::value>::BOOST_NESTED_TEMPLATE inner<T>
{
};

#endif
} // namespace boost

#undef BOOST_HASH_CHAR_TRAITS
#undef BOOST_FUNCTIONAL_HASH_ROTL32

#if defined(BOOST_MSVC)
#pragma warning(pop)
#endif

#endif // BOOST_FUNCTIONAL_HASH_HASH_HPP

// Include this outside of the include guards in case the file is included
// twice - once with BOOST_HASH_NO_EXTENSIONS defined, and then with it
// undefined.

#if !defined(BOOST_HASH_NO_EXTENSIONS) &&                                      \
    !defined(BOOST_FUNCTIONAL_HASH_EXTENSIONS_HPP)
#include <boost/container_hash/extensions.hpp>
#endif

max_stars_repo_name: sotaoverride/backup

max_issues_repo_name: sotaoverride/backup

max_forks_repo_name: sotaoverride/backup


text:
#define BOOST_TEST_MODULE "Ethkey_Tests"
#include <boost/test/included/unit_test.hpp>

max_stars_repo_name: devktor/libbitcrypto

max_issues_repo_name: BitProfile/libethcrypto

max_forks_repo_name: BitProfile/libethcrypto


text:
//
// Created by lramirez on 11.11.19.
//

#include <boost/range/irange.hpp>
#include "reads_processing.h"

#include "utils.h"

extern std::shared_ptr<CG_Index> cg_index;
extern std::shared_ptr<BisquickOptions> bisquickOptions;
extern std::unordered_map<seqan::DnaString, std::vector<map_value>, DnaStringHasher> compKMap;
extern std::unordered_map<unsigned, unsigned> cgpos2index;

int process_reads() {
    seqan::CharString seqFileName = bisquickOptions->readsfile;
    seqan::SeqFileIn seqFileIn;
    if (!seqan::open(seqFileIn, seqan::toCString(seqFileName))) {
        std::cerr << "ERROR: Could not open the file.\n";
        return 1;
    }
    seqan::StringSet<seqan::CharString> ids;
    seqan::StringSet<seqan::Dna5String> seqs;
    try { seqan::readRecords(ids, seqs, seqFileIn); }
    catch (seqan::Exception const &e) {
        std::cout << "ERROR: " << e.what() << std::endl;
        return 1;
    }
    for (unsigned i = 0; i < seqan::length(ids); ++i) {
    //for (unsigned i = 0; i < 10; ++i) {
        if (i % (seqan::length(ids)/100) == 0) {
            std::cout << "read [" << i << "/" << seqan::length(ids) << "]:\t" << ids[i] << '\n';
        }
        process_read(seqs[i]);
    }
    return 0;
}

void process_read(seqan::Dna5String seq) {
    int seqlen = seqan::length(seq);
    for (auto i : boost::irange(0, seqlen - bisquickOptions->kmersize + 1)) {
        std::vector<kmer_match> possible_calls;
        seqan::Dna5String kmer = infixWithLength(seq, i, bisquickOptions->kmersize);
        possible_calls = process_kmer(kmer);
        possible_calls.erase(unique(possible_calls.begin(), possible_calls.end()), possible_calls.end());
        if (possible_calls.size() > 1) {
            for (auto &possible_call : possible_calls) {
                int c_read_pos = possible_call.k_beg - i;
                seqan::Dna5String seqref = recoverKmerFai(c_read_pos, seqlen - bisquickOptions->kmersize);
                possible_call.tie_break_missmatch = countdiff_chars(seqan::DnaString(seqref), seqan::DnaString(seq));
            }
        }
        auto best_call = std::min_element(possible_calls.begin(),possible_calls.end());
        if (!possible_calls.empty()) {
            for (auto cpg: best_call->cpgs) {
                int caddress = cgpos2index[cpg.cpos + best_call->k_beg];
                cg_index->methylated[caddress] = cg_index->methylated[caddress] + cpg.methylated;
                cg_index->unmethylated[caddress] = cg_index->unmethylated[caddress] + cpg.unmethylated;
            }
        }
    }

}

std::vector<kmer_match> process_kmer(seqan::Dna5String kmer) {
    seqan::DnaString base4kmerStr(kmer);
    seqan::DnaString compresskmer = seqan::DnaString(compressKmer(base4kmerStr));
    seqan::Dna5 t_nucleotide('T');
    std::vector<kmer_match> possible_calls;
    if (compKMap.find(compresskmer) == compKMap.end()) {
    } else {
        // When the reduced kmer is in the map
        // check all possible matches
        for (int i = 0; i < compKMap[compresskmer].size(); ++i) {
            kmer_match possible_match;
            possible_match.k_beg = compKMap[compresskmer][i].beg;
            int miss_matchs = 0;
            int max_miss_matchs = compKMap[compresskmer][i].cpg_pos.size() + bisquickOptions->missmatch_tol;
            seqan::Dna5String refkmer = recoverKmerFai(compKMap[compresskmer][i].beg);
            int diffs = countdiff_chars(seqan::DnaString(refkmer), seqan::DnaString(kmer));
            if (diffs <= max_miss_matchs) {
                std::vector<meth_caller_struct> curr_cgs(compKMap[compresskmer][i].cpg_pos.size(), {0, 0, 0});
                // check  if there is a conversion in al cpg positions of the kmer
                for (int j = 0; j < compKMap[compresskmer][i].cpg_pos.size(); ++j) {
                    int cpos = compKMap[compresskmer][i].cpg_pos[j];
                    curr_cgs[j].cpos = cpos;
                    if (kmer[cpos] == t_nucleotide) {
                        curr_cgs[j].unmethylated++;
                        miss_matchs++;
                    } else {
                        curr_cgs[j].methylated++;
                    }
                }
                if (diffs == miss_matchs) {
                    possible_match.cpgs.resize(curr_cgs.size());
                    possible_match.cpgs = curr_cgs;
                    possible_calls.emplace_back(possible_match);
                }
            }
        }
    }
    return possible_calls;
}

int countdiff_chars(seqan::DnaString kmerref, seqan::DnaString kmerread) {
    int sum = 0;
    for (int i = 0; i < length(kmerref); i++) {
        sum = sum + (std::bitset<2>(kmerref[i].value) ^ std::bitset<2>(kmerread[i].value)).count();
    }
    return sum;
}

seqan::Dna5String recoverKmerFai(unsigned beg, unsigned morechars) {
    auto current_file = seqan::toCString(bisquickOptions->currentFile);
    auto seq_id = cg_index->seq_id;
    unsigned end = beg + bisquickOptions->kmersize + morechars;
    // Try to load index and create on the fly if necessary.
    seqan::FaiIndex faiIndex;
    if (!seqan::open(faiIndex, current_file)) {
        if (!seqan::build(faiIndex, current_file)) {
            std::cerr << "ERROR: Index could not be loaded or built.\n";
            return 0;
        }
        if (!seqan::save(faiIndex))    // Name is stored from when reading.
        {
            std::cerr << "ERROR: Index could not be written do disk.\n";
            return 0;
        }
    }
    // Translate sequence name to index.
    unsigned idx = 0;
    if (!seqan::getIdByName(idx, faiIndex, seq_id)) {
        std::cerr << "ERROR: Index does not know about sequence " << seq_id << "\n";
        return 0;
    }
    // Convert positions into integers.
    unsigned beginPos = beg;
    unsigned endPos = end;
    // Make sure begin and end pos are on the sequence and begin <= end.
    if (beginPos > seqan::sequenceLength(faiIndex, idx))
        beginPos = seqan::sequenceLength(faiIndex, idx);
    if (endPos > seqan::sequenceLength(faiIndex, idx))
        endPos = seqan::sequenceLength(faiIndex, idx);
    if (beginPos > endPos)
        endPos = beginPos;
    // Finally, get infix of sequence.
    seqan::Dna5String sequenceInfix;
    seqan::readRegion(sequenceInfix, faiIndex, idx, beginPos, endPos);
    return sequenceInfix;
}

max_stars_repo_name: sccluisx/Bisquick

max_issues_repo_name: sccluisx/Bisquick

max_forks_repo_name: sccluisx/Bisquick


text: #include <boost/date_time/gregorian/gregorian_io.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <map>
#include <algorithm>
#include <stdint.h>

#include "gflags/gflags.h"
#include "glog/logging.h"
#include <boost/shared_ptr.hpp>

#include "caffe/proto/caffe.pb.h"
#include "caffe/blob.hpp"
#include "caffe/util/benchmark.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/rng.hpp"
#include "caffe/layer.hpp"
#include "caffe/layers/roi_align_layer.hpp"
#include "caffe/filler.hpp"

#include "gtest/gtest.h"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/test/test_gradient_check_util.hpp"

using namespace std;
using namespace caffe;

int main(int nargc, char** args) {
  while(1) {
    std::cout << "type ENTER to save: ";
    // std::string line;
    // cin >> line;
    char line;
    line = cin.get();
    if (line == '\n') {
      std::cout << "YES" << '\n';
    } else {
      std::cout << "NO" << "\n\n";
    }
    while(cin.get() != '\n');
  }
  return 0;
}


text:
/**
 ** Copyright (c) 2014 Illumina, Inc.
 **
 ** This file is part of Illumina's Enhanced Artificial Genome Engine (EAGLE),
 ** covered by the "BSD 2-Clause License" (see accompanying LICENSE file)
 **
 ** \description Syntactic sugar for Genotype info.
 **
 ** \author Mauricio Varea
 **/

#ifndef EAGLE_MODEL_GENOTYPE_HH
#define EAGLE_MODEL_GENOTYPE_HH

#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>

namespace eagle
{
namespace model
{

class Ploidy
{
public:
    Ploidy( unsigned int level, std::map<std::string,unsigned int> exceptions )
    : organismPloidy_(level), nonPloidyChromosomes_(exceptions) {}
    Ploidy( unsigned int level = 0)
    : organismPloidy_(level) {}

    unsigned int level(const std::string& chrom) const;
    unsigned int max() const;
    std::string label(unsigned int p) const;
    std::string label() const {return label(organismPloidy_);}
private:
    unsigned int organismPloidy_;
    std::map<std::string,unsigned int> nonPloidyChromosomes_;
};

/*
class Genotype : public std::vector<bool>
{
public:
    // initialize Genotype as Homo-ref
    Genotype(unsigned int n)
    : std::vector<bool>(n,false), phased_(false) {}
    // assume haploid, if no ploidy is given
    Genotype()
    : std::vector<bool>(1,false), phased_(false) {}

    // an event cannot be Homo-ref, since this implies a variant has not been applied
    bool isHomozygousRef() const {return this->size() == (size_t) std::count(this->begin(),this->end(),false);}
    void setHomozygousRef() {std::fill(this->begin(),this->end(),false);}  // not processed
    // non-conflicting events are Homo-diff by default
    bool isHomozygousDiff() const {return this->size() == (size_t) std::count(this->begin(),this->end(),true);}
    void setHomozygousDiff() {std::fill(this->begin(),this->end(),true);}  // processed in all alleles
    // any of the above
    bool isHomozygous() const {return isHomozygousDiff() || isHomozygousRef();}
    // conflicting events end up as Het
    bool isHeterozygous() const {return !isHomozygous();}

public:
    bool phased_;
};
*/

/*
 * \brief Genotype contains discrete set of alleles
 *    -1: any allele
 *     0: REF allele
 *  1..n: ALT alleles
 */
class Genotype : public std::set<int>
{
public:
    Genotype(unsigned int n = 1, unsigned int altGtIndex = 1)
        : phased(false), ploidy(n), altGtIndex_(altGtIndex) {}

    void setPloidy(unsigned int n);
    unsigned int getPloidy() const {return ploidy;}

    std::set<int>::iterator altBegin() const {int i=1; while (this->find(--i) == this->end()) {if (-2 == i) return this->begin();} return this->upper_bound(i);}
    std::set<int>::iterator altBegin() {int i=1; while (this->find(--i) == this->end()) {if (-2 == i) return this->begin();} return this->upper_bound(i);}

    // a processed event cannot be Homo-ref, since this implies a variant has not been applied
    //bool isHomozygousRef() const {return this->empty() || this->rbegin().base() == this->find(0);}
    bool isHomozygousRef() const  {return this->empty() || ( 1 == this->size() && 0 == *(this->begin()) );}
    bool isHomozygousDiff() const {return             ploidy == this->size() && 0 < *(this->begin());}
    bool isHeterozygous() const   {return                  1 == this->size() && 0 < *(this->begin());}
    bool isHomozygous() const {return isHomozygousDiff() || isHomozygousRef();}

    unsigned int minPloidy() const {return (0 == this->size() || 0 >= *(this->rbegin())) ? 1      : static_cast<unsigned int>( *(altBegin()) );}
    unsigned int maxPloidy() const {return (0 == this->size() || 0 >= *(this->rbegin())) ? ploidy : static_cast<unsigned int>( *(this->rbegin()) );}

    unsigned int altSize() const {return this->size() - static_cast<size_t>(this->find(0) != this->end())
                                                      - static_cast<size_t>(-1 == *(this->begin()));}

    bool set(int v);
    bool reset(int v);
    std::ostream& dump(std::ostream& os);
    friend std::istream& operator>>( std::istream& is, Genotype& gt );

    bool phased;

private:
    unsigned int ploidy;
    unsigned int altGtIndex_;
};

std::ostream& operator<<( std::ostream& os, const Genotype& gt );

} // namespace model
} // namespace eagle

#endif // EAGLE_MODEL_GENOTYPE_HH

ext: hh

max_stars_repo_name: sequencing/EAGLE

max_issues_repo_name: sequencing/EAGLE

max_forks_repo_name: sequencing/EAGLE


text:
// -*-c++-*-

/***************************************************************************
                                csvsaver.cpp
         Class for saving results to a file as comma seperated values
                             -------------------
    begin                : 23-JUN-2003
    copyright            : (C) 2003 by The RoboCup Soccer Simulator
                           Maintenance Group.
    email                : sserver-admin@lists.sourceforge.net
***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU LGPL as published by the Free Software  *
 *   Foundation; either version 3 of the License, or (at your option) any  *
 *   later version.                                                        *
 *                                                                         *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "csvsaver.h"

#include "utility.h"

#include <rcssbase/conf/builder.hpp>
#include <rcssbase/conf/parser.hpp>

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>

#include <fstream>
#include <cerrno>
#include <ctime>

#ifdef __CYGWIN__
// cygwin is not win32
#elif defined(_WIN32) || defined(__WIN32__) || defined (WIN32)
#define RCSS_WIN
#endif

const std::string CSVSaver::NAME = "CSVSaver";

CSVSaverParam &
CSVSaverParam::instance()
{
    return CSVSaverParam::instance( NULL );
}

CSVSaverParam &
CSVSaverParam::instance( rcss::conf::Builder * parent )
{
    static bool parent_set = false;
    if ( parent != NULL || parent_set )
    {
        static CSVSaverParam rval( parent );
        parent_set = true;
        return rval;
    }
    // hack to allow link testing to call instance without crashing
    // do not used the return value in these situations
    CSVSaverParam * rval = NULL;
    return *rval;
}

bool
CSVSaverParam::init( rcss::conf::Builder * parent )
{
    assert( parent );
    instance( parent );

    if ( ! instance().M_builder->parser() )
    {
        std::cerr << __FILE__ << ": " << __LINE__
                  << ": internal error: CSVSaverParam could not find configuration parser\n";
        std::cerr << "Please submit a full bug report to sserver-bugs@lists.sf.net\n";
        return false;
    }

#if defined(RCSS_WIN) || defined(__CYGWIN__)
    //std::string conf_dir = "~\\.rcssserver\\";
    std::string conf_dir = ".";
#else
    std::string conf_dir = "~/.rcssserver";
#endif
    const char * env_conf_dir = std::getenv( "RCSS_CONF_DIR" );
    if ( env_conf_dir )
    {
        conf_dir = env_conf_dir;
    }

    boost::filesystem::path conf_path;
    try
    {
        conf_path = boost::filesystem::path( tildeExpand( conf_dir )
#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2
#  ifndef BOOST_FILESYSTEM_NO_DEPRECATED
                                             , &boost::filesystem::native
#  endif
#endif
                                             );

        conf_path /= "CSVSaver.conf";
    }
    catch ( std::exception & e )
    {
        std::cerr << __FILE__ << ": " << __LINE__
                  << " Exception caught! " << e.what()
                  << "\nCould not read config directory '"
                  << tildeExpand( conf_dir ) << "'"
                  << std::endl;
    }

    if ( ! instance().M_builder->parser()->parseCreateConf( conf_path,
                                                            "CSVSaver" ) )
    {
        std::cerr << "could not create or parse configuration file '"
                  << conf_path.BOOST_FS_FILE_STRING()
                  << "'" << std::endl;
        return false;
    }

    if ( instance().M_builder->version() != instance().M_builder->parsedVersion() )
    {
        std::cerr << "Version mismatched in the configuration file. "
                  << "Need to regenerate '" << conf_path.BOOST_FS_FILE_STRING() << "'"
                  << " or set '" << instance().M_builder->version() << "' to the 'version' option."
                  << std::endl;
//         std::cerr << "registered version = ["
//                   << instance().M_builder->version() << "]\n"
//                   << "parsed version = ["
//                   << instance().M_builder->parsedVersion() << "]\n"
//                   << std::flush;
        return false;
    }

    return true;
}

CSVSaverParam::CSVSaverParam( rcss::conf::Builder * parent )
    : M_builder( new rcss::conf::Builder( parent, VERSION, "CSVSaver" ) )
{
    setDefaults();
    addParams();
}

CSVSaverParam::~CSVSaverParam()
{
    //std::cerr << "delete CSVSaverParam" << std::endl;
}

void
CSVSaverParam::setDefaults()
{
    M_save = false;
    M_filename = "rcssserver.csv";
}

void
CSVSaverParam::addParams()
{
    M_builder->addParam( "save",
                         M_save,
                         "If save is on/true, then the saver will attempt to save"
                         " the results to the database.  Otherwise it will do nothing." );
    M_builder->addParam( "filename",
                         M_filename,
                         "The file to save the results to.  If this file does not"
                         " exist it will be created.  If the file does exist, the"
                         " results will be appended to the end." );
}

CSVSaver::CSVSaver()
    : ResultSaver(),
      M_left_coin( false ),
      M_right_coin( false )
{
    for ( int i = 0; i < TEAM_RIGHT + 1; ++i )
    {
        M_score[ i ] = 0;
        M_pen_taken[ i ] = 0;
        M_pen_scored[ i ] = 0;
    }
}

CSVSaver::~CSVSaver()
{
    if ( M_file.is_open() )
    {
        M_file.close();
    }
}

void
CSVSaver::openResultsFile()
{
    bool new_file = false;
    boost::filesystem::path file_path;
    try
    {
        file_path = boost::filesystem::path( tildeExpand( CSVSaverParam::instance().filename() )
#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2
#  ifndef BOOST_FILESYSTEM_NO_DEPRECATED
                                             , &boost::filesystem::native
#  endif
#endif
                                             );
        new_file = ! boost::filesystem::exists( file_path );
    }
    catch ( std::exception & e )
    {
        std::cerr << __FILE__ << ':' << __LINE__
                  << " Exception caught! " << e.what()
                  << "\nCould not open result file: "
                  << tildeExpand( CSVSaverParam::instance().filename() )
                  << std::endl;
        return;
    }

    M_file.open( file_path.BOOST_FS_FILE_STRING().c_str(),
                 std::ofstream::out | std::ostream::app );
    if ( ! M_file.is_open() )
    {
        std::cerr << "Error: could not open results file:"
                  << strerror( errno ) << std::endl;
        return;
    }

    if ( new_file )
    {
        M_file << "time, left team, right team, left coach, right coach,"
               << " left score, right score, left pen taken, right pen taken,"
               << " left pen score, right pen score, cointoss"
               << std::endl;
    }
}

bool
CSVSaver::doEnabled() const
{
    return CSVSaverParam::instance().save();
}

void
CSVSaver::doSaveStart()
{
    if ( CSVSaverParam::instance().save() )
    {
        openResultsFile();
    }
}

void
CSVSaver::doSaveTime( const tm & time )
{
    M_time = time;
}

void
CSVSaver::doSaveTeamName( team_id id,
                          const std::string & name )
{
    M_team_name[ id ] = name;
}

void
CSVSaver::doSaveCoachName( team_id id,
                           const std::string & name )
{
    M_coach_name[ id ] = name;
}

void
CSVSaver::doSaveScore( team_id id,
                       unsigned int score )
{
    M_score[ id ] = score;
}

void
CSVSaver::doSavePenTaken( team_id id,
                          unsigned int taken )
{
    M_pen_taken[ id ] = taken;
}

void
CSVSaver::doSavePenScored( team_id id,
                           unsigned int scored )
{
    M_pen_scored[ id ] = scored;
}

void
CSVSaver::doSaveCoinTossWinner( team_id id )
{
    switch ( id ) {
    case TEAM_LEFT:
        M_left_coin = true;
        M_right_coin = false;
        break;
    case TEAM_RIGHT:
        M_left_coin = false;
        M_right_coin = true;
        break;
    default:
        M_left_coin = false;
        M_right_coin = false;
        break;
    }
}

bool
CSVSaver::doSaveComplete()
{
    if ( M_file.is_open() )
    {
        M_file.seekp( std::ofstream::end );
        char time_str[256];
        std::strftime( time_str, 256, "%Y-%m-%d %H:%M:%S", &M_time );
        M_file << time_str << ", ";

        if ( M_team_name[ TEAM_LEFT ].empty() )
        {
            M_file << "NULL, ";
        }
        else
        {
            M_file << "\"" << M_team_name[ TEAM_LEFT ] << "\", ";
        }

        if ( M_team_name[ TEAM_RIGHT ].empty() )
        {
            M_file << "NULL, ";
        }
        else
        {
            M_file << "\"" << M_team_name[ TEAM_RIGHT ] << "\", ";
        }

        if ( M_coach_name[ TEAM_LEFT ].empty() )
        {
            M_file << "NULL, ";
        }
        else
        {
            M_file << "\"" << M_coach_name[ TEAM_LEFT ] << "\", ";
        }

        if ( M_coach_name[ TEAM_RIGHT ].empty() )
        {
            M_file << "NULL, ";
        }
        else
        {
            M_file << "\"" << M_coach_name[ TEAM_RIGHT ] << "\", ";
        }

        M_file << M_score[ TEAM_LEFT ] << ", " << M_score[ TEAM_RIGHT ] << ", ";
        if ( M_pen_taken[ TEAM_LEFT ] || M_pen_taken[ TEAM_RIGHT ] )
        {
            M_file << M_pen_taken[ TEAM_LEFT ] << ", " << M_pen_taken[ TEAM_RIGHT ] << ", "
                   << M_pen_scored[ TEAM_LEFT ] << ", " << M_pen_scored[ TEAM_RIGHT ] << ", ";
        }
        else
        {
            M_file << "NULL, NULL, ";
            M_file << "NULL, NULL, ";
        }

        if ( M_left_coin )
        {
            M_file << "LEFT";
        }
        else if ( M_right_coin )
        {
            M_file << "RIGHT";
        }
        else
        {
            M_file << "NULL";
        }
        M_file << std::endl;

        if ( ! M_file.good() )
        {
            std::cerr << CSVSaverParam::instance().filename()
                      << ": Error writing results: "
                      << strerror( errno ) << std::endl;
        }
        else
        {
            return true;
        }
    }
    return false;
}

const char *
CSVSaver::doGetName() const
{
    //return "CSVSaver";
    return CSVSaver::NAME.c_str();
}

ResultSaver::Ptr
CSVSaver::create()
{
    return ResultSaver::Ptr( new CSVSaver() );
}

namespace {
// template< typename Saver >
// ResultSaver::Ptr
// create()
// {
//     return ResultSaver::Ptr( new Saver() );
// }
//rcss::RegHolder s = ResultSaver::factory().autoReg( &create< CSVSaver >, "CSVSaver" );

rcss::RegHolder s = ResultSaver::factory().autoReg( &CSVSaver::create, CSVSaver::NAME );
}


text:
/* To the extent possible under law, bayan has waived all copyright and related
 * or neighboring rights to program.
 *
 * Written by 2020 Anton Karmanov <bergentroll@insiberia.net>.
 */

#define BOOST_TEST_MAIN

#include <boost/test/unit_test.hpp>
#include <filesystem>
#include <fstream>

#include "lazy_digest.hpp"

using namespace std;
using namespace otus;
namespace fs = filesystem;

BOOST_AUTO_TEST_SUITE(LazyDigestTest);

BOOST_AUTO_TEST_CASE(equal) {
  fs::path path { "test_file_equal.txt" };
  ofstream f { path };
  for(int i { }; i < 10; ++i)
    f << to_string(i) << " Dolorem ipsum dolor sit amet";
  f.close();

  LazyDigest dig1 { path, 21 };
  LazyDigest dig2 { path, 21 };

  BOOST_CHECK(dig1.matches(dig2));
}

BOOST_AUTO_TEST_CASE(not_equal) {
  fs::path path1 { "test_file_not_equal_1.txt" };
  fs::path path2 { "test_file_not_equal_2.txt" };
  ofstream f1 { path1 };
  ofstream f2 { path2 };
  for(int i { }; i < 10; ++i) {
    f1 << to_string(i) << " Dolorem ipsum dolor sit amet";
    f2 << to_string(i) << " Dolorem ipsum dolor sit amet";
  }
  f1 << '!'; f2 << '?';
  f1.close(); f2.close();

  LazyDigest dig1 { path1, 21 };
  LazyDigest dig2 { path2, 21 };

  BOOST_CHECK(!dig1.matches(dig2));
}

BOOST_AUTO_TEST_CASE(different_block_size) {
  fs::path path { "test_file_block_size.txt" };
  ofstream f { path };
  LazyDigest dig1 { path, 20 }, dig2 { path, 21 };
  BOOST_CHECK_THROW(dig1.matches(dig2), LazyDigest::BinaryOpIncompatibility);
}

BOOST_AUTO_TEST_CASE(different_digest_func) {
  fs::path path { "test_file_digest_func.txt" };
  ofstream f { path };
  LazyDigest
    dig1 { path, 20, make_crc_digest<boost::crc_16_type> },
    dig2 { path, 20, make_crc_digest<boost::crc_32_type> };
  BOOST_CHECK_THROW(dig1.matches(dig2), LazyDigest::BinaryOpIncompatibility);
}

BOOST_AUTO_TEST_SUITE_END();


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

#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include "PeriodVal.h"
#include "PatternScannerEngine.h"
#include "SegmentConstraint.h"
#include "SegmentValsCloseToLinearEq.h"
#include "SegmentListConstraint.h"
#include "SlopeIncreasesConstraint.h"
#include "PatternMatchValidator.h"
#include "EndWithinPercentOfStart.h"
#include "PeriodValSegment.h"
#include "VScanner.h"
#include "TestHelper.h"
#include "RecoverPercentOfDepth.h"
#include "BreakoutAboveFirstHighValidatorFactory.h"

using namespace boost::posix_time;
using namespace boost::gregorian;
using namespace testHelper;

BOOST_AUTO_TEST_CASE( VScanner_QCOR_20130819_LHSofDoubleBottom )
{
	PeriodValSegmentPtr allPerSegment = PeriodValSegment::readFromFile("./patternScan/QCOR_DoubleBottom_Weekly.csv");

	PeriodValSegmentPair splitSeg = allPerSegment->split(11);
	PeriodValSegmentPtr vData = splitSeg.first;
	genPeriodValSegmentInfo("V segment data",*vData);

	VScanner scanner;
	scanner.upTrendValidatorFactory().addFactory(
			PatternMatchValidatorFactoryPtr(new RecoverPercentOfDepth(60.0)));

	PatternMatchListPtr patternMatches = scanner.scanPatternMatches(vData);

	verifyMatchList("VScanner_QCOR_20130819_LHSofDoubleBottom",patternMatches,1);

	PatternMatchPtr thePatternMatch = patternMatches->front();

	verifyPatternMatch("V Match on LHS",
			ptime(date(2013,8,26)),ptime(date(2013,10,21)),2,thePatternMatch);

}

BOOST_AUTO_TEST_CASE( VScanner_QCOR_20130819_RHSofDoubleBottom )
{
	PeriodValSegmentPtr chartData = PeriodValSegment::readFromFile("./patternScan/QCOR_DoubleBottom_Weekly.csv");

	BOOST_TEST_MESSAGE("Testing V sub-patterns for RHS of double bottom of QCOR");
	PeriodValSegmentPair splitQCORdata = chartData->split(8);
	PeriodValSegmentPtr rhsSegData = splitQCORdata.second;

	genPeriodValSegmentInfo("V RHS segment data",*rhsSegData);

	VScanner scanner;
    scanner.upTrendValidatorFactory().addFactory(
            PatternMatchValidatorFactoryPtr(new RecoverPercentOfDepth(50.0)));
    scanner.upTrendValidatorFactory().addFactory(PatternMatchValidatorFactoryPtr(new BreakoutAboveFirstHighValidatorFactory()));

	PatternMatchListPtr patternMatches = scanner.scanPatternMatches(rhsSegData);

	verifyMatchList("VScanner_QCOR_20130819_RHSofDoubleBottom",patternMatches,1);

	PatternMatchPtr thePatternMatch = patternMatches->front();

	verifyPatternMatch("V Match on RHS",
            ptime(date(2013,10,21)),ptime(date(2014,2,10)),2,thePatternMatch);

}

max_stars_repo_name: sroehling/ChartPatternRecognitionLib

max_issues_repo_name: sroehling/ChartPatternRecognitionLib

max_forks_repo_name: sroehling/ChartPatternRecognitionLib


text:
#include <scitbx/array_family/boost_python/flex_fwd.h>

#include <scitbx/array_family/boost_python/flex_wrapper.h>
#include <scitbx/serialization/single_buffered.h>
#include <scitbx/matrix/transpose_multiply.h>
#include <scitbx/math/utils.h>
#include <boost/python/make_constructor.hpp>
#include <boost/python/args.hpp>
#include <boost/python/return_arg.hpp>
#include <boost/format.hpp>
#include "flex_helpers.h"

namespace scitbx { namespace serialization { namespace single_buffered {

  inline
  char* to_string(char* start, vec3<int> const& value)
  {
    return
      to_string(to_string(to_string(start, value[0]), value[1]), value[2]);
  }

  template <>
  struct from_string<vec3<int> >
  {
    from_string(const char* start)
    {
      end = start;
      for(std::size_t i=0;i<3;i++) {
        from_string<int> proxy(end);
        value[i] = proxy.value;
        end = proxy.end;
      }
    }

    vec3<int> value;
    const char* end;
  };

}}} // namespace scitbx::serialization::single_buffered

#include <scitbx/array_family/boost_python/flex_pickle_single_buffered.h>

namespace scitbx { namespace af {
namespace {

  flex<vec3<int> >::type*
  join(
    af::const_ref<int> const& x,
    af::const_ref<int> const& y,
    af::const_ref<int> const& z)
  {
    SCITBX_ASSERT(y.size() == x.size());
    SCITBX_ASSERT(z.size() == x.size());
    af::shared<vec3<int> > result((af::reserve(x.size())));
    for(std::size_t i=0;i<x.size();i++) {
      result.push_back(vec3<int>(x[i],y[i],z[i]));
    }
    return new flex<vec3<int> >::type(result, result.size());
  }

  flex<vec3<int> >::type*
  from_int(
    af::const_ref<int> const& x)
  {
    SCITBX_ASSERT(x.size() % 3 == 0);
    std::size_t result_size = x.size() / 3;
    af::shared<vec3<int> > result((af::reserve(result_size)));
    const int* d = x.begin();
    for(std::size_t i=0;i<result_size;i++) {
      result.push_back(vec3<int>(d));
      d += 3;
    }
    return new flex<vec3<int> >::type(result, result.size());
  }

  flex_int
  as_int(flex<vec3<int> >::type const& a)
  {
    SCITBX_ASSERT(a.accessor().is_trivial_1d());
    flex_int result(a.size()*3, init_functor_null<int>());
    int* r = result.begin();
    const_ref<vec3<int> > a_ref = a.const_ref().as_1d();
    for(std::size_t i=0;i<a_ref.size();i++) {
      for(std::size_t j=0;j<3;j++) {
        *r++ = a_ref[i][j];
      }
    }
    return result;
  }

  af::shared<vec3<double> >
  as_vec3_double(flex<vec3<int> >::type const& a)
  {
    af::shared<vec3<double> > result((af::reserve(a.size())));
    for(std::size_t i=0;i<a.size();i++) {
      result.push_back(vec3<double>(a[i]));
    }
    return result;
  }

} // namespace <anonymous>

namespace boost_python {

  template <>
  struct flex_default_element<vec3<int> >
  {
    static vec3<int>
    get() { return vec3<int>(0,0,0); }
  };

  void wrap_flex_vec3_int()
  {
    using namespace boost::python;
    using boost::python::arg;
    typedef flex_wrapper<vec3<int> > f_w;
    f_w::plain("vec3_int")
      .def_pickle(flex_pickle_single_buffered<vec3<int>,
        3*pickle_size_per_element<int>::value>())
      .def("__init__", make_constructor(join))
      .def("__init__", make_constructor(from_int))
      .def("as_int", as_int)
      .def("as_vec3_double", as_vec3_double)
      .def("add_selected",
        (object(*)(
          object const&,
          af::const_ref<std::size_t> const&,
          af::const_ref<vec3<int> > const&)) add_selected_unsigned_a, (
            arg("indices"), arg("values")))
    ;
  }

}}} // namespace scitbx::af::boost_python


text: #include <boost/wave/grammars/cpp_grammar_gen.hpp>


text:
/* Boost interval/compare/tribool.hpp template implementation file
 *
 * Copyright Guillaume Melquiond 2002-2003
 * Permission to use, copy, modify, sell, and distribute this software
 * is hereby granted without fee provided that the above copyright notice
 * appears in all copies and that both that copyright notice and this
 * permission notice appear in supporting documentation,
 *
 * None of the above authors make any representation about the
 * suitability of this software for any purpose. It is provided "as
 * is" without express or implied warranty.
 *
 * $Id: tribool.hpp,v 1.2 2003/02/05 17:34:31 gmelquio Exp $
 */

#ifndef BOOST_NUMERIC_INTERVAL_COMPARE_TRIBOOL_HPP
#define BOOST_NUMERIC_INTERVAL_COMPARE_TRIBOOL_HPP

#include <boost/numeric/interval/detail/interval_prototype.hpp>
#include <boost/numeric/interval/detail/test_input.hpp>
#include <boost/tribool.hpp>

namespace boost {
namespace numeric {
namespace interval_lib {
namespace compare {
namespace tribool {

template<class T, class Policies1, class Policies2> inline
tribool operator<(const interval<T, Policies1>& x, const interval<T, Policies2>& y)
{
  if (detail::test_input(x, y)) throw comparison_error();
  if (x.upper() < y.lower()) return true;
  if (x.lower() >= y.upper()) return false;
  return indeterminate;
}

template<class T, class Policies> inline
tribool operator<(const interval<T, Policies>& x, const T& y)
{
  if (detail::test_input(x, y)) throw comparison_error();
  if (x.upper() < y) return true;
  if (x.lower() >= y) return false;
  return indeterminate;
}

template<class T, class Policies1, class Policies2> inline
tribool operator<=(const interval<T, Policies1>& x, const interval<T, Policies2>& y)
{
  if (detail::test_input(x, y)) throw comparison_error();
  if (x.upper() <= y.lower()) return true;
  if (x.lower() > y.upper()) return false;
  return indeterminate;
}

template<class T, class Policies> inline
tribool operator<=(const interval<T, Policies>& x, const T& y)
{
  if (detail::test_input(x, y)) throw comparison_error();
  if (x.upper() <= y) return true;
  if (x.lower() > y) return false;
  return indeterminate;
}

template<class T, class Policies1, class Policies2> inline
tribool operator>(const interval<T, Policies1>& x, const interval<T, Policies2>& y)
{
  if (detail::test_input(x, y)) throw comparison_error();
  if (x.lower() > y.upper()) return true;
  if (x.upper() <= y.lower()) return false;
  return indeterminate;
}

template<class T, class Policies> inline
tribool operator>(const interval<T, Policies>& x, const T& y)
{
  if (detail::test_input(x, y)) throw comparison_error();
  if (x.lower() > y) return true;
  if (x.upper() <= y) return false;
  return indeterminate;
}

template<class T, class Policies1, class Policies2> inline
tribool operator>=(const interval<T, Policies1>& x, const interval<T, Policies2>& y)
{
  if (detail::test_input(x, y)) throw comparison_error();
  if (x.lower() >= y.upper()) return true;
  if (x.upper() < y.lower()) return false;
  return indeterminate;
}

template<class T, class Policies> inline
tribool operator>=(const interval<T, Policies>& x, const T& y)
{
  if (detail::test_input(x, y)) throw comparison_error();
  if (x.lower() >= y) return true;
  if (x.upper() < y) return false;
  return indeterminate;
}

template<class T, class Policies1, class Policies2> inline
tribool operator==(const interval<T, Policies1>& x, const interval<T, Policies2>& y)
{
  if (detail::test_input(x, y)) throw comparison_error();
  if (x.upper() == y.lower() && x.lower() == y.upper()) return true;
  if (x.upper() < y.lower() || x.lower() > y.upper()) return false;
  return indeterminate;
}

template<class T, class Policies> inline
tribool operator==(const interval<T, Policies>& x, const T& y)
{
  if (detail::test_input(x, y)) throw comparison_error();
  if (x.upper() == y && x.lower() == y) return true;
  if (x.upper() < y || x.lower() > y) return false;
  return indeterminate;
}

template<class T, class Policies1, class Policies2> inline
tribool operator!=(const interval<T, Policies1>& x, const interval<T, Policies2>& y)
{
  if (detail::test_input(x, y)) throw comparison_error();
  if (x.upper() < y.lower() || x.lower() > y.upper()) return true;
  if (x.upper() == y.lower() && x.lower() == y.upper()) return false;
  return indeterminate;
}

template<class T, class Policies> inline
tribool operator!=(const interval<T, Policies>& x, const T& y)
{
  if (detail::test_input(x, y)) throw comparison_error();
  if (x.upper() < y || x.lower() > y) return true;
  if (x.upper() == y && x.lower() == y) return false;
  return indeterminate;
}

} // namespace tribool
} // namespace compare
} // namespace interval_lib
} // namespace numeric
} // namespace boost

#endif // BOOST_NUMERIC_INTERVAL_COMPARE_TRIBOOL_HPP


text:
/**
 * Copyright (c) 2017 Melown Technologies SE
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * *  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE 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.
 */
/**
 * \file vts/merge.hpp
 * \author Vaclav Blazek <vaclav.blazek@citationtech.net>
 *
 * Tile content merge.
 */

#ifndef vtslibs_vts_merge_hpp_included_
#define vtslibs_vts_merge_hpp_included_

#include <boost/optional.hpp>

#include "../basetypes.hpp"
#include "../tileop.hpp"
#include "../opencv/atlas.hpp"
#include "../opencv/navtile.hpp"
#include "../meshopinput.hpp"
#include "detail.hpp"

namespace vtslibs { namespace vts { namespace merge {

typedef std::vector<math::Points3d> Vertices3List;

/** Merge input.
 */
typedef MeshOpInput Input;

struct TileSource {
    // list of tiles this tile's mesh/atlas was generated from
    Input::list mesh;

    // source of navtile
    Input::list navtile;

    TileSource() {}
    TileSource(const Input::list &mesh, const Input::list &navtile)
        : mesh{mesh}, navtile{navtile} {}
};

/** Merge output.
 */
struct Output {
    TileId tileId;

    Mesh::pointer mesh;
    opencv::HybridAtlas::pointer atlas;
    opencv::NavTile::pointer navtile;
    GeomExtents geomExtents;

    // list of tiles this tile was generated from
    TileSource source;

    explicit Output(const TileId &tileId) : tileId(tileId) {}

    Output(const TileId &tileId, const Input &input
           , const Input::list &navtileInput)
        : tileId(tileId), source({input}, navtileInput) {}

    Output(const TileId &tileId, const Input::list &meshInput
           , const Input::list &navtileInput)
        : tileId(tileId), source(meshInput, navtileInput)
    {}

    operator bool() const {
        return mesh || atlas || navtile;
    }

    const Mesh* getMesh() const { return mesh ? mesh.get() : nullptr; }
    const opencv::HybridAtlas* getAtlas() const {
        return atlas ? atlas.get() : nullptr;
    }
    const NavTile* getNavtile() const {
        return navtile ? navtile.get() : nullptr;
    }

    /** Takes content as a tile
     *
     *  NB: all shared pointers in returned Tile point to data inside this
     *  Output instance. Do not use tile after this instance destruction!
     */
    Tile tile(int textureQuality);

    Mesh& forceMesh();
    opencv::HybridAtlas& forceAtlas();
    opencv::NavTile& forceNavtile();

    bool derived(std::size_t index) const {
        if (index >= source.mesh.size()) { return false; }
        return (source.mesh[index].tileId().lod != tileId.lod);
    }

    bool fullyDerived() const {
        for (const auto &src : source.mesh) {
            if (src.tileId().lod == tileId.lod) { return false; }
        }
        return  true;
    }

    bool derived(const Input &input) const {
        return (input.tileId().lod != tileId.lod);
    }
};

/** Various merging constraints.
 */
class MergeConstraints {
public:
    MergeConstraints(bool generable = false, bool generateNavtile = false)
        : generable_(generable), generateNavtile_(generateNavtile)
    {}

    virtual ~MergeConstraints() {}

    /** Called when possible sources collected. Merge returns immediately on
     *  false.
     */
    bool generable() const { return generable_; }

    /** Navtile is generable.
     */
    bool generateNavtile() const { return generateNavtile_; }

    /** Called when exact sources are identified. Merge returns immediately on
     *  false. By default returns true.
     */
    virtual bool feasible(const Output &result) const;

private:
    bool generable_;
    bool generateNavtile_;
};

/** Extra merge options. Use only in special cases.
 */
struct ExtraOptions {
    /** Meshes are stored in spatial division SRS already if true. Output mesh
     *  is kept in SDS as well.
     */
    bool meshesInSds;

    /** Single sourced merges nornally skip coverage checking. Setting this flag
     *  to true forces check even for single sourced tiles.
     */
    bool checkCoverageForSingleSources;

    ExtraOptions()
        : meshesInSds(false), checkCoverageForSingleSources(false)
    {}
};

/** Generates new tile from given source and parent source fallback.
 *
 * Source and parent source inputs are merged together using their id's.
 *
 * If dummy flag is set only merged list of sources is returned.
 *
 * \param tileId tile's ID
 * \param nodeInfo node info
 * \param source list of current tile's sources
 * \param parentSource list of parent tile's sources
 * \param constraints various merging constraints
 */
Output mergeTile(const TileId &tileId
                 , const NodeInfo &nodeInfo
                 , const Input::list &source
                 , const TileSource &parentSource
                 , const MergeConstraints &constraints
                 , const MergeOptions &options
                 , const ExtraOptions &extraOptions = ExtraOptions());

// inlines

inline bool MergeConstraints::feasible(const Output &) const { return true; }

} } } // namespace vtslibs::vts::merge

#endif // vtslibs_vts_merge_hpp_included_

max_stars_repo_name: melowntech/vts-libs

max_issues_repo_name: HanochZhu/vts-browser-unity-plugin

max_forks_repo_name: HanochZhu/vts-browser-unity-plugin


text:
////////////////////////////////////////////////////////////////////////////////
///
/// \file posix.hpp
/// ---------------
///
/// Copyright (c) Domagoj Saric 2011 - 2019.
///
///  Use, modification and distribution is 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)
///
/// For more information, see http://www.boost.org
///
////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
#ifndef posix_hpp__8FC3F669_80D4_4455_829D_F72E8ABDE9D0
#define posix_hpp__8FC3F669_80D4_4455_829D_F72E8ABDE9D0
#pragma once
//------------------------------------------------------------------------------
#include <boost/config.hpp>

#if defined( BOOST_HAS_UNISTD_H )
    #include <boost/config/detail/posix_features.hpp>
#elif defined( BOOST_MSVC )
    #pragma warning ( disable : 4996 ) // "The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name."
    #include <io.h>
    #include <wchar.h>
#else
    #error no suitable POSIX implementation found
#endif // BOOST_MSVC

#if defined( BOOST_MSVC )
    #define BOOST_MMAP_POSIX_STANDARD_LINUX_OSX_MSVC( standard, linux, osx, msvc ) msvc
#elif defined( __APPLE__ )
    #define BOOST_MMAP_POSIX_STANDARD_LINUX_OSX_MSVC( standard, linux, osx, msvc ) osx
#elif defined( _GNU_SOURCE )
    #define BOOST_MMAP_POSIX_STANDARD_LINUX_OSX_MSVC( standard, linux, osx, msvc ) linux
#else
    #define BOOST_MMAP_POSIX_STANDARD_LINUX_OSX_MSVC( standard, linux, osx, msvc ) standard
#endif // POSIX impl

#if !defined( __has_include )
#   define __has_include( x ) 0
#endif // __has_include

//------------------------------------------------------------------------------
namespace boost
{
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
} // namespace boost
//------------------------------------------------------------------------------
#endif // posix_hpp

max_stars_repo_name: microblink/mmap

max_issues_repo_name: microblink/mmap

max_forks_repo_name: microblink/mmap