text:
#include "stdafx.h"
#include "html_formatter.h"

#include <boost/test/unit_test.hpp>
#ifdef UNIT_TEST

/************************************************************************/
/* get_text                                                             */
/************************************************************************/
BOOST_AUTO_TEST_SUITE( test_html_formatter_get_text )

	BOOST_AUTO_TEST_CASE( HeadingLevel_none )
	{
		wstring html_text( L"Some text" ) ;

		html_formatter formatter ;

		formatter.add_text( html_text ) ;
		BOOST_CHECK ( formatter.get_text() == L"Some text" ) ;

	}
	BOOST_AUTO_TEST_CASE( HeadingLevel_init )
	{
		wstring html_text( L"Some text" ) ;

		html_formatter formatter ;

		formatter.add_text( html_text ) ;
		formatter.init() ;
		BOOST_CHECK ( formatter.get_text() == L"" ) ;
	}

BOOST_AUTO_TEST_SUITE_END()

/************************************************************************/
/* get_paragraph_text                                                   */
/************************************************************************/
BOOST_AUTO_TEST_SUITE( test_html_formatter_get_paragraph_text )

	BOOST_AUTO_TEST_CASE( HeadingLevel_p )
	{
		wstring html_text( L"Some text" ) ;
		html_formatter formatter ;

		formatter.add_text( html_text ) ;
		BOOST_CHECK ( formatter.get_paragraph_text() == L"
Some text
" ) ;
	}

	BOOST_AUTO_TEST_CASE( HeadingLevel_1 )
	{
		wstring html_text( L"Some text" ) ;
		html_formatter formatter ;

		formatter.set_heading_level( 1u ) ;
		formatter.add_text( html_text ) ;
		BOOST_CHECK ( formatter.get_text() == L"Some text" ) ;

		formatter.init() ;
		formatter.set_heading_level( 1u ) ;
		formatter.add_text( html_text ) ;
		BOOST_CHECK ( formatter.get_paragraph_text() == L"
Some text
" ) ;
	}

	BOOST_AUTO_TEST_CASE( HeadingLevel_3 )
	{
		wstring html_text( L"Some text" ) ;
		html_formatter formatter ;

		formatter.set_heading_level( 3u ) ;
		formatter.add_text( html_text ) ;
		BOOST_CHECK ( formatter.get_text() == L"Some text" ) ;

		formatter.init() ;
		formatter.set_heading_level( 3u ) ;
		formatter.add_text( html_text ) ;
		BOOST_CHECK ( formatter.get_paragraph_text() == L"
Some text
" ) ;
	}

	BOOST_AUTO_TEST_CASE( HeadingLevel_0 )
	{
		wstring html_text( L"Some text" ) ;
		html_formatter formatter ;

		formatter.set_heading_level( 0u ) ;
		formatter.add_text( html_text ) ;
		BOOST_CHECK ( formatter.get_text() == L"Some text" ) ;

		formatter.init() ;
		formatter.set_heading_level( 0u ) ;
		formatter.add_text( html_text ) ;
		BOOST_CHECK ( formatter.get_paragraph_text() == L"
Some text
" ) ;
	}

BOOST_AUTO_TEST_SUITE_END()

//////////////////////////////////////////////////////////////////////////
// formatting
//////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_SUITE( test_html_formatter_formatting )

	BOOST_AUTO_TEST_CASE( Italic_init )
	{
		html_formatter formatter ;

		BOOST_CHECK( formatter.get_italic() == false ) ;
		BOOST_CHECK ( formatter.is_italic_specified() == false ) ;
	}
	BOOST_AUTO_TEST_CASE( Italic_true )
	{
		html_formatter formatter ;
		formatter.set_italic( true ) ;

		BOOST_CHECK( formatter.get_italic() == true ) ;
		BOOST_CHECK ( formatter.is_italic_specified() == true ) ;

	}
	BOOST_AUTO_TEST_CASE( Italic_false )
	{
		html_formatter formatter ;
		formatter.set_italic( true ) ;
		formatter.set_italic( false ) ;

		BOOST_CHECK( formatter.get_italic() == false ) ;
		BOOST_CHECK ( formatter.is_italic_specified() == true ) ;
	}

	BOOST_AUTO_TEST_CASE( Bold_init )
	{
		html_formatter formatter ;

		BOOST_CHECK( formatter.get_bold() == false ) ;
		BOOST_CHECK ( formatter.is_bold_specified() == false ) ;
	}
	BOOST_AUTO_TEST_CASE( Bold_true )
	{
		html_formatter formatter ;
		formatter.set_bold( true ) ;

		BOOST_CHECK( formatter.get_bold() == true ) ;
		BOOST_CHECK ( formatter.is_bold_specified() == true ) ;

	}
	BOOST_AUTO_TEST_CASE( Bold_false )
	{
		html_formatter formatter ;
		formatter.set_bold( true ) ;
		formatter.set_bold( false ) ;

		BOOST_CHECK( formatter.get_bold() == false ) ;
		BOOST_CHECK ( formatter.is_bold_specified() == true ) ;
	}

	BOOST_AUTO_TEST_CASE( ForeColor )
	{
		html_formatter formatter ;

		BOOST_CHECK( formatter.get_fore_color() == RGB(0,0,0) ) ;
		BOOST_CHECK ( formatter.is_fore_color_specified() == false ) ;

		CColorRef color( 255, 100, 255 ) ;
		formatter.set_fore_color( color ) ;

		BOOST_CHECK( formatter.get_fore_color() == RGB( 255, 100, 255 ) ) ;
		BOOST_CHECK ( formatter.is_fore_color_specified() == true ) ;
	}

	//////////////////////////////////////////////////////////////////////////
	// font size
	//////////////////////////////////////////////////////////////////////////

	BOOST_AUTO_TEST_CASE( FontSize )
	{
		html_formatter formatter ;

		BOOST_CHECK( formatter.get_font_size() == 4 ) ;
		BOOST_CHECK ( formatter.is_font_size_specified() == false ) ;

		formatter.set_size( 12 ) ;

		BOOST_CHECK( formatter.get_font_size() == point_size_to_html_size( 12 ) ) ;
		BOOST_CHECK ( formatter.is_font_size_specified() == true ) ;
	}

	BOOST_AUTO_TEST_CASE( Superscript )
	{
		html_formatter formatter ;

		BOOST_CHECK( formatter.get_superscript() == false ) ;

		formatter.set_superscript( true ) ;

		BOOST_CHECK ( formatter.get_superscript() == true ) ;
		BOOST_CHECK ( formatter.get_subscript() == false ) ;

		formatter.set_subscript( true ) ;

		BOOST_CHECK ( formatter.get_superscript() == false ) ;
		BOOST_CHECK ( formatter.get_subscript() == true ) ;
	}

	BOOST_AUTO_TEST_CASE( Subscript )
	{
		html_formatter formatter ;

		BOOST_CHECK( formatter.get_subscript() == false ) ;

		formatter.set_subscript( true ) ;

		BOOST_CHECK ( formatter.get_superscript() == false ) ;
		BOOST_CHECK ( formatter.get_subscript() == true ) ;

		formatter.set_superscript( true ) ;

		BOOST_CHECK ( formatter.get_subscript() == false ) ;
		BOOST_CHECK ( formatter.get_superscript() == true ) ;

	}
	BOOST_AUTO_TEST_CASE( Underline )
	{
		html_formatter formatter ;

		BOOST_CHECK( formatter.get_underline() == false ) ;
		BOOST_CHECK ( formatter.is_underline_specified() == false ) ;

		formatter.set_underline( true ) ;

		BOOST_CHECK( formatter.get_underline() == true ) ;
		BOOST_CHECK ( formatter.is_underline_specified() == true ) ;

		html_formatter formatter2 ;

		formatter2.set_underline( false ) ;

		BOOST_CHECK( formatter2.get_underline() == false ) ;
		BOOST_CHECK ( formatter2.is_underline_specified() == true ) ;
	}
	BOOST_AUTO_TEST_CASE( VertAlign )
	{
		html_formatter formatter ;

		BOOST_CHECK( formatter.get_v_align() == html_processing::VA_BASELINE ) ;

		formatter.set_v_alignment( html_processing::VA_SUBSCRIPT ) ;

		BOOST_CHECK( formatter.get_v_align() == html_processing::VA_SUBSCRIPT ) ;

		formatter.set_v_alignment( html_processing::VA_SUPERSCRIPT ) ;

		BOOST_CHECK( formatter.get_v_align() == html_processing::VA_SUPERSCRIPT ) ;

		formatter.set_v_alignment( html_processing::VA_BASELINE ) ;

		BOOST_CHECK( formatter.get_v_align() == html_processing::VA_BASELINE ) ;
	}

	/** implementation of black-box test for clear_fore_color. */
	BOOST_AUTO_TEST_CASE( ClearForeColor )
	{
		html_formatter formatter ;

		BOOST_CHECK ( formatter.get_fore_color() == RGB( 0, 0, 0 ) ) ;

		CColorRef color( RGB( 255, 10, 155 ) ) ;
		formatter.set_fore_color( color ) ;

		BOOST_CHECK ( formatter.get_fore_color() == RGB( 255, 10, 155 ) ) ;

		color = RGB( 100, 55, 100 ) ;
		formatter.set_fore_color( color ) ;

		BOOST_CHECK ( formatter.get_fore_color() == RGB( 100, 55, 100 ) ) ;

		formatter.clear_fore_color() ;

		BOOST_CHECK ( formatter.get_fore_color() == RGB( 0, 0, 0 ) ) ;
	}

BOOST_AUTO_TEST_SUITE_END()

#endif

max_stars_repo_name: ultimatezen/felix

max_issues_repo_name: ultimatezen/felix

max_forks_repo_name: ultimatezen/felix


text:
/*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <boost/hana/ext/std/integral_constant.hpp>
#include <boost/hana/tuple.hpp>

#include <laws/comparable.hpp>
#include <laws/orderable.hpp>

#include <type_traits>
using namespace boost::hana;

int main() {
    //////////////////////////////////////////////////////////////////////////
    // Setup for the laws below
    //////////////////////////////////////////////////////////////////////////
    auto ints = make<Tuple>(
        std::integral_constant<int, -10>{},
        std::integral_constant<int, -2>{},
        std::integral_constant<int, 0>{},
        std::integral_constant<int, 1>{},
        std::integral_constant<int, 3>{}
    );

    //////////////////////////////////////////////////////////////////////////
    // Comparable and Orderable
    //////////////////////////////////////////////////////////////////////////
    {
        // laws
        test::TestComparable<ext::std::IntegralConstant<int>>{ints};
        test::TestOrderable<ext::std::IntegralConstant<int>>{ints};
    }
}

ext: cpp

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


text:
#define BOOST_TEST_MODULE lue translate import
#include <boost/test/unit_test.hpp>
#include "lue/translate/format.hpp"
#include "lue/validate.hpp"
#include "lue/test/print.hpp"

/*
    Skeleton for writing tests:
    - Define input dataset
        - Create one in-memory (e.g. GDAL driver)
        - Use an existing dataset
        - Create a dataset (e.g. Geo-JSON)
        - Use values in a JSON
        - ...
    - Import the dataset using a high-level function that is appropriate
        for the kind of input dataset
        - import from JSON
        - import from GDAL raster
        - ...
    - Verify the resulting LUE dataset contains all information
*/

BOOST_AUTO_TEST_CASE(empty_dataset)
{
    // Test importing the smallest JSON file supported

    {
        auto lue_json = R"({
"dataset": {
}
})"_json;

        auto const dataset =
            lue::utility::translate_json_to_lue(lue_json, "empty_dataset.lue");
        lue::data_model::assert_is_valid(dataset);

        BOOST_CHECK_EQUAL(dataset.universes().size(), 0);
        BOOST_CHECK_EQUAL(dataset.phenomena().size(), 0);
    }

    {
        auto lue_json = R"({
"dataset": {
    "phenomena": [
    ],
    "universes": [
    ]
}
})"_json;

        auto const dataset =
            lue::utility::translate_json_to_lue(lue_json, "empty_dataset.lue");
        lue::data_model::assert_is_valid(dataset);

        BOOST_CHECK_EQUAL(dataset.universes().size(), 0);
        BOOST_CHECK_EQUAL(dataset.phenomena().size(), 0);
    }

}

