text:
#ifndef basic_list_mediator_h__31080910
#define basic_list_mediator_h__31080910

#include "litwindow/tstring.hpp"
#include "litwindow/dataadapter.h"
#include <vector>
#include <iterator>
#include <boost/ref.hpp>
#include <boost/function.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/bind/protect.hpp>
#include <boost/utility/result_of.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_member_function_pointer.hpp>
#include <boost/type_traits/is_member_object_pointer.hpp>
#include <boost/type_traits/is_function.hpp>
#include <boost/type_traits/remove_pointer.hpp>
#include <boost/type_traits/function_traits.hpp>
#include <boost/type_traits/add_const.hpp>
#include <boost/type_traits/add_reference.hpp>

#include <boost/serialization/nvp.hpp>
#include <boost/serialization/vector.hpp>
//#include <boost/archive/text_wiarchive.hpp>
//#include <boost/archive/text_woarchive.hpp>

#include <boost/version.hpp>
#if BOOST_VERSION < 104700
#ifndef BOOST_TYPEOF_SILENT
#define BOOST_TYPEOF_SILENT
#endif
#endif

#include <boost/typeof/typeof.hpp>
#include <iterator>

//#pragma optimize("ty", on)

namespace litwindow {
    namespace ui {
		using namespace std;

		class basic_column_label
		{
		public:
            /// the title or header of the column
            tstring title() const { return m_title; }
            /// set the column width
            void width(int new_width) { m_width=new_width; }
            /// return the column width
            int width() const { return m_width; }
            /// visibility
            bool visible() const { return m_visible; }
            void visible(bool do_show) { m_visible=do_show; }
			bool image() const { return m_image; }
			void image(bool is_image) { m_image=is_image; }
			void position(int new_position) { m_position=new_position; }
			int  position() const { return m_position; }
			template <typename Archive>
			void serialize(Archive &ar, const unsigned int version)
			{
				ar & BOOST_SERIALIZATION_NVP(m_title) & BOOST_SERIALIZATION_NVP(m_width) & BOOST_SERIALIZATION_NVP(m_visible);
				if (version>=1)
					ar & BOOST_SERIALIZATION_NVP(m_position);
				else if (Archive::is_loading())
					m_position=-1;
			}
			basic_column_label(const tstring &title, int width=-1, bool visible=true, bool is_image=false)
				:m_title(title),m_width(width),m_visible(visible),m_image(is_image),m_position(-1){}
		protected:
			tstring m_title;
			int     m_width;
			bool    m_visible;
			bool	m_image;
			int		m_position;
		};

        template <typename Value/*, typename TextRenderer*/>
		class basic_column_descriptor:public basic_column_label
        {
        public:
            typedef boost::function<void (const Value&, tstring&)> text_renderer_type;
			typedef boost::function<void (const Value&, int&)> image_index_renderer_type;
			typedef boost::function<bool (const Value &left, const Value &right)> comparator_type;
            //typedef TextRenderer text_renderer_type;
            typedef Value value_type;
        public:
			text_renderer_type m_text_renderer;
			image_index_renderer_type m_image_index_renderer;
			comparator_type m_comparator;
			basic_column_descriptor(const tstring &title, int width=-1, const text_renderer_type &v=text_renderer_type())
                :basic_column_label(title, width, true, false), m_text_renderer(v), m_image_index_renderer(0)
            {}
			basic_column_descriptor(const tstring &title, int width, const image_index_renderer_type &i)
				:basic_column_label(title, width, true, true), m_text_renderer(0), m_image_index_renderer(i)
			{}

			basic_column_descriptor():basic_column_label(tstring(), -1, false, false){}
            template <typename Control>
            bool render_element(size_t row, size_t col, Control &c, const value_type &v) const { return false; }

            bool render_element(tstring &c, const value_type &v) const
            {
				if (m_text_renderer)
	                m_text_renderer(v, c);
                return true;
            }
			bool render_element_image(int &i, const value_type &v) const
			{
				if (m_image_index_renderer)
					m_image_index_renderer(v, i);
				else
					i=-1;
				return true;
			}

            //tstring value_as_text(const typename text_renderer_type::value_type &t) const;// { return m_text_renderer(t); }
			bool compare(const value_type &left, const value_type &right, size_t col) const
			{
				if (m_comparator)
					return m_comparator(left, right);
				if (m_image_index_renderer) {
					int l, r;
					m_image_index_renderer(left, l);
					m_image_index_renderer(right, r);
					return l<r;
				}
				tstring left_string, right_string;
				render_element(left_string, left);
				render_element(right_string, right);
				return left_string<right_string;
			}
            template <typename Archive>
            void serialize(Archive &ar, const unsigned int version)
            {
				ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(basic_column_label);
            }
		};

		template <typename Value>
		basic_column_descriptor<Value> image_column(const tstring &title, int width, const typename basic_column_descriptor<Value>::image_index_renderer_type &i)
		{
			return basic_column_descriptor<Value>(title, width, i);
		}

#pragma region TextRenderer
        template <typename Value>
        inline void to_string(Value v, tstring &c)
        {
            //c=boost::lexical_cast<tstring>(v);
            c=litwindow::make_const_accessor(v).to_string();
        }
        template <typename ValueType, typename MemberType>
        inline const MemberType &to_member(const ValueType &v, MemberType (ValueType::*ptr_to_member))
        {
            return v.*ptr_to_member;
        }
        template <typename MemberType, typename ValueType>
        inline typename basic_column_descriptor<ValueType>::text_renderer_type make_text_renderer(MemberType (ValueType::*ptr_to_member))
        {
            return boost::bind(&to_string<MemberType>,
                boost::bind(&to_member<ValueType, MemberType>, _1, ptr_to_member),
                _2);
        }
		template <typename MemberType, typename ValueType, typename Formatter>
		inline typename basic_column_descriptor<ValueType>::text_renderer_type make_text_renderer(MemberType (ValueType::*ptr_to_member), Formatter fmt)
		{
			using boost::bind;
			return bind(&to_string<typename Formatter::result_type>,
					bind(fmt, bind(&to_member<ValueType, MemberType>, _1, ptr_to_member) ),
				_2);
		}
		template <typename Result, typename MemberClass>
		inline void member_result_to_string(Result (MemberClass::*ptr_to_member)() const, const MemberClass &p, tstring &c)
		{
			to_string((p.*ptr_to_member)(), c);
		}
        template <typename MemberType, typename ValueType>
        inline typename basic_column_descriptor<ValueType>::text_renderer_type make_text_renderer(MemberType (ValueType::*ptr_to_member)() const)
        {
			using namespace boost;
			function<void (ValueType, tstring &c)> render(bind(&member_result_to_string<MemberType, ValueType>, ptr_to_member, _1, _2));
			return render;
        }

		template <typename MemberType, typename ValueType>
		inline bool comparator(const ValueType &left, const ValueType &right, MemberType (ValueType::*ptr_to_member))
		{
			return (left.*ptr_to_member)<(right.*ptr_to_member);
		}
		template <typename MemberType, typename ValueType>
		inline bool compare_memfnc(const ValueType &left, const ValueType &right, MemberType (ValueType::*ptr_to_member)() const)
		{
			return (left.*ptr_to_member)()<(right.*ptr_to_member)();
		}
#ifdef not
		template <typename MemberType, typename ValueType>
		inline basic_column_descriptor<ValueType> make_column_descriptor(const wstring &title, int width, MemberType (ValueType::*ptr_to_member))
		{
			basic_column_descriptor<ValueType> rc(title, width, make_text_renderer(ptr_to_member));
			//function<const MemberType&(const ValueType &, MemberType (ValueType::*))> left, right;
			//left=bind(&to_member<ValueType, MemberType>, _1, ptr_to_member);
			//right=bind(&to_member<ValueType, MemberType>, _1, ptr_to_member);
			rc.m_comparator=boost::bind(&comparator<MemberType, ValueType>, _1, _2, ptr_to_member);
				//bind(std::less<MemberType>(), bind(&to_member<ValueType, MemberType>, _1, ptr_to_member), bind(to_member<ValueType, MemberType>,_2, ptr_to_member));
			return rc;
		}
#endif // _DEBUG
#ifdef not
		template <typename MemberFnc, typename ValueType>
		inline basic_column_descriptor<ValueType> make_column_descriptor(const wstring &title, int width, MemberFnc (ValueType::*ptr_to_member)() const)
		{
			basic_column_descriptor<ValueType> rc(title, width, make_text_renderer(ptr_to_member));
			function<MemberFnc (const ValueType &)> left, right;
			left=bind(ptr_to_member, _1);
			right=bind(ptr_to_member, _1);
			rc.m_comparator=boost::bind(&compare_memfnc<MemberFnc, ValueType>, _1, _2, ptr_to_member);
			//rc.m_comparator=boost::bind(&comparator<MemberFnc, ValueType>, _1, _2, ptr_to_member);
			//rc.m_comparator=boost::bind(std::less<MemberFnc>, left, right);
			return rc;
		}
#endif // not
		template <typename GetterFnc, typename ValueType, typename Formatter>
		inline basic_column_descriptor<ValueType> make_column_descriptor_with_fmt(const wstring &title, int width, const boost::function<GetterFnc(const ValueType &)> &ptr, Formatter fmt)
		{
			using boost::bind;
			basic_column_descriptor<ValueType> rc(title, width, bind(fmt, bind(ptr, _1), _2));
			rc.m_comparator=bind(less<GetterFnc>(), bind(ptr, _1), bind(ptr, _2));
			return rc;
		}

#pragma endregion TextRenderer

		template <typename Accessor, typename RowValue, typename Enabled=void>
		struct column_accessor
		{
			//typedef Accessor accessor_type;
			//typedef typename accessor_type::result_type column_value_type;
		};
		template <typename ColValue, typename RowValue>
		struct column_accessor<ColValue (RowValue::*), RowValue>
		{
			typedef ColValue column_value_type;
			typedef RowValue row_value_type;
			typedef void (formatter_type)(column_value_type, wstring &);
		};
		template <typename ColValue, typename RowValue>
		struct column_accessor<ColValue (RowValue::*)()const, RowValue>
		{
			typedef ColValue column_value_type;
			typedef RowValue row_value_type;
			typedef void (formatter_type)(column_value_type, wstring &);
		};
		template <typename ColValue, typename RowValue>
		struct column_accessor<ColValue (*)(const RowValue&), RowValue>
		{
			typedef ColValue column_value_type;
			typedef RowValue row_value_type;
			typedef void (formatter_type)(const column_value_type&, wstring &);
		};
		template <typename ColumnAccessor, typename RowValue>
		struct column_accessor<ColumnAccessor, RowValue, typename boost::disable_if<boost::is_void<typename ColumnAccessor::result_type> >::type >
		{
			//typedef typename boost::remove_const<typename boost::remove_reference<typename ColumnAccessor::result_type>::type>::type column_value_type;
			typedef typename ColumnAccessor::result_type column_value_type;
			typedef RowValue row_value_type;
			typedef void (formatter_type)(const column_value_type&, wstring &);
		};

		template <typename RowValue, typename ColumnAccessor>
		basic_column_descriptor<RowValue> make_basic_column_descriptor(const wstring &title, int width, const ColumnAccessor &a, typename column_accessor<ColumnAccessor, RowValue>::formatter_type f=0)
		{
			typedef typename column_accessor<ColumnAccessor, RowValue>::column_value_type column_value_type;
			//typedef BOOST_TYPEOF(boost::bind(a, _1)(*(const RowValue*)0)) column_value_type;
			basic_column_descriptor<RowValue> rc(title, width);
			if (f==0)
				rc.m_text_renderer=boost::bind(&to_string<column_value_type>, boost::bind(a, _1), _2);
			else
				rc.m_text_renderer=boost::bind(f, boost::bind(a, _1), _2);
			rc.m_comparator=boost::bind(a, _1) < boost::bind(a, _2);
			return rc;
		}

