<commit_before>#pragma%# -*- mode: c++; coding: utf-8 -*-
#pragma%# to be included from binning2.ProductBinning_{variadic,nonvariadic}.h
#pragma%x
#ifndef $"header_name"
#define $"header_name"
#pragma%end.i
#include <mwg/std/tuple>
#include <mwg/std/utility>
namespace mwg{
namespace stat{
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

  namespace detail{
    template<std::size_t I>
    struct ProductBinningImpl{
      template<typename TT>
      static int GetBinNumber(const TT& bins){
        return ProductBinningImpl<I-1>::GetBinNumber(bins)*mwg::stdm::get<I>(bins).size();
      }
      template<typename TTB,typename TTV>
      typename stdm::enable_if<!stdm::is_same<bindex,typename stdm::tuple_element<I,TTV>::type>::value,int>::type
      static GetBinIndex(const TTB& bins,const TTV& vals){
        int const ithis=(int)mwg::stdm::get<I>(bins)(mwg::stdm::get<I>(vals));if(ithis<0)return -1;
        int const irest=ProductBinningImpl<I-1>::GetBinIndex(bins,vals);if(irest<0)return -1;
        return irest*mwg::stdm::get<I>(bins).size()+ithis;
      }
      template<typename TTB,typename TTV>
      typename stdm::enable_if<stdm::is_same<bindex,typename stdm::tuple_element<I,TTV>::type>::value,int>::type
      static GetBinIndex(const TTB& bins,const TTV& vals){
        int const ithis=(int)mwg::stdm::get<I>(vals);if(ithis<0)return -1;
        int const irest=ProductBinningImpl<I-1>::GetBinIndex(bins,vals);if(irest<0)return -1;
        return irest*mwg::stdm::get<I>(bins).size()+ithis;
      }
      template<typename TT>
      struct IsBins:mwg::stdm::integral_constant<
        bool,
        ProductBinningImpl<I-1>::template IsBins<TT>::value&&binning_concept<typename mwg::stdm::tuple_element<I,TT>::type>::value
      >{};
    };
    template<>
    struct ProductBinningImpl<0>{
      template<typename TT>
      static int GetBinNumber(const TT& bins){
        return mwg::stdm::get<0>(bins).size();
      }
      template<typename TTB,typename TTV>
      typename stdm::enable_if<!stdm::is_same<bindex,typename stdm::tuple_element<0,TTV>::type>::value,int>::type
      static GetBinIndex(const TTB& bins,const TTV& vals){
        return (int)mwg::stdm::get<0>(bins)(mwg::stdm::get<0>(vals));
      }
      template<typename TTB,typename TTV>
      typename stdm::enable_if<stdm::is_same<bindex,typename stdm::tuple_element<0,TTV>::type>::value,int>::type
      static GetBinIndex(const TTB& bins,const TTV& vals){
        return (int)mwg::stdm::get<0>(vals);
      }
      template<typename TT>
      struct IsBins:mwg::stdm::integral_constant<bool,binning_concept<typename mwg::stdm::tuple_element<0,TT>::type>::value>{};
    };

#pragma%if variadic
    template<typename TT1,typename TT2,bool S>
    struct is_bindex_pack_impl:stdm::false_type{};
    template<typename... As,typename... Bs>
    struct is_bindex_pack_impl<stdx::parameter_pack<As...>,stdx::parameter_pack<Bs...>,true>
      :stdm::integral_constant<bool,stdx::ice_and<(stdm::is_same<As,bindex>::value||stdm::is_convertible<As,typename Bs::domain_type>::value)...>::value>{};

    template<typename TT1,typename TT2>
    struct is_bindex_pack:stdm::false_type{};
    template<typename... As,typename... Bs>
    struct is_bindex_pack<stdx::parameter_pack<As...>,stdx::parameter_pack<Bs...> >
      :is_bindex_pack_impl<stdx::parameter_pack<As...>,stdx::parameter_pack<Bs...>,sizeof...(As)==sizeof...(Bs)>{};
#pragma%else /* end of if variadic */
    template<typename TT1,typename TT2,bool S=true> struct is_bindex_pack_impl:stdm::false_type{};
    template<> struct is_bindex_pack_impl<stdx::parameter_pack<>,stdx::parameter_pack<> >:stdm::true_type{};
#pragma%%[ArN=10]
#pragma%%x
    template<
      $".for/K/0/ArN/typename AK/,",
      $".for/K/0/ArN/typename BK/,"
      >
    struct is_bindex_pack_impl<stdx::parameter_pack<$".for/K/0/ArN/AK/,">,stdx::parameter_pack<$".for/K/0/ArN/BK/,"> >
      :stdm::integral_constant<
      bool,
      (stdm::is_same<A0,bindex>::value||stdm::is_convertible<A0,typename B0::domain_type>::value)&&is_bindex_pack_impl<
        stdx::parameter_pack<$".for/K/1/ArN/AK/,">,
        stdx::parameter_pack<$".for/K/1/ArN/BK/,">
        >::value
      >{};
#pragma%%end.i

    template<typename TT1,typename TT2>
    struct is_bindex_pack
      :is_bindex_pack_impl<TT1,TT2,TT1::size==TT2::size>
    {};
#pragma%end /* end of if !variadic */
  }

#pragma%if variadic
  template<typename... TBs>
  class product_binning{
    mwg::stdm::tuple<TBs...> data;
  public:
    typedef mwg::stdm::tuple<typename TBs::domain_type...> domain_type;
    product_binning(){}
    template<typename... UBs>
    product_binning(UBs mwg_forward_rvalue ... args)
      :data(mwg::stdm::forward<UBs>(args)...){}
    product_binning(const product_binning& other)
      :data(other.data){}
# if defined(MWGCONF_STD_RVALUE_REFERENCES)
    product_binning(product_binning&& other)
      :data(mwg::stdm::move(other.data)){}
# endif
  public:
    std::size_t size() const{
      return detail::ProductBinningImpl<sizeof...(TBs)-1>::GetBinNumber(data);
    }
    bindex operator()(const domain_type& value) const{
      return (bindex)detail::ProductBinningImpl<sizeof...(TBs)-1>::GetBinIndex(data,value);
    }
    template<typename... Vs>
    typename stdm::enable_if<detail::is_bindex_pack<stdx::parameter_pack<Vs...>,stdx::parameter_pack<TBs...> >::value,bindex>::type
    operator()(Vs const&... args) const{
      return (bindex)detail::ProductBinningImpl<sizeof...(TBs)-1>::GetBinIndex(data,stdm::make_tuple(args...));
    }
  };

  template<typename... TBs> typename stdm::enable_if<
    detail::ProductBinningImpl<sizeof...(TBs)-1>::template IsBins<stdm::tuple<typename stdm::decay<TBs>::type...>>::value,
    product_binning<typename stdm::decay<TBs>::type...>
  >::type make_binning(TBs mwg_forward_rvalue... bins){
    return product_binning<typename stdm::decay<TBs>::type...>(mwg::stdm::forward<TBs>(bins)...);
  }
#pragma%else /* end of if variadic */
  namespace detail{
    template<typename B>
    struct binning_get_domain_type:mwg::identity<typename B::domain_type>{};
    template<>
    struct binning_get_domain_type<void>:mwg::identity<void>{};
  }

#pragma%%x
  template<$".for/K/0/ArN/typename TBK=void/,">
  class product_binning{
    typedef mwg::stdm::tuple<$".for/K/0/ArN/TBK/,"> bins_type;
    bins_type data;
  public:
    typedef mwg::stdm::tuple<$".for/K/0/ArN/
      typename detail::binning_get_domain_type<TBK>::type/,"
    > domain_type;

    product_binning(){}
#pragma%%x
    template<$".for/K/0/_AR_/typename UBK/,">
    product_binning($".for/K/0/_AR_/UBK mwg_forward_rvalue argK/,")
      :data($".for/K/0/_AR_/mwg::stdm::forward<UBK>(argK)/,"){}
#pragma%%end.f/_AR_/1/ArN+1/
    product_binning(const product_binning& other)
      :data(other.data)
    {}
# if defined(MWGCONF_STD_RVALUE_REFERENCES)
    product_binning(product_binning&& other)
      :data(mwg::stdm::move(other.data))
    {}
# endif
  public:
    std::size_t size() const{
      return detail::ProductBinningImpl<stdm::tuple_size<bins_type>::value-1>::GetBinNumber(data);
    }
    bindex operator()(const domain_type& value) const{
      return (bindex)detail::ProductBinningImpl<stdm::tuple_size<bins_type>::value-1>::GetBinIndex(data,value);
    }
#pragma%%x
    template<$".for/K/0/_AR_/typename VK/,">
    typename stdm::enable_if<detail::is_bindex_pack<stdx::parameter_pack<$".for/K/0/_AR_/VK/,">,stdx::parameter_pack<$".for/K/0/ArN/TBK/,"> >::value,bindex>::type
    operator()($".for/K/0/_AR_/VK const& argK/,") const{
      return (bindex)detail::ProductBinningImpl<stdm::tuple_size<bins_type>::value-1>::GetBinIndex(data,stdm::make_tuple($".for/K/0/_AR_/argK/,"));
    }
#pragma%%end.f/_AR_/1/ArN+1/
  };
#pragma%%end.i

#pragma%%x
  template<$".for/K/0/_AR_/typename BK/,"> typename mwg::stdm::enable_if<
    ($".for/K/0/_AR_/binning_concept<BK>::value/&&"),
    product_binning<$".for/K/0/_AR_/BK/,">
  >::type make_binning($".for/K/0/_AR_/const BK& bK/,"){
    return product_binning<$".for/K/0/_AR_/BK/,">($".for/K/0/_AR_/bK/,");
  }
#pragma%%end.f/_AR_/2/ArN+1/.i
#pragma%end /* end of if !variadic */

//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
}
}
#endif
<commit_msg>stat (mwg::stat::product_binning): add copy assignment operator<commit_after>#pragma%# -*- mode: c++; coding: utf-8 -*-
#pragma%# to be included from binning2.ProductBinning_{variadic,nonvariadic}.h
#pragma%x
#ifndef $"header_name"
#define $"header_name"
#pragma%end.i
#include <mwg/std/tuple>
#include <mwg/std/utility>
namespace mwg{
namespace stat{
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

