<commit_before>/**
 * @file tc.hxx
 * @author Muhammad A. Awad (mawad@ucdavis.edu)
 * @brief Triangle Counting algorithm.
 * @version 0.1
 * @date 2022-08-06
 *
 * @copyright Copyright (c) 2022
 *
 */
#pragma once

#include <gunrock/algorithms/algorithms.hxx>

namespace gunrock {
namespace tc {

template <typename vertex_t>
struct param_t {
  bool reduce_all_triangles;
  param_t(bool _reduce_all_triangles)
      : reduce_all_triangles(_reduce_all_triangles) {}
};

template <typename vertex_t>
struct result_t {
  vertex_t* vertex_triangles_count;
  std::size_t* total_triangles_count;
  result_t(vertex_t* _vertex_triangles_count, uint64_t* _total_triangles_count)
      : vertex_triangles_count(_vertex_triangles_count),
        total_triangles_count(_total_triangles_count) {}
};

template <typename graph_t, typename param_type, typename result_type>
struct problem_t : gunrock::problem_t<graph_t> {
  param_type param;
  result_type result;

  problem_t(graph_t& G,
            param_type& _param,
            result_type& _result,
            std::shared_ptr<gcuda::multi_context_t> _context)
      : gunrock::problem_t<graph_t>(G, _context),
        param(_param),
        result(_result) {}

  using vertex_t = typename graph_t::vertex_type;
  using edge_t = typename graph_t::edge_type;

  void init() override {}

  void reset() override {}
};

template <typename problem_t>
struct enactor_t : gunrock::enactor_t<problem_t> {
  enactor_t(problem_t* _problem,
            std::shared_ptr<gcuda::multi_context_t> _context)
      : gunrock::enactor_t<problem_t>(_problem, _context) {}

  using vertex_t = typename problem_t::vertex_t;
  using edge_t = typename problem_t::edge_t;
  using weight_t = typename problem_t::weight_t;
  using frontier_t = typename enactor_t<problem_t>::frontier_t;

  void prepare_frontier(frontier_t* f,
                        gcuda::multi_context_t& context) override {
    auto P = this->get_problem();
    auto n_vertices = P->get_graph().get_number_of_vertices();

    f->sequence((vertex_t)0, n_vertices, context.get_context(0)->stream());
  }

  void loop(gcuda::multi_context_t& context) override {
    // Data slice
    auto E = this->get_enactor();
    auto P = this->get_problem();
    auto G = P->get_graph();

    auto vertex_triangles_count = P->result.vertex_triangles_count;
    auto iteration = this->iteration;

    auto intersect = [G, vertex_triangles_count] __host__ __device__(
                         vertex_t const& source,    // ... source
                         vertex_t const& neighbor,  // neighbor
                         edge_t const& edge,        // edge
                         weight_t const& weight     // weight (tuple).
                         ) -> bool {
      if (neighbor > source) {
        auto src_vertex_triangles_count = G.get_intersection_count(
            source, neighbor,
            [vertex_triangles_count](auto intersection_vertex) {
              math::atomic::add(&(vertex_triangles_count[intersection_vertex]),
                                vertex_t{1});
            });
      }
      return false;
    };

    // Execute advance operator on the provided lambda
    operators::advance::execute<operators::load_balance_t::block_mapped>(
        G, E, intersect, context);
  }
};  // struct enactor_t

template <typename graph_t>
float run(graph_t& G,
          bool reduce_all_triangles,
          typename graph_t::vertex_type* vertex_triangles_count,  // Output
          std::size_t* total_triangles_count,                     // Output
          std::shared_ptr<gcuda::multi_context_t> context =
              std::shared_ptr<gcuda::multi_context_t>(
                  new gcuda::multi_context_t(0))  // Context
) {
  // <user-defined>
  using vertex_t = typename graph_t::vertex_type;
  using weight_t = typename graph_t::weight_type;

  using param_type = param_t<vertex_t>;
  using result_type = result_t<vertex_t>;

  param_type param(reduce_all_triangles);
  result_type result(vertex_triangles_count, total_triangles_count);
  // </user-defined>

  using problem_type = problem_t<graph_t, param_type, result_type>;
  using enactor_type = enactor_t<problem_type>;

  problem_type problem(G, param, result, context);
  problem.init();
  problem.reset();

  enactor_type enactor(&problem, context);
  auto time = enactor.enact();

  if (param.reduce_all_triangles) {
    auto policy = context->get_context(0)->execution_policy();
    *result.total_triangles_count = thrust::transform_reduce(
        policy, result.vertex_triangles_count,
        result.vertex_triangles_count + G.get_number_of_vertices(),
        [] __device__(const vertex_t& vertex_triangles) {
          return static_cast<std::size_t>(vertex_triangles);
        },
        std::size_t{0}, thrust::plus<std::size_t>());
  }

  // </boiler-plate>
  return time;
}

}  // namespace tc
}  // namespace gunrock<commit_msg>Add post processing step<commit_after>/**
 * @file tc.hxx
 * @author Muhammad A. Awad (mawad@ucdavis.edu)
 * @brief Triangle Counting algorithm.
 * @version 0.1
 * @date 2022-08-06
 *
 * @copyright Copyright (c) 2022
 *
 */
#pragma once

#include <gunrock/algorithms/algorithms.hxx>
#include <gunrock/util/timer.hxx>

namespace gunrock {
namespace tc {

template <typename vertex_t>
struct param_t {
  bool reduce_all_triangles;
  param_t(bool _reduce_all_triangles)
      : reduce_all_triangles(_reduce_all_triangles) {}
};

template <typename vertex_t>
struct result_t {
  vertex_t* vertex_triangles_count;
  std::size_t* total_triangles_count;
  result_t(vertex_t* _vertex_triangles_count, uint64_t* _total_triangles_count)
      : vertex_triangles_count(_vertex_triangles_count),
        total_triangles_count(_total_triangles_count) {}
};

template <typename graph_t, typename param_type, typename result_type>
struct problem_t : gunrock::problem_t<graph_t> {
  param_type param;
  result_type result;

  problem_t(graph_t& G,
            param_type& _param,
            result_type& _result,
            std::shared_ptr<gcuda::multi_context_t> _context)
      : gunrock::problem_t<graph_t>(G, _context),
        param(_param),
        result(_result) {}

  using vertex_t = typename graph_t::vertex_type;
  using edge_t = typename graph_t::edge_type;

  void init() override {}

  void reset() override {}
};

template <typename problem_t>
struct enactor_t : gunrock::enactor_t<problem_t> {
  enactor_t(problem_t* _problem,
            std::shared_ptr<gcuda::multi_context_t> _context)
      : gunrock::enactor_t<problem_t>(_problem, _context) {}

  using vertex_t = typename problem_t::vertex_t;
  using edge_t = typename problem_t::edge_t;
  using weight_t = typename problem_t::weight_t;
  using frontier_t = typename enactor_t<problem_t>::frontier_t;

  void prepare_frontier(frontier_t* f,
                        gcuda::multi_context_t& context) override {
    auto P = this->get_problem();
    auto n_vertices = P->get_graph().get_number_of_vertices();

    f->sequence((vertex_t)0, n_vertices, context.get_context(0)->stream());
  }

  void loop(gcuda::multi_context_t& context) override {
    // Data slice
    auto E = this->get_enactor();
    auto P = this->get_problem();
    auto G = P->get_graph();

    auto vertex_triangles_count = P->result.vertex_triangles_count;
    auto iteration = this->iteration;

    auto intersect = [G, vertex_triangles_count] __host__ __device__(
                         vertex_t const& source,    // ... source
                         vertex_t const& neighbor,  // neighbor
                         edge_t const& edge,        // edge
                         weight_t const& weight     // weight (tuple).
                         ) -> bool {
      if (neighbor > source) {
        auto src_vertex_triangles_count = G.get_intersection_count(
            source, neighbor,
            [vertex_triangles_count](auto intersection_vertex) {
              math::atomic::add(&(vertex_triangles_count[intersection_vertex]),
                                vertex_t{1});
            });
      }
      return false;
    };

    // Execute advance operator on the provided lambda
    operators::advance::execute<operators::load_balance_t::block_mapped>(
        G, E, intersect, context);
  }

  float post_process() {
    util::timer_t timer;
    timer.begin();
    auto P = this->get_problem();
    auto G = P->get_graph();

    if (P->param.reduce_all_triangles) {
      auto policy = this->context->get_context(0)->execution_policy();
      *P->result.total_triangles_count = thrust::transform_reduce(
          policy, P->result.vertex_triangles_count,
          P->result.vertex_triangles_count + G.get_number_of_vertices(),
          [] __device__(const vertex_t& vertex_triangles) {
            return static_cast<std::size_t>(vertex_triangles);
          },
          std::size_t{0}, thrust::plus<std::size_t>());
    }
    return timer.end();
  }
};  // struct enactor_t

template <typename graph_t>
float run(graph_t& G,
          bool reduce_all_triangles,
          typename graph_t::vertex_type* vertex_triangles_count,  // Output
          std::size_t* total_triangles_count,                     // Output
          std::shared_ptr<gcuda::multi_context_t> context =
              std::shared_ptr<gcuda::multi_context_t>(
                  new gcuda::multi_context_t(0))  // Context
) {
  // <user-defined>
  using vertex_t = typename graph_t::vertex_type;
  using weight_t = typename graph_t::weight_type;

  using param_type = param_t<vertex_t>;
  using result_type = result_t<vertex_t>;

  param_type param(reduce_all_triangles);
  result_type result(vertex_triangles_count, total_triangles_count);
  // </user-defined>

  using problem_type = problem_t<graph_t, param_type, result_type>;
  using enactor_type = enactor_t<problem_type>;

  problem_type problem(G, param, result, context);
  problem.init();
  problem.reset();

  enactor_type enactor(&problem, context);
  auto time = enactor.enact();
  time += enactor.post_process();

  // </boiler-plate>
  return time;
}

}  // namespace tc
}  // namespace gunrock<|endoftext|>


<commit_before><commit_msg>no message<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: register.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2007-03-26 14:48:51 $
 *
 *  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
 *
 ************************************************************************/
#if defined(_MSC_VER) && (_MSC_VER > 1310)
#pragma warning(disable : 4917 4555)
#endif

#ifdef __MINGW32__
#define INITGUID
#endif
#include "servprov.hxx"

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_INVALIDREGISTRYEXCEPTION_HPP_
#include <com/sun/star/registry/InvalidRegistryException.hpp>
#endif

#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif

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

uno::Reference<uno::XInterface> SAL_CALL EmbedServer_createInstance(
    const uno::Reference<lang::XMultiServiceFactory> & xSMgr)
throw (uno::Exception)
{
    uno::Reference<uno::XInterface > xService = *new EmbedServer_Impl( xSMgr );
    return xService;
}

::rtl::OUString SAL_CALL EmbedServer_getImplementationName() throw()
{
    return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.ole.EmbedServer") );

}