		template <typename RowValue>
		basic_column_descriptor<RowValue> make_basic_column_descriptor(const wstring &title, int width, boost::function<void(const RowValue&, wstring &)> fncObject)
		{
			//typedef BOOST_TYPEOF(boost::bind(a, _1)(*(const RowValue*)0)) column_value_type;
			basic_column_descriptor<RowValue> rc(title, width);
			rc.m_text_renderer=boost::bind(fncObject, _1, _2);
			return rc;
		}

		template <typename RowValue, typename R>
		basic_column_descriptor<RowValue> make_basic_column_descriptor(const wstring &title, int width, R (RowValue::*r), typename column_accessor<R (RowValue::*), RowValue>::formatter_type f)
		{
			basic_column_descriptor<RowValue> rc(title, width);
			typedef typename boost::remove_reference<R>::type column_value_type;
			if (f==0)
				rc.m_text_renderer=boost::bind(&to_string<column_value_type>, boost::bind(r, _1), _2);
			else
				rc.m_text_renderer=boost::bind(f, boost::bind(r, _1), _2);
			rc.m_comparator=boost::bind(r, _1) < boost::bind(r, _2);
			return rc;
		}

		template <typename RowValue, typename R>
		basic_column_descriptor<RowValue> make_basic_column_descriptor(const wstring &title, int width, R (RowValue::*r)() const, typename column_accessor<R (RowValue::*)(), RowValue>::formatter_type f)
		{
			basic_column_descriptor<RowValue> rc(title, width);
			typedef typename boost::remove_reference<R>::type column_value_type;
			if (f==0)
				rc.m_text_renderer=boost::bind(&to_string<column_value_type>, boost::bind(r, _1), _2);
			else
				rc.m_text_renderer=boost::bind(f, boost::bind(r, _1), _2);
				rc.m_text_renderer=boost::bind(&to_string<column_value_type>, boost::bind(r, _1), _2);
			rc.m_comparator=boost::bind(r, _1) < boost::bind(r, _2);
			return rc;
		}

		//template <typename RowValue, typename TextRenderer>
		//basic_column_descriptor<RowValue> make_basic_column_descriptor(const wstring &title, int width, void (TextRenderer fncObject)(const RowValue&, wstring &))
		//{
		//	//typedef BOOST_TYPEOF(boost::bind(a, _1)(*(const RowValue*)0)) column_value_type;
		//	basic_column_descriptor<RowValue> rc(title, width);
		//	rc.m_text_renderer=boost::bind(fncObject, _1, _2);
		//	return rc;
		//}

		template <typename ColumnDescriptor>
        class basic_columns_adapter
        {
        public:
            typedef ColumnDescriptor column_descriptor_type;
            typedef typename column_descriptor_type::value_type value_type;
            typedef typename column_descriptor_type::text_renderer_type text_renderer_type;
			typedef typename column_descriptor_type::image_index_renderer_type image_index_renderer_type;

            typedef std::vector<column_descriptor_type> columns_t;
            const columns_t &columns() const { return m_column_data; }
			columns_t &columns() { return m_column_data; }
            std::back_insert_iterator<columns_t> do_add(const column_descriptor_type &d)
            {
                set_dirty();
                m_column_data.push_back(d);
                return std::back_inserter<columns_t>(m_column_data);
            }
			struct default_formatter
			{
			};
            struct back_inserter
            {
			private:
                basic_columns_adapter *m_c;
				void set_this(basic_columns_adapter *c) { m_c=c; }
				friend class basic_columns_adapter;
			public:
				back_inserter add(const column_descriptor_type &d) const
				{
					m_c->do_add(d);
					return *this;
				}
				template <typename ColDescrType>
                back_inserter operator()(const ColDescrType &d) const
				{
                    return add(d);
                }

				back_inserter operator()(const wstring &title, int width, void (fnc)(const value_type&, wstring&)) const
				{
					return operator()(column_descriptor_type(title, width, text_renderer_type(fnc)));
				}
				//back_inserter operator()(const tstring &title, int width, const text_renderer_type &a) const
				//{
				//	return operator()(column_descriptor_type(title, width, a));
				//}
				template <typename ValueMember>
				back_inserter operator()(const tstring &title, int width, ValueMember (*free_function)(const value_type &), typename column_accessor<ValueMember (*)(const value_type &), value_type>::formatter_type f=0) const
				{
					return add(make_basic_column_descriptor<value_type>(title, width, free_function, f));
				}
				template <typename ValueMember>
				back_inserter operator()(const tstring &title, int width, ValueMember (value_type::*ptr_to_member), typename column_accessor<ValueMember (value_type::*), value_type>::formatter_type f=0) const
				{
					return add(make_basic_column_descriptor(title, width, ptr_to_member, f));
				}
				template <typename ValueMember>
				back_inserter operator()(const tstring &title, int width, ValueMember (value_type::*ptr_mem_fnc)() const, typename column_accessor<ValueMember (value_type::*)() const, value_type>::formatter_type f=0) const
				{
					return add(make_basic_column_descriptor<value_type>(title, width, ptr_mem_fnc, f));
				}
				template <typename T1>
				back_inserter operator()(const tstring &title, int width, const T1 &v, typename column_accessor<T1, value_type>::formatter_type f=0, typename boost::disable_if<boost::is_void<typename T1::result_type> >::type *dmy=0) const
				{
					return add(make_basic_column_descriptor<value_type>(title, width, v, f));
				}
				template <typename TextRenderer>
				back_inserter operator()(const wstring &title, int width, TextRenderer t, typename boost::enable_if<boost::is_void<typename TextRenderer::result_type> >::type* dmy=0) const
				{
					return add(column_descriptor_type(title, width, text_renderer_type(t)));
				}
            };
			back_inserter add;
			//template <typename T1, typename T2> back_inserter add(const tstring &title, int width, const T1 &t1, const T2 &t2) { return back_inserter(*this)(title, width, t1, t2); }
			//template <typename T1> back_inserter add(const tstring &title, int width, const T1 &t1) { return back_inserter(*this)(title, width, t1); }
			//template <typename T1> back_inserter add(const tstring &title, int width, T1 (value_type::*t1)) { return back_inserter(*this)(title, width, t1); }
			//back_inserter add(const column_descriptor_type &d) { return back_inserter(*this)(d); }
            size_t size() const { return columns().size(); }
			bool empty() const { return columns().empty(); }
            bool dirty() const { return m_dirty; }
			void dirty(bool is_dirty) { m_dirty=is_dirty; }
			void clear() { m_column_data.clear(); dirty(true); }
            basic_columns_adapter()
                :m_dirty(true){ add.set_this(this); }
            const column_descriptor_type &column_descriptor(size_t idx) const { return columns().at(idx); }
			column_descriptor_type &column_descriptor(size_t idx) { return columns().at(idx); }

			size_t get_column_index(const wstring &title) const
			{
				columns_t::const_iterator i=find_if(columns().begin(), columns().end(), boost::bind(&columns_t::value_type::title, _1)==title);
				if (i==columns().end())
					throw runtime_error("get_column_index: no such column");
				return i-columns().begin();
			}

            template <typename Control>
            bool render_element_at(size_t row, size_t col, Control &c, const value_type &v) const
            {
                return columns().at(col).render_element(row, col, c, v);
            }
            bool render_element_at(size_t col, tstring &rc, const value_type &v) const
            {
                return columns().at(col).render_element(rc, v);
            }
			bool render_element_image_at(size_t col, int &rc, const value_type &v) const
			{
				return columns().at(col).render_element_image(rc, v);
			}
			bool render_element_at(const wstring &column, tstring &rc, const value_type &v) const
			{
				return render_element_at(get_column_index(column), rc, v);
			}
            typename columns_t::value_type &at(size_t col) { return columns().at(col); }
			typename const columns_t::value_type &at(size_t col) const { return columns().at(col); }
            //const value_type &column_description(size_t idx) const { return columns().at(idx); }

            //const element_value_type &get(const value_type &e, const column_position_type &pos) const
            //{
            //    return m_element_adapter(e, pos);
            //}
			void set_dirty() { dirty(true); }
			void clear_dirty() { dirty(false); }
			void toggle_show(size_t col)
			{
				columns().at(col).visible(!columns().at(col).visible());
				dirty(true);
			}

			bool compare(size_t col, const typename column_descriptor_type::value_type &left, const typename column_descriptor_type::value_type &right) const
			{
				return at(col).compare(left, right, col);
			}

            template <typename Archive>
            void serialize(Archive &ar, const unsigned int version)
            {
				if (Archive::is_loading()) {
					columns_t temp;
					ar & boost::serialization::make_nvp("m_column_data", temp);
					merge_in(temp);
				} else {
					ar & boost::serialization::make_nvp("m_column_data", m_column_data);
				}
            }
		protected:
        private:
            bool m_dirty;
            columns_t m_column_data;

			void merge_in(const columns_t &in)
			{
				struct merge_element
				{
					static void do_merge(columns_t &dest, const columns_t::value_type &src)
					{
						columns_t::iterator i;
						i=std::find_if(dest.begin(), dest.end(), boost::bind(&columns_t::value_type::title, _1) == src.title());
						if (i!=dest.end()) {
							columns_t::value_type &current(*i);
							current.width(src.width());
							current.visible(src.visible());
							current.position(src.position());
						}
					}
				};
				for_each(in.begin(), in.end(), boost::bind(&merge_element::do_merge, boost::ref(m_column_data), _1));
				m_dirty=true;
			}
            //element_adapter m_element_adapter;
        };

    }
}

namespace litwindow {
    namespace ui {

        template <typename DatasetAdapter>
        class basic_dataset_accessor
        {
        public:
            typedef DatasetAdapter value_type;
            typedef typename DatasetAdapter::value_type element_type;

            void sort();
            void filter();
            size_t size() const;
        };

        template <typename ContainerType, typename ItemHandle=typename ContainerType::iterator>
        class stl_container_dataset_accessor
        {
        public:
            typedef stl_container_dataset_accessor _Myt;
            typedef ContainerType container_type;
            typedef typename ContainerType::value_type value_type;
            typedef ItemHandle item_handle_type;
            typedef std::vector<item_handle_type> sorted_container_type;
            typedef boost::function<bool(const item_handle_type &left, const item_handle_type &right)> sort_pred_type;
            typedef boost::function<bool(const item_handle_type &f)> filter_pred_type;
        private:
            container_type *m_c;
            sorted_container_type m_item_handles;
            //columns_adapter_type m_columns_adapter;
            sort_pred_type m_sort_pred;
            filter_pred_type m_filter_pred;
            bool m_needs_update;

            container_type &container() const { return *m_c; }
        public:
            //const columns_adapter_type &columns_adapter() const { return m_columns_adapter; }
            //columns_adapter_type &columns_adapter() { return m_columns_adapter; }
            _Myt &set_container(container_type &v)
            {
                m_c=&v;
                m_needs_update=true;
                return *this;
            }
            //_Myt &set_columns_adapter(const columns_adapter_type &cadapter)
            //{
            //    m_columns_adapter=cadapter;
            //    return *this;
            //}
            size_t size() const { return m_item_handles.size(); }
            void sort()
            {
                sorted_container_type::iterator dest=m_item_handles.begin();
                container_type::iterator i=container().begin();
                while (dest!=m_item_handles.end() && i!=container().end()) {
                    if (!m_filter_pred || m_filter_pred(i))
                        *dest++=i;
                    ++i;
                }
                if (dest<m_item_handles.end())
                    m_item_handles.erase(dest, m_item_handles.end());
                else while (i!=container().end()) {
                    if (!m_filter_pred || m_filter_pred(i))
                        m_item_handles.push_back(i);
                    ++i;
                }
                if (m_sort_pred)
                    std::sort(m_item_handles.begin(), m_item_handles.end(), m_sort_pred);
            }
			void set_dirty() { m_needs_update=true; }
            void force_update() { m_needs_update=true; update(); }
            void update() { if (m_needs_update) sort(); m_needs_update=false; }
            void refresh(bool force=false) { if (force) force_update(); else update(); }
            const value_type &value_at(size_t pos) const
			{
				//TODO: this needs a mechanism to return 'no-item' to signal the caller
				// that the container has changed and no longer has 'pos' items
				return *m_item_handles.at(pos);
			}
            void modify_value_at(size_t pos, const value_type &new_value)
            {
                *m_item_handles.at(pos)=new_value;
                m_needs_update=true;
            }
            void delete_value_at(size_t pos)
            {
                (*m_c).erase(m_item_handles.at(pos));
                m_needs_update=true;
            }
            void clear()
            {
                (*m_c).clear();
                m_needs_update=true;
            }
            void append(const value_type &new_value)
            {
                std::back_inserter(*m_c)=new_value;
                m_needs_update=true;
            }
        };