  namespace detail{
    template<std::size_t I>
    struct ProductBinningImpl{
      template<typename TT>
      static int GetBinNumber(const TT& bins){
        return ProductBinningImpl<I-1>::GetBinNumber(bins)*mwg::stdm::get<I>(bins).size();
      }
      template<typename TTB,typename TTV>
      typename stdm::enable_if<!stdm::is_same<bindex,typename stdm::tuple_element<I,TTV>::type>::value,int>::type
      static GetBinIndex(const TTB& bins,const TTV& vals){
        int const ithis=(int)mwg::stdm::get<I>(bins)(mwg::stdm::get<I>(vals));if(ithis<0)return -1;
        int const irest=ProductBinningImpl<I-1>::GetBinIndex(bins,vals);if(irest<0)return -1;
        return irest*mwg::stdm::get<I>(bins).size()+ithis;
      }
      template<typename TTB,typename TTV>
      typename stdm::enable_if<stdm::is_same<bindex,typename stdm::tuple_element<I,TTV>::type>::value,int>::type
      static GetBinIndex(const TTB& bins,const TTV& vals){
        int const ithis=(int)mwg::stdm::get<I>(vals);if(ithis<0)return -1;
        int const irest=ProductBinningImpl<I-1>::GetBinIndex(bins,vals);if(irest<0)return -1;
        return irest*mwg::stdm::get<I>(bins).size()+ithis;
      }
      template<typename TT>
      struct IsBins:mwg::stdm::integral_constant<
        bool,
        ProductBinningImpl<I-1>::template IsBins<TT>::value&&binning_concept<typename mwg::stdm::tuple_element<I,TT>::type>::value
      >{};
    };
    template<>
    struct ProductBinningImpl<0>{
      template<typename TT>
      static int GetBinNumber(const TT& bins){
        return mwg::stdm::get<0>(bins).size();
      }
      template<typename TTB,typename TTV>
      typename stdm::enable_if<!stdm::is_same<bindex,typename stdm::tuple_element<0,TTV>::type>::value,int>::type
      static GetBinIndex(const TTB& bins,const TTV& vals){
        return (int)mwg::stdm::get<0>(bins)(mwg::stdm::get<0>(vals));
      }
      template<typename TTB,typename TTV>
      typename stdm::enable_if<stdm::is_same<bindex,typename stdm::tuple_element<0,TTV>::type>::value,int>::type
      static GetBinIndex(const TTB& bins,const TTV& vals){
        return (int)mwg::stdm::get<0>(vals);
      }
      template<typename TT>
      struct IsBins:mwg::stdm::integral_constant<bool,binning_concept<typename mwg::stdm::tuple_element<0,TT>::type>::value>{};
    };

#pragma%if variadic
    template<typename TT1,typename TT2,bool S>
    struct is_bindex_pack_impl:stdm::false_type{};
    template<typename... As,typename... Bs>
    struct is_bindex_pack_impl<stdx::parameter_pack<As...>,stdx::parameter_pack<Bs...>,true>
      :stdm::integral_constant<bool,stdx::ice_and<(stdm::is_same<As,bindex>::value||stdm::is_convertible<As,typename Bs::domain_type>::value)...>::value>{};

    template<typename TT1,typename TT2>
    struct is_bindex_pack:stdm::false_type{};
    template<typename... As,typename... Bs>
    struct is_bindex_pack<stdx::parameter_pack<As...>,stdx::parameter_pack<Bs...> >
      :is_bindex_pack_impl<stdx::parameter_pack<As...>,stdx::parameter_pack<Bs...>,sizeof...(As)==sizeof...(Bs)>{};
#pragma%else /* end of if variadic */
    template<typename TT1,typename TT2,bool S=true> struct is_bindex_pack_impl:stdm::false_type{};
    template<> struct is_bindex_pack_impl<stdx::parameter_pack<>,stdx::parameter_pack<> >:stdm::true_type{};
#pragma%%[ArN=10]
#pragma%%x
    template<
      $".for/K/0/ArN/typename AK/,",
      $".for/K/0/ArN/typename BK/,"
      >
    struct is_bindex_pack_impl<stdx::parameter_pack<$".for/K/0/ArN/AK/,">,stdx::parameter_pack<$".for/K/0/ArN/BK/,"> >
      :stdm::integral_constant<
      bool,
      (stdm::is_same<A0,bindex>::value||stdm::is_convertible<A0,typename B0::domain_type>::value)&&is_bindex_pack_impl<
        stdx::parameter_pack<$".for/K/1/ArN/AK/,">,
        stdx::parameter_pack<$".for/K/1/ArN/BK/,">
        >::value
      >{};
#pragma%%end.i

    template<typename TT1,typename TT2>
    struct is_bindex_pack
      :is_bindex_pack_impl<TT1,TT2,TT1::size==TT2::size>
    {};
#pragma%end /* end of if !variadic */
  }

#pragma%if variadic
  template<typename... TBs>
  class product_binning{
    mwg::stdm::tuple<TBs...> data;
  public:
    typedef mwg::stdm::tuple<typename TBs::domain_type...> domain_type;
    product_binning(){}
    template<typename... UBs>
    product_binning(UBs mwg_forward_rvalue ... args)
      :data(mwg::stdm::forward<UBs>(args)...){}
    product_binning(const product_binning& other)
      :data(other.data){}
# if defined(MWGCONF_STD_RVALUE_REFERENCES)
    product_binning(product_binning&& other)
      :data(mwg::stdm::move(other.data)){}
# endif

  public:
    product_binning& operator=(const product_binning& rhs)
#ifdef MWGCONF_STD_DEFAULTED_FUNCTIONS
    = default;
#else
    {this->data = rhs.data;}
#endif

  public:
    std::size_t size() const{
      return detail::ProductBinningImpl<sizeof...(TBs)-1>::GetBinNumber(data);
    }
    bindex operator()(const domain_type& value) const{
      return (bindex)detail::ProductBinningImpl<sizeof...(TBs)-1>::GetBinIndex(data,value);
    }
    template<typename... Vs>
    typename stdm::enable_if<detail::is_bindex_pack<stdx::parameter_pack<Vs...>,stdx::parameter_pack<TBs...> >::value,bindex>::type
    operator()(Vs const&... args) const{
      return (bindex)detail::ProductBinningImpl<sizeof...(TBs)-1>::GetBinIndex(data,stdm::make_tuple(args...));
    }
  };

  template<typename... TBs> typename stdm::enable_if<
    detail::ProductBinningImpl<sizeof...(TBs)-1>::template IsBins<stdm::tuple<typename stdm::decay<TBs>::type...>>::value,
    product_binning<typename stdm::decay<TBs>::type...>
  >::type make_binning(TBs mwg_forward_rvalue... bins){
    return product_binning<typename stdm::decay<TBs>::type...>(mwg::stdm::forward<TBs>(bins)...);
  }
#pragma%else /* end of if variadic */
  namespace detail{
    template<typename B>
    struct binning_get_domain_type:mwg::identity<typename B::domain_type>{};
    template<>
    struct binning_get_domain_type<void>:mwg::identity<void>{};
  }

#pragma%%x
  template<$".for/K/0/ArN/typename TBK=void/,">
  class product_binning{
    typedef mwg::stdm::tuple<$".for/K/0/ArN/TBK/,"> bins_type;
    bins_type data;
  public:
    typedef mwg::stdm::tuple<$".for/K/0/ArN/
      typename detail::binning_get_domain_type<TBK>::type/,"
    > domain_type;

    product_binning(){}
#pragma%%x
    template<$".for/K/0/_AR_/typename UBK/,">
    product_binning($".for/K/0/_AR_/UBK mwg_forward_rvalue argK/,")
      :data($".for/K/0/_AR_/mwg::stdm::forward<UBK>(argK)/,"){}
#pragma%%end.f/_AR_/1/ArN+1/
    product_binning(const product_binning& other)
      :data(other.data)
    {}
# if defined(MWGCONF_STD_RVALUE_REFERENCES)
    product_binning(product_binning&& other)
      :data(mwg::stdm::move(other.data))
    {}
# endif
  public:
    std::size_t size() const{
      return detail::ProductBinningImpl<stdm::tuple_size<bins_type>::value-1>::GetBinNumber(data);
    }
    bindex operator()(const domain_type& value) const{
      return (bindex)detail::ProductBinningImpl<stdm::tuple_size<bins_type>::value-1>::GetBinIndex(data,value);
    }
#pragma%%x
    template<$".for/K/0/_AR_/typename VK/,">
    typename stdm::enable_if<detail::is_bindex_pack<stdx::parameter_pack<$".for/K/0/_AR_/VK/,">,stdx::parameter_pack<$".for/K/0/ArN/TBK/,"> >::value,bindex>::type
    operator()($".for/K/0/_AR_/VK const& argK/,") const{
      return (bindex)detail::ProductBinningImpl<stdm::tuple_size<bins_type>::value-1>::GetBinIndex(data,stdm::make_tuple($".for/K/0/_AR_/argK/,"));
    }
#pragma%%end.f/_AR_/1/ArN+1/
  };
#pragma%%end.i

#pragma%%x
  template<$".for/K/0/_AR_/typename BK/,"> typename mwg::stdm::enable_if<
    ($".for/K/0/_AR_/binning_concept<BK>::value/&&"),
    product_binning<$".for/K/0/_AR_/BK/,">
  >::type make_binning($".for/K/0/_AR_/const BK& bK/,"){
    return product_binning<$".for/K/0/_AR_/BK/,">($".for/K/0/_AR_/bK/,");
  }
#pragma%%end.f/_AR_/2/ArN+1/.i
#pragma%end /* end of if !variadic */

//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
}
}
#endif
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000-2002 The Apache Software Foundation.  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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#if !defined(ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680)
#define ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680

#include <ICUBridge/ICUBridgeDefinitions.hpp>

#include <list>

#include <XSLT/StylesheetExecutionContextDefault.hpp>

#include <unicode/coll.h>

XALAN_CPP_NAMESPACE_BEGIN

class XALAN_ICUBRIDGE_EXPORT ICUBridgeCollationCompareFunctorImpl : public StylesheetExecutionContextDefault::CollationCompareFunctor
{
public:

	typedef StylesheetExecutionContextDefault::eCaseOrder	eCaseOrder;

	/**
	 * Constructor.
	 *
	 * @param fCacheCollators If true, the instance will cache collators.  This is not thread-safe, so each thread must have its own instance.
	 */
	ICUBridgeCollationCompareFunctorImpl(bool	fCacheCollators = false);

	~ICUBridgeCollationCompareFunctorImpl();

	int
	operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS,
			eCaseOrder				theCaseOrder = StylesheetExecutionContextDefault::eDefault) const;

	int
	operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS,
			const XalanDOMChar*		theLocale,
			eCaseOrder				theCaseOrder = StylesheetExecutionContextDefault::eDefault) const;

	bool
	isValid() const
	{
		return m_isValid;
	}

#if defined(XALAN_HAS_CPP_NAMESPACE)
	typedef U_ICU_NAMESPACE::Collator	CollatorType;
#else
	typedef Collator					CollatorType;
#endif

	struct CollationCacheStruct
	{
		CollationCacheStruct(
				const XalanDOMString&	theLocale,
				CollatorType*			theCollator) :
			m_locale(theLocale),
			m_collator(theCollator)
		{
		}

		CollationCacheStruct() :
			m_locale(),
			m_collator(0)
		{
		}

		void
		swap(CollationCacheStruct&	theOther)
		{
			m_locale.swap(theOther.m_locale);

			CollatorType* const		theTemp = m_collator;

			m_collator = theOther.m_collator;

			theOther.m_collator = theTemp;
		}

		XalanDOMString	m_locale;

		CollatorType*	m_collator;

		struct CollatorDeleteFunctor
		{
			void
			operator()(CollationCacheStruct&	theStruct) const
			{
				delete theStruct.m_collator;
			}
		};

		struct CollatorFindFunctor
		{
			CollatorFindFunctor(const XalanDOMChar*	theLocale) :
				m_locale(theLocale)
			{
			}

			bool
			operator()(CollationCacheStruct&	theStruct) const
			{
				return XalanDOMString::equals(theStruct.m_locale ,m_locale);
			}

			const XalanDOMChar* const	m_locale;
		};
	};

#if defined(XALAN_NO_STD_NAMESPACE)
	typedef list<CollationCacheStruct>			CollatorCacheListType;
#else
	typedef std::list<CollationCacheStruct>		CollatorCacheListType;
#endif

	enum { eCacheMax = 10 };

