text:
#define BOOST_TEST_NO_MAIN

#include <iostream>
#include <sstream>
#include <boost/test/unit_test.hpp>
#include "../core/RegistryCache.h"
#include "../core/FileCache.h"

using namespace FinagleRegistryProxy;
using namespace std;

BOOST_AUTO_TEST_SUITE( serialize_suite )

RegistryCache* p;
const string filename = "/tmp/serialize.test";
const int count = 2;

Registry createReg(int i=0) {
	Registry r;
	stringstream ss;
	ss << "servier" << i;
	r.name = ss.str();
	r.host = "localhost";
	r.port = i;
	r.ephemeral = "e";
	r.ctime = 1232344;
	return r;
}

void setup() {
	p = new RegistryCache();
	for (int i = 0; i < count; i++) {
		Registry r = createReg(i);
		p->add(r);
	}
}

void teardown() {
	if (p) {
		delete p;
		p = NULL;
	}
	// // cout << "-------------------------------------" << endl;
}

string to_string(RegistryCache* up) {
	if (up) {
		RVector v;
		for (RMap::iterator mit = up->cache.begin(); mit != up->cache.end(); ++mit) {
			RVector& pv = mit->second;
			for (RVector::iterator vit = pv.begin(); vit != pv.end(); ++vit) {
				v.push_back(*vit);
			}
		}
		string json = Registry::serialize(v);
		return json;
	}
	return "";
}

BOOST_AUTO_TEST_CASE( empty ) {
//	// cout << "-------------------------------------empty" << endl;
	setup();
	BOOST_CHECK(true);
	teardown();
}

BOOST_AUTO_TEST_CASE( serialize ) {
//	// cout << "-------------------------------------serialize" << endl;
	setup();

	p->save(filename);
	BOOST_CHECK(true);

	teardown();
}

BOOST_AUTO_TEST_CASE( unserialize0 ) {
//	// cout << "-------------------------------------unserialize0" << endl;
	const string content = "[{\"name\":\"xxxx\" , \"host\":\"localhost\" , \"port\":999 , \"weight\":3600 }]";
	RVector v = Registry::unserialize(content);
	BOOST_CHECK_EQUAL(v.size(), 1);
//	// cout << content << endl;
//	// cout << v.front().host << v.front().port << v.front().name << endl;

	BOOST_CHECK_EQUAL(v.front().host, "localhost");
	BOOST_CHECK_EQUAL(v.front().port, 999);
	BOOST_CHECK_EQUAL(v.front().name, "xxxx");
}

BOOST_AUTO_TEST_CASE( unserialize1 ) {
//	// cout << "-------------------------------------unserialize1" << endl;

	const string content =
			"[{\"name\":\"servier0\",\"host\":\"localhost\",\"port\":0,\"weight\":3600 },{\"name\":\"servier1\",\"host\":\"localhost\",\"port\":1,\"weight\":3600 }]";
	RVector v = Registry::unserialize(content);
	BOOST_CHECK_EQUAL(v.size(), 2);
//	// cout << content << endl;
//	// cout << v[0].host << v[0].port << v[0].name << endl;
//	// cout << v[1].host << v[1].port << v[1].name << endl;

	Registry& l = v[0];

	BOOST_CHECK_EQUAL(l.name, "servier0");
	BOOST_CHECK_EQUAL(l.host, "localhost");
	BOOST_CHECK_EQUAL(l.port, 0);

	Registry& r = v[1];
	BOOST_CHECK_EQUAL(r.name, "servier1");
	BOOST_CHECK_EQUAL(r.host, "localhost");
	BOOST_CHECK_EQUAL(r.port, 1);

	// teardown();
}

BOOST_AUTO_TEST_CASE( unserialize2 ) {
	// cout << "-------------------------------------unserialize2" << endl;
	setup();
	string orginal = to_string(p);
	// cout << orginal << endl;
	RegistryCache* up = new RegistryCache();
	RVector v = Registry::unserialize(orginal);
	string now = Registry::serialize(v);
	// cout<< now << endl;
	BOOST_CHECK_EQUAL(p->size(), v.size());
}

BOOST_AUTO_TEST_CASE( ser_vs_unser ) {
// // cout << "-------------------------------------ser_vs_unser" << endl;
	assert(count > 0);

	setup();
	p->save(filename);

// // cout << to_string(p) << endl;

	RegistryCache* up = new RegistryCache();
	up->from_file(filename);

// // cout << to_string(up) << endl;

	BOOST_CHECK_EQUAL(up->size(), count);

	Registry left = createReg(1);
	RVector* v = p->get(left.name);
	BOOST_CHECK_EQUAL(v->size(), 1);
	Registry right = v->front();
	BOOST_CHECK_EQUAL(left.name, right.name);
	BOOST_CHECK_EQUAL(left.host, right.host);
// // cout << left.host << " = " << right.host << endl;
	BOOST_CHECK_EQUAL(left.port, right.port);

	left = createReg(count - 1);
	BOOST_CHECK_EQUAL(v->size(), 1);
	right = v->front();
	BOOST_CHECK_EQUAL(left.name, right.name);
	BOOST_CHECK_EQUAL(left.host, right.host);
// // cout << left.host << " = " << right.host << endl;
	BOOST_CHECK_EQUAL(left.port, right.port);

	delete up;
	up = NULL;

	teardown();
}

BOOST_AUTO_TEST_CASE( encode_test ) {
// // cout << "-------------------------------------encode" << endl;
	string file = "/tmp/frproxy.cache";
	RegistryCache* cache = new RegistryCache();
	cache->from_file(file);
	// cout << cache->dump() << endl;

	BOOST_CHECK(true);
}

BOOST_AUTO_TEST_CASE( large_data1 ) {
	string file = "/tmp/frproxy.cache";
	RegistryCache* cache = new RegistryCache();
	int count = 10;
	for(int i=0; i<count; i++) {
		Registry r = createReg(i);
		cache->add(r);
	}
	cache->save(file);

	delete cache;
	cache = NULL;

	cache = new RegistryCache();
	cache->from_file(file);
//	cout << cache->dump() << endl;
	BOOST_CHECK(cache->size() > 0);
	BOOST_CHECK(cache->size() == count);
}

BOOST_AUTO_TEST_CASE( large_data2 ) {
	string file = "/tmp/frproxy.cache";
	RegistryCache* cache = new RegistryCache();
	int count = 100;
	for(int i=0; i<count; i++) {
		Registry r = createReg(i);
		cache->add(r);
	}
	cache->save(file);

	delete cache;
	cache = NULL;

	cache = new RegistryCache();
	cache->from_file(file);
	// cout << cache->dump() << endl;
	BOOST_CHECK(cache->size() > 0);
	BOOST_CHECK(cache->size() == count);
}

BOOST_AUTO_TEST_CASE( large_data3 ) {
	string file = "/tmp/frproxy.cache";
	RegistryCache* cache = new RegistryCache();
	int count = 1000;
	for(int i=0; i<count; i++) {
		Registry r = createReg(i);
		cache->add(r);
	}
	cache->save(file);

	delete cache;
	cache = NULL;

	cache = new RegistryCache();
	cache->from_file(file);
	// cout << cache->dump() << endl;
	BOOST_CHECK(cache->size() > 0);
	BOOST_CHECK(cache->size() == count);
}