        template <typename ContainerType>
        inline stl_container_dataset_accessor<ContainerType> make_dataset_adapter(ContainerType &d)
        {
            stl_container_dataset_accessor<ContainerType> rc;
            rc.set_container(d);
            return rc;
        }

        template <typename ColumnTraits, typename UIControl, typename Columns>
        void setup_columns(ColumnTraits tr, UIControl c, Columns &cols)
        {
            size_t idx=0;
            while (idx<cols.size()) {
                if (idx>=tr.count(c))
                    tr.insert_column(c, idx, cols.column_descriptor(idx));
                else
                    tr.set_column(c, idx, cols.column_descriptor(idx));
                ++idx;
            }
            while (tr.count(c)>cols.size())
                tr.remove_column(c, tr.count(c)-1);
        }

        class basic_ui_control_adapter
        {
        public:
            void begin_update() {}
            void end_update() {}
            template <typename Mediator>
            void connect_mediator(const Mediator &m) {}
            static const size_t npos=(size_t)-1;
            size_t get_selected_index() const { return npos; }
        };

//////////////////////////////////////////////////////////////////////////

        /*! A basic_list_mediator encapsules all interactions between a tabular UI control
        * and a dataset. The DatasetAdapter connects the mediator with a dataset
        * structure such as a vector, odbc statement or others. The UIControlAdapter
        * connects the mediator with a UI control such as a list, combobox, listctrl,
        * grid or others.
        */
		template <typename DatasetAdapter, typename UIControlAdapter, typename ColumnsAdapter=typename DatasetAdapter::columns_adapter_type>
        class basic_list_mediator
        {
        public:
            /// refresh the ui control
            /// call this after the dataset has changed
            void refresh();

			typedef basic_list_mediator _Myt;
            typedef UIControlAdapter ui_control_adapter_type;
            typedef DatasetAdapter dataset_adapter_type;
            typedef ColumnsAdapter columns_adapter_type;
            typedef typename dataset_adapter_type::value_type value_type;

            //void set_columns_adapter(const columns_adapter_type &cols) { m_columns=cols; m_needs_refresh_columns=true; }
            columns_adapter_type &columns_adapter()
			{
				return m_columns_adapter;
				//return m_dataset_adapter.columns_adapter();
			}
            const columns_adapter_type &columns_adapter() const { return m_columns_adapter; }

			columns_adapter_type &columns() { return columns_adapter(); }
			const columns_adapter_type &columns() const { return columns_adapter(); }
            _Myt &set_columns_adapter(const columns_adapter_type &cadapter)
            {
                m_columns_adapter=cadapter;
                return *this;
            }

            template <typename Data, typename Columns>
            void set_dataset(Data &d, const Columns &c)
            {
                set_dataset_adapter(make_dataset_adapter(d));
				set_columns_adapter(c);
            }
            template <typename List>
            void set_ui(List &l)
            {
                set_ui_adapter(make_list_adapter(l));
            }
            void set_ui_adapter(const ui_control_adapter_type &a)
            {
                m_ui_control_adapter=a;
                m_ui_control_adapter.connect_mediator(*this);
            }

            void set_dataset_adapter(const dataset_adapter_type &d) { m_dataset_adapter=d; }
            const dataset_adapter_type &dataset_adapter() const { return m_dataset_adapter; }
            dataset_adapter_type &dataset_adapter() { return m_dataset_adapter; }
            const ui_control_adapter_type &ui_adapter() const { return m_ui_control_adapter; }
            ui_control_adapter_type &ui_adapter() { return m_ui_control_adapter; }

            basic_list_mediator()
                :m_needs_refresh_columns(true){}

            void get_item_text(size_t row, size_t col, tstring &rc) const
            {
                const columns_adapter_type &ca(columns_adapter());
                ca.render_element_at(col, rc, dataset_adapter().value_at(row));
            }

            void refresh_dataset()
            {
                m_dataset_adapter.refresh(true);
            }

            const value_type &get_selected_item() const
            {
                return dataset_adapter().value_at(ui_adapter().get_selected_index());
            }
            void modify_selected_item(const value_type &data)
            {
                dataset_adapter().modify_value_at(ui_adapter().get_selected_index(), data);
            }
            void delete_selected_item()
            {
                dataset_adapter().delete_value_at(ui_adapter().get_selected_index());
            }
            void delete_all_items()
            {
                dataset_adapter().clear();
            }
            void append_item(const value_type &data)
            {
                dataset_adapter().append(data);
            }

#ifdef not
			template <typename Fnc>
			void visit(size_t idx, Fnc f)
			{
				f(dataset_adapter().value_at(idx), idx);
			}
			template <typename Fnc>
			void for_each_selected(Fnc f)
			{
				ui_adapter().for_each_selected(bind(&basic_list_mediator::visit, this, _1, f));
			}
#endif // not
			template <typename ResultSet, typename Fnc>
			void visit(ResultSet* rc, size_t idx, Fnc f)
			{
				rc->push_back(f(dataset_adapter().value_at(idx), idx));
			}
			template <typename Fnc>
			std::vector<typename boost::function_traits<Fnc>::result_type> get_selection(Fnc f)
			{
				std::vector<typename boost::function_traits<Fnc>::result_type> rc;
				ui_adapter().for_each_selected(bind(&basic_list_mediator::visit, this, &rc, _1, f));
				return rc;
			}
			void show_hide_column(int col, bool show_hide);
			void toggle_show_column(int col);

        protected:
            void refresh_columns(bool do_refresh=true);
            void refresh_list();

            void begin_update() { m_ui_control_adapter.begin_update(); }
            void end_update() { m_ui_control_adapter.end_update(); }

            void setup_columns();

            ui_control_adapter_type m_ui_control_adapter;
            columns_adapter_type    m_columns_adapter;
            dataset_adapter_type   m_dataset_adapter;
            bool            m_needs_refresh_columns;
        };

		//------------------------------------------------------------------------------------------------------------------------------------
		//////////////////////////////////////////////////////////////////////////
        template <typename DatasetAdapter, typename UIControlAdapter, typename ColumnsAdapter>
        void litwindow::ui::basic_list_mediator<DatasetAdapter, UIControlAdapter, typename ColumnsAdapter>::refresh()
        {
            begin_update();
            refresh_dataset();
            refresh_columns(m_needs_refresh_columns);
            refresh_list();
            end_update();
        }

        template <typename DatasetAdapter, typename UIControlAdapter, typename ColumnsAdapter>
        void litwindow::ui::basic_list_mediator<DatasetAdapter, UIControlAdapter, typename ColumnsAdapter>::refresh_columns(bool do_refresh)
        {
            if (do_refresh || columns_adapter().dirty()) {
                begin_update();
                setup_columns();
                end_update();
                m_needs_refresh_columns=false;
            }
        }

		template <typename DatasetAdapter, typename UIControlAdapter, typename ColumnsAdapter>
		void litwindow::ui::basic_list_mediator<DatasetAdapter, UIControlAdapter, ColumnsAdapter>::toggle_show_column(int col)
		{
			columns_adapter().toggle_show(col);
			refresh_columns(true);
		}

        template <typename DatasetAdapter, typename UIControlAdapter, typename ColumnsAdapter>
        void litwindow::ui::basic_list_mediator<DatasetAdapter, UIControlAdapter, typename ColumnsAdapter>::refresh_list()
        {
            m_ui_control_adapter.refresh_list(m_dataset_adapter, m_columns_adapter);
        }

        template <typename DatasetAdapter, typename UIControlAdapter, typename ColumnsAdapter>
        void litwindow::ui::basic_list_mediator<DatasetAdapter, UIControlAdapter, typename ColumnsAdapter>::setup_columns()
        {
            m_ui_control_adapter.setup_columns(columns_adapter());
			columns_adapter().clear_dirty();
        }

    }
}

BOOST_CLASS_VERSION(litwindow::ui::basic_column_label, 1);

#pragma optimize("", on)
#endif // list_mediator_h__31080910

max_stars_repo_name: hajokirchhoff/litwindow

max_issues_repo_name: hajokirchhoff/litwindow

max_forks_repo_name: hajokirchhoff/litwindow


text:
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:

// Copyright (c) 2007 Aristid Breitkreuz, Ruediger Sonderfeld, Christian Uhrhan
//
// Distributed under the Boost Software License, Version 1.0 and under the MIT
// License.
//
// See accompanying LICENSES.txt or
// <http://fragments.sourceforge.net/LICENSES.txt> or, for the Boost Software
// License, <http://www.boost.org/LICENSE_1_0.txt>.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

#include <fragments/detail/apply_default_fragments.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/map.hpp>
#include <boost/mpl/pair.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/at.hpp>
#include <boost/type_traits.hpp>
#include <boost/static_assert.hpp>

using namespace boost;

struct container {};

struct vector {
  typedef mpl::vector1<container> concept;
};

struct list {
  typedef mpl::vector1<container> concept;
};

struct stack {
  typedef mpl::vector0<> concept;
  typedef mpl::vector1<container> require_before;
  typedef mpl::map1<
      mpl::pair<
        container,
        vector
      >
    > default_fragment;
};

int main() {
  {
    typedef mpl::vector1<stack> seq;
    typedef fragments::detail::apply_default_fragments<seq>::type res;
    BOOST_STATIC_ASSERT((mpl::size<res>::value == 2));
    BOOST_STATIC_ASSERT((is_same<mpl::at_c<res, 0>::type, stack>::value));
    BOOST_STATIC_ASSERT((is_same<mpl::at_c<res, 1>::type, vector>::value));
  }
  {
    typedef mpl::vector2<stack, list> seq;
    typedef fragments::detail::apply_default_fragments<seq>::type res;
    BOOST_STATIC_ASSERT((mpl::size<res>::value == 2));
    BOOST_STATIC_ASSERT((is_same<mpl::at_c<res, 0>::type, stack>::value));
    BOOST_STATIC_ASSERT((is_same<mpl::at_c<res, 1>::type, list>::value));
  }
  {
    typedef mpl::vector2<list, stack> seq;
    typedef fragments::detail::apply_default_fragments<seq>::type res;
    BOOST_STATIC_ASSERT((mpl::size<res>::value == 2));
    BOOST_STATIC_ASSERT((is_same<mpl::at_c<res, 0>::type, list>::value));
    BOOST_STATIC_ASSERT((is_same<mpl::at_c<res, 1>::type, stack>::value));
  }
  {
    typedef mpl::vector2<stack, vector> seq;
    typedef fragments::detail::apply_default_fragments<seq>::type res;
    BOOST_STATIC_ASSERT((mpl::size<res>::value == 2));
    BOOST_STATIC_ASSERT((is_same<mpl::at_c<res, 0>::type, stack>::value));
    BOOST_STATIC_ASSERT((is_same<mpl::at_c<res, 1>::type, vector>::value));
  }
}

ext: cpp

max_stars_repo_name: aristidb/fragments

max_issues_repo_name: aristidb/fragments

max_forks_repo_name: aristidb/fragments


text:
//  Boost static_min_max.hpp test program  -----------------------------------//

//  (C) Copyright Daryle Walker 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 for most recent version including documentation.

//  Revision History
//  23 Sep 2001  Initial version (Daryle Walker)

#define  BOOST_INCLUDE_MAIN
#include <boost/test/test_tools.hpp>  // for main, BOOST_CHECK

#include <boost/cstdlib.hpp>                 // for boost::exit_success
#include <boost/integer/static_min_max.hpp>  // for boost::static_signed_min, etc.

#include <iostream>  // for std::cout (std::endl indirectly)

