<commit_before>#ifndef DUNE_STUFF_INTEGRALS_HH
#define DUNE_STUFF_INTEGRALS_HH

#ifdef HAVE_CMAKE_CONFIG
 #include "cmake_config.h"
#else
 #include "config.h"
#endif

#ifdef HAVE_DUNE_FEM

#include <dune/stuff/fem/localmassmatrix.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/fem/quadrature/cachingquadrature.hh>

#include <dune/stuff/fem/namespace.hh>

namespace Dune {
namespace Stuff {
namespace Fem {

/** Generate and return a Dune::Fem::CachingQuadrature on a codim-0 entity of the grid.
 *
 *  @param[in] entity The codim-0 entity that will be used as domain for the quadrature
 *  @param[in] space The discrete function space that hosts function to be integrated with this quadrature
 *  @param[in] order The desired order for the quadrature
 *  @return Returns a caching quadrature of order order (or 2*space.order()+2 if no order was provided) on the entity.
 */
template <class SpaceTraits, class GridImp, template <int, int, class> class EntityImp>
Dune::Fem::CachingQuadrature<typename SpaceTraits::GridPartType, 0>
make_quadrature(const Dune::Entity<0, GridImp::dimension, GridImp, EntityImp>& entity,
                const Dune::Fem::DiscreteFunctionSpaceInterface<SpaceTraits>& space, int order = -1) {
  order = order > -1 ? order : 2 * space.order() + 2;
  return Dune::Fem::CachingQuadrature<typename SpaceTraits::GridPartType, 0>(entity, order);
}

/** Generate and return a Dune::Fem::CachingQuadrature on a codim-1 entity of the grid.
 *
 *  @param[in] intersection The codim-1 entity that will be used as domain for the quadrature
 *  @param[in] space The discrete function space that hosts function to be integrated with this quadrature
 *  @param[in] order The desired order for the quadrature
 *  @param[in] inside Switch to change from inside quadrature to outside.
 *  @return Returns a caching quadrature of order order (or 2*space.order()+2 if no order was provided) on the entity.
 */
template <class SpaceTraits, class IntersectionImp>
Dune::Fem::CachingQuadrature<typename SpaceTraits::GridPartType, 1> make_quadrature(
    const Dune::Intersection<const typename SpaceTraits::GridPartType::GridType, IntersectionImp>& intersection,
    const Dune::Fem::DiscreteFunctionSpaceInterface<SpaceTraits>& space, int order = -1, bool inside = true) {
  order = order > -1 ? order : 2 * space.order() + 2;
  typedef Dune::Fem::CachingQuadrature<typename SpaceTraits::GridPartType, 1> Quad;
  // this const_cast cast is necessary because the gridPart() method in DiscreteFunctionSpaceInterface
  // has no const version
  auto& castedSpace = const_cast<Dune::Fem::DiscreteFunctionSpaceInterface<SpaceTraits>&>(space);
  return Quad(castedSpace.gridPart(), intersection, order, inside ? Quad::INSIDE : Quad::OUTSIDE);
}

/** \todo RENE needs to doc me **/
template< class FunctionType, class SpaceTraits >
std::pair< typename FunctionType::RangeType, double >
integralAndVolume(const FunctionType& function,
                  const Dune::Fem::DiscreteFunctionSpaceInterface<SpaceTraits>& space,
                  const int polOrd = -1)
{
//  typedef Dune::Stuff::Fem::LocalMassMatrix< DiscreteFunctionSpaceType, QuadratureType > LocalMassMatrixType;

  typedef typename FunctionType::RangeType RangeType;

  RangeType integral_value(0);
  double total_volume = 0;
  RangeType ret(0.0);

  for (const auto& en : space)
  {
    const auto& geo = en.geometry();
    total_volume += geo.volume();
    const auto& quad = make_quadrature(en, space, polOrd);
    for (const auto& qP : Dune::Stuff::Common::valueRange(quad.nop())) {
      const double intel = quad.weight(qP) * geo.integrationElement( quad.point(qP) );
      // evaluate function
      RangeType dummy;
      const auto xWorld = geo.global( quad.point(qP) );
      function.evaluate(xWorld, dummy);
      ret = dummy;
      ret *= intel;

      integral_value += ret;
    }
  }
  const auto& comm = space.gridPart().grid().comm();
  integral_value = comm.sum(integral_value);
  total_volume = comm.sum(total_volume);
  return std::make_pair(integral_value, total_volume);
} // integralAndVolume

/** \todo RENE needs to doc me **/
template< class FunctionType, class DiscreteFunctionSpaceType >
typename FunctionType::RangeType meanValue(const FunctionType& function,
                                           const DiscreteFunctionSpaceType& space,
                                           const int polOrd = -1) {
  std::pair< typename FunctionType::RangeType, double > pair = integralAndVolume(function, space, polOrd);
  pair.first /= pair.second;
  return pair.first;
}

/** \todo RENE needs to doc me **/
template< class FunctionType, class DiscreteFunctionSpaceType >
double boundaryIntegral(const FunctionType& function, const DiscreteFunctionSpaceType& space, const int polOrd = -1)
{
  typedef typename DiscreteFunctionSpaceType::Traits::GridPartType GridPartType;
#if DUNE_FEM_IS_MULTISCALE_COMPATIBLE
  typedef Dune::CachingQuadrature< GridPartType, 1 > QuadratureType;
  typedef Dune::Stuff::Fem::LocalMassMatrix< DiscreteFunctionSpaceType,
                                  Dune::CachingQuadrature< GridPartType, 0 > > LocalMassMatrixType;
#elif DUNE_FEM_IS_LOCALFUNCTIONS_COMPATIBLE
  typedef Dune::Fem::CachingQuadrature< GridPartType, 1 > QuadratureType;
  typedef Dune::Stuff::Fem::LocalMassMatrix< DiscreteFunctionSpaceType,
                                  Dune::Fem::CachingQuadrature< GridPartType, 0 > > LocalMassMatrixType;
#else
  typedef Dune::Fem::CachingQuadrature< GridPartType, 1 > QuadratureType;
  typedef Dune::Stuff::Fem::LocalMassMatrix< DiscreteFunctionSpaceType,
                                  Dune::Fem::CachingQuadrature< GridPartType, 0 > > LocalMassMatrixType;
#endif
  double integral_value = 0;
  double total_volume = 0;
  typename DiscreteFunctionSpaceType::RangeType ret(0.0);
  const int quadOrd = std::max(2 * space.order() + 2, polOrd);
  // create local mass matrix object
  LocalMassMatrixType massMatrix(space, quadOrd);
  // check whether geometry mappings are affine or not
  const bool affineMapping = massMatrix.affine();
  for (const auto& entity : space)
  {
    const auto& geo = entity.geometry();
    total_volume += geo.volume();

    const auto intItEnd = space.gridPart().iend(entity);
    for (auto intIt = space.gridPart().ibegin(entity);
         intIt != intItEnd;
         ++intIt)
    {
      if ( !intIt->neighbor() && intIt->boundary() )
      {
        const QuadratureType quad(space.gridPart(),
                                  *intIt,
                                  quadOrd,
                                  QuadratureType::INSIDE);
        const int quadNop = quad.nop();
        for (int qP = 0; qP < quadNop; ++qP)
        {
          const double intel = (affineMapping) ?
                               quad.weight(qP) : // affine case
                               quad.weight(qP) * geo.integrationElement( quad.point(qP) ); // general case

          // evaluate function
          typename DiscreteFunctionSpaceType::RangeType dummy;
          const auto xWorld = geo.global( quad.point(qP) );
          function.evaluate(xWorld, dummy, *intIt);
          ret = dummy;
          ret *= intel;
          integral_value += ret * intIt->unitOuterNormal( quad.localPoint(qP) );
        }
      }
    }
  }
  return integral_value;
} // boundaryIntegral

} // end namespace Fem
} // end namespace Stuff
} // end namespace Dune

#endif // HAVE_DUNE_FEM

#endif // DUNE_STUFF_INTEGRALS_HH

/** Copyright (c) 2012, Felix Albrecht, Rene Milk
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the documentation
   *    and/or other materials provided with the distribution.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
   *
   * The views and conclusions contained in the software and documentation are those
   * of the authors and should not be interpreted as representing official policies,
   * either expressed or implied, of the FreeBSD Project.
   **/
<commit_msg>Whitespace changes<commit_after>#ifndef DUNE_STUFF_INTEGRALS_HH
#define DUNE_STUFF_INTEGRALS_HH

#ifdef HAVE_CMAKE_CONFIG
 #include "cmake_config.h"
#else
 #include "config.h"
#endif

#ifdef HAVE_DUNE_FEM

#include <dune/stuff/fem/localmassmatrix.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/fem/quadrature/cachingquadrature.hh>

#include <dune/stuff/fem/namespace.hh>