uno::Sequence< ::rtl::OUString > SAL_CALL EmbedServer_getSupportedServiceNames() throw()
{
    uno::Sequence< ::rtl::OUString > aServiceNames( 1 );
    aServiceNames[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.OleEmbeddedServerRegistration" ) );
    return aServiceNames;
}

extern "C" {

void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
{
    void * pRet = 0;

    ::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplName ) );
    uno::Reference< lang::XSingleServiceFactory > xFactory;

    if(pServiceManager && aImplName.equals( EmbedServer_getImplementationName() ) )
    {
        xFactory= ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory*>(pServiceManager),
                                            EmbedServer_getImplementationName(),
                                            EmbedServer_createInstance,
                                            EmbedServer_getSupportedServiceNames() );
    }

    if (xFactory.is())
    {
        xFactory->acquire();
        pRet = xFactory.get();
    }

    return pRet;
}

sal_Bool SAL_CALL component_writeInfo( void * /*pServiceManager*/, void * pRegistryKey )
{
    if (pRegistryKey)
    {
        try
        {
            uno::Reference< registry::XRegistryKey > xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) );

            uno::Reference< registry::XRegistryKey >  xNewKey;

            xNewKey = xKey->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) +
                                        EmbedServer_getImplementationName() +
                                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") )  );

            uno::Sequence< ::rtl::OUString > rServices = EmbedServer_getSupportedServiceNames();
            for( sal_Int32 ind = 0; ind < rServices.getLength(); ind++ )
                xNewKey->createKey( rServices.getConstArray()[ind] );

            return sal_True;
        }
        catch (registry::InvalidRegistryException &)
                {
                    OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
                }
        }
        return sal_False;
}

} // extern "C"

// Fix strange warnings about some
// ATL::CAxHostWindow::QueryInterface|AddRef|Releae functions.
// warning C4505: 'xxx' : unreferenced local function has been removed
#if defined(_MSC_VER)
#pragma warning(disable: 4505)
#endif<commit_msg>INTEGRATION: CWS changefileheader (1.6.22); FILE MERGED 2008/04/01 15:13:59 thb 1.6.22.3: #i85898# Stripping all external header guards 2008/04/01 12:29:02 thb 1.6.22.2: #i85898# Stripping all external header guards 2008/03/31 13:33:41 rt 1.6.22.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: register.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#if defined(_MSC_VER) && (_MSC_VER > 1310)
#pragma warning(disable : 4917 4555)
#endif

#ifdef __MINGW32__
#define INITGUID
#endif
#include "servprov.hxx"
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/registry/InvalidRegistryException.hpp>
#include <rtl/ustring.h>
#include <cppuhelper/factory.hxx>

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

uno::Reference<uno::XInterface> SAL_CALL EmbedServer_createInstance(
    const uno::Reference<lang::XMultiServiceFactory> & xSMgr)
throw (uno::Exception)
{
    uno::Reference<uno::XInterface > xService = *new EmbedServer_Impl( xSMgr );
    return xService;
}

::rtl::OUString SAL_CALL EmbedServer_getImplementationName() throw()
{
    return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.ole.EmbedServer") );

}

uno::Sequence< ::rtl::OUString > SAL_CALL EmbedServer_getSupportedServiceNames() throw()
{
    uno::Sequence< ::rtl::OUString > aServiceNames( 1 );
    aServiceNames[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.OleEmbeddedServerRegistration" ) );
    return aServiceNames;
}

extern "C" {

void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
{
    void * pRet = 0;

    ::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplName ) );
    uno::Reference< lang::XSingleServiceFactory > xFactory;

    if(pServiceManager && aImplName.equals( EmbedServer_getImplementationName() ) )
    {
        xFactory= ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory*>(pServiceManager),
                                            EmbedServer_getImplementationName(),
                                            EmbedServer_createInstance,
                                            EmbedServer_getSupportedServiceNames() );
    }

    if (xFactory.is())
    {
        xFactory->acquire();
        pRet = xFactory.get();
    }

    return pRet;
}

sal_Bool SAL_CALL component_writeInfo( void * /*pServiceManager*/, void * pRegistryKey )
{
    if (pRegistryKey)
    {
        try
        {
            uno::Reference< registry::XRegistryKey > xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) );

            uno::Reference< registry::XRegistryKey >  xNewKey;

            xNewKey = xKey->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) +
                                        EmbedServer_getImplementationName() +
                                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") )  );

            uno::Sequence< ::rtl::OUString > rServices = EmbedServer_getSupportedServiceNames();
            for( sal_Int32 ind = 0; ind < rServices.getLength(); ind++ )
                xNewKey->createKey( rServices.getConstArray()[ind] );

            return sal_True;
        }
        catch (registry::InvalidRegistryException &)
                {
                    OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
                }
        }
        return sal_False;
}

} // extern "C"

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


<commit_before>#include "callback_parameter.hpp"
#include "callback_object.hpp"
#include "code/ylikuutio/common/any_value.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"

// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <memory>   // std::make_shared, std::shared_ptr
#include <string>   // std::string

namespace yli
{
    namespace callback_system
    {
        void CallbackParameter::bind_to_parent()
        {
            // requirements:
            // `this->parent` must not be `nullptr`.
            yli::callback_system::CallbackObject* const callback_object = this->parent;

            if (callback_object == nullptr)
            {
                std::cerr << "ERROR: `CallbackParameter::bind_to_parent`: `callback_object` is `nullptr`!\n";
                return;
            }

            // note: `CallbackObject::bind_callback_parameter` also stores named variables in its `anyvalue_hashmap`.
            callback_object->bind_callback_parameter(this);
        }

        CallbackParameter::CallbackParameter(const std::string& name, std::shared_ptr<yli::datatypes::AnyValue> any_value, const bool is_reference, yli::callback_system::CallbackObject* const parent)
        {
            // constructor.
            this->name = name;
            this->any_value = any_value;
            this->is_reference = is_reference;
            this->parent = parent;

            // get childID from the CallbackObject and set pointer to this CallbackParameter.
            this->bind_to_parent();
        }

        CallbackParameter::~CallbackParameter()
        {
            // destructor.
            std::cout << "Callback parameter with childID " << this->childID << " will be destroyed.\n";

            // set pointer to this object to nullptr.
            this->parent->set_callback_parameter_pointer(this->childID, nullptr);
        }

        std::shared_ptr<yli::datatypes::AnyValue> CallbackParameter::get_any_value() const
        {
            return std::make_shared<yli::datatypes::AnyValue>(*this->any_value);
        }
    }
}
<commit_msg>`CallbackParameter::~CallbackParameter`: check `parent` for `nullptr`.<commit_after>#include "callback_parameter.hpp"
#include "callback_object.hpp"
#include "code/ylikuutio/common/any_value.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"

// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <memory>   // std::make_shared, std::shared_ptr
#include <string>   // std::string

namespace yli
{
    namespace callback_system
    {
        void CallbackParameter::bind_to_parent()
        {
            // requirements:
            // `this->parent` must not be `nullptr`.
            yli::callback_system::CallbackObject* const callback_object = this->parent;

            if (callback_object == nullptr)
            {
                std::cerr << "ERROR: `CallbackParameter::bind_to_parent`: `callback_object` is `nullptr`!\n";
                return;
            }

            // note: `CallbackObject::bind_callback_parameter` also stores named variables in its `anyvalue_hashmap`.
            callback_object->bind_callback_parameter(this);
        }

        CallbackParameter::CallbackParameter(const std::string& name, std::shared_ptr<yli::datatypes::AnyValue> any_value, const bool is_reference, yli::callback_system::CallbackObject* const parent)
        {
            // constructor.
            this->name = name;
            this->any_value = any_value;
            this->is_reference = is_reference;
            this->parent = parent;

            // get childID from the CallbackObject and set pointer to this CallbackParameter.
            this->bind_to_parent();
        }

        CallbackParameter::~CallbackParameter()
        {
            // destructor.
            //
            // requirements:
            // `this->parent` must not be `nullptr`.

            std::cout << "Callback parameter with childID " << this->childID << " will be destroyed.\n";

            yli::callback_system::CallbackObject* const callback_object = this->parent;

            if (callback_object == nullptr)
            {
                std::cerr << "ERROR: `CallbackParameter::~CallbackParameter`: `callback_object` is `nullptr`!\n";
                return;
            }

            // set pointer to this `CallbackParameter` to `nullptr`.
            callback_object->set_callback_parameter_pointer(this->childID, nullptr);
        }