private:

	int
	doDefaultCompare(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS) const;

	int
	doCompare(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS,
			const XalanDOMChar*		theLocale,
			eCaseOrder				theCaseOrder) const;

	int
	doCompareCached(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS,
			const XalanDOMChar*		theLocale,
			eCaseOrder				theCaseOrder) const;

	int
	doCompare(
			const CollatorType&		theCollator,
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS) const;

	int
	doCompare(
			CollatorType&			theCollator,
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS,
			eCaseOrder				theCaseOrder) const;

	CollatorType*
	getCachedCollator(const XalanDOMChar*	theLocale) const;

	void
	cacheCollator(
			CollatorType*			theCollator,
			const XalanDOMChar*		theLocale) const;

	// Data members...
	bool							m_isValid;

	CollatorType*					m_defaultCollator;

	XalanDOMString					m_defaultCollatorLocaleName;

	bool							m_cacheCollators;

	mutable CollatorCacheListType	m_collatorCache;

	const static StylesheetExecutionContextDefault::DefaultCollationCompareFunctor	s_defaultFunctor;
};

XALAN_CPP_NAMESPACE_END

#endif	// ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680
<commit_msg>Added operators for brain-dead compilers.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000-2002 The Apache Software Foundation.  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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#if !defined(ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680)
#define ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680

#include <ICUBridge/ICUBridgeDefinitions.hpp>

#include <list>

#include <XSLT/StylesheetExecutionContextDefault.hpp>

#include <unicode/coll.h>

XALAN_CPP_NAMESPACE_BEGIN

class XALAN_ICUBRIDGE_EXPORT ICUBridgeCollationCompareFunctorImpl : public StylesheetExecutionContextDefault::CollationCompareFunctor
{
public:

	typedef StylesheetExecutionContextDefault::eCaseOrder	eCaseOrder;

	/**
	 * Constructor.
	 *
	 * @param fCacheCollators If true, the instance will cache collators.  This is not thread-safe, so each thread must have its own instance.
	 */
	ICUBridgeCollationCompareFunctorImpl(bool	fCacheCollators = false);

	~ICUBridgeCollationCompareFunctorImpl();

	int
	operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS,
			eCaseOrder				theCaseOrder = StylesheetExecutionContextDefault::eDefault) const;

	int
	operator()(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS,
			const XalanDOMChar*		theLocale,
			eCaseOrder				theCaseOrder = StylesheetExecutionContextDefault::eDefault) const;

	bool
	isValid() const
	{
		return m_isValid;
	}

#if defined(XALAN_HAS_CPP_NAMESPACE)
	typedef U_ICU_NAMESPACE::Collator	CollatorType;
#else
	typedef Collator					CollatorType;
#endif

	struct CollationCacheStruct
	{
		CollationCacheStruct(
				const XalanDOMString&	theLocale,
				CollatorType*			theCollator) :
			m_locale(theLocale),
			m_collator(theCollator)
		{
		}

		CollationCacheStruct() :
			m_locale(),
			m_collator(0)
		{
		}

		void
		swap(CollationCacheStruct&	theOther)
		{
			m_locale.swap(theOther.m_locale);

			CollatorType* const		theTemp = m_collator;

			m_collator = theOther.m_collator;

			theOther.m_collator = theTemp;
		}

#if defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)
		bool
		operator<(const CollationCacheStruct&  theRHS) const
		{
			return this < &theRHS;
		}

		bool
		operator==(const CollationCacheStruct&	theRHS) const
		{
			return this == &theRHS;
		}
#endif

		XalanDOMString	m_locale;

		CollatorType*	m_collator;

		struct CollatorDeleteFunctor
		{
			void
			operator()(CollationCacheStruct&	theStruct) const
			{
				delete theStruct.m_collator;
			}
		};

		struct CollatorFindFunctor
		{
			CollatorFindFunctor(const XalanDOMChar*	theLocale) :
				m_locale(theLocale)
			{
			}

			bool
			operator()(CollationCacheStruct&	theStruct) const
			{
				return XalanDOMString::equals(theStruct.m_locale ,m_locale);
			}

			const XalanDOMChar* const	m_locale;
		};
	};

#if defined(XALAN_NO_STD_NAMESPACE)
	typedef list<CollationCacheStruct>			CollatorCacheListType;
#else
	typedef std::list<CollationCacheStruct>		CollatorCacheListType;
#endif

	enum { eCacheMax = 10 };

private:

	int
	doDefaultCompare(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS) const;

	int
	doCompare(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS,
			const XalanDOMChar*		theLocale,
			eCaseOrder				theCaseOrder) const;

	int
	doCompareCached(
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS,
			const XalanDOMChar*		theLocale,
			eCaseOrder				theCaseOrder) const;

	int
	doCompare(
			const CollatorType&		theCollator,
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS) const;

	int
	doCompare(
			CollatorType&			theCollator,
			const XalanDOMChar*		theLHS,
			const XalanDOMChar*		theRHS,
			eCaseOrder				theCaseOrder) const;

	CollatorType*
	getCachedCollator(const XalanDOMChar*	theLocale) const;

	void
	cacheCollator(
			CollatorType*			theCollator,
			const XalanDOMChar*		theLocale) const;

	// Data members...
	bool							m_isValid;

	CollatorType*					m_defaultCollator;

	XalanDOMString					m_defaultCollatorLocaleName;

	bool							m_cacheCollators;

	mutable CollatorCacheListType	m_collatorCache;

	const static StylesheetExecutionContextDefault::DefaultCollationCompareFunctor	s_defaultFunctor;
};

XALAN_CPP_NAMESPACE_END

#endif	// ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680
<|endoftext|>


<commit_before>#include "ros/ros.h"
#include "std_msgs/String.h"
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/LaserScan.h>
#include "EventTriggerConstants.h"
#include "PerformTaskConstants.h"
#include "elderly_care_simulation/PerformTask.h"

#include <sstream>
#include "math.h"

#include "DiceRollerTypeConstants.h"
#include "elderly_care_simulation/DiceRollTrigger.h"
#include "EventTriggerConstants.h"
#include "elderly_care_simulation/EventTrigger.h"
#include <unistd.h> // sleep

// Velocity
double linearX;
double angularZ;

// Pose
const double WORLD_POS_X = 0;
const double WORLD_POS_Y = 0;
double px;
double py;
double theta;

// Current task type: -1 corresponds to no task
int currentTaskType = -1;

// Basic health attributes
const int HEALTHY_THRESHOLD = 50;
int happiness = 0;
int amusement = 0;

// Signatures
ros::Publisher robotNodeStagePub;
ros::Subscriber stageOdoSub;
ros::Subscriber diceTriggerSub;
ros::Publisher residentEventPub;

// Locations to visit
std::queue<geometry_msgs::Point> locationQueue;

void stageOdomCallback(nav_msgs::Odometry msg);
void diceTriggerCallback();

void taskGetPerformed(const std_msgs::Empty){
	geometry_msgs::Point locationOne;
    locationOne.x = 0;
    locationOne.y = -2;

    geometry_msgs::Point locationTwo;
    locationTwo.x = 0;
    locationTwo.y = 2;

    geometry_msgs::Point locationThree;
    locationThree.x = 0;
    locationThree.y = 0;

    locationQueue.push(locationOne);
    locationQueue.push(locationTwo);
    locationQueue.push(locationThree);
}

/**
    Process odometry messages from Stage
*/
void stageOdomCallback(nav_msgs::Odometry msg) {

	px = WORLD_POS_X + msg.pose.pose.position.x;
	py = WORLD_POS_Y + msg.pose.pose.position.y;
	// ROS_INFO("Current x position is: %f", px);
	// ROS_INFO("Current y position is: %f", py);
}

void diceTriggerCallback(elderly_care_simulation::DiceRollTrigger msg) {
    elderly_care_simulation::EventTrigger msgOut;
    msgOut.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST;
    msgOut.result = EVENT_TRIGGER_RESULT_FAILURE;

    switch(msg.type) {
        case MORAL_SUPPORT:
            ROS_INFO("I really need moral support right now ...");
            msgOut.event_type = EVENT_TRIGGER_EVENT_TYPE_VISITOR;
            break;
        case ENTERTAINMENT:
			ROS_INFO("I really need some entertainment ...");
			msgOut.event_type = EVENT_TRIGGER_EVENT_TYPE_ASSISTANT;
			break;
    }

    ROS_INFO("Sending request to scheduler");
    residentEventPub.publish(msgOut);
}

/**
 * Change the resident's state in response to a task that is being performed
 * by a helper.
 *
 * At this stage, it is assumed for simplicity that the visitor is
 * consoling and the assistant is entertaining. TODO: In a later release
 * there will be many other types of task.
 *
 * @param taskType the type of task that is being performed
 * @return PERFORM_TASK_RESULT_ACCEPTED or PERFORM_TASK_RESULT_FINISHED
 *         (which correspond to 0 and 1 respectively)
 */
int handleTask(int taskType) {
	int result;

	switch (taskType) {
		case EVENT_TRIGGER_EVENT_TYPE_VISITOR:
			// The visitor is consoling us
			happiness += 1;
			if (happiness > HEALTHY_THRESHOLD) {
				ROS_INFO("Happiness raised to %d and I'm now happy as can be!", happiness);
				result = PERFORM_TASK_RESULT_FINISHED;
				currentTaskType = NO_CURRENT_TASK;
			} else {
				ROS_INFO("Happiness raised to %d, but I could still do with some more consoling...", happiness);
				result = PERFORM_TASK_RESULT_ACCEPTED;
			}
			break;
		case EVENT_TRIGGER_EVENT_TYPE_ASSISTANT:
			// The assistant is entertaining us
			amusement += 1;
			if (amusement > HEALTHY_THRESHOLD) {
				ROS_INFO("Amusement raised to %d and I've had enough!", amusement);
				result = PERFORM_TASK_RESULT_FINISHED;
				currentTaskType = NO_CURRENT_TASK;
			} else {
				ROS_INFO("Amusement raised to %d, keep being funny.", amusement);
				result = PERFORM_TASK_RESULT_ACCEPTED;
			}
		    break;
	}

	return result;
}

/**
 * Handler for PerformTask.srv service
 *
 * Robots and Visitors use this to perform tasks on the resident.
 *
 * In the request there will be an event type. The resident will check
 * if this corresponds to the type of event they are currently accepting.
 *
 * Based on this the response will contain one of the following codes:
 *   0 - I accepted the task and updated my state
 *   1 - I accepted the task and you can now stop
 *   2 - I am busy at the moment, try again
 */
bool performTaskServiceHandler(elderly_care_simulation::PerformTask::Request &req,
				   elderly_care_simulation::PerformTask::Response &res) {

	ROS_INFO("Received service call with task type: %d", req.taskType);

	if (currentTaskType == NO_CURRENT_TASK) {
		// I don't yet have a task, make this one our current task
		currentTaskType = req.taskType;
	}

	if (req.taskType == currentTaskType) {
		// We must be dealing with the current helper
		res.result = handleTask(req.taskType);
	} else {
		// We are busy with another task
		res.result = PERFORM_TASK_RESULT_BUSY;
	}

	return true;
}

/**
    Process
*/