BOOST_AUTO_TEST_CASE( large_data4 ) {
	string file = "/tmp/frproxy.cache";
	RegistryCache* cache = new RegistryCache();
	int count = 10000;
	for(int i=0; i<count; i++) {
		Registry r = createReg(i);
		cache->add(r);
	}
	cache->save(file);

	delete cache;
	cache = NULL;

	cache = new RegistryCache();
	cache->from_file(file);
	// cout << cache->dump() << endl;
	BOOST_CHECK(cache->size() > 0);
	BOOST_CHECK(cache->size() == count);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: cychenyin/sfproxy

max_issues_repo_name: cychenyin/sfproxy

max_forks_repo_name: cychenyin/sfproxy


text:
// Copyright (C) 2009-2020 Christian@Schladetsch.com
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_MONOTONIC_SHARED_ALLOCATOR_HPP
#define BOOST_MONOTONIC_SHARED_ALLOCATOR_HPP

#include <boost/monotonic/detail/prefix.hpp>
#include <boost/monotonic/shared_storage.hpp>

namespace boost
{
    namespace monotonic
    {
        template <class Region>
        struct shared_allocator<void, Region>
        {
            typedef void* pointer;
            typedef const void* const_pointer;

            typedef void value_type;
            template <class U>
            struct rebind
            {
                typedef shared_allocator<U, Region> other;
            };
        };

        template <class T, class Region>
        struct shared_allocator : allocator<T, Region, shared_access_tag>
        {
            typedef allocator<T, Region, shared_access_tag> Parent;
            using typename Parent::size_type;
            using typename Parent::difference_type;
            using typename Parent::pointer;
            using typename Parent::const_pointer;
            using typename Parent::reference;
            using typename Parent::const_reference;
            using typename Parent::value_type;

            template <class U>
            struct rebind
            {
                typedef shared_allocator<U, Region> other;
            };

            shared_allocator() throw()
                : Parent(boost::monotonic::static_storage<Region,shared_access_tag>::get_storage()) { }

        public:
            shared_allocator(storage_base &store) throw()
                : Parent(store) { }

        public:
            shared_allocator(const shared_allocator& alloc) throw()
                : Parent(alloc) { }

            template <class U>
            shared_allocator(const shared_allocator<U, Region> &alloc) throw()
                : Parent(alloc) { }

            friend bool operator==(shared_allocator<T,Region> const &A, shared_allocator<T,Region> const &B)
            {
                return static_cast<Parent const &>(A) == static_cast<Parent const &>(B);
            }

            friend bool operator!=(shared_allocator<T,Region> const &A, shared_allocator<T,Region> const &B)
            {
                return static_cast<Parent const &>(A) != static_cast<Parent const &>(B);
            }
        };

    } // namespace monotonic

} // namespace boost

#include <boost/monotonic/detail/postfix.hpp>

#endif // BOOST_MONOTONIC_SHARED_ALLOCATOR_HPP

//EOF

ext: hpp

max_stars_repo_name: cschladetsch/Monotonic

max_issues_repo_name: cschladetsch/Monotonic

max_forks_repo_name: cschladetsch/Monotonic


text:
/*
 * Copyright 2018 Angel Caban
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify,
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the
 * following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies
 * or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <string>

#include <cpprest/containerstream.h>
#include <cpprest/http_msg.h>
#include <cpprest/http_client.h>

#include <boost/python.hpp>

using std::string;
using boost::python::class_;
using boost::python::range;
using boost::python::return_value_policy;
using boost::python::copy_const_reference;
using boost::python::allow_null;
using boost::python::exec_file;
using boost::python::borrowed;
using boost::python::extract;
using boost::python::object;
using boost::python::import;
using boost::python::handle;
using boost::python::scope;
using boost::python::str;
using boost::python::ptr;

using web::uri;
using web::http::methods;
using web::http::status_code;
using web::http::status_codes;
using web::http::http_headers;
using web::http::http_request;

#ifdef _XPLATSTR
#undef _XPLATSTR
#endif

#define STRINGIFY(x) #x
#define _XPLATSTR(x) std::string(x)

using headers_overload = const http_headers&(http_request::*)() const;
using reply = pplx::task<void>(http_request::*)(status_code, const string&, const string&) const;
using copy_const_policy = return_value_policy<copy_const_reference>;

BOOST_PYTHON_MODULE(libpyservlet) {

  class_<status_codes>("status_codes")
#define _PHRASES
#define DAT(a,b,c)    .def_readonly(STRINGIFY(a), &status_codes::a)
#include "cpprest/details/http_constants.dat"
#undef _PHRASES
#undef DAT
    ;

  class_<methods>("methods")
#define _METHODS
#define DAT(a,b)    .def_readonly(STRINGIFY(a), &methods::a)
#include "cpprest/details/http_constants.dat"
#undef _METHODS
#undef DAT
    ;

  class_<http_headers>("http_headers")
    .def("has",      &http_headers::has)
    .def("size",     &http_headers::size)
    .def("empty",    &http_headers::empty)
    .def("__iter__", boost::python::iterator<http_headers>());

  class_<uri>("uri")
    .def("scheme",    &uri::scheme,    copy_const_policy())
    .def("user_info", &uri::user_info, copy_const_policy())
    .def("host",      &uri::host,      copy_const_policy())
    .def("path",      &uri::path,      copy_const_policy())
    .def("query",     &uri::query,     copy_const_policy())
    .def("fragment",  &uri::fragment,  copy_const_policy())
    .def("port",      &uri::port)
    .def("is_host_loopback", &uri::is_host_loopback)
    .def("is_host_wildcard", &uri::is_host_wildcard)
    .def("is_host_portable", &uri::is_host_portable)
    .def("is_port_default",  &uri::is_port_default)
    .def("is_authority",     &uri::is_authority)
    .def("is_path_empty",    &uri::is_path_empty);

  class_<http_request>("http_request")
    .def("method",        &http_request::method,
         copy_const_policy())
    .def("request_uri",   &http_request::request_uri,
         copy_const_policy())
    .def<headers_overload>("headers",
                           &http_request::headers,
                           copy_const_policy())
    .def("http_version",   &http_request::http_version)
    .def("remote_address", &http_request::remote_address,
         copy_const_policy())
    .def("reply", static_cast<reply>(&http_request::reply));

} // boost python module libpyservlet


text:
#include "driver-test.h"
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(ZoneGraphTestSuite)

BOOST_AUTO_TEST_CASE(zone_graph_building)
{
    Driver d;
    DriverTest dt;
    boost::filesystem::path directory("TestFiles");
    std::string test_file = (directory / "parser_tests" / "test_parser.txt").string();
    cout << test_file << endl;
    BOOST_TEST(8 == dt.GetNumberofResourceRecordsParsed(d, test_file, "ns1.test."));
    const zone::Graph &g = dt.GetLatestZone(d);
    BOOST_TEST(6 == num_vertices(g));
    BOOST_TEST(5 == num_edges(g));
}

BOOST_AUTO_TEST_CASE(multiple_CNAME)
{
    zone::Graph zoneGraph(0);
    ResourceRecord r1("foo.com", "CNAME", 1, 10, "bar.com");
    auto [code1, id1] = zoneGraph.AddResourceRecord(r1);
    BOOST_CHECK(code1 == zone::RRAddCode::SUCCESS);

    auto [code2, id2] = zoneGraph.AddResourceRecord(r1);
    BOOST_CHECK(code2 == zone::RRAddCode::DUPLICATE); // Duplicate record

    ResourceRecord r3("foo.com", "CNAME", 1, 10, "aaa.com");
    auto [code3, id3] = zoneGraph.AddResourceRecord(r3);
    BOOST_CHECK(code3 == zone::RRAddCode::CNAME_MULTIPLE); // Multiple CNAME records

    ResourceRecord r4("foo.com", "A", 1, 10, "1.2.3.4");
    auto [code4, id4] = zoneGraph.AddResourceRecord(r4);
    BOOST_CHECK(code4 == zone::RRAddCode::CNAME_OTHER); // Other records at CNAME node should not return SUCCESS
}

BOOST_AUTO_TEST_CASE(multiple_DNAME)
{
    zone::Graph zoneGraph(0);
    ResourceRecord r1("foo.com", "DNAME", 1, 10, "bar.com");
    auto [code1, id1] = zoneGraph.AddResourceRecord(r1);
    BOOST_CHECK(code1 == zone::RRAddCode::SUCCESS);

    auto [code2, id2] = zoneGraph.AddResourceRecord(r1);
    BOOST_CHECK(code2 == zone::RRAddCode::DUPLICATE); // Duplicate record

    ResourceRecord r3("foo.com", "DNAME", 1, 10, "aaa.com");
    auto [code3, id3] = zoneGraph.AddResourceRecord(r3);
    BOOST_CHECK(code3 == zone::RRAddCode::DNAME_MULTIPLE); // Multiple DNAME records

    ResourceRecord r4("foo.com", "A", 1, 10, "1.2.3.4");
    auto [code4, id4] = zoneGraph.AddResourceRecord(r4);
    BOOST_CHECK(code4 == zone::RRAddCode::SUCCESS); // Other records at DNAME node should return success
}

BOOST_AUTO_TEST_CASE(DNAME_SOA_NS)
{
    zone::Graph zoneGraph(0);
    ResourceRecord r1(
        "foo.com", "SOA", 1, 10, "us.illinois.net. us-domain.illinois.net. 2018083000 14400 3600 2419200 14400");
    auto [code1, id1] = zoneGraph.AddResourceRecord(r1);
    BOOST_CHECK(code1 == zone::RRAddCode::SUCCESS);

    ResourceRecord r2("foo.com", "NS", 1, 10, "ns1.bar.com");
    auto [code2, id2] = zoneGraph.AddResourceRecord(r2);
    BOOST_CHECK(code2 == zone::RRAddCode::SUCCESS);

    EC longer;
    longer.name = LabelUtils::StringToLabels("alpha.foo.com");
    longer.rrTypes.set(RRType::A);

    EC exact;
    exact.name = LabelUtils::StringToLabels("foo.com");
    exact.rrTypes.set(RRType::A);

    EC negation;
    negation.name = LabelUtils::StringToLabels("foo.com");
    negation.rrTypes.set(RRType::A);
    negation.excluded = boost::make_optional(std::vector<NodeLabel>{});

    bool complete = false;

    auto longer_answer = zoneGraph.QueryLookUpAtZone(longer, complete);
    BOOST_ASSERT(longer_answer.is_initialized());
    BOOST_CHECK(std::get<0>(longer_answer.get()[0]) == ReturnTag::NX);

    auto exact_answer = zoneGraph.QueryLookUpAtZone(exact, complete);
    BOOST_ASSERT(exact_answer.is_initialized());
    BOOST_CHECK(std::get<0>(exact_answer.get()[0]) == ReturnTag::ANS);

    auto negation_answer = zoneGraph.QueryLookUpAtZone(negation, complete);
    BOOST_ASSERT(negation_answer.is_initialized());
    BOOST_CHECK(std::get<0>(negation_answer.get()[0]) == ReturnTag::NX);

    ResourceRecord r3("foo.com", "DNAME", 1, 10, "bar.com"); // DNAME is allowed to stay with NS as there is SOA
    auto [code3, id3] = zoneGraph.AddResourceRecord(r3);
    BOOST_CHECK(code3 == zone::RRAddCode::SUCCESS);

    longer_answer = zoneGraph.QueryLookUpAtZone(longer, complete);
    BOOST_ASSERT(longer_answer.is_initialized());
    BOOST_CHECK(std::get<0>(longer_answer.get()[0]) == ReturnTag::REWRITE);

    exact_answer = zoneGraph.QueryLookUpAtZone(exact, complete);
    BOOST_ASSERT(exact_answer.is_initialized());
    BOOST_CHECK(std::get<0>(exact_answer.get()[0]) == ReturnTag::ANS);

    negation_answer = zoneGraph.QueryLookUpAtZone(negation, complete);
    BOOST_ASSERT(negation_answer.is_initialized());
    BOOST_CHECK(std::get<0>(negation_answer.get()[0]) == ReturnTag::REWRITE);

    ResourceRecord r4("alpha.foo.com", "A", 1, 10, "1.1.1.1");
    auto [code4, id4] = zoneGraph.AddResourceRecord(r4);
    BOOST_CHECK(code4 == zone::RRAddCode::SUCCESS);

    // Even though there is an exact match that should be ignored because of DNAME
    longer_answer = zoneGraph.QueryLookUpAtZone(longer, complete);
    BOOST_ASSERT(longer_answer.is_initialized());
    BOOST_CHECK(std::get<0>(longer_answer.get()[0]) == ReturnTag::REWRITE);

    ResourceRecord r5("*.foo.com", "A", 1, 10, "2.2.2.2");
    auto [code5, id5] = zoneGraph.AddResourceRecord(r5);
    BOOST_CHECK(code5 == zone::RRAddCode::SUCCESS);

    // Even though there is a wildcard match that should be ignored because of DNAME
    negation_answer = zoneGraph.QueryLookUpAtZone(negation, complete);
    BOOST_ASSERT(negation_answer.is_initialized());
    BOOST_CHECK(std::get<0>(negation_answer.get()[0]) == ReturnTag::REWRITE);
}

BOOST_AUTO_TEST_CASE(DNAME_NS)
{
    zone::Graph zoneGraph(0);
    ResourceRecord r1(
        "foo.com", "SOA", 1, 10, "us.illinois.net. us-domain.illinois.net. 2018083000 14400 3600 2419200 14400");
    auto [code1, id1] = zoneGraph.AddResourceRecord(r1);
    BOOST_CHECK(code1 == zone::RRAddCode::SUCCESS);

    ResourceRecord r2("alpha.foo.com", "NS", 1, 10, "ns1.bar.com");
    auto [code2, id2] = zoneGraph.AddResourceRecord(r2);
    BOOST_CHECK(code2 == zone::RRAddCode::SUCCESS);

    EC longer;
    longer.name = LabelUtils::StringToLabels("beta.alpha.foo.com");
    longer.rrTypes.set(RRType::A);

    EC exact;
    exact.name = LabelUtils::StringToLabels("alpha.foo.com");
    exact.rrTypes.set(RRType::A);

    EC negation;
    negation.name = LabelUtils::StringToLabels("alpha.foo.com");
    negation.rrTypes.set(RRType::A);
    negation.excluded = boost::make_optional(std::vector<NodeLabel>{});

    bool complete = false;

    auto longer_answer = zoneGraph.QueryLookUpAtZone(longer, complete);
    BOOST_ASSERT(longer_answer.is_initialized());
    BOOST_CHECK(std::get<0>(longer_answer.get()[0]) == ReturnTag::REF);

    auto exact_answer = zoneGraph.QueryLookUpAtZone(exact, complete);
    BOOST_ASSERT(exact_answer.is_initialized());
    BOOST_CHECK(std::get<0>(exact_answer.get()[0]) == ReturnTag::REF);

    auto negation_answer = zoneGraph.QueryLookUpAtZone(negation, complete);
    BOOST_ASSERT(negation_answer.is_initialized());
    BOOST_CHECK(std::get<0>(negation_answer.get()[0]) == ReturnTag::REF);

    ResourceRecord r3("alpha.foo.com", "DNAME", 1, 10, "bar.com"); // By RFC6672 DNAME and NS can not stay together.
    auto [code3, id3] = zoneGraph.AddResourceRecord(r3);
    BOOST_CHECK(code3 == zone::RRAddCode::SUCCESS);

    // DNAME should be ignored by all the ECs as there is no SOA and NS takes priority (zone-cut)
    longer_answer = zoneGraph.QueryLookUpAtZone(longer, complete);
    BOOST_ASSERT(longer_answer.is_initialized());
    BOOST_CHECK(std::get<0>(longer_answer.get()[0]) == ReturnTag::REF);

    exact_answer = zoneGraph.QueryLookUpAtZone(exact, complete);
    BOOST_ASSERT(exact_answer.is_initialized());
    BOOST_CHECK(std::get<0>(exact_answer.get()[0]) == ReturnTag::REF);

    negation_answer = zoneGraph.QueryLookUpAtZone(negation, complete);
    BOOST_ASSERT(negation_answer.is_initialized());
    BOOST_CHECK(std::get<0>(negation_answer.get()[0]) == ReturnTag::REF);

    ResourceRecord r5("*.alpha.foo.com", "A", 1, 10, "2.2.2.2");
    auto [code5, id5] = zoneGraph.AddResourceRecord(r5);
    BOOST_CHECK(code5 == zone::RRAddCode::SUCCESS);

    // Even though there is a wildcard match that should be ignored because of zone-cut
    negation_answer = zoneGraph.QueryLookUpAtZone(negation, complete);
    BOOST_ASSERT(negation_answer.is_initialized());
    BOOST_CHECK(std::get<0>(negation_answer.get()[0]) == ReturnTag::REF);
}

BOOST_AUTO_TEST_CASE(Wildcard)
{
    zone::Graph zoneGraph(0);
    ResourceRecord r1(
        "foo.com", "SOA", 1, 10, "us.illinois.net. us-domain.illinois.net. 2018083000 14400 3600 2419200 14400");
    auto [code1, id1] = zoneGraph.AddResourceRecord(r1);
    BOOST_CHECK(code1 == zone::RRAddCode::SUCCESS);

    ResourceRecord r2("*.foo.com", "A", 1, 10, "1.1.1.1");
    auto [code2, id2] = zoneGraph.AddResourceRecord(r2);
    BOOST_CHECK(code2 == zone::RRAddCode::SUCCESS);

    EC longer;
    longer.name = LabelUtils::StringToLabels("beta.alpha.foo.com");
    longer.rrTypes.set(RRType::A);
    longer.rrTypes.set(RRType::MX);

    EC negation;
    negation.name = LabelUtils::StringToLabels("foo.com");
    negation.rrTypes.set(RRType::A);
    negation.rrTypes.set(RRType::MX);
    negation.excluded = boost::make_optional(std::vector<NodeLabel>{});

    bool complete = false;

    auto longer_answer = zoneGraph.QueryLookUpAtZone(longer, complete);
    BOOST_ASSERT(longer_answer.is_initialized());
    BOOST_CHECK(std::get<0>(longer_answer.get()[0]) == ReturnTag::ANS); // for A
    BOOST_CHECK(std::get<0>(longer_answer.get()[1]) == ReturnTag::ANS); // for MX

    auto negation_answer = zoneGraph.QueryLookUpAtZone(negation, complete);
    BOOST_ASSERT(negation_answer.is_initialized());
    BOOST_CHECK(std::get<0>(negation_answer.get()[0]) == ReturnTag::ANS);
    BOOST_CHECK(std::get<0>(negation_answer.get()[1]) == ReturnTag::ANS);

    ResourceRecord r3("*.*.foo.com", "CNAME", 1, 10, "aaa.com"); // wildcard under a wildcard
    auto [code3, id3] = zoneGraph.AddResourceRecord(r3);
    BOOST_CHECK(code3 == zone::RRAddCode::SUCCESS);

    EC star;
    star.name = LabelUtils::StringToLabels("alpha.*.foo.com");
    star.rrTypes.set(RRType::A);
    star.rrTypes.set(RRType::MX);

    auto star_answer = zoneGraph.QueryLookUpAtZone(star, complete);
    BOOST_ASSERT(star_answer.is_initialized());
    BOOST_CHECK(std::get<0>(star_answer.get()[0]) == ReturnTag::REWRITE);

    star.rrTypes.reset(RRType::A);
    star.rrTypes.reset(RRType::MX);
    star.rrTypes.set(RRType::CNAME);

    star_answer = zoneGraph.QueryLookUpAtZone(star, complete);
    BOOST_ASSERT(star_answer.is_initialized());
    BOOST_CHECK(std::get<0>(star_answer.get()[0]) == ReturnTag::ANS); // If CNAME is the only type requested.

    EC double_start;
    double_start.name = LabelUtils::StringToLabels("alpha.*.*.foo.com");
    double_start.rrTypes.set(RRType::A);

    auto double_star_answer = zoneGraph.QueryLookUpAtZone(double_start, complete);
    BOOST_ASSERT(double_star_answer.is_initialized());
    BOOST_CHECK(std::get<0>(double_star_answer.get()[0]) == ReturnTag::NX);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp


text:
#include <csignal>
#include <cstdlib>
#if defined ( _WIN32 )
#include <windows.h>
#else
#include <unistd.h>
#endif  // defined ( _WIN32 )
#include <boost/algorithm/string.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/filesystem/exception.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/format.hpp>
#include <Wt/WServer>
#include <CoreLib/corelib.hpp>
#include <CoreLib/exception.hpp>
#include <CoreLib/log.hpp>
#include <CoreLib/make_unique.hpp>
#include <CoreLib/system.hpp>
#include "dbtables.hpp"
#include "publicapiresource.hpp"
#include "rt.hpp"
#include "versioninfo.hpp"

void Terminate [[noreturn]] (int signo);

int main(int argc, char **argv)
{
    try {
        /// Gracefully handling SIGTERM
        void (*prev_fn)(int);
        prev_fn = signal(SIGTERM, Terminate);
        if (prev_fn == SIG_IGN)
            signal(SIGTERM, SIG_IGN);

        /// Extract the executable path and name
        boost::filesystem::path path(boost::filesystem::initial_path<boost::filesystem::path>());
        if (argc > 0 && argv[0] != NULL)
            path = boost::filesystem::system_complete(boost::filesystem::path(argv[0]));
        std::string appId(path.filename().string());
        std::string appPath(boost::algorithm::replace_last_copy(path.string(), appId, ""));
        RossNBoss::RT::Storage()->AppPath = appPath;

        /// Force changing the current path to executable path
        boost::filesystem::current_path(appPath);

        /// Initializing CoreLib
        CoreLib::CoreLibInitialize(argc, argv);

        /// Initializing log system
        CoreLib::Log::Initialize(std::cout,
                                 (boost::filesystem::path(appPath)
                                  / boost::filesystem::path("..")
                                  / boost::filesystem::path("log")).string(),
                                 "RossNBossServer");

        /// Acquiring process lock
        std::string lockId;
#if defined ( __unix__ )
        int lock;
        lockId = (boost::filesystem::path(appPath)
                  / boost::filesystem::path("..")
                  / boost::filesystem::path("tmp")
                  / (appId + ".lock")).string();
#elif defined ( _WIN32 )
        HANDLE lock;
        lockId = appId;
#endif  // defined ( __unix__ )

        /// Logging application info
        LOG_INFO("Version Information", "", "BUILD_COMPILER             " VERSION_INFO_BUILD_COMPILER, "BUILD_DATE                 " VERSION_INFO_BUILD_DATE, "BUILD_HOST                 " VERSION_INFO_BUILD_HOST, "BUILD_PROCESSOR            " VERSION_INFO_BUILD_PROCESSOR, "BUILD_SYSTEM               " VERSION_INFO_BUILD_SYSTEM, "PRODUCT_COMPANY_NAME       " VERSION_INFO_PRODUCT_COMPANY_NAME, "PRODUCT_COPYRIGHT          " VERSION_INFO_PRODUCT_COPYRIGHT, "PRODUCT_INTERNAL_NAME      " VERSION_INFO_PRODUCT_INTERNAL_NAME, "PRODUCT_NAME               " VERSION_INFO_PRODUCT_NAME, "PRODUCT_VERSION            " VERSION_INFO_PRODUCT_VERSION, "PRODUCT_DESCRIPTION        " VERSION_INFO_PRODUCT_DESCRIPTION);

        if(!CoreLib::System::GetLock(lockId, lock)) {
            LOG_WARNING("Process is already running!");
        } else {
            LOG_INFO("Got the process lock!");

            // Initialize database structure
            RossNBoss::RT::DBTables()->InitTables();
        }

        /// Starting RESTful service server, otherwise going down
        LOG_INFO("Starting RESTful service server...");
        Wt::WServer server(argv[0]);
        server.setServerConfiguration(argc, argv, WTHTTP_CONFIGURATION);
        RossNBoss::PublicAPIResource publicAPIResource;
        server.addResource(&publicAPIResource, "/RossNBoss");
        if (server.start()) {
            Wt::WServer::waitForShutdown();
            server.stop();
        }
    }

    catch (CoreLib::Exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (Wt::WServer::Exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (boost::exception &ex) {
        LOG_ERROR(boost::diagnostic_information(ex));
    }

    catch (std::exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (...) {
        LOG_ERROR("Unknown error!");
    }

    return EXIT_SUCCESS;
}

void Terminate(int signo)
{
    LOG_WARNING((boost::format("Terminating by signal %1%...") % signo).str());
    exit(1);
}

max_stars_repo_licenses: MIT Unlicense

max_issues_repo_licenses: MIT Unlicense

max_forks_repo_licenses: MIT Unlicense


text:
// Copyright (C) 2020 T. Zachary Laine
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/program_options_2/parse_command_line.hpp>

#include <iostream>

namespace po2 = boost::program_options_2;

int main(int argc, char const * argv[])
{
    auto const result = po2::parse_command_line(
        argc,
        argv,
        "A program that prints hello.",
        std::cout,
        po2::positional("addressee", "The person to say hello to."));

    using namespace boost::hana::literals;
    std::cout << "Hello, " << result[0_c] << "!\n";
}


text:
/*
 * Copyright Nick Thompson, 2019
 * Copyright Matt Borland, 2021
 * Use, modification and distribution are subject to the
 * Boost Software License, Version 1.0. (See accompanying file
 * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
 */

#include "math_unit_test.hpp"
#include <vector>
#include <random>
#include <utility>
#include <tuple>
#include <algorithm>
#include <boost/math/statistics/linear_regression.hpp>

using boost::math::statistics::simple_ordinary_least_squares;
using boost::math::statistics::simple_ordinary_least_squares_with_R_squared;

template<typename Real>
void test_line()
{
    std::vector<Real> x(128);
    std::vector<Real> y(128);
    Real expected_c0 = 7;
    Real expected_c1 = 12;
    for (size_t i = 0; i < x.size(); ++i) {
        x[i] = i;
        y[i] = expected_c0 + expected_c1*x[i];
    }

    std::pair<Real, Real> temp = simple_ordinary_least_squares(x, y);
    Real computed_c0 = std::get<0>(temp);
    Real computed_c1 = std::get<1>(temp);

    CHECK_ULP_CLOSE(expected_c0, computed_c0, 0);
    CHECK_ULP_CLOSE(expected_c1, computed_c1, 0);

    std::tuple<Real, Real, Real> temp_with_R = simple_ordinary_least_squares_with_R_squared(x, y);
    Real computed_c0_R = std::get<0>(temp_with_R);
    Real computed_c1_R = std::get<1>(temp_with_R);
    Real Rsquared = std::get<2>(temp_with_R);

    Real expected_Rsquared = 1;
    CHECK_ULP_CLOSE(expected_c0, computed_c0_R, 0);
    CHECK_ULP_CLOSE(expected_c1, computed_c1_R, 0);
    CHECK_ULP_CLOSE(expected_Rsquared, Rsquared, 0);

}

template<typename Z>
void test_integer_line()
{
    std::vector<Z> x(128);
    std::vector<Z> y(128);
    double expected_c0 = 7;
    double expected_c1 = 12;
    for (size_t i = 0; i < x.size(); ++i) {
        x[i] = i;
        y[i] = expected_c0 + expected_c1*x[i];
    }

    std::pair<double, double> temp = simple_ordinary_least_squares(x, y);
    double computed_c0 = std::get<0>(temp);
    double computed_c1 = std::get<1>(temp);

    CHECK_ULP_CLOSE(expected_c0, computed_c0, 0);
    CHECK_ULP_CLOSE(expected_c1, computed_c1, 0);

    std::tuple<double, double, double> temp_with_R = simple_ordinary_least_squares_with_R_squared(x, y);
    double computed_c0_R = std::get<0>(temp_with_R);
    double computed_c1_R = std::get<1>(temp_with_R);
    double Rsquared = std::get<2>(temp_with_R);

    double expected_Rsquared = 1;
    CHECK_ULP_CLOSE(expected_c0, computed_c0_R, 0);
    CHECK_ULP_CLOSE(expected_c1, computed_c1_R, 0);
    CHECK_ULP_CLOSE(expected_Rsquared, Rsquared, 0);

}

template<typename Real>
void test_constant()
{
    std::vector<Real> x(128);
    std::vector<Real> y(128);
    Real expected_c0 = 7;
    Real expected_c1 = 0;
    for (size_t i = 0; i < x.size(); ++i) {
        x[i] = i;
        y[i] = expected_c0 + expected_c1*x[i];
    }

    std::pair<Real, Real> temp = simple_ordinary_least_squares(x, y);
    Real computed_c0 = std::get<0>(temp);
    Real computed_c1 = std::get<1>(temp);

    CHECK_ULP_CLOSE(expected_c0, computed_c0, 0);
    CHECK_ULP_CLOSE(expected_c1, computed_c1, 0);

    std::tuple<Real, Real, Real> temp_with_R = simple_ordinary_least_squares_with_R_squared(x, y);
    Real computed_c0_R = std::get<0>(temp_with_R);
    Real computed_c1_R = std::get<1>(temp_with_R);
    Real Rsquared = std::get<2>(temp_with_R);

    Real expected_Rsquared = 1;
    CHECK_ULP_CLOSE(expected_c0, computed_c0_R, 0);
    CHECK_ULP_CLOSE(expected_c1, computed_c1_R, 0);
    CHECK_ULP_CLOSE(expected_Rsquared, Rsquared, 0);

}

template<typename Z>
void test_integer_constant()
{
    std::vector<Z> x(128);
    std::vector<Z> y(128);
    double expected_c0 = 7;
    double expected_c1 = 0;
    for (size_t i = 0; i < x.size(); ++i) {
        x[i] = i;
        y[i] = expected_c0 + expected_c1*x[i];
    }

    std::pair<double, double> temp = simple_ordinary_least_squares(x, y);
    double computed_c0 = std::get<0>(temp);
    double computed_c1 = std::get<1>(temp);

    CHECK_ULP_CLOSE(expected_c0, computed_c0, 0);
    CHECK_ULP_CLOSE(expected_c1, computed_c1, 0);

    std::tuple<double, double, double> temp_with_R = simple_ordinary_least_squares_with_R_squared(x, y);
    double computed_c0_R = std::get<0>(temp_with_R);
    double computed_c1_R = std::get<1>(temp_with_R);
    double Rsquared = std::get<2>(temp_with_R);

    double expected_Rsquared = 1;
    CHECK_ULP_CLOSE(expected_c0, computed_c0_R, 0);
    CHECK_ULP_CLOSE(expected_c1, computed_c1_R, 0);
    CHECK_ULP_CLOSE(expected_Rsquared, Rsquared, 0);

}

template<typename Real>
void test_permutation_invariance()
{
    std::vector<Real> x(256);
    std::vector<Real> y(256);
    std::mt19937_64 gen{123456};
    std::normal_distribution<Real> dis(0, 0.1);

    Real expected_c0 = -7.2;
    Real expected_c1 = -13.5;

    x[0] = 0;
    y[0] = expected_c0 + dis(gen);
    for(size_t i = 1; i < x.size(); ++i) {
        Real t = dis(gen);
        x[i] = x[i-1] + t*t;
        y[i] = expected_c0 + expected_c1*x[i] + dis(gen);
    }

    std::tuple<Real, Real, Real> temp = simple_ordinary_least_squares_with_R_squared(x, y);
    Real c0 = std::get<0>(temp);
    Real c1 = std::get<1>(temp);
    Real Rsquared = std::get<2>(temp);
    CHECK_MOLLIFIED_CLOSE(expected_c0, c0, 0.002);
    CHECK_MOLLIFIED_CLOSE(expected_c1, c1, 0.002);

    int j = 0;
    std::mt19937_64 gen1{12345};
    std::mt19937_64 gen2{12345};
    while(j++ < 10) {
        std::shuffle(x.begin(), x.end(), gen1);
        std::shuffle(y.begin(), y.end(), gen2);

        std::tuple<Real, Real, Real> temp_ = simple_ordinary_least_squares_with_R_squared(x, y);
        Real c0_ = std::get<0>(temp_);
        Real c1_ = std::get<1>(temp_);
        Real Rsquared_ = std::get<2>(temp_);

        CHECK_ULP_CLOSE(c0, c0_, 100);
        CHECK_ULP_CLOSE(c1, c1_, 100);
        CHECK_ULP_CLOSE(Rsquared, Rsquared_, 65);
    }
}

template<typename Real>
void test_scaling_relations()
{
    std::vector<Real> x(256);
    std::vector<Real> y(256);
    std::mt19937_64 gen{123456};
    std::normal_distribution<Real> dis(0, 0.1);

    Real expected_c0 = 3.2;
    Real expected_c1 = -13.5;

    x[0] = 0;
    y[0] = expected_c0 + dis(gen);
    for(size_t i = 1; i < x.size(); ++i) {
        Real t = dis(gen);
        x[i] = x[i-1] + t*t;
        y[i] = expected_c0 + expected_c1*x[i] + dis(gen);
    }

    std::tuple<Real, Real, Real> temp = simple_ordinary_least_squares_with_R_squared(x, y);
    Real c0 = std::get<0>(temp);
    Real c1 = std::get<1>(temp);
    Real Rsquared = std::get<2>(temp);
    CHECK_MOLLIFIED_CLOSE(expected_c0, c0, 0.005);
    CHECK_MOLLIFIED_CLOSE(expected_c1, c1, 0.005);

    // If y -> lambda y, then c0 -> lambda c0 and c1 -> lambda c1.
    Real lambda = 6;

    for (auto& s : y) {
        s *= lambda;
    }

    temp = simple_ordinary_least_squares_with_R_squared(x, y);
    Real c0_lambda = std::get<0>(temp);
    Real c1_lambda = std::get<1>(temp);
    Real Rsquared_lambda = std::get<2>(temp);

    CHECK_ULP_CLOSE(lambda*c0, c0_lambda, 30);
    CHECK_ULP_CLOSE(lambda*c1, c1_lambda, 30);
    CHECK_ULP_CLOSE(Rsquared, Rsquared_lambda, 3);

    // If x -> lambda x, then c0 -> c0 and c1 -> c1/lambda
    for (auto& s : x) {
        s *= lambda;
    }
    // Put y back into it's original state:
    for (auto& s : y) {
        s /= lambda;
    }

    temp = simple_ordinary_least_squares_with_R_squared(x, y);
    Real c0_ = std::get<0>(temp);
    Real c1_ = std::get<1>(temp);
    Real Rsquared_ = std::get<2>(temp);

    CHECK_ULP_CLOSE(c0, c0_, 70);
    CHECK_ULP_CLOSE(c1, c1_*lambda, 50);
    CHECK_ULP_CLOSE(Rsquared, Rsquared_, 50);

}

int main()
{
    test_line<float>();
    test_line<double>();
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
    test_line<long double>();
#endif
    test_integer_line<int>();
    test_integer_line<int32_t>();
    test_integer_line<int64_t>();
    test_integer_line<uint32_t>();

    test_constant<float>();
    test_constant<double>();
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
    test_constant<long double>();
#endif
    test_integer_constant<int>();
    test_integer_constant<int32_t>();
    test_integer_constant<int64_t>();
    test_integer_constant<uint32_t>();

    test_permutation_invariance<float>();
    test_permutation_invariance<double>();
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
    test_permutation_invariance<long double>();
#endif

    test_scaling_relations<float>();
    test_scaling_relations<double>();
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
    test_scaling_relations<long double>();
#endif
    return boost::math::test::report_errors();
}

max_stars_repo_name: oleg-alexandrov/math

max_issues_repo_name: oleg-alexandrov/math


text:
//
// Copyright (c) 2019-2021 Ruben Perez Hidalgo (rubenperez038 at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_MYSQL_DETAIL_PROTOCOL_IMPL_CHANNEL_HPP
#define BOOST_MYSQL_DETAIL_PROTOCOL_IMPL_CHANNEL_HPP

#include <boost/asio/read.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/compose.hpp>
#include <cassert>
#include "boost/mysql/detail/protocol/common_messages.hpp"
#include "boost/mysql/detail/protocol/constants.hpp"
#include "boost/mysql/detail/auxiliar/valgrind.hpp"

namespace boost {
namespace mysql {
namespace detail {

inline std::uint32_t compute_size_to_write(
    std::size_t buffer_size,
    std::size_t transferred_size
)
{
    return static_cast<std::uint32_t>(std::min(
        MAX_PACKET_SIZE,
        buffer_size - transferred_size
    ));
}

} // detail
} // mysql
} // boost

template <class Stream>
bool boost::mysql::detail::channel<Stream>::process_sequence_number(
    std::uint8_t got
)
{
    if (got == sequence_number_)
    {
        ++sequence_number_;
        return true;
    }
    else
    {
        return false;
    }
}

template <class Stream>
boost::mysql::error_code boost::mysql::detail::channel<Stream>::process_header_read(
    std::uint32_t& size_to_read
)
{
    packet_header header;
    deserialization_context ctx (boost::asio::buffer(header_buffer_), capabilities(0)); // unaffected by capabilities
    errc err = deserialize(ctx, header);
    if (err != errc::ok)
    {
        return make_error_code(err);
    }
    if (!process_sequence_number(header.sequence_number))
    {
        return make_error_code(errc::sequence_number_mismatch);
    }
    size_to_read = header.packet_size.value;
    return error_code();
}

template <class Stream>
void boost::mysql::detail::channel<Stream>::process_header_write(
    std::uint32_t size_to_write
)
{
    packet_header header;
    header.packet_size.value = size_to_write;
    header.sequence_number = next_sequence_number();
    serialization_context ctx (capabilities(0), header_buffer_.data()); // capabilities not relevant here
    serialize(ctx, header);
}

template <class Stream>
template <class BufferSeq>
std::size_t boost::mysql::detail::channel<Stream>::read_impl(
    BufferSeq&& buff,
    error_code& ec
)
{
    if (ssl_active())
    {
        return boost::asio::read(*ssl_stream_, std::forward<BufferSeq>(buff), ec);
    }
    else
    {
        return boost::asio::read(stream_, std::forward<BufferSeq>(buff), ec);
    }
}

template <class Stream>
template <class BufferSeq>
std::size_t boost::mysql::detail::channel<Stream>::write_impl(
    BufferSeq&& buff,
    error_code& ec
)
{
    if (ssl_active())
    {
        return boost::asio::write(*ssl_stream_, std::forward<BufferSeq>(buff), ec);
    }
    else
    {
        return boost::asio::write(stream_, std::forward<BufferSeq>(buff), ec);
    }
}

template <class Stream>
template <class BufferSeq, class CompletionToken>
BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void(boost::mysql::error_code, std::size_t))
boost::mysql::detail::channel<Stream>::async_read_impl(
    BufferSeq&& buff,
    CompletionToken&& token
)
{
    if (ssl_active())
    {
        return boost::asio::async_read(
            *ssl_stream_,
            std::forward<BufferSeq>(buff),
            boost::asio::transfer_all(),
            std::forward<CompletionToken>(token)
        );
    }
    else
    {
        return boost::asio::async_read(
            stream_,
            std::forward<BufferSeq>(buff),
            boost::asio::transfer_all(),
            std::forward<CompletionToken>(token)
        );
    }
}