// Main testing function
int
test_main
(
    int         ,   // "argc" is unused
    char *      []  // "argv" is unused
)
{
    using std::cout;
    using std::endl;
    using boost::static_signed_min;
    using boost::static_signed_max;
    using boost::static_unsigned_min;
    using boost::static_unsigned_max;

    // Two positives
    cout << "Doing tests with two positive values." << endl;

    BOOST_CHECK( (static_signed_min< 9, 14>::value) ==  9 );
    BOOST_CHECK( (static_signed_max< 9, 14>::value) == 14 );
    BOOST_CHECK( (static_signed_min<14,  9>::value) ==  9 );
    BOOST_CHECK( (static_signed_max<14,  9>::value) == 14 );

    BOOST_CHECK( (static_unsigned_min< 9, 14>::value) ==  9 );
    BOOST_CHECK( (static_unsigned_max< 9, 14>::value) == 14 );
    BOOST_CHECK( (static_unsigned_min<14,  9>::value) ==  9 );
    BOOST_CHECK( (static_unsigned_max<14,  9>::value) == 14 );

    // Two negatives
    cout << "Doing tests with two negative values." << endl;

    BOOST_CHECK( (static_signed_min<  -8, -101>::value) == -101 );
    BOOST_CHECK( (static_signed_max<  -8, -101>::value) ==   -8 );
    BOOST_CHECK( (static_signed_min<-101,   -8>::value) == -101 );
    BOOST_CHECK( (static_signed_max<-101,   -8>::value) ==   -8 );

    // With zero
    cout << "Doing tests with zero and a positive or negative value." << endl;

    BOOST_CHECK( (static_signed_min< 0, 14>::value) ==  0 );
    BOOST_CHECK( (static_signed_max< 0, 14>::value) == 14 );
    BOOST_CHECK( (static_signed_min<14,  0>::value) ==  0 );
    BOOST_CHECK( (static_signed_max<14,  0>::value) == 14 );

    BOOST_CHECK( (static_unsigned_min< 0, 14>::value) ==  0 );
    BOOST_CHECK( (static_unsigned_max< 0, 14>::value) == 14 );
    BOOST_CHECK( (static_unsigned_min<14,  0>::value) ==  0 );
    BOOST_CHECK( (static_unsigned_max<14,  0>::value) == 14 );

    BOOST_CHECK( (static_signed_min<   0, -101>::value) == -101 );
    BOOST_CHECK( (static_signed_max<   0, -101>::value) ==    0 );
    BOOST_CHECK( (static_signed_min<-101,    0>::value) == -101 );
    BOOST_CHECK( (static_signed_max<-101,    0>::value) ==    0 );

    // With identical
    cout << "Doing tests with two identical values." << endl;

    BOOST_CHECK( (static_signed_min<0, 0>::value) == 0 );
    BOOST_CHECK( (static_signed_max<0, 0>::value) == 0 );
    BOOST_CHECK( (static_unsigned_min<0, 0>::value) == 0 );
    BOOST_CHECK( (static_unsigned_max<0, 0>::value) == 0 );

    BOOST_CHECK( (static_signed_min<14, 14>::value) == 14 );
    BOOST_CHECK( (static_signed_max<14, 14>::value) == 14 );
    BOOST_CHECK( (static_unsigned_min<14, 14>::value) == 14 );
    BOOST_CHECK( (static_unsigned_max<14, 14>::value) == 14 );

    BOOST_CHECK( (static_signed_min< -101, -101>::value) == -101 );
    BOOST_CHECK( (static_signed_max< -101, -101>::value) == -101 );

    return boost::exit_success;
}

max_issues_repo_name: boost-cmake/vintage

max_forks_repo_name: boost-cmake/vintage


text:
/*
 * (C) Copyright 2016 Kurento (http://kurento.org/)
 *
 * 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.
 *
 */

#define BOOST_TEST_STATIC_LINK
#define BOOST_TEST_PROTECTED_VIRTUAL

#include <boost/test/included/unit_test.hpp>
#include <MediaPipelineImpl.hpp>
#include <objects/FacadeRtpEndpointImpl.hpp>
//#include <IceCandidate.hpp>
#include <mutex>
#include <condition_variable>
#include <ModuleManager.hpp>
#include <KurentoException.hpp>
#include <MediaSet.hpp>
#include <MediaElementImpl.hpp>
#include <ConnectionState.hpp>
#include <MediaState.hpp>
#include "SDES.hpp"
#include "CryptoSuite.hpp"
#include <chrono>

#include <sigc++/connection.h>

#include <RegisterParent.hpp>

using namespace kurento;
using namespace boost::unit_test;
using namespace std::chrono_literals;

boost::property_tree::ptree config;
std::string mediaPipelineId;
ModuleManager moduleManager;

std::string sdpOffer1 = "v=0\n"
"o=Test 4518353 4518353 IN IP4 127.0.0.1\n"
"s=TEST\n"
"t=0 0\n"
"m=audio 0 RTP/SAVP 0\n"
"c=IN IP4 127.0.0.1\n"
"a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:YzM2ZmU2MTEzNjM2N2FiZDZhZWU3MTZhNTg2NDgz\n"
"a=inactive\n"
"m=video 0 RTP/SAVP 98\n"
"c=IN IP4 127.0.0.1\n"
"a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:YzBlNGQ4ZjBmMWZkY2RhNzg2NGI0NTcwNDQyYWQ0\n"
"a=inactive\n"
"m=audio 60684 RTP/AVP 8 0 96\n"
"c=IN IP4 127.0.0.1\n"
"a=rtpmap:8 PCMA/8000\n"
"a=rtpmap:0 PCMU/8000\n"
"a=rtpmap:96 opus/48000/2\n"
"a=rtcp:60685\n"
"a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n"
"a=setup:actpass\n"
"a=mid:audio0\n"
"a=ptime:20\n"
"a=sendrecv\n"
"a=ssrc:3101238828 cname:user4234385188@host-496f29bd\n"
"m=video 0 RTP/AVP 98\n"
"c=IN IP4 127.0.0.1\n"
"a=inactive\n";

struct GF {
  GF();
  ~GF();
};

BOOST_GLOBAL_FIXTURE (GF);

GF::GF()
{
  boost::property_tree::ptree ac, audioCodecs, vc, videoCodecs;
  gst_init(nullptr, nullptr);

//  moduleManager.loadModulesFromDirectories ("./src/server:../../kms-omni-build:../../src/server:../../../../kms-omni-build");
  moduleManager.loadModulesFromDirectories ("../../src/server:./");

  config.add ("configPath", "../../../tests" );
  config.add ("modules.kurento.SdpEndpoint.numAudioMedias", 1);
  config.add ("modules.kurento.SdpEndpoint.numVideoMedias", 1);

  ac.put ("name", "opus/48000/2");
  audioCodecs.push_back (std::make_pair ("", ac) );
  config.add_child ("modules.kurento.SdpEndpoint.audioCodecs", audioCodecs);

  vc.put ("name", "VP8/90000");
  videoCodecs.push_back (std::make_pair ("", vc) );
  config.add_child ("modules.kurento.SdpEndpoint.videoCodecs", videoCodecs);

  mediaPipelineId = moduleManager.getFactory ("MediaPipeline")->createObject (
                      config, "",
                      Json::Value() )->getId();
}

GF::~GF()
{
  MediaSet::deleteMediaSet();
}

class TestEventHandler: public kurento::EventHandler
{
private:
	std::condition_variable *testCV;
	std::string lastEvent;

public:
	TestEventHandler (std::condition_variable *cv, std::shared_ptr<MediaObjectImpl> object): kurento::EventHandler(object), testCV(cv)
	{ }

	virtual void sendEvent (Json::Value &value)
	{
        BOOST_TEST_MESSAGE ("EventHandledr: " + value.toStyledString());
        if (value["data"]["state"].asString().compare(std::string{"FLOWING"}) == 0) {
        lastEvent = value.toStyledString();
        if (testCV)
        	testCV->notify_one();
        }
	}

	std::string getLastEvent ()
	{
		return lastEvent;
	}
};

#define CRYPTOKEY "00108310518720928b30d38f411493"

//static std::shared_ptr<SDES> getCrypto ()
//{
//	std::shared_ptr<kurento::SDES> crypto = std::make_shared<kurento::SDES>(new kurento::SDES());
//	std::shared_ptr<kurento::CryptoSuite> cryptoSuite = std::make_shared<kurento::CryptoSuite> (new kurento::CryptoSuite (kurento::CryptoSuite::AES_128_CM_HMAC_SHA1_80));
//
//	crypto->setCrypto(cryptoSuite);
//	crypto->setKey(CRYPTOKEY);
//	return crypto;
//}

static std::shared_ptr <PassThroughImpl>
createPassThrough ()
{
  std::shared_ptr <kurento::MediaObjectImpl> pt;
  Json::Value constructorParams;

  constructorParams ["mediaPipeline"] = mediaPipelineId;

  pt = moduleManager.getFactory ("PassThrough")->createObject (
                  config, "",
                  constructorParams );

  return std::dynamic_pointer_cast <PassThroughImpl> (pt);
}

static void
releasePassThrough (std::shared_ptr<PassThroughImpl> &ep)
{
  std::string id = ep->getId();

  ep.reset();
  MediaSet::getMediaSet ()->release (id);
}

static std::shared_ptr<MediaElementImpl> createTestSrc() {
  std::shared_ptr <MediaElementImpl> src = std::dynamic_pointer_cast
      <MediaElementImpl> (MediaSet::getMediaSet()->ref (new  MediaElementImpl (
                            boost::property_tree::ptree(),
                            MediaSet::getMediaSet()->getMediaObject (mediaPipelineId),
                            "dummysrc") ) );

  g_object_set (src->getGstreamerElement(), "audio", TRUE, "video", TRUE, NULL);

  return std::dynamic_pointer_cast <MediaElementImpl> (src);
}

static void
releaseTestSrc (std::shared_ptr<MediaElementImpl> &ep)
{
  std::string id = ep->getId();

  ep.reset();
  MediaSet::getMediaSet ()->release (id);
}

static std::shared_ptr <MediaElementImpl>
createRtpEndpoint (bool useIpv6, bool useCrypto)
{
  std::shared_ptr <kurento::MediaObjectImpl> rtpEndpoint;
  Json::Value constructorParams;

  constructorParams ["mediaPipeline"] = mediaPipelineId;
  constructorParams ["useIpv6"] = useIpv6;
//  if (useCrypto) {
//	  constructorParams ["crypto"] = getCrypto ()->;
//  }

  rtpEndpoint = moduleManager.getFactory ("RtpEndpoint")->createObject (
                  config, "",
                  constructorParams );

  return std::dynamic_pointer_cast <MediaElementImpl> (rtpEndpoint);
}

static std::shared_ptr<SDES> getCrypto ()
{
	std::shared_ptr<SDES> crypto (new SDES());
	std::shared_ptr<CryptoSuite> cryptoSuite (new kurento::CryptoSuite (kurento::CryptoSuite::AES_128_CM_HMAC_SHA1_80));

	crypto->setCrypto(cryptoSuite);
	crypto->setKey(CRYPTOKEY);
	return crypto;
}

static Json::Value
createSdesJson (std::shared_ptr<SDES> sdes)
{
	Json::Value sdesParams;

	sdesParams ["key"] = sdes->getKey();
	sdesParams ["crypto"] = sdes->getCrypto()->getString();

	return sdesParams;
}

static std::shared_ptr <FacadeRtpEndpointImpl>
createSipRtpEndpoint (bool useIpv6, bool useCrypto)
{
  std::shared_ptr <kurento::MediaObjectImpl> rtpEndpoint;
  Json::Value constructorParams;

  constructorParams ["mediaPipeline"] = mediaPipelineId;
  constructorParams ["cryptoAgnostic"] = TRUE;
  if (useCrypto) {
	  constructorParams ["crypto"] = createSdesJson (getCrypto ());
  }
  constructorParams ["useIpv6"] = useIpv6;
//  if (useCrypto) {
//	  constructorParams ["crypto"] = getCrypto ()->;
//  }

  rtpEndpoint = moduleManager.getFactory ("SipRtpEndpoint")->createObject (
                  config, "",
                  constructorParams );

  return std::dynamic_pointer_cast <FacadeRtpEndpointImpl> (rtpEndpoint);
}