        std::shared_ptr<yli::datatypes::AnyValue> CallbackParameter::get_any_value() const
        {
            return std::make_shared<yli::datatypes::AnyValue>(*this->any_value);
        }
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: source.cxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:18:03 $
 *
 *  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 _COM_SUN_STAR_DATATRANSFER_DND_DNDCONSTANTS_HPP_
#include <com/sun/star/datatransfer/dnd/DNDConstants.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_MOUSEBUTTON_HPP_
#include <com/sun/star/awt/MouseButton.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_MOUSEEVENT_HPP_
#include <com/sun/star/awt/MouseEvent.hpp>
#endif
#ifndef _RTL_UNLOAD_H_
#include <rtl/unload.h>
#endif

#include <process.h>
#include <memory>

#include "source.hxx"
#include "globals.hxx"
#include "sourcecontext.hxx"
#include "../../inc/DtObjFactory.hxx"
#include <rtl/ustring.h>
#include <process.h>
#include <winuser.h>
#include <stdio.h>

using namespace rtl;
using namespace cppu;
using namespace osl;
using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::dnd;
using namespace com::sun::star::datatransfer::dnd::DNDConstants;
using namespace com::sun::star::uno;
using namespace com::sun::star::awt::MouseButton;
using namespace com::sun::star::awt;
using namespace com::sun::star::lang;

extern rtl_StandardModuleCount g_moduleCount;

//--> TRA

extern Reference< XTransferable > g_XTransferable;

//<-- TRA

unsigned __stdcall DndOleSTAFunc(LPVOID pParams);

//----------------------------------------------------
/** Ctor
*/
DragSource::DragSource( const Reference<XMultiServiceFactory>& sf):
    m_serviceFactory( sf),
    WeakComponentImplHelper3< XDragSource, XInitialization, XServiceInfo >(m_mutex),
//  m_pcurrentContext_impl(0),
    m_hAppWindow(0),
    m_MouseButton(0),
    m_RunningDndOperationCount(0)
{
    g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
}

//----------------------------------------------------
/** Dtor
*/
DragSource::~DragSource()
{
    g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}

//----------------------------------------------------
/** First start a new drag and drop thread if
     the last one has finished

     ????
          Do we really need a separate thread for
          every Dnd opeartion or only if the source
          thread is an MTA thread
     ????
*/
void DragSource::StartDragImpl(
    const DragGestureEvent& trigger,
    sal_Int8 sourceActions,
    sal_Int32 cursor,
    sal_Int32 image,
    const Reference<XTransferable >& trans,
    const Reference<XDragSourceListener >& listener )
{
    // The actions supported by the drag source
    m_sourceActions= sourceActions;
    // We need to know which mouse button triggered the operation.
    // If it was the left one, then the drop occurs when that button
    // has been released and if it was the right one then the drop
    // occurs when the right button has been released. If the event is not
    // set then we assume that the left button is pressed.
    MouseEvent evtMouse;
    trigger.Event >>= evtMouse;
    m_MouseButton= evtMouse.Buttons;

    // The SourceContext class administers the XDragSourceListener s and
    // fires events to them. An instance only exists in the scope of this
    // functions. However, the drag and drop operation causes callbacks
    // to the IDropSource interface implemented in this class (but only
    // while this function executes). The source context is also used
    // in DragSource::QueryContinueDrag.
    m_currentContext= static_cast<XDragSourceContext*>( new SourceContext(
                      static_cast<DragSource*>(this), listener ) );

    // Convert the XTransferable data object into an IDataObject object;

    //--> TRA
    g_XTransferable = trans;
    //<-- TRA

    m_spDataObject= m_aDataConverter.createDataObjFromTransferable(
                    m_serviceFactory, trans);

    // Obtain the id of the thread that created the window
    DWORD processId;
    m_threadIdWindow= GetWindowThreadProcessId( m_hAppWindow, &processId);

    // hold the instance for the DnD thread, it's to late
    // to acquire at the start of the thread procedure
    // the thread procedure is responsible for the release
    acquire();

    // The thread acccesses members of this instance but does not call acquire.
    // Hopefully this instance is not destroyed before the thread has terminated.
    unsigned threadId;
    HANDLE hThread= reinterpret_cast<HANDLE>(_beginthreadex(
        0, 0, DndOleSTAFunc, reinterpret_cast<void*>(this), 0, &threadId));

    // detach from thread
    CloseHandle(hThread);
}

// XInitialization

//----------------------------------------------------
/** aArguments contains a machine id
*/
void SAL_CALL DragSource::initialize( const Sequence< Any >& aArguments )
    throw(Exception, RuntimeException)
{
    if( aArguments.getLength() >=2)
        m_hAppWindow= *(HWND*)aArguments[1].getValue();
    OSL_ASSERT( IsWindow( m_hAppWindow) );
}

//----------------------------------------------------
/** XDragSource
*/
sal_Bool SAL_CALL DragSource::isDragImageSupported(  )
         throw(RuntimeException)
{
    return 0;
}

//----------------------------------------------------
/**
*/
sal_Int32 SAL_CALL DragSource::getDefaultCursor( sal_Int8 dragAction )
          throw( IllegalArgumentException, RuntimeException)
{
    return 0;
}

//----------------------------------------------------
/** Notifies the XDragSourceListener by
     calling dragDropEnd
*/
void SAL_CALL DragSource::startDrag(
    const DragGestureEvent& trigger,
    sal_Int8 sourceActions,
    sal_Int32 cursor,
    sal_Int32 image,
    const Reference<XTransferable >& trans,
    const Reference<XDragSourceListener >& listener ) throw( RuntimeException)
{
    // Allow only one running dnd operation at a time,
    // see XDragSource documentation

    long cnt = InterlockedIncrement(&m_RunningDndOperationCount);

    if (1 == cnt)
    {
        StartDragImpl(trigger, sourceActions, cursor, image, trans, listener);
    }
    else
    {
        //OSL_ENSURE(false, "Overlapping Drag&Drop operation rejected!");

        cnt = InterlockedDecrement(&m_RunningDndOperationCount);

        DragSourceDropEvent dsde;

        dsde.DropAction  = ACTION_NONE;
        dsde.DropSuccess = false;

        try
        {
            listener->dragDropEnd(dsde);
        }
        catch(RuntimeException&)
        {
            OSL_ENSURE(false, "Runtime exception during event dispatching");
        }
    }
}

//----------------------------------------------------
/**
*/
#if OSL_DEBUG_LEVEL > 1
void SAL_CALL DragSource::release()
{
    if( m_refCount == 1)
    {
        int a = m_refCount;
    }
    WeakComponentImplHelper3< XDragSource, XInitialization, XServiceInfo>::release();
}
#endif

//----------------------------------------------------
/**IDropTarget
*/
HRESULT STDMETHODCALLTYPE DragSource::QueryInterface( REFIID riid, void  **ppvObject)
{
    if( !ppvObject)
        return E_POINTER;
    *ppvObject= NULL;

    if(  riid == __uuidof( IUnknown) )
        *ppvObject= static_cast<IUnknown*>( this);
    else if ( riid == __uuidof( IDropSource) )
        *ppvObject= static_cast<IDropSource*>( this);

    if(*ppvObject)
    {
        AddRef();
        return S_OK;
    }
    else
        return E_NOINTERFACE;

}

//----------------------------------------------------
/**
*/
ULONG STDMETHODCALLTYPE DragSource::AddRef( void)
{
    acquire();
    return (ULONG) m_refCount;
}

//----------------------------------------------------
/**
*/
ULONG STDMETHODCALLTYPE DragSource::Release( void)
{
    ULONG ref= m_refCount;
    release();
    return --ref;
}

//----------------------------------------------------
/** IDropSource
*/
HRESULT STDMETHODCALLTYPE DragSource::QueryContinueDrag(
/* [in] */ BOOL fEscapePressed,
/* [in] */ DWORD grfKeyState)
{
#if DBG_CONSOLE_OUT
    printf("\nDragSource::QueryContinueDrag");
#endif

    HRESULT retVal= S_OK; // default continue DnD

    if (fEscapePressed)
    {
        retVal= DRAGDROP_S_CANCEL;
    }
    else
    {
        if( ( m_MouseButton == MouseButton::RIGHT &&  !(grfKeyState & MK_RBUTTON) ) ||
            ( m_MouseButton == MouseButton::MIDDLE && !(grfKeyState & MK_MBUTTON) ) ||
            ( m_MouseButton == MouseButton::LEFT && !(grfKeyState & MK_LBUTTON) )   ||
            ( m_MouseButton == 0 && !(grfKeyState & MK_LBUTTON) ) )
        {
            retVal= DRAGDROP_S_DROP;
        }
    }

    // fire dropActionChanged event.
    // this is actually done by the context, which also detects whether the action
    // changed at all
    sal_Int8 dropAction= fEscapePressed ? ACTION_NONE :
                                                         dndOleKeysToAction( grfKeyState, m_sourceActions);

    sal_Int8 userAction= fEscapePressed ? ACTION_NONE :
                                                         dndOleKeysToAction( grfKeyState, -1 );

    static_cast<SourceContext*>(m_currentContext.get())->fire_dropActionChanged(
        dropAction, userAction);

    return retVal;
}

//----------------------------------------------------
/**
*/
HRESULT STDMETHODCALLTYPE DragSource::GiveFeedback(
/* [in] */ DWORD dwEffect)
{
#if DBG_CONSOLE_OUT
    printf("\nDragSource::GiveFeedback %d", dwEffect);
#endif

    return DRAGDROP_S_USEDEFAULTCURSORS;
}

// XServiceInfo
OUString SAL_CALL DragSource::getImplementationName(  ) throw (RuntimeException)
{
    return OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_IMPL_NAME));;
}
// XServiceInfo
sal_Bool SAL_CALL DragSource::supportsService( const OUString& ServiceName ) throw (RuntimeException)
{
    if( ServiceName.equals(OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_SERVICE_NAME ))))
        return sal_True;
    return sal_False;
}

Sequence< OUString > SAL_CALL DragSource::getSupportedServiceNames(  ) throw (RuntimeException)
{
    OUString names[1]= {OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_SERVICE_NAME))};

    return Sequence<OUString>(names, 1);
}

//----------------------------------------------------
/**This function is called as extra thread from
    DragSource::executeDrag. The function
    carries out a drag and drop operation by calling
    DoDragDrop. The thread also notifies all
    XSourceListener.
*/
unsigned __stdcall DndOleSTAFunc(LPVOID pParams)
{
    // The structure contains all arguments for DoDragDrop and other
    DragSource *pSource= (DragSource*)pParams;

    // Drag and drop only works in a thread in which OleInitialize is called.
    HRESULT hr= OleInitialize( NULL);

    if(SUCCEEDED(hr))
    {
        // We force the creation of a thread message queue. This is necessary
        // for a later call to AttachThreadInput
        MSG msgtemp;
        PeekMessage( &msgtemp, NULL, WM_USER, WM_USER, PM_NOREMOVE);

        DWORD threadId= GetCurrentThreadId();

        // This thread is attached to the thread that created the window. Hence
        // this thread also receives all mouse and keyboard messages which are
        // needed by DoDragDrop
        AttachThreadInput( threadId , pSource->m_threadIdWindow, TRUE );

        DWORD dwEffect= 0;
        hr= DoDragDrop(
            pSource->m_spDataObject.get(),
            static_cast<IDropSource*>(pSource),
            dndActionsToDropEffects( pSource->m_sourceActions),
            &dwEffect);

        // #105428 detach my message queue from the other threads
        // message queue before calling fire_dragDropEnd else
        // the office may appear to hang sometimes
        AttachThreadInput( threadId, pSource->m_threadIdWindow, FALSE);

        //--> TRA
        // clear the global transferable again
        g_XTransferable = Reference< XTransferable >( );
        //<-- TRA

        OSL_ENSURE( hr != E_INVALIDARG, "IDataObject impl does not contain valid data");

        //Fire event
        sal_Int8 action= hr == DRAGDROP_S_DROP ? dndOleDropEffectsToActions( dwEffect) : ACTION_NONE;

        static_cast<SourceContext*>(pSource->m_currentContext.get())->fire_dragDropEnd(
                                                        hr == DRAGDROP_S_DROP ? sal_True : sal_False, action);

        // Destroy SourceContextslkfgj
        pSource->m_currentContext= 0;
        // Destroy the XTransferable wrapper
        pSource->m_spDataObject=0;

        OleUninitialize();
    }

    long cnt = InterlockedDecrement(&pSource->m_RunningDndOperationCount);

    // the DragSource was manually acquired by
    // thread starting method DelayedStartDrag
    pSource->release();

    return 0;
}

<commit_msg>INTEGRATION: CWS warnings01 (1.18.4); FILE MERGED 2006/03/09 20:31:48 pl 1.18.4.1: #i55991# removed warnings for windows platform<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: source.cxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 06:02:45 $
 *
 *  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 _COM_SUN_STAR_DATATRANSFER_DND_DNDCONSTANTS_HPP_
#include <com/sun/star/datatransfer/dnd/DNDConstants.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_MOUSEBUTTON_HPP_
#include <com/sun/star/awt/MouseButton.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_MOUSEEVENT_HPP_
#include <com/sun/star/awt/MouseEvent.hpp>
#endif
#ifndef _RTL_UNLOAD_H_
#include <rtl/unload.h>
#endif

#include <process.h>
#include <memory>

#include "source.hxx"
#include "globals.hxx"
#include "sourcecontext.hxx"
#include "../../inc/DtObjFactory.hxx"
#include <rtl/ustring.h>
#include <process.h>
#include <winuser.h>
#include <stdio.h>