template <class Stream>
template <class BufferSeq, class CompletionToken>
BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void(boost::mysql::error_code, std::size_t))
boost::mysql::detail::channel<Stream>::async_write_impl(
    BufferSeq&& buff,
    CompletionToken&& token
)
{
    if (ssl_active())
    {
        return boost::asio::async_write(
            *ssl_stream_,
            std::forward<BufferSeq>(buff),
            std::forward<CompletionToken>(token)
        );
    }
    else
    {
        return boost::asio::async_write(
            stream_,
            std::forward<BufferSeq>(buff),
            std::forward<CompletionToken>(token)
        );
    }
}

template <class Stream>
void boost::mysql::detail::channel<Stream>::read(
    bytestring& buffer,
    error_code& code
)
{
    std::size_t transferred_size = 0;
    std::uint32_t size_to_read = 0;
    buffer.clear();
    code.clear();
    auto header_buff = boost::asio::buffer(header_buffer_);

    do
    {
        // Read header
        read_impl(header_buff, code);
        valgrind_make_mem_defined(header_buff);
        if (code)
            return;

        // See how many bytes we should be reading
        code = process_header_read(size_to_read);
        if (code)
            return;

        // Read the rest of the message
        buffer.resize(buffer.size() + size_to_read);
        auto read_buffer = boost::asio::buffer(buffer.data() + transferred_size, size_to_read);
        read_impl(read_buffer, code);
        valgrind_make_mem_defined(read_buffer);
        if (code)
            return;
        transferred_size += size_to_read;

    } while (size_to_read == MAX_PACKET_SIZE);
}