static void
releaseSipRtpEndpoint (std::shared_ptr<FacadeRtpEndpointImpl> &ep)
{
  ep->release();
//  std::string id = ep->getId();
//
//  ep.reset();
//  MediaSet::getMediaSet ()->release (id);
}

static void
releaseRtpEndpoint (std::shared_ptr<MediaElementImpl> &ep)
{
  ep->release();
//  std::string id = ep->getId();
//
//  ep.reset();
//  MediaSet::getMediaSet ()->release (id);
}

static void
source_connections_impl ()
{
  bool useIpv6 = FALSE;
  bool useCrypto = FALSE;
  std::shared_ptr <MediaElementImpl> rtpEp1 = createRtpEndpoint (useIpv6, useCrypto);
  std::shared_ptr <MediaElementImpl> rtpEp2 = createRtpEndpoint (useIpv6, useCrypto);
  std::shared_ptr <MediaElementImpl> rtpEp3 = createRtpEndpoint (useIpv6, useCrypto);
  std::shared_ptr <FacadeRtpEndpointImpl> sipRtp = createSipRtpEndpoint (useIpv6, useCrypto);

  sipRtp->connect (rtpEp1);
  sipRtp->connect (rtpEp3);
  sipRtp->connect (rtpEp3);

  rtpEp1->connect (sipRtp);
  rtpEp2->connect (sipRtp);
  rtpEp3->connect (sipRtp);

  releaseRtpEndpoint (rtpEp1);
  releaseRtpEndpoint (rtpEp2);
  releaseRtpEndpoint (rtpEp3);
  releaseSipRtpEndpoint (sipRtp);
}

static void
source_connections_regenerate_impl ()
{
  bool useIpv6 = FALSE;
  //bool useCrypto = TRUE;
  std::shared_ptr <PassThroughImpl> pt1 = createPassThrough ();
  std::shared_ptr <PassThroughImpl> pt2 = createPassThrough ();
  std::shared_ptr <PassThroughImpl> pt3 = createPassThrough ();
  std::shared_ptr <MediaElementImpl> src = createTestSrc();

  std::shared_ptr <FacadeRtpEndpointImpl> sipRtp = createSipRtpEndpoint (useIpv6, TRUE);
  std::shared_ptr <FacadeRtpEndpointImpl> sipRtp2 = createSipRtpEndpoint (useIpv6, FALSE);
  std::condition_variable cv;
  std::mutex mtx;
  std::unique_lock<std::mutex> lck (mtx);
  std::shared_ptr<TestEventHandler> testEH (new TestEventHandler (&cv,std::dynamic_pointer_cast <MediaObjectImpl> (pt3)));

  sipRtp2->connect(sipRtp2);
  sipRtp->connect (pt1);
  sipRtp->connect (pt2);
  sipRtp->connect (pt3);

  pt3->connect (std::string("MediaFlowInStateChange"), std::dynamic_pointer_cast <EventHandler>(testEH));

  pt1->connect (sipRtp);
  pt2->connect (sipRtp);
  src->connect (sipRtp);

  std::string offer = sipRtp2->generateOffer();
  std::string answer = sipRtp->processOffer(offer);
  sipRtp2->processAnswer(answer);

	  // First stream
	bool result = cv.wait_for (lck, 5000ms, [&] () {
	    return !(testEH->getLastEvent().empty());
	  });

	  if (!result) {
	    BOOST_ERROR ("Not media Flowing");
	  }

  releaseSipRtpEndpoint (sipRtp);
  releasePassThrough(pt1);
  releasePassThrough(pt2);
  releasePassThrough(pt3);
  releaseTestSrc (src);
}

static void
source_connections()
{
	  BOOST_TEST_MESSAGE ("Start test: test source connections on several sources");
	  source_connections_impl ();
}

static void
source_connections_regenerate()
{
	  BOOST_TEST_MESSAGE ("Start test: test source connections on several sources");
	  source_connections_regenerate_impl ();
}

test_suite *
init_unit_test_suite ( int , char *[] )
{
  test_suite *test = BOOST_TEST_SUITE ( "SipRtpEndpoint" );

  test->add (BOOST_TEST_CASE ( source_connections ), 0, /* timeout */ 10);
  test->add (BOOST_TEST_CASE ( source_connections_regenerate ), 0, /* timeout */ 10);
  return test;
}

max_stars_repo_name: synergysky/kms-siprtpendpoint

max_issues_repo_name: synergysky/kms-siprtpendpoint

max_forks_repo_name: synergysky/kms-siprtpendpoint


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_PREDICATES_FUNCTIONS_SIMD_COMMON_MAJORITY_HPP_INCLUDED
#define BOOST_SIMD_PREDICATES_FUNCTIONS_SIMD_COMMON_MAJORITY_HPP_INCLUDED
#include <boost/simd/predicates/functions/majority.hpp>
#include <boost/simd/sdk/meta/as_logical.hpp>
#include <boost/simd/include/functions/simd/is_nez.hpp>
#include <boost/simd/include/functions/simd/logical_and.hpp>
#include <boost/simd/include/functions/simd/logical_or.hpp>

namespace boost { namespace simd { namespace ext
{
  BOOST_DISPATCH_IMPLEMENT         (majority_, tag::cpu_,
                           (A0)(X),
                           ((simd_<arithmetic_<A0>,X>))
                           ((simd_<arithmetic_<A0>,X>))
                           ((simd_<arithmetic_<A0>,X>))
                          )
  {
    typedef typename meta::as_logical<A0>::type result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(3)
    {
      result_type aa0 = is_nez(a0);
      result_type aa1 = is_nez(a1);
      result_type aa2 = is_nez(a2);
      result_type r =  logical_or(
               logical_or(
                 logical_and(aa0, aa1),
                 logical_and(aa1, aa2)
               ),
               logical_and(aa2, aa0)
             );
      return r;
    }
  };
} } }
#endif

ext: hpp


text:
// Copyright 2014-2015 SDL plc
// 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 <sdl/Util/Debug.hpp>
#include <sdl/Util/DefaultPrintRange.hpp>
#include <sdl/Util/FindFile.hpp>
#include <sdl/Util/LogHelper.hpp>
#include <boost/filesystem/operations.hpp>  // exists
#include <algorithm>
#include <fstream>
#include <istream>
#include <iterator>
#include <stdexcept>
#include <string>

namespace sdl {
namespace Util {

namespace bfs = boost::filesystem;

std::string const& requireExists(std::string const& filename) {
  bfs::path filePath(filename);
  if (!exists(filePath))
    SDL_THROW_LOG(FindFile, ConfigException, "File '" << filename << "' does not exist.");
  return filename;
}

std::string findExistingFile(std::string const& filename, Dirs const& searchDirs, bool doLogging) {

  bfs::path filePath(filename);
  UTIL_DBG_MSG(1, "findExistingFile: " << filePath);

  if (filePath.is_absolute()) {
    UTIL_DBG_MSG(1, "absolute: " << filename);
    return requireExists(filename);
  }

  if (searchDirs.empty()) {
    // TODO: test
    Dirs searchCwd(1, bfs::current_path().string());
    UTIL_DBG_MSG(1, "empty search dirs, using cwd: " << searchCwd[0]);
    if (doLogging) {
      SDL_INFO(FindFile, "No base directory specified - looking for "
                             << filename << " relative to cwd: " << searchCwd[0]);
    }
    return findExistingFile(filename, searchCwd, doLogging);
  }

  // Try each search dir.
  for (std::string const& dirName : searchDirs) {
    // TODO: test
    bfs::path tryPath(dirName);
    UTIL_DBG_MSG(1, "try in dir: " << tryPath << " for file: " << filePath);
    tryPath /= filePath;
    UTIL_DBG_MSG(1, "trying: " << tryPath);
    if (exists(tryPath)) {
      if (doLogging) {
        SDL_INFO(FindFile, "Found '" << tryPath.string() << "'");
      }
      return tryPath.string();
    }
  }

  SDL_THROW_LOG(FindFile, ConfigException,
                "Could not find file '" << filename << "' "
                                        << printer(searchDirs, RangeSep(":", "(search directories: ", ")")));
}

void splitFilePath(std::string const& resolvedPath, std::string* pStrDir, std::string* pStrFileName) {
  // TODO: test
  bfs::path filePath(resolvedPath);
  if (pStrDir) *pStrDir = filePath.parent_path().string();
  if (pStrFileName) *pStrFileName = filePath.filename().string();
}

std::string absPath(std::string const& pathName) {
  bfs::path path(pathName);
  return system_complete(path).string();
}

std::string dirname(std::string const& pathName) {
  return bfs::path(pathName).parent_path().string();
}

std::string basename(std::string const& pathName) {
  return bfs::path(pathName).filename().string();
}

void mkdirs(std::string const& path) {
  // TODO: test
  boost::filesystem::create_directories(path);
}

std::string mkdirParentPath(std::string const& pathName) {
  bfs::path p((pathName));
  bfs::path parent(p.parent_path());
  create_directories(parent);
  return parent.string();
}

std::string absParent(std::string const& pathName) {
  // TODO: test
  bfs::path path(pathName);
  return system_complete(path).parent_path().string();
}

void SearchDirs::appendParent(std::string const& fileInParent) {
  // TODO: test
  std::string const& parent = absParent(fileInParent);
  UTIL_DBG_MSG(1, "SearchDirs: appending dirname(" << fileInParent << ") = " << parent);
  append(parent);
}

}}

max_stars_repo_name: sdl-research/hyp

max_issues_repo_name: hypergraphs/hyp

max_forks_repo_name: hypergraphs/hyp


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

#include "wikipedia_graph.h"

#define BOOST_TEST_MAIN
#include <boost/test/included/unit_test.hpp>
//#include <boost/test/floating_point_comparison.hpp>

using namespace std;
using namespace boost::unit_test;

BOOST_AUTO_TEST_CASE( test_construction )
{
}


text:
/*
 * Copyright 2015-2019 CNRS-UM LIRMM, CNRS-AIST JRL
 */

#include <mc_rtc/gui/ArrayLabel.h>
#include <mc_rtc/gui/Label.h>
#include <mc_rtc/gui/StateBuilder.h>

#include <boost/test/unit_test.hpp>

struct DummyProvider
{
  double value = 42.0;
  Eigen::Vector3d point = Eigen::Vector3d(0., 1., 2.);
};