BOOST_AUTO_TEST_CASE(new_rasters)
{
    // Test importing single raster for multiple areas

    auto lue_json = R"({
    "dataset": {
        "phenomena": [
            {
                "name": "park",
                "object_id": [5, 9],
                "property_sets": [
                    {
                        "name": "area",
                        "space_domain": {
                            "datatype": "float64",
                            "rank": 2,
                            "space_box": [
                                100, 200, 400, 600,
                                200, 400, 800, 1200
                            ]
                        },
                        "properties": [
                            {
                                "name": "discretization",
                                "shape_per_object": "same_shape",
                                "value_variability": "constant",
                                "datatype": "uint64",
                                "shape": [2],
                                "value": [
                                    75, 85,
                                    95, 105
                                ]
                            },
                            {
                                "name": "dem",
                                "shape_per_object": "different_shape",
                                "value_variability": "constant",
                                "datatype": "float64",
                                "rank": 2,
                                "value": [
                                    {
                                        "id": 5,
                                        "shape": [4, 6],
                                        "value": [
                                            11.5, 12.5, 13.5, 14.5, 15.5, 16.5,
                                            21.5, 22.5, 23.5, 24.5, 25.5, 26.5,
                                            31.5, 32.5, 33.5, 34.5, 35.5, 36.5,
                                            41.5, 42.5, 43.5, 44.5, 45.5, 46.5
                                        ]
                                    },
                                    {
                                        "id": 9,
                                        "shape": [3, 5],
                                        "value": [
                                            11.5, 12.5, 13.5, 14.5, 15.5,
                                            21.5, 22.5, 23.5, 24.5, 25.5,
                                            31.5, 32.5, 33.5, 34.5, 35.5
                                        ]
                                    }
                                ],
                                "space_discretization": {
                                    "type": "regular_grid",
                                    "property": "/park/area/discretization"
                                }
                            }
                        ]
                    }
                ]
            }
        ]
    }
})"_json;

    auto dataset =
        lue::utility::translate_json_to_lue(lue_json, "new_raster.lue");
    lue::data_model::assert_is_valid(dataset);

    BOOST_CHECK_EQUAL(dataset.universes().size(), 0);
    BOOST_CHECK_EQUAL(dataset.phenomena().size(), 1);
    BOOST_REQUIRE(dataset.phenomena().contains("park"));

    auto& phenomenon{dataset.phenomena()["park"]};

    // Object-ID
    {
        auto& object_id{phenomenon.object_id()};
        BOOST_REQUIRE_EQUAL(object_id.nr_objects(), 2);
        std::vector<lue::data_model::Index> ids(2);
        object_id.read(lue::data_model::IndexRange{0, 2}, ids.data());
        BOOST_CHECK_EQUAL(ids[0], 5);
        BOOST_CHECK_EQUAL(ids[1], 9);
    }

    // Collection property-sets
    BOOST_CHECK(phenomenon.collection_property_sets().empty());

    // Property-sets
    BOOST_CHECK_EQUAL(phenomenon.property_sets().size(), 1);
    BOOST_REQUIRE(phenomenon.property_sets().contains("area"));

    // Property-set
    auto& property_set{phenomenon.property_sets()["area"]};

    // Object tracker
    {
        BOOST_CHECK(property_set.owns_object_tracker());

        auto const& object_tracker{property_set.object_tracker()};

        BOOST_CHECK_EQUAL(object_tracker.active_set_index().nr_indices(), 0);
        BOOST_CHECK_EQUAL(object_tracker.active_object_index().nr_indices(), 0);
        BOOST_CHECK_EQUAL(object_tracker.active_object_id().nr_ids(), 0);
    }

    // Time domain
    BOOST_CHECK(!property_set.has_time_domain());

    // Space domain
    {
        BOOST_REQUIRE(property_set.has_space_domain());

        auto const& space_domain{property_set.space_domain()};
        auto const& configuration{space_domain.configuration()};

        BOOST_REQUIRE_EQUAL(
            configuration.value<lue::data_model::Mobility>(),
            lue::data_model::Mobility::stationary);
        BOOST_REQUIRE_EQUAL(
            configuration.value<lue::data_model::SpaceDomainItemType>(),
            lue::data_model::SpaceDomainItemType::box);

        BOOST_CHECK(!space_domain.presence_is_discretized());

        auto value{
            const_cast<lue::data_model::SpaceDomain&>(space_domain)
                .value<lue::data_model::StationarySpaceBox>()};

        BOOST_REQUIRE_EQUAL(value.nr_boxes(), 2);
        BOOST_REQUIRE_EQUAL(value.array_shape(), lue::hdf5::Shape{4});

        BOOST_CHECK_EQUAL(
            value.file_datatype(), lue::hdf5::ieee_float64_le);
        BOOST_REQUIRE_EQUAL(
            value.memory_datatype(), lue::hdf5::native_float64);

        std::vector<double> elements(2 * 4);

        value.read(lue::data_model::IndexRange{0, 2}, elements.data());

        // Object 5
        BOOST_CHECK_EQUAL(elements[0], 100);
        BOOST_CHECK_EQUAL(elements[1], 200);
        BOOST_CHECK_EQUAL(elements[2], 400);
        BOOST_CHECK_EQUAL(elements[3], 600);

        // Object 9
        BOOST_CHECK_EQUAL(elements[4], 200);
        BOOST_CHECK_EQUAL(elements[5], 400);
        BOOST_CHECK_EQUAL(elements[6], 800);
        BOOST_CHECK_EQUAL(elements[7], 1200);
    }

    // Properties
    auto const& properties{property_set.properties()};

    BOOST_CHECK_EQUAL(properties.size(), 2);
    BOOST_REQUIRE(properties.contains("dem"));
    BOOST_REQUIRE(properties.contains("discretization"));

    // DEM
    {
        BOOST_REQUIRE_EQUAL(
            properties.shape_per_object("dem"),
            lue::data_model::ShapePerObject::different);
        BOOST_REQUIRE_EQUAL(
            properties.value_variability("dem"),
            lue::data_model::ValueVariability::constant);

        auto const& property{
            properties.collection<lue::data_model::different_shape::Properties>()["dem"]};

        auto const& value{property.value()};
        BOOST_REQUIRE_EQUAL(value.nr_objects(), 2);

        // Object 5
        {
            BOOST_REQUIRE(value.contains(5));

            auto const array{const_cast<lue::data_model::different_shape::Value&>(value)[5]};

            BOOST_REQUIRE_EQUAL(array.shape(), (lue::hdf5::Shape{4, 6}));
            BOOST_CHECK_EQUAL(
                array.file_datatype(), lue::hdf5::ieee_float64_le);
            BOOST_REQUIRE_EQUAL(
                array.memory_datatype(), lue::hdf5::native_float64);

            std::vector<double> elements(24);

            array.read(elements.data());

            // Row 1
            BOOST_CHECK_EQUAL(elements[0], 11.5);
            BOOST_CHECK_EQUAL(elements[1], 12.5);
            BOOST_CHECK_EQUAL(elements[2], 13.5);
            BOOST_CHECK_EQUAL(elements[3], 14.5);
            BOOST_CHECK_EQUAL(elements[4], 15.5);
            BOOST_CHECK_EQUAL(elements[5], 16.5);

            // Row 2
            BOOST_CHECK_EQUAL(elements[ 6], 21.5);
            BOOST_CHECK_EQUAL(elements[ 7], 22.5);
            BOOST_CHECK_EQUAL(elements[ 8], 23.5);
            BOOST_CHECK_EQUAL(elements[ 9], 24.5);
            BOOST_CHECK_EQUAL(elements[10], 25.5);
            BOOST_CHECK_EQUAL(elements[11], 26.5);

            // ...

            // Row 4
            BOOST_CHECK_EQUAL(elements[18], 41.5);
            BOOST_CHECK_EQUAL(elements[19], 42.5);
            BOOST_CHECK_EQUAL(elements[20], 43.5);
            BOOST_CHECK_EQUAL(elements[21], 44.5);
            BOOST_CHECK_EQUAL(elements[22], 45.5);
            BOOST_CHECK_EQUAL(elements[23], 46.5);
        }

        // Object 9
        {
            BOOST_REQUIRE(value.contains(9));
            auto const array{const_cast<lue::data_model::different_shape::Value&>(value)[9]};

            BOOST_REQUIRE_EQUAL(array.shape(), (lue::hdf5::Shape{3, 5}));
            BOOST_CHECK_EQUAL(
                array.file_datatype(), lue::hdf5::ieee_float64_le);
            BOOST_REQUIRE_EQUAL(
                array.memory_datatype(), lue::hdf5::native_float64);

            std::vector<double> elements(3 * 5);

            array.read(elements.data());

            // Row 1
            BOOST_CHECK_EQUAL(elements[ 0], 11.5);
            BOOST_CHECK_EQUAL(elements[ 1], 12.5);
            BOOST_CHECK_EQUAL(elements[ 2], 13.5);
            BOOST_CHECK_EQUAL(elements[ 3], 14.5);
            BOOST_CHECK_EQUAL(elements[ 4], 15.5);

            // Row 2
            BOOST_CHECK_EQUAL(elements[ 5], 21.5);
            BOOST_CHECK_EQUAL(elements[ 6], 22.5);
            BOOST_CHECK_EQUAL(elements[ 7], 23.5);
            BOOST_CHECK_EQUAL(elements[ 8], 24.5);
            BOOST_CHECK_EQUAL(elements[ 9], 25.5);

            // Row 3
            BOOST_CHECK_EQUAL(elements[10], 31.5);
            BOOST_CHECK_EQUAL(elements[11], 32.5);
            BOOST_CHECK_EQUAL(elements[12], 33.5);
            BOOST_CHECK_EQUAL(elements[13], 34.5);
            BOOST_CHECK_EQUAL(elements[14], 35.5);
        }

        // Discretization
        BOOST_CHECK(!property.time_is_discretized());
        BOOST_REQUIRE(property.space_is_discretized());
        BOOST_REQUIRE_EQUAL(
            property.space_discretization_type(),
            lue::data_model::SpaceDiscretization::regular_grid);

        auto discretization_property{
            const_cast<lue::data_model::different_shape::Property&>(property)
                .space_discretization_property()};

        BOOST_CHECK_EQUAL(discretization_property.name(), "discretization");
    }

    // Discretization
    {
        BOOST_REQUIRE_EQUAL(
            properties.shape_per_object("discretization"),
            lue::data_model::ShapePerObject::same);
        BOOST_REQUIRE_EQUAL(
            properties.value_variability("discretization"),
            lue::data_model::ValueVariability::constant);

        auto const& property{
            properties
                .collection<lue::data_model::same_shape::Properties>()["discretization"]};

        auto const& value{property.value()};
        BOOST_REQUIRE_EQUAL(value.nr_arrays(), 2);
        BOOST_REQUIRE_EQUAL(value.array_shape(), (lue::hdf5::Shape{2}));
        BOOST_CHECK_EQUAL(
            value.file_datatype(), lue::hdf5::std_uint64_le);
        BOOST_REQUIRE_EQUAL(
            value.memory_datatype(), lue::hdf5::native_uint64);

        std::vector<std::uint64_t> elements(2 * 2);

        value.read(elements.data());

        BOOST_CHECK_EQUAL(elements[0], 75);
        BOOST_CHECK_EQUAL(elements[1], 85);
        BOOST_CHECK_EQUAL(elements[2], 95);
        BOOST_CHECK_EQUAL(elements[3], 105);
    }
}

max_stars_repo_name: OliverSchmitz/lue

max_issues_repo_name: OliverSchmitz/lue

max_forks_repo_name: OliverSchmitz/lue


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)
/*
* This file is derived from software bearing the following
* restrictions:
*
* Copyright (c) 1994
* Hewlett-Packard Company
*
* Permission to use, copy, modify, distribute and sell this
* software and its documentation for any purpose is hereby
* granted without fee, provided that the above copyright notice
* appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation.
* Hewlett-Packard Company makes no representations about the
* suitability of this software for any purpose. It is provided
* "as is" without express or implied warranty.
*/

/*
* Copyright (c) 1992-2007 by P.J. Plauger.  ALL RIGHTS RESERVED.
* Consult your license regarding permissions and restrictions.
V5.03:0009 */

#ifndef BOOST_MONOTONIC_LIST_HPP
#define BOOST_MONOTONIC_LIST_HPP