using namespace rtl;
using namespace cppu;
using namespace osl;
using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::dnd;
using namespace com::sun::star::datatransfer::dnd::DNDConstants;
using namespace com::sun::star::uno;
using namespace com::sun::star::awt::MouseButton;
using namespace com::sun::star::awt;
using namespace com::sun::star::lang;

extern rtl_StandardModuleCount g_moduleCount;

//--> TRA

extern Reference< XTransferable > g_XTransferable;

//<-- TRA

unsigned __stdcall DndOleSTAFunc(LPVOID pParams);

//----------------------------------------------------
/** Ctor
*/
DragSource::DragSource( const Reference<XMultiServiceFactory>& sf):
    m_serviceFactory( sf),
    WeakComponentImplHelper3< XDragSource, XInitialization, XServiceInfo >(m_mutex),
//  m_pcurrentContext_impl(0),
    m_hAppWindow(0),
    m_MouseButton(0),
    m_RunningDndOperationCount(0)
{
    g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
}

//----------------------------------------------------
/** Dtor
*/
DragSource::~DragSource()
{
    g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}

//----------------------------------------------------
/** First start a new drag and drop thread if
     the last one has finished

     ????
          Do we really need a separate thread for
          every Dnd opeartion or only if the source
          thread is an MTA thread
     ????
*/
void DragSource::StartDragImpl(
    const DragGestureEvent& trigger,
    sal_Int8 sourceActions,
    sal_Int32 /*cursor*/,
    sal_Int32 /*image*/,
    const Reference<XTransferable >& trans,
    const Reference<XDragSourceListener >& listener )
{
    // The actions supported by the drag source
    m_sourceActions= sourceActions;
    // We need to know which mouse button triggered the operation.
    // If it was the left one, then the drop occurs when that button
    // has been released and if it was the right one then the drop
    // occurs when the right button has been released. If the event is not
    // set then we assume that the left button is pressed.
    MouseEvent evtMouse;
    trigger.Event >>= evtMouse;
    m_MouseButton= evtMouse.Buttons;

    // The SourceContext class administers the XDragSourceListener s and
    // fires events to them. An instance only exists in the scope of this
    // functions. However, the drag and drop operation causes callbacks
    // to the IDropSource interface implemented in this class (but only
    // while this function executes). The source context is also used
    // in DragSource::QueryContinueDrag.
    m_currentContext= static_cast<XDragSourceContext*>( new SourceContext(
                      static_cast<DragSource*>(this), listener ) );

    // Convert the XTransferable data object into an IDataObject object;

    //--> TRA
    g_XTransferable = trans;
    //<-- TRA

    m_spDataObject= m_aDataConverter.createDataObjFromTransferable(
                    m_serviceFactory, trans);

    // Obtain the id of the thread that created the window
    DWORD processId;
    m_threadIdWindow= GetWindowThreadProcessId( m_hAppWindow, &processId);

    // hold the instance for the DnD thread, it's to late
    // to acquire at the start of the thread procedure
    // the thread procedure is responsible for the release
    acquire();

    // The thread acccesses members of this instance but does not call acquire.
    // Hopefully this instance is not destroyed before the thread has terminated.
    unsigned threadId;
    HANDLE hThread= reinterpret_cast<HANDLE>(_beginthreadex(
        0, 0, DndOleSTAFunc, reinterpret_cast<void*>(this), 0, &threadId));

    // detach from thread
    CloseHandle(hThread);
}

// XInitialization

//----------------------------------------------------
/** aArguments contains a machine id
*/
void SAL_CALL DragSource::initialize( const Sequence< Any >& aArguments )
    throw(Exception, RuntimeException)
{
    if( aArguments.getLength() >=2)
        m_hAppWindow= *(HWND*)aArguments[1].getValue();
    OSL_ASSERT( IsWindow( m_hAppWindow) );
}

//----------------------------------------------------
/** XDragSource
*/
sal_Bool SAL_CALL DragSource::isDragImageSupported(  )
         throw(RuntimeException)
{
    return 0;
}

//----------------------------------------------------
/**
*/
sal_Int32 SAL_CALL DragSource::getDefaultCursor( sal_Int8 /*dragAction*/ )
          throw( IllegalArgumentException, RuntimeException)
{
    return 0;
}

//----------------------------------------------------
/** Notifies the XDragSourceListener by
     calling dragDropEnd
*/
void SAL_CALL DragSource::startDrag(
    const DragGestureEvent& trigger,
    sal_Int8 sourceActions,
    sal_Int32 cursor,
    sal_Int32 image,
    const Reference<XTransferable >& trans,
    const Reference<XDragSourceListener >& listener ) throw( RuntimeException)
{
    // Allow only one running dnd operation at a time,
    // see XDragSource documentation

    long cnt = InterlockedIncrement(&m_RunningDndOperationCount);

    if (1 == cnt)
    {
        StartDragImpl(trigger, sourceActions, cursor, image, trans, listener);
    }
    else
    {
        //OSL_ENSURE(false, "Overlapping Drag&Drop operation rejected!");

        cnt = InterlockedDecrement(&m_RunningDndOperationCount);

        DragSourceDropEvent dsde;

        dsde.DropAction  = ACTION_NONE;
        dsde.DropSuccess = false;

        try
        {
            listener->dragDropEnd(dsde);
        }
        catch(RuntimeException&)
        {
            OSL_ENSURE(false, "Runtime exception during event dispatching");
        }
    }
}

//----------------------------------------------------
/**
*/
#if OSL_DEBUG_LEVEL > 1
void SAL_CALL DragSource::release()
{
    if( m_refCount == 1)
    {
        int a = m_refCount;
    }
    WeakComponentImplHelper3< XDragSource, XInitialization, XServiceInfo>::release();
}
#endif

//----------------------------------------------------
/**IDropTarget
*/
HRESULT STDMETHODCALLTYPE DragSource::QueryInterface( REFIID riid, void  **ppvObject)
{
    if( !ppvObject)
        return E_POINTER;
    *ppvObject= NULL;

    if(  riid == __uuidof( IUnknown) )
        *ppvObject= static_cast<IUnknown*>( this);
    else if ( riid == __uuidof( IDropSource) )
        *ppvObject= static_cast<IDropSource*>( this);

    if(*ppvObject)
    {
        AddRef();
        return S_OK;
    }
    else
        return E_NOINTERFACE;

}

//----------------------------------------------------
/**
*/
ULONG STDMETHODCALLTYPE DragSource::AddRef( void)
{
    acquire();
    return (ULONG) m_refCount;
}

//----------------------------------------------------
/**
*/
ULONG STDMETHODCALLTYPE DragSource::Release( void)
{
    ULONG ref= m_refCount;
    release();
    return --ref;
}

//----------------------------------------------------
/** IDropSource
*/
HRESULT STDMETHODCALLTYPE DragSource::QueryContinueDrag(
/* [in] */ BOOL fEscapePressed,
/* [in] */ DWORD grfKeyState)
{
#if defined DBG_CONSOLE_OUT
    printf("\nDragSource::QueryContinueDrag");
#endif

    HRESULT retVal= S_OK; // default continue DnD

    if (fEscapePressed)
    {
        retVal= DRAGDROP_S_CANCEL;
    }
    else
    {
        if( ( m_MouseButton == MouseButton::RIGHT &&  !(grfKeyState & MK_RBUTTON) ) ||
            ( m_MouseButton == MouseButton::MIDDLE && !(grfKeyState & MK_MBUTTON) ) ||
            ( m_MouseButton == MouseButton::LEFT && !(grfKeyState & MK_LBUTTON) )   ||
            ( m_MouseButton == 0 && !(grfKeyState & MK_LBUTTON) ) )
        {
            retVal= DRAGDROP_S_DROP;
        }
    }

    // fire dropActionChanged event.
    // this is actually done by the context, which also detects whether the action
    // changed at all
    sal_Int8 dropAction= fEscapePressed ? ACTION_NONE :
                                                         dndOleKeysToAction( grfKeyState, m_sourceActions);

    sal_Int8 userAction= fEscapePressed ? ACTION_NONE :
                                                         dndOleKeysToAction( grfKeyState, -1 );

    static_cast<SourceContext*>(m_currentContext.get())->fire_dropActionChanged(
        dropAction, userAction);

    return retVal;
}

//----------------------------------------------------
/**
*/
HRESULT STDMETHODCALLTYPE DragSource::GiveFeedback(
/* [in] */ DWORD
#if defined DBG_CONSOLE_OUT
dwEffect
#endif
)
{
#if defined DBG_CONSOLE_OUT
    printf("\nDragSource::GiveFeedback %d", dwEffect);
#endif

    return DRAGDROP_S_USEDEFAULTCURSORS;
}

// XServiceInfo
OUString SAL_CALL DragSource::getImplementationName(  ) throw (RuntimeException)
{
    return OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_IMPL_NAME));;
}
// XServiceInfo
sal_Bool SAL_CALL DragSource::supportsService( const OUString& ServiceName ) throw (RuntimeException)
{
    if( ServiceName.equals(OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_SERVICE_NAME ))))
        return sal_True;
    return sal_False;
}

Sequence< OUString > SAL_CALL DragSource::getSupportedServiceNames(  ) throw (RuntimeException)
{
    OUString names[1]= {OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_SERVICE_NAME))};

    return Sequence<OUString>(names, 1);
}

//----------------------------------------------------
/**This function is called as extra thread from
    DragSource::executeDrag. The function
    carries out a drag and drop operation by calling
    DoDragDrop. The thread also notifies all
    XSourceListener.
*/
unsigned __stdcall DndOleSTAFunc(LPVOID pParams)
{
    // The structure contains all arguments for DoDragDrop and other
    DragSource *pSource= (DragSource*)pParams;

    // Drag and drop only works in a thread in which OleInitialize is called.
    HRESULT hr= OleInitialize( NULL);

    if(SUCCEEDED(hr))
    {
        // We force the creation of a thread message queue. This is necessary
        // for a later call to AttachThreadInput
        MSG msgtemp;
        PeekMessage( &msgtemp, NULL, WM_USER, WM_USER, PM_NOREMOVE);

        DWORD threadId= GetCurrentThreadId();

        // This thread is attached to the thread that created the window. Hence
        // this thread also receives all mouse and keyboard messages which are
        // needed by DoDragDrop
        AttachThreadInput( threadId , pSource->m_threadIdWindow, TRUE );

        DWORD dwEffect= 0;
        hr= DoDragDrop(
            pSource->m_spDataObject.get(),
            static_cast<IDropSource*>(pSource),
            dndActionsToDropEffects( pSource->m_sourceActions),
            &dwEffect);

        // #105428 detach my message queue from the other threads
        // message queue before calling fire_dragDropEnd else
        // the office may appear to hang sometimes
        AttachThreadInput( threadId, pSource->m_threadIdWindow, FALSE);

        //--> TRA
        // clear the global transferable again
        g_XTransferable = Reference< XTransferable >( );
        //<-- TRA

        OSL_ENSURE( hr != E_INVALIDARG, "IDataObject impl does not contain valid data");

        //Fire event
        sal_Int8 action= hr == DRAGDROP_S_DROP ? dndOleDropEffectsToActions( dwEffect) : ACTION_NONE;

        static_cast<SourceContext*>(pSource->m_currentContext.get())->fire_dragDropEnd(
                                                        hr == DRAGDROP_S_DROP ? sal_True : sal_False, action);

        // Destroy SourceContextslkfgj
        pSource->m_currentContext= 0;
        // Destroy the XTransferable wrapper
        pSource->m_spDataObject=0;

        OleUninitialize();
    }

    InterlockedDecrement(&pSource->m_RunningDndOperationCount);

    // the DragSource was manually acquired by
    // thread starting method DelayedStartDrag
    pSource->release();

    return 0;
}