namespace Dune {
namespace Stuff {
namespace Fem {

/** Generate and return a Dune::Fem::CachingQuadrature on a codim-0 entity of the grid.
 *
 *  @param[in] entity The codim-0 entity that will be used as domain for the quadrature
 *  @param[in] space The discrete function space that hosts function to be integrated with this quadrature
 *  @param[in] order The desired order for the quadrature
 *  @return Returns a caching quadrature of order order (or 2*space.order()+2 if no order was provided) on the entity.
 */
template <class SpaceTraits, class GridImp, template <int, int, class> class EntityImp>
Dune::Fem::CachingQuadrature<typename SpaceTraits::GridPartType, 0>
make_quadrature(const Dune::Entity<0, GridImp::dimension, GridImp, EntityImp>& entity,
                const Dune::Fem::DiscreteFunctionSpaceInterface<SpaceTraits>& space, int order = -1) {
  order = order > -1 ? order : 2 * space.order() + 2;
  return Dune::Fem::CachingQuadrature<typename SpaceTraits::GridPartType, 0>(entity, order);
}

/** Generate and return a Dune::Fem::CachingQuadrature on a codim-1 entity of the grid.
 *
 *  @param[in] intersection The codim-1 entity that will be used as domain for the quadrature
 *  @param[in] space The discrete function space that hosts function to be integrated with this quadrature
 *  @param[in] order The desired order for the quadrature
 *  @param[in] inside Switch to change from inside quadrature to outside.
 *  @return Returns a caching quadrature of order order (or 2*space.order()+2 if no order was provided) on the entity.
 */
template <class SpaceTraits, class IntersectionImp>
Dune::Fem::CachingQuadrature<typename SpaceTraits::GridPartType, 1> make_quadrature(
    const Dune::Intersection<const typename SpaceTraits::GridPartType::GridType, IntersectionImp>& intersection,
    const Dune::Fem::DiscreteFunctionSpaceInterface<SpaceTraits>& space, int order = -1, bool inside = true) {
  order = order > -1 ? order : 2 * space.order() + 2;
  typedef Dune::Fem::CachingQuadrature<typename SpaceTraits::GridPartType, 1> Quad;
  // this const_cast cast is necessary because the gridPart() method in DiscreteFunctionSpaceInterface
  // has no const version
  auto& castedSpace = const_cast<Dune::Fem::DiscreteFunctionSpaceInterface<SpaceTraits>&>(space);
  return Quad(castedSpace.gridPart(), intersection, order, inside ? Quad::INSIDE : Quad::OUTSIDE);
}

/** \todo RENE needs to doc me **/
template< class FunctionType, class SpaceTraits >
std::pair< typename FunctionType::RangeType, double >
integralAndVolume(const FunctionType& function,
                  const Dune::Fem::DiscreteFunctionSpaceInterface<SpaceTraits>& space,
                  const int polOrd = -1)
{
//  typedef Dune::Stuff::Fem::LocalMassMatrix< DiscreteFunctionSpaceType, QuadratureType > LocalMassMatrixType;

  typedef typename FunctionType::RangeType RangeType;

  RangeType integral_value(0);
  double total_volume = 0;
  RangeType ret(0.0);

  for (const auto& en : space)
  {
    const auto& geo = en.geometry();
    total_volume += geo.volume();
    const auto& quad = make_quadrature(en, space, polOrd);
    for (const auto& qP : Dune::Stuff::Common::valueRange(quad.nop())) {
      const double intel = quad.weight(qP) * geo.integrationElement( quad.point(qP) );
      // evaluate function
      RangeType dummy;
      const auto xWorld = geo.global( quad.point(qP) );
      function.evaluate(xWorld, dummy);
      ret = dummy;
      ret *= intel;

      integral_value += ret;
    }
  }
  const auto& comm = space.gridPart().grid().comm();
  integral_value = comm.sum(integral_value);
  total_volume = comm.sum(total_volume);
  return std::make_pair(integral_value, total_volume);
} // integralAndVolume

/** \todo RENE needs to doc me **/
template< class FunctionType, class DiscreteFunctionSpaceType >
typename FunctionType::RangeType meanValue(const FunctionType& function,
                                           const DiscreteFunctionSpaceType& space,
                                           const int polOrd = -1) {
  std::pair< typename FunctionType::RangeType, double > pair = integralAndVolume(function, space, polOrd);
  pair.first /= pair.second;
  return pair.first;
}

/** \todo RENE needs to doc me **/
template< class FunctionType, class DiscreteFunctionSpaceType >
double boundaryIntegral(const FunctionType& function,
                        const DiscreteFunctionSpaceType& space,
                        const int polOrd = -1)
{
  typedef typename DiscreteFunctionSpaceType::Traits::GridPartType GridPartType;
#if DUNE_FEM_IS_MULTISCALE_COMPATIBLE
  typedef Dune::CachingQuadrature< GridPartType, 1 > QuadratureType;
  typedef Dune::Stuff::Fem::LocalMassMatrix< DiscreteFunctionSpaceType,
                                  Dune::CachingQuadrature< GridPartType, 0 > > LocalMassMatrixType;
#elif DUNE_FEM_IS_LOCALFUNCTIONS_COMPATIBLE
  typedef Dune::Fem::CachingQuadrature< GridPartType, 1 > QuadratureType;
  typedef Dune::Stuff::Fem::LocalMassMatrix< DiscreteFunctionSpaceType,
                                  Dune::Fem::CachingQuadrature< GridPartType, 0 > > LocalMassMatrixType;
#else
  typedef Dune::Fem::CachingQuadrature< GridPartType, 1 > QuadratureType;
  typedef Dune::Stuff::Fem::LocalMassMatrix< DiscreteFunctionSpaceType,
                                  Dune::Fem::CachingQuadrature< GridPartType, 0 > > LocalMassMatrixType;
#endif
  double integral_value = 0;
  double total_volume = 0;
  typename DiscreteFunctionSpaceType::RangeType ret(0.0);
  const int quadOrd = std::max(2 * space.order() + 2, polOrd);
  // create local mass matrix object
  LocalMassMatrixType massMatrix(space, quadOrd);
  // check whether geometry mappings are affine or not
  const bool affineMapping = massMatrix.affine();
  for (const auto& entity : space)
  {
    const auto& geo = entity.geometry();
    total_volume += geo.volume();

    const auto intItEnd = space.gridPart().iend(entity);
    for (auto intIt = space.gridPart().ibegin(entity);
         intIt != intItEnd;
         ++intIt)
    {
      if ( !intIt->neighbor() && intIt->boundary() )
      {
        const QuadratureType quad(space.gridPart(),
                                  *intIt,
                                  quadOrd,
                                  QuadratureType::INSIDE);
        const int quadNop = quad.nop();
        for (int qP = 0; qP < quadNop; ++qP)
        {
          const double intel = (affineMapping) ?
                               quad.weight(qP) : // affine case
                               quad.weight(qP) * geo.integrationElement( quad.point(qP) ); // general case

          // evaluate function
          typename DiscreteFunctionSpaceType::RangeType dummy;
          const auto xWorld = geo.global( quad.point(qP) );
          function.evaluate(xWorld, dummy, *intIt);
          ret = dummy;
          ret *= intel;
          integral_value += ret * intIt->unitOuterNormal( quad.localPoint(qP) );
        }
      }
    }
  }
  return integral_value;
} // boundaryIntegral

} // end namespace Fem
} // end namespace Stuff
} // end namespace Dune

#endif // HAVE_DUNE_FEM

#endif // DUNE_STUFF_INTEGRALS_HH

/** Copyright (c) 2012, Felix Albrecht, Rene Milk
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the documentation
   *    and/or other materials provided with the distribution.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
   *
   * The views and conclusions contained in the software and documentation are those
   * of the authors and should not be interpreted as representing official policies,
   * either expressed or implied, of the FreeBSD Project.
   **/
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: providerimpl.hxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 03:19:47 $
 *
 *  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
 *
 ************************************************************************/

#ifndef CONFIGMGR_API_PROVIDERIMPL_HXX_
#define CONFIGMGR_API_PROVIDERIMPL_HXX_

#ifndef CONFIGMGR_TREEPROVIDER_HXX
#include "treeprovider.hxx"
#endif
#ifndef CONFIGMGR_DEFAULTPROVIDER_HXX
#include "defaultprovider.hxx"
#endif
#ifndef _CONFIGMGR_COMMONTYPES_HXX_
#include "commontypes.hxx" // IInterface
#endif

#ifndef CONFIGMGR_MISC_REQUESTOPTIONS_HXX_
#include "requestoptions.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_XTYPECONVERTER_HPP_
#include <com/sun/star/script/XTypeConverter.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

namespace com { namespace sun { namespace star {
    namespace uno
    {
        class Any;
        class XInterface;
        template <class> class Sequence;
        template <class> class Reference;
    }
    namespace beans
    {
        struct PropertyValue;
    }
}   }   }

namespace rtl
{
    class OUString;
    template <class RCType> class Reference;
}

namespace configmgr
{
    namespace css       = ::com::sun::star;
    namespace uno       = css::uno;
    namespace script    = css::script;
    namespace lang      = css::lang;
    namespace beans     = css::beans;
    using ::rtl::OUString;

    class ISubtree;
    class ITemplateManager;
    class IConfigDefaultProvider;
    class TreeManager;
    class ContextReader;
    class OProvider;

    struct IConfigBroadcaster;

    namespace configapi
    {
        class NodeElement;
        class ApiProviderInstances;
        class Factory;
    }

    // -----------------------------------------------------------------------------
    class OProviderImpl : public ITreeManager, public IDefaultableTreeManager, public IInterface
    {
        friend class OProvider;
        friend class OConfigurationProvider;
    public:
        //==========================================================================
        //= FactoryArguments
        //==========================================================================
        /** Helper class for evaluation of the arguments for creating a service instance.*/
        struct FactoryArguments
        {
            /// possible arguments, given only in small letters.
            enum Argument
            {
                ARG_NODEPATH,           // requested node path
                ARG_DEPTH,              // depth of the tree
                ARG_USER_DEPRECATED,    // name of the entity to be manipulated - deprecated version
                ARG_LOCALE,             // desired locale
                ARG_NOCACHE_OBSOLETE,   // cache disabling - obsolete and nonfunctional
                ARG_ASYNC_DEPRECATED,   // lasy write data - deprecated version
                ARG_ASYNC,              // lazy write data
                ARG_ENTITY,             // name of the entity to be manipulated - only for admin
                ARG_REFRESH,            // force refresh of data into cache

                _arg_count,
                ARG_NOT_FOUND = _arg_count
            };
            static sal_Char const * const asciiArgumentNames[];

            static OUString getArgumentName(Argument _which)                CFG_NOTHROW();
            static Argument lookupArgument(OUString const& sArgumentName)   CFG_NOTHROW();

            static OUString getUserArgumentNameD()              CFG_NOTHROW() { return getArgumentName(ARG_USER_DEPRECATED);     }
            static OUString getEntityArgumentName()             CFG_NOTHROW() { return getArgumentName(ARG_ENTITY);     }
            static OUString getNodePathArgumentName()           CFG_NOTHROW() { return getArgumentName(ARG_NODEPATH); }
            static OUString getDepthArgumentNameArgumentName()  CFG_NOTHROW() { return getArgumentName(ARG_DEPTH);    }
            static OUString getLocaleArgumentName()             CFG_NOTHROW() { return getArgumentName(ARG_LOCALE);   }
            static OUString getNoCacheArgumentNameD()           CFG_NOTHROW() { return getArgumentName(ARG_NOCACHE_OBSOLETE);  }
            static OUString getAsyncArgumentName()              CFG_NOTHROW() { return getArgumentName(ARG_ASYNC);    }
        public:
            /** extracts arguments from the argument sequence into to the parameter variables

unknown arguments are ignored

                @throws com::sun::star::lang::IllegalArgumentException
                    if an element of _rArgs had the wrong type or
                    if the value of a known argument has the wrong type or
                    if the value of a known argument is out of range (sometimes)
                    or if no non-empty node path argument could be extracted,
            */
            static void extractArgs(    const uno::Sequence<uno::Any>& _rArgs,
                                        OUString&   /* [out] */ _rNodeAccessor,
                                        sal_Int32&  /* [out] */ _nLevels,
                                        RequestOptions& /* [in/out] */ xOptions
                                   ) CFG_THROW1(lang::IllegalArgumentException);

            static bool extractOneArgument( OUString const& aName, uno::Any const& aValue,
                                            OUString&   /* [out] */ _rNodeAccessor,
                                            sal_Int32&  /* [out] */ _nLevels,
                                            RequestOptions& /* [in/out] */ xOptions
                                          ) CFG_NOTHROW();

        };

    public:
        typedef uno::Reference< uno::XComponentContext >        CreationContext;
        typedef uno::Reference< script::XTypeConverter >        TypeConverterRef;
    private:
        OProvider*                          m_pProvider;        /// used for ref counting, uno representation

        TypeConverterRef                    m_xTypeConverter;
        RequestOptions                      m_aDefaultOptions;
        configapi::ApiProviderInstances*    m_pNewProviders;
        mutable osl::Mutex                  m_aTreeManagerMutex;
        TreeManager*                        m_pTreeManager;     /// the tree cache. Will hold a reference to us as long as it life

        rtl::Reference< TreeManager > maybeGetTreeManager() const CFG_NOTHROW();
        rtl::Reference< TreeManager > getTreeManager() const CFG_UNO_THROW_RTE();
        void setTreeManager(TreeManager * pTreeManager) CFG_UNO_THROW_RTE();
        void clearTreeManager() CFG_NOTHROW();
    public:
        OProviderImpl(OProvider* _pProvider, CreationContext const & _xContext);

        virtual ~OProviderImpl();

        /// ITreeManager
        virtual memory::Segment* getDataSegment(AbsolutePath const& _rAccessor, const RequestOptions& _aOptions);
        virtual data::NodeAccess requestSubtree(AbsolutePath const& aSubtreePath, const RequestOptions& _aOptions) CFG_UNO_THROW_ALL(  );
        virtual void updateTree(memory::UpdateAccessor& _aAccessToken, TreeChangeList& aChanges) CFG_UNO_THROW_ALL(  );