#include <list>
#include <boost/interprocess/containers/list.hpp>
#include <boost/monotonic/detail/prefix.hpp>
#include <boost/monotonic/detail/container.hpp>

namespace boost
{
    namespace monotonic
    {
        /// A list that uses a monotonic allocator with the given region and access
        template <class T, class Region = default_region_tag, class Access = default_access_tag>
        struct list : detail::container<list<T,Region,Access> >
        {
            typedef allocator<T,Region,Access> Allocator;
            //typedef interprocess::list<T, Allocator> List, Implementation;
            typedef std::list<T, Allocator> List, Implementation;
            typedef detail::container<list<T, Allocator> > Parent;

            typedef typename List::iterator iterator;
            typedef typename List::const_iterator const_iterator;
            typedef typename List::size_type size_type;
            typedef typename List::value_type value_type;
            typedef typename List::reference reference;
            typedef typename List::const_reference const_reference;
            typedef list<T,Region,Access> This;

        private:
            Implementation impl;

        public:
            list() { }
            list(Allocator A)
                : impl(A) { }

            template <class II>
            list(II F, II L, Allocator A = Allocator())
                : impl(F,L,A) { }

            Allocator get_allocator()
            {
                return impl.get_allocator();
            }
            bool empty() const
            {
                return impl.empty();
            }
            size_type size() const
            {
                return impl.size();
            }
            void push_back(value_type const &value)
            {
                impl.push_back(value);
            }
            void pop_back()
            {
                impl.pop_back();
            }
            void push_front(value_type const &value)
            {
                impl.push_front(value);
            }
            void pop_front()
            {
                impl.pop_front();
            }
            iterator begin()
            {
                return impl.begin();
            }
            iterator end()
            {
                return impl.end();
            }
            const_iterator begin() const
            {
                return impl.begin();
            }
            const_iterator end() const
            {
                return impl.end();
            }
            value_type const &front() const
            {
                return impl.front();
            }
            value_type &front()
            {
                return impl.front();
            }
            value_type const &back() const
            {
                return impl.back();
            }
            value_type &back()
            {
                return impl.back();
            }

            void erase(iterator A)
            {
                impl.erase(A);
            }

            template <class Pred2>
            void sort(Pred2 pred)
            {
                impl.sort(pred);
            }

            void sort()
            {
                sort(std::less<T>());
            }

            template <class Pred3>
            void merge(This& other, Pred3 pred)
            {
                impl.merge(other.impl, pred);
            }

            void splice(const_iterator where, This& other)
            {
                impl.splice(where, other.impl);
            }

            void swap(This &other)
            {
                impl.swap(other.impl);
            }
        };

        template <class Ty,class R,class Acc,class Ty2,class R2,class Acc2>
        bool operator==(list<Ty,R,Acc> const &A, list<Ty2,R2,Acc2> const &B)
        {
            return A.size() == B.size() && std::equal(A.begin(), A.end(), B.begin());
        }
        template <class Ty,class R,class Acc,class Ty2,class R2,class Acc2>
        bool operator!=(list<Ty,R,Acc> const &A, list<Ty2,R2,Acc2> const &B)
        {
            return !(A == B);
        }
        template <class Ty,class R,class Acc,class Ty2,class R2,class Acc2>
        bool operator<(list<Ty,R,Acc> const &A, list<Ty2,R2,Acc2> const &B)
        {
            return std::lexicographical_compare(A.begin(), A.end(), B.begin(), B.end());
        }
        template <class Ty,class R,class Acc,class Ty2,class R2,class Acc2>
        bool operator>(list<Ty,R,Acc> const &A, list<Ty2,R2,Acc2> const &B)
        {
            return std::lexicographical_compare(B.begin(), B.end(), A.begin(), A.end());
        }
        template <class Ty,class R,class Acc,class Ty2,class R2,class Acc2>
        bool operator<=(list<Ty,R,Acc> const &A, list<Ty2,R2,Acc2> const &B)
        {
            return !(A > B);
        }
        template <class Ty,class R,class Acc,class Ty2,class R2,class Acc2>
        bool operator>=(list<Ty,R,Acc> const &A, list<Ty2,R2,Acc2> const &B)
        {
            return !(A < B);
        }

    } // namespace monotonic

} // namespace boost

#endif // BOOST_MONOTONIC_LIST_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 Mateusz Loskot <mateusz at loskot dot net>
//
// 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
//
#define BOOST_TEST_MODULE gil/test/core/point/point
#include "unit_test.hpp"

#include <boost/gil/point.hpp>

#include <type_traits>

namespace gil = boost::gil;

BOOST_AUTO_TEST_CASE(default_constructor)
{
    gil::point<int> p;
    BOOST_TEST(p.x == 0);
    BOOST_TEST(p.y == 0);
}

BOOST_AUTO_TEST_CASE(user_constructor)
{
    gil::point<int> p{1, 2};
    BOOST_TEST(p.x == 1);
    BOOST_TEST(p.y == 2);
}

BOOST_AUTO_TEST_CASE(copy_constructor)
{
    gil::point<int> p1{1, 2};
    gil::point<int> p2{p1};
    BOOST_TEST(p1.x == p2.x);
    BOOST_TEST(p1.y == p2.y);
}

BOOST_AUTO_TEST_CASE(copy_assignment_operator)
{
    gil::point<int> p1{1, 2};
    gil::point<int> p2;
    p2 = p1;
    BOOST_TEST(p1.x == p2.x);
    BOOST_TEST(p1.y == p2.y);
}

BOOST_AUTO_TEST_CASE(index_operator)
{
    gil::point<int> p{1, 2};
    BOOST_TEST(p[0] == 1);
    BOOST_TEST(p[1] == 2);
}

BOOST_AUTO_TEST_CASE(addition_operator)
{
    gil::point<int> p1{1, 1};
    gil::point<int> const p2{2, 4};
    auto p3 = p1 + p2;
    BOOST_TEST(p3.x == 3);
    BOOST_TEST(p3.y == 5);
}

BOOST_AUTO_TEST_CASE(addition_assignment_operator)
{
    gil::point<int> p1{1, 1};
    gil::point<int> const p2{2, 4};
    p1 += p2;
    BOOST_TEST(p1.x == 3);
    BOOST_TEST(p1.y == 5);
}

BOOST_AUTO_TEST_CASE(subtraction_assignment_operator)
{
    gil::point<int> p1{2, 4};
    gil::point<int> const p2{1, 1};
    p1 -= p2;
    BOOST_TEST(p1.x == 1);
    BOOST_TEST(p1.y == 3);
}

BOOST_AUTO_TEST_CASE(subtraction_operator)
{
    gil::point<int> p1{2, 4};
    gil::point<int> const p2{1, 1};
    p1 = p1 - p2;
    BOOST_TEST(p1.x == 1);
    BOOST_TEST(p1.y == 3);
}

BOOST_AUTO_TEST_CASE(unary_minus_operator)
{
    gil::point<int> p1{2, 4};
    auto p2 = -p1;
    BOOST_TEST(p2.x == -2);
    BOOST_TEST(p2.y == -4);
    p2 = -p2;
    BOOST_TEST(p2.x == p1.x);
    BOOST_TEST(p2.y == p1.y);
}

BOOST_AUTO_TEST_CASE(division_assignment_operator)
{
    {
        gil::point<int> p1{2, 4};
        p1 /= 2;
        static_assert(std::is_same<decltype((p1 / short{}).x), int>::value, "!int");
        static_assert(std::is_same<decltype((p1 / int{}).x), int>::value, "!int");
        static_assert(std::is_same<decltype((p1 / float{}).x), float>::value, "!float");
        static_assert(std::is_same<decltype((p1 / double{}).x), double>::value, "!double");
        BOOST_TEST(p1.x == 1);
        BOOST_TEST(p1.y == 2);
    }
    // point / d
    {
        gil::point<int> p1{2, 4};
        auto p2 = p1 / float{2};
        static_assert(std::is_same<decltype((p2 / int{}).x), float>::value, "!float");
        static_assert(std::is_same<decltype((p2 / float{}).x), float>::value, "!float");
        static_assert(std::is_same<decltype((p2 / double{}).x), double>::value, "!double");
        BOOST_TEST(p2.x >= 1.0); // means == but >= avoids compiler warning
        BOOST_TEST(p2.y >= 2.0);
    }
}

BOOST_AUTO_TEST_CASE(multiplication_operator)
{
    gil::point<int> p1{2, 4};
    p1 *= 2;
    BOOST_TEST(p1.x == 4);
    BOOST_TEST(p1.y == 8);

    // point * m
    {
        auto p2 = p1 * int{2};
        static_assert(std::is_same<decltype(p2.x), int>::value, "!int");
        static_assert(std::is_same<decltype(p2.y), int>::value, "!int");
        BOOST_TEST(p2.x == 8);
        BOOST_TEST(p2.y == 16);
    }
    // m * point
    {
        auto p2 = double{2} *p1;
        static_assert(std::is_same<decltype(p2.x), double>::value, "!double");
        static_assert(std::is_same<decltype(p2.y), double>::value, "!double");
        BOOST_TEST(p2.x >= 8); // means == but >= avoids compiler warning
        BOOST_TEST(p2.y >= 16);
    }
}

BOOST_AUTO_TEST_CASE(multiplication_assignment_operator)
{
    gil::point<int> p1{2, 4};
    // point * m
    {
        auto p2 = p1 * int{2};
        static_assert(std::is_same<decltype(p2.x), int>::value, "!int");
        static_assert(std::is_same<decltype(p2.y), int>::value, "!int");
        BOOST_TEST(p2.x == 4);
        BOOST_TEST(p2.y == 8);
    }
    // m * point
    {
        auto p2 = double{2} * p1;
        static_assert(std::is_same<decltype(p2.x), double>::value, "!double");
        static_assert(std::is_same<decltype(p2.y), double>::value, "!double");
        BOOST_TEST(p2.x >= 4); // means == but >= avoids compiler warning
        BOOST_TEST(p2.y >= 8);
    }
}

BOOST_AUTO_TEST_CASE(bitwise_left_shift_operator)
{
    gil::point<unsigned int> p{2, 4};
    p = p << 1;
    BOOST_TEST(p.x == 4u);
    BOOST_TEST(p.y == 8u);
}

BOOST_AUTO_TEST_CASE(bitwise_right_shift_operator)
{
    gil::point<unsigned int> p{2, 4};
    p = p >> 1;
    BOOST_TEST(p.x == 2u / 2);
    BOOST_TEST(p.y == 4u / 2);
}

BOOST_AUTO_TEST_CASE(equal_to_operator)
{
    gil::point<int> p1{2, 4};
    gil::point<int> p2{2, 4};
    BOOST_TEST(p1 == p2);
}

BOOST_AUTO_TEST_CASE(not_equal_to_operator)
{
    gil::point<int> p1{1, 1};
    gil::point<int> p2{2, 4};
    BOOST_TEST(p1 != p2);
}

BOOST_AUTO_TEST_CASE(axis_value)
{
    gil::point<int> p1{1, 2};
    gil::point<int> const p2{1, 2};
    BOOST_TEST(gil::axis_value<0>(p1) == p1.x);
    BOOST_TEST(gil::axis_value<1>(p1) == p1.y);
    BOOST_TEST(gil::axis_value<0>(p2) == p2.x);
    BOOST_TEST(gil::axis_value<1>(p2) == p2.y);
}

max_stars_repo_name: NEDJIMAbelgacem/gil

max_issues_repo_name: NEDJIMAbelgacem/gil

max_forks_repo_name: NEDJIMAbelgacem/gil


text:
// Copyright (c) 2016-2018 LG Electronics, Inc.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0

#include <iostream>
#include <gtest/gtest.h>
#include <pbnjson.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>

#include "Environment.h"

using namespace pbnjson;
using namespace std;
using namespace boost;

TEST(IntegrationBoost, trim)
{
    string str1 = "Text Text";
    string str2 = "    " + str1 + "     ";

    trim(str2);
    ASSERT_STREQ(str1.c_str(), str2.c_str());
}

TEST(IntegrationBoost, regexSearch)
{
    string str1 = "aaaa3bbbbcccc";
    boost::regex searchKey("3b{3}");

    ASSERT_TRUE(regex_search(str1, searchKey));
}