template <class Stream>
void boost::mysql::detail::channel<Stream>::write(
    boost::asio::const_buffer buffer,
    error_code& code
)
{
    std::size_t transferred_size = 0;
    auto bufsize = buffer.size();
    auto first = static_cast<const std::uint8_t*>(buffer.data());

    // If the packet is empty, we should still write the header, saying
    // we are sending an empty packet.
    do
    {
        auto size_to_write = compute_size_to_write(bufsize, transferred_size);
        process_header_write(size_to_write);
        write_impl(
            std::array<boost::asio::const_buffer, 2> {
                boost::asio::buffer(header_buffer_),
                boost::asio::buffer(first + transferred_size, size_to_write)
            },
            code
        );
        if (code)
            return;
        transferred_size += size_to_write;
    } while (transferred_size < bufsize);
}

template<class Stream>
struct boost::mysql::detail::channel<Stream>::read_op
    : boost::asio::coroutine
{
    channel<Stream>& chan_;
    bytestring& buffer_;
    std::size_t total_transferred_size_ = 0;

    read_op(
        channel<Stream>& chan,
        bytestring& buffer
    ) :
        chan_(chan),
        buffer_(buffer)
    {
    }

    template<class Self>
    void operator()(
        Self& self,
        error_code code = {},
        std::size_t bytes_transferred=0
    )
    {
        // Error checking
        if (code)
        {
            self.complete(code);
            return;
        }

        // Non-error path
        std::uint32_t size_to_read = 0;
        BOOST_ASIO_CORO_REENTER(*this)
        {
            do
            {
                BOOST_ASIO_CORO_YIELD chan_.async_read_impl(
                    boost::asio::buffer(chan_.header_buffer_),
                    std::move(self)
                );
                valgrind_make_mem_defined(boost::asio::buffer(chan_.header_buffer_));

                code = chan_.process_header_read(size_to_read);
                if (code)
                {
                    self.complete(code);
                    BOOST_ASIO_CORO_YIELD break;
                }

                buffer_.resize(buffer_.size() + size_to_read);

                BOOST_ASIO_CORO_YIELD chan_.async_read_impl(
                    boost::asio::buffer(buffer_.data() + total_transferred_size_, size_to_read),
                    std::move(self)
                );
                valgrind_make_mem_defined(
                    boost::asio::buffer(buffer_.data() + total_transferred_size_, bytes_transferred)
                );

                total_transferred_size_ += bytes_transferred;
            } while (bytes_transferred == MAX_PACKET_SIZE);

            self.complete(error_code());
        }
    }
};