        virtual void releaseSubtree( AbsolutePath const& aSubtreePath, const RequestOptions& _aOptions ) CFG_NOTHROW();
        virtual void saveAndNotifyUpdate(memory::Accessor const& _aChangedDataAccessor, TreeChangeList const& aChanges) CFG_UNO_THROW_ALL(  );
        virtual void disposeData(const RequestOptions& _aOptions) CFG_NOTHROW();
        virtual void fetchSubtree(AbsolutePath const& aSubtreePath, const RequestOptions& _aOptions) CFG_NOTHROW();

        virtual void refreshAll() CFG_UNO_THROW_ALL(  );
        virtual void flushAll() CFG_NOTHROW();
        virtual void enableAsync(const sal_Bool& bEnableAsync) CFG_NOTHROW();

        /// IDefaultableTreeManager
        virtual sal_Bool fetchDefaultData(  memory::UpdateAccessor& _aAccessToken,
                                            AbsolutePath const& aSubtreePath, const RequestOptions& _aOptions
                                          ) CFG_UNO_THROW_ALL(  );

        // IInterface
        virtual void SAL_CALL acquire(  ) throw ();
        virtual void SAL_CALL release(  ) throw ();

        // DefaultProvider access
        rtl::Reference< IConfigDefaultProvider >  getDefaultProvider() const CFG_UNO_THROW_RTE( );

        // TemplateManager access
        rtl::Reference< IConfigTemplateManager >  getTemplateProvider() const CFG_UNO_THROW_RTE( );

    protected:
        static OUString getErrorMessage(AbsolutePath const& _rAccessor, const RequestOptions& _aOptions);

        virtual void SAL_CALL dispose() throw();
    public:
        void setDefaultLocale( RequestOptions::Locale const & aLocale );

        RequestOptions const& getDefaultOptions() const {return m_aDefaultOptions;}
        TypeConverterRef getTypeConverter() const {return m_xTypeConverter;}
        configapi::Factory& getWriterFactory();
        IConfigBroadcaster* getNotifier() CFG_NOTHROW();
        uno::XInterface*    getProviderInstance();

        // actual factory methods
        // the returned object (if any) has to be acquired once)
        configapi::NodeElement* buildReadAccess( OUString const& _rAccessor, const RequestOptions& _aOptions, sal_Int32 nMinLevels) CFG_UNO_THROW_ALL(  );
        // the returned object (if any) has to be acquired once)
        configapi::NodeElement* buildUpdateAccess(OUString const& _rAccessor, const RequestOptions& _aOptions, sal_Int32 nMinLevels) CFG_UNO_THROW_ALL(  );

    private:
        bool initSession(const ContextReader& _rSettings);
    private:
        void implInitFromSettings(const ContextReader& _rSettings, bool& rNeedProfile);
        void implInitFromProfile(data::NodeAccess const& aProfile);

        virtual void initFromSettings(const ContextReader& _rSettings, bool& rNeedProfile);
        virtual void initFromProfile(data::NodeAccess const& aProfile);
    };
} // namespace configmgr

#endif // CONFIGMGR_API_PROVIDERIMPL_HXX_

<commit_msg>INTEGRATION: CWS configrefactor01 (1.18.84); FILE MERGED 2007/01/16 12:18:19 mmeeks 1.18.84.3: Submitted by: mmeeks Kill 'memory::Segment' - no longer needed. Bin some other (empty / redundant) headers. 2007/01/12 11:48:31 mmeeks 1.18.84.2: Remove a load of unneeded Accessor fluff Fix SimpleReferenceObject - it has to have 1 virtual method. 2007/01/11 10:35:26 mmeeks 1.18.84.1: Submitted by: mmeeks<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: providerimpl.hxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-23 14:09:01 $
 *
 *  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
 *
 ************************************************************************/

#ifndef CONFIGMGR_API_PROVIDERIMPL_HXX_
#define CONFIGMGR_API_PROVIDERIMPL_HXX_

#ifndef CONFIGMGR_TREEPROVIDER_HXX
#include "treeprovider.hxx"
#endif
#ifndef CONFIGMGR_DEFAULTPROVIDER_HXX
#include "defaultprovider.hxx"
#endif
#ifndef _CONFIGMGR_COMMONTYPES_HXX_
#include "commontypes.hxx" // IInterface
#endif

#ifndef CONFIGMGR_MISC_REQUESTOPTIONS_HXX_
#include "requestoptions.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_XTYPECONVERTER_HPP_
#include <com/sun/star/script/XTypeConverter.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

namespace com { namespace sun { namespace star {
    namespace uno
    {
        class Any;
        class XInterface;
        template <class> class Sequence;
        template <class> class Reference;
    }
    namespace beans
    {
        struct PropertyValue;
    }
}   }   }

namespace rtl
{
    class OUString;
    template <class RCType> class Reference;
}

namespace configmgr
{
    namespace css       = ::com::sun::star;
    namespace uno       = css::uno;
    namespace script    = css::script;
    namespace lang      = css::lang;
    namespace beans     = css::beans;
    using ::rtl::OUString;

    class ISubtree;
    class ITemplateManager;
    class IConfigDefaultProvider;
    class TreeManager;
    class ContextReader;
    class OProvider;

    struct IConfigBroadcaster;

    namespace configapi
    {
        class NodeElement;
        class ApiProviderInstances;
        class Factory;
    }

    // -----------------------------------------------------------------------------
    class OProviderImpl : public ITreeManager, public IDefaultableTreeManager, public IInterface
    {
        friend class OProvider;
        friend class OConfigurationProvider;
    public:
        //==========================================================================
        //= FactoryArguments
        //==========================================================================
        /** Helper class for evaluation of the arguments for creating a service instance.*/
        struct FactoryArguments
        {
            /// possible arguments, given only in small letters.
            enum Argument
            {
                ARG_NODEPATH,           // requested node path
                ARG_DEPTH,              // depth of the tree
                ARG_USER_DEPRECATED,    // name of the entity to be manipulated - deprecated version
                ARG_LOCALE,             // desired locale
                ARG_NOCACHE_OBSOLETE,   // cache disabling - obsolete and nonfunctional
                ARG_ASYNC_DEPRECATED,   // lasy write data - deprecated version
                ARG_ASYNC,              // lazy write data
                ARG_ENTITY,             // name of the entity to be manipulated - only for admin
                ARG_REFRESH,            // force refresh of data into cache

                _arg_count,
                ARG_NOT_FOUND = _arg_count
            };
            static sal_Char const * const asciiArgumentNames[];

            static OUString getArgumentName(Argument _which)                CFG_NOTHROW();
            static Argument lookupArgument(OUString const& sArgumentName)   CFG_NOTHROW();

            static OUString getUserArgumentNameD()              CFG_NOTHROW() { return getArgumentName(ARG_USER_DEPRECATED);     }
            static OUString getEntityArgumentName()             CFG_NOTHROW() { return getArgumentName(ARG_ENTITY);     }
            static OUString getNodePathArgumentName()           CFG_NOTHROW() { return getArgumentName(ARG_NODEPATH); }
            static OUString getDepthArgumentNameArgumentName()  CFG_NOTHROW() { return getArgumentName(ARG_DEPTH);    }
            static OUString getLocaleArgumentName()             CFG_NOTHROW() { return getArgumentName(ARG_LOCALE);   }
            static OUString getNoCacheArgumentNameD()           CFG_NOTHROW() { return getArgumentName(ARG_NOCACHE_OBSOLETE);  }
            static OUString getAsyncArgumentName()              CFG_NOTHROW() { return getArgumentName(ARG_ASYNC);    }
        public:
            /** extracts arguments from the argument sequence into to the parameter variables

unknown arguments are ignored

                @throws com::sun::star::lang::IllegalArgumentException
                    if an element of _rArgs had the wrong type or
                    if the value of a known argument has the wrong type or
                    if the value of a known argument is out of range (sometimes)
                    or if no non-empty node path argument could be extracted,
            */
            static void extractArgs(    const uno::Sequence<uno::Any>& _rArgs,
                                        OUString&   /* [out] */ _rNodeAccessor,
                                        sal_Int32&  /* [out] */ _nLevels,
                                        RequestOptions& /* [in/out] */ xOptions
                                   ) CFG_THROW1(lang::IllegalArgumentException);

            static bool extractOneArgument( OUString const& aName, uno::Any const& aValue,
                                            OUString&   /* [out] */ _rNodeAccessor,
                                            sal_Int32&  /* [out] */ _nLevels,
                                            RequestOptions& /* [in/out] */ xOptions
                                          ) CFG_NOTHROW();

        };

    public:
        typedef uno::Reference< uno::XComponentContext >        CreationContext;
        typedef uno::Reference< script::XTypeConverter >        TypeConverterRef;
    private:
        OProvider*                          m_pProvider;        /// used for ref counting, uno representation

        TypeConverterRef                    m_xTypeConverter;
        RequestOptions                      m_aDefaultOptions;
        configapi::ApiProviderInstances*    m_pNewProviders;
        mutable osl::Mutex                  m_aTreeManagerMutex;
        TreeManager*                        m_pTreeManager;     /// the tree cache. Will hold a reference to us as long as it life

        rtl::Reference< TreeManager > maybeGetTreeManager() const CFG_NOTHROW();
        rtl::Reference< TreeManager > getTreeManager() const CFG_UNO_THROW_RTE();
        void setTreeManager(TreeManager * pTreeManager) CFG_UNO_THROW_RTE();
        void clearTreeManager() CFG_NOTHROW();
    public:
        OProviderImpl(OProvider* _pProvider, CreationContext const & _xContext);

        virtual ~OProviderImpl();

        /// ITreeManager
        virtual data::NodeAccess requestSubtree(AbsolutePath const& aSubtreePath, const RequestOptions& _aOptions) CFG_UNO_THROW_ALL(  );
        virtual void updateTree(TreeChangeList& aChanges) CFG_UNO_THROW_ALL(  );

        virtual void releaseSubtree( AbsolutePath const& aSubtreePath, const RequestOptions& _aOptions ) CFG_NOTHROW();
        virtual void saveAndNotifyUpdate(TreeChangeList const& aChanges) CFG_UNO_THROW_ALL(  );
        virtual void disposeData(const RequestOptions& _aOptions) CFG_NOTHROW();
        virtual void fetchSubtree(AbsolutePath const& aSubtreePath, const RequestOptions& _aOptions) CFG_NOTHROW();

        virtual void refreshAll() CFG_UNO_THROW_ALL(  );
        virtual void flushAll() CFG_NOTHROW();
        virtual void enableAsync(const sal_Bool& bEnableAsync) CFG_NOTHROW();

        /// IDefaultableTreeManager
        virtual sal_Bool fetchDefaultData(AbsolutePath const& aSubtreePath, const RequestOptions& _aOptions
                                          ) CFG_UNO_THROW_ALL(  );

        // IInterface
        virtual void SAL_CALL acquire(  ) throw ();
        virtual void SAL_CALL release(  ) throw ();

        // DefaultProvider access
        rtl::Reference< IConfigDefaultProvider >  getDefaultProvider() const CFG_UNO_THROW_RTE( );

        // TemplateManager access
        rtl::Reference< IConfigTemplateManager >  getTemplateProvider() const CFG_UNO_THROW_RTE( );

    protected:
        static OUString getErrorMessage(AbsolutePath const& _rAccessor, const RequestOptions& _aOptions);

        virtual void SAL_CALL dispose() throw();
    public:
        void setDefaultLocale( RequestOptions::Locale const & aLocale );

        RequestOptions const& getDefaultOptions() const {return m_aDefaultOptions;}
        TypeConverterRef getTypeConverter() const {return m_xTypeConverter;}
        configapi::Factory& getWriterFactory();
        IConfigBroadcaster* getNotifier() CFG_NOTHROW();
        uno::XInterface*    getProviderInstance();