<|endoftext|>


<commit_before>/*
 * LayoutAppender.hh
 *
 * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2000, Bastiaan Bakker. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#ifndef _LOG4CPP_LAYOUTAPPENDER_HH
#define _LOG4CPP_LAYOUTAPPENDER_HH

#include <string>
#include "log4cpp/Export.hh"
#include "log4cpp/AppenderSkeleton.hh"

namespace log4cpp {

    /**
     * LayoutAppender is a common superclass for all Appenders that require
     * a Layout.
     **/
    class LOG4CPP_EXPORT LayoutAppender : public AppenderSkeleton {
        public:
        LayoutAppender(const std::string& name);
        virtual ~LayoutAppender();

        /**
         * Check if the appender requires a layout. All LayoutAppenders do,
         * therefore this method returns true for all subclasses.
         *
         * @returns true.
         **/
        virtual bool requiresLayout() const;
        virtual void setLayout(Layout* layout);

        protected:
        /**
         * Return the layout of the appender.
         * This method is the Layout accessor for subclasses of LayoutAppender.
         * @returns the Layout.
         **/
        Layout& _getLayout();

        private:
        Layout* _layout;
    };
}

#endif // _LOG4CPP_LAYOUTAPPENDER_HH
<commit_msg>typedef SimpleLayout as DefaultLayoutType.<commit_after>/*
 * LayoutAppender.hh
 *
 * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2000, Bastiaan Bakker. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#ifndef _LOG4CPP_LAYOUTAPPENDER_HH
#define _LOG4CPP_LAYOUTAPPENDER_HH

#include <string>
#include "log4cpp/Export.hh"
#include "log4cpp/AppenderSkeleton.hh"
#include "log4cpp/SimpleLayout.hh"

namespace log4cpp {

    /**
     * LayoutAppender is a common superclass for all Appenders that require
     * a Layout.
     **/
    class LOG4CPP_EXPORT LayoutAppender : public AppenderSkeleton {
        public:

        typedef SimpleLayout DefaultLayoutType;

        LayoutAppender(const std::string& name);
        virtual ~LayoutAppender();

        /**
         * Check if the appender requires a layout. All LayoutAppenders do,
         * therefore this method returns true for all subclasses.
         *
         * @returns true.
         **/
        virtual bool requiresLayout() const;
        virtual void setLayout(Layout* layout = NULL);

        protected:
        /**
         * Return the layout of the appender.
         * This method is the Layout accessor for subclasses of LayoutAppender.
         * @returns the Layout.
         **/
        Layout& _getLayout();

        private:
        Layout* _layout;
    };
}

#endif // _LOG4CPP_LAYOUTAPPENDER_HH
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.
 * License: https://github.com/taylor001/crown/blob/master/LICENSE
 */

#include "config.h"

#if CROWN_PLATFORM_ANDROID

#include "apk_file.h"
#include "assert.h"
#include "macros.h"
#include <android/asset_manager.h>

namespace crown
{

ApkFile::ApkFile(AAssetManager* asset_manager, const char* path)
	: File(FOM_READ)
	, _asset(NULL)
{
	_asset = AAssetManager_open(asset_manager, path, AASSET_MODE_RANDOM);
	CE_ASSERT(_asset != NULL, "AAssetManager_open: failed to open %s", path);
}

ApkFile::~ApkFile()
{
	if (_asset != NULL)
	{
		AAsset_close(_asset);
		_asset = NULL;
	}
}

void ApkFile::seek(size_t position)
{
	off_t seek_result = AAsset_seek(_asset, (off_t)position, SEEK_SET);
	CE_ASSERT(seek_result != (off_t) -1, "AAsset_seek: error");
	CE_UNUSED(seek_result);
}

void ApkFile::seek_to_end()
{
	off_t seek_result = AAsset_seek(_asset, 0, SEEK_END);
	CE_ASSERT(seek_result != (off_t) -1, "AAsset_seek: error");
	CE_UNUSED(seek_result);
}

void ApkFile::skip(size_t bytes)
{
	off_t seek_result = AAsset_seek(_asset, (off_t) bytes, SEEK_CUR);
	CE_ASSERT(seek_result != (off_t) -1, "AAsset_seek: error");
	CE_UNUSED(seek_result);
}

void ApkFile::read(void* buffer, size_t size)
{
	CE_ASSERT_NOT_NULL(buffer);
	size_t bytes_read = (size_t) AAsset_read(_asset, buffer, size);
	CE_ASSERT(bytes_read == size, "AAsset_read: requested: %lu, read: %lu", size, bytes_read);
	CE_UNUSED(bytes_read);
}

void ApkFile::write(const void* /*buffer*/, size_t /*size*/)
{
	CE_ASSERT(false, "Apk files are read only!");
}

bool ApkFile::copy_to(File& /*file*/, size_t /*size = 0*/)
{
	CE_ASSERT(false, "Not implemented");
	return false;
}

void ApkFile::flush()
{
	// Not needed
}

bool ApkFile::is_valid()
{
	return _asset != NULL;
}

bool ApkFile::end_of_file()
{
	return AAsset_getRemainingLength(_asset) == 0;
}

size_t ApkFile::size()
{
	return AAsset_getLength(_asset);
}

size_t ApkFile::position()
{
	return (size_t) (AAsset_getLength(_asset) - AAsset_getRemainingLength(_asset));
}

bool ApkFile::can_read() const
{
	return true;
}

bool ApkFile::can_write() const
{
	return false;
}

bool ApkFile::can_seek() const
{
	return true;
}

} // namespace crown

#endif // CROWN_PLATFORM_ANDROID
<commit_msg>Fix android build<commit_after>/*
 * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.
 * License: https://github.com/taylor001/crown/blob/master/LICENSE
 */

#include "config.h"

#if CROWN_PLATFORM_ANDROID

#include "apk_file.h"
#include "assert.h"
#include "macros.h"
#include <stdio.h> // SEEK_SET, ...
#include <android/asset_manager.h>

namespace crown
{

ApkFile::ApkFile(AAssetManager* asset_manager, const char* path)
	: File(FOM_READ)
	, _asset(NULL)
{
	_asset = AAssetManager_open(asset_manager, path, AASSET_MODE_RANDOM);
	CE_ASSERT(_asset != NULL, "AAssetManager_open: failed to open %s", path);
}

ApkFile::~ApkFile()
{
	if (_asset != NULL)
	{
		AAsset_close(_asset);
		_asset = NULL;
	}
}

void ApkFile::seek(size_t position)
{
	off_t seek_result = AAsset_seek(_asset, (off_t)position, SEEK_SET);
	CE_ASSERT(seek_result != (off_t) -1, "AAsset_seek: error");
	CE_UNUSED(seek_result);
}

void ApkFile::seek_to_end()
{
	off_t seek_result = AAsset_seek(_asset, 0, SEEK_END);
	CE_ASSERT(seek_result != (off_t) -1, "AAsset_seek: error");
	CE_UNUSED(seek_result);
}

void ApkFile::skip(size_t bytes)
{
	off_t seek_result = AAsset_seek(_asset, (off_t) bytes, SEEK_CUR);
	CE_ASSERT(seek_result != (off_t) -1, "AAsset_seek: error");
	CE_UNUSED(seek_result);
}

void ApkFile::read(void* buffer, size_t size)
{
	CE_ASSERT_NOT_NULL(buffer);
	size_t bytes_read = (size_t) AAsset_read(_asset, buffer, size);
	CE_ASSERT(bytes_read == size, "AAsset_read: requested: %lu, read: %lu", size, bytes_read);
	CE_UNUSED(bytes_read);
}

void ApkFile::write(const void* /*buffer*/, size_t /*size*/)
{
	CE_ASSERT(false, "Apk files are read only!");
}

bool ApkFile::copy_to(File& /*file*/, size_t /*size = 0*/)
{
	CE_ASSERT(false, "Not implemented");
	return false;
}

void ApkFile::flush()
{
	// Not needed
}

bool ApkFile::is_valid()
{
	return _asset != NULL;
}

bool ApkFile::end_of_file()
{
	return AAsset_getRemainingLength(_asset) == 0;
}

size_t ApkFile::size()
{
	return AAsset_getLength(_asset);
}

size_t ApkFile::position()
{
	return (size_t) (AAsset_getLength(_asset) - AAsset_getRemainingLength(_asset));
}

bool ApkFile::can_read() const
{
	return true;
}

bool ApkFile::can_write() const
{
	return false;
}

bool ApkFile::can_seek() const
{
	return true;
}

} // namespace crown

#endif // CROWN_PLATFORM_ANDROID
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#define DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH

#include <vector>
#include <type_traits>

#include <dune/common/deprecated.hh>

#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container/interfaces.hh>

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/fv/interface.hh>
#include <dune/gdt/mapper/interface.hh>

namespace Dune {
namespace GDT {

template <class VectorImp>
class ConstLocalDoFVector
{
  static_assert(
      std::is_base_of<Stuff::LA::VectorInterface<typename VectorImp::Traits, typename VectorImp::Traits::ScalarType>,
                      VectorImp>::value,
      "VectorImp has to be derived from Stuff::LA::VectorInterface!");

public:
  typedef VectorImp VectorType;
  typedef typename VectorType::ScalarType ScalarType;

  template <class M, class EntityType>
  ConstLocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, const VectorType& vector)
    : vector_(vector)
    , indices_(mapper.numDofs(entity))
  {
    mapper.globalIndices(entity, indices_);
  }

  ~ConstLocalDoFVector()
  {
  }

  size_t size() const
  {
    return indices_.size();
  }

  ScalarType get(const size_t ii) const
  {
    assert(ii < indices_.size());
    return vector_.get_entry(indices_[ii]);
  }

private:
  const VectorType& vector_;

protected:
  Dune::DynamicVector<size_t> indices_;

private:
  template <class V>
  friend std::ostream& operator<<(std::ostream& /*out*/, const ConstLocalDoFVector<V>& /*vector*/);
}; // class ConstLocalDoFVector

template <class V>
std::ostream& operator<<(std::ostream& out, const ConstLocalDoFVector<V>& vector)
{
  out << "[";
  const size_t sz = vector.size();
  if (sz > 0) {
    out << vector.get(0);
    for (size_t ii = 1; ii < sz; ++ii)
      out << ", " << vector.get(ii);
  } else
    out << " ";
  out << "]";
  return out;
} // ... operator<<(...)

template <class VectorImp>
class LocalDoFVector : public ConstLocalDoFVector<VectorImp>
{
  typedef ConstLocalDoFVector<VectorImp> BaseType;

public:
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::ScalarType ScalarType;