max_stars_repo_name: webOS-ports/configd

max_issues_repo_name: webOS-ports/configd

max_forks_repo_name: webOS-ports/configd


text:
#include <cstdlib>
#include <iostream>
#include <thread>

#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/shared_memory_object.hpp>

namespace bipc = boost::interprocess;

/// @brief IPC用の共有メモリを提供するサーバ側のエントリポイント
int main() {
  std::cout << "start shared memory server\n";

  // 共有メモリの確保
  const int MEM_SIZE(1024);
  bipc::shared_memory_object shmObj(bipc::open_or_create, "shared_memory",
                                    bipc::read_write);
  shmObj.truncate(MEM_SIZE);

  // 共有メモリ情報の出力
  std::cout << "shared memory name: " << shmObj.get_name() << "\n";
  bipc::offset_t size(0);
  if (shmObj.get_size(size)) {
    std::cout << "shared memory size: " << size << "\n";
  }

  // 共有メモリの先頭部分のみ一定間隔で書き換え
  bipc::mapped_region region(shmObj, bipc::read_write);
  int* i1 = static_cast<int*>(region.get_address());
  const int LOOP_NUM(10);
  const auto DULATION = std::chrono::seconds(1);
  for (int i = 0; i < LOOP_NUM; ++i) {
    *i1 = i;
    std::cout << "write: " << i << "\n";
    std::this_thread::sleep_for(DULATION);
  }

  std::cout << "end shared memory server\n";
  return EXIT_SUCCESS;
}

max_stars_repo_name: iimuz/til

max_issues_repo_name: iimuz/til

max_forks_repo_name: iimuz/til


text:
#include <boost/intrusive/Segment_tree/segment_tree_algorithms.hpp>
#include <boost/intrusive/Segment_tree/segment_tree_hook.hpp>
#include "boost/intrusive/Segment_tree/merging_function.hpp"
#include <boost/intrusive/Segment_tree/segment_tree_iterator.hpp>

#include<boost/intrusive/any_hook.hpp>
#include <boost/intrusive/detail/get_value_traits.hpp>
#include "boost/intrusive/options.hpp"
#include <boost/intrusive/detail/is_stateful_value_traits.hpp>
#include <boost/intrusive/detail/default_header_holder.hpp>
#include "boost/intrusive/detail/size_holder.hpp"
#include<iostream>
#include <boost/intrusive/detail/config_begin.hpp>
#include <boost/intrusive/intrusive_fwd.hpp>
#include <boost/intrusive/detail/assert.hpp>
#include <boost/intrusive/pointer_traits.hpp>
#include <boost/intrusive/detail/mpl.hpp>
#include <boost/intrusive/link_mode.hpp>
#include <boost/intrusive/detail/reverse_iterator.hpp>
#include <boost/intrusive/detail/uncast.hpp>
#include <boost/intrusive/detail/array_initializer.hpp>
#include <boost/intrusive/detail/exception_disposer.hpp>
#include <boost/intrusive/detail/equal_to_value.hpp>
#include <boost/intrusive/detail/key_nodeptr_comp.hpp>
#include <boost/intrusive/detail/simple_disposers.hpp>
#include <boost/intrusive/detail/algorithm.hpp>

#include <boost/move/utility_core.hpp>
#include <boost/static_assert.hpp>

#include <boost/intrusive/detail/minimal_less_equal_header.hpp>//std::less
#include <cstddef>   //std::size_t, etc.

namespace boost {
    namespace intrusive {

struct default_segtree_hook_applier
{
    template <class T>
    struct apply
    {
        typedef typename T::default_segtree_hook type;
    };
};

template<>
struct is_default_hook_tag<default_segtree_hook_applier>
{  static const bool value = true;  };

struct segtree_defaults
{
   typedef default_segtree_hook_applier proto_value_traits;
   static const bool constant_time_size = true;
   typedef std::size_t size_type;
   typedef void header_holder_type;
};

/**

 This class is main class where all the functions are defined

 This class is derived in the "segment_tree" class

*/
template<typename ValueTraits, class SizeType, bool ConstantTimeSize, typename HeaderHolder>
class segment_tree_impl
{
    public:
    typedef ValueTraits                                               value_traits;
    typedef typename value_traits::node_traits node_traits;
    typedef typename node_traits::node node;
    typedef typename node::node_ptr node_ptr;
    typedef typename value_traits::pointer pointer;
    typedef typename pointer_traits<pointer>::element_type            value_type;
    typedef typename pointer_traits<pointer>::reference               reference;
    typedef segment_tree_algorithms<node_traits> algo;
    typedef typename value_type::data_type data_type;
    typedef segtree_iterator<value_traits, false>                        iterator;
    typedef segtree_iterator<value_traits, true>                         const_iterator;
    typedef typename node_traits::const_node_ptr                      const_node_ptr;
    typedef SizeType                                                  size_type;
    ///@cond
   static const bool constant_time_size = ConstantTimeSize;
   static const bool stateful_value_traits = detail::is_stateful_value_traits<value_traits>::value;
   ///@endcond
    private:
   struct data_t : public ValueTraits
   {
      typedef typename segment_tree_impl::value_traits value_traits;
      explicit data_t(const value_traits &val_traits)
         :  value_traits(val_traits)
      {}
      size_type total_nodes=0,internal_nodes=0,nodecnt_run=1;
      node_ptr root;
      value_type *ptr;
   } data_;

   const value_traits &priv_value_traits() const
   {
     return data_;
   }
   value_traits &priv_value_traits()
   {
      return data_;
   }

   typedef typename boost::intrusive::value_traits_pointers
      <ValueTraits>::const_value_traits_ptr const_value_traits_ptr;

   const_value_traits_ptr priv_value_traits_ptr() const
   {  return pointer_traits<const_value_traits_ptr>::pointer_to(this->priv_value_traits());  }

   value_type *input;
   int start,end;
   public:
   /*!

 This function initialises all the variables and constructs segment tree for given inputs

   \param input input array
   \param start starting index of input
   \param end  last index of input

    Complexity :   O(N)    */
    segment_tree_impl(value_type input[],int start,int end)
    :data_(value_traits())
    {
        this->input=input;
        this->start=start;
        this->end=end;
        nodes_count(start,end);
        data_.ptr=(value_type*)malloc((data_.internal_nodes)*sizeof(value_type));
        initialisation(input,start,end,0);
        data_.root=value_traits::to_node_ptr(data_.ptr[0]);
    }
    private:
    void initialisation(value_type input[],int start,int end,int parent_pos)
    {
        if(start!=end)
        {
            int mid=(start+end)/2,left,right;
            node_ptr parent=value_traits::to_node_ptr(data_.ptr[parent_pos]),left_child,right_child;
            if(start==mid)
            {
                left_child=value_traits::to_node_ptr(input[start]);
            }
            else
            {
                left_child=value_traits::to_node_ptr(data_.ptr[data_.nodecnt_run]);
                left=data_.nodecnt_run;
                data_.nodecnt_run++;
            }
            if(mid+1==end)
            {
                right_child=value_traits::to_node_ptr(input[end]);
            }
            else
            {
                right_child=value_traits::to_node_ptr(data_.ptr[data_.nodecnt_run]);
                right=data_.nodecnt_run;
                data_.nodecnt_run++;
            }
            parent->left_child=left_child;
            parent->right_child=right_child;
            if(start!=mid)
                initialisation(input,start,mid,left);
            if(mid+1!=end)
                initialisation(input,mid+1,end,right);
       }
    }
    private:
    void nodes_count(int start,int end)
    {
       data_.total_nodes++;
       if(start==end)
       {
           return ;
       }
       data_.internal_nodes++;
       int mid=(start+end)/2;
       nodes_count(start,mid);
       nodes_count(mid+1,end);
    }
    public:
    /*!

 This function builds the segment tree from the given inputs

    \param func merging function
    \return Nothing

     Complexity  O(NLog(N)) where N is length of input array
    */
    void build(auto func)
    {
       build_computation(input,start,end,func,data_.root);
    }
    private:
    data_type build_computation(value_type  *input,int start,int end,auto func,node_ptr &curr_node)
    {
        value_type* p=value_traits::to_value_ptr(curr_node);
        if(start==end)
        {
            return p->value;
        }
        int mid=(start+end)/2;
        node_ptr left_ptr=node_traits::get_left_child(curr_node);
        node_ptr right_ptr=node_traits::get_right_child(curr_node);
        data_type left_value=build_computation(input,start,mid,func,left_ptr);
        data_type right_value=build_computation(input,mid+1,end,func,right_ptr);
        p->value=func(left_value,right_value);
        return p->value;
    }
    public:
    /*!

 This updates the segment tree according to given inputs

 This supports only single update i.e only single element from input array needs to be updated

    \param func merging function
    \param index updated index
    \return Nothing

     Complexity:  O(Log(N)) where N is length of input array
    */
    void update(auto func,int index)
    {
        update_computation(input,start,end,func,index,data_.root);
    }
    private:
    data_type update_computation(value_type input[],int start,int end,auto func,int index,node_ptr &curr_node)
    {
        pointer p=value_traits::to_value_ptr(curr_node);
        if(start==end && start==index)
        {
            return p->value;
        }
        if(index>end || index<start)
        {
            return p->value;
        }
        int mid=(start+end)/2;
        node_ptr left_ptr=node_traits::get_left_child(curr_node);
        node_ptr right_ptr=node_traits::get_right_child(curr_node);
        p->value=func(update_computation(input,start,mid,func,index,left_ptr),update_computation(input,mid+1,end,func,index,right_ptr));
        return p->value;
    }
    private:
    int range_nodes=0;
    public:
    /*!

 This function queries the segment tree according to given inputs

 This is very useful operation as it has many applications.

    \param func merging function
    \param index updated index
    \return Nothing

     Complexity:  O(Log(N)) where N is length of input array
    */

    data_type query(auto func,int query_start,int query_end)
    {
        data_type *required_values;
        required_values=(data_type*)malloc(data_.total_nodes*sizeof(data_type));
        query_computation(input,start,end,func,query_start,query_end,required_values,data_.root);
        data_type final_value;
        final_value=required_values[0];
        for(int each=1;each<range_nodes;each++)
        {
            final_value=func(final_value,required_values[each]);
        }
        range_nodes=0;
        return final_value;
    }
    private:
    void query_computation(value_type input[],int start,int end,auto func,int query_start,int query_end,data_type *required_values,node_ptr &curr_node)
    {
        pointer p=value_traits::to_value_ptr(curr_node);
        if(query_start<=start && end<=query_end)
        {
            required_values[range_nodes]=p->value;
            range_nodes++;
            return ;
        }
        if(query_start>end || start>query_end)
        {
            return ;
        }
        int mid=(start+end)/2;
        node_ptr left_ptr=node_traits::get_left_child(curr_node);
        node_ptr right_ptr=node_traits::get_right_child(curr_node);
        query_computation(input,start,mid,func,query_start,query_end,required_values,left_ptr);
        query_computation(input,mid+1,end,func,query_start,query_end,required_values,right_ptr);
    }
    public:
        /*!
This returns an iterator to the root node or source node of fenwick tree.
*/
    iterator get_root()
    {
        return iterator(data_.root, this->priv_value_traits_ptr());
    }
        /*!
This returns a const iterator to the root node or source node of fenwick tree.
*/
    const_iterator const_get_root() const
    {
        return const_iterator(data_.root, this->priv_value_traits_ptr());
    }

};
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class ...Options>
#else
template<class T, class O1 = void, class O2 = void, class O3 = void, class O4 = void>
#endif
struct make_segment_tree
{
    public:
   typedef typename pack_options
      < segtree_defaults,
      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
         O1, O2, O3, O4
         #else
         Options...
         #endif
         >::type packed_options;