template <class Stream>
template <class CompletionToken>
BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(
    CompletionToken,
    void(boost::mysql::error_code)
)
boost::mysql::detail::channel<Stream>::async_read(
    bytestring& buffer,
    CompletionToken&& token
)
{
    buffer.clear();
    return boost::asio::async_compose<CompletionToken, void(error_code)>(
        read_op(*this, buffer),
        token,
        *this
    );
}

template<class Stream>
struct boost::mysql::detail::channel<Stream>::write_op
    : boost::asio::coroutine
{
    channel<Stream>& chan_;
    boost::asio::const_buffer buffer_;
    std::size_t total_transferred_size_ = 0;

    write_op(
        channel<Stream>& chan,
        boost::asio::const_buffer buffer
    ) :
        chan_(chan),
        buffer_(buffer)
    {
    }

    template<class Self>
    void operator()(
        Self& self,
        error_code code = {},
        std::size_t bytes_transferred=0
    )
    {
        // Error handling
        if (code)
        {
            self.complete(code);
            return;
        }

        // Non-error path
        std::uint32_t size_to_write;
        BOOST_ASIO_CORO_REENTER(*this)
        {
            // Force write the packet header on an empty packet, at least.
            do
            {
                size_to_write = compute_size_to_write(buffer_.size(), total_transferred_size_);
                chan_.process_header_write(size_to_write);

                BOOST_ASIO_CORO_YIELD chan_.async_write_impl(
                    std::array<boost::asio::const_buffer, 2> {
                        boost::asio::buffer(chan_.header_buffer_),
                        boost::asio::buffer(buffer_ + total_transferred_size_, size_to_write)
                    },
                    std::move(self)
                );

                total_transferred_size_ += (bytes_transferred - 4); // header size

            } while (total_transferred_size_ < buffer_.size());

            self.complete(error_code());
        }
    }
};

template <class Stream>
template <class CompletionToken>
BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(
    CompletionToken,
    void(boost::mysql::error_code)
)
boost::mysql::detail::channel<Stream>::async_write(
    boost::asio::const_buffer buffer,
    CompletionToken&& token
)
{
    return boost::asio::async_compose<CompletionToken, void(error_code)>(
        write_op(*this, buffer),
        token,
        *this
    );
}

template <typename Stream>
void boost::mysql::detail::channel<Stream>::create_ssl_stream()
{
    // Determine the context to use
    boost::asio::ssl::context* ctx = external_ctx_;
    if (!ctx)
    {
        local_ctx_.emplace(boost::asio::ssl::context::tls_client);
        ctx = &*local_ctx_;
    }

    // Actually create the stream
    ssl_stream_.emplace(stream_, *ctx);
}

template <class Stream>
void boost::mysql::detail::channel<Stream>::ssl_handshake(
    error_code& ec
)
{
    create_ssl_stream();
    ssl_stream_->handshake(boost::asio::ssl::stream_base::client, ec);
}

template <class Stream>
template <class CompletionToken>
BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(
    CompletionToken,
    void(boost::mysql::error_code)
)
boost::mysql::detail::channel<Stream>::async_ssl_handshake(
    CompletionToken&& token
)
{
    create_ssl_stream();
    return ssl_stream_->async_handshake(
        boost::asio::ssl::stream_base::client,
        std::forward<CompletionToken>(token)
    );
}

template <class Stream>
boost::mysql::error_code boost::mysql::detail::channel<Stream>::close()
{
    error_code err;
    stream_.shutdown(Stream::shutdown_both, err);
    stream_.close(err);
    return err;
}

#endif

max_stars_repo_name: sehe/mysql

max_issues_repo_name: sehe/mysql

max_forks_repo_name: sehe/mysql


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

#include <boost/asio/io_service.hpp>
#include <boost/thread/thread.hpp>
#include <boost/atomic.hpp>
#include "headers.h"
#include "SelfTuning.h"
#include <iostream>
#include <vector>
#include <string>
#include "TimeSeriesBuilder.h"
#include "LSHManager.h"
#include "LSHHashFunction.h"
#include "IndexSearch.h"
#include "NaiveSearch.h"
#include "MergeResult.h"
#include <fstream>
#include <chrono>
#include <thread>
#include <numa.h>

// LSHtest is for testing c++-based implementation of LSH search

using namespace std;

boost::atomic_int threads_finished(0);
boost::atomic_int ts_thread_finished(0);
boost::atomic_int init_index_thread_finished(0);