BOOST_AUTO_TEST_CASE(TestGUIStateBuilder)
{
  DummyProvider provider;
  mc_rtc::gui::StateBuilder builder;
  std::vector<char> buffer;
  // Size of the GUI message when the GUI is empty
  auto empty_size = builder.update(buffer);
  builder.addElement({"dummy", "provider"}, mc_rtc::gui::Label("value", [&provider] { return provider.value; }));
  builder.addElement({"dummy", "provider"}, mc_rtc::gui::ArrayLabel("point", [&provider] { return provider.point; }));
  // Check that after adding elements we have a different size, ref_size is our full message
  auto ref_size = builder.update(buffer);
  {
    BOOST_REQUIRE(ref_size != empty_size);
  }
  builder.removeElement({"dummy", "provider"}, "value");
  builder.removeElement({"dummy", "provider"}, "point");
  // Removing all elements manually sends us back to the empty state
  {
    auto s = builder.update(buffer);
    BOOST_REQUIRE(s == empty_size);
  }
  // Add the elements back
  builder.addElement({"dummy", "provider"}, mc_rtc::gui::Label("value", [&provider] { return provider.value; }));
  builder.addElement({"dummy", "provider"}, mc_rtc::gui::ArrayLabel("point", [&provider] { return provider.point; }));
  {
    auto s = builder.update(buffer);
    BOOST_REQUIRE(s == ref_size);
  }
  // Removing through the category should clean up the full GUI
  builder.removeCategory({"dummy", "provider"});
  {
    auto s = builder.update(buffer);
    BOOST_REQUIRE(s == empty_size);
  }
  // Now we add them with explicit sources
  builder.addElement(&provider, {"dummy", "provider"},
                     mc_rtc::gui::Label("value", [&provider] { return provider.value; }));
  builder.addElement(&provider, {"dummy", "provider"},
                     mc_rtc::gui::ArrayLabel("point", [&provider] { return provider.point; }));
  {
    auto s = builder.update(buffer);
    BOOST_REQUIRE(s == ref_size);
  }
  // We remove by providing the source only
  builder.removeElements(&provider);
  {
    auto s = builder.update(buffer);
    BOOST_REQUIRE(s == empty_size);
  }
  builder.addElement(&provider, {"dummy"}, mc_rtc::gui::Label("value", [&provider] { return provider.value; }));
  // New ref_size for the GUI with one element
  ref_size = builder.update(buffer);
  BOOST_REQUIRE(ref_size != empty_size);
  builder.addElement(&provider, {"dummy", "provider"},
                     mc_rtc::gui::ArrayLabel("point", [&provider] { return provider.point; }));
  {
    auto s = builder.update(buffer);
    BOOST_REQUIRE(s != ref_size && s != empty_size);
  }
  // Remove elements within a category using a source
  builder.removeElements({"dummy", "provider"}, &provider);
  {
    auto s = builder.update(buffer);
    BOOST_REQUIRE(s == ref_size);
  }
  builder.removeElements({"dummy"}, &provider);
  {
    auto s = builder.update(buffer);
    BOOST_REQUIRE(s == empty_size);
  }
  // Update ref_size
  builder.addElement(&provider, {"dummy"}, mc_rtc::gui::Label("value", [&provider] { return provider.value; }));
  builder.addElement(&provider, {"dummy", "provider"},
                     mc_rtc::gui::ArrayLabel("point", [&provider] { return provider.point; }));
  ref_size = builder.update(buffer);
  {
    BOOST_REQUIRE(ref_size != empty_size);
  }
  // Remove only the elements of a given category (no recursion)
  builder.removeElements({"dummy"}, &provider, false);
  {
    auto s = builder.update(buffer);
    BOOST_REQUIRE(s != empty_size);
  }
  // Restore the message
  builder.addElement(&provider, {"dummy"}, mc_rtc::gui::Label("value", [&provider] { return provider.value; }));
  {
    auto s = builder.update(buffer);
    BOOST_REQUIRE(s == ref_size);
  }
  // Remove the elements of a given category with recursion
  builder.removeElements({"dummy"}, &provider, true);
  {
    auto s = builder.update(buffer);
    BOOST_REQUIRE(s == empty_size);
  }
}


text:
//
// Copyright (c) 2015-2019 CNRS INRIA
// Copyright (c) 2015-2016 Wandercraft, 86 rue de Paris 91400 Orsay, France.
//

#ifndef __pinocchio_joint_free_flyer_hpp__
#define __pinocchio_joint_free_flyer_hpp__

#include "pinocchio/macros.hpp"
#include "pinocchio/spatial/inertia.hpp"
#include "pinocchio/spatial/explog.hpp"
#include "pinocchio/multibody/joint/joint-base.hpp"
#include "pinocchio/multibody/constraint.hpp"
#include "pinocchio/math/fwd.hpp"
#include "pinocchio/math/quaternion.hpp"

namespace pinocchio
{

  template<typename Scalar, int Options> struct ConstraintIdentityTpl;

  template<typename _Scalar, int _Options>
  struct traits< ConstraintIdentityTpl<_Scalar,_Options> >
  {
    typedef _Scalar Scalar;
    enum { Options = _Options };
    typedef Eigen::Matrix<Scalar,6,6,Options> Matrix6;
    enum {
      LINEAR = 0,
      ANGULAR = 3
    };
    typedef MotionTpl<Scalar,Options> JointMotion;
    typedef Eigen::Matrix<Scalar,6,1,Options> JointForce;
    typedef Eigen::Matrix<Scalar,6,6,Options> DenseBase;
    typedef typename Matrix6::IdentityReturnType ConstMatrixReturnType;
    typedef typename Matrix6::IdentityReturnType MatrixReturnType;
  }; // traits ConstraintRevolute

  template<typename _Scalar, int _Options>
  struct ConstraintIdentityTpl
  : ConstraintBase< ConstraintIdentityTpl<_Scalar,_Options> >
  {
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    PINOCCHIO_CONSTRAINT_TYPEDEF_TPL(ConstraintIdentityTpl)

    enum { NV = 6 };

    template<typename Vector6Like>
    JointMotion __mult__(const Eigen::MatrixBase<Vector6Like> & vj) const
    {
      EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Vector6Like,6);
      return JointMotion(vj);
    }

    template<typename S1, int O1>
    typename SE3Tpl<S1,O1>::ActionMatrixType
    se3Action(const SE3Tpl<S1,O1> & m) const
    {
      return m.toActionMatrix();

    }

    template<typename S1, int O1>
    typename SE3Tpl<S1,O1>::ActionMatrixType
    se3ActionInverse(const SE3Tpl<S1,O1> & m) const
    {
      return m.toActionMatrixInverse();
    }

    int nv_impl() const { return NV; }

    struct TransposeConst
    {
      template<typename Derived>
      typename ForceDense<Derived>::ToVectorConstReturnType
      operator*(const ForceDense<Derived> & phi)
      {  return phi.toVector();  }

      /* [CRBA]  MatrixBase operator* (Constraint::Transpose S, ForceSet::Block) */
      template<typename MatrixDerived>
      typename PINOCCHIO_EIGEN_REF_CONST_TYPE(MatrixDerived)
      operator*(const Eigen::MatrixBase<MatrixDerived> & F)
      {
        return F.derived();
      }
    };

    TransposeConst transpose() const { return TransposeConst(); }
    MatrixReturnType matrix_impl() const { return DenseBase::Identity(); }

    template<typename MotionDerived>
    typename MotionDerived::ActionMatrixType
    motionAction(const MotionBase<MotionDerived> & v) const
    { return v.toActionMatrix(); }

    bool isEqual(const ConstraintIdentityTpl &) const { return true; }

  }; // struct ConstraintIdentityTpl

  template<typename Scalar, int Options, typename Vector6Like>
  MotionRef<const Vector6Like>
  operator*(const ConstraintIdentityTpl<Scalar,Options> &,
            const Eigen::MatrixBase<Vector6Like> & v)
  {
    EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Vector6Like,6);
//    typedef typename ConstraintIdentityTpl<Scalar,Options>::Motion Motion;
    typedef MotionRef<const Vector6Like> Motion;
    return Motion(v.derived());
  }

  /* [CRBA] ForceSet operator* (Inertia Y,Constraint S) */
  template<typename S1, int O1, typename S2, int O2>
  inline typename InertiaTpl<S1,O1>::Matrix6
  operator*(const InertiaTpl<S1,O1> & Y, const ConstraintIdentityTpl<S2,O2> &)
  {
    return Y.matrix();
  }

  /* [ABA] Y*S operator*/
  template<typename Matrix6Like, typename S2, int O2>
  inline typename PINOCCHIO_EIGEN_REF_CONST_TYPE(Matrix6Like)
  operator*(const Eigen::MatrixBase<Matrix6Like> & Y, const ConstraintIdentityTpl<S2,O2> &)
  {
    return Y.derived();
  }

  template<typename S1, int O1>
  struct SE3GroupAction< ConstraintIdentityTpl<S1,O1> >
  { typedef typename SE3Tpl<S1,O1>::ActionMatrixType ReturnType; };

  template<typename S1, int O1, typename MotionDerived>
  struct MotionAlgebraAction< ConstraintIdentityTpl<S1,O1>,MotionDerived >
  { typedef typename SE3Tpl<S1,O1>::ActionMatrixType ReturnType; };

  template<typename Scalar, int Options> struct JointFreeFlyerTpl;

  template<typename _Scalar, int _Options>
  struct traits< JointFreeFlyerTpl<_Scalar,_Options> >
  {
    enum {
      NQ = 7,
      NV = 6
    };
    typedef _Scalar Scalar;
    enum { Options = _Options };
    typedef JointDataFreeFlyerTpl<Scalar,Options> JointDataDerived;
    typedef JointModelFreeFlyerTpl<Scalar,Options> JointModelDerived;
    typedef ConstraintIdentityTpl<Scalar,Options> Constraint_t;
    typedef SE3Tpl<Scalar,Options> Transformation_t;
    typedef MotionTpl<Scalar,Options> Motion_t;
    typedef MotionZeroTpl<Scalar,Options> Bias_t;

    // [ABA]
    typedef Eigen::Matrix<Scalar,6,NV,Options> U_t;
    typedef Eigen::Matrix<Scalar,NV,NV,Options> D_t;
    typedef Eigen::Matrix<Scalar,6,NV,Options> UD_t;

    PINOCCHIO_JOINT_DATA_BASE_ACCESSOR_DEFAULT_RETURN_TYPE

    typedef Eigen::Matrix<Scalar,NQ,1,Options> ConfigVector_t;
    typedef Eigen::Matrix<Scalar,NV,1,Options> TangentVector_t;
  };

  template<typename Scalar, int Options>
  struct traits< JointDataFreeFlyerTpl<Scalar,Options> >
  { typedef JointFreeFlyerTpl<Scalar,Options> JointDerived; };

  template<typename Scalar, int Options>
  struct traits< JointModelFreeFlyerTpl<Scalar,Options> >
  { typedef JointFreeFlyerTpl<Scalar,Options> JointDerived; };

  template<typename _Scalar, int _Options>
  struct JointDataFreeFlyerTpl : public JointDataBase< JointDataFreeFlyerTpl<_Scalar,_Options> >
  {
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    typedef JointFreeFlyerTpl<_Scalar,_Options> JointDerived;
    PINOCCHIO_JOINT_DATA_TYPEDEF_TEMPLATE(JointDerived);
    PINOCCHIO_JOINT_DATA_BASE_DEFAULT_ACCESSOR

    Constraint_t S;
    Transformation_t M;
    Motion_t v;
    Bias_t c;

    // [ABA] specific data
    U_t U;
    D_t Dinv;
    UD_t UDinv;

    JointDataFreeFlyerTpl()
    : M(Transformation_t::Identity())
    , v(Motion_t::Zero())
    , U(U_t::Zero())
    , Dinv(D_t::Zero())
    , UDinv(UD_t::Identity())
    {}

    static std::string classname() { return std::string("JointDataFreeFlyer"); }
    std::string shortname() const { return classname(); }

  }; // struct JointDataFreeFlyerTpl

  PINOCCHIO_JOINT_CAST_TYPE_SPECIALIZATION(JointModelFreeFlyerTpl);
  template<typename _Scalar, int _Options>
  struct JointModelFreeFlyerTpl
  : public JointModelBase< JointModelFreeFlyerTpl<_Scalar,_Options> >
  {
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    typedef JointFreeFlyerTpl<_Scalar,_Options> JointDerived;
    PINOCCHIO_JOINT_TYPEDEF_TEMPLATE(JointDerived);

    typedef JointModelBase<JointModelFreeFlyerTpl> Base;
    using Base::id;
    using Base::idx_q;
    using Base::idx_v;
    using Base::setIndexes;

    JointDataDerived createData() const { return JointDataDerived(); }

    template<typename ConfigVectorLike>
    inline void forwardKinematics(Transformation_t & M, const Eigen::MatrixBase<ConfigVectorLike> & q_joint) const
    {
      EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(ConfigVector_t,ConfigVectorLike);
      typedef typename Eigen::Quaternion<typename ConfigVectorLike::Scalar,PINOCCHIO_EIGEN_PLAIN_TYPE(ConfigVectorLike)::Options> Quaternion;
      typedef Eigen::Map<const Quaternion> ConstQuaternionMap;

      ConstQuaternionMap quat(q_joint.template tail<4>().data());
      //assert(math::fabs(quat.coeffs().squaredNorm()-1.) <= sqrt(Eigen::NumTraits<typename V::Scalar>::epsilon())); TODO: check validity of the rhs precision
      assert(math::fabs(quat.coeffs().squaredNorm()-1.) <= 1e-4);

      M.rotation(quat.matrix());
      M.translation(q_joint.template head<3>());
    }

    template<typename Vector3Derived, typename QuaternionDerived>
    EIGEN_DONT_INLINE
    void calc(JointDataDerived & data,
              const typename Eigen::MatrixBase<Vector3Derived> & trans,
              const typename Eigen::QuaternionBase<QuaternionDerived> & quat) const
    {
      data.M.translation(trans);
      data.M.rotation(quat.matrix());
    }

    template<typename ConfigVector>
    EIGEN_DONT_INLINE
    void calc(JointDataDerived & data,
              const typename Eigen::PlainObjectBase<ConfigVector> & qs) const
    {
      typedef typename Eigen::Quaternion<typename ConfigVector::Scalar,ConfigVector::Options> Quaternion;
      typedef Eigen::Map<const Quaternion> ConstQuaternionMap;

      typename ConfigVector::template ConstFixedSegmentReturnType<NQ>::Type q = qs.template segment<NQ>(idx_q());
      ConstQuaternionMap quat(q.template tail<4>().data());

      calc(data,q.template head<3>(),quat);
    }

    template<typename ConfigVector>
    EIGEN_DONT_INLINE
    void calc(JointDataDerived & data,
              const typename Eigen::MatrixBase<ConfigVector> & qs) const
    {
      typedef typename Eigen::Quaternion<Scalar,Options> Quaternion;

      typename ConfigVector::template ConstFixedSegmentReturnType<NQ>::Type q = qs.template segment<NQ>(idx_q());
      const Quaternion quat(q.template tail<4>());

      calc(data,q.template head<3>(),quat);
    }

    template<typename ConfigVector, typename TangentVector>
    EIGEN_DONT_INLINE
    void calc(JointDataDerived & data,
              const typename Eigen::MatrixBase<ConfigVector> & qs,
              const typename Eigen::MatrixBase<TangentVector> & vs) const
    {
      calc(data,qs.derived());

      data.v = vs.template segment<NV>(idx_v());
    }

    template<typename Matrix6Like>
    void calc_aba(JointDataDerived & data,
                  const Eigen::MatrixBase<Matrix6Like> & I,
                  const bool update_I) const
    {
      data.U = I;

      // compute inverse
//      data.Dinv.setIdentity();
//      I.llt().solveInPlace(data.Dinv);
      internal::PerformStYSInversion<Scalar>::run(I,data.Dinv);

      if (update_I)
        PINOCCHIO_EIGEN_CONST_CAST(Matrix6Like,I).setZero();
    }

    static std::string classname() { return std::string("JointModelFreeFlyer"); }
    std::string shortname() const { return classname(); }

    /// \returns An expression of *this with the Scalar type casted to NewScalar.
    template<typename NewScalar>
    JointModelFreeFlyerTpl<NewScalar,Options> cast() const
    {
      typedef JointModelFreeFlyerTpl<NewScalar,Options> ReturnType;
      ReturnType res;
      res.setIndexes(id(),idx_q(),idx_v());
      return res;
    }

  }; // struct JointModelFreeFlyerTpl

} // namespace pinocchio