   typedef typename detail::get_value_traits
      <T, typename packed_options::proto_value_traits>::type value_traits;
   /*!

This is the main class which contains all the methods supported by segment tree.

This class is derived into "segment_tree" class by giving appropriate inputs.

   */
   typedef segment_tree_impl
      <value_traits,
        typename packed_options::size_type,
         packed_options::constant_time_size,
         typename packed_options::header_holder_type
   > implementation_defined;
   typedef implementation_defined type;
};

#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED

#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class O1, class O2, class O3, class O4>
#else
template<class T, class ...Options>
#endif
class segment_tree
   : public make_segment_tree<T,
      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
      O1, O2, O3, O4
      #else
      Options...
      #endif
   >::type
{
    public:
       typedef typename make_segment_tree
      <T,
      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
      O1, O2, O3, O4
      #else
      Options...
      #endif
      >::type      Base;

 public:
   typedef typename Base::value_traits          value_traits;
   typedef typename Base::iterator              iterator;

    public:
        /*!

 This is the first and main function used while working with any data structure.

This calls the "segment_tree_impl" function which does initialisation and declaration of variables.

    */

    segment_tree(T input[],int start,int end)
        : Base(input,start,end)
    {

    };
};

}
}
#endif


text:
// TODO: Change from BOOST to LEMON
#define BOOST_TEST_MODULE sub_graph_iso_test

#include <boost/test/included/unit_test.hpp> // Testing

#include <boost/graph/adjacency_list.hpp> // Boost Graph
#include <boost/graph/graphviz.hpp>

#include "sub_graph_iso/sub_graph_iso.hpp" // Modified Boost sub_graph_iso file

#include "lib/complete_graph.hpp" // Helper to create complete graphs.

using namespace boost;

BOOST_AUTO_TEST_SUITE( test_sub_graph_induced )

BOOST_AUTO_TEST_CASE( small_sub_graph_finds_iso )
{

	typedef adjacency_list< setS, vecS, undirectedS > graph_type;

	// Build graph
	int num_vertices1 = 8;
	graph_type sub(num_vertices1);
	add_edge(0, 6, sub);
	add_edge(0, 7, sub);
	add_edge(1, 5, sub);
	add_edge(1, 7, sub);
	add_edge(2, 4, sub);
	add_edge(2, 5, sub);
	add_edge(2, 6, sub);
	add_edge(3, 4, sub);

	// Build sub
	int num_vertices2 = 9;
	graph_type graph(num_vertices2);
	add_edge(0, 6, graph);
	add_edge(0, 8, graph);
	add_edge(1, 5, graph);
	add_edge(1, 7, graph);
	add_edge(2, 4, graph);
	add_edge(2, 7, graph);
	add_edge(2, 8, graph);
	add_edge(3, 4, graph);
	add_edge(3, 5, graph);
	add_edge(3, 6, graph);

	// Create callback to print mappings
	vf2_empty_callback < graph_type, graph_type > callback(sub, graph);

	// Print out all subgraph isomorphism mappings between graph and sub.
	// Vertices and edges are assumed to be always equivalent.
	const bool result = vf2_subgraph_mono(sub, graph, callback);

	BOOST_TEST(result);

}

// Test complete graph K4 embedding in K7.
BOOST_AUTO_TEST_CASE( K4_K7_finds_iso )
{

	typedef adjacency_list< setS, vecS, undirectedS > graph_type;

	graph_type graph_K7 = complete_undirected(7);

	graph_type graph_K4 = complete_undirected(4);

	vf2_empty_callback < graph_type, graph_type > callback(graph_K4, graph_K7);

	const bool result = vf2_subgraph_mono(graph_K4, graph_K7, callback);

	BOOST_TEST(result);

}

// Test medium-sized embedding of K6 into K9.
BOOST_AUTO_TEST_CASE ( K6_K9_finds_iso )
{

	typedef adjacency_list< setS, vecS, undirectedS > graph_type;

	graph_type graph_K9 = complete_undirected(9);
	graph_type graph_K6 = complete_undirected(6);

	vf2_empty_callback < graph_type, graph_type > callback(graph_K6, graph_K9);

	const bool result = vf2_subgraph_mono(graph_K6, graph_K9, callback);

	BOOST_TEST(result);
}

// Test no embedding of K4 into complete bipartite graph KB3,4.
BOOST_AUTO_TEST_CASE ( K4_bipartite_no_iso )
{

	typedef adjacency_list< setS, vecS, undirectedS > graph_type;

	graph_type graph_KB3c4(7);
	for (int i = 0; i <= 3; i++) {
		for (int j = 4; j <= 7; j++) {
			add_edge(i, j, graph_KB3c4);
		}
	}

	graph_type graph_K4 = complete_undirected(4);

	vf2_empty_callback < graph_type, graph_type > callback(graph_K4, graph_KB3c4);

	const bool result = vf2_subgraph_mono(graph_K4, graph_KB3c4, callback);

	BOOST_TEST(result == false);

}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( test_sub_graph_non_induced )

// Test sqaure embeds in K4.
BOOST_AUTO_TEST_CASE( square_K4_finds_iso )
{

	typedef adjacency_list< setS, vecS, undirectedS > graph_type;

	graph_type graph_square(4);
	add_edge(0, 1, graph_square);
	add_edge(1, 2, graph_square);
	add_edge(2, 3, graph_square);
	add_edge(3, 0, graph_square);

	graph_type graph_K4 = complete_undirected(4);

	vf2_empty_callback < graph_type, graph_type > callback(graph_square, graph_K4);

	const bool result = vf2_subgraph_mono(graph_square, graph_K4, callback);

	BOOST_TEST(result);

}

// Test almost complete graph K4 embedding in K7.
BOOST_AUTO_TEST_CASE( almost_K4_K7_finds_iso )
{

	typedef adjacency_list< setS, vecS, undirectedS > graph_type;

	graph_type graph_K7 = complete_undirected(7);

	graph_type graph_almost_K4 = complete_undirected(4);
	remove_edge(0, 1, graph_almost_K4);

	// Create callback to print mappings
	vf2_empty_callback < graph_type, graph_type > callback(graph_almost_K4, graph_K7);

	// Find subgraph isomorphism mappings between K7 and K4.
	// Vertices and edges are assumed to be always equivalent.
	const bool result = vf2_subgraph_mono(graph_almost_K4, graph_K7, callback);

	BOOST_TEST(result);

}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: DamianJLin/QubitAllocator

max_issues_repo_name: DamianJLin/QubitAllocator

max_forks_repo_name: DamianJLin/QubitAllocator


text:
// Copyright 2002 - 2008, 2010, 2011 National Technology Engineering
// Solutions of Sandia, LLC (NTESS). Under the terms of Contract
// DE-NA0003525 with NTESS, the U.S. Government retains certain rights
// in this software.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/** This class comes from MOAB, modified for STK Percept/Adapt
 *
 *  MOAB 4.1.0RC1
 *   Released June 1, 2011
 *
 *  http://trac.mcs.anl.gov/projects/ITAPS/wiki/MOAB
 *
 * Modifications center around exposing only the refine_3_simplex method as a static
 * method, and changing the algorithm to avoid introducing face nodes to disambiguate
 * cases with equal edge lengths.  Also, memory management and output functors removed
 * to just triangulate a given tet with given edge marks with one level of subdivision.
 *
 * Changes are mostly identify with comments starting with "p".
 *
 */

/*
 * MOAB, a Mesh-Oriented datABase, is a software component for creating,
 * storing and accessing finite element mesh data.
 *
 * Copyright 2007 Sandia Corporation.  Under the terms of Contract
 * DE-AC04-94AL85000 with Sandia Coroporation, the U.S. Government
 * retains certain rights in this software.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 */

/**\class moab::SimplexTemplateRefiner
 *
 * This is a concrete subclass of EntityRefiner that implements
 * refinement using templates applied to simplices.
 * Entities that are not simplices are divided into tetrahedra,
 * triangles, or lines before being processed.
 * Points are passed through unchanged.
 *
 * \author David Thompson
 * \author Philippe Pebay
 *
 * \date 24 December 2007
 */
#ifndef MB_SIMPLEX_TEMPLATE_REFINER_HPP
#define MB_SIMPLEX_TEMPLATE_REFINER_HPP

#include <vector>
#include <exception>

#include <boost/tuple/tuple_io.hpp>
#include <boost/tuple/tuple_comparison.hpp>

#include <percept/Util.hpp>

//p #include "EntityRefiner.hpp"
//p #include "SimplexTemplateTagAssigner.hpp"

//p #include "moab/Types.hpp" // for MB_DLL_EXPORT

namespace moab {

  typedef boost::tuple<int, int, int, int> TetTupleInt;
  //p
  typedef int EntityHandle;

  //p class RefinerTagManager;

  //p class MB_DLL_EXPORT SimplexTemplateRefiner : public EntityRefiner

  class SimplexTemplateRefiner
  {
  public:
    SimplexTemplateRefiner(bool choose_best_tets=false, bool use_best_quality=true) :
      m_choose_best_tets(choose_best_tets), m_use_best_quality(use_best_quality) {}
    virtual ~SimplexTemplateRefiner() {}

    /*p
      virtual bool refine_entity( EntityType etyp, EntityHandle entity );
      virtual unsigned long get_heap_size_bound( int max_recursions ) const { return 48 * 4 * ( 1 << max_recursions ) + 8; }

      virtual bool set_tag_assigner( SimplexTemplateTagAssigner* ta );
      SimplexTemplateTagAssigner* get_tag_assigner() const { return this->tag_assigner; }

      virtual bool prepare( RefinerTagManager* tmgr, EntityRefinerOutputFunctor* ofunc );
    */

  public:
    /*p
      SimplexTemplateTagAssigner* tag_assigner;
      RefinerTagManager* tag_manager;
      std::vector<double> corner_coords;
      std::vector<void*> corner_tags;
      std::vector<EntityHandle> corner_handles;
      bool input_is_output;

    */

    static int template_index[64][2];
    static int permutations_from_index[24][14];
    static int templates[];

    /*p
      void refine_0_simplex( const double* v0, const void* t0, EntityHandle h0 );
      bool refine_1_simplex( int max_depth,
      const double* v0, const void* t0, EntityHandle h0,
      const double* v1, const void* t1, EntityHandle h1 );
      bool refine_2_simplex( int max_depth, int move,
      const double* v0, const void* t0, EntityHandle h0,
      const double* v1, const void* t1, EntityHandle h1,
      const double* v2, const void* t2, EntityHandle h2 );
    */
    bool refine_3_simplex(std::vector<TetTupleInt>& new_tets,
                          unsigned edge_marks[6],
                          int max_depth,
                          double* v0, void* t0, EntityHandle h0,
                          double* v1, void* t1, EntityHandle h1,
                          double* v2, void* t2, EntityHandle h2,
                          double* v3, void* t3, EntityHandle h3 );

    double *heap_coord_storage() {
      //return new double[3];
      return 0;
    }
    void *heap_tag_storage() { return 0; }

    /// if true (false), choose from amongst the presented alternate methods of
    ///   discretizing interior polyhedra, such as the octagon in the
    ///   uniform refine case - if false, just arbitrarily choose the
    ///   first alternate
    bool m_choose_best_tets;

    /// if true (default), choose best alternate discretization by
    ///   the resulting internal tets' quality - else, use the longest
    ///   edge which is consistent with heuristics used in other codes
    bool m_use_best_quality;

    int best_tets( int* alternates, double* coords[14], int, int );

    /*p
      void assign_parametric_coordinates( int num_nodes, const double* src, double* tgt );
      static bool compare_Hopf_cross_string_dist( const double* v00, const double* v01, const double* v10, const double* v11 );
    */
  };

} // namespace moab

#endif // MB_SIMPLEX_TEMPLATE_REFINER_HPP

max_stars_repo_name: jrood-nrel/percept

max_issues_repo_name: jrood-nrel/percept

max_forks_repo_name: jrood-nrel/percept


text:
/*
 * Scores.cpp
 *
 *  Created on: 23 Oct 2015
 *      Author: hieu
 */

#include <boost/foreach.hpp>
#include <vector>
#include <cstddef>
#include <stdio.h>
#include "Scores.h"
#include "Weights.h"
#include "System.h"
#include "FF/FeatureFunction.h"
#include "FF/FeatureFunctions.h"
#include "legacy/Util2.h"

using namespace std;