        // actual factory methods
        // the returned object (if any) has to be acquired once)
        configapi::NodeElement* buildReadAccess( OUString const& _rAccessor, const RequestOptions& _aOptions, sal_Int32 nMinLevels) CFG_UNO_THROW_ALL(  );
        // the returned object (if any) has to be acquired once)
        configapi::NodeElement* buildUpdateAccess(OUString const& _rAccessor, const RequestOptions& _aOptions, sal_Int32 nMinLevels) CFG_UNO_THROW_ALL(  );

    private:
        bool initSession(const ContextReader& _rSettings);
    private:
        void implInitFromSettings(const ContextReader& _rSettings, bool& rNeedProfile);
        void implInitFromProfile(data::NodeAccess const& aProfile);

        virtual void initFromSettings(const ContextReader& _rSettings, bool& rNeedProfile);
        virtual void initFromProfile(data::NodeAccess const& aProfile);
    };
} // namespace configmgr

#endif // CONFIGMGR_API_PROVIDERIMPL_HXX_

<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	ルネサス RX 選択
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2016, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/byte_order.h"
#include "common/vect.h"
#include "common/delay.hpp"
#include "common/device.hpp"

#include "RX600/port.hpp"
#include "RX600/bus.hpp"

#if defined(SIG_RX63T)
#include "RX600/cmt.hpp"
#include "RX63T/system.hpp"
#include "RX63T/sci.hpp"
#include "RX63T/power_cfg.hpp"

#elif defined(SIG_RX24T)
#include "RX24T/system.hpp"
#include "RX24T/system_io.hpp"
#include "RX24T/mtu3.hpp"
#include "RX24T/poe3.hpp"
#include "RX600/cmt.hpp"
#include "RX24T/sci.hpp"
#include "RX24T/s12ad.hpp"
#include "RX24T/adc_io.hpp"
#include "RX24T/da.hpp"
#include "RX600/cmpc.hpp"
#include "RX24T/flash.hpp"
#include "RX24T/flash_io.hpp"

#elif defined(SIG_RX64M) || defined(SIG_RX71M)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/tpu.hpp"
#include "RX600/cmt.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/scif.hpp"
#include "RX600/can.hpp"
#include "RX600/qspi.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"
#include "RX600/dmac_mgr.hpp"

#elif defined(SIG_RX65N)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/tpu.hpp"
#include "RX600/cmt.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/scif.hpp"
#include "RX600/can.hpp"
#include "RX600/qspi.hpp"
#include "RX65x/s12adf.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/standby_ram.hpp"
#include "RX65x/glcdc.hpp"
#include "RX65x/glcdc_io.hpp"
#include "RX65x/drw2d.hpp"
#include "RX65x/drw2d_mgr.hpp"
#include "RX600/dmac_mgr.hpp"

#elif defined(SIG_RX66T)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/cmt.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/can.hpp"
// #include "RX65x/s12adf.hpp"
// #include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/usb.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/cmpc.hpp"

#else
#  error "renesas.hpp: Requires SIG_XXX to be defined"
#endif

#include "RX600/dtc.hpp"
#include "RX600/gpt.hpp"
#include "RX600/tmr.hpp"
#include "RX600/riic.hpp"
#include "RX600/rspi.hpp"
#include "RX600/crc.hpp"
#include "RX600/mpu.hpp"
#include "RX600/doc.hpp"
<commit_msg>update: include path<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	ルネサス RX 選択
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2016, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/byte_order.h"
#include "common/vect.h"
#include "common/delay.hpp"
#include "common/device.hpp"

#include "RX600/port.hpp"
#include "RX600/bus.hpp"

#if defined(SIG_RX24T)
#include "RX24T/system.hpp"
#include "RX24T/system_io.hpp"
#include "RX24T/mtu3.hpp"
#include "RX24T/poe3.hpp"
#include "RX24T/s12ad.hpp"
#include "RX24T/adc_io.hpp"
#include "RX24T/da.hpp"
#include "RX600/cmpc.hpp"
#include "RX24T/flash.hpp"
#include "RX24T/flash_io.hpp"

#elif defined(SIG_RX64M) || defined(SIG_RX71M)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/tpu.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/can.hpp"
#include "RX600/qspi.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/scif.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"
#include "RX600/dmac_mgr.hpp"

#elif defined(SIG_RX65N)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/tpu.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/can.hpp"
#include "RX600/qspi.hpp"
#include "RX65x/s12adf.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/standby_ram.hpp"
#include "RX65x/glcdc.hpp"
#include "RX65x/glcdc_io.hpp"
#include "RX65x/drw2d.hpp"
#include "RX65x/drw2d_mgr.hpp"
#include "RX600/dmac_mgr.hpp"

#elif defined(SIG_RX66T)
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/mpc.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/can.hpp"
#include "RX600/r12da.hpp"
#include "RX600/usb.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/cmpc.hpp"

#else
#  error "renesas.hpp: Requires SIG_XXX to be defined"
#endif

#include "RX600/dtc.hpp"
#include "RX600/gpt.hpp"
#include "RX600/tmr.hpp"
#include "RX600/cmt.hpp"
#include "RX600/iwdt.hpp"
#include "RX600/sci.hpp"
#include "RX600/riic.hpp"
#include "RX600/rspi.hpp"
#include "RX600/crc.hpp"
#include "RX600/mpu.hpp"
#include "RX600/doc.hpp"
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef VECTOR_H
#define VECTOR_H

#include <types.hpp>
#include <algorithms.hpp>
#include <new.hpp>

//TODO The vector does not call any destructor

namespace std {

template<typename T>
class vector {
public:
    typedef T                       value_type;
    typedef value_type*             pointer_type;
    typedef size_t                  size_type;
    typedef value_type*             iterator;
    typedef const value_type*       const_iterator;

private:
    T* data;
    uint64_t _size;
    uint64_t _capacity;

public:
    vector() : data(nullptr), _size(0), _capacity(0) {}
    explicit vector(uint64_t c) : data(new T[c]), _size(0), _capacity(c) {}

    vector(const vector& rhs) : data(nullptr), _size(rhs._size), _capacity(rhs._capacity) {
        if(!rhs.empty()){
            data = new T[_capacity];

            for(size_t i = 0; i < _size; ++i){
                data[i] = rhs.data[i];
            }
        }
    }

    vector& operator=(const vector& rhs){
        if(data && _capacity < rhs._capacity){
            delete[] data;
            data = nullptr;
        }

        _size = rhs._size;
        _capacity = rhs._capacity;

        if(!rhs.empty()){
            data = new T[_capacity];

            for(size_t i = 0; i < _size; ++i){
                data[i] = rhs.data[i];
            }
        }
    }

    //Move constructors

    vector(vector&& rhs) : data(rhs.data), _size(rhs._size), _capacity(rhs._capacity) {
        rhs.data = nullptr;
        rhs._size = 0;
        rhs._capacity = 0;
    };

    vector& operator=(vector&& rhs){
        if(data){
            delete[] data;
        }

        data = rhs.data;
        _size = rhs._size;
        _capacity = rhs._capacity;
        rhs.data = nullptr;
        rhs._size = 0;
        rhs._capacity = 0;

        return *this;
    }

    ~vector(){
        if(data){
            delete[] data;
        }
    }

    //Getters

    constexpr size_type size() const {
        return _size;
    }

    bool empty() const {
        return _size == 0;
    }

    constexpr size_type capacity() const {
        return _capacity;
    }

    constexpr const value_type& operator[](size_type pos) const {
        return data[pos];
    }

    value_type& operator[](size_type pos){
        return data[pos];
    }

    value_type& front(){
        return data[0];
    }

    const value_type& front() const  {
        return data[0];
    }

    value_type& back(){
        return data[size() - 1];
    }

    const value_type& back() const  {
        return data[size() - 1];
    }

    //Modifiers

    void reserve(size_t new_capacity){
        if(new_capacity > capacity()){
            ensure_capacity(new_capacity);
        }
    }

    void resize(size_t new_size){
        if(new_size > size()){
            ensure_capacity(new_size);

            //The elements will automatically be created to their defaults when
            //the array gets resized in ensure_capacity
            _size = new_size;
        } else if(new_size < _size){
            //By diminishing the size, the last elements become unreachable
            _size = new_size;
        }
    }

    void push_back(value_type&& element){
        ensure_capacity(_size + 1);

        data[_size++] = std::forward<value_type>(element);
    }

    void push_back(const value_type& element){
        ensure_capacity(_size + 1);

        data[_size++] = element;
    }

    template<typename... Args>
    void emplace_back(Args... args){
        ensure_capacity(_size + 1);

        new (&data[_size++]) T(std::forward<Args>(args)...);
    }

    void pop_back(){
        --_size;
    }

    void clear(){
        _size = 0;
    }

    void erase(size_t position){
        for(size_t i = position; i < _size - 1; ++i){
            data[i] = std::move(data[i+1]);
        }

        --_size;
    }

    //Iterators

    iterator begin(){
        return iterator(&data[0]);
    }

    constexpr const_iterator begin() const {
        return const_iterator(&data[0]);
    }

    iterator end(){
        return iterator(&data[_size]);
    }

    constexpr const_iterator end() const {
        return const_iterator(&data[_size]);
    }

private:
    void ensure_capacity(size_t new_capacity){
        if(_capacity == 0){
            _capacity = new_capacity;
            data = new T[_capacity];
        } else if(_capacity < new_capacity){
            _capacity= _capacity * 2;
            if(new_capacity > _capacity){
                _capacity = new_capacity;
            }

            auto new_data = new T[_capacity];
            std::move_n(new_data, data, _size);

            delete[] data;
            data = new_data;
        }
    }
};

} //end of namespace std

#endif
<commit_msg>Fix bug<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef VECTOR_H
#define VECTOR_H

#include <types.hpp>
#include <algorithms.hpp>
#include <new.hpp>

//TODO The vector does not call any destructor

namespace std {

template<typename T>
class vector {
public:
    typedef T                       value_type;
    typedef value_type*             pointer_type;
    typedef size_t                  size_type;
    typedef value_type*             iterator;
    typedef const value_type*       const_iterator;

private:
    T* data;
    uint64_t _size;
    uint64_t _capacity;

public:
    vector() : data(nullptr), _size(0), _capacity(0) {}
    explicit vector(uint64_t c) : data(new T[c]), _size(0), _capacity(c) {}

    vector(const vector& rhs) : data(nullptr), _size(rhs._size), _capacity(rhs._capacity) {
        if(!rhs.empty()){
            data = new T[_capacity];

            for(size_t i = 0; i < _size; ++i){
                data[i] = rhs.data[i];
            }
        }
    }

    vector& operator=(const vector& rhs){
        if(data && _capacity < rhs._capacity){
            delete[] data;
            data = nullptr;
        }

        _size = rhs._size;
        _capacity = rhs._capacity;

        if(!rhs.empty()){
            data = new T[_capacity];

            for(size_t i = 0; i < _size; ++i){
                data[i] = rhs.data[i];
            }
        }

        return *this;
    }

    //Move constructors

    vector(vector&& rhs) : data(rhs.data), _size(rhs._size), _capacity(rhs._capacity) {
        rhs.data = nullptr;
        rhs._size = 0;
        rhs._capacity = 0;
    };

    vector& operator=(vector&& rhs){
        if(data){
            delete[] data;
        }

        data = rhs.data;
        _size = rhs._size;
        _capacity = rhs._capacity;
        rhs.data = nullptr;
        rhs._size = 0;
        rhs._capacity = 0;

        return *this;
    }