int main(int argc, char **argv) {

    // ROS initialiser calls
    ros::init(argc, argv, "Resident");
    ros::NodeHandle nodeHandle;
    ros::Rate loop_rate(10);

    // Initialise pose (must be same as world file)
	theta = M_PI/2.0;
	px = WORLD_POS_X;
	py = WORLD_POS_Y;

	// Initialise velocity
	linearX = 0.0;
	angularZ = 0.0;

    // Initialise publishers
    robotNodeStagePub = nodeHandle.advertise<geometry_msgs::Twist>("robot_0/cmd_vel",1000);
    residentEventPub = nodeHandle.advertise<elderly_care_simulation::EventTrigger>("resident_event",1000, true);

    // Initialise subscribers
    stageOdoSub = nodeHandle.subscribe<nav_msgs::Odometry>("robot_0/odom", 1000, stageOdomCallback);
    diceTriggerSub = nodeHandle.subscribe<elderly_care_simulation::DiceRollTrigger>("dice_roll_trigger", 1000, diceTriggerCallback);

    // Initialise messages
    geometry_msgs::Twist robotNodeCmdvel;

    // Advertise that the Resident responds to PerformTask service calls
	ros::ServiceServer service = nodeHandle.advertiseService("perform_task", performTaskServiceHandler);

	//a count of howmany messages we have sent
	int count = 0;

	while (ros::ok())
	{
		// Publish to Stage
		robotNodeCmdvel.linear.x = linearX;
		robotNodeCmdvel.angular.z = angularZ;
		robotNodeStagePub.publish(robotNodeCmdvel);

		// Every once in a while, decrease health values
		if (count % 50 == 0) {
			// Every 5 secs

			amusement = (amusement - 15) > 0 ? amusement - 15 : 0;
			ROS_INFO("Amusement level fell to %d", amusement);

			happiness = (happiness - 10) > 0 ? happiness - 10 : 0;
			ROS_INFO("Happiness level fell to %d", happiness);
		}

		ros::spinOnce();

		loop_rate.sleep();
		++count;
	}

    return 0;

}
<commit_msg>Modified stageOdomCallback to get the current location and translate Quaternion to roll pitch and yaw<commit_after>#include "ros/ros.h"
#include "std_msgs/String.h"
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/LaserScan.h>
#include "EventTriggerConstants.h"
#include "PerformTaskConstants.h"
#include "elderly_care_simulation/PerformTask.h"
#include <queue>
#include <tf/tf.h>
#include "std_msgs/Empty.h"

#include <sstream>
#include "math.h"

#include "DiceRollerTypeConstants.h"
#include "elderly_care_simulation/DiceRollTrigger.h"
#include "EventTriggerConstants.h"
#include "elderly_care_simulation/EventTrigger.h"
#include <unistd.h> // sleep

// Current task type: -1 corresponds to no task
int currentTaskType = -1;

// Basic health attributes
const int HEALTHY_THRESHOLD = 50;
int happiness = 0;
int amusement = 0;

// Signatures
ros::Publisher robotNodeStagePub;
ros::Subscriber stageOdoSub;
ros::Subscriber diceTriggerSub;
ros::Publisher residentEventPub;
ros::Subscriber locationInstructionsSub;
ros::Subscriber pathOfResidentSub;

double currentAngle;

// Current velocity of the Robot
geometry_msgs::Twist currentVelocity;

// Current location of the robot
geometry_msgs::Pose currentLocation;

// Locations to visit
std::queue<geometry_msgs::Point> locationQueue;

void stageOdomCallback(nav_msgs::Odometry msg);
void diceTriggerCallback();

void taskGetPerformed(const std_msgs::Empty){
	geometry_msgs::Point locationOne;
    locationOne.x = 0;
    locationOne.y = -2;

    geometry_msgs::Point locationTwo;
    locationTwo.x = 0;
    locationTwo.y = 2;

    geometry_msgs::Point locationThree;
    locationThree.x = 0;
    locationThree.y = 0;

    locationQueue.push(locationOne);
    locationQueue.push(locationTwo);
    locationQueue.push(locationThree);
}

/**
    Process odometry messages from Stage
*/
void stageOdomCallback(const nav_msgs::Odometry msg) {

	 //Update Current Position
    currentLocation = msg.pose.pose;
    double x = currentLocation.orientation.x;
    double y = currentLocation.orientation.y;
    double z = currentLocation.orientation.z;
    double w = currentLocation.orientation.w;
    ROS_INFO("THE LOCATION IS: %f, %f", currentLocation.position.x, currentLocation.position.y);
    double roll, pitch, yaw;
    tf::Matrix3x3(tf::Quaternion(x, y, z, w)).getRPY(roll, pitch, yaw);
    currentAngle = yaw;

}

void diceTriggerCallback(elderly_care_simulation::DiceRollTrigger msg) {
    elderly_care_simulation::EventTrigger msgOut;
    msgOut.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST;
    msgOut.result = EVENT_TRIGGER_RESULT_FAILURE;

    switch(msg.type) {
        case MORAL_SUPPORT:
            ROS_INFO("I really need moral support right now ...");
            msgOut.event_type = EVENT_TRIGGER_EVENT_TYPE_VISITOR;
            break;
        case ENTERTAINMENT:
			ROS_INFO("I really need some entertainment ...");
			msgOut.event_type = EVENT_TRIGGER_EVENT_TYPE_ASSISTANT;
			break;
    }

    ROS_INFO("Sending request to scheduler");
    residentEventPub.publish(msgOut);
}

/**
 * Change the resident's state in response to a task that is being performed
 * by a helper.
 *
 * At this stage, it is assumed for simplicity that the visitor is
 * consoling and the assistant is entertaining. TODO: In a later release
 * there will be many other types of task.
 *
 * @param taskType the type of task that is being performed
 * @return PERFORM_TASK_RESULT_ACCEPTED or PERFORM_TASK_RESULT_FINISHED
 *         (which correspond to 0 and 1 respectively)
 */
int handleTask(int taskType) {
	int result;

	switch (taskType) {
		case EVENT_TRIGGER_EVENT_TYPE_VISITOR:
			// The visitor is consoling us
			happiness += 1;
			if (happiness > HEALTHY_THRESHOLD) {
				ROS_INFO("Happiness raised to %d and I'm now happy as can be!", happiness);
				result = PERFORM_TASK_RESULT_FINISHED;
				currentTaskType = NO_CURRENT_TASK;
			} else {
				ROS_INFO("Happiness raised to %d, but I could still do with some more consoling...", happiness);
				result = PERFORM_TASK_RESULT_ACCEPTED;
			}
			break;
		case EVENT_TRIGGER_EVENT_TYPE_ASSISTANT:
			// The assistant is entertaining us
			amusement += 1;
			if (amusement > HEALTHY_THRESHOLD) {
				ROS_INFO("Amusement raised to %d and I've had enough!", amusement);
				result = PERFORM_TASK_RESULT_FINISHED;
				currentTaskType = NO_CURRENT_TASK;
			} else {
				ROS_INFO("Amusement raised to %d, keep being funny.", amusement);
				result = PERFORM_TASK_RESULT_ACCEPTED;
			}
		    break;
	}

	return result;
}

/**
 * Handler for PerformTask.srv service
 *
 * Robots and Visitors use this to perform tasks on the resident.
 *
 * In the request there will be an event type. The resident will check
 * if this corresponds to the type of event they are currently accepting.
 *
 * Based on this the response will contain one of the following codes:
 *   0 - I accepted the task and updated my state
 *   1 - I accepted the task and you can now stop
 *   2 - I am busy at the moment, try again
 */
bool performTaskServiceHandler(elderly_care_simulation::PerformTask::Request &req,
				   elderly_care_simulation::PerformTask::Response &res) {

	ROS_INFO("Received service call with task type: %d", req.taskType);

	if (currentTaskType == NO_CURRENT_TASK) {
		// I don't yet have a task, make this one our current task
		currentTaskType = req.taskType;
	}

	if (req.taskType == currentTaskType) {
		// We must be dealing with the current helper
		res.result = handleTask(req.taskType);
	} else {
		// We are busy with another task
		res.result = PERFORM_TASK_RESULT_BUSY;
	}

	return true;
}

/**
    Process
*/

int main(int argc, char **argv) {

    // ROS initialiser calls
    ros::init(argc, argv, "Resident");
    ros::NodeHandle nodeHandle;
    ros::Rate loop_rate(10);

    // Initialise pose (must be same as world file)
	theta = M_PI/2.0;
	px = WORLD_POS_X;
	py = WORLD_POS_Y;

	// Initialise velocity
	linearX = 0.0;
	angularZ = 0.0;

    // Initialise publishers
    robotNodeStagePub = nodeHandle.advertise<geometry_msgs::Twist>("robot_0/cmd_vel",1000);
    residentEventPub = nodeHandle.advertise<elderly_care_simulation::EventTrigger>("resident_event",1000, true);

    // Initialise subscribers
    stageOdoSub = nodeHandle.subscribe<nav_msgs::Odometry>("robot_0/odom", 1000, stageOdomCallback);
    diceTriggerSub = nodeHandle.subscribe<elderly_care_simulation::DiceRollTrigger>("dice_roll_trigger", 1000, diceTriggerCallback);

    // Initialise messages
    geometry_msgs::Twist robotNodeCmdvel;

    // Advertise that the Resident responds to PerformTask service calls
	ros::ServiceServer service = nodeHandle.advertiseService("perform_task", performTaskServiceHandler);

	//a count of howmany messages we have sent
	int count = 0;

	while (ros::ok())
	{
		// Publish to Stage
		robotNodeCmdvel.linear.x = linearX;
		robotNodeCmdvel.angular.z = angularZ;
		robotNodeStagePub.publish(robotNodeCmdvel);

		// Every once in a while, decrease health values
		if (count % 50 == 0) {
			// Every 5 secs

			amusement = (amusement - 15) > 0 ? amusement - 15 : 0;
			ROS_INFO("Amusement level fell to %d", amusement);

			happiness = (happiness - 10) > 0 ? happiness - 10 : 0;
			ROS_INFO("Happiness level fell to %d", happiness);
		}

		ros::spinOnce();

		loop_rate.sleep();
		++count;
	}

    return 0;

}
<|endoftext|>


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

#include "boost/python.hpp"

#include "IECore/CompoundObject.h"
#include "IECore/ParameterisedProcedural.h"

#include "IECoreHoudini/FromHoudiniCortexObjectConverter.h"
#include "IECoreHoudini/GU_CortexPrimitive.h"

using namespace IECore;
using namespace IECoreHoudini;

IE_CORE_DEFINERUNTIMETYPED( FromHoudiniCortexObjectConverter );

FromHoudiniGeometryConverter::Description<FromHoudiniCortexObjectConverter> FromHoudiniCortexObjectConverter::m_description( ObjectTypeId );
FromHoudiniGeometryConverter::Description<FromHoudiniCortexObjectConverter> FromHoudiniCortexObjectConverter::m_universalDescription( InvalidTypeId );

FromHoudiniCortexObjectConverter::FromHoudiniCortexObjectConverter( const GU_DetailHandle &handle ) :
	FromHoudiniGeometryConverter( handle, "Converts a Houdini GU_Detail to an IECore::Object." )
{
}

FromHoudiniCortexObjectConverter::FromHoudiniCortexObjectConverter( const SOP_Node *sop ) :
	FromHoudiniGeometryConverter( sop, "Converts a Houdini GU_Detail to an IECore::Object." )
{
}

FromHoudiniCortexObjectConverter::~FromHoudiniCortexObjectConverter()
{
}