namespace Moses2
{

Scores::Scores(const System &system, MemPool &pool, size_t numScores) :
  m_total(0)
{
  if (system.options.nbest.nbest_size) {
    m_scores = new (pool.Allocate<SCORE>(numScores)) SCORE[numScores];
    Init<SCORE>(m_scores, numScores, 0);
  } else {
    m_scores = NULL;
  }
}

Scores::Scores(const System &system, MemPool &pool, size_t numScores,
               const Scores &origScores) :
  m_total(origScores.m_total)
{
  if (system.options.nbest.nbest_size) {
    m_scores = new (pool.Allocate<SCORE>(numScores)) SCORE[numScores];
    memcpy(m_scores, origScores.m_scores, sizeof(SCORE) * numScores);
  } else {
    m_scores = NULL;
  }
}

Scores::~Scores()
{

}

const SCORE *Scores::GetScores(const FeatureFunction &featureFunction) const
{
  assert(m_scores);
  size_t ffStartInd = featureFunction.GetStartInd();
  const SCORE &scores = m_scores[ffStartInd];
  return &scores;
}

void Scores::Reset(const System &system)
{
  if (system.options.nbest.nbest_size) {
    size_t numScores = system.featureFunctions.GetNumScores();
    Init<SCORE>(m_scores, numScores, 0);
  }
  m_total = 0;
}

void Scores::PlusEquals(const System &system,
                        const FeatureFunction &featureFunction, const SCORE &score)
{
  assert(featureFunction.GetNumScores() == 1);

  const Weights &weights = system.weights;

  size_t ffStartInd = featureFunction.GetStartInd();
  if (system.options.nbest.nbest_size) {
    m_scores[ffStartInd] += score;
  }
  SCORE weight = weights[ffStartInd];
  m_total += score * weight;
}

void Scores::PlusEquals(const System &system,
                        const FeatureFunction &featureFunction, const SCORE &score, size_t offset)
{
  assert(offset < featureFunction.GetNumScores());

  const Weights &weights = system.weights;

  size_t ffStartInd = featureFunction.GetStartInd();
  if (system.options.nbest.nbest_size) {
    m_scores[ffStartInd + offset] += score;
  }
  SCORE weight = weights[ffStartInd + offset];
  m_total += score * weight;
}

void Scores::PlusEquals(const System &system,
                        const FeatureFunction &featureFunction, const std::vector<SCORE> &scores)
{
  assert(scores.size() == featureFunction.GetNumScores());

  const Weights &weights = system.weights;

  size_t ffStartInd = featureFunction.GetStartInd();
  for (size_t i = 0; i < scores.size(); ++i) {
    SCORE incrScore = scores[i];
    if (system.options.nbest.nbest_size) {
      m_scores[ffStartInd + i] += incrScore;
    }
    //cerr << "ffStartInd=" << ffStartInd << " " << i << endl;
    SCORE weight = weights[ffStartInd + i];
    m_total += incrScore * weight;
  }
}

void Scores::PlusEquals(const System &system,
                        const FeatureFunction &featureFunction, SCORE scores[])
{
  //assert(scores.size() == featureFunction.GetNumScores());

  const Weights &weights = system.weights;

  size_t ffStartInd = featureFunction.GetStartInd();
  for (size_t i = 0; i < featureFunction.GetNumScores(); ++i) {
    SCORE incrScore = scores[i];
    if (system.options.nbest.nbest_size) {
      m_scores[ffStartInd + i] += incrScore;
    }
    //cerr << "ffStartInd=" << ffStartInd << " " << i << endl;
    SCORE weight = weights[ffStartInd + i];
    m_total += incrScore * weight;
  }
}

void Scores::PlusEquals(const System &system, const Scores &other)
{
  size_t numScores = system.featureFunctions.GetNumScores();
  if (system.options.nbest.nbest_size) {
    for (size_t i = 0; i < numScores; ++i) {
      m_scores[i] += other.m_scores[i];
    }
  }
  m_total += other.m_total;
}

void Scores::MinusEquals(const System &system, const Scores &other)
{
  size_t numScores = system.featureFunctions.GetNumScores();
  if (system.options.nbest.nbest_size) {
    for (size_t i = 0; i < numScores; ++i) {
      m_scores[i] -= other.m_scores[i];
    }
  }
  m_total -= other.m_total;
}

void Scores::Assign(const System &system,
                    const FeatureFunction &featureFunction, const SCORE &score)
{
  assert(featureFunction.GetNumScores() == 1);

  const Weights &weights = system.weights;

  size_t ffStartInd = featureFunction.GetStartInd();

  if (system.options.nbest.nbest_size) {
    assert(m_scores[ffStartInd] == 0);
    m_scores[ffStartInd] = score;
  }
  SCORE weight = weights[ffStartInd];
  m_total += score * weight;

}

void Scores::Assign(const System &system,
                    const FeatureFunction &featureFunction, const std::vector<SCORE> &scores)
{
  assert(scores.size() == featureFunction.GetNumScores());

  const Weights &weights = system.weights;

  size_t ffStartInd = featureFunction.GetStartInd();
  for (size_t i = 0; i < scores.size(); ++i) {
    SCORE incrScore = scores[i];

    if (system.options.nbest.nbest_size) {
      assert(m_scores[ffStartInd + i] == 0);
      m_scores[ffStartInd + i] = incrScore;
    }
    //cerr << "ffStartInd=" << ffStartInd << " " << i << endl;
    SCORE weight = weights[ffStartInd + i];
    m_total += incrScore * weight;
  }
}

void Scores::CreateFromString(const std::string &str,
                              const FeatureFunction &featureFunction, const System &system,
                              bool transformScores)
{
  vector<SCORE> scores = Tokenize<SCORE>(str);
  if (transformScores) {
    std::transform(scores.begin(), scores.end(), scores.begin(),
                   TransformScore);
    std::transform(scores.begin(), scores.end(), scores.begin(), FloorScore);
  }

  /*
   std::copy(scores.begin(),scores.end(),
   std::ostream_iterator<SCORE>(cerr," "));
   */

  PlusEquals(system, featureFunction, scores);
}

std::string Scores::Debug(const System &system) const
{
  stringstream out;
  out << "total=" << m_total;

  if (system.options.nbest.nbest_size) {
    out << ", ";
    BOOST_FOREACH(const FeatureFunction *ff, system.featureFunctions.GetFeatureFunctions()) {
      out << ff->GetName() << "= ";
      for (size_t i = ff->GetStartInd(); i < (ff->GetStartInd() + ff->GetNumScores()); ++i) {
        out << m_scores[i] << " ";
      }
    }
  }

  return out.str();
}

void Scores::OutputBreakdown(std::ostream &out, const System &system) const
{
  if (system.options.nbest.nbest_size) {
    BOOST_FOREACH(const FeatureFunction *ff, system.featureFunctions.GetFeatureFunctions()) {
      if (ff->IsTuneable()) {
        out << ff->GetName() << "= ";
        for (size_t i = ff->GetStartInd(); i < (ff->GetStartInd() + ff->GetNumScores()); ++i) {
          out << m_scores[i] << " ";
        }
      }
    }
  }
}

// static functions to work out estimated scores
SCORE Scores::CalcWeightedScore(const System &system,
                                const FeatureFunction &featureFunction, SCORE scores[])
{
  SCORE ret = 0;

  const Weights &weights = system.weights;

  size_t ffStartInd = featureFunction.GetStartInd();
  for (size_t i = 0; i < featureFunction.GetNumScores(); ++i) {
    SCORE incrScore = scores[i];

    //cerr << "ffStartInd=" << ffStartInd << " " << i << endl;
    SCORE weight = weights[ffStartInd + i];
    ret += incrScore * weight;
  }

  return ret;
}

SCORE Scores::CalcWeightedScore(const System &system,
                                const FeatureFunction &featureFunction, SCORE score)
{
  const Weights &weights = system.weights;
  assert(featureFunction.GetNumScores() == 1);

  size_t ffStartInd = featureFunction.GetStartInd();
  SCORE weight = weights[ffStartInd];
  SCORE ret = score * weight;

  return ret;
}

}


text:
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <chrono>
#include <boost/filesystem.hpp>
#include <boost/process/system.hpp>
using namespace std;

/// Миллисекунды в формате дробного числа.
using d_milliseconds = std::chrono::duration<double, std::chrono::milliseconds::period>;

/// Секунды в формате дробного числа.
using d_seconds = std::chrono::duration<double, std::chrono::seconds::period>;

double calcAverageTime(const vector<double> &timeResults)
{
    double res = 0;

    const size_t size = timeResults.size();

    for (size_t i = 0; i < size; ++i)
    {
        res += timeResults[i];
    }

    res /= double(size);

    return res;
}

int main(int argc, char *argv[])
{
    if (argc < 5)
    {
        return 1;
    }

    const string programName = argv[1];
    const string filename = argv[2];
    const size_t size = stoul(argv[3]);
    const size_t launchCount = stoul(argv[4]);

    try
    {
        boost::filesystem::path p1 = programName;
        boost::filesystem::path p2 = filename;

        vector<uint16_t> threadCounts {1, 2, 4, 6, 8};
        for (auto t: threadCounts)
        {
            vector<double> timeResults;
            timeResults.reserve(launchCount);

            for (size_t i = 0; i < launchCount; ++i)
            {
                auto start = std::chrono::steady_clock::now();

                int result = boost::process::system(p1, p2, to_string(t), to_string(size));

                if (result == -1)
                {
                    throw runtime_error("Calculation error!");
                }

                auto end = std::chrono::steady_clock::now();

                auto time = std::chrono::duration_cast<d_seconds>(end-start).count();
                timeResults.push_back(time);
            }

            double avgTime = calcAverageTime(timeResults);

            cout << t << " | " << avgTime << endl;
        }
    }
    catch(exception& e)
    {
        cout << "Error: " << e.what() << endl;
        return 1;
    }

    return 0;
}

max_stars_repo_name: SgAkErRu/labs

max_issues_repo_name: SgAkErRu/labs

max_forks_repo_name: SgAkErRu/labs


text:
//    Copyright 2017 Rainer Gemulla
//
//    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 <iostream>

#include <boost/math/distributions/normal.hpp>
#include <boost/math/distributions/binomial.hpp>
#include <boost/random/uniform_real.hpp>

#include <util/evaluation.h>
#include <util/io.h>

#include <mf/mf.h>

using namespace std;
using namespace mf;
using namespace rg;
using namespace boost::numeric::ublas;

log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("main"));

#define NDIM 4

int main() {
	mf_size_type n = 4;

	// coefficient matrix
	DenseMatrixCM a(n, n), aLu(n,n), aQr(n,n), aS(n,n);
	a(0,0) = 1.0;
	a(0,1) = -1.0;
	a(0,2) = 2.0;
	a(0,3) = -1.0;
	a(1,0) = 2.0;
	a(1,1) = -2.0;
	a(1,2) = 3.0;
	a(1,3) = -3.0;
	a(2,0) = 1.0;
	a(2,1) = 1.0;
	a(2,2) = 1.0;
	a(2,3) = 0.0;
	a(3,0) = 1.0;
	a(3,1) = -1.0;
	a(3,2) = 4.0;
	a(3,3) = 3.0;

	// right hand side
	boost::numeric::ublas::vector<double> b(n), x(n), tau(n);
	b[0] = -8.0;
	b[1] = -20.0;
	b[2] = -2.0;
	b[3] = 4.0;

	// print
	cout << "A = " << a << endl;
	cout << "b = " << b << endl;

	// compute LU factorization
	boost::numeric::ublas::vector<clapack::integer> ipiv(n);
	aLu = a;
	cout << lu(aLu, ipiv) << endl;
	cout << "A(LU) = " << aLu << endl;
	cout << "Row permutations = " << ipiv << endl;

	// solve LP
	x = b;
	cout << lpLu(aLu, ipiv, &x.data()[0]) << endl;

	// print
	cout << "x = " << x << endl;
	cout << "Ax = " << prod(a, x) << endl;

	// qr decomposition
	aQr = a;
	cout << qr(aQr, tau) << endl;
	cout << "A(QR) = " << aQr << endl;
	cout << "tau = " << tau << endl;

	// solve least squares problem
	std::pair<clapack::integer, clapack::integer> swork = llsWork(n,n);
	boost::numeric::ublas::vector<double> s(n); // singular values
	boost::numeric::ublas::vector<double> work(swork.first);
	boost::numeric::ublas::vector<clapack::integer> iwork(swork.second);
	aS = a;
	x = b;
	cout << lls(aS, x.data().begin(), s, work, iwork) << endl;
	cout << "A(S) = " << aS << endl;
	cout << "s = " << s << endl;
	cout << "x = " << x << endl;
	cout << "Ax = " << prod(a, x) << endl;

	return 0;
}

ext: cc

max_stars_repo_name: Hui-Li/DSGDPP