    ~vector(){
        if(data){
            delete[] data;
        }
    }

    //Getters

    constexpr size_type size() const {
        return _size;
    }

    bool empty() const {
        return _size == 0;
    }

    constexpr size_type capacity() const {
        return _capacity;
    }

    constexpr const value_type& operator[](size_type pos) const {
        return data[pos];
    }

    value_type& operator[](size_type pos){
        return data[pos];
    }

    value_type& front(){
        return data[0];
    }

    const value_type& front() const  {
        return data[0];
    }

    value_type& back(){
        return data[size() - 1];
    }

    const value_type& back() const  {
        return data[size() - 1];
    }

    //Modifiers

    void reserve(size_t new_capacity){
        if(new_capacity > capacity()){
            ensure_capacity(new_capacity);
        }
    }

    void resize(size_t new_size){
        if(new_size > size()){
            ensure_capacity(new_size);

            //The elements will automatically be created to their defaults when
            //the array gets resized in ensure_capacity
            _size = new_size;
        } else if(new_size < _size){
            //By diminishing the size, the last elements become unreachable
            _size = new_size;
        }
    }

    void push_back(value_type&& element){
        ensure_capacity(_size + 1);

        data[_size++] = std::forward<value_type>(element);
    }

    void push_back(const value_type& element){
        ensure_capacity(_size + 1);

        data[_size++] = element;
    }

    template<typename... Args>
    void emplace_back(Args... args){
        ensure_capacity(_size + 1);

        new (&data[_size++]) T(std::forward<Args>(args)...);
    }

    void pop_back(){
        --_size;
    }

    void clear(){
        _size = 0;
    }

    void erase(size_t position){
        for(size_t i = position; i < _size - 1; ++i){
            data[i] = std::move(data[i+1]);
        }

        --_size;
    }

    //Iterators

    iterator begin(){
        return iterator(&data[0]);
    }

    constexpr const_iterator begin() const {
        return const_iterator(&data[0]);
    }

    iterator end(){
        return iterator(&data[_size]);
    }

    constexpr const_iterator end() const {
        return const_iterator(&data[_size]);
    }

private:
    void ensure_capacity(size_t new_capacity){
        if(_capacity == 0){
            _capacity = new_capacity;
            data = new T[_capacity];
        } else if(_capacity < new_capacity){
            _capacity= _capacity * 2;
            if(new_capacity > _capacity){
                _capacity = new_capacity;
            }

            auto new_data = new T[_capacity];
            std::move_n(new_data, data, _size);

            delete[] data;
            data = new_data;
        }
    }
};

} //end of namespace std

#endif
<|endoftext|>


<commit_before>#include "TH1.h"
#include "TF1.h"
#include "TLegend.h"
#include "TCanvas.h"

// Quadratic background function
Double_t background(Double_t *x, Double_t *par) {
   return par[0] + par[1]*x[0] + par[2]*x[0]*x[0];
}

// Lorenzian Peak function
Double_t lorentzianPeak(Double_t *x, Double_t *par) {
  return (0.5*par[0]*par[1]/TMath::Pi()) /
    TMath::Max( 1.e-10,(x[0]-par[2])*(x[0]-par[2]) + .25*par[1]*par[1]);
}

// Sum of background and peak function
Double_t fitFunction(Double_t *x, Double_t *par) {
  return background(x,par) + lorentzianPeak(x,&par[3]);
}

void FittingDemo() {
 //Bevington Exercise by Peter Malzacher, modified by Rene Brun

   const int nBins = 60;

   Stat_t data[nBins] = { 6, 1,10,12, 6,13,23,22,15,21,
                         23,26,36,25,27,35,40,44,66,81,
                         75,57,48,45,46,41,35,36,53,32,
                         40,37,38,31,36,44,42,37,32,32,
                         43,44,35,33,33,39,29,41,32,44,
                         26,39,29,35,32,21,21,15,25,15};
   TCanvas *c1 = new TCanvas("c1","Fitting Demo",10,10,700,500);
   c1->SetFillColor(33);
   c1->SetFrameFillColor(41);
   c1->SetGrid();

   TH1F *histo = new TH1F("histo","Lorentzian Peak on Quadratic Background",60,0,3);
   histo->SetMarkerStyle(21);
   histo->SetMarkerSize(0.8);
   histo->SetStats(0);

   for(int i=0; i < nBins;  i++) histo->SetBinContent(i+1,data[i]);

   // create a TF1 with the range from 0 to 3 and 6 parameters
   TF1 *fitFcn = new TF1("fitFcn",fitFunction,0,3,6);
   fitFcn->SetNpx(500);
   fitFcn->SetLineWidth(4);
   fitFcn->SetLineColor(kMagenta);

   // first try without starting values for the parameters
   // This defaults to 1 for each param.
   // this results in an ok fit for the polynomial function
   // however the non-linear part (lorenzian) does not
   // respond well.
   histo->Fit("fitFcn","0");

   // second try: set start values for some parameters
   fitFcn->SetParameter(4,0.2); // width
   fitFcn->SetParameter(5,1);   // peak

   histo->Fit("fitFcn","V+","ep");

   // improve the picture:
   TF1 *backFcn = new TF1("backFcn",background,0,3,3);
   backFcn->SetLineColor(kRed);
   TF1 *signalFcn = new TF1("signalFcn",lorentzianPeak,0,3,3);
   signalFcn->SetLineColor(kBlue);
   signalFcn->SetNpx(500);
   Double_t par[6];

   // writes the fit results into the par array
   fitFcn->GetParameters(par);

   backFcn->SetParameters(par);
   backFcn->Draw("same");

   signalFcn->SetParameters(&par[3]);
   signalFcn->Draw("same");

   // draw the legend
   TLegend *legend=new TLegend(0.6,0.65,0.88,0.85);
   legend->SetTextFont(72);
   legend->SetTextSize(0.04);
   legend->AddEntry(histo,"Data","lp");
   legend->AddEntry(backFcn,"Background fit","l");
   legend->AddEntry(signalFcn,"Signal fit","l");
   legend->AddEntry(fitFcn,"Global Fit","l");
   legend->Draw();

}
<commit_msg>Preset parameters for fitFcn to have the same result between Minuit and Fumili.<commit_after>#include "TH1.h"
#include "TF1.h"
#include "TLegend.h"
#include "TCanvas.h"

// Quadratic background function
Double_t background(Double_t *x, Double_t *par) {
   return par[0] + par[1]*x[0] + par[2]*x[0]*x[0];
}

// Lorenzian Peak function
Double_t lorentzianPeak(Double_t *x, Double_t *par) {
  return (0.5*par[0]*par[1]/TMath::Pi()) /
    TMath::Max( 1.e-10,(x[0]-par[2])*(x[0]-par[2]) + .25*par[1]*par[1]);
}

// Sum of background and peak function
Double_t fitFunction(Double_t *x, Double_t *par) {
  return background(x,par) + lorentzianPeak(x,&par[3]);
}

void FittingDemo() {
 //Bevington Exercise by Peter Malzacher, modified by Rene Brun

   const int nBins = 60;

   Stat_t data[nBins] = { 6, 1,10,12, 6,13,23,22,15,21,
                         23,26,36,25,27,35,40,44,66,81,
                         75,57,48,45,46,41,35,36,53,32,
                         40,37,38,31,36,44,42,37,32,32,
                         43,44,35,33,33,39,29,41,32,44,
                         26,39,29,35,32,21,21,15,25,15};
   TCanvas *c1 = new TCanvas("c1","Fitting Demo",10,10,700,500);
   c1->SetFillColor(33);
   c1->SetFrameFillColor(41);
   c1->SetGrid();

   TH1F *histo = new TH1F("histo","Lorentzian Peak on Quadratic Background",60,0,3);
   histo->SetMarkerStyle(21);
   histo->SetMarkerSize(0.8);
   histo->SetStats(0);

   for(int i=0; i < nBins;  i++) histo->SetBinContent(i+1,data[i]);

   // create a TF1 with the range from 0 to 3 and 6 parameters
   TF1 *fitFcn = new TF1("fitFcn",fitFunction,0,3,6);
   fitFcn->SetNpx(500);
   fitFcn->SetLineWidth(4);
   fitFcn->SetLineColor(kMagenta);

   // first try without starting values for the parameters
   // This defaults to 1 for each param.
   // this results in an ok fit for the polynomial function
   // however the non-linear part (lorenzian) does not
   // respond well.
   fitFcn->SetParameters(1,1,1,1,1,1);
   histo->Fit("fitFcn","0");

   // second try: set start values for some parameters
   fitFcn->SetParameter(4,0.2); // width
   fitFcn->SetParameter(5,1);   // peak

   histo->Fit("fitFcn","V+","ep");

   // improve the picture:
   TF1 *backFcn = new TF1("backFcn",background,0,3,3);
   backFcn->SetLineColor(kRed);
   TF1 *signalFcn = new TF1("signalFcn",lorentzianPeak,0,3,3);
   signalFcn->SetLineColor(kBlue);
   signalFcn->SetNpx(500);
   Double_t par[6];

   // writes the fit results into the par array
   fitFcn->GetParameters(par);

   backFcn->SetParameters(par);
   backFcn->Draw("same");

   signalFcn->SetParameters(&par[3]);
   signalFcn->Draw("same");

   // draw the legend
   TLegend *legend=new TLegend(0.6,0.65,0.88,0.85);
   legend->SetTextFont(72);
   legend->SetTextSize(0.04);
   legend->AddEntry(histo,"Data","lp");
   legend->AddEntry(backFcn,"Background fit","l");
   legend->AddEntry(signalFcn,"Signal fit","l");
   legend->AddEntry(fitFcn,"Global Fit","l");
   legend->Draw();

}
<|endoftext|>


<commit_before>#pragma once
#ifndef AMFDICTIONARY_HPP
#define AMFDICTIONARY_HPP

#include "amfitem.hpp"
#include "amfinteger.hpp"
#include "amfstring.hpp"

#include <functional>
#include <unordered_map>

namespace std {
	template<>
	struct hash<std::vector<u8>> {
	public:
		std::size_t operator()(const std::vector<u8>& s) const {
			std::string chars(s.begin(), s.end());
			return std::hash<std::string>()(chars);
		}
	};
}

// Flash Player doesn't support deserializing booleans and number types
// (AmfInteger/AmfDouble), so we have to serialize them as strings
template<class T>
struct AmfDictionaryKeyConverter {
	static std::vector<u8> convert(const T& item) {
		return item.serialize();
	}
};

template<>
struct AmfDictionaryKeyConverter<AmfInteger> {
	static std::vector<u8> convert(const AmfInteger& item) {
		std::string val = std::to_string(static_cast<int>(item));
		return AmfString(val).serialize();
	}
};

template<>
struct AmfDictionaryKeyConverter<AmfDouble> {
	static std::vector<u8> convert(const AmfDouble& item) {
		std::string val = std::to_string(static_cast<double>(item));
		return AmfString(val).serialize();
	}
};

template<>
struct AmfDictionaryKeyConverter<AmfBool> {
	static std::vector<u8> convert(const AmfBool& item) {
		return AmfString(item ? "true" : "false").serialize();
	}
};

class AmfDictionary : public AmfItem {
public:
	AmfDictionary(bool weak = false) : weak(weak) { };

	template<class T>
	std::vector<u8>& operator[](const T& item) {
		return values[AmfDictionaryKeyConverter<T>::convert(item)];
	}