typedef struct str_thdata
{
    LSHManager* pLSH;
    int R_index;
    int low_L;
    int high_L;
    int querylength;
} thdata;
/* prototype for thread routine */
// individual index building threads
void * indexbuilding_function ( void *ptr )
{
    /* do the work */

    numa_run_on_node(0); // allocate this job in numa0

    // the followings are not needed
    //struct bitmask* mask = numa_get_run_node_mask();
    //numa_set_membind(mask);

    thdata *data;
    data = (thdata *) ptr;  /* type cast to a pointer to thdata */
    printf("Thread %d %d %d running\n", data->R_index, data->low_L, data->high_L);

    IndexBuilder indexBuilder = data->pLSH->getIndexBuilder();
    indexBuilder.buildIndex(data->R_index, make_pair(data->low_L,data->high_L),  data->querylength);
    threads_finished++;
    printf("Thread %d %d %d finished\n", data->R_index, data->low_L, data->high_L);

} /* print_message_function ( void *ptr ) */

// input data thread
void load_input(LSHManager* pLSH, string datafile) {
	cout << "Timeseries read thread running" << endl;
	numa_run_on_node(7);
    //struct bitmask* mask = numa_get_run_node_mask();
    //numa_set_membind(mask);

	TimeSeriesBuilder& tBuilder = pLSH->getTimeSeriesBuilder();
	tBuilder.deserialize(datafile);
	tBuilder.constructCompactTs();
	ts_thread_finished = 1;
	cout << "Timeseries read thread finished" << endl;
}

// index thread
void init_index(LSHManager* pLSH, int R_num, int L_num) {
	numa_run_on_node(0);
    //struct bitmask* mask = numa_get_run_node_mask();
    //numa_set_membind(mask);

 	int capacity = 700000;
	pLSH->initHashIndex(R_num,L_num,capacity);
	init_index_thread_finished = 1;
	cout << "initHashIndex finished" << endl;
}

/* struct to hold data to be passed to a thread
 *    this shows how multiple data items can be passed to a thread */
// SEarchCoordinatorTracker should be added
void testLSHManager(int R_num, int L_num, int topk_no, int pert_no, RealT* rVals, string datafile, string queryfile) {

	// create LSHManager
	LSHManager* pLSH = LSHManager::getInstance();

	//int R_num = 4;
	//int L_num = 200;
	//int topk_no = 5;
	//int pert_no = 2;
	//RealT rVals[4] = {1.2,2.04,3.4680,9.7365};

	// create TimeSeriesBuilder to populate time series data
	boost::thread ts_thread(load_input, pLSH, datafile);
	while(ts_thread_finished == 0) {
		boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
	}
	ts_thread.join();

	// create hash index
	boost::thread init_index_thread(init_index, pLSH, R_num, L_num);
	while(init_index_thread_finished == 0) {
		boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
	}
	init_index_thread.join();

	// create sample LSH hash functions
	// we hard-code each LSH parameter since c++ can not use the LSH Hash file used in Java
	int dimension = 384;
	int useUfunctions = 0;//1;
	int paramK = 21; //22; // parameter K of the algorithm.
	int paramM = 22;//6;
	int paramL = 800; //12; // parameter L of the algorithm.
	RealT paramW = 3.0; //370.2669449999992; //4.000000000; // parameter W of the algorithm.
	int paramT = 4000000; // parameter T of the algorithm.
	int nPoints = 4000000;

 	LSH_HashFunction& lsh_hash = pLSH->getLSH_HashFunction();
        lsh_hash.initLSHHashFunctions(R_num);
	cout << "initLSHHashFunction done" << endl;

	//ioservice object
	timespec before, after;
#ifndef DESERIALIZE_CANDIDATES
	boost::thread_group threadpool;
	int numThreads = 10;
	int numLforOneThread = 1;
	boost::shared_ptr< boost::asio::io_service > ioservice(
		new boost::asio::io_service
		);
	//work object
	boost::shared_ptr< boost::asio::io_service::work > work(
			new boost::asio::io_service::work( *ioservice )
		);

	cout << "buildIndex  start" << endl;
       	clock_gettime(CLOCK_MONOTONIC, &before);
	for(int i=0;i<numThreads;i++) {
		threadpool.create_thread(boost::bind(&boost::asio::io_service::run, ioservice));
	}
	int numTasks;
	if(L_num%numLforOneThread == 0)
		numTasks = L_num/numLforOneThread;
	else
		numTasks = L_num/numLforOneThread+1;
        thdata data[R_num][numTasks];
	cout << "numtask=" << numTasks << endl;
	for(int i=0;i<R_num;i++) {
		int low = 0;
		int high = numLforOneThread-1;
		int j=0;
		while(true) {
			if(high > L_num-1) {
				high = L_num-1;
			}
                	data[i][j].pLSH = pLSH;
                	data[i][j].R_index = i;
                	data[i][j].low_L = low;
                	data[i][j].high_L = high;
			data[i][j].querylength = dimension;
			low = low+numLforOneThread;
			high = high+numLforOneThread;
			if(low > L_num-1) {
				break;
			}
			j++;
		}

	}
	for(int i=0;i<R_num;i++) {
		RealT paramR = rVals[i];
		RealT paramR2 = paramR*paramR;
		lsh_hash.init(i, paramR, paramR2, useUfunctions, paramK, paramL, paramM, paramT, dimension, paramW, nPoints);
		//int j = 0;
		//while(true) {
			//threads_finished = 0;
			for(int k=0;k<numTasks;k++) {
				ioservice->post(boost::bind(&indexbuilding_function, &data[i][k]));

			}
			//while(threads_finished < numThreads) {
			//	boost::this_thread::yield();
			//}
			//if(j == numTasks)
			//	break;
		//}
	}
	while(threads_finished < numTasks*R_num) {
		boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
	}
	work.reset();
	ioservice->stop();
	threadpool.join_all();

       	clock_gettime(CLOCK_MONOTONIC, &after);
	timespec diff_time = diff(before, after);
	long build_time = diff_time.tv_sec*1000 + diff_time.tv_nsec/1000000;
	cout << "buildIndex  done" << endl;
        cout << "buildIndex_time(ms)=" << build_time << endl;
#else
	cout << "Skipped to build index" << endl;
	for(int i=0;i<R_num;i++) {
		RealT paramR = rVals[i];
		RealT paramR2 = paramR*paramR;
		lsh_hash.init(i, paramR, paramR2, useUfunctions, paramK, paramL, paramM, paramT, dimension, paramW, nPoints);
	}
#endif

	SearchCoordinatorTracker& tracker = pLSH->getSearchCoordinatorTracker();
	string sId("search");

	std::ifstream infile(queryfile);
	int query_id = 0;
	for (std::string line; std::getline(infile, line); ) {
		vector<RealT> query;

		// get query points
		char* str = (char*)line.c_str();
		char* pch = strtok (str," ");
	//id = atoi(pch);
	//pch = strtok (NULL, ",");
		cout << "\n\n*****************query " << query_id++ << endl;
	//int i=0;
		while (pch != NULL)
		{
			query.push_back(atof(pch));
	//cout << i << "," << query[i] << endl;
			pch = strtok (NULL, " ");
	//	i++;
		}

        tracker.addSearchCoordinator(sId,query,topk_no);
        SearchCoordinator& searchCoord = tracker.getSearchCoordinator(sId);
        MergeResult& mergeResult = searchCoord.getMergeResult();
        IndexSearch& indexSearch = searchCoord.getIndexSearch();
        QueryHashFunctions &queryHashes = searchCoord.getQueryHashFunctions();
        NaiveSearch& naiveSearch = searchCoord.getNaiveSearch();
        priority_queue<SearchResult, vector<SearchResult>, CompareSearchResult> topK;
        vector<SearchResult> vec_result;

        	clock_gettime(CLOCK_MONOTONIC, &before);

		for(int i=0;i<R_num;i++) {
		//cout << "indexSearch  start" << endl;
		indexSearch.searchIndex(query, i, make_pair(0,L_num-1), pert_no, mergeResult, queryHashes);  // we should have range of L values
		//cout << "indexSearch  done" << endl;

		naiveSearch.computeTopK(i, query, mergeResult, topk_no);

        	while(naiveSearch.getTopK().size() != 0) {
                	SearchResult searchResult = naiveSearch.getTopK().top();
			bool bfind = false;
			for(int j=0;j<vec_result.size();j++) {
				SearchResult mt = vec_result[j];
               			if(mt.getId() == searchResult.getId() &&
               			   mt.getOffset() == searchResult.getOffset()) {
					bfind = true;
					break;
				}

			}
			naiveSearch.getTopK().pop();
		//cout << "**id=" << searchResult.getId() << ",offset=" << searchResult.getOffset() << ",distance=" << searchResult.getDistance() << endl;
			if(bfind) continue;
			vec_result.push_back(searchResult);
		}
		tracker.cleanup(sId);

		int* cand = naiveSearch.getCandCntWithinThreshold();
         	if(cand[0] >= 10)
			break;

		}

	for(int i=0;i<vec_result.size();i++) {
		SearchResult searchResult = vec_result[i];
		if(topK.size() < topk_no) {
			topK.push(searchResult);
		}
		else {
			SearchResult mt = topK.top();
		 	if(mt.getDistance() > searchResult.getDistance()) {
		   		topK.pop();
			 	topK.push(searchResult);
		    	}
		}
	}
        	clock_gettime(CLOCK_MONOTONIC, &after);

	while(topK.size() > 0) {

               	SearchResult searchResult = topK.top();
               	int id = searchResult.getId();
               	int offset = searchResult.getOffset();
               	float distance = searchResult.getDistance();

		cout << "id=" << id << ",offset=" << offset << ",distance=" << distance << endl;

               	topK.pop();
	}
	timespec diff_time = diff(before, after);
	long search_time = diff_time.tv_sec*1000 + diff_time.tv_nsec/1000000;
        cout << "search_time(ms)=" << search_time << endl;
	tracker.removeSearchCoordinator(sId);
	}

	while(true) {
		std::chrono::milliseconds dura( 2000 );
    		std::this_thread::sleep_for( dura );
	}
}

int main(int nargs, char **args){
	numa_run_on_node(7);
    //struct bitmask* mask = numa_get_run_node_mask();
    //numa_set_membind(mask);

	if(nargs < 8) {
		printf("LSHtest <R_num> <L_num> <topk_no> <pert_no> <R values, e.g.: 2.23,4.52,5.67> <datafile> <queryfile>\n");
		fflush(stdout);
	} else {
		int R_num = atoi(args[1]);
		cout << "R_num=" << R_num << endl;
		int L_num = atoi(args[2]);
		cout << "L_num=" << L_num << endl;
		int topk_no = atoi(args[3]);
		cout << "topk_no=" << topk_no << endl;
		int pert_no = atoi(args[4]);
		cout << "pert_no=" << pert_no << endl;
		RealT rvals[R_num];
        	char* pch = strtok (args[5],",");
		int i=0;
		while (pch != NULL)
        	{
                	rvals[i] = atof(pch);
		cout << "rvals[" << i << "]=" << rvals[i] << endl;
                	pch = strtok (NULL, ",");
			i++;
        	}
		string datafile = string(args[6]);
		cout << "datafile=" << datafile << endl;
		string queryfile = string(args[7]);
		cout << "queryfile=" << queryfile << endl;
		testLSHManager(R_num, L_num, topk_no, pert_no, rvals, datafile, queryfile);
	}

}