FromHoudiniGeometryConverter::Convertability FromHoudiniCortexObjectConverter::canConvert( const GU_Detail *geo )
{
	size_t numPrims = geo->getNumPrimitives();
	if ( numPrims )
	{
		const GA_Primitive *prim = geo->getPrimitiveList().get( geo->getPrimitiveRange().begin().getOffset() );
		if ( prim->getTypeId() == GU_CortexPrimitive::typeId() )
		{
			return ( numPrims == 1 ) ? Ideal : Admissible;
		}
	}

	return Inapplicable;
}

ObjectPtr FromHoudiniCortexObjectConverter::doDetailConversion( const GU_Detail *geo, const CompoundObject *operands ) const
{
	const GA_Primitive *prim = geo->getPrimitiveList().get( geo->getPrimitiveRange().begin().getOffset() );
	if ( prim->getTypeId() != GU_CortexPrimitive::typeId() )
	{
		throw std::runtime_error( "FromHoudiniCortexObjectConverter: Geometry does not contain a single CortexObject primitive" );
	}

	ConstObjectPtr object = ((GU_CortexPrimitive *)prim)->getObject();
	ObjectPtr result = filterAttribs( object, operands->member<StringData>( "attributeFilter" )->readable().c_str() );

	if ( result )
	{
		return result;
	}

	if ( object )
	{
		if ( object->isInstanceOf( IECore::ParameterisedProcedural::staticTypeId() ) )
		{
			return IECore::constPointerCast<IECore::Object>( object );
		}

		return object->copy();
	}

	return 0;
}

ObjectPtr FromHoudiniCortexObjectConverter::filterAttribs( const Object *object, const char *filter ) const
{
	const Primitive *primitive = IECore::runTimeCast<const Primitive>( object );
	if ( !primitive )
	{
		return 0;
	}

	std::vector<InternedString> variablesToErase;
	const PrimitiveVariableMap &variables = primitive->variables;
	for ( PrimitiveVariableMap::const_iterator it = variables.begin(); it != variables.end(); ++it )
	{
		if ( !UT_String( it->first ).multiMatch( filter ) )
		{
			variablesToErase.push_back( it->first );
		}
	}

	if ( variablesToErase.empty() )
	{
		return 0;
	}

	PrimitivePtr result = primitive->copy();
	PrimitiveVariableMap &resultVariables = result->variables;
	for ( size_t i = 0; i < variablesToErase.size(); ++i )
	{
		resultVariables.erase( variablesToErase[i] );
	}

	return result;
}
<commit_msg>FromHoudiniCortexObjectConverter rejects multiple primitives<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "IECore/CompoundObject.h"
#include "IECore/ParameterisedProcedural.h"

#include "IECoreHoudini/FromHoudiniCortexObjectConverter.h"
#include "IECoreHoudini/GU_CortexPrimitive.h"

using namespace IECore;
using namespace IECoreHoudini;

IE_CORE_DEFINERUNTIMETYPED( FromHoudiniCortexObjectConverter );

FromHoudiniGeometryConverter::Description<FromHoudiniCortexObjectConverter> FromHoudiniCortexObjectConverter::m_description( ObjectTypeId );
FromHoudiniGeometryConverter::Description<FromHoudiniCortexObjectConverter> FromHoudiniCortexObjectConverter::m_universalDescription( InvalidTypeId );

FromHoudiniCortexObjectConverter::FromHoudiniCortexObjectConverter( const GU_DetailHandle &handle ) :
	FromHoudiniGeometryConverter( handle, "Converts a Houdini GU_Detail to an IECore::Object." )
{
}

FromHoudiniCortexObjectConverter::FromHoudiniCortexObjectConverter( const SOP_Node *sop ) :
	FromHoudiniGeometryConverter( sop, "Converts a Houdini GU_Detail to an IECore::Object." )
{
}

FromHoudiniCortexObjectConverter::~FromHoudiniCortexObjectConverter()
{
}

FromHoudiniGeometryConverter::Convertability FromHoudiniCortexObjectConverter::canConvert( const GU_Detail *geo )
{
	size_t numPrims = geo->getNumPrimitives();
	if ( numPrims == 1 )
	{
		const GA_Primitive *prim = geo->getPrimitiveList().get( geo->getPrimitiveRange().begin().getOffset() );
		if ( prim->getTypeId() == GU_CortexPrimitive::typeId() )
		{
			return Ideal;
		}
	}

	return Inapplicable;
}

ObjectPtr FromHoudiniCortexObjectConverter::doDetailConversion( const GU_Detail *geo, const CompoundObject *operands ) const
{
	const GA_Primitive *prim = geo->getPrimitiveList().get( geo->getPrimitiveRange().begin().getOffset() );
	if ( prim->getTypeId() != GU_CortexPrimitive::typeId() )
	{
		throw std::runtime_error( "FromHoudiniCortexObjectConverter: Geometry does not contain a single CortexObject primitive" );
	}

	ConstObjectPtr object = ((GU_CortexPrimitive *)prim)->getObject();
	ObjectPtr result = filterAttribs( object, operands->member<StringData>( "attributeFilter" )->readable().c_str() );

	if ( result )
	{
		return result;
	}

	if ( object )
	{
		if ( object->isInstanceOf( IECore::ParameterisedProcedural::staticTypeId() ) )
		{
			return IECore::constPointerCast<IECore::Object>( object );
		}

		return object->copy();
	}

	return 0;
}

ObjectPtr FromHoudiniCortexObjectConverter::filterAttribs( const Object *object, const char *filter ) const
{
	const Primitive *primitive = IECore::runTimeCast<const Primitive>( object );
	if ( !primitive )
	{
		return 0;
	}

	std::vector<InternedString> variablesToErase;
	const PrimitiveVariableMap &variables = primitive->variables;
	for ( PrimitiveVariableMap::const_iterator it = variables.begin(); it != variables.end(); ++it )
	{
		if ( !UT_String( it->first ).multiMatch( filter ) )
		{
			variablesToErase.push_back( it->first );
		}
	}

	if ( variablesToErase.empty() )
	{
		return 0;
	}

	PrimitivePtr result = primitive->copy();
	PrimitiveVariableMap &resultVariables = result->variables;
	for ( size_t i = 0; i < variablesToErase.size(); ++i )
	{
		resultVariables.erase( variablesToErase[i] );
	}

	return result;
}
<|endoftext|>


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

#include "../libmem.h"

/*
 * libmem_test.cc
 *
 *  Created on: Oct 19, 2015
 *  @author Mike McGee
 */

//Main method that will test the execution of the libmem api
int main (int argc, char**argv) {
  // Use libmem to send a message to the server.

  //1. Connect to server [Test server is port 3490]
  int sock_fd = libmem::Connect(3490, "localhost", "");
  std::cout << "Connected" << std::endl;
  //2. Execute a SQLCommand
  libmem::ResultSet result_set = libmem::ExecuteSQL("SELECT * FROM Users",
                                                     sock_fd);

  for (int i = 0, j = result_set.get_size(); i < j; ++i) {
    libmem::ResultRow current_row = result_set.get_next_row();
    std::vector<libmem::ResultPair> cur_vec = current_row.m_result_row;
    for (int k = 0, n = current_row.m_result_row.size(); k < n; ++k){
      std::cout << "Name :" << cur_vec.at(k).get_name();
      std::cout << "Value: " << cur_vec.at(k).get_value() << std::endl;
    }
  }

  std::cout << "Executed command" << std::endl;
  //3.Disconnect from database.
  libmem::Disconnect(sock_fd);
  std::cout << "Disconnected" << std::endl;

  return 0;
}

<commit_msg>Updated for loop again<commit_after>/*
The MIT License (MIT)
Copyright (c) 2015 University of Central Florida's Computer Software Engineering
Scalable & Secure Systems (CSE - S3) Lab
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "../libmem.h"

/*
 * libmem_test.cc
 *
 *  Created on: Oct 19, 2015
 *  @author Mike McGee
 */

//Main method that will test the execution of the libmem api
int main (int argc, char**argv) {
  // Use libmem to send a message to the server.

  //1. Connect to server [Test server is port 3490]
  int sock_fd = libmem::Connect(3490, "localhost", "");
  std::cout << "Connected" << std::endl;
  //2. Execute a SQLCommand
  libmem::ResultSet result_set = libmem::ExecuteSQL("SELECT * FROM Users",
                                                     sock_fd);

 // for (int i = 0, j = result_set.get_size(); i < j; ++i) {
  //  libmem::ResultRow current_row = result_set.get_next_row();
  //  std::vector<libmem::ResultPair> cur_vec = current_row.m_result_row;
  //  for (int k = 0, n = current_row.m_result_row.size(); k < n; ++k){
  //    std::cout << "Name :" << cur_vec.at(k).get_name();
//      std::cout << "Value: " << cur_vec.at(k).get_value() << std::endl;
    //}
  //}

  libmem::ResultRow row;
  for (int i = 0; i < result_set.get_size(); ++i) {
    row = result_set.get_next_row();
    for (auto pair: row.m_result_row) {
      std::cout << "Name: " << pair.get_name();
      std::cout << "Value: " << pair.get_value();
    }
  }

  std::cout << "Executed command" << std::endl;
  //3.Disconnect from database.
  libmem::Disconnect(sock_fd);
  std::cout << "Disconnected" << std::endl;

  return 0;
}

<|endoftext|>


<commit_before>#include <DO/Geometry/Objects/Ellipse.hpp>
#include <DO/Geometry/Objects/Triangle.hpp>
#include <DO/Geometry/Tools/Utilities.hpp>

#include "TestPolygon.hpp"

using namespace DO;
using namespace std;

class TestEllipse : public TestPolygon
{
protected:
  TestEllipse() : TestPolygon()
  {
    _width = 300;
    _height = 300;
  }
};

TEST_F(TestEllipse, test_segment_area)
{
  Ellipse E(270, 150, to_radian(42.), Point2d::Zero());

  try
  {
    int steps = 18;

    for (int i0 = 0; i0 <= steps; ++i0)
    {
      double theta0 = i0*2*M_PI/steps;
      for (int i1 = i0+1; i1 < i0+steps; ++i1)
      {
        double theta1 = i1*2*M_PI/steps;

        const Point2d a(E(theta0));
        const Point2d b(E(theta1));
        const Point2d& o = E.center();
        Triangle t(o, a, b);

        auto inside_segment = [&](const Point2d& p) -> bool {
          return (ccw(a,b,p) == -1) && inside(p, E);
        };

        double segArea1 = sweep_count_pixels(inside_segment);
        double segArea2 = segment_area(E, theta0, theta1);

        double absError = fabs(segArea1 -segArea2);
        double relError = absError/segArea1;

        const double thres = 0.1;
        EXPECT_NEAR(relError, 0, thres);
#if 0
        if (relError > thres)
        {
          printStage("Numerical error");
          CHECK(i0);
          CHECK(i1);
          CHECK(toDegree(theta0));
          CHECK(toDegree(theta1));
          CHECK(segArea1);
          CHECK(segArea2);
          CHECK(relError);
          getKey();
        }
#endif
      }
    }
  }
  catch (exception& e)
  {
    cout << e.what() << endl;
  }

}

int main(int argc, char **argv)
{
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}<commit_msg>Restructure ellipse unit tests.<commit_after>#include <DO/Core.hpp>
#include <DO/Geometry/Objects/Cone.hpp>
#include <DO/Geometry/Objects/CSG.hpp>
#include <DO/Geometry/Objects/Ellipse.hpp>
#include <DO/Geometry/Objects/Triangle.hpp>
#include <DO/Geometry/Tools/Utilities.hpp>