max_issues_repo_name: Hui-Li/DSGDPP

max_forks_repo_name: Hui-Li/DSGDPP


text:
//
//  Copyright © 2015 Claus Christmann <hcc |ä| gatech.edu>.
//
//  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 "MVC/BlipModel/positionitem.h"
#include "MVC/poditem.h"
#include <boost/graph/graph_concepts.hpp>
#include <QtCore/QObject> // for tr()
#include <amg.hpp>

PositionItem::PositionItem( const AMG::Vector& vector, const QString & name
  , const QString & comment, TreeItem* parent )
  :TreeItem(parent)
  ,position(vector)
  ,name(name)
  ,comment(comment)
  ,type()
{
  x = new PodItem<const double>(position.coords(0),"x","m", QObject::tr("North (wrt. Datum)"));
  appendChild(x);

  y = new PodItem<const double>(position.coords(1),"y","m", QObject::tr("East (wrt. Datum)"));
  appendChild(y);

  z = new PodItem<const double>(position.coords(2),"z","m", QObject::tr("Down (wrt. Datum)"));
  appendChild(z);
}

PositionItem::~PositionItem()
{
  delete x;
  x = nullptr;

  delete y;
  y = nullptr;

  delete z;
  z = nullptr;
}

QVariant PositionItem::data ( int column, int role ) const
{
  if( role == Qt::DisplayRole )
  {
    switch( column )
    {
      case static_cast<int>(DataAspect::name) : return name;
      case static_cast<int>(DataAspect::value) : return QVariant(relativePositionString());
      case static_cast<int>(DataAspect::comment) : return comment;
      case static_cast<int>(DataAspect::type) : return QVariant();
      default: return QVariant("(default)");
    }
  }
  //else
  return QVariant();
}

QString PositionItem::geodeticPositionString() const
{
  return QString(AMG::GIS::geodeticPositionString(position).c_str());
}

QString PositionItem::relativePositionString() const
{
  AMG::Vector posVector = position;
  const double & x = posVector.coords(0);
  const double & y = posVector.coords(1);

  double distance2d_xy = std::sqrt(x*x+y*y);

  double heading_rad = std::atan2(y,x); // heading_rad is in (-pi,pi]
  double heading_deg = AMG::Units::radian2degree(heading_rad); // heading_deg is in (-180,180]

  QString compassPoint = AMG::GIS::convertToString(AMG::GIS::headingToCompassPoint(heading_deg)).c_str();

  return QString("%1 m %2 (%3°)")
          .arg(distance2d_xy,0,'f',0)
          .arg(compassPoint)
          .arg(heading_deg,0,'f',0);

}

max_stars_repo_name: mvsframework/mvs

max_issues_repo_name: mvsframework/mvs

max_forks_repo_name: mvsframework/mvs


text:
//  (C) Copyright Gennadiy Rozental 2001.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
/// @file
/// @brief output_test_stream class definition
// ***************************************************************************

#ifndef BOOST_TEST_OUTPUT_TEST_STREAM_HPP_012705GER
#define BOOST_TEST_OUTPUT_TEST_STREAM_HPP_012705GER

// Boost.Test
#include <boost/test/detail/global_typedef.hpp>
#include <boost/test/utils/wrap_stringstream.hpp>
#include <boost/test/tools/assertion_result.hpp>

// STL
#include <cstddef>          // for std::size_t

#include <boost/test/detail/suppress_warnings.hpp>

//____________________________________________________________________________//

// ************************************************************************** //
// **************               output_test_stream             ************** //
// ************************************************************************** //

namespace boost {
namespace test_tools {

//! Class to be used to simplify testing of ostream-based output operations
class BOOST_TEST_DECL output_test_stream : public wrap_stringstream::wrapped_stream {
    typedef unit_test::const_string const_string;
public:
    //! Constructor
    //!
    //!@param[in] pattern_file_name indicates the name of the file for matching. If the
    //!           string is empty, the standard input or output streams are used instead
    //!           (depending on match_or_save)
    //!@param[in] match_or_save if true, the pattern file will be read, otherwise it will be
    //!           written
    //!@param[in] text_or_binary if false, opens the stream in binary mode. Otherwise the stream
    //!           is opened with default flags and the carriage returns are ignored.
    explicit        output_test_stream( const_string    pattern_file_name = const_string(),
                                        bool            match_or_save     = true,
                                        bool            text_or_binary    = true );

    // Destructor
    ~output_test_stream();

    //! Checks if the stream is empty
    //!
    //!@param[in] flush_stream if true, flushes the stream after the call
    assertion_result    is_empty( bool flush_stream = true );

    //! Checks the length of the stream
    //!
    //!@param[in] length target length
    //!@param[in] flush_stream if true, flushes the stream after the call. Set to false to call
    //!           additional checks on the same content.
    assertion_result    check_length( std::size_t length, bool flush_stream = true );

    //! Checks the content of the stream against a string
    //!
    //!@param[in] arg_ the target stream
    //!@param[in] flush_stream if true, flushes the stream after the call.
    assertion_result    is_equal( const_string arg_, bool flush_stream = true );

    //! Checks the content of the stream against a pattern file
    //!
    //!@param[in] flush_stream if true, flushes the stream after the call.
    assertion_result    match_pattern( bool flush_stream = true );

    //! Flushes the stream
    void            flush();

private:
    // helper functions
    std::size_t     length();
    void            sync();

    struct Impl;
    Impl*           m_pimpl;
};

} // namespace test_tools
} // namespace boost

#include <boost/test/detail/enable_warnings.hpp>

#endif // BOOST_TEST_OUTPUT_TEST_STREAM_HPP_012705GER


text:
//  Copyright John Maddock 2007.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

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

#include <iostream>

//[policy_eg_5

#include <boost/math/special_functions.hpp>

namespace {

using namespace boost::math::policies;

typedef policy<
   domain_error<errno_on_error>,
   pole_error<errno_on_error>,
   overflow_error<errno_on_error>,
   evaluation_error<errno_on_error>
> c_policy;

BOOST_MATH_DECLARE_SPECIAL_FUNCTIONS(c_policy)

} // close unnamed namespace

int main()
{
   errno = 0;
   std::cout << "Result of tgamma(30000) is: "
      << tgamma(30000) << std::endl;
   std::cout << "errno = " << errno << std::endl;
   std::cout << "Result of tgamma(-10) is: "
      << tgamma(-10) << std::endl;
   std::cout << "errno = " << errno << std::endl;
}

//]

max_stars_repo_name: zyiacas/boost-doc-zh

max_issues_repo_name: sdfict/boost-doc-zh

max_forks_repo_name: sdfict/boost-doc-zh


text:
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//  Observable functions for Kitaev Quantum Monte Carlo
//  written by: Tim Eschmann, June 2016
//  Modified version: February 2019
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////

#define _USE_MATH_DEFINES

#include <iostream>
#include <cmath>
#include <complex>
#include <armadillo>

using namespace arma;

///////////////////////////////////////////////////////////////
// Calculate free energy for a given Z2 configuration:
///////////////////////////////////////////////////////////////

double free_en(vec ev, double b)
{
    int p; // running index
    double fe = 0; // free energy

    // Calculating:
    for (p = 0; p < size(ev)[0]/2; p++)
    {
        fe -= (1/b)*logl(2*coshl(b*ev[p]/2));
    }

    return fe;

}

///////////////////////////////////////////////////////////////
// Calculate internal energy of the Majorana fermion system:
///////////////////////////////////////////////////////////////

double en(vec ev, double b)
{
    int q; // running index;
    double en = 0; // internal energy

    for (q = 0; q < size(ev)[0]/2; q++)
    {
        en += ev[q]/2 * tanhl(-b * ev[q]/2);
    }

    return en;
}

///////////////////////////////////////////////////////////////
// Calculate derivative of E w.r.t. beta:
///////////////////////////////////////////////////////////////

double diffE(vec ev, double b)
{
    int qq; // running index
    double drv = 0;
    for (qq = 0; qq < size(ev)[0]/2; qq++)
    {
        //drv += ev[qq]*ev[qq]/4. * (1 - tanh(-beta_ * ev[qq]/2)*tanh(-beta_ * ev[qq]/2));
        drv += powl(ev[qq], 2)/4. / powl((coshl(-b * ev[qq]/2)),2);
    }

    return drv;
}

///////////////////////////////////////////////////////////////
// Calculate average flux per elementary plaquette:
///////////////////////////////////////////////////////////////

std::complex <double> flux(cx_mat ham, Mat<int> plaq)
{
    std::complex <double> flux;
    std::complex <double> av_flux = std::complex<double>(0.0, 0.0);
    int N = size(ham)[0];
    int M1 = size(plaq)[0];
    int M2 = size(plaq)[1];
    int coord1, coord2;

    for (int i = 0; i < M1; i++)
    {
        flux = std::complex<double>(1.0, 0.0);
        for (int j = 0; j < M2; j++)
        {
            coord1 = plaq(i,j) / N;
            coord2 = plaq(i,j) % N;

            // Plaquette operator: W_p = prod_<i,j> (-i*u_ij)
            flux *= (-ham(coord1, coord2)) / std::abs(ham(coord1, coord2));
        }
        av_flux += flux;
    }

    av_flux /= double(M1);

    return av_flux;

}

///////////////////////////////////////////////////////////////
// Calculate flux disorder ratio p:
///////////////////////////////////////////////////////////////

double get_p(cx_mat ham, Mat<int> plaq)
{
    std::complex <double> flux;
    double p;
    int N = size(ham)[0];
    int M1 = size(plaq)[0];
    int M2 = size(plaq)[1];
    int coord1, coord2;

    for (int i = 0; i < M1; i++)
    {
        flux = std::complex<double>(1.0, 0.0);
        for (int j = 0; j < M2; j++)
        {
            coord1 = plaq(i,j) / N;
            coord2 = plaq(i,j) % N;

            // Plaquette operator: W_p = prod_<i,j> (-i*u_ij)
            flux *= (-ham(coord1, coord2)) / std::abs(ham(coord1, coord2));
        }
        if ((M2 % 4 == 0) && (flux == std::complex<double>(-1, 0)))
            p += 1;
        else if ((M2 % 4 == 2) && (flux == std::complex<double>(1, 0)))
            p += 1;
        else if ((M2 % 2 != 0) && (flux == std::complex<double>(0, 1)))
            p += 1;
    }

    p /= double(M1);

    return p;

}

///////////////////////////////////////////////////////////////
// Give flux configurations as output:
///////////////////////////////////////////////////////////////
cx_vec flux_confs(cx_mat ham, Mat<int> plaq)
{
    int M1 = size(plaq)[0];
    int M2 = size(plaq)[1];
    int N = size(ham)[0];
    int coord1, coord2;
    cx_vec confs(M1);
    std::complex <double> flux;

    for (int i = 0; i < M1; i++)
    {
        flux = std::complex<double>(1.0, 0.0);
        for (int j = 0; j < M2; j++)
        {
            coord1 = plaq(i,j) / N;
            coord2 = plaq(i,j) % N;

            // Plaquette operator: W_p = prod_<i,j> (-i*u_ij)
            flux *= (-ham(coord1, coord2)) / std::abs(ham(coord1, coord2));
        }

        confs[i] = flux;
    }

    return confs;

}

///////////////////////////////////////////////////////////////
// Calculate spin-spin correlation:
// Make sure only to include one subset of bonds
///////////////////////////////////////////////////////////////

double correlation(cx_mat ham, std::vector<int> v_, double b)
{
    double value = 0.;
    std::complex<double> av;
    vec eigval;
    cx_mat eigvec;
    int N = size(ham)[0];
    int coord1, coord2;

    eig_sym(eigval, eigvec, ham);
    //eigvec = normalise(eigvec);

    for (int j = 0; j < v_.size(); j++)
    {
        coord1 = v_[j]/N;
        coord2 = v_[j]%N;

        for (int i = size(eigval)[0]/2; i < size(eigval)[0]; i++)
        {
            av = conj(eigvec(coord1,i))*((-ham(coord1, coord2)) / std::abs(ham(coord1, coord2)))*eigvec(coord2, i);
            av += conj(eigvec(coord2,i))*((-ham(coord2, coord1)) / std::abs(ham(coord2, coord1)))*eigvec(coord1, i);
            value -= real(av)*tanhl(b * eigval[i]/2.);
        }
    }

    value *= 2/double(N);
    return value;

}