max_stars_repo_name: HewlettPackard/SimilaritySearch

max_issues_repo_name: HewlettPackard/SimilaritySearch

max_forks_repo_name: HewlettPackard/SimilaritySearch


text:
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_CLIENT_IPP_20120306
#define BOOST_NETWORK_PROTOCOL_HTTP_CLIENT_IPP_20120306

// Copyright 2012 Dean Michael Berris <dberris@google.com>.
// Copyright 2012 Google, Inc.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <boost/network/protocol/http/client.hpp>
#include <boost/network/protocol/http/client/options.hpp>
#include <boost/network/detail/debug.hpp>

namespace boost { namespace network { namespace http {

client::client()
: base_facade_type() {
  BOOST_NETWORK_MESSAGE("client::client()");
}

client::client(client_options const &options)
: base_facade_type(options)
{
  BOOST_NETWORK_MESSAGE("client::client(client_options const &)");
}

}  // namespace http
}  // namespace network
}  // namespace boost

#endif  // BOOST_NETWORK_PROTOCOL_HTTP_CLIENT_IPP_20120306

ext: ipp

max_stars_repo_name: sureandrew/cpp-netlib

max_issues_repo_name: sureandrew/cpp-netlib

max_forks_repo_name: sureandrew/cpp-netlib


text:
/*
 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
 *
 * 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 <boost/test/unit_test.hpp>
#include <Elementary.h>
#include <EWebKit.h>
#include <EWebKit_internal.h>

#include "ServiceManager.h"
#include "AbstractWebEngine.h"
#include "BrowserLogger.h"

#define TAG "[UT] WebKitEngine - "

BOOST_AUTO_TEST_SUITE(WebEngineService)

BOOST_AUTO_TEST_CASE(EwkInit)
{
    BROWSER_LOGI(TAG "EwkInit - START --> ");
    BOOST_REQUIRE(ewk_init() > 0);
    BROWSER_LOGI(TAG "--> END - EwkInit");
}

BOOST_AUTO_TEST_CASE(UriSetGet)
{
    BROWSER_LOGI(TAG "UriSetGet - START --> ");

    std::shared_ptr<tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>> webEngineService =
        std::dynamic_pointer_cast
        <tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>,tizen_browser::core::AbstractService>
        (tizen_browser::core::ServiceManager::getInstance().getService("org.tizen.browser.webengineservice"));

    BOOST_CHECK(webEngineService);

//    elm_policy_set(ELM_POLICY_QUIT, ELM_POLICY_QUIT_LAST_WINDOW_CLOSED);
//    Evas_Object *main_window = elm_win_util_standard_add("browserApp-ut", "browserApp-ut");
//    if (main_window == nullptr)
//        BROWSER_LOGE(TAG "Failed to create main window");
//    elm_win_autodel_set(main_window, EINA_TRUE);
    Evas_Object *main_window = nullptr;

    webEngineService->init(main_window);

    tizen_browser::basic_webengine::TabId parentTabId = webEngineService->addTab("www.test.com");

    BOOST_CHECK(!(webEngineService->getLayout()));

    webEngineService->setURI("www.test2.com");

    // URIs are different because of WebKit didn't load webpage (lack of initialization)
    BOOST_TEST_MESSAGE(TAG "Print getURI():" << webEngineService->getURI());

    BOOST_TEST_MESSAGE(TAG "Print getTitle():" << webEngineService->getTitle());

    BOOST_TEST_MESSAGE(TAG "Print closeTab():" << webEngineService->closeTab());

    BROWSER_LOGI(TAG "--> END - UriSetGet");
}

BOOST_AUTO_TEST_CASE(NavigationTest)
{
    BROWSER_LOGI(TAG "NavigationTest - START --> ");

    std::shared_ptr<tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>> webEngineService =
        std::dynamic_pointer_cast
        <tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>,tizen_browser::core::AbstractService>
        (tizen_browser::core::ServiceManager::getInstance().getService("org.tizen.browser.webengineservice"));

    BOOST_CHECK(webEngineService);

    webEngineService->init(NULL);

    tizen_browser::basic_webengine::TabId parentTabId = webEngineService->addTab("www.test2.com");

    webEngineService->stopLoading();

    webEngineService->reload();

    webEngineService->setURI("www.nextpage.com");

    BOOST_TEST_MESSAGE(TAG "Is back enabled: " << webEngineService->isBackEnabled());

    webEngineService->back();

    BOOST_TEST_MESSAGE(TAG "Is forward enabled: " << webEngineService->isForwardEnabled());

    webEngineService->forward();

    BOOST_TEST_MESSAGE(TAG "Is loading: " << webEngineService->isLoading());

    BOOST_TEST_MESSAGE(TAG "Print closeTab():" << webEngineService->closeTab());

    BROWSER_LOGI(TAG "--> END - NavigationTest");
}

BOOST_AUTO_TEST_CASE(ClearPrivateData)
{
    BROWSER_LOGI(TAG "ClearPrivateData - START --> ");

    std::shared_ptr<tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>> webEngineService =
        std::dynamic_pointer_cast
        <tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>,tizen_browser::core::AbstractService>
        (tizen_browser::core::ServiceManager::getInstance().getService("org.tizen.browser.webengineservice"));

    BOOST_CHECK(webEngineService);

    tizen_browser::basic_webengine::TabId parentTabId = webEngineService->addTab("www.clearingdata.com");

    webEngineService->clearPrivateData();

    BOOST_TEST_MESSAGE(TAG "Print closeTab():" << webEngineService->closeTab());

    BROWSER_LOGI(TAG "--> END - ClearPrivateData");
}

BOOST_AUTO_TEST_CASE(TabsCreationDeletion)
{
    BROWSER_LOGI(TAG "TabsCreationDeletion - START --> ");

    std::shared_ptr<tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>> webEngineService =
        std::dynamic_pointer_cast
        <tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>,tizen_browser::core::AbstractService>
        (tizen_browser::core::ServiceManager::getInstance().getService("org.tizen.browser.webengineservice"));

    BOOST_CHECK(webEngineService);

    BOOST_TEST_MESSAGE(TAG "Tabs count: " << webEngineService->tabsCount());

    tizen_browser::basic_webengine::TabId first = webEngineService->addTab("www.first.com");

    BOOST_CHECK(webEngineService->tabsCount() == 1);

    tizen_browser::basic_webengine::TabId second = webEngineService->addTab("www.second.com");

    BOOST_CHECK(webEngineService->tabsCount() == 2);

    BOOST_TEST_MESSAGE(TAG "Print closeTab():" << webEngineService->closeTab(first));

    BOOST_CHECK(webEngineService->tabsCount() == 1);

    BOOST_TEST_MESSAGE(TAG "Print closeTab():" << webEngineService->closeTab(second));

    BOOST_CHECK(!(webEngineService->tabsCount()));

    BROWSER_LOGI(TAG "--> END - TabsCreationDeletion");
}

BOOST_AUTO_TEST_CASE(TabsSwitching)
{
    BROWSER_LOGI(TAG "TabsSwitching - START --> ");

    std::shared_ptr<tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>> webEngineService =
        std::dynamic_pointer_cast
        <tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>,tizen_browser::core::AbstractService>
        (tizen_browser::core::ServiceManager::getInstance().getService("org.tizen.browser.webengineservice"));

    BOOST_CHECK(webEngineService);

    BOOST_TEST_MESSAGE(TAG "Tabs count: " << webEngineService->tabsCount());

    BOOST_TEST_MESSAGE(TAG "Initial current tab: " << webEngineService->currentTabId().toString());

    tizen_browser::basic_webengine::TabId first = webEngineService->addTab("www.first.com");
    BOOST_TEST_MESSAGE(TAG "First tab: " << first.toString());

    webEngineService->switchToTab(first);

    BOOST_CHECK(webEngineService->currentTabId() == first);

    BOOST_CHECK(webEngineService->tabsCount() == 1);

    tizen_browser::basic_webengine::TabId second = webEngineService->addTab("www.second.com");
    BOOST_TEST_MESSAGE(TAG "Second tab: " << second.toString());

    BOOST_CHECK(webEngineService->currentTabId() == first);

    webEngineService->switchToTab(second);

    BOOST_CHECK(webEngineService->currentTabId() == second);

    BOOST_CHECK(webEngineService->tabsCount() == 2);

    BOOST_TEST_MESSAGE(TAG "Print closeTab():" << webEngineService->closeTab(second));

    BOOST_CHECK(webEngineService->currentTabId() == first);

    BOOST_CHECK(webEngineService->tabsCount() == 1);

    BOOST_TEST_MESSAGE(TAG "Print closeTab():" << webEngineService->closeTab(first));

    BOOST_CHECK(!(webEngineService->tabsCount()));

    BROWSER_LOGI(TAG "--> END - TabsSwitching");
}

BOOST_AUTO_TEST_CASE(Snapshots)
{
    BROWSER_LOGI(TAG "Snapshots - START --> ");

    std::shared_ptr<tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>> webEngineService =
        std::dynamic_pointer_cast
        <tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>,tizen_browser::core::AbstractService>
        (tizen_browser::core::ServiceManager::getInstance().getService("org.tizen.browser.webengineservice"));

    BOOST_CHECK(webEngineService);

    webEngineService->init(NULL);

    tizen_browser::basic_webengine::TabId parentTabId = webEngineService->addTab("www.test.com");

    webEngineService->getSnapshotData(100, 100);

    webEngineService->getSnapshotData(parentTabId, 100, 100);

    BOOST_TEST_MESSAGE(TAG "Print closeTab():" << webEngineService->closeTab());

    BROWSER_LOGI(TAG "--> END - Snapshots");
}

BOOST_AUTO_TEST_CASE(PrivateModeOnOff)
{
    BROWSER_LOGI(TAG "PrivateModeOnOff - START --> ");

    std::shared_ptr<tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>> webEngineService =
        std::dynamic_pointer_cast
        <tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>,tizen_browser::core::AbstractService>
        (tizen_browser::core::ServiceManager::getInstance().getService("org.tizen.browser.webengineservice"));

    BOOST_CHECK(webEngineService);

    webEngineService->init(NULL);

    tizen_browser::basic_webengine::TabId parentTabId = webEngineService->addTab("www.test.com");

    BOOST_CHECK(!(webEngineService->isSecretMode()));

    webEngineService->setPrivateMode(true);

    BOOST_CHECK(webEngineService->isSecretMode());

    webEngineService->setPrivateMode(false);

    BOOST_CHECK(!(webEngineService->isSecretMode()));

    BOOST_TEST_MESSAGE(TAG "Print closeTab():" << webEngineService->closeTab());

    BROWSER_LOGI(TAG "--> END - PrivateModeOnOff");
}

BOOST_AUTO_TEST_CASE(LoadErrorDefaultValue)
{
    BROWSER_LOGI(TAG "LoadErrorDefaultValue - START --> ");

    std::shared_ptr<tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>> webEngineService =
        std::dynamic_pointer_cast
        <tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>,tizen_browser::core::AbstractService>
        (tizen_browser::core::ServiceManager::getInstance().getService("org.tizen.browser.webengineservice"));

    BOOST_CHECK(webEngineService);

    webEngineService->init(NULL);

    tizen_browser::basic_webengine::TabId parentTabId = webEngineService->addTab("www.test.com");

    BOOST_CHECK(!(webEngineService->isLoadError()));

    BOOST_TEST_MESSAGE(TAG "Print closeTab():" << webEngineService->closeTab());

    BROWSER_LOGI(TAG "--> END - LoadErrorDefaultValue");
}

BOOST_AUTO_TEST_CASE(Focus)
{
    BROWSER_LOGI(TAG "Focus - START --> ");

    std::shared_ptr<tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>> webEngineService =
        std::dynamic_pointer_cast
        <tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>,tizen_browser::core::AbstractService>
        (tizen_browser::core::ServiceManager::getInstance().getService("org.tizen.browser.webengineservice"));

    BOOST_CHECK(webEngineService);

    webEngineService->init(NULL);

    tizen_browser::basic_webengine::TabId parentTabId = webEngineService->addTab("www.test.com");

    BOOST_TEST_MESSAGE(TAG "Has focus at start:" << webEngineService->hasFocus());

    webEngineService->setFocus();

    BOOST_TEST_MESSAGE(TAG "Has focus after setting focus:" << webEngineService->hasFocus());

    webEngineService->clearFocus();

    BOOST_TEST_MESSAGE(TAG "Has focus after clearing focus:" << webEngineService->hasFocus());

    webEngineService->setFocus();

    BOOST_TEST_MESSAGE(TAG "Has focus after setting focus:" << webEngineService->hasFocus());

    BOOST_TEST_MESSAGE(TAG "Print closeTab():" << webEngineService->closeTab());

    BROWSER_LOGI(TAG "--> END - Focus");
}

BOOST_AUTO_TEST_CASE(ZoomAndAutofit)
{
    BROWSER_LOGI(TAG "ZoomAndAutofit - START --> ");

    std::shared_ptr<tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>> webEngineService =
        std::dynamic_pointer_cast
        <tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>,tizen_browser::core::AbstractService>
        (tizen_browser::core::ServiceManager::getInstance().getService("org.tizen.browser.webengineservice"));

    BOOST_CHECK(webEngineService);

    webEngineService->init(NULL);

    tizen_browser::basic_webengine::TabId parentTabId = webEngineService->addTab("www.test.com");

    BOOST_TEST_MESSAGE(TAG "Zoom factor at start:" << webEngineService->getZoomFactor());

    webEngineService->setZoomFactor(200);

    BOOST_TEST_MESSAGE(TAG "Zoom factor after setting 200:" << webEngineService->getZoomFactor());

    webEngineService->setZoomFactor(100);

    BOOST_TEST_MESSAGE(TAG "Zoom factor after setting 100:" << webEngineService->getZoomFactor());

    BOOST_TEST_MESSAGE(TAG "Print closeTab():" << webEngineService->closeTab());

    BROWSER_LOGI(TAG "--> END - ZoomAndAutofit");
}

BOOST_AUTO_TEST_CASE(Favicon)
{
    BROWSER_LOGI(TAG "Favicon - START --> ");

    std::shared_ptr<tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>> webEngineService =
        std::dynamic_pointer_cast
        <tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>,tizen_browser::core::AbstractService>
        (tizen_browser::core::ServiceManager::getInstance().getService("org.tizen.browser.webengineservice"));

    BOOST_CHECK(webEngineService);

    webEngineService->init(NULL);

    tizen_browser::basic_webengine::TabId parentTabId = webEngineService->addTab("www.test.com");

    webEngineService->getFavicon();

    BOOST_TEST_MESSAGE(TAG "Print closeTab():" << webEngineService->closeTab());

    BROWSER_LOGI(TAG "--> END - Favicon");
}

BOOST_AUTO_TEST_CASE(SearchOnWebsite)
{
    BROWSER_LOGI(TAG "SearchOnWebsite - START --> ");

    std::shared_ptr<tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>> webEngineService =
        std::dynamic_pointer_cast
        <tizen_browser::basic_webengine::AbstractWebEngine<Evas_Object>,tizen_browser::core::AbstractService>
        (tizen_browser::core::ServiceManager::getInstance().getService("org.tizen.browser.webengineservice"));

    BOOST_CHECK(webEngineService);

    webEngineService->init(NULL);

    tizen_browser::basic_webengine::TabId parentTabId = webEngineService->addTab("www.test.com");

    webEngineService->searchOnWebsite("test", 0);

    webEngineService->searchOnWebsite("test2", 0);

    webEngineService->searchOnWebsite("", 0);

    BOOST_TEST_MESSAGE(TAG "Print closeTab():" << webEngineService->closeTab());

    BROWSER_LOGI(TAG "--> END - SearchOnWebsite");
}

//BOOST_AUTO_TEST_CASE(EwkShutdown)
//{
//    BROWSER_LOGI(TAG "EwkShutdown - START --> ");
//    BOOST_CHECK(ewk_shutdown() == 0);
//    BROWSER_LOGI(TAG "--> END - EwkShutdown");
//}

BOOST_AUTO_TEST_SUITE_END()


text: #include <boost/spirit/include/qi_domain.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <iostream>

#include <mapbox/variant.hpp>
#include <mapbox/boost_spirit_qi.hpp>
#include <boost/spirit/include/qi.hpp>

typedef mapbox::util::variant<int, bool, std::string> frame;

struct visitor {
    template <typename T>
    void operator()(T const& val) const
    {
      std::cout << typeid(T).name() << " " << val << std::endl;
    }

};

int main(int argc, char** argv) {
  typedef std::string::const_iterator Iterator;

  using namespace boost::spirit::qi;

  rule<Iterator, frame()> r =
      int_
    | bool_
    | as_string[*char_]
  ;

  frame frm{};
  auto text = std::string{argv[1]};
  auto s = parse(text.cbegin(), text.cend(), r, frm);

  if (s) mapbox::util::apply_visitor(visitor(), frm);

  return 0;
}

max_stars_repo_name: sauter-hq/boost-spirit-mapbox-variant

max_issues_repo_name: sauter-hq/boost-spirit-mapbox-variant

max_forks_repo_name: sauter-hq/boost-spirit-mapbox-variant


text:
#include <boost/shared_ptr.hpp>
#include <nodelet/nodelet.h>
#include <pluginlib/class_list_macros.h>
#include <ros/ros.h>

#include "camera_publisher.hpp"

namespace perception
{

class ECameraPublisherNodelet: public nodelet::Nodelet
{
public:
  ECameraPublisherNodelet() {}

private:
  virtual void onInit(void);
  boost::shared_ptr<ECameraPublisher> cam_pub_;
};

void ECameraPublisherNodelet::onInit()
{
  NODELET_DEBUG("Initializing eagle2_camera_publisher nodelet");
  cam_pub_.reset(new ECameraPublisher(getNodeHandle(), getPrivateNodeHandle()));
}

} // namespace perception

PLUGINLIB_EXPORT_CLASS(perception::ECameraPublisherNodelet, nodelet::Nodelet);


text:
#include <cstdio>    // fileno()
#include <unistd.h>  // isatty()
#include <csignal>

#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>

#include <QFile>
#include <QTextStream>
#include <QApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>

#include "copperfx/Ui/Application.h"
#include "copperfx/Ui/LogWindow.h"
#include "copperfx/Ui/MainWindow.h"
#include "copper/Engine.h"

namespace logging = boost::log;
namespace sinks = boost::log::sinks;

using namespace copper;
namespace ui = copper::ui;

ui::LogWindow *logWindow = nullptr;

typedef sinks::synchronous_sink< ui::LogSink > sink_t;

void initGuiLog(ui::LogWindow *logwnd) {
  boost::shared_ptr< logging::core > core = logging::core::get();

  // Construct gui logging backend separately and pass it to the frontend
  boost::shared_ptr< ui::LogSink > backend(new ui::LogSink(logwnd));
  boost::shared_ptr< sink_t > gui_sink(new sink_t(backend));
  core->add_sink(gui_sink);

  // We can manage filtering through the sink interface
  //gui_sink->set_filter(expr::attr< severity_level >("Severity") >= warning);
}

void signalHandler( int signum ){
    BOOST_LOG_TRIVIAL(debug) << "Interrupt signal (" << signum << ") received !";

    // cleanup and close up stuff here
    if(logWindow)delete logWindow;
    exit(signum); // terminate program
}

void myQtMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray localMsg = msg.toLocal8Bit();
    const char *file = context.file ? context.file : "";
    const char *function = context.function ? context.function : "";
    switch (type) {
    case QtDebugMsg:
        fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    case QtInfoMsg:
        fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    case QtWarningMsg:
        fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    case QtCriticalMsg:
        fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    case QtFatalMsg:
        fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
        break;
    }
}

int main(int argc, char *argv[])
{
    // Set up logging level quick
    logging::core::get()->set_filter( logging::trivial::severity >= logging::trivial::debug );

    // Basic signal handlers
    signal(SIGTERM, signalHandler);
    signal(SIGABRT, signalHandler);

    // qt messages handler
    qInstallMessageHandler(myQtMessageHandler);

	ui::Application app(argc, argv);
    QCoreApplication::setOrganizationName("RedSoft");
    QCoreApplication::setApplicationName("CopperFX");
    QCoreApplication::setApplicationVersion("0.0.001");

    // Show simple QT logging window first so we can see debug messages while everything is
    // being initialized. Later we'll attach it to main window. This only applies then copper
    // started from Desktop ( or /Application on macos )

    if (! isatty(fileno(stdin))) {
        // We were launched from inside the desktop
        logWindow = new ui::LogWindow();
        logWindow->show();
        initGuiLog(logWindow);
    }

    // Retina display support for Mac OS, iOS and X11:
    // http://blog.qt.io/blog/2013/04/25/retina-display-support-for-mac-os-ios-and-x11/
    //
    // AA_UseHighDpiPixmaps attribute is off by default in Qt 5.1 but will most
    // likely be on by default in a future release of Qt.
    app.setAttribute(Qt::AA_UseHighDpiPixmaps);

    //QIcon appIcon;
    //appIcon.addFile(":/Icons/AppIcon32");
    //appIcon.addFile(":/Icons/AppIcon128");
    //app.setWindowIcon(appIcon);

    // Load stylesheet
    QFile f(":/styles/dark");
    if (!f.exists()) {
        BOOST_LOG_TRIVIAL(warning) << "Unable to set stylesheet, file not found !";
    } else {
        f.open(QFile::ReadOnly | QFile::Text);
        QTextStream ts(&f);
        app.setStyleSheet(ts.readAll());
    }

    // Now it's time to init engine core
    Engine::getInstance().init();

    ui::MainWindow mainWindow;
    mainWindow.show();
    //if(logWindow)mainWindow.workspace()->setCentralWidget( logWindow ); // attach log window

    return app.exec();
}

max_stars_repo_name: all-in-one-of/CopperFX

max_issues_repo_name: all-in-one-of/CopperFX

max_forks_repo_name: all-in-one-of/CopperFX