  template <class M, class EntityType>
  LocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, VectorType& vector)
    : BaseType(mapper, entity, vector)
    , vector_(vector)
  {
  }

  ~LocalDoFVector()
  {
  }

  void set(const size_t ii, const ScalarType& val)
  {
    assert(ii < indices_.size());
    vector_.set_entry(indices_[ii], val);
  }

  void add(const size_t ii, const ScalarType& val)
  {
    assert(ii < indices_.size());
    vector_.add_to_entry(indices_[ii], val);
  }

  template <class OtherVectorImp>
  void add(const OtherVectorImp& vector)
  {
    assert(vector.size() == indices_.size());
    for (size_t ii = 0; ii < indices_.size(); ++ii)
      add(ii, vector[ii]);
  }

private:
  using BaseType::indices_;
  VectorType& vector_;
}; // class LocalDoFVector

template <class SpaceImp, class VectorImp>
class ConstLocalDiscreteFunction
    : public Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                           SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
                                           SpaceImp::dimRangeCols>
{
  static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits, SpaceImp::dimDomain, SpaceImp::dimRange,
                                               SpaceImp::dimRangeCols>,
                                SpaceImp>::value,
                "SpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits,
                                                                 typename VectorImp::Traits::ScalarType>,
                                VectorImp>::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
  static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
                "Types do not match!");
  typedef Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                        SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
                                        SpaceImp::dimRangeCols> BaseType;
  typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef SpaceImp SpaceType;
  typedef VectorImp VectorType;
  typedef typename BaseType::EntityType EntityType;

  typedef typename BaseType::DomainFieldType DomainFieldType;
  static const size_t dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType DomainType;

  typedef typename BaseType::RangeFieldType RangeFieldType;
  static const size_t dimRangeRows = BaseType::dimRangeCols;
  static const size_t dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeType RangeType;

  typedef typename BaseType::JacobianRangeType JacobianRangeType;

private:
  typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;

public:
  typedef ConstLocalDoFVector<VectorType> ConstLocalDoFVectorType;

  ConstLocalDiscreteFunction(const SpaceType& space, const VectorType& globalVector, const EntityType& ent)
    : BaseType(ent)
    , space_(space)
    , base_(new BaseFunctionSetType(space_.base_function_set(this->entity())))
    , localVector_(new ConstLocalDoFVectorType(space_.mapper(), this->entity(), globalVector))
  {
    assert(localVector_->size() == base_->size());
  }

  ConstLocalDiscreteFunction(ThisType&& source) = default;

  ConstLocalDiscreteFunction(const ThisType& other) = delete;

  ThisType& operator=(const ThisType& other) = delete;

  virtual ~ConstLocalDiscreteFunction()
  {
  }

  const SpaceType& space() const
  {
    return space_;
  }

  const DUNE_DEPRECATED_MSG("Use basis() instead (05.07.2015)!") BaseFunctionSetType& base() const
  {
    return basis();
  }

  const BaseFunctionSetType& basis() const
  {
    return *base_;
  }

  const ConstLocalDoFVectorType& vector() const
  {
    return *localVector_;
  }

  virtual size_t order() const override
  {
    return base_->order();
  }

  void evaluate(const DomainType& xx, RangeType& ret) const override final
  {
    assert(this->is_a_valid_point(xx));
    if (!GDT::is_fv_space<SpaceType>::value) {
      std::fill(ret.begin(), ret.end(), RangeFieldType(0));
      std::vector<RangeType> tmpBaseValues(base_->size(), RangeType(0));
      assert(localVector_->size() == tmpBaseValues.size());
      base_->evaluate(xx, tmpBaseValues);
      for (size_t ii = 0; ii < localVector_->size(); ++ii) {
        ret.axpy(localVector_->get(ii), tmpBaseValues[ii]);
      }
    } else {
      for (size_t ii = 0; ii < localVector_->size(); ++ii)
        ret[ii] = localVector_->get(ii);
    }
  } // ... evaluate(...)

  virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override final
  {
    assert(this->is_a_valid_point(xx));
    if (!GDT::is_fv_space<SpaceType>::value) {
      std::fill(ret.begin(), ret.end(), RangeFieldType(0));
      std::vector<JacobianRangeType> tmpBaseJacobianValues(base_->size(), JacobianRangeType(0));
      assert(localVector_->size() == tmpBaseJacobianValues.size());
      base_->jacobian(xx, tmpBaseJacobianValues);
      for (size_t ii = 0; ii < localVector_->size(); ++ii)
        ret.axpy(localVector_->get(ii), tmpBaseJacobianValues[ii]);
    } else {
      ret = JacobianRangeType(0);
    }
  } // ... jacobian(...)

  using BaseType::evaluate;
  using BaseType::jacobian;

protected:
  const SpaceType& space_;
  std::unique_ptr<const BaseFunctionSetType> base_;
  std::unique_ptr<const ConstLocalDoFVectorType> localVector_;
}; // class ConstLocalDiscreteFunction

template <class SpaceImp, class VectorImp>
class LocalDiscreteFunction : public ConstLocalDiscreteFunction<SpaceImp, VectorImp>
{
  typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> BaseType;
  typedef LocalDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef typename BaseType::SpaceType SpaceType;
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::EntityType EntityType;

  typedef typename BaseType::DomainFieldType DomainFieldType;
  static const size_t dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType DomainType;

  typedef typename BaseType::RangeFieldType RangeFieldType;
  static const size_t dimRangeRows = BaseType::dimRangeCols;
  static const size_t dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeType RangeType;

  typedef typename BaseType::JacobianRangeType JacobianRangeType;

private:
  typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;

public:
  typedef LocalDoFVector<VectorType> LocalDoFVectorType;

  LocalDiscreteFunction(const SpaceType& space, VectorType& globalVector, const EntityType& ent)
    : BaseType(space, globalVector, ent)
    , localVector_(new LocalDoFVectorType(space_.mapper(), entity_, globalVector))
  {
    assert(localVector_->size() == base_->size());
  }

  //! previous comment questioned validity, defaulting this doesn't touch that question
  LocalDiscreteFunction(ThisType&& source) = default;

  LocalDiscreteFunction(const ThisType& other) = delete;

  ThisType& operator=(const ThisType& other) = delete;

  virtual ~LocalDiscreteFunction()
  {
  }

  LocalDoFVectorType& vector()
  {
    return *localVector_;
  }

private:
  using BaseType::space_;
  using BaseType::entity_;
  using BaseType::base_;
  std::unique_ptr<LocalDoFVectorType> localVector_;
}; // class LocalDiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
<commit_msg>[discretefunction.local] fix warning<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#define DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH

#include <vector>
#include <type_traits>

#include <dune/common/deprecated.hh>

#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container/interfaces.hh>

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/fv/interface.hh>
#include <dune/gdt/mapper/interface.hh>

namespace Dune {
namespace GDT {

template <class VectorImp>
class ConstLocalDoFVector
{
  static_assert(
      std::is_base_of<Stuff::LA::VectorInterface<typename VectorImp::Traits, typename VectorImp::Traits::ScalarType>,
                      VectorImp>::value,
      "VectorImp has to be derived from Stuff::LA::VectorInterface!");

public:
  typedef VectorImp VectorType;
  typedef typename VectorType::ScalarType ScalarType;

  template <class M, class EntityType>
  ConstLocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, const VectorType& vector)
    : vector_(vector)
    , indices_(mapper.numDofs(entity))
  {
    mapper.globalIndices(entity, indices_);
  }

  ~ConstLocalDoFVector()
  {
  }

  size_t size() const
  {
    return indices_.size();
  }

  ScalarType get(const size_t ii) const
  {
    assert(ii < indices_.size());
    return vector_.get_entry(indices_[ii]);
  }

private:
  const VectorType& vector_;

protected:
  Dune::DynamicVector<size_t> indices_;

private:
  template <class V>
  friend std::ostream& operator<<(std::ostream& /*out*/, const ConstLocalDoFVector<V>& /*vector*/);
}; // class ConstLocalDoFVector

template <class V>
std::ostream& operator<<(std::ostream& out, const ConstLocalDoFVector<V>& vector)
{
  out << "[";
  const size_t sz = vector.size();
  if (sz > 0) {
    out << vector.get(0);
    for (size_t ii = 1; ii < sz; ++ii)
      out << ", " << vector.get(ii);
  } else
    out << " ";
  out << "]";
  return out;
} // ... operator<<(...)

template <class VectorImp>
class LocalDoFVector : public ConstLocalDoFVector<VectorImp>
{
  typedef ConstLocalDoFVector<VectorImp> BaseType;

public:
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::ScalarType ScalarType;

  template <class M, class EntityType>
  LocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, VectorType& vector)
    : BaseType(mapper, entity, vector)
    , vector_(vector)
  {
  }

  ~LocalDoFVector()
  {
  }

  void set(const size_t ii, const ScalarType& val)
  {
    assert(ii < indices_.size());
    vector_.set_entry(indices_[ii], val);
  }

  void add(const size_t ii, const ScalarType& val)
  {
    assert(ii < indices_.size());
    vector_.add_to_entry(indices_[ii], val);
  }

  template <class OtherVectorImp>
  void add(const OtherVectorImp& vector)
  {
    assert(vector.size() == indices_.size());
    for (size_t ii = 0; ii < indices_.size(); ++ii)
      add(ii, vector[ii]);
  }

private:
  using BaseType::indices_;
  VectorType& vector_;
}; // class LocalDoFVector

template <class SpaceImp, class VectorImp>
class ConstLocalDiscreteFunction
    : public Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                           SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
                                           SpaceImp::dimRangeCols>
{
  static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits, SpaceImp::dimDomain, SpaceImp::dimRange,
                                               SpaceImp::dimRangeCols>,
                                SpaceImp>::value,
                "SpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits,
                                                                 typename VectorImp::Traits::ScalarType>,
                                VectorImp>::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
  static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
                "Types do not match!");
  typedef Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                        SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
                                        SpaceImp::dimRangeCols> BaseType;
  typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef SpaceImp SpaceType;
  typedef VectorImp VectorType;
  typedef typename BaseType::EntityType EntityType;

  typedef typename BaseType::DomainFieldType DomainFieldType;
  static const size_t dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType DomainType;

  typedef typename BaseType::RangeFieldType RangeFieldType;
  static const size_t dimRangeRows = BaseType::dimRangeCols;
  static const size_t dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeType RangeType;

  typedef typename BaseType::JacobianRangeType JacobianRangeType;

private:
  typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;