	std::vector<u8> serialize() const {
		std::vector<u8> buf = AmfInteger(values.size()).asLength(AMF_DICTIONARY);

		buf.push_back(weak ? 0x01 : 0x00);

		for (auto it : values) {
			buf.insert(buf.end(), it.first.begin(), it.first.end());
			buf.insert(buf.end(), it.second.begin(), it.second.end());
		}

		return buf;
	}

private:
	bool weak;
	std::unordered_map<std::vector<u8>, std::vector<u8>> values;
};

#endif
<commit_msg>Add utility function for key/value insertation.<commit_after>#pragma once
#ifndef AMFDICTIONARY_HPP
#define AMFDICTIONARY_HPP

#include "amfitem.hpp"
#include "amfinteger.hpp"
#include "amfstring.hpp"

#include <functional>
#include <unordered_map>

namespace std {
	template<>
	struct hash<std::vector<u8>> {
	public:
		std::size_t operator()(const std::vector<u8>& s) const {
			std::string chars(s.begin(), s.end());
			return std::hash<std::string>()(chars);
		}
	};
}

// Flash Player doesn't support deserializing booleans and number types
// (AmfInteger/AmfDouble), so we have to serialize them as strings
template<class T>
struct AmfDictionaryKeyConverter {
	static std::vector<u8> convert(const T& item) {
		return item.serialize();
	}
};

template<>
struct AmfDictionaryKeyConverter<AmfInteger> {
	static std::vector<u8> convert(const AmfInteger& item) {
		std::string val = std::to_string(static_cast<int>(item));
		return AmfString(val).serialize();
	}
};

template<>
struct AmfDictionaryKeyConverter<AmfDouble> {
	static std::vector<u8> convert(const AmfDouble& item) {
		std::string val = std::to_string(static_cast<double>(item));
		return AmfString(val).serialize();
	}
};

template<>
struct AmfDictionaryKeyConverter<AmfBool> {
	static std::vector<u8> convert(const AmfBool& item) {
		return AmfString(item ? "true" : "false").serialize();
	}
};

class AmfDictionary : public AmfItem {
public:
	AmfDictionary(bool weak = false) : weak(weak) { };

	template<class T>
	std::vector<u8>& operator[](const T& item) {
		return values[AmfDictionaryKeyConverter<T>::convert(item)];
	}

	template<class T, class U>
	void insert(const T& key, const U& value) {
		(*this)[key] = value.serialize();
	}

	std::vector<u8> serialize() const {
		std::vector<u8> buf = AmfInteger(values.size()).asLength(AMF_DICTIONARY);

		buf.push_back(weak ? 0x01 : 0x00);

		for (auto it : values) {
			buf.insert(buf.end(), it.first.begin(), it.first.end());
			buf.insert(buf.end(), it.second.begin(), it.second.end());
		}

		return buf;
	}

private:
	bool weak;
	std::unordered_map<std::vector<u8>, std::vector<u8>> values;
};

#endif
<|endoftext|>


<commit_before>
// Copyright 2014 Toggl Desktop developers.

#include "./ui.h"

#include <cstdlib>
#include <sstream>

namespace kopsik {

void UI::DisplayLogin(const _Bool open, const uint64_t user_id) {
    logger().debug("DisplayLogin");

    on_display_login_(open, user_id);
}

_Bool UI::DisplayError(const error err) {
    if (noError == err) {
        return true;
    }

    if (isNetworkingError(err)) {
        DisplayOnlineState(false);
        return false;
    }

    logger().debug("DisplayError");

    if (err.find("Request to server failed with status code: 403")
            != std::string::npos) {
        on_display_error_("Invalid e-mail or password!", true);
        return false;
    }

    on_display_error_(err.c_str(), isUserError(err));
    return false;
}

error UI::VerifyCallbacks() {
    logger().debug("VerifyCallbacks");
    error err = findMissingCallbacks();
    if (err != noError) {
        logger().error(err);
    }
    std::stringstream ss;
    ss << "sizeof(KopsikTimeEntryViewItem)=" << sizeof(KopsikTimeEntryViewItem)
       << ", sizeof(KopsikAutocompleteItem)=" << sizeof(KopsikAutocompleteItem)
       << ", sizeof(KopsikViewItem)=" << sizeof(KopsikViewItem)
       << ", sizeof(KopsikSettingsViewItem)=" << sizeof(KopsikSettingsViewItem)
       << std::endl;
    logger().debug(ss.str());
    return err;
}

error UI::findMissingCallbacks() {
    if (!on_display_error_) {
        return error("!on_display_error_");
    }
    if (!on_display_update_) {
        return error("!on_display_update_");
    }
    if (!on_display_online_state_) {
        return error("!on_display_online_state_");
    }
    if (!on_display_login_) {
        return error("!on_display_login_");
    }
    if (!on_display_url_) {
        return error("!on_display_url_");
    }
    if (!on_display_reminder_) {
        return error("!on_display_reminder_");
    }
    if (!on_display_time_entry_list_) {
        return error("!on_display_time_entry_list_");
    }
    if (!on_display_autocomplete_) {
        return error("!on_display_autocomplete_");
    }
    if (!on_display_workspace_select_) {
        return error("!on_display_workspace_select_");
    }
    if (!on_display_client_select_) {
        return error("!on_display_client_select_");
    }
    if (!on_display_tags_) {
        return error("!on_display_tags_");
    }
    if (!on_display_time_entry_editor_) {
        return error("!on_display_time_entry_editor_");
    }
    if (!on_display_settings_) {
        return error("!on_display_settings_");
    }
    if (!on_display_timer_state_) {
        return error("!on_display_timer_state_");
    }
    return noError;
}

void UI::DisplayReminder() {
    logger().debug("DisplayReminder");

    on_display_reminder_("Reminder from Toggl Desktop",
                         "Don't forget to track your time!");
}

void UI::DisplayOnlineState(const _Bool is_online) {
    logger().debug("DisplayOnlineState");

    on_display_online_state_(is_online);
}

void UI::DisplayUpdate(const bool is_available,
                       const std::string url,
                       const std::string version) {
    logger().debug("DisplayUpdate");

    on_display_update_(is_available, url.c_str(), version.c_str());
}

void UI::DisplayAutocomplete(std::vector<kopsik::AutocompleteItem> *items) {
    logger().debug("DisplayAutocomplete");

    KopsikAutocompleteItem *first = 0;
    for (std::vector<kopsik::AutocompleteItem>::const_iterator it =
        items->begin(); it != items->end(); it++) {
        KopsikAutocompleteItem *item = autocomplete_item_init(*it);
        item->Next = first;
        first = item;
    }
    on_display_autocomplete_(first);
    autocomplete_item_clear(first);
}

void UI::DisplayTimeEntryList(const _Bool open,
                              KopsikTimeEntryViewItem* first) {
    logger().debug("DisplayTimeEntryList");
    on_display_time_entry_list_(open, first);
}

void UI::DisplayTags(std::vector<std::string> *tags) {
    logger().debug("DisplayTags");

    KopsikViewItem *first = 0;
    for (std::vector<std::string>::const_iterator it = tags->begin();
            it != tags->end(); it++) {
        std::string name = *it;
        KopsikViewItem *item = tag_to_view_item(name);
        item->Next = first;
        first = item;
    }
    on_display_tags_(first);
    view_item_clear(first);
}

void UI::DisplayClientSelect(std::vector<kopsik::Client *> *clients) {
    logger().debug("DisplayClientSelect");

    KopsikViewItem *first = 0;
    for (std::vector<kopsik::Client *>::const_iterator it = clients->begin();
            it != clients->end(); it++) {
        KopsikViewItem *item = client_to_view_item(*it);
        item->Next = first;
        first = item;
    }
    on_display_client_select_(first);
    view_item_clear(first);
}

void UI::DisplayWorkspaceSelect(std::vector<kopsik::Workspace *> *list) {
    logger().debug("DisplayWorkspaceSelect");

    KopsikViewItem *first = 0;
    for (std::vector<kopsik::Workspace *>::const_iterator it =
        list->begin(); it != list->end(); it++) {
        KopsikViewItem *item = workspace_to_view_item(*it);
        item->Next = first;
        first = item;
    }
    on_display_workspace_select_(first);
    view_item_clear(first);
}

void UI::DisplayTimeEntryEditor(const _Bool open,
                                KopsikTimeEntryViewItem *te,
                                const std::string focused_field_name) {
    logger().debug("DisplayTimeEntryEditor");
    on_display_time_entry_editor_(open, te, focused_field_name.c_str());
}

void UI::DisplayURL(const std::string URL) {
    logger().debug("DisplayURL");

    on_display_url_(URL.c_str());
}

void UI::DisplaySettings(const _Bool open,
                         const _Bool record_timeline,
                         const Settings settings,
                         const _Bool use_proxy,
                         const Proxy proxy) {
    logger().debug("DisplaySettings");

    KopsikSettingsViewItem *view = settings_view_item_init(
        record_timeline,
        settings,
        use_proxy,
        proxy);

    on_display_settings_(open, view);

    settings_view_item_clear(view);
}

void UI::DisplayTimerState(KopsikTimeEntryViewItem *te) {
    logger().debug("DisplayTimerState");
    on_display_timer_state_(te);
}

_Bool UI::isNetworkingError(const error err) const {
    std::string value(err);
    if (value.find("Host not found") != std::string::npos) {
        return true;
    }
    if (value.find("Cannot upgrade to WebSocket connection")
            != std::string::npos) { // NOLINT
        return true;
    }
    if (value.find("No message received") != std::string::npos) {
        return true;
    }
    if (value.find("Connection refused") != std::string::npos) {
        return true;
    }
    if (value.find("Connection timed out") != std::string::npos) {
        return true;
    }
    if (value.find("connect timed out") != std::string::npos) {
        return true;
    }
    if (value.find("SSL connection unexpectedly closed") != std::string::npos) {
        return true;
    }
    if (value.find("Network is down") != std::string::npos) {
        return true;
    }
    if (value.find("Network is unreachable") != std::string::npos) {
        return true;
    }
    if (value.find("Host is down") != std::string::npos) {
        return true;
    }
    if (value.find("No route to host") != std::string::npos) {
        return true;
    }
    if ((value.find("I/O error: 1") != std::string::npos)
            && (value.find(":443") != std::string::npos)) {
        return true;
    }
    if (value.find("The request timed out") != std::string::npos) {
        return true;
    }
    if (value.find("Could not connect to the server") != std::string::npos) {
        return true;
    }
    if (value.find("Connection reset by peer") != std::string::npos) {
        return true;
    }
    if (value.find("The Internet connection appears to be offline")
            != std::string::npos) {
        return true;
    }
    return false;
}

_Bool UI::isUserError(const error err) const {
    if (noError == err) {
        return false;
    }
    std::string value(err);
    if (value.find("is suspended") != std::string::npos) {
        return true;
    }
    if (value.find("Request to server failed with status code: 403")
            != std::string::npos) {
        return true;
    }
    return false;
}

}  // namespace kopsik
<commit_msg>Log sizeof view struct field types<commit_after>
// Copyright 2014 Toggl Desktop developers.

#include "./ui.h"

#include <cstdlib>
#include <sstream>