#include <boost/type_traits.hpp>

namespace boost
{
  template<typename Scalar, int Options>
  struct has_nothrow_constructor< ::pinocchio::JointModelFreeFlyerTpl<Scalar,Options> >
  : public integral_constant<bool,true> {};

  template<typename Scalar, int Options>
  struct has_nothrow_copy< ::pinocchio::JointModelFreeFlyerTpl<Scalar,Options> >
  : public integral_constant<bool,true> {};

  template<typename Scalar, int Options>
  struct has_nothrow_constructor< ::pinocchio::JointDataFreeFlyerTpl<Scalar,Options> >
  : public integral_constant<bool,true> {};

  template<typename Scalar, int Options>
  struct has_nothrow_copy< ::pinocchio::JointDataFreeFlyerTpl<Scalar,Options> >
  : public integral_constant<bool,true> {};
}

#endif // ifndef __pinocchio_joint_free_flyer_hpp__

max_stars_repo_name: ikalevatykh/pinocchio

max_issues_repo_name: ikalevatykh/pinocchio

max_forks_repo_name: ikalevatykh/pinocchio


text:
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>

#include <elle/reactor/network/rdv-socket.hh>
#include <elle/reactor/network/resolve.hh>
#include <elle/reactor/network/rdv.hh>
#include <elle/reactor/network/Error.hh>
#include <elle/reactor/scheduler.hh>

ELLE_LOG_COMPONENT("rdv.socket");

namespace elle
{
  namespace reactor
  {
    namespace network
    {
      using Endpoint = boost::asio::ip::udp::endpoint;

      RDVSocket::RDVSocket()
        : _server_reached(elle::sprintf("%s: server reached", *this))
        , _breacher("breacher", [this] { this->_loop_breach(); })
        , _keep_alive("keep-alive", [this]  { this->_loop_keep_alive(); })
        , _tasks(elle::sprintf("%s tasks barrier", this))
      {}

      RDVSocket::~RDVSocket()
      {
        this->_breacher.terminate_now();
        this->_keep_alive.terminate_now();
        for (auto& c: this->_contacts)
          c.second.barrier.open();
        ELLE_DEBUG("%s: waiting for tasks to terminate...", this);
        reactor::wait(this->_tasks);
        ELLE_DEBUG("%s: waiting done", this);
      }

      void
      RDVSocket::rdv_connect(std::string const& id,
                             std::string const& rdv_host, int rdv_port,
                             DurationOpt timeout)
      {
        this->_id = id;
        this->rdv_connect(id, resolve_udp(rdv_host, rdv_port)[0],
                          timeout);
      }

      void
      RDVSocket::rdv_connect(std::string const& id, Endpoint ep,
                             DurationOpt timeout)
      {
        this->_id = id;
        ELLE_TRACE_SCOPE("rdv_connect to %s as %s", ep, id);
        this->_server_reached.close();
        this->_server = ep;
        rdv::Message req;
        req.command = rdv::Command::ping;
        req.id = id;
        elle::Buffer buf = elle::serialization::json::serialize(req, false);
        auto now = boost::posix_time::second_clock::universal_time();
        while (true)
        {
          this->_send_to_failsafe(
            elle::ConstWeakBuffer(buf.contents(), buf.size()),
            ep);
          if (reactor::wait(_server_reached, 500_ms))
            return;
          if (timeout &&
              boost::posix_time::second_clock::universal_time() - now > *timeout)
            throw TimeOut();
        }
      }

      Size
      RDVSocket::receive_from(elle::WeakBuffer buffer,
                              boost::asio::ip::udp::endpoint &endpoint,
                              DurationOpt timeout)
      {
        while (true)
        {
          bool set_endpoint = false;
          Size sz = UDPSocket::receive_from(buffer, endpoint, timeout);
          if (sz < 8)
            return sz;
          bool server_hit = (endpoint == _server);
          auto addr = endpoint.address();
          if (endpoint.port() == _server.port()
              && addr.is_v6()
              && addr.to_v6().is_v4_mapped()
              && addr.to_v6().to_v4() == _server.address())
            server_hit = true;
          if (!this->_server_reached.opened() &&  server_hit)
          {
            ELLE_TRACE("message from server, open reached");
            this->_server_reached.open();
            set_endpoint = true;
          }
          auto magic = std::string(buffer.contents(), buffer.contents() + 8);
          auto it = this->_readers.find(magic);
          if (it != this->_readers.end())
          {
            it->second(elle::WeakBuffer(buffer.mutable_contents(), sz),
                       endpoint);
          }
          else if (magic == rdv::rdv_magic)
          {
            rdv::Message repl =
              elle::serialization::json::deserialize<rdv::Message>(
                elle::Buffer(buffer.contents() + 8, sz - 8), false);
            if (set_endpoint && repl.source_endpoint)
            {
              this->_public_endpoint = *repl.source_endpoint;
            }
            ELLE_DEBUG("got message from %s, code %s", endpoint,
                       (int)repl.command);
            switch (repl.command)
            {
            case rdv::Command::ping:
              {
                rdv::Message reply;
                reply.id = this->_id;
                reply.command = rdv::Command::pong;
                reply.source_endpoint = endpoint;
                reply.target_address = repl.target_address;
                elle::Buffer buf = elle::serialization::json::serialize(reply,
                                                                        false);
                this->_send_with_magik(buf, endpoint);
              }
              break;
            case rdv::Command::pong:
              {
                ELLE_DEBUG("pong from '%s' (%s)", repl.id, repl.target_address ?
                  *repl.target_address : "");
                auto it = this->_contacts.find(repl.id);
                if (it != this->_contacts.end())
                {
                  ELLE_TRACE("opening result barrier");
                  it->second.set_result(endpoint);
                  it->second.barrier.open();
                }
                if (repl.target_address)
                {
                  auto it = this->_contacts.find(*repl.target_address);
                  if (it != this->_contacts.end())
                  {
                    ELLE_TRACE("opening result barrier");
                    it->second.set_result(endpoint);
                    it->second.barrier.open();
                  }
                }
              }
              break;
            case rdv::Command::connect:
              {
                ELLE_TRACE("connect result tgt=%s, peer=%s",
                           *repl.target_address, !!repl.target_endpoint);
                auto it = this->_contacts.find(*repl.target_address);
                if (it != this->_contacts.end() && !it->second.barrier.opened())
                {
                  if (repl.target_endpoint)
                  {
                    // set result but do not open barrier yet, so that
                    // contact() can retry pinging it
                    it->second.set_result(*repl.target_endpoint);
                    // give it a ping
                    this->_send_ping(*repl.target_endpoint);
                  }
                  else
                  { // nothing to do, contact() will resend periodically
                  }
                }
              }
              break;
            case rdv::Command::connect_requested:
              { // add to breach requests
                ELLE_ASSERT(repl.target_endpoint);
                ELLE_TRACE("connect_requested, id=%s, ep=%s",
                  repl.id, *repl.target_endpoint);
                auto it = std::find_if(
                  this->_breach_requests.begin(),
                  this->_breach_requests.end(),
                  [&](std::pair<Endpoint, int>const& b)
                  {
                    return b.first == *repl.target_endpoint;
                  });
                if (it != _breach_requests.end())
                  it->second += 5;
                else
                  this->_breach_requests.push_back(
                    std::make_pair(*repl.target_endpoint, 5));
              }
              break;
            case rdv::Command::error:
              break;
            }
          }
          else
            return sz;
        }
      }

      Endpoint
      RDVSocket::contact(std::string const& id,
                         std::vector<Endpoint> const& endpoints,
                         DurationOpt timeout)
      {
        auto task_lock = this->_tasks.lock();
        ELLE_TRACE_SCOPE("%s: contact %s", *this, id);
        std::string tempid;
        std::string contactid = id;
        if (id.empty())
        {
          tempid = to_string(
            boost::uuids::basic_random_generator<boost::mt19937>()());
          contactid = tempid;
        }
        auto ci = this->_contacts.emplace(
          std::piecewise_construct,
          std::forward_as_tuple(contactid),
          std::forward_as_tuple(*this, contactid));
        ++ci.first->second.waiters;
        elle::SafeFinally unregister_request(
          [&]
          {
            auto it = this->_contacts.find(contactid);
            ELLE_ASSERT(it != this->_contacts.end());
            if (--it->second.waiters <= 0)
              this->_contacts.erase(it);
          });
        auto now = boost::posix_time::second_clock::universal_time();
        while (true)
        {
          if (!endpoints.empty())
          {
            // try known endpoints
            ELLE_TRACE("pinging id=%s", contactid);
            for (auto const& ep: endpoints)
              this->_send_ping(ep, contactid);
          }
          // try establishing link through RDV.
          auto const& c = this->_contacts.at(contactid);
          if (!c.barrier.opened()
              && this->_server_reached.opened()
              && !id.empty())
          {
            if (c.result
                && boost::posix_time::second_clock::local_time() - c.result_time
                   < 10_sec)
            {
              // RDV gave us an enpoint, but we are not connected to it yet,
              // ping it.
              this->_send_ping(*c.result);
            }
            else
            {
              rdv::Message req;
              req.command = rdv::Command::connect;
              req.id = this->_id;
              req.target_address = id;
              auto buf = elle::serialization::json::serialize(req, false);
              this->_send_to_failsafe(buf, _server);
            }
          }
          if (reactor::wait(this->_contacts.at(contactid).barrier, 500_ms))
          {
            auto& c = _contacts.at(contactid);
            if (c.result)
            {
              ELLE_TRACE("got result: %s", *c.result);
              return *c.result;
            }
            else
              throw elle::Error(elle::sprintf("contact(%s) aborted", id));
          }
          if (timeout &&
              boost::posix_time::second_clock::universal_time() - now > *timeout)
            throw TimeOut();
        }
      }