public:
  typedef ConstLocalDoFVector<VectorType> ConstLocalDoFVectorType;

  ConstLocalDiscreteFunction(const SpaceType& sp, const VectorType& globalVector, const EntityType& ent)
    : BaseType(ent)
    , space_(sp)
    , base_(new BaseFunctionSetType(space_.base_function_set(this->entity())))
    , localVector_(new ConstLocalDoFVectorType(space_.mapper(), this->entity(), globalVector))
  {
    assert(localVector_->size() == base_->size());
  }

  ConstLocalDiscreteFunction(ThisType&& source) = default;

  ConstLocalDiscreteFunction(const ThisType& other) = delete;

  ThisType& operator=(const ThisType& other) = delete;

  virtual ~ConstLocalDiscreteFunction()
  {
  }

  const SpaceType& space() const
  {
    return space_;
  }

  const DUNE_DEPRECATED_MSG("Use basis() instead (05.07.2015)!") BaseFunctionSetType& base() const
  {
    return basis();
  }

  const BaseFunctionSetType& basis() const
  {
    return *base_;
  }

  const ConstLocalDoFVectorType& vector() const
  {
    return *localVector_;
  }

  virtual size_t order() const override
  {
    return base_->order();
  }

  void evaluate(const DomainType& xx, RangeType& ret) const override final
  {
    assert(this->is_a_valid_point(xx));
    if (!GDT::is_fv_space<SpaceType>::value) {
      std::fill(ret.begin(), ret.end(), RangeFieldType(0));
      std::vector<RangeType> tmpBaseValues(base_->size(), RangeType(0));
      assert(localVector_->size() == tmpBaseValues.size());
      base_->evaluate(xx, tmpBaseValues);
      for (size_t ii = 0; ii < localVector_->size(); ++ii) {
        ret.axpy(localVector_->get(ii), tmpBaseValues[ii]);
      }
    } else {
      for (size_t ii = 0; ii < localVector_->size(); ++ii)
        ret[ii] = localVector_->get(ii);
    }
  } // ... evaluate(...)

  virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override final
  {
    assert(this->is_a_valid_point(xx));
    if (!GDT::is_fv_space<SpaceType>::value) {
      std::fill(ret.begin(), ret.end(), RangeFieldType(0));
      std::vector<JacobianRangeType> tmpBaseJacobianValues(base_->size(), JacobianRangeType(0));
      assert(localVector_->size() == tmpBaseJacobianValues.size());
      base_->jacobian(xx, tmpBaseJacobianValues);
      for (size_t ii = 0; ii < localVector_->size(); ++ii)
        ret.axpy(localVector_->get(ii), tmpBaseJacobianValues[ii]);
    } else {
      ret = JacobianRangeType(0);
    }
  } // ... jacobian(...)

  using BaseType::evaluate;
  using BaseType::jacobian;

protected:
  const SpaceType& space_;
  std::unique_ptr<const BaseFunctionSetType> base_;
  std::unique_ptr<const ConstLocalDoFVectorType> localVector_;
}; // class ConstLocalDiscreteFunction

template <class SpaceImp, class VectorImp>
class LocalDiscreteFunction : public ConstLocalDiscreteFunction<SpaceImp, VectorImp>
{
  typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> BaseType;
  typedef LocalDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef typename BaseType::SpaceType SpaceType;
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::EntityType EntityType;

  typedef typename BaseType::DomainFieldType DomainFieldType;
  static const size_t dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType DomainType;

  typedef typename BaseType::RangeFieldType RangeFieldType;
  static const size_t dimRangeRows = BaseType::dimRangeCols;
  static const size_t dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeType RangeType;

  typedef typename BaseType::JacobianRangeType JacobianRangeType;

private:
  typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;

public:
  typedef LocalDoFVector<VectorType> LocalDoFVectorType;

  LocalDiscreteFunction(const SpaceType& space, VectorType& globalVector, const EntityType& ent)
    : BaseType(space, globalVector, ent)
    , localVector_(new LocalDoFVectorType(space_.mapper(), entity_, globalVector))
  {
    assert(localVector_->size() == base_->size());
  }

  //! previous comment questioned validity, defaulting this doesn't touch that question
  LocalDiscreteFunction(ThisType&& source) = default;

  LocalDiscreteFunction(const ThisType& other) = delete;

  ThisType& operator=(const ThisType& other) = delete;

  virtual ~LocalDiscreteFunction()
  {
  }

  LocalDoFVectorType& vector()
  {
    return *localVector_;
  }

private:
  using BaseType::space_;
  using BaseType::entity_;
  using BaseType::base_;
  std::unique_ptr<LocalDoFVectorType> localVector_;
}; // class LocalDiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
<|endoftext|>


<commit_before>// This file is part of the dune-pymor project:
//   https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_PYMOR_OPERATORS_INTERFACES_HH
#define DUNE_PYMOR_OPERATORS_INTERFACES_HH

#include <dune/pymor/common/exceptions.hh>
#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/la/container/interfaces.hh>

namespace Dune {
namespace Pymor {

class OperatorInterface
  : public Parametric
{
public:
  template< class... Args >
  OperatorInterface(Args&& ...args)
    : Parametric(std::forward< Args >(args)...)
  {}

  virtual ~OperatorInterface() {}

  virtual bool linear() const = 0;

  virtual unsigned int dim_source() const = 0;

  virtual unsigned int dim_range() const = 0;

  virtual std::string type_source() const = 0;

  virtual std::string type_range() const = 0;

  virtual void apply(const LA::VectorInterface* /*source*/,
                     LA::VectorInterface* /*range*/,
                     const Parameter /*mu*/ = Parameter()) const
    throw (Exception::types_are_not_compatible,
           Exception::you_have_to_implement_this,
           Exception::sizes_do_not_match,
           Exception::wrong_parameter_type) = 0;

  virtual LA::VectorInterface* apply(const LA::VectorInterface* source, const Parameter mu = Parameter()) const
    throw (Exception::types_are_not_compatible,
           Exception::you_have_to_implement_this,
           Exception::sizes_do_not_match,
           Exception::wrong_parameter_type)
  {
    DUNE_PYMOR_THROW(Exception::types_are_not_compatible,
                     "U (" << U->type() << ") is not a compatible type_source (" << type_source() << ")!");
    LA::VectorInterface* ret = LA::createVector(type_range(), dim_range());
    apply(U, ret, mu);
    return ret;
  }

  virtual double apply2(const LA::VectorInterface* range,
                        const LA::VectorInterface* source,
                        const Parameter mu = Parameter()) const
    throw (Exception::types_are_not_compatible,
           Exception::sizes_do_not_match,
           Exception::wrong_parameter_type)
  {
    std::stringstream msg;
    size_t throw_up = 0;
    if (source->type() != type_source()) {
      msg << "source (" << source->type() << ") is not a compatible type_source (" << type_source() << ")";
      ++throw_up;
    }
    if (range->type() != type_range()) {
      if (throw_up)
        msg << " and ";
      msg << "range (" << range->type() << ") is not a compatible type_range (" << type_range() << ")";
    }
    if (throw_up) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, msg.str() << "!");
    LA::VectorInterface* tmp = apply(source, tmp, mu);
    return range->dot(tmp);
  }

  virtual OperatorInterface* freeze_parameter(const Parameter /*mu*/ = Parameter()) const
    throw (Exception::this_is_not_parametric) = 0;
}; // class OperatorInterface

} // namespace Pymor
} // namespace Dune

#endif // DUNE_PYMOR_OPERATORS_INTERFACES_HH
<commit_msg>[operators.interface] some fixes<commit_after>// This file is part of the dune-pymor project:
//   https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_PYMOR_OPERATORS_INTERFACES_HH
#define DUNE_PYMOR_OPERATORS_INTERFACES_HH

#include <dune/pymor/common/exceptions.hh>
#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/la/container/interfaces.hh>
#include <dune/pymor/la/container.hh>

namespace Dune {
namespace Pymor {

class OperatorInterface
  : public Parametric
{
public:
  template< class... Args >
  OperatorInterface(Args&& ...args)
    : Parametric(std::forward< Args >(args)...)
  {}

  virtual ~OperatorInterface() {}

  virtual bool linear() const = 0;

  virtual unsigned int dim_source() const = 0;

  virtual unsigned int dim_range() const = 0;

  virtual std::string type_source() const = 0;

  virtual std::string type_range() const = 0;

  virtual void apply(const LA::VectorInterface* /*source*/,
                     LA::VectorInterface* /*range*/,
                     const Parameter /*mu*/ = Parameter()) const
    throw (Exception::types_are_not_compatible,
           Exception::you_have_to_implement_this,
           Exception::sizes_do_not_match,
           Exception::wrong_parameter_type) = 0;

  virtual LA::VectorInterface* apply(const LA::VectorInterface* source, const Parameter mu = Parameter()) const
    throw (Exception::types_are_not_compatible,
           Exception::you_have_to_implement_this,
           Exception::sizes_do_not_match,
           Exception::wrong_parameter_type)
  {
    DUNE_PYMOR_THROW(Exception::types_are_not_compatible,
                     "source (" << source->type() << ") is not a compatible type_source (" << type_source() << ")!");
    LA::VectorInterface* ret = LA::createVector(type_range(), dim_range());
    apply(source, ret, mu);
    return ret;
  }

  virtual double apply2(const LA::VectorInterface* range,
                        const LA::VectorInterface* source,
                        const Parameter mu = Parameter()) const
    throw (Exception::types_are_not_compatible,
           Exception::sizes_do_not_match,
           Exception::wrong_parameter_type)
  {
    std::stringstream msg;
    size_t throw_up = 0;
    if (source->type() != type_source()) {
      msg << "source (" << source->type() << ") is not a compatible type_source (" << type_source() << ")";
      ++throw_up;
    }
    if (range->type() != type_range()) {
      if (throw_up)
        msg << " and ";
      msg << "range (" << range->type() << ") is not a compatible type_range (" << type_range() << ")";
    }
    if (throw_up) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, msg.str() << "!");
    LA::VectorInterface* tmp = apply(source, mu);
    return range->dot(tmp);
  }

  virtual OperatorInterface* freeze_parameter(const Parameter /*mu*/ = Parameter()) const
    throw (Exception::this_is_not_parametric) = 0;
}; // class OperatorInterface

} // namespace Pymor
} // namespace Dune

#endif // DUNE_PYMOR_OPERATORS_INTERFACES_HH
<|endoftext|>


<commit_before>/*
 * error.hpp
 *
 *  Created on: Oct 6, 2015
 *      Author: zmij
 */

#ifndef TIP_HTTP_SERVER_ERROR_HPP_
#define TIP_HTTP_SERVER_ERROR_HPP_

#include <stdexcept>
#include <tip/log.hpp>
#include <tip/http/common/response_status.hpp>

namespace tip {
namespace http {
namespace server {

class error: public std::runtime_error {
public:
	error(std::string const& cat, std::string const& w,
			response_status s
				= response_status::internal_server_error,
			log::logger::event_severity sv = log::logger::ERROR) :
		runtime_error(w), category_(cat), status_(s), severity_(sv) {};
	virtual ~error() {}

	virtual std::string const&
	name() const;

	virtual int
	code() const
	{ return !0; }

	log::logger::event_severity
	severity() const
	{ return severity_; }

	std::string const&
	category() const
	{ return category_; }