namespace kopsik {

void UI::DisplayLogin(const _Bool open, const uint64_t user_id) {
    logger().debug("DisplayLogin");

    on_display_login_(open, user_id);
}

_Bool UI::DisplayError(const error err) {
    if (noError == err) {
        return true;
    }

    if (isNetworkingError(err)) {
        DisplayOnlineState(false);
        return false;
    }

    logger().debug("DisplayError");

    if (err.find("Request to server failed with status code: 403")
            != std::string::npos) {
        on_display_error_("Invalid e-mail or password!", true);
        return false;
    }

    on_display_error_(err.c_str(), isUserError(err));
    return false;
}

error UI::VerifyCallbacks() {
    logger().debug("VerifyCallbacks");
    error err = findMissingCallbacks();
    if (err != noError) {
        logger().error(err);
    }
    std::stringstream ss;
    ss << "sizeof(int64_t)=" << sizeof(int64_t)
       << ", sizeof(uint64_t)=" << sizeof(uint64_t)
       << ", sizeof(_Bool)=" << sizeof(_Bool)
       << ", sizeof(void *)=" << sizeof(void *)  // NOLINT
       << ", sizeof(KopsikTimeEntryViewItem)=" <<
       sizeof(KopsikTimeEntryViewItem)
       << ", sizeof(KopsikAutocompleteItem)=" << sizeof(KopsikAutocompleteItem)
       << ", sizeof(KopsikViewItem)=" << sizeof(KopsikViewItem)
       << ", sizeof(KopsikSettingsViewItem)=" << sizeof(KopsikSettingsViewItem)
       << std::endl;
    logger().debug(ss.str());
    return err;
}

error UI::findMissingCallbacks() {
    if (!on_display_error_) {
        return error("!on_display_error_");
    }
    if (!on_display_update_) {
        return error("!on_display_update_");
    }
    if (!on_display_online_state_) {
        return error("!on_display_online_state_");
    }
    if (!on_display_login_) {
        return error("!on_display_login_");
    }
    if (!on_display_url_) {
        return error("!on_display_url_");
    }
    if (!on_display_reminder_) {
        return error("!on_display_reminder_");
    }
    if (!on_display_time_entry_list_) {
        return error("!on_display_time_entry_list_");
    }
    if (!on_display_autocomplete_) {
        return error("!on_display_autocomplete_");
    }
    if (!on_display_workspace_select_) {
        return error("!on_display_workspace_select_");
    }
    if (!on_display_client_select_) {
        return error("!on_display_client_select_");
    }
    if (!on_display_tags_) {
        return error("!on_display_tags_");
    }
    if (!on_display_time_entry_editor_) {
        return error("!on_display_time_entry_editor_");
    }
    if (!on_display_settings_) {
        return error("!on_display_settings_");
    }
    if (!on_display_timer_state_) {
        return error("!on_display_timer_state_");
    }
    return noError;
}

void UI::DisplayReminder() {
    logger().debug("DisplayReminder");

    on_display_reminder_("Reminder from Toggl Desktop",
                         "Don't forget to track your time!");
}

void UI::DisplayOnlineState(const _Bool is_online) {
    logger().debug("DisplayOnlineState");

    on_display_online_state_(is_online);
}

void UI::DisplayUpdate(const bool is_available,
                       const std::string url,
                       const std::string version) {
    logger().debug("DisplayUpdate");

    on_display_update_(is_available, url.c_str(), version.c_str());
}

void UI::DisplayAutocomplete(std::vector<kopsik::AutocompleteItem> *items) {
    logger().debug("DisplayAutocomplete");

    KopsikAutocompleteItem *first = 0;
    for (std::vector<kopsik::AutocompleteItem>::const_iterator it =
        items->begin(); it != items->end(); it++) {
        KopsikAutocompleteItem *item = autocomplete_item_init(*it);
        item->Next = first;
        first = item;
    }
    on_display_autocomplete_(first);
    autocomplete_item_clear(first);
}

void UI::DisplayTimeEntryList(const _Bool open,
                              KopsikTimeEntryViewItem* first) {
    logger().debug("DisplayTimeEntryList");
    on_display_time_entry_list_(open, first);
}

void UI::DisplayTags(std::vector<std::string> *tags) {
    logger().debug("DisplayTags");

    KopsikViewItem *first = 0;
    for (std::vector<std::string>::const_iterator it = tags->begin();
            it != tags->end(); it++) {
        std::string name = *it;
        KopsikViewItem *item = tag_to_view_item(name);
        item->Next = first;
        first = item;
    }
    on_display_tags_(first);
    view_item_clear(first);
}

void UI::DisplayClientSelect(std::vector<kopsik::Client *> *clients) {
    logger().debug("DisplayClientSelect");

    KopsikViewItem *first = 0;
    for (std::vector<kopsik::Client *>::const_iterator it = clients->begin();
            it != clients->end(); it++) {
        KopsikViewItem *item = client_to_view_item(*it);
        item->Next = first;
        first = item;
    }
    on_display_client_select_(first);
    view_item_clear(first);
}

void UI::DisplayWorkspaceSelect(std::vector<kopsik::Workspace *> *list) {
    logger().debug("DisplayWorkspaceSelect");

    KopsikViewItem *first = 0;
    for (std::vector<kopsik::Workspace *>::const_iterator it =
        list->begin(); it != list->end(); it++) {
        KopsikViewItem *item = workspace_to_view_item(*it);
        item->Next = first;
        first = item;
    }
    on_display_workspace_select_(first);
    view_item_clear(first);
}

void UI::DisplayTimeEntryEditor(const _Bool open,
                                KopsikTimeEntryViewItem *te,
                                const std::string focused_field_name) {
    logger().debug("DisplayTimeEntryEditor");
    on_display_time_entry_editor_(open, te, focused_field_name.c_str());
}

void UI::DisplayURL(const std::string URL) {
    logger().debug("DisplayURL");

    on_display_url_(URL.c_str());
}

void UI::DisplaySettings(const _Bool open,
                         const _Bool record_timeline,
                         const Settings settings,
                         const _Bool use_proxy,
                         const Proxy proxy) {
    logger().debug("DisplaySettings");

    KopsikSettingsViewItem *view = settings_view_item_init(
        record_timeline,
        settings,
        use_proxy,
        proxy);

    on_display_settings_(open, view);

    settings_view_item_clear(view);
}

void UI::DisplayTimerState(KopsikTimeEntryViewItem *te) {
    logger().debug("DisplayTimerState");
    on_display_timer_state_(te);
}

_Bool UI::isNetworkingError(const error err) const {
    std::string value(err);
    if (value.find("Host not found") != std::string::npos) {
        return true;
    }
    if (value.find("Cannot upgrade to WebSocket connection")
            != std::string::npos) { // NOLINT
        return true;
    }
    if (value.find("No message received") != std::string::npos) {
        return true;
    }
    if (value.find("Connection refused") != std::string::npos) {
        return true;
    }
    if (value.find("Connection timed out") != std::string::npos) {
        return true;
    }
    if (value.find("connect timed out") != std::string::npos) {
        return true;
    }
    if (value.find("SSL connection unexpectedly closed") != std::string::npos) {
        return true;
    }
    if (value.find("Network is down") != std::string::npos) {
        return true;
    }
    if (value.find("Network is unreachable") != std::string::npos) {
        return true;
    }
    if (value.find("Host is down") != std::string::npos) {
        return true;
    }
    if (value.find("No route to host") != std::string::npos) {
        return true;
    }
    if ((value.find("I/O error: 1") != std::string::npos)
            && (value.find(":443") != std::string::npos)) {
        return true;
    }
    if (value.find("The request timed out") != std::string::npos) {
        return true;
    }
    if (value.find("Could not connect to the server") != std::string::npos) {
        return true;
    }
    if (value.find("Connection reset by peer") != std::string::npos) {
        return true;
    }
    if (value.find("The Internet connection appears to be offline")
            != std::string::npos) {
        return true;
    }
    return false;
}

_Bool UI::isUserError(const error err) const {
    if (noError == err) {
        return false;
    }
    std::string value(err);
    if (value.find("is suspended") != std::string::npos) {
        return true;
    }
    if (value.find("Request to server failed with status code: 403")
            != std::string::npos) {
        return true;
    }
    return false;
}

}  // namespace kopsik
<|endoftext|>


<commit_before>#ifndef VM_HH
#define VM_HH

#include <memory>
#include <vector>
#include <deque>
#include <iosfwd>

#include "lisp_ptr.hh"
#include "cons.hh"
#include "symbol.hh"
#include "env.hh"

class VM {
public:
  struct winding {
    Lisp_ptr before;
    Lisp_ptr thunk;
    Lisp_ptr after;
  };

  VM();
  VM(const VM&);
  VM(VM&&) = delete;

  ~VM();

  VM& operator=(const VM&);
  VM& operator=(VM&&) = delete;

  void set_frame(Env* e){ frame_ = e; }
  Env* frame() const { return frame_; }

  Lisp_ptr find(Symbol*);
  void set(Symbol*, Lisp_ptr);
  void local_set(Symbol*, Lisp_ptr);

  SymTable& symtable(){ return *symtable_; }

  friend std::ostream& operator<<(std::ostream&, const VM&);

public:
  std::deque<Lisp_ptr> code;
  std::vector<Lisp_ptr> stack;
  std::vector<Lisp_ptr> return_value;

  std::vector<winding> extent;

private:
  Env* frame_;
  std::shared_ptr<SymTable> symtable_;
};

extern VM vm;

#include "vm.i.hh"

#endif //VM_HH
<commit_msg>changed deque->vector in vm<commit_after>#ifndef VM_HH
#define VM_HH

#include <memory>
#include <vector>
#include <iosfwd>

#include "lisp_ptr.hh"
#include "cons.hh"
#include "symbol.hh"
#include "env.hh"

class VM {
public:
  struct winding {
    Lisp_ptr before;
    Lisp_ptr thunk;
    Lisp_ptr after;
  };

  VM();
  VM(const VM&);
  VM(VM&&) = delete;

  ~VM();

  VM& operator=(const VM&);
  VM& operator=(VM&&) = delete;

  void set_frame(Env* e){ frame_ = e; }
  Env* frame() const { return frame_; }

  Lisp_ptr find(Symbol*);
  void set(Symbol*, Lisp_ptr);
  void local_set(Symbol*, Lisp_ptr);

  SymTable& symtable(){ return *symtable_; }

  friend std::ostream& operator<<(std::ostream&, const VM&);

public:
  std::vector<Lisp_ptr> code;
  std::vector<Lisp_ptr> stack;
  std::vector<Lisp_ptr> return_value;

  std::vector<winding> extent;

private:
  Env* frame_;
  std::shared_ptr<SymTable> symtable_;
};

extern VM vm;

#include "vm.i.hh"

#endif //VM_HH
<|endoftext|>


<commit_before>#include <boost/test/unit_test.hpp>

#include "SoftXMT.hpp"
#include "GlobalTaskJoiner.hpp"
#include "ForkJoin.hpp"
#include "AsyncParallelFor.hpp"
#include "Delegate.hpp"

#include "PerformanceTools.hpp"

BOOST_AUTO_TEST_SUITE( AsyncParallelFor_Global_tests );

#define MAX_NODES 8
#define SIZE 10000
int64_t done[SIZE*MAX_NODES] = {0};
int64_t count2 = 0;
int64_t global_count = 0;
int64_t local_count = 0;

void loop_body(int64_t start, int64_t num ) {
  /*BOOST_MESSAGE( "execute [" << start << ","
            << start+num << ") with thread " << CURRENT_THREAD->id );*/
  BOOST_CHECK( num <= FLAGS_async_par_for_threshold );
  for (int i=start; i<start+num; i++) {
    int64_t marked = SoftXMT_delegate_fetch_and_add_word( make_global( &done[i], 0 ), 1 );
    BOOST_CHECK( marked == 0 );

    SoftXMT_delegate_fetch_and_add_word( make_global( &global_count, 0 ), 1 );
    local_count++;
  }
}