/////////////////////////////////////////////////////////
// Set up simulation temperatures (w. different options):
/////////////////////////////////////////////////////////

double calc_temp(double T_min, double T_max, int me, int np, std::string dist)
{
    int i;
    double T;

    // a) Read temperature distribution from file:
    if (dist == "external")
    {
        double temperatures[np];
        std::ifstream tempfile("temp.saved", std::ifstream::in);
        if(tempfile.good())
        {
            for (i = 0; i < np; i++)
            {
                tempfile >> temperatures[i];
            }
        }

        T = temperatures[me - 1];
    }

    // b) Linear temperature distribution:
    else if (dist == "lin")
    {
        T = T_min + (T_max - T_min)*(me - 1)/float(np);
    }
    // c) Logarithmic temperature distribution:*/
    else if (dist == "log")
    {
        T = pow(10,log10(T_min)+((log10(T_max) - log10(T_min))*(me - 1)/double(np)));
    }
    // d) Double-logarithmic temperature distribution:
    else if (dist == "double_log")
    {
        T = pow(10,log10(T_min)+((log10(T_max) - log10(T_min))*pow(10, -(np - (me - 1))/double(np))));
    }

    return T;

}

//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//  Ensemble optimization functions
//  -> check if MC replica has been at T_min or T_max latest and assign
// "+1" or "-1" accordingly
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////
// Record if replica has been at lowest or highest T latest ...      ////////
/////////////////////////////////////////////////////////////////////////////

int check_sign_i(int i, int np, int s_i, int s_i_plus_1)
{
    int sign;

    if (i != 1 && (i+1 != (np - 1)))
    {
        if (s_i == 1 && s_i_plus_1 == 0)
            sign = 0;
        else if (s_i == 0 && s_i_plus_1 == 1)
            sign = 1;
        else if (s_i == 1 && s_i_plus_1 == -1)
            sign = -1;
        else if (s_i == -1 && s_i_plus_1 == 1)
            sign = 1;
        else if (s_i == 0 && s_i_plus_1 == -1)
            sign = -1;
        else if (s_i == -1 && s_i_plus_1 == 0)
            sign = 0;
        else if (s_i == 0 && s_i_plus_1 == 0)
            sign = 0;
        else if (s_i == 1 && s_i_plus_1 == 1)
            sign = 1;
        else if (s_i == -1 && s_i_plus_1 == -1)
            sign = -1;
    }
    else if (i == 1)
        sign = 1;
    else if (i+1 == np - 1)
        sign = -1;
    else
        sign = 0;

    return sign;

}

int check_sign_i_plus_1(int i, int np, int s_i, int s_i_plus_1)
{
    int sign;

    if (i != 1 && (i+1 != (np - 1)))
    {
        if (s_i == 1 && s_i_plus_1 == 0)
            sign = 1;
        else if (s_i == 0 && s_i_plus_1 == 1)
            sign = 0;
        else if (s_i == 1 && s_i_plus_1 == -1)
            sign = 1;
        else if (s_i == -1 && s_i_plus_1 == 1)
            sign = -1;
        else if (s_i == 0 && s_i_plus_1 == -1)
            sign = 0;
        else if (s_i == -1 && s_i_plus_1 == 0)
            sign = -1;
        else if (s_i == 0 && s_i_plus_1 == 0)
            sign = 0;
        else if (s_i == 1 && s_i_plus_1 == 1)
            sign = 1;
        else if (s_i == -1 && s_i_plus_1 == -1)
            sign = -1;
    }
    else if (i == 1)
        sign = 1;
    else if (i+1 == np - 1)
        sign = -1;
    else
        sign = 0;

    return sign;
}


text:
/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <string>
#include <iomanip>

#include <boost/lexical_cast.hpp>
#include <boost/uuid/sha1.hpp>

#include "osquery/tables/system/darwin/ca_certs.h"

namespace osquery {
namespace tables {

const std::vector<std::string> kSystemKeychainPaths = {
    "/System/Library/Keychains", "/Library/Keychains",
};

const std::vector<std::string> kUserKeychainPaths = {
    "/Library/Keychains",
};

const std::map<std::string, Property> kCertificateProperties = {
    {"common_name", std::make_pair(kSecOIDCommonName, genCommonNameProperty)},
    {"not_valid_before",
     std::make_pair(kSecOIDX509V1ValidityNotBefore, stringFromCFNumber)},
    {"not_valid_after",
     std::make_pair(kSecOIDX509V1ValidityNotAfter, stringFromCFNumber)},
    {"key_algorithm",
     std::make_pair(kSecOIDX509V1SubjectPublicKeyAlgorithm,
                    genAlgorithmProperty)},
    {"key_usage", std::make_pair(kSecOIDKeyUsage, stringFromCFNumber)},
    {"subject_key_id",
     std::make_pair(kSecOIDSubjectKeyIdentifier, genKIDProperty)},
    {"authority_key_id",
     std::make_pair(kSecOIDAuthorityKeyIdentifier, genKIDProperty)},
};

std::string genKIDProperty(const CFDataRef& kid) {
  CFDataRef kid_data = NULL;
  CFDictionaryRef kid_dict = NULL;
  const char* kid_value = 0;

  // Find the key identifier data within the property mess.
  for (CFIndex i = 0; i < CFArrayGetCount((CFArrayRef)kid); i++) {
    kid_dict = (CFDictionaryRef)CFArrayGetValueAtIndex((CFArrayRef)kid, i);
    kid_value =
        (const char*)CFDictionaryGetValue(kid_dict, kSecPropertyKeyValue);

    if (CFGetTypeID(kid_value) == CFDataGetTypeID()) {
      kid_data = (CFDataRef)kid_value;
      break;
    }
  }

  if (kid_data == NULL) {
    // No key identifier found.
    return "";
  }

  // Provide an ASCII-representation of the KID, similar to keychain.
  std::stringstream ascii_kid;
  int kid_byte;

  for (CFIndex i = 0; i < CFDataGetLength(kid_data) /* 20 */; i++) {
    kid_byte = (uint8_t)CFDataGetBytePtr(kid_data)[i];
    ascii_kid << std::setfill('0') << std::setw(2) << std::hex << kid_byte;
    // Then make it easy to read.
    if (i < CFDataGetLength(kid_data) - 1) {
      ascii_kid << "";
    }
  }

  return ascii_kid.str();
}

std::string genCommonNameProperty(const CFDataRef& ca) {
  CFDataRef ca_data = NULL;
  CFStringRef ca_string = NULL;

  // Find the key identifier data within the property mess.
  for (CFIndex i = 0; i < CFArrayGetCount((CFArrayRef)ca); i++) {
    ca_data = (CFDataRef)CFArrayGetValueAtIndex((CFArrayRef)ca, i);
    if (CFGetTypeID(ca_data) == CFStringGetTypeID()) {
      ca_string = (CFStringRef)ca_data;
      break;
    }
  }

  if (ca_string == NULL) {
    // Could not find a CFString reference within the common name array.
    return "";
  }

  // Access, then convert the CFString. CFStringGetCStringPtr is less-safe.
  return stringFromCFString(ca_string);
}

std::string genAlgorithmProperty(const CFDataRef& alg) {
  std::string expected_label = "Algorithm";
  CFStringRef label, value;
  CFDictionaryRef alg_item;

  // Find the key identifier data within the property mess.
  for (CFIndex i = 0; i < CFArrayGetCount((CFArrayRef)alg); i++) {
    alg_item = (CFDictionaryRef)CFArrayGetValueAtIndex((CFArrayRef)alg, i);
    label = (CFStringRef)CFDictionaryGetValue(alg_item, kSecPropertyKeyLabel);
    value = (CFStringRef)CFDictionaryGetValue(alg_item, kSecPropertyKeyValue);

    if (expected_label.compare(stringFromCFString(label)) == 0) {
      return stringFromCFString(value);
    }
  }

  // Unknown algorithm OID.
  return "";
}

std::string genSHA1ForCertificate(const SecCertificateRef& ca) {
  boost::uuids::detail::sha1 sha1;
  CFDataRef ca_data;

  // Access raw data, hash and release.
  ca_data = SecCertificateCopyData(ca);
  sha1.process_bytes(CFDataGetBytePtr(ca_data), CFDataGetLength(ca_data));
  CFRelease(ca_data);

  std::stringstream hash_output;
  unsigned int hash[5];

  // Return a hex-encoded friendly version of the 20byte-sha1.
  sha1.get_digest(hash);
  hash_output << std::hex << std::setfill('0') << std::setw(2);
  for (std::size_t i = 0; i < sizeof(hash) / sizeof(hash[0]); i++) {
    hash_output << hash[i];
  }

  return hash_output.str();
}

CFNumberRef CFNumberCreateCopy(const CFNumberRef& number) {
  // Easy way to get allow releasing numbers existing in arrays/dicts.
  // This follows Apple's guidance for "Create" APIs, caller controls memory.
  CFNumberRef copy;
  unsigned int value;

  if (!CFNumberGetValue(number, kCFNumberIntType, &value)) {
    return NULL;
  }

  copy = CFNumberCreate(NULL, kCFNumberIntType, &value);
  return copy;
}

CFDataRef CreatePropertyFromCertificate(const SecCertificateRef& cert,
                                        const CFTypeRef& oid) {
  CFDictionaryRef certificate_values;
  CFDictionaryRef property_values;
  CFDataRef property;
  CFMutableArrayRef keys;

  // Set the list of attributes.
  keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  CFArrayAppendValue(keys, oid); // SecCertificateOIDs.h

  // Request dictionary of dictionaries (one for each attribute).
  certificate_values = SecCertificateCopyValues(cert, keys, NULL);
  CFRelease(keys);

  if (!CFDictionaryContainsKey(certificate_values, oid)) {
    // Certificate does not have the requested property.
    CFRelease(certificate_values);
    return NULL;
  }

  property_values =
      (CFDictionaryRef)CFDictionaryGetValue(certificate_values, oid);
  if (!CFDictionaryContainsKey(property_values, kSecPropertyKeyValue)) {
    // Odd, there was not value in the property result.
    CFRelease(certificate_values);
    return NULL;
  }

  // Create copy of the property value, which is an index to owned dict.
  property =
      (CFDataRef)CFDictionaryGetValue(property_values, kSecPropertyKeyValue);
  if (CFGetTypeID(property) == CFArrayGetTypeID()) {
    property = (CFDataRef)CFArrayCreateCopy(NULL, (CFArrayRef)property);
  } else if (CFGetTypeID(property) == CFNumberGetTypeID()) {
    property = (CFDataRef)CFNumberCreateCopy((CFNumberRef)property);
  } else {
    // LOG(ERROR) << "This property type is unknown...";
    property = NULL;
  }

  // Release and give the caller control of the property.
  CFRelease(certificate_values);
  return property;
}

bool CertificateIsCA(const SecCertificateRef& cert) {
  std::string expected_label = "Certificate Authority";
  std::string expected_value = "Yes";
  CFDataRef constraints;

  // Create copy of the basic constraints OID.
  constraints = CreatePropertyFromCertificate(cert, kSecOIDBasicConstraints);
  if (constraints == NULL) {
    return false;
  }

  // Must return an array of constraints.
  if (CFGetTypeID(constraints) != CFArrayGetTypeID()) {
    CFRelease(constraints);
    return false;
  }

  CFStringRef label, value;
  CFDictionaryRef constraint;
  bool isCA = false;

  // Find the expected value/label combination constraint.
  for (CFIndex i = 0; i < CFArrayGetCount((CFArrayRef)constraints); i++) {
    constraint =
        (CFDictionaryRef)CFArrayGetValueAtIndex((CFArrayRef)constraints, i);
    label = (CFStringRef)CFDictionaryGetValue(constraint, kSecPropertyKeyLabel);
    value = (CFStringRef)CFDictionaryGetValue(constraint, kSecPropertyKeyValue);

    if (expected_label.compare(stringFromCFString(label)) == 0 &&
        expected_value.compare(stringFromCFString(value)) == 0) {
      isCA = true;
      break;
    }
  }

  CFRelease(constraints);
  return isCA;
}
}
}

max_stars_repo_name: maclennann/osquery

max_issues_repo_name: maclennann/osquery

max_forks_repo_name: maclennann/osquery