	response_status
	status() const
	{ return status_; }

	void
	log_error(std::string const& message = "") const;
private:
	std::string						category_;
	response_status					status_;
	log::logger::event_severity		severity_;
};

class client_error : public error {
public:
	client_error(std::string const& cat, std::string const& w,
			response_status s
				= response_status::bad_request,
				log::logger::event_severity sv = log::logger::ERROR)
		: error(cat, w, s, sv) {};
	virtual ~client_error() {};

	virtual std::string const&
	name() const;
};

} /* namespace server */
} /* namespace http */
} /* namespace tip */

#endif /* TIP_HTTP_SERVER_ERROR_HPP_ */
<commit_msg>Special function for lobby_error log<commit_after>/*
 * error.hpp
 *
 *  Created on: Oct 6, 2015
 *      Author: zmij
 */

#ifndef TIP_HTTP_SERVER_ERROR_HPP_
#define TIP_HTTP_SERVER_ERROR_HPP_

#include <stdexcept>
#include <tip/log.hpp>
#include <tip/http/common/response_status.hpp>

namespace tip {
namespace http {
namespace server {

class error: public std::runtime_error {
public:
	error(std::string const& cat, std::string const& w,
			response_status s
				= response_status::internal_server_error,
			log::logger::event_severity sv = log::logger::ERROR) :
		runtime_error(w), category_(cat), status_(s), severity_(sv) {};
	virtual ~error() {}

	virtual std::string const&
	name() const;

	virtual int
	code() const
	{ return !0; }

	log::logger::event_severity
	severity() const
	{ return severity_; }

	std::string const&
	category() const
	{ return category_; }

	response_status
	status() const
	{ return status_; }

	virtual void
	log_error(std::string const& message = "") const;
private:
	std::string						category_;
	response_status					status_;
	log::logger::event_severity		severity_;
};

class client_error : public error {
public:
	client_error(std::string const& cat, std::string const& w,
			response_status s
				= response_status::bad_request,
				log::logger::event_severity sv = log::logger::ERROR)
		: error(cat, w, s, sv) {};
	virtual ~client_error() {};

	virtual std::string const&
	name() const;
};

} /* namespace server */
} /* namespace http */
} /* namespace tip */

#endif /* TIP_HTTP_SERVER_ERROR_HPP_ */
<|endoftext|>


<commit_before>// -----------------------------------------------------------------------------
//
// GAMCS -- Generalized Agent Model and Computer Simulation
//
// Copyright (C) 2013-2014, Andy Huang  <andyspider@126.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// -----------------------------------------------------------------------------

#include <stdlib.h>
#include <sys/timeb.h>
#include "gamcs/Avatar.h"
#include "gamcs/debug.h"
#include "gamcs/platforms.h"

namespace gamcs
{

/**
 * @brief The default constructor.
 *
 * @param id the avatar id
 */
Avatar::Avatar(int i) :
		id(i), ava_loop_count(0), myagent(NULL)
{
}

/**
 * @brief The default destructor.
 */
Avatar::~Avatar()
{
}

/**
 * @brief Step avatar for one circle.
 *
 * Note: if there are no more actions for an avatar to perform, the step will return -1 which means the end is reached.
 * @return 0 on success, -1 if reach the end
 * @see loop()
 */
int Avatar::step()
{
	++ava_loop_count;    // increase count

	/* Perceive state */
	Agent::State cs = perceiveState();    // get current state
	dbgmoreprt("Launch():", "Avatar %d, State: %" ST_FMT "\n", id, cs);

	/* Process */
	OSpace acts = availableActions(cs);    // get all action candidates of a state

	Agent::Action act = myagent->process(cs, acts);    // choose an action from candidates
	// check validation
	if (act == Agent::INVALID_ACTION)    // no valid actions available, reach a dead end, quit. !!!: be sure to check this before update stage
		return -1;

	/* update memory */
	myagent->update(originalPayoff(cs));    // agent update inner states

	/* Perform action */
	performAction(act);    // otherwise, perform the action

	return 0;
}

/**
 * @brief Step avatar in loops.
 *
 * @param [in] sps steps/loops per second, < 0 if not control
 * @see step()
 */
void Avatar::loop(int sps)
{
	// check if agent is connected
	if (myagent == NULL)
		ERROR("launch(): Avatar is not connected to any agent!\n");

	unsigned long control_step_time = 0; /**< delta time in millisecond requested bewteen two steps */
	if (sps > 0)
		control_step_time = 1000 / sps;    // (1 / sps) * 1000

	unsigned long start_time = 0;

	while (true)
	{
		dbgmoreprt("Enter Launch Loop ", "------------------------------ count == %ld\n", ava_loop_count);
		if (sps > 0)
			start_time = getCurrentTime();

		int re = step();
		if (re == -1)    // break if no actions available
			break;

		// handle time related job
		if (sps > 0)    // no control when sps <= 0
		{
			unsigned long consumed_time = getCurrentTime() - start_time;
			long time_remaining = control_step_time - consumed_time;
			if (time_remaining > 0)    // remaining time
			{
				dbgmoreprt("",
						"You got %ld milliseconds remaining to do other things.\n",
						time_remaining);
				// do some useful things here if you don't want to sleep
				pi_msleep(time_remaining);
			}
			else
			{
				WARNNING(
						"time is not enough to run a step, %ldms in lack, try to decrease the sps!\n",
						-time_remaining);
			}
		}
	}
	// quit
	dbgmoreprt("Exit Launch Loop", "----------------------------------------------------------- %s Exit!\n", name.c_str());
	return;
}

/**
 * @brief Connect avatar to an agent.
 *
 * Every avatar should be connected to an agent before activated. Just like every man should have soul.
 * @param [in] agt the agent to be connected
 */
void Avatar::connectAgent(Agent *agt)
{
	myagent = agt;
}

/**
 * @brief Get the original payoff of a state.
 *
 * There is where you can control your avatar, you can train it by telling what it likes and dislikes.
 * Your avatar will chase after the states that it told to like, and escape from the states told to dislike.
 *
 * By default this function returns 1 for every state which means that as long as the avatar can survive in the next state, the avatar should like it.
 * This is how the evolution works.
 * @param [in] st the state
 * @return original payoff of the state
 */
float Avatar::originalPayoff(Agent::State st)
{
	UNUSED(st);
	return 1;    // original payoff of states is 1.0 by default
}

/**
 * @brief Get current time in milliseconds.
 *
 * @return the current time as milliseconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC)
 */
unsigned long Avatar::getCurrentTime()
{
	struct timeb tb;
	ftime(&tb);
	return 1000 * tb.time + tb.millitm;
}

}    // namespace gamcs
<commit_msg>fix originalPayoof return comments<commit_after>// -----------------------------------------------------------------------------
//
// GAMCS -- Generalized Agent Model and Computer Simulation
//
// Copyright (C) 2013-2014, Andy Huang  <andyspider@126.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// -----------------------------------------------------------------------------

#include <stdlib.h>
#include <sys/timeb.h>
#include "gamcs/Avatar.h"
#include "gamcs/debug.h"
#include "gamcs/platforms.h"

namespace gamcs
{

/**
 * @brief The default constructor.
 *
 * @param id the avatar id
 */
Avatar::Avatar(int i) :
		id(i), ava_loop_count(0), myagent(NULL)
{
}

/**
 * @brief The default destructor.
 */
Avatar::~Avatar()
{
}

/**
 * @brief Step avatar for one circle.
 *
 * Note: if there are no more actions for an avatar to perform, the step will return -1 which means the end is reached.
 * @return 0 on success, -1 if reach the end
 * @see loop()
 */
int Avatar::step()
{
	++ava_loop_count;    // increase count

	/* Perceive state */
	Agent::State cs = perceiveState();    // get current state
	dbgmoreprt("Launch():", "Avatar %d, State: %" ST_FMT "\n", id, cs);

	/* Process */
	OSpace acts = availableActions(cs);    // get all action candidates of a state

	Agent::Action act = myagent->process(cs, acts);    // choose an action from candidates
	// check validation
	if (act == Agent::INVALID_ACTION)    // no valid actions available, reach a dead end, quit. !!!: be sure to check this before update stage
		return -1;

	/* update memory */
	myagent->update(originalPayoff(cs));    // agent update inner states

	/* Perform action */
	performAction(act);    // otherwise, perform the action

	return 0;
}

/**
 * @brief Step avatar in loops.
 *
 * @param [in] sps steps/loops per second, < 0 if not control
 * @see step()
 */
void Avatar::loop(int sps)
{
	// check if agent is connected
	if (myagent == NULL)
		ERROR("launch(): Avatar is not connected to any agent!\n");

	unsigned long control_step_time = 0; /**< delta time in millisecond requested bewteen two steps */
	if (sps > 0)
		control_step_time = 1000 / sps;    // (1 / sps) * 1000

	unsigned long start_time = 0;

	while (true)
	{
		dbgmoreprt("Enter Launch Loop ", "------------------------------ count == %ld\n", ava_loop_count);
		if (sps > 0)
			start_time = getCurrentTime();

		int re = step();
		if (re == -1)    // break if no actions available
			break;

		// handle time related job
		if (sps > 0)    // no control when sps <= 0
		{
			unsigned long consumed_time = getCurrentTime() - start_time;
			long time_remaining = control_step_time - consumed_time;
			if (time_remaining > 0)    // remaining time
			{
				dbgmoreprt("",
						"You got %ld milliseconds remaining to do other things.\n",
						time_remaining);
				// do some useful things here if you don't want to sleep
				pi_msleep(time_remaining);
			}
			else
			{
				WARNNING(
						"time is not enough to run a step, %ldms in lack, try to decrease the sps!\n",
						-time_remaining);
			}
		}
	}
	// quit
	dbgmoreprt("Exit Launch Loop", "----------------------------------------------------------- %s Exit!\n", name.c_str());
	return;
}

/**
 * @brief Connect avatar to an agent.
 *
 * Every avatar should be connected to an agent before activated. Just like every man should have soul.
 * @param [in] agt the agent to be connected
 */
void Avatar::connectAgent(Agent *agt)
{
	myagent = agt;
}

/**
 * @brief Get the original payoff of a state.
 *
 * There is where you can control your avatar, you can train it by telling what it likes and dislikes.
 * Your avatar will chase after the states that it told to like, and escape from the states told to dislike.
 *
 * By default this function returns 1 for every state which means that as long as the avatar can survive in the next state, the avatar should like it.
 * This is how the evolution works.
 * @param [in] st the state
 * @return original payoff of the state, if you want avatar to use the original payoff of the state set last time, return INVALID_PAYOFF.
 */
float Avatar::originalPayoff(Agent::State st)
{
	UNUSED(st);
	return 1;    // original payoff of states is 1.0 by default
}

/**
 * @brief Get current time in milliseconds.
 *
 * @return the current time as milliseconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC)
 */
unsigned long Avatar::getCurrentTime()
{
	struct timeb tb;
	ftime(&tb);
	return 1000 * tb.time + tb.millitm;
}

}    // namespace gamcs
<|endoftext|>