struct parallel_func : public ForkJoinIteration {
  void operator()(int64_t nid) const {
    int64_t start = nid * SIZE;
    int64_t iters = SIZE;

    global_joiner.reset();
    async_parallel_for<&loop_body, &joinerSpawn<&loop_body> > ( start, iters );
    global_joiner.wait();
  }
};

// don't care what type goes into the GlobalAddress
typedef int64_t dummy_t;

void loop_body2(int64_t start, int64_t num, GlobalAddress<dummy_t> shared_arg_packed) {
  /*BOOST_MESSAGE( "execute [" << start << ","
            << start+num << ") with thread " << CURRENT_THREAD->id );*/
  BOOST_CHECK( num <= FLAGS_async_par_for_threshold );
  int64_t origin = reinterpret_cast<int64_t>(shared_arg_packed.pointer());
  for (int i=start; i<start+num; i++) {
    SoftXMT_delegate_fetch_and_add_word( make_global( &count2, origin ), 1 );

    SoftXMT_delegate_fetch_and_add_word( make_global( &global_count, 0 ), 1 );
    local_count++;
  }
}

LOOP_FUNCTION(check_count2, nid) {
  BOOST_CHECK( count2 == SIZE );
}

struct parallel_func2 : public ForkJoinIteration {
  void operator()(int64_t nid) const {
    local_count = 0;

    int64_t start = nid * SIZE;
    int64_t iters = SIZE;

    // pack an argument into the global address (hack).
    // This is useful if we need just the node() from the global address and want to use the other
    // bits for something else.
    int64_t shared_arg = SoftXMT_mynode();
    GlobalAddress<dummy_t> shared_arg_packed = make_global( reinterpret_cast<dummy_t*>(shared_arg) );

    global_joiner.reset();
    async_parallel_for<dummy_t,&loop_body2, &joinerSpawn_hack<dummy_t,&loop_body2> >(start,iters,shared_arg_packed);
    global_joiner.wait();
  }
};

LOOP_FUNCTION(func_enable_google_profiler, nid) {
  SoftXMT_start_profiling();
}
void profile_start() {
#ifdef GOOGLE_PROFILER
  func_enable_google_profiler g;
  fork_join_custom(&g);
#endif
}
LOOP_FUNCTION(func_disable_google_profiler, nid) {
  SoftXMT_stop_profiling();
}
void profile_stop() {
#ifdef GOOGLE_PROFILER
  func_disable_google_profiler g;
  fork_join_custom(&g);
#endif
}

void user_main( void * args ) {
  BOOST_CHECK( SoftXMT_nodes() <= MAX_NODES );

  int64_t total_iters = SoftXMT_nodes() * SIZE;
  BOOST_MESSAGE( total_iters << " iterations over " <<
                 SoftXMT_nodes() << " nodes" );

  BOOST_MESSAGE( "Test default" );
  {
  parallel_func f;

  SoftXMT_reset_stats_all_nodes();
  profile_start();
  fork_join_custom(&f);
  profile_stop();

  for (int i=0; i<total_iters; i++) {
    BOOST_CHECK( done[i] == 1 );
  }
  BOOST_CHECK( global_count == total_iters );

  // print out individual participations
  for (Node n=0; n<SoftXMT_nodes(); n++) {
    int64_t n_count = SoftXMT_delegate_read_word( make_global( &local_count, n ) );
    BOOST_MESSAGE( n << " did " << n_count << " iterations" );
  }
  }

  BOOST_MESSAGE( "Test with shared arg" );
  {
  // with shared arg
  global_count = 0;
  parallel_func2 f;
  profile_start();
  fork_join_custom(&f);
  profile_stop();

  // check all iterations happened
  BOOST_CHECK( global_count == total_iters );

  // check all shared args used properly
  check_count2 ff;
  fork_join_custom(&ff);

  // print out individual participations
  for (Node n=0; n<SoftXMT_nodes(); n++) {
    int64_t n_count = SoftXMT_delegate_read_word( make_global( &local_count, n ) );
    BOOST_MESSAGE( n << " did " << n_count << " iterations" );
  }
  }

  BOOST_MESSAGE( "user main is exiting" );
  SoftXMT_dump_stats_all_nodes();
}

BOOST_AUTO_TEST_CASE( test1 ) {

  SoftXMT_init( &(boost::unit_test::framework::master_test_suite().argc),
                &(boost::unit_test::framework::master_test_suite().argv) );

  SoftXMT_activate();

  DVLOG(1) << "Spawning user main Thread....";
  SoftXMT_run_user_main( &user_main, (void*)NULL );
  VLOG(5) << "run_user_main returned";
  CHECK( SoftXMT_done() );

  SoftXMT_finish( 0 );
}

BOOST_AUTO_TEST_SUITE_END();

<commit_msg>add more tests for Global task joiner; such as one work item and no work items<commit_after>#include <boost/test/unit_test.hpp>

#include "SoftXMT.hpp"
#include "GlobalTaskJoiner.hpp"
#include "ForkJoin.hpp"
#include "AsyncParallelFor.hpp"
#include "Delegate.hpp"

#include "PerformanceTools.hpp"

BOOST_AUTO_TEST_SUITE( AsyncParallelFor_Global_tests );

#define MAX_NODES 8
#define SIZE 10000
int64_t done[SIZE*MAX_NODES] = {0};
int64_t count2 = 0;
int64_t global_count = 0;
int64_t local_count = 0;

void loop_body(int64_t start, int64_t num ) {
  /*BOOST_MESSAGE( "execute [" << start << ","
            << start+num << ") with thread " << CURRENT_THREAD->id );*/
  BOOST_CHECK( num <= FLAGS_async_par_for_threshold );
  for (int i=start; i<start+num; i++) {
    int64_t marked = SoftXMT_delegate_fetch_and_add_word( make_global( &done[i], 0 ), 1 );
    BOOST_CHECK( marked == 0 );

    SoftXMT_delegate_fetch_and_add_word( make_global( &global_count, 0 ), 1 );
    local_count++;
  }
}

struct parallel_func : public ForkJoinIteration {
  void operator()(int64_t nid) const {
    int64_t start = nid * SIZE;
    int64_t iters = SIZE;

    global_joiner.reset();
    async_parallel_for<&loop_body, &joinerSpawn<&loop_body> > ( start, iters );
    global_joiner.wait();
  }
};

// don't care what type goes into the GlobalAddress
typedef int64_t dummy_t;

void loop_body2(int64_t start, int64_t num, GlobalAddress<dummy_t> shared_arg_packed) {
  /*BOOST_MESSAGE( "execute [" << start << ","
            << start+num << ") with thread " << CURRENT_THREAD->id );*/
  BOOST_CHECK( num <= FLAGS_async_par_for_threshold );
  int64_t origin = reinterpret_cast<int64_t>(shared_arg_packed.pointer());
  for (int i=start; i<start+num; i++) {
    SoftXMT_delegate_fetch_and_add_word( make_global( &count2, origin ), 1 );

    SoftXMT_delegate_fetch_and_add_word( make_global( &global_count, 0 ), 1 );
    local_count++;
  }
}

LOOP_FUNCTION(check_count2, nid) {
  BOOST_CHECK( count2 == SIZE );
}

struct parallel_func2 : public ForkJoinIteration {
  void operator()(int64_t nid) const {
    local_count = 0;

    int64_t start = nid * SIZE;
    int64_t iters = SIZE;

    // pack an argument into the global address (hack).
    // This is useful if we need just the node() from the global address and want to use the other
    // bits for something else.
    int64_t shared_arg = SoftXMT_mynode();
    GlobalAddress<dummy_t> shared_arg_packed = make_global( reinterpret_cast<dummy_t*>(shared_arg) );

    global_joiner.reset();
    async_parallel_for<dummy_t,&loop_body2, &joinerSpawn_hack<dummy_t,&loop_body2> >(start,iters,shared_arg_packed);
    global_joiner.wait();
  }
};

LOOP_FUNCTION(func_enable_google_profiler, nid) {
  SoftXMT_start_profiling();
}
void profile_start() {
#ifdef GOOGLE_PROFILER
  func_enable_google_profiler g;
  fork_join_custom(&g);
#endif
}
LOOP_FUNCTION(func_disable_google_profiler, nid) {
  SoftXMT_stop_profiling();
}
void profile_stop() {
#ifdef GOOGLE_PROFILER
  func_disable_google_profiler g;
  fork_join_custom(&g);
#endif
}

LOOP_FUNCTION( no_work_func, nid ) {
    global_joiner.reset();
    /* no work */
    global_joiner.wait();
}

void signaling_task( int64_t * arg ) {
  global_joiner.signal();
}

LOOP_FUNCTION( one_work_func, nid ) {
    global_joiner.reset();
    global_joiner.registerTask();
    int64_t ignore;
    SoftXMT_privateTask( &signaling_task, &ignore );
    global_joiner.wait();
}

LOOP_FUNCTION( one_self_work_func, nid ) {
    global_joiner.reset();

    // register and signal
    global_joiner.registerTask();
    global_joiner.signal();

    global_joiner.wait();
}

void user_main( void * args ) {
  BOOST_CHECK( SoftXMT_nodes() <= MAX_NODES );

  int64_t total_iters = SoftXMT_nodes() * SIZE;
  BOOST_MESSAGE( total_iters << " iterations over " <<
                 SoftXMT_nodes() << " nodes" );

  BOOST_MESSAGE( "Test default" );
  {
  parallel_func f;

  SoftXMT_reset_stats_all_nodes();
  profile_start();
  fork_join_custom(&f);
  profile_stop();

  for (int i=0; i<total_iters; i++) {
    BOOST_CHECK( done[i] == 1 );
  }
  BOOST_CHECK( global_count == total_iters );

  // print out individual participations
  for (Node n=0; n<SoftXMT_nodes(); n++) {
    int64_t n_count = SoftXMT_delegate_read_word( make_global( &local_count, n ) );
    BOOST_MESSAGE( n << " did " << n_count << " iterations" );
  }
  }

  BOOST_MESSAGE( "No work test" );
  {
    no_work_func f;
    fork_join_custom(&f);
  }

  BOOST_MESSAGE( "One work test" );
  {
    one_work_func f;
    fork_join_custom(&f);
  }

  BOOST_MESSAGE( "One self work test" );
  {
    one_self_work_func f;
    fork_join_custom(&f);
  }

  BOOST_MESSAGE( "Test with shared arg" );
  {
  // with shared arg
  global_count = 0;
  parallel_func2 f;
  profile_start();
  fork_join_custom(&f);
  profile_stop();

  // check all iterations happened
  BOOST_CHECK( global_count == total_iters );

  // check all shared args used properly
  check_count2 ff;
  fork_join_custom(&ff);

  // print out individual participations
  for (Node n=0; n<SoftXMT_nodes(); n++) {
    int64_t n_count = SoftXMT_delegate_read_word( make_global( &local_count, n ) );
    BOOST_MESSAGE( n << " did " << n_count << " iterations" );
  }
  }

  BOOST_MESSAGE( "user main is exiting" );
  SoftXMT_dump_stats_all_nodes();
}

BOOST_AUTO_TEST_CASE( test1 ) {

  SoftXMT_init( &(boost::unit_test::framework::master_test_suite().argc),
                &(boost::unit_test::framework::master_test_suite().argv) );

  SoftXMT_activate();

  DVLOG(1) << "Spawning user main Thread....";
  SoftXMT_run_user_main( &user_main, (void*)NULL );
  VLOG(5) << "run_user_main returned";
  CHECK( SoftXMT_done() );

  SoftXMT_finish( 0 );
}

BOOST_AUTO_TEST_SUITE_END();

<|endoftext|>