      void
      RDVSocket::_send_with_magik(elle::Buffer const& b, Endpoint peer)
      {
        elle::Buffer data;
        data.append(reactor::network::rdv::rdv_magic, 8);
        data.append(b.contents(), b.size());
        this->_send_to_failsafe(
          elle::ConstWeakBuffer(data.contents(), data.size()),
          peer);
      }

      void
      RDVSocket::_send_ping(Endpoint target, std::string const& tid)
      {
        ELLE_DEBUG("send ping to %s", target);
        rdv::Message ping;
        ping.command = rdv::Command::ping;
        ping.id = this->_id;
        ping.source_endpoint = target;
        ping.target_address = tid;
        elle::Buffer buf = elle::serialization::json::serialize(ping, false);
        this->_send_with_magik(buf, target);
      }

      void
      RDVSocket::_loop_breach()
      {
        while (true)
        {
          std::vector<Endpoint> to_ping;
          for (int i = 0; i < signed(_breach_requests.size()); ++i)
          {
            auto& b = this->_breach_requests[i];
            to_ping.push_back(b.first);
            if (!--b.second)
            {
              std::swap(
                this->_breach_requests[i],
                this->_breach_requests[this->_breach_requests.size()-1]);
              this->_breach_requests.pop_back();
              --i;
            }
          }
          for (auto const& ep: to_ping)
            this->_send_ping(ep);
          reactor::sleep(500_ms);
        }
      }

      void
      RDVSocket::_loop_keep_alive()
      {
        reactor::wait(_server_reached);
        while (true)
        {
          this->_send_ping(_server);
          reactor::sleep(30_sec);
        }
      }

      bool
      RDVSocket::rdv_connected() const
      {
        return _server_reached.opened();
      }

      void
      RDVSocket::set_local_id(std::string const& id)
      {
        this->_id = id;
      }

      void
      RDVSocket::register_reader(std::string const& magic,
                                 Reader handler)
      {
        ELLE_ASSERT_EQ(signed(magic.size()), 8);
        this->_readers[magic] = handler;
      }

      void
      RDVSocket::unregister_reader(std::string const& magic)
      {
        this->_readers.erase(magic);
      }

      void
      RDVSocket::_send_to_failsafe(elle::ConstWeakBuffer buffer,
                                   Endpoint endpoint)
      {
        try
        {
          send_to(buffer, endpoint);
        }
        catch (Error const& e)
        {
          ELLE_DEBUG("send_to failed with %s", e);
        }
      }

      RDVSocket::ContactInfo::ContactInfo(RDVSocket const& owner,
                                          std::string const& id)
        : barrier(elle::sprintf("%s: contact %s", owner, id))
        , waiters()
      {}

      void
      RDVSocket::ContactInfo::set_result(Endpoint ep)
      {
        this->result = ep;
        this->result_time = boost::posix_time::second_clock::local_time();
      }
    }
  }
}

ext: cc

max_stars_repo_name: infinitio/elle

max_issues_repo_name: infinitio/elle

max_forks_repo_name: infinitio/elle


text:
/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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 <bitset>
#include <boost/mp11.hpp>
#include <gtest/gtest.h>
#include <thrift/lib/cpp2/gen/module_types_h.h>

TEST(IssetBitsetTest, basic) {
  const int N = 100;
  apache::thrift::detail::isset_bitset<N, true> packed;
  apache::thrift::detail::isset_bitset<N, false> unpacked;
  std::bitset<8> bits;
  for (int i = 0; i < N; i++) {
    if (i % 8 == 0) {
      bits = 0;
    }
    for (bool b : {true, false, true}) {
      boost::mp11::mp_with_index<N>(i, [&](auto index) {
        packed.__fbthrift_set(index, b);
        unpacked.__fbthrift_set(index, b);
        EXPECT_EQ(packed.__fbthrift_get(index), b);
        EXPECT_EQ(unpacked.__fbthrift_get(index), b);

        bits.set(index % 8, b);
        EXPECT_EQ(packed.__fbthrift_at(index), bits.to_ulong());
        EXPECT_EQ(unpacked.__fbthrift_at(index), b ? 1 : 0);
        EXPECT_EQ(packed.__fbthrift_bit(index), index % 8);
        EXPECT_EQ(unpacked.__fbthrift_bit(index), 0);
      });
    }
  }
}

TEST(IssetBitsetTest, compare_size) {
  static_assert(sizeof(apache::thrift::detail::isset_bitset<1>) == 1);
  static_assert(sizeof(apache::thrift::detail::isset_bitset<2>) == 2);
  static_assert(sizeof(apache::thrift::detail::isset_bitset<7, true>) == 1);
  static_assert(sizeof(apache::thrift::detail::isset_bitset<8, true>) == 1);
  static_assert(sizeof(apache::thrift::detail::isset_bitset<9, true>) == 2);
}

max_stars_repo_name: sakibguy/fbthrift

max_issues_repo_name: sakibguy/fbthrift

max_forks_repo_name: sakibguy/fbthrift


text:
// Distributed under the MIT License.
// See LICENSE.txt for details.

#include "Framework/TestingFramework.hpp"

#include <boost/math/quaternion.hpp>

#include "DataStructures/DataVector.hpp"
#include "Domain/FunctionsOfTime/QuaternionHelpers.hpp"
#include "Utilities/Gsl.hpp"

SPECTRE_TEST_CASE("Unit.Domain.FunctionsOfTime.QuaternionHelpers",
                  "[Unit][Domain]") {
  using quaternion = boost::math::quaternion<double>;

  quaternion quat1(1.0, 2.0, 3.0, -4.0);
  DataVector dv{1.0, 2.0, 3.0, -4.0};
  DataVector dv_short{9.9, 9.8, 9.7};

  DataVector dv2 = quaternion_to_datavector(quat1);
  CHECK(dv2 == dv);

  quaternion quat2 = datavector_to_quaternion(dv2);
  CHECK(quat2 == quat1);

  quaternion quat3 = datavector_to_quaternion(dv_short);
  CHECK(quat3 == quaternion{0.0, 9.9, 9.8, 9.7});

  normalize_quaternion(make_not_null(&quat2));
  CHECK(norm(quat2) == approx(1.0));
  CHECK(abs(quat2) == approx(1.0));
}

max_stars_repo_name: nilsvu/spectre

max_issues_repo_name: GitHimanshuc/spectre


text:
/**
 * @file PTP18.hpp
 * @brief Provides ptp instance (based on linuxptp-1.8) to the sync interface
 * @author Anon D'Anon
 *
 * Copyright (c) Regents of the Anon, 2018. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 	1. Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 */

#ifndef PTP18_HPP
#define PTP18_HPP

// Parent class include
#include "../Sync.hpp"
#include "../SyncUncertainty.hpp"
#include "../qot_tlcomm.hpp"

// Boost includes
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/log/trivial.hpp>

/* Linuxptp includes */
extern "C"
{
	// Standard includes
	#include <limits.h>
	#include <stdio.h>
	#include <stdlib.h>
	#include <string.h>
	#include <unistd.h>
	#include <linux/net_tstamp.h>

	// Linuxptp includes
	#include "linuxptp-1.8/clock.h"
	#include "linuxptp-1.8/config.h"
	#include "linuxptp-1.8/ntpshm.h"
	#include "linuxptp-1.8/pi.h"
	#include "linuxptp-1.8/print.h"
	#include "linuxptp-1.8/raw.h"
	#include "linuxptp-1.8/sk.h"
	#include "linuxptp-1.8/transport.h"
	#include "linuxptp-1.8/udp6.h"
	#include "linuxptp-1.8/uds.h"
	#include "linuxptp-1.8/util.h"
	#include "linuxptp-1.8/version.h"

	// Include to share data from ptp sync to uncertainty calculation
	#include "uncertainty_data.h"
}

namespace qot
{
	class PTP18  : public Sync
	{

		// Constructor and destructor
		public: PTP18(boost::asio::io_service *io, const std::string &iface, struct uncertainty_params config);
		public: ~PTP18();

		// Control functions
		public: void Reset();
		public: void Start(bool master, int log_sync_interval,
			uint32_t sync_session, int timelineid, int *timelinesfd, const std::string &tl_name, std::string &node_name, uint16_t timelines_size);
		public: void Stop();						// Stop

		// Send a data/ask functionality to the sync instance -> pointer and an int flag for sync session to decide what to do
		public: int ExtControl(void** pointer, ExtCtrlOptions type);

		// Set the desired accuracy of the timeline
		private: void SetDesiredAccuracy(uint64_t accuracy);

		// Set the NATS server
		#ifdef QOT_TIMELINE_SERVICE
		private: void SetPubSubServer(std::string server);
		#endif

		// This thread performs rhe actual syncrhonization
		private: int SyncThread(int timelineid, int *timelinesfd, uint16_t timelines_size);

		// Function which changes the sync rate
		private: int ChangeSyncRate();

		// Boost ASIO
		private: boost::asio::io_service *asio;
		private: boost::thread thread;
		private: std::string baseiface;
		private: bool kill;

		// PTP settings
		private: struct config *cfg;

		 // Timeline Name
    	private: std::string timeline_uuid;

    	// Node name
    	private: std::string node_uuid;

		// Sync Uncertainty Calculation Class
		private: SyncUncertainty sync_uncertainty;

		// Last Received Clock-Sync Skew Statistic Data Point
		private: qot_stat_t last_clocksync_data_point;

		// Desired QoT for the Timeline
		private: uint64_t desired_accuracy;

		#ifdef QOT_TIMELINE_SERVICE
        // Communicator class with the timeline service
    	private: TLCommunicator comm;

    	// Pointer to the timeline clock shared memory
    	private: tl_translation_t* tl_clk_params;

    	// NATS Service Server
    	private: std::string nats_server;

    	// NATS Subscriber Running
    	private: bool qot_subscriber_flag;
        #endif

	};
}

#endif

max_stars_repo_name: quartz-roseline/quartz

max_issues_repo_name: quartz-roseline/quartz

max_forks_repo_name: quartz-roseline/quartz


text:
/*
 * AnyEdgeTest.cpp
 *
 *  Created on: Jun 13, 2017
 *      Author: quang
 */

#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

#include "../../../AnyGraph.h"

using namespace anygraph;

BOOST_AUTO_TEST_CASE(AnyEdgeTest) {
	AnyEdge edge;
	//constructor
	BOOST_CHECK(edge.get_From() == std::string("0"));
	BOOST_CHECK(edge.get_To() == std::string("0"));

	std::string from = "1";
	std::string to = "2";

	edge = AnyEdge(from, to);

	BOOST_CHECK(edge.get_From() == std::string("1"));
	BOOST_CHECK(edge.get_To() == std::string("2"));

	//else

	from = "3";
	to = "4";

	edge.set_from(from);
	edge.set_to(to);

	BOOST_CHECK(edge.get_From() == std::string("3"));
	BOOST_CHECK(edge.get_To() == std::string("4"));

	Attributes attr1, attr2;

	attr1.set_id("id1");
	attr2.set_id("id2");

	std::vector<Attributes>attrList;

	attrList.push_back(attr1);
	attrList.push_back(attr2);

	edge.add_attribute(attr1);
	edge.add_attribute(attr2);

	BOOST_CHECK(edge.get_Attribute().size() == attrList.size());
	BOOST_CHECK(edge.get_attribute_at(0).get_attribute_id() == attr1.get_attribute_id());
	BOOST_CHECK(edge.get_attribute_at(1).get_attribute_id() == attr2.get_attribute_id());

}