#include "TestPolygon.hpp"

using namespace DO;
using namespace std;

class TestEllipse : public TestPolygon
{
protected:
  TestEllipse() : TestPolygon()
  {
    _width = 300;
    _height = 300;
  }
};

// TODO: make test faster. TOO SLOW!!!
TEST_F(TestEllipse, DISABLED_test_sector_area)
{
  Ellipse E(250, 150, to_radian(75.), _center);

  CSG::Singleton<Ellipse> ell(E);

  try {

    int steps = 18;
    for (int i0 = 0; i0 <= steps; ++i0)
    {
      double theta0 = i0*2*M_PI/steps;
      for (int i1 = i0+1; i1 <= i0+steps; ++i1)
      {
        double theta1 = i1*2*M_PI/steps;

        // Compute the sector area in a closed form.
        double analyticSectorArea = sector_area(E, theta0, theta1);

        // Build constructive solid geometry.
        CSG::Singleton<AffineCone2> cone ( affine_cone2(
          theta0+E.orientation(), theta1+E.orientation(), E.center()) );
        auto E_and_Cone = ell*cone;
        auto E_minus_Cone = ell - E_and_Cone;

        // Use the CSGs to estimate the sector area by pixel counting.
        auto inside_E_and_Cone = [&](const Point2d& p){
          return E_and_Cone.contains(p);
        };
        auto inside_E_minus_Cone = [&](const Point2d& p){
          return E_minus_Cone.contains(p);
        };

        // Use the lambda functors to estimate the elliptic sector area.
        int estimated_sector_area;
        if (i1 - i0 < steps/2)
          estimated_sector_area = sweep_count_pixels(inside_E_and_Cone);
        else if (abs(i1-i0) == steps/2)
          estimated_sector_area = area(E) / 2.;
        else
          estimated_sector_area = sweep_count_pixels(inside_E_minus_Cone);

        // Absolute error and relative error.
        double abs_error = fabs(estimated_sector_area -analyticSectorArea);
        double rel_error = abs_error/estimated_sector_area;

        double thres = 1e-1;
        EXPECT_NEAR(rel_error, 0, thres);
        if (rel_error > thres)
        {
          printStage("Numerical error");
          cout << i0 << "     " << i1 << endl;
          CHECK(abs(i1-i0));
          CHECK(analytic_sector_area);
          CHECK(estimated_sector_area);
          CHECK(abs_error);
          CHECK(rel_error);
        }
      }
    }
  }
  catch (exception& e)
  {
    cout << e.what() << endl;
  }
}

// TODO: make test faster. TOO SLOW!!!
TEST_F(TestEllipse, DISABLED_test_segment_area)
{
  Ellipse E(270, 150, to_radian(42.), Point2d::Zero());

  try
  {
    int steps = 18;

    for (int i0 = 0; i0 <= steps; ++i0)
    {
      double theta0 = i0*2*M_PI/steps;
      for (int i1 = i0+1; i1 < i0+steps; ++i1)
      {
        double theta1 = i1*2*M_PI/steps;

        const Point2d a(E(theta0));
        const Point2d b(E(theta1));
        const Point2d& o = E.center();
        Triangle t(o, a, b);

        auto inside_segment = [&](const Point2d& p) -> bool {
          return (ccw(a,b,p) == -1) && inside(p, E);
        };

        double segArea1 = sweep_count_pixels(inside_segment);
        double segArea2 = segment_area(E, theta0, theta1);

        double absError = fabs(segArea1 -segArea2);
        double relError = absError/segArea1;

        const double thres = 0.1;
        EXPECT_NEAR(relError, 0, thres);
        if (relError > thres)
        {
          printStage("Numerical error");
          CHECK(i0);
          CHECK(i1);
          CHECK(to_degree(theta0));
          CHECK(to_degree(theta1));
          CHECK(segArea1);
          CHECK(segArea2);
          CHECK(relError);
        }
      }
    }
  }
  catch (exception& e)
  {
    cout << e.what() << endl;
  }

}

int main(int argc, char **argv)
{
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ed_ioleobject.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: kz $ $Date: 2006-10-06 10:38:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "embeddoc.hxx"

#ifndef _OSL_DIAGNOSE_H_
#include <ols/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_FRAME_XController_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

using namespace ::com::sun::star;

extern ::rtl::OUString  getFilterNameFromGUID_Impl( GUID* );

//-------------------------------------------------------------------------------
// IOleObject

STDMETHODIMP EmbedDocument_Impl::SetClientSite( IOleClientSite* pSite )
{
    m_pClientSite = pSite;
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::GetClientSite( IOleClientSite** pSite )
{
    *pSite = m_pClientSite;
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::SetHostNames( LPCOLESTR szContainerApp, LPCOLESTR szContainerObj )
{
    m_pDocHolder->setTitle(
        rtl::OUString(
            (sal_Unicode*)szContainerObj));
    m_pDocHolder->setContainerName(
        rtl::OUString(
            (sal_Unicode*)szContainerApp));
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::Close( DWORD dwSaveOption )
{
    HRESULT hr = S_OK;

    if ( dwSaveOption && m_pClientSite )
        hr = SaveObject(); // ADVF_DATAONSTOP);

    m_pDocHolder->CloseFrame();

    if ( m_pClientSite )
        m_pClientSite->OnShowWindow( FALSE );

    AdviseSinkHashMap aAHM(m_aAdviseHashMap);

    for ( AdviseSinkHashMapIterator iAdvise = aAHM.begin();
          iAdvise != aAHM.end(); iAdvise++ )
    {
        if ( iAdvise->second )
            iAdvise->second->OnClose();
    }

    return hr;
}

STDMETHODIMP EmbedDocument_Impl::SetMoniker( DWORD /*dwWhichMoniker*/, IMoniker * /*pmk*/ )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetMoniker( DWORD /*dwAssign*/, DWORD /*dwWhichMoniker*/, IMoniker ** /*ppmk*/ )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::InitFromData( IDataObject * /*pDataObject*/, BOOL /*fCreation*/, DWORD /*dwReserved*/ )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetClipboardData( DWORD /*dwReserved*/, IDataObject ** /*ppDataObject*/ )
{
    return E_NOTIMPL;
}

/**
 *  Well, this is a not so very inefficient way to deliver
 *
 */

STDMETHODIMP EmbedDocument_Impl::DoVerb(
    LONG iVerb,
    LPMSG,
    IOleClientSite *pActiveSite,
    LONG,
    HWND,
    LPCRECT )
{
    // no locking is used since the OLE must use the same thread always
    if ( m_bIsInVerbHandling )
        return OLEOBJ_S_CANNOT_DOVERB_NOW;

    BooleanGuard_Impl aGuard( m_bIsInVerbHandling );

    switch(iVerb) {
        case OLEIVERB_DISCARDUNDOSTATE:
            // free any undostate?
            break;
        case OLEIVERB_INPLACEACTIVATE:
            OSL_ENSURE(m_pDocHolder,"no document for inplace activation");

            return m_pDocHolder->InPlaceActivate(pActiveSite,FALSE);
            break;
        case OLEIVERB_UIACTIVATE:
            OSL_ENSURE(m_pDocHolder,"no document for     inplace activation");

            return m_pDocHolder->InPlaceActivate(pActiveSite,TRUE);
            break;
        case OLEIVERB_PRIMARY:
        case OLEIVERB_SHOW:
            OSL_ENSURE(m_pDocHolder,"no document for inplace activation");

            if(m_pDocHolder->isActive())
                return NOERROR; //Already active

            if(SUCCEEDED(
                m_pDocHolder->InPlaceActivate(
                    pActiveSite,TRUE)))
                return NOERROR;

            // intended fall trough
        case OLEIVERB_OPEN:
            OSL_ENSURE(m_pDocHolder,"no document to open");

            // the commented code could be usefull in case
            // outer window would be resized depending from inner one
            // RECTL aEmbArea;
            // m_pDocHolder->GetVisArea( &aEmbArea );
            // m_pDocHolder->show();
            // m_pDocHolder->SetVisArea( &aEmbArea );

            if(m_pDocHolder->isActive())
            {
                m_pDocHolder->InPlaceDeactivate();
                m_pDocHolder->DisableInplaceActivation(true);
            }

            SIZEL aEmbSize;
            m_pDocHolder->GetExtent( &aEmbSize );
            m_pDocHolder->show();
            m_pDocHolder->resizeWin( aEmbSize );

            if ( m_pClientSite )
                m_pClientSite->OnShowWindow( TRUE );

            notify();
            break;
        case OLEIVERB_HIDE:
            OSL_ENSURE(m_pDocHolder,"no document to hide");

            if(m_pDocHolder->isActive())
                m_pDocHolder->InPlaceDeactivate();
            else {
                m_pDocHolder->hide();

                if( m_pClientSite )
                    m_pClientSite->OnShowWindow(FALSE);
            }
            break;
        default:
            break;
    }

    return NOERROR;
}

STDMETHODIMP EmbedDocument_Impl::EnumVerbs( IEnumOLEVERB ** /*ppEnumOleVerb*/ )
{
    return OLE_S_USEREG;
}

STDMETHODIMP EmbedDocument_Impl::Update()
{
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::IsUpToDate()
{
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::GetUserClassID( CLSID *pClsid )
{
    return GetClassID( pClsid );
}

STDMETHODIMP EmbedDocument_Impl::GetUserType( DWORD /*dwFormOfTypeUe*/, LPOLESTR * /*pszUserType*/ )
{
    return OLE_S_USEREG;
}

STDMETHODIMP EmbedDocument_Impl::SetExtent( DWORD /*dwDrawAspect*/, SIZEL *psizel )
{
    if ( !psizel )
        return E_FAIL;

    m_pDocHolder->SetExtent( psizel );

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::GetExtent( DWORD /*dwDrawAspect*/, SIZEL * psizel )
{
    if ( !psizel )
        return E_INVALIDARG;

    if ( FAILED( m_pDocHolder->GetExtent( psizel ) ) )
    {
        // return default values
        psizel->cx = 500;
        psizel->cy = 500;
    }

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::Advise( IAdviseSink *pAdvSink, DWORD *pdwConnection )
{
    if ( m_nAdviseNum == 0xFFFFFFFF )
        return E_OUTOFMEMORY;

    pAdvSink->AddRef();
    m_aAdviseHashMap.insert( ::std::pair< DWORD, IAdviseSink* >( m_nAdviseNum, pAdvSink ) );
    *pdwConnection = m_nAdviseNum++;

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::Unadvise( DWORD dwConnection )
{
    AdviseSinkHashMapIterator iAdvise = m_aAdviseHashMap.find( dwConnection );
    if ( iAdvise != m_aAdviseHashMap.end() )
    {
        iAdvise->second->Release();
        m_aAdviseHashMap.erase( iAdvise );
    }
    else
        return OLE_E_NOCONNECTION;

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::EnumAdvise( IEnumSTATDATA ** /*ppenumAdvise*/ )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetMiscStatus( DWORD /*dwAspect*/, DWORD * /*pdwStatus*/ )
{
    return OLE_S_USEREG;
}

STDMETHODIMP EmbedDocument_Impl::SetColorScheme( LOGPALETTE * /*pLogpal*/ )
{
    return E_NOTIMPL;
}

//-------------------------------------------------------------------------------
// IDispatch

STDMETHODIMP EmbedDocument_Impl::GetTypeInfoCount( unsigned int FAR*  pctinfo )
{
    if ( m_pDocHolder->GetIDispatch() )
        return m_pDocHolder->GetIDispatch()->GetTypeInfoCount( pctinfo );

    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetTypeInfo( unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo )
{
    if ( m_pDocHolder->GetIDispatch() )
        return m_pDocHolder->GetIDispatch()->GetTypeInfo( iTInfo, lcid, ppTInfo );

    return DISP_E_BADINDEX; // the only error that can be returned
}

STDMETHODIMP EmbedDocument_Impl::GetIDsOfNames( REFIID riid,
                                                OLECHAR FAR* FAR* rgszNames,
                                                unsigned int cNames,
                                                LCID lcid,
                                                DISPID FAR* rgDispId )
{
    if ( m_pDocHolder->GetIDispatch() )
        return m_pDocHolder->GetIDispatch()->GetIDsOfNames( riid, rgszNames, cNames, lcid, rgDispId );

    for ( unsigned int ind = 0; ind < cNames; ind++ )
        rgDispId[ind] = DISPID_UNKNOWN;

    return DISP_E_UNKNOWNNAME;
}

STDMETHODIMP EmbedDocument_Impl::Invoke( DISPID dispIdMember,
                                         REFIID riid,
                                         LCID lcid,
                                         WORD wFlags,
                                         DISPPARAMS FAR* pDispParams,
                                         VARIANT FAR* pVarResult,
                                         EXCEPINFO FAR* pExcepInfo,
                                         unsigned int FAR* puArgErr )
{
    if ( m_pDocHolder->GetIDispatch() )
        return m_pDocHolder->GetIDispatch()->Invoke( dispIdMember,
                                                     riid,
                                                     lcid,
                                                     wFlags,
                                                     pDispParams,
                                                     pVarResult,
                                                     pExcepInfo,
                                                     puArgErr );

    return DISP_E_MEMBERNOTFOUND;
}

// C++ - methods

HRESULT EmbedDocument_Impl::SaveObject()
{
    HRESULT hr = S_OK;

    if(m_pClientSite) {
        hr = m_pClientSite->SaveObject();

        for ( AdviseSinkHashMapIterator iAdvise =
                  m_aAdviseHashMap.begin();
              iAdvise != m_aAdviseHashMap.end();
              iAdvise++ )
            if ( iAdvise->second )
                iAdvise->second->OnSave( );
    }

    notify( false );

    return hr;
}

HRESULT EmbedDocument_Impl::ShowObject()
{
    HRESULT hr = S_OK;

    if(m_pClientSite)
        hr = m_pClientSite->ShowObject();

    return hr;
}

void EmbedDocument_Impl::notify( bool bDataChanged )
{
    for ( AdviseSinkHashMapIterator iAdvise =
              m_aAdviseHashMap.begin();
          iAdvise != m_aAdviseHashMap.end();
          iAdvise++ )
        if ( iAdvise->second )
            iAdvise->second->OnViewChange( DVASPECT_CONTENT, -1 );

    if ( m_pDAdviseHolder && bDataChanged )
        m_pDAdviseHolder->SendOnDataChange( (IDataObject*)this, 0, 0 );
}

// Fix strange warnings about some
// ATL::CAxHostWindow::QueryInterface|AddRef|Releae functions.
// warning C4505: 'xxx' : unreferenced local function has been removed
#if defined(_MSC_VER)
#pragma warning(disable: 4505)
#endif
<commit_msg>INTEGRATION: CWS c04v3_SRC680 (1.15.10); FILE MERGED 2006/11/24 18:42:54 mav 1.15.10.2: #143410# reimplement links support correctly 2006/11/10 14:16:06 mav 1.15.10.1: #143410# allow saving even if there is no client<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ed_ioleobject.cxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: rt $ $Date: 2006-12-05 13:03:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "embeddoc.hxx"

#ifndef _OSL_DIAGNOSE_H_
#include <ols/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_FRAME_XController_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

using namespace ::com::sun::star;

extern ::rtl::OUString  getFilterNameFromGUID_Impl( GUID* );

//-------------------------------------------------------------------------------
// IOleObject

STDMETHODIMP EmbedDocument_Impl::SetClientSite( IOleClientSite* pSite )
{
    m_pClientSite = pSite;
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::GetClientSite( IOleClientSite** pSite )
{
    *pSite = m_pClientSite;
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::SetHostNames( LPCOLESTR szContainerApp, LPCOLESTR szContainerObj )
{
    // the code should be ignored for links
    if ( !m_aFileName.getLength() )
    {
        m_pDocHolder->setTitle(
            rtl::OUString(
                (sal_Unicode*)szContainerObj));
        m_pDocHolder->setContainerName(
            rtl::OUString(
                (sal_Unicode*)szContainerApp));
    }

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::Close( DWORD dwSaveOption )
{
    if ( dwSaveOption == 2 && m_aFileName.getLength() )
    {
        // ask the user about saving
        if ( m_pDocHolder->ExecuteSuspendCloseFrame() )
        {
            m_pDocHolder->CloseDocument();
            return S_OK;
        }
        else
            return OLE_E_PROMPTSAVECANCELLED;
    }

    HRESULT hr = S_OK;

    if ( dwSaveOption != 1 )
        hr = SaveObject(); // ADVF_DATAONSTOP);

    m_pDocHolder->FreeOffice();
    m_pDocHolder->CloseDocument();
    m_pDocHolder->CloseFrame();

    OLENotifyClosing();

    return hr;
}

HRESULT EmbedDocument_Impl::OLENotifyClosing()
{
    HRESULT hr = S_OK;

    if ( m_pClientSite )
        m_pClientSite->OnShowWindow( FALSE );

    AdviseSinkHashMap aAHM(m_aAdviseHashMap);

    for ( AdviseSinkHashMapIterator iAdvise = aAHM.begin();
          iAdvise != aAHM.end(); iAdvise++ )
    {
        if ( iAdvise->second )
            iAdvise->second->OnClose();
    }

    return hr;

}

STDMETHODIMP EmbedDocument_Impl::SetMoniker( DWORD /*dwWhichMoniker*/, IMoniker * /*pmk*/ )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetMoniker( DWORD /*dwAssign*/, DWORD /*dwWhichMoniker*/, IMoniker ** /*ppmk*/ )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::InitFromData( IDataObject * /*pDataObject*/, BOOL /*fCreation*/, DWORD /*dwReserved*/ )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetClipboardData( DWORD /*dwReserved*/, IDataObject ** /*ppDataObject*/ )
{
    return E_NOTIMPL;
}

/**
 *  Well, this is a not so very inefficient way to deliver
 *
 */

STDMETHODIMP EmbedDocument_Impl::DoVerb(
    LONG iVerb,
    LPMSG,
    IOleClientSite *pActiveSite,
    LONG,
    HWND,
    LPCRECT )
{
    // no locking is used since the OLE must use the same thread always
    if ( m_bIsInVerbHandling )
        return OLEOBJ_S_CANNOT_DOVERB_NOW;

    BooleanGuard_Impl aGuard( m_bIsInVerbHandling );

    if ( iVerb == OLEIVERB_PRIMARY )
    {
        if ( m_aFileName.getLength() )
        {
            // that should be a link
            iVerb = OLEIVERB_OPEN;
        }
        else
            iVerb = OLEIVERB_SHOW;
    }

    switch(iVerb) {
        case OLEIVERB_DISCARDUNDOSTATE:
            // free any undostate?
            break;
        case OLEIVERB_INPLACEACTIVATE:
            OSL_ENSURE(m_pDocHolder,"no document for inplace activation");

            return m_pDocHolder->InPlaceActivate(pActiveSite,FALSE);
            break;
        case OLEIVERB_UIACTIVATE:
            OSL_ENSURE(m_pDocHolder,"no document for     inplace activation");

            return m_pDocHolder->InPlaceActivate(pActiveSite,TRUE);
            break;
        case OLEIVERB_PRIMARY:
        case OLEIVERB_SHOW:
            OSL_ENSURE(m_pDocHolder,"no document for inplace activation");

            if(m_pDocHolder->isActive())
                return NOERROR; //Already active

            if(SUCCEEDED(
                m_pDocHolder->InPlaceActivate(
                    pActiveSite,TRUE)))
                return NOERROR;

            // intended fall trough
        case OLEIVERB_OPEN:
            OSL_ENSURE(m_pDocHolder,"no document to open");

            // the commented code could be usefull in case
            // outer window would be resized depending from inner one
            // RECTL aEmbArea;
            // m_pDocHolder->GetVisArea( &aEmbArea );
            // m_pDocHolder->show();
            // m_pDocHolder->SetVisArea( &aEmbArea );

            if(m_pDocHolder->isActive())
            {
                m_pDocHolder->InPlaceDeactivate();
                m_pDocHolder->DisableInplaceActivation(true);
            }

            SIZEL aEmbSize;
            m_pDocHolder->GetExtent( &aEmbSize );
            m_pDocHolder->show();
            m_pDocHolder->resizeWin( aEmbSize );

            if ( m_pClientSite )
                m_pClientSite->OnShowWindow( TRUE );

            notify();
            break;
        case OLEIVERB_HIDE:
            OSL_ENSURE(m_pDocHolder,"no document to hide");

            if(m_pDocHolder->isActive())
                m_pDocHolder->InPlaceDeactivate();
            else {
                m_pDocHolder->hide();

                if( m_pClientSite )
                    m_pClientSite->OnShowWindow(FALSE);
            }
            break;
        default:
            break;
    }

    return NOERROR;
}

STDMETHODIMP EmbedDocument_Impl::EnumVerbs( IEnumOLEVERB ** /*ppEnumOleVerb*/ )
{
    return OLE_S_USEREG;
}

STDMETHODIMP EmbedDocument_Impl::Update()
{
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::IsUpToDate()
{
    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::GetUserClassID( CLSID *pClsid )
{
    return GetClassID( pClsid );
}

STDMETHODIMP EmbedDocument_Impl::GetUserType( DWORD /*dwFormOfTypeUe*/, LPOLESTR * /*pszUserType*/ )
{
    return OLE_S_USEREG;
}

STDMETHODIMP EmbedDocument_Impl::SetExtent( DWORD /*dwDrawAspect*/, SIZEL *psizel )
{
    if ( !psizel )
        return E_FAIL;

    m_pDocHolder->SetExtent( psizel );

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::GetExtent( DWORD /*dwDrawAspect*/, SIZEL * psizel )
{
    if ( !psizel )
        return E_INVALIDARG;

    if ( FAILED( m_pDocHolder->GetExtent( psizel ) ) )
    {
        // return default values
        psizel->cx = 500;
        psizel->cy = 500;
    }

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::Advise( IAdviseSink *pAdvSink, DWORD *pdwConnection )
{
    if ( m_nAdviseNum == 0xFFFFFFFF )
        return E_OUTOFMEMORY;

    pAdvSink->AddRef();
    m_aAdviseHashMap.insert( ::std::pair< DWORD, IAdviseSink* >( m_nAdviseNum, pAdvSink ) );
    *pdwConnection = m_nAdviseNum++;

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::Unadvise( DWORD dwConnection )
{
    AdviseSinkHashMapIterator iAdvise = m_aAdviseHashMap.find( dwConnection );
    if ( iAdvise != m_aAdviseHashMap.end() )
    {
        iAdvise->second->Release();
        m_aAdviseHashMap.erase( iAdvise );
    }
    else
        return OLE_E_NOCONNECTION;

    return S_OK;
}

STDMETHODIMP EmbedDocument_Impl::EnumAdvise( IEnumSTATDATA ** /*ppenumAdvise*/ )
{
    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetMiscStatus( DWORD /*dwAspect*/, DWORD * /*pdwStatus*/ )
{
    return OLE_S_USEREG;
}

STDMETHODIMP EmbedDocument_Impl::SetColorScheme( LOGPALETTE * /*pLogpal*/ )
{
    return E_NOTIMPL;
}

//-------------------------------------------------------------------------------
// IDispatch

STDMETHODIMP EmbedDocument_Impl::GetTypeInfoCount( unsigned int FAR*  pctinfo )
{
    if ( m_pDocHolder->GetIDispatch() )
        return m_pDocHolder->GetIDispatch()->GetTypeInfoCount( pctinfo );

    return E_NOTIMPL;
}

STDMETHODIMP EmbedDocument_Impl::GetTypeInfo( unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo )
{
    if ( m_pDocHolder->GetIDispatch() )
        return m_pDocHolder->GetIDispatch()->GetTypeInfo( iTInfo, lcid, ppTInfo );

    return DISP_E_BADINDEX; // the only error that can be returned
}

STDMETHODIMP EmbedDocument_Impl::GetIDsOfNames( REFIID riid,
                                                OLECHAR FAR* FAR* rgszNames,
                                                unsigned int cNames,
                                                LCID lcid,
                                                DISPID FAR* rgDispId )
{
    if ( m_pDocHolder->GetIDispatch() )
        return m_pDocHolder->GetIDispatch()->GetIDsOfNames( riid, rgszNames, cNames, lcid, rgDispId );

    for ( unsigned int ind = 0; ind < cNames; ind++ )
        rgDispId[ind] = DISPID_UNKNOWN;

    return DISP_E_UNKNOWNNAME;
}

STDMETHODIMP EmbedDocument_Impl::Invoke( DISPID dispIdMember,
                                         REFIID riid,
                                         LCID lcid,
                                         WORD wFlags,
                                         DISPPARAMS FAR* pDispParams,
                                         VARIANT FAR* pVarResult,
                                         EXCEPINFO FAR* pExcepInfo,
                                         unsigned int FAR* puArgErr )
{
    if ( m_pDocHolder->GetIDispatch() )
        return m_pDocHolder->GetIDispatch()->Invoke( dispIdMember,
                                                     riid,
                                                     lcid,
                                                     wFlags,
                                                     pDispParams,
                                                     pVarResult,
                                                     pExcepInfo,
                                                     puArgErr );

    return DISP_E_MEMBERNOTFOUND;
}

// C++ - methods

HRESULT EmbedDocument_Impl::SaveObject()
{
    HRESULT hr = S_OK;

    if(m_pClientSite) {
        hr = m_pClientSite->SaveObject();

        for ( AdviseSinkHashMapIterator iAdvise =
                  m_aAdviseHashMap.begin();
              iAdvise != m_aAdviseHashMap.end();
              iAdvise++ )
            if ( iAdvise->second )
                iAdvise->second->OnSave( );
    }
    else if ( m_aFileName.getLength() && IsDirty() == S_OK )
    {
        ::rtl::OUString aPreservFileName = m_aFileName;

        // in case of links the containers does not provide client site sometimes
        hr = Save( (LPCOLESTR)NULL, FALSE ); // triggers saving to the link location
        SaveCompleted( (LPCOLESTR)aPreservFileName.getStr() );
    }

    notify( false );

    return hr;
}

HRESULT EmbedDocument_Impl::ShowObject()
{
    HRESULT hr = S_OK;

    if(m_pClientSite)
        hr = m_pClientSite->ShowObject();

    return hr;
}

void EmbedDocument_Impl::notify( bool bDataChanged )
{
    for ( AdviseSinkHashMapIterator iAdvise =
              m_aAdviseHashMap.begin();
          iAdvise != m_aAdviseHashMap.end();
          iAdvise++ )
        if ( iAdvise->second )
            iAdvise->second->OnViewChange( DVASPECT_CONTENT, -1 );

    if ( m_pDAdviseHolder && bDataChanged )
        m_pDAdviseHolder->SendOnDataChange( (IDataObject*)this, 0, 0 );
}

// Fix strange warnings about some
// ATL::CAxHostWindow::QueryInterface|AddRef|Releae functions.
// warning C4505: 'xxx' : unreferenced local function has been removed
#if defined(_MSC_VER)
#pragma warning(disable: 4505)
#endif
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Interface/Modules/Visualization/ShowFieldDialog.h>
#include <Modules/Visualization/ShowField.h>
#include <Dataflow/Network/ModuleStateInterface.h>  //TODO: extract into intermediate
#include <Core/Datatypes/Color.h>
#include <QColorDialog>

using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Visualization;
using namespace SCIRun::Core::Datatypes;

ShowFieldDialog::ShowFieldDialog(const std::string& name, ModuleStateHandle state,
  QWidget* parent /* = 0 */)
  : ModuleDialogGeneric(state, parent),
  defaultMeshColor_(Qt::gray)
{
  setupUi(this);
  setWindowTitle(QString::fromStdString(name));
  fixSize();

  addCheckBoxManager(showNodesCheckBox_, ShowFieldModule::ShowNodes);
  addCheckBoxManager(showEdgesCheckBox_, ShowFieldModule::ShowEdges);
  addCheckBoxManager(showFacesCheckBox_, ShowFieldModule::ShowFaces);
  addCheckBoxManager(enableTransparencyNodesCheckBox_, ShowFieldModule::NodeTransparency);
  addCheckBoxManager(enableTransparencyEdgesCheckBox_, ShowFieldModule::EdgeTransparency);
  addCheckBoxManager(enableTransparencyFacesCheckBox_, ShowFieldModule::FaceTransparency);
  addCheckBoxManager(invertNormalsCheckBox, ShowFieldModule::FaceInvertNormals);

  buttonBox->setVisible(false);
  connect(defaultMeshColorButton_, SIGNAL(clicked()), this, SLOT(assignDefaultMeshColor()));
  connect(nodesAsPointsButton_, SIGNAL(clicked()), this, SLOT(pushNodeType()));
  connect(nodesAsSpheresButton_, SIGNAL(clicked()), this, SLOT(pushNodeType()));

  pushNodeType();
}

void ShowFieldDialog::push()
{
  if (!pulling_)
  {
    pushColor();
  }
}

void ShowFieldDialog::pull()
{
  pull_newVersionToReplaceOld();
  Pulling p(this);
  ColorRGB color(state_->getValue(ShowFieldModule::DefaultMeshColor).getString());
  defaultMeshColor_ = QColor(
      static_cast<int>(color.r() * 255.0),
      static_cast<int>(color.g() * 255.0),
      static_cast<int>(color.b() * 255.0));
}

void ShowFieldDialog::assignDefaultMeshColor()
{
  auto newColor = QColorDialog::getColor(defaultMeshColor_, this, "Choose default mesh color");
  if (newColor.isValid())
  {
    defaultMeshColor_ = newColor;
    //TODO: set color of button to this color
    //defaultMeshColorButton_->set
    pushColor();
  }
}

void ShowFieldDialog::pushColor()
{
  state_->setValue(ShowFieldModule::DefaultMeshColor, ColorRGB(defaultMeshColor_.red(), defaultMeshColor_.green(), defaultMeshColor_.blue()).toString());
}

void ShowFieldDialog::pushNodeType()
{
  state_->setValue(ShowFieldModule::NodeAsPoints, nodesAsPointsButton_->isChecked());
  state_->setValue(ShowFieldModule::NodeAsSpheres, nodesAsSpheresButton_->isChecked());

  std::cout << "Nodes as points: " << state_->getValue(ShowFieldModule::NodeAsPoints) << std::endl;
  std::cout << "Nodes as spheres: " << state_->getValue(ShowFieldModule::NodeAsSpheres) << std::endl;
}

<commit_msg>Remove debug comments.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Interface/Modules/Visualization/ShowFieldDialog.h>
#include <Modules/Visualization/ShowField.h>
#include <Dataflow/Network/ModuleStateInterface.h>  //TODO: extract into intermediate
#include <Core/Datatypes/Color.h>
#include <QColorDialog>

using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Visualization;
using namespace SCIRun::Core::Datatypes;

ShowFieldDialog::ShowFieldDialog(const std::string& name, ModuleStateHandle state,
  QWidget* parent /* = 0 */)
  : ModuleDialogGeneric(state, parent),
  defaultMeshColor_(Qt::gray)
{
  setupUi(this);
  setWindowTitle(QString::fromStdString(name));
  fixSize();

  addCheckBoxManager(showNodesCheckBox_, ShowFieldModule::ShowNodes);
  addCheckBoxManager(showEdgesCheckBox_, ShowFieldModule::ShowEdges);
  addCheckBoxManager(showFacesCheckBox_, ShowFieldModule::ShowFaces);
  addCheckBoxManager(enableTransparencyNodesCheckBox_, ShowFieldModule::NodeTransparency);
  addCheckBoxManager(enableTransparencyEdgesCheckBox_, ShowFieldModule::EdgeTransparency);
  addCheckBoxManager(enableTransparencyFacesCheckBox_, ShowFieldModule::FaceTransparency);
  addCheckBoxManager(invertNormalsCheckBox, ShowFieldModule::FaceInvertNormals);

  buttonBox->setVisible(false);
  connect(defaultMeshColorButton_, SIGNAL(clicked()), this, SLOT(assignDefaultMeshColor()));
  connect(nodesAsPointsButton_, SIGNAL(clicked()), this, SLOT(pushNodeType()));
  connect(nodesAsSpheresButton_, SIGNAL(clicked()), this, SLOT(pushNodeType()));

  pushNodeType();
}

void ShowFieldDialog::push()
{
  if (!pulling_)
  {
    pushColor();
  }
}

void ShowFieldDialog::pull()
{
  pull_newVersionToReplaceOld();
  Pulling p(this);
  ColorRGB color(state_->getValue(ShowFieldModule::DefaultMeshColor).getString());
  defaultMeshColor_ = QColor(
      static_cast<int>(color.r() * 255.0),
      static_cast<int>(color.g() * 255.0),
      static_cast<int>(color.b() * 255.0));
}

void ShowFieldDialog::assignDefaultMeshColor()
{
  auto newColor = QColorDialog::getColor(defaultMeshColor_, this, "Choose default mesh color");
  if (newColor.isValid())
  {
    defaultMeshColor_ = newColor;
    //TODO: set color of button to this color
    //defaultMeshColorButton_->set
    pushColor();
  }
}

void ShowFieldDialog::pushColor()
{
  state_->setValue(ShowFieldModule::DefaultMeshColor, ColorRGB(defaultMeshColor_.red(), defaultMeshColor_.green(), defaultMeshColor_.blue()).toString());
}

void ShowFieldDialog::pushNodeType()
{
  state_->setValue(ShowFieldModule::NodeAsPoints, nodesAsPointsButton_->isChecked());
  state_->setValue(ShowFieldModule::NodeAsSpheres, nodesAsSpheresButton_->isChecked());
}

<|endoftext|>