<commit_before>#include <gtest/gtest.h>

#include "./unordered_set.h"
#include "./unordered_map.h"

TEST(unordered_test, reserve) {
  std::size_t n = 10000;

  {
    pfi::data::unordered_set<int> us;
    us.reserve(n);
    EXPECT_GE(us.bucket_count(), std::ceil(n / us.max_load_factor()));
  }

  {
    pfi::data::unordered_multiset<int> ums;
    ums.reserve(n);
    EXPECT_GE(ums.bucket_count(), std::ceil(n / ums.max_load_factor()));
  }

  {
    pfi::data::unordered_map<int, int> um;
    um.reserve(n);
    EXPECT_GE(um.bucket_count(), std::ceil(n / um.max_load_factor()));
  }

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

#include <gtest/gtest.h>

#include "./unordered_set.h"
#include "./unordered_map.h"

TEST(unordered_test, reserve) {
  std::size_t n = 10000;

  {
    pfi::data::unordered_set<int> us;
    us.reserve(n);
    EXPECT_GE(us.bucket_count(), std::ceil(n / us.max_load_factor()));
  }

  {
    pfi::data::unordered_multiset<int> ums;
    ums.reserve(n);
    EXPECT_GE(ums.bucket_count(), std::ceil(n / ums.max_load_factor()));
  }

  {
    pfi::data::unordered_map<int, int> um;
    um.reserve(n);
    EXPECT_GE(um.bucket_count(), std::ceil(n / um.max_load_factor()));
  }

  {
    pfi::data::unordered_multimap<int, int> umm;
    umm.reserve(n);
    EXPECT_GE(umm.bucket_count(), std::ceil(n / umm.max_load_factor()));
  }
}
<|endoftext|>


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

#include <precomp.h>
#include <ary/cpp/c_namesp.hxx>

// NOT FULLY DECLARED SERVICES
#include <algorithm>
#include <cosv/tpl/tpltools.hxx>
#include <ary/cpp/c_funct.hxx>
#include <ary/cpp/c_gate.hxx>
#include <ary/getncast.hxx>
#include <slots.hxx>
#include "c_slots.hxx"

namespace ary
{
namespace cpp
{

typedef std::multimap<String, Ce_id>::const_iterator      operations_citer;

Namespace::Namespace()
    :   aEssentials(),
        aAssignedNode(),
        // aLocalNamespaces,
        // aLocalClasses,
        // aLocalEnums,
        // aLocalTypedefs,
        // aLocalOperations,
        // aLocalVariables,
        // aLocalConstants,
        pParent(0),
        nDepth(0)
{
    aAssignedNode.Assign_Entity(*this);
}

Namespace::Namespace( const String  &     i_sLocalName,
                      Namespace &         i_rParent )
    :   aEssentials( i_sLocalName,
                     i_rParent.CeId(),
                     Lid(0) ),
        aAssignedNode(),
        // aLocalNamespaces,
        // aLocalClasses,
        // aLocalEnums,
        // aLocalTypedefs,
        // aLocalOperations,
        // aLocalVariables,
        // aLocalConstants,
        pParent(&i_rParent),
        nDepth(i_rParent.Depth()+1)
{
    aAssignedNode.Assign_Entity(*this);
}

Namespace::~Namespace()
{
}

void
Namespace::Add_LocalNamespace( DYN Namespace & io_rLocalNamespace )
{
    aLocalNamespaces[io_rLocalNamespace.LocalName()] = &io_rLocalNamespace;
}

void
Namespace::Add_LocalClass( const String  &     i_sLocalName,
                           Cid                 i_nId )
{
    aLocalClasses[i_sLocalName] = i_nId;
}

void
Namespace::Add_LocalEnum( const String  &     i_sLocalName,
                          Cid                 i_nId )
{
    aLocalEnums[i_sLocalName] = i_nId;
}

void
Namespace::Add_LocalTypedef( const String  &     i_sLocalName,
                             Cid                 i_nId )
{
    aLocalTypedefs[i_sLocalName] = i_nId;
}

void
Namespace::Add_LocalOperation( const String  &     i_sLocalName,
                               Cid                 i_nId )
{
    aLocalOperations.insert( Map_Operations::value_type(i_sLocalName, i_nId) );
}

void
Namespace::Add_LocalVariable( const String  &     i_sLocalName,
                              Cid                 i_nId )
{
    aLocalVariables[i_sLocalName] = i_nId;
}

void
Namespace::Add_LocalConstant( const String  &     i_sLocalName,
                              Cid                 i_nId )
{
    aLocalConstants[i_sLocalName] = i_nId;
}

uintt
Namespace::Depth() const
{
    return nDepth;
}

Namespace *
Namespace::Parent() const
{
    return pParent;
}

Ce_id
Namespace::Search_Child(const String & i_key) const
{
    Namespace *
        ret_nsp = Search_LocalNamespace(i_key);
    if (ret_nsp != 0)
        return ret_nsp->CeId();

    Ce_id
        ret = Search_LocalClass(i_key);
    if (ret.IsValid())
        return ret;

    ret = csv::value_from_map(aLocalEnums, i_key, Ce_id(0));
    if (ret.IsValid())
        return ret;
    ret = csv::value_from_map(aLocalTypedefs, i_key, Ce_id(0));
    if (ret.IsValid())
        return ret;
    ret = csv::value_from_map(aLocalVariables, i_key, Ce_id(0));
    if (ret.IsValid())
        return ret;
    return csv::value_from_map(aLocalConstants, i_key, Ce_id(0));
}

Namespace *
Namespace::Search_LocalNamespace( const String  & i_sLocalName ) const
{
    return csv::value_from_map(aLocalNamespaces, i_sLocalName, (Namespace*)(0));
}

uintt
Namespace::Get_SubNamespaces( std::vector< const Namespace* > & o_rResultList ) const
{
    for ( Map_NamespacePtr::const_iterator it = aLocalNamespaces.begin();
          it != aLocalNamespaces.end();
          ++it )
    {
        o_rResultList.push_back( (*it).second );
    }
    return o_rResultList.size();
}

Ce_id
Namespace::Search_LocalClass( const String  & i_sName ) const
{
    return csv::value_from_map(aLocalClasses, i_sName, Ce_id(0));
}

void
Namespace::Search_LocalOperations( std::vector<Ce_id> & o_result,
                                   const String &       i_sName ) const
{
    operations_citer
        itLower = aLocalOperations.lower_bound(i_sName);
    if (itLower == aLocalOperations.end())
        return;
    if ( (*itLower).first != i_sName )
        return;

    operations_citer
        itEnd = aLocalOperations.end();
    for ( operations_citer it = itLower;
          it != aLocalOperations.end() ? (*itLower).first == i_sName : false;
          ++it )
    {
        o_result.push_back((*it).second);
    }
}

const String  &
Namespace::inq_LocalName() const
{
    return aEssentials.LocalName();
}

Cid
Namespace::inq_Owner() const
{
    return aEssentials.Owner();
}

Lid
Namespace::inq_Location() const
{
    return Lid(0);
}

void
Namespace::do_Accept(csv::ProcessorIfc & io_processor) const
{
    csv::CheckedCall(io_processor,*this);
}

ClassId
Namespace::get_AryClass() const
{
    return class_id;
}

Gid
Namespace::inq_Id_Group() const
{
    return static_cast<Gid>(Id());
}

const ary::cpp::CppEntity &
Namespace::inq_RE_Group() const
{
    return *this;
}

const ary::group::SlotList &
Namespace::inq_Slots() const
{
    static const SlotAccessId aProjectSlotData[]
            = { SLOT_SubNamespaces, SLOT_Classes, SLOT_Enums, SLOT_Typedefs, SLOT_Operations,
                SLOT_Variables, SLOT_Constants };
    static const std::vector< SlotAccessId >
            aSlots( &aProjectSlotData[0],
                      &aProjectSlotData[0]
                        + sizeof aProjectSlotData / sizeof (SlotAccessId) );
    return aSlots;
}

DYN Slot *
Namespace::inq_Create_Slot( SlotAccessId i_nSlot ) const
{
    switch ( i_nSlot )
    {
        case SLOT_SubNamespaces:    return new Slot_SubNamespaces(aLocalNamespaces);
        case SLOT_Classes:          return new Slot_MapLocalCe(aLocalClasses);
        case SLOT_Enums:            return new Slot_MapLocalCe(aLocalEnums);
        case SLOT_Typedefs:         return new Slot_MapLocalCe(aLocalTypedefs);
        case SLOT_Operations:       return new Slot_MapOperations(aLocalOperations);
        case SLOT_Variables:        return new Slot_MapLocalCe(aLocalVariables);
        case SLOT_Constants:        return new Slot_MapLocalCe(aLocalConstants);
        default:
                                    return new Slot_Null;
    }   // end switch
}

}   // namespace cpp
}   // namespace ary
<commit_msg>INTEGRATION: CWS changefileheader (1.6.22); FILE MERGED 2008/03/28 16:01:36 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: c_namesp.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.
 *
 ************************************************************************/

#include <precomp.h>
#include <ary/cpp/c_namesp.hxx>

// NOT FULLY DECLARED SERVICES
#include <algorithm>
#include <cosv/tpl/tpltools.hxx>
#include <ary/cpp/c_funct.hxx>
#include <ary/cpp/c_gate.hxx>
#include <ary/getncast.hxx>
#include <slots.hxx>
#include "c_slots.hxx"

namespace ary
{
namespace cpp
{

typedef std::multimap<String, Ce_id>::const_iterator      operations_citer;

Namespace::Namespace()
    :   aEssentials(),
        aAssignedNode(),
        // aLocalNamespaces,
        // aLocalClasses,
        // aLocalEnums,
        // aLocalTypedefs,
        // aLocalOperations,
        // aLocalVariables,
        // aLocalConstants,
        pParent(0),
        nDepth(0)
{
    aAssignedNode.Assign_Entity(*this);
}

Namespace::Namespace( const String  &     i_sLocalName,
                      Namespace &         i_rParent )
    :   aEssentials( i_sLocalName,
                     i_rParent.CeId(),
                     Lid(0) ),
        aAssignedNode(),
        // aLocalNamespaces,
        // aLocalClasses,
        // aLocalEnums,
        // aLocalTypedefs,
        // aLocalOperations,
        // aLocalVariables,
        // aLocalConstants,
        pParent(&i_rParent),
        nDepth(i_rParent.Depth()+1)
{
    aAssignedNode.Assign_Entity(*this);
}

Namespace::~Namespace()
{
}

void
Namespace::Add_LocalNamespace( DYN Namespace & io_rLocalNamespace )
{
    aLocalNamespaces[io_rLocalNamespace.LocalName()] = &io_rLocalNamespace;
}

void
Namespace::Add_LocalClass( const String  &     i_sLocalName,
                           Cid                 i_nId )
{
    aLocalClasses[i_sLocalName] = i_nId;
}

void
Namespace::Add_LocalEnum( const String  &     i_sLocalName,
                          Cid                 i_nId )
{
    aLocalEnums[i_sLocalName] = i_nId;
}

void
Namespace::Add_LocalTypedef( const String  &     i_sLocalName,
                             Cid                 i_nId )
{
    aLocalTypedefs[i_sLocalName] = i_nId;
}

void
Namespace::Add_LocalOperation( const String  &     i_sLocalName,
                               Cid                 i_nId )
{
    aLocalOperations.insert( Map_Operations::value_type(i_sLocalName, i_nId) );
}

void
Namespace::Add_LocalVariable( const String  &     i_sLocalName,
                              Cid                 i_nId )
{
    aLocalVariables[i_sLocalName] = i_nId;
}

void
Namespace::Add_LocalConstant( const String  &     i_sLocalName,
                              Cid                 i_nId )
{
    aLocalConstants[i_sLocalName] = i_nId;
}

uintt
Namespace::Depth() const
{
    return nDepth;
}

Namespace *
Namespace::Parent() const
{
    return pParent;
}

Ce_id
Namespace::Search_Child(const String & i_key) const
{
    Namespace *
        ret_nsp = Search_LocalNamespace(i_key);
    if (ret_nsp != 0)
        return ret_nsp->CeId();

    Ce_id
        ret = Search_LocalClass(i_key);
    if (ret.IsValid())
        return ret;

    ret = csv::value_from_map(aLocalEnums, i_key, Ce_id(0));
    if (ret.IsValid())
        return ret;
    ret = csv::value_from_map(aLocalTypedefs, i_key, Ce_id(0));
    if (ret.IsValid())
        return ret;
    ret = csv::value_from_map(aLocalVariables, i_key, Ce_id(0));
    if (ret.IsValid())
        return ret;
    return csv::value_from_map(aLocalConstants, i_key, Ce_id(0));
}

Namespace *
Namespace::Search_LocalNamespace( const String  & i_sLocalName ) const
{
    return csv::value_from_map(aLocalNamespaces, i_sLocalName, (Namespace*)(0));
}

uintt
Namespace::Get_SubNamespaces( std::vector< const Namespace* > & o_rResultList ) const
{
    for ( Map_NamespacePtr::const_iterator it = aLocalNamespaces.begin();
          it != aLocalNamespaces.end();
          ++it )
    {
        o_rResultList.push_back( (*it).second );
    }
    return o_rResultList.size();
}

Ce_id
Namespace::Search_LocalClass( const String  & i_sName ) const
{
    return csv::value_from_map(aLocalClasses, i_sName, Ce_id(0));
}

void
Namespace::Search_LocalOperations( std::vector<Ce_id> & o_result,
                                   const String &       i_sName ) const
{
    operations_citer
        itLower = aLocalOperations.lower_bound(i_sName);
    if (itLower == aLocalOperations.end())
        return;
    if ( (*itLower).first != i_sName )
        return;

    operations_citer
        itEnd = aLocalOperations.end();
    for ( operations_citer it = itLower;
          it != aLocalOperations.end() ? (*itLower).first == i_sName : false;
          ++it )
    {
        o_result.push_back((*it).second);
    }
}

const String  &
Namespace::inq_LocalName() const
{
    return aEssentials.LocalName();
}

Cid
Namespace::inq_Owner() const
{
    return aEssentials.Owner();
}

Lid
Namespace::inq_Location() const
{
    return Lid(0);
}

void
Namespace::do_Accept(csv::ProcessorIfc & io_processor) const
{
    csv::CheckedCall(io_processor,*this);
}

ClassId
Namespace::get_AryClass() const
{
    return class_id;
}

Gid
Namespace::inq_Id_Group() const
{
    return static_cast<Gid>(Id());
}

const ary::cpp::CppEntity &
Namespace::inq_RE_Group() const
{
    return *this;
}

const ary::group::SlotList &
Namespace::inq_Slots() const
{
    static const SlotAccessId aProjectSlotData[]
            = { SLOT_SubNamespaces, SLOT_Classes, SLOT_Enums, SLOT_Typedefs, SLOT_Operations,
                SLOT_Variables, SLOT_Constants };
    static const std::vector< SlotAccessId >
            aSlots( &aProjectSlotData[0],
                      &aProjectSlotData[0]
                        + sizeof aProjectSlotData / sizeof (SlotAccessId) );
    return aSlots;
}

DYN Slot *
Namespace::inq_Create_Slot( SlotAccessId i_nSlot ) const
{
    switch ( i_nSlot )
    {
        case SLOT_SubNamespaces:    return new Slot_SubNamespaces(aLocalNamespaces);
        case SLOT_Classes:          return new Slot_MapLocalCe(aLocalClasses);
        case SLOT_Enums:            return new Slot_MapLocalCe(aLocalEnums);
        case SLOT_Typedefs:         return new Slot_MapLocalCe(aLocalTypedefs);
        case SLOT_Operations:       return new Slot_MapOperations(aLocalOperations);
        case SLOT_Variables:        return new Slot_MapLocalCe(aLocalVariables);
        case SLOT_Constants:        return new Slot_MapLocalCe(aLocalConstants);
        default:
                                    return new Slot_Null;
    }   // end switch
}

}   // namespace cpp
}   // namespace ary
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tplparam.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: np $ $Date: 2002-03-08 14:45:18 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef ARY_CPP_TPLPARAM_HXX
#define ARY_CPP_TPLPARAM_HXX

// USED SERVICES
    // BASE CLASSES
    // COMPONENTS
    // PARAMETERS
#include <ary/ids.hxx>

namespace ary
{
namespace cpp
{
    class UsedType;
    class DisplayGate;

namespace ut
{

class TemplateParameter
{
  public:
    virtual             ~TemplateParameter() {}

    virtual intt        Compare(
                            const TemplateParameter &
                                                i_rOther ) const = 0;
    virtual void        Get_Text(
                            StreamStr &         o_rOut,
                            const ary::cpp::DisplayGate &
                                                i_rGate ) const = 0;
};

class TplParameter_Type : public TemplateParameter
{
  public:
                        TplParameter_Type(
                            Tid                 i_nType );
                        ~TplParameter_Type();

    virtual intt        Compare(
                            const TemplateParameter &
                                                i_rOther ) const;
    virtual void        Get_Text(
                            StreamStr &         o_rOut,
                            const ary::cpp::DisplayGate &
                                                i_rGate ) const;
  private:
    Tid                 nType;
};

class TplParameter_Const : public TemplateParameter
{
  public:
                        TplParameter_Const(
                            const udmstri &     i_sConst );
                        ~TplParameter_Const();

    virtual intt        Compare(
                            const TemplateParameter &
                                                i_rOther ) const;
    virtual void        Get_Text(
                            StreamStr &         o_rOut,
                            const ary::cpp::DisplayGate &
                                                i_rGate ) const;
  private:
    udmstri             sConstant;
};

}   // namespace ut
}   // namespace cpp
}   // namespace ary

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.146); FILE MERGED 2005/09/05 13:09:53 rt 1.1.1.1.146.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tplparam.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 16:39:18 $
 *
 *  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 ARY_CPP_TPLPARAM_HXX
#define ARY_CPP_TPLPARAM_HXX

// USED SERVICES
    // BASE CLASSES
    // COMPONENTS
    // PARAMETERS
#include <ary/ids.hxx>

namespace ary
{
namespace cpp
{
    class UsedType;
    class DisplayGate;

namespace ut
{

class TemplateParameter
{
  public:
    virtual             ~TemplateParameter() {}

    virtual intt        Compare(
                            const TemplateParameter &
                                                i_rOther ) const = 0;
    virtual void        Get_Text(
                            StreamStr &         o_rOut,
                            const ary::cpp::DisplayGate &
                                                i_rGate ) const = 0;
};

class TplParameter_Type : public TemplateParameter
{
  public:
                        TplParameter_Type(
                            Tid                 i_nType );
                        ~TplParameter_Type();

    virtual intt        Compare(
                            const TemplateParameter &
                                                i_rOther ) const;
    virtual void        Get_Text(
                            StreamStr &         o_rOut,
                            const ary::cpp::DisplayGate &
                                                i_rGate ) const;
  private:
    Tid                 nType;
};

class TplParameter_Const : public TemplateParameter
{
  public:
                        TplParameter_Const(
                            const udmstri &     i_sConst );
                        ~TplParameter_Const();

    virtual intt        Compare(
                            const TemplateParameter &
                                                i_rOther ) const;
    virtual void        Get_Text(
                            StreamStr &         o_rOut,
                            const ary::cpp::DisplayGate &
                                                i_rGate ) const;
  private:
    udmstri             sConstant;
};

}   // namespace ut
}   // namespace cpp
}   // namespace ary

#endif

<|endoftext|>


<commit_before><commit_msg>Related fdo#84000: Improve framerate of the models.<commit_after><|endoftext|>


<commit_before>/*
  * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  *
  * Licensed under the Apache License, Version 2.0 (the "License").
  * You may not use this file except in compliance with the License.
  * A copy of the License is located at
  *
  *  http://aws.amazon.com/apache2.0
  *
  * or in the "license" file accompanying this file. This file is distributed
  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  * express or implied. See the License for the specific language governing
  * permissions and limitations under the License.
  */

#include <aws/external/gtest.h>
#include <aws/core/utils/crypto/Factories.h>
#include <aws/core/http/HttpClientFactory.h>
#include <aws/core/Aws.h>
#include <aws/testing/TestingEnvironment.h>
#include <aws/testing/platform/PlatformTesting.h>
#include <aws/testing/MemoryTesting.h>

int main(int argc, char** argv)
{
    Aws::Testing::RedirectHomeToTempIfAppropriate();

    Aws::SDKOptions options;

    ExactTestMemorySystem memorySystem(16, 10);
    options.memoryManagementOptions.memoryManager = &memorySystem;
    Aws::Testing::InitPlatformTest(options);

    options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace;
    options.httpOptions.installSigPipeHandler = true;

    Aws::InitAPI(options);
    ::testing::InitGoogleTest(&argc, argv);
    int retVal = RUN_ALL_TESTS();
    Aws::ShutdownAPI(options);
    EXPECT_EQ(memorySystem.GetCurrentOutstandingAllocations(), 0ULL);
    EXPECT_EQ(memorySystem.GetCurrentBytesAllocated(), 0ULL);
    EXPECT_TRUE(memorySystem.IsClean());

    Aws::Testing::ShutdownPlatformTest(options);

    return retVal;
}
<commit_msg>Fix #232 (#114)<commit_after>/*
  * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  *
  * Licensed under the Apache License, Version 2.0 (the "License").
  * You may not use this file except in compliance with the License.
  * A copy of the License is located at
  *
  *  http://aws.amazon.com/apache2.0
  *
  * or in the "license" file accompanying this file. This file is distributed
  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  * express or implied. See the License for the specific language governing
  * permissions and limitations under the License.
  */

#include <aws/external/gtest.h>
#include <aws/core/utils/crypto/Factories.h>
#include <aws/core/http/HttpClientFactory.h>
#include <aws/core/Aws.h>
#include <aws/testing/TestingEnvironment.h>
#include <aws/testing/platform/PlatformTesting.h>
#include <aws/testing/MemoryTesting.h>

#ifndef _MSC_VER
#include <sys/stat.h>
#endif

int main(int argc, char** argv)
{
#ifndef _MSC_VER
	// In order to fix github issue at https://github.com/aws/aws-sdk-cpp/issues/232
    // Created dir by this process will be set with mode 0777, so that multiple users can build on the same machine
	umask(0);
#endif

    Aws::Testing::RedirectHomeToTempIfAppropriate();

    Aws::SDKOptions options;

    ExactTestMemorySystem memorySystem(16, 10);
    options.memoryManagementOptions.memoryManager = &memorySystem;
    Aws::Testing::InitPlatformTest(options);

    options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace;
    options.httpOptions.installSigPipeHandler = true;

    Aws::InitAPI(options);
    ::testing::InitGoogleTest(&argc, argv);
    int retVal = RUN_ALL_TESTS();
    Aws::ShutdownAPI(options);
    EXPECT_EQ(memorySystem.GetCurrentOutstandingAllocations(), 0ULL);
    EXPECT_EQ(memorySystem.GetCurrentBytesAllocated(), 0ULL);
    EXPECT_TRUE(memorySystem.IsClean());

    Aws::Testing::ShutdownPlatformTest(options);

    return retVal;
}
<|endoftext|>


<commit_before>#ifndef ENTT_SIGNAL_EMITTER_HPP
#define ENTT_SIGNAL_EMITTER_HPP

#include <type_traits>
#include <functional>
#include <algorithm>
#include <utility>
#include <cstdint>
#include <memory>
#include <vector>
#include <list>

namespace entt {

/**
 * @brief General purpose event emitter.
 *
 * The emitter class template follows the CRTP idiom. To create a custom emitter
 * type, derived classes must inherit directly from the base class as:
 *
 * ```cpp
 * struct MyEmitter: Emitter<MyEmitter> {
 *     // ...
 * }
 * ```
 *
 * Handlers for the type of events are created internally on the fly. It's not
 * required to specify in advance the full list of accepted types.

 * Moreover, whenever an event is published, an emitter provides the listeners
 * with a reference to itself along with a const reference to the event.
 * Therefore listeners have an handy way to work with it without incurring in
 * the need of capturing a reference to the emitter.
 *
 * @tparam Derived Actual type of emitter that extends the class template.
 */
template<typename Derived>
class Emitter {
    struct BaseHandler {
        virtual ~BaseHandler() = default;
        virtual bool empty() const noexcept = 0;
        virtual void clear() noexcept = 0;
    };

    template<typename Event>
    struct Handler final: BaseHandler {
        using listener_type = std::function<void(const Event &, Derived &)>;
        using element_type = std::pair<bool, listener_type>;
        using container_type = std::list<element_type>;
        using connection_type = typename container_type::iterator;

        bool empty() const noexcept override {
            auto pred = [](auto &&element){ return element.first; };

            return std::all_of(onceL.cbegin(), onceL.cend(), pred) &&
                    std::all_of(onL.cbegin(), onL.cend(), pred);
        }

        void clear() noexcept override {
            if(publishing) {
                auto func = [](auto &&element){ element.first = true; };
                std::for_each(onceL.begin(), onceL.end(), func);
                std::for_each(onL.begin(), onL.end(), func);
            } else {
                onceL.clear();
                onL.clear();
            }
        }

        inline connection_type once(listener_type listener) {
            return onceL.emplace(onceL.cend(), false, std::move(listener));
        }

        inline connection_type on(listener_type listener) {
            return onL.emplace(onL.cend(), false, std::move(listener));
        }

        void erase(connection_type conn) noexcept {
            conn->first = true;

            if(!publishing) {
                auto pred = [](auto &&element){ return element.first; };
                onceL.remove_if(pred);
                onL.remove_if(pred);
            }
        }

        void publish(const Event &event, Derived &ref) {
            container_type currentL;
            onceL.swap(currentL);

            auto func = [&event, &ref](auto &&element) {
                return element.first ? void() : element.second(event, ref);
            };

            publishing = true;

            std::for_each(onL.rbegin(), onL.rend(), func);
            std::for_each(currentL.rbegin(), currentL.rend(), func);

            publishing = false;

            onL.remove_if([](auto &&element){ return element.first; });
        }

    private:
        bool publishing{false};
        container_type onceL{};
        container_type onL{};
    };

    static std::size_t next() noexcept {
        static std::size_t counter = 0;
        return counter++;
    }

    template<typename>
    static std::size_t type() noexcept {
        static std::size_t value = next();
        return value;
    }

    template<typename Event>
    Handler<Event> & handler() noexcept {
        const std::size_t family = type<Event>();

        if(!(family < handlers.size())) {
            handlers.resize(family+1);
        }

        if(!handlers[family]) {
            handlers[family] = std::make_unique<Handler<Event>>();
        }

        return static_cast<Handler<Event> &>(*handlers[family]);
    }

public:
    /** @brief Type of listeners accepted for the given type of event. */
    template<typename Event>
    using Listener = typename Handler<Event>::listener_type;

    /**
     * @brief Generic connection type for events.
     *
     * Type of the connection object returned by the event emitter whenever a
     * listener for the given type is registered.

     * It can be used to break connections still in use.
     *
     * @tparam Event Type of event for which the connection is created.
     */
    template<typename Event>
    struct Connection final: private Handler<Event>::connection_type {
        /** @brief Event emitters are friend classes of connections. */
        friend class Emitter;

        /*! @brief Default constructor. */
        Connection() noexcept = default;

        /**
         * @brief Creates a connection that wraps its underlying instance.
         * @param conn A connection object to wrap.
         */
        Connection(typename Handler<Event>::connection_type conn)
            : Handler<Event>::connection_type{std::move(conn)}
        {}

        /*! @brief Default copy constructor. */
        Connection(const Connection &) = default;
        /*! @brief Default move constructor. */
        Connection(Connection &&) = default;

        /**
         * @brief Default copy assignament operator.
         * @return This connection.
         */
        Connection & operator=(const Connection &) = default;

        /**
         * @brief Default move assignment operator.
         * @return This connection.
         */
        Connection & operator=(Connection &&) = default;
    };

    /*! @brief Default constructor. */
    Emitter() noexcept = default;

    /*! @brief Default destructor. */
    virtual ~Emitter() noexcept {
        static_assert(std::is_base_of<Emitter<Derived>, Derived>::value, "!");
    }

    /*! @brief Copying an emitter isn't allowed. */
    Emitter(const Emitter &) = delete;
    /*! @brief Default move constructor. */
    Emitter(Emitter &&) = default;

    /*! @brief Copying an emitter isn't allowed. @return This emitter. */
    Emitter & operator=(const Emitter &) = delete;
    /*! @brief Default move assignament operator. @return This emitter. */
    Emitter & operator=(Emitter &&) = default;

    /**
     * @brief Emits the given event.
     *
     * All the listeners registered for the specific event type are invoked with
     * the given event. The event type must either have a proper constructor for
     * the arguments provided or be an aggregate type.
     *
     * @tparam Event Type of event to publish.
     * @tparam Args Types of arguments to use to construct the event.
     * @param args Parameters to use to initialize the event.
     */
    template<typename Event, typename... Args>
    void publish(Args&&... args) {
        handler<Event>().publish({ std::forward<Args>(args)... }, *static_cast<Derived *>(this));
    }

    /**
     * @brief Registers a long-lived listener with the event emitter.
     *
     * This method can be used to register a listener designed to be invoked
     * more than once for the given event type.

     * The connection returned by the method can be freely discarded. It's meant
     * to be used later to disconnect the listener if required.
     *
     * The listener is as a callable object that can be moved and the type of
     * which is `void(const Event &, Derived &)`.
     *
     * @note
     * Whenever an event is emitted, the emitter provides the listener with a
     * reference to the derived class. Listeners don't have to capture those
     * instances for later uses.
     *
     * @tparam Event Type of event to which to connect the listener.
     * @param listener The listener to register.
     * @return Connection object that can be used to disconnect the listener.
     */
    template<typename Event>
    Connection<Event> on(Listener<Event> listener) {
        return handler<Event>().on(std::move(listener));
    }

    /**
     * @brief Registers a short-lived listener with the event emitter.
     *
     * This method can be used to register a listener designed to be invoked
     * only once for the given event type.

     * The connection returned by the method can be freely discarded. It's meant
     * to be used later to disconnect the listener if required.
     *
     * The listener is as a callable object that can be moved and the type of
     * which is `void(const Event &, Derived &)`.
     *
     * @note
     * Whenever an event is emitted, the emitter provides the listener with a
     * reference to the derived class. Listeners don't have to capture those
     * instances for later uses.
     *
     * @tparam Event Type of event to which to connect the listener.
     * @param listener The listener to register.
     * @return Connection object that can be used to disconnect the listener.
     */
    template<typename Event>
    Connection<Event> once(Listener<Event> listener) {
        return handler<Event>().once(std::move(listener));
    }

    /**
     * @brief Disconnects a listener from the event emitter.
     *
     * Do not use twice the same connection to disconnect a listener, it results
     * in undefined behavior. Once used, discard the connection object.
     *
     * @tparam Event Type of event of the connection.
     * @param conn A valid connection.
     */
    template<typename Event>
    void erase(Connection<Event> conn) noexcept {
        handler<Event>().erase(std::move(conn));
    }

    /**
     * @brief Disconnects all the listeners for the given event type.
     *
     * All the connections previously returned for the given event are
     * invalidated. Using them results in undefined behaviour.
     *
     * @tparam Event Type of event to reset.
     */
    template<typename Event>
    void clear() noexcept {
        handler<Event>().clear();
    }

    /**
     * @brief Disconnects all the listeners.
     *
     * All the connections previously returned are invalidated. Using them
     * results in undefined behaviour.
     */
    void clear() noexcept {
        std::for_each(handlers.begin(), handlers.end(),
                      [](auto &&handler){ if(handler) { handler->clear(); } });
    }

    /**
     * @brief Checks if there are listeners registered for the specific event.
     * @tparam Event Type of event to test.
     * @return True if there are no listeners registered, false otherwise.
     */
    template<typename Event>
    bool empty() const noexcept {
        const std::size_t family = type<Event>();

        return (!(family < handlers.size()) ||
                !handlers[family] ||
                static_cast<Handler<Event> &>(*handlers[family]).empty());
    }

    /**
     * @brief Checks if there are listeners registered with the event emitter.
     * @return True if there are no listeners registered, false otherwise.
     */
    bool empty() const noexcept {
        return std::all_of(handlers.cbegin(), handlers.cend(),
                           [](auto &&handler){ return !handler || handler->empty(); });
    }

private:
    std::vector<std::unique_ptr<BaseHandler>> handlers{};
};

}

#endif // ENTT_SIGNAL_EMITTER_HPP
<commit_msg>fixed typo<commit_after>#ifndef ENTT_SIGNAL_EMITTER_HPP
#define ENTT_SIGNAL_EMITTER_HPP

#include <type_traits>
#include <functional>
#include <algorithm>
#include <utility>
#include <cstdint>
#include <memory>
#include <vector>
#include <list>

namespace entt {

/**
 * @brief General purpose event emitter.
 *
 * The emitter class template follows the CRTP idiom. To create a custom emitter
 * type, derived classes must inherit directly from the base class as:
 *
 * ```cpp
 * struct MyEmitter: Emitter<MyEmitter> {
 *     // ...
 * }
 * ```
 *
 * Handlers for the type of events are created internally on the fly. It's not
 * required to specify in advance the full list of accepted types.

 * Moreover, whenever an event is published, an emitter provides the listeners
 * with a reference to itself along with a const reference to the event.
 * Therefore listeners have an handy way to work with it without incurring in
 * the need of capturing a reference to the emitter.
 *
 * @tparam Derived Actual type of emitter that extends the class template.
 */
template<typename Derived>
class Emitter {
    struct BaseHandler {
        virtual ~BaseHandler() = default;
        virtual bool empty() const noexcept = 0;
        virtual void clear() noexcept = 0;
    };

    template<typename Event>
    struct Handler final: BaseHandler {
        using listener_type = std::function<void(const Event &, Derived &)>;
        using element_type = std::pair<bool, listener_type>;
        using container_type = std::list<element_type>;
        using connection_type = typename container_type::iterator;

        bool empty() const noexcept override {
            auto pred = [](auto &&element){ return element.first; };

            return std::all_of(onceL.cbegin(), onceL.cend(), pred) &&
                    std::all_of(onL.cbegin(), onL.cend(), pred);
        }

        void clear() noexcept override {
            if(publishing) {
                auto func = [](auto &&element){ element.first = true; };
                std::for_each(onceL.begin(), onceL.end(), func);
                std::for_each(onL.begin(), onL.end(), func);
            } else {
                onceL.clear();
                onL.clear();
            }
        }

        inline connection_type once(listener_type listener) {
            return onceL.emplace(onceL.cend(), false, std::move(listener));
        }

        inline connection_type on(listener_type listener) {
            return onL.emplace(onL.cend(), false, std::move(listener));
        }

        void erase(connection_type conn) noexcept {
            conn->first = true;

            if(!publishing) {
                auto pred = [](auto &&element){ return element.first; };
                onceL.remove_if(pred);
                onL.remove_if(pred);
            }
        }

        void publish(const Event &event, Derived &ref) {
            container_type currentL;
            onceL.swap(currentL);

            auto func = [&event, &ref](auto &&element) {
                return element.first ? void() : element.second(event, ref);
            };

            publishing = true;

            std::for_each(onL.rbegin(), onL.rend(), func);
            std::for_each(currentL.rbegin(), currentL.rend(), func);

            publishing = false;

            onL.remove_if([](auto &&element){ return element.first; });
        }

    private:
        bool publishing{false};
        container_type onceL{};
        container_type onL{};
    };

    static std::size_t next() noexcept {
        static std::size_t counter = 0;
        return counter++;
    }

    template<typename>
    static std::size_t type() noexcept {
        static std::size_t value = next();
        return value;
    }

    template<typename Event>
    Handler<Event> & handler() noexcept {
        const std::size_t family = type<Event>();

        if(!(family < handlers.size())) {
            handlers.resize(family+1);
        }

        if(!handlers[family]) {
            handlers[family] = std::make_unique<Handler<Event>>();
        }

        return static_cast<Handler<Event> &>(*handlers[family]);
    }

public:
    /** @brief Type of listeners accepted for the given type of event. */
    template<typename Event>
    using Listener = typename Handler<Event>::listener_type;

    /**
     * @brief Generic connection type for events.
     *
     * Type of the connection object returned by the event emitter whenever a
     * listener for the given type is registered.

     * It can be used to break connections still in use.
     *
     * @tparam Event Type of event for which the connection is created.
     */
    template<typename Event>
    struct Connection final: private Handler<Event>::connection_type {
        /** @brief Event emitters are friend classes of connections. */
        friend class Emitter;

        /*! @brief Default constructor. */
        Connection() noexcept = default;

        /**
         * @brief Creates a connection that wraps its underlying instance.
         * @param conn A connection object to wrap.
         */
        Connection(typename Handler<Event>::connection_type conn)
            : Handler<Event>::connection_type{std::move(conn)}
        {}

        /*! @brief Default copy constructor. */
        Connection(const Connection &) = default;
        /*! @brief Default move constructor. */
        Connection(Connection &&) = default;

        /**
         * @brief Default copy assignament operator.
         * @return This connection.
         */
        Connection & operator=(const Connection &) = default;

        /**
         * @brief Default move assignment operator.
         * @return This connection.
         */
        Connection & operator=(Connection &&) = default;
    };

    /*! @brief Default constructor. */
    Emitter() noexcept = default;

    /*! @brief Default destructor. */
    virtual ~Emitter() noexcept {
        static_assert(std::is_base_of<Emitter<Derived>, Derived>::value, "!");
    }

    /*! @brief Copying an emitter isn't allowed. */
    Emitter(const Emitter &) = delete;
    /*! @brief Default move constructor. */
    Emitter(Emitter &&) = default;

    /*! @brief Copying an emitter isn't allowed. @return This emitter. */
    Emitter & operator=(const Emitter &) = delete;
    /*! @brief Default move assignament operator. @return This emitter. */
    Emitter & operator=(Emitter &&) = default;

    /**
     * @brief Emits the given event.
     *
     * All the listeners registered for the specific event type are invoked with
     * the given event. The event type must either have a proper constructor for
     * the arguments provided or be an aggregate type.
     *
     * @tparam Event Type of event to publish.
     * @tparam Args Types of arguments to use to construct the event.
     * @param args Parameters to use to initialize the event.
     */
    template<typename Event, typename... Args>
    void publish(Args&&... args) {
        handler<Event>().publish({ std::forward<Args>(args)... }, *static_cast<Derived *>(this));
    }

    /**
     * @brief Registers a long-lived listener with the event emitter.
     *
     * This method can be used to register a listener designed to be invoked
     * more than once for the given event type.

     * The connection returned by the method can be freely discarded. It's meant
     * to be used later to disconnect the listener if required.
     *
     * The listener is as a callable object that can be moved and the type of
     * which is `void(const Event &, Derived &)`.
     *
     * @note
     * Whenever an event is emitted, the emitter provides the listener with a
     * reference to the derived class. Listeners don't have to capture those
     * instances for later uses.
     *
     * @tparam Event Type of event to which to connect the listener.
     * @param listener The listener to register.
     * @return Connection object that can be used to disconnect the listener.
     */
    template<typename Event>
    Connection<Event> on(Listener<Event> listener) {
        return handler<Event>().on(std::move(listener));
    }

    /**
     * @brief Registers a short-lived listener with the event emitter.
     *
     * This method can be used to register a listener designed to be invoked
     * only once for the given event type.

     * The connection returned by the method can be freely discarded. It's meant
     * to be used later to disconnect the listener if required.
     *
     * The listener is as a callable object that can be moved and the type of
     * which is `void(const Event &, Derived &)`.
     *
     * @note
     * Whenever an event is emitted, the emitter provides the listener with a
     * reference to the derived class. Listeners don't have to capture those
     * instances for later uses.
     *
     * @tparam Event Type of event to which to connect the listener.
     * @param listener The listener to register.
     * @return Connection object that can be used to disconnect the listener.
     */
    template<typename Event>
    Connection<Event> once(Listener<Event> listener) {
        return handler<Event>().once(std::move(listener));
    }

    /**
     * @brief Disconnects a listener from the event emitter.
     *
     * Do not use twice the same connection to disconnect a listener, it results
     * in undefined behavior. Once used, discard the connection object.
     *
     * @tparam Event Type of event of the connection.
     * @param conn A valid connection.
     */
    template<typename Event>
    void erase(Connection<Event> conn) noexcept {
        handler<Event>().erase(std::move(conn));
    }

    /**
     * @brief Disconnects all the listeners for the given event type.
     *
     * All the connections previously returned for the given event are
     * invalidated. Using them results in undefined behavior.
     *
     * @tparam Event Type of event to reset.
     */
    template<typename Event>
    void clear() noexcept {
        handler<Event>().clear();
    }

    /**
     * @brief Disconnects all the listeners.
     *
     * All the connections previously returned are invalidated. Using them
     * results in undefined behavior.
     */
    void clear() noexcept {
        std::for_each(handlers.begin(), handlers.end(),
                      [](auto &&handler){ if(handler) { handler->clear(); } });
    }

    /**
     * @brief Checks if there are listeners registered for the specific event.
     * @tparam Event Type of event to test.
     * @return True if there are no listeners registered, false otherwise.
     */
    template<typename Event>
    bool empty() const noexcept {
        const std::size_t family = type<Event>();

        return (!(family < handlers.size()) ||
                !handlers[family] ||
                static_cast<Handler<Event> &>(*handlers[family]).empty());
    }

    /**
     * @brief Checks if there are listeners registered with the event emitter.
     * @return True if there are no listeners registered, false otherwise.
     */
    bool empty() const noexcept {
        return std::all_of(handlers.cbegin(), handlers.cend(),
                           [](auto &&handler){ return !handler || handler->empty(); });
    }

private:
    std::vector<std::unique_ptr<BaseHandler>> handlers{};
};

}

#endif // ENTT_SIGNAL_EMITTER_HPP
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "DirectoryNames.h"

/* implementation system headers */
#ifndef _WIN32
#  include <stdlib.h>
#  include <unistd.h>
#  include <sys/types.h>
#  include <pwd.h>
#else   // _WIN32
#  include <sys/types.h>
#  include <sys/stat.h>
#  include <stdio.h>
#  include <direct.h>
#  include <shlobj.h>
#endif  // _WIN32
#if defined(__APPLE__)
#  include <CoreServices/CoreServices.h>
#endif

// NOTE: terminate all strings with either '/' or '\\'

std::string		getConfigDirName()
{
#if defined(_WIN32)
  std::string name("C:");
  char dir[MAX_PATH];
  ITEMIDLIST* idl;
  if (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_PERSONAL, &idl))) {
    if (SHGetPathFromIDList(idl, dir)) {
      struct stat statbuf;
      if (stat(dir, &statbuf) == 0 && (statbuf.st_mode & _S_IFDIR) != 0)
	name = dir;
    }

    IMalloc* shalloc;
    if (SUCCEEDED(SHGetMalloc(&shalloc))) {
      shalloc->Free(idl);
      shalloc->Release();
    }
  }

  // yes your suposed to have the "my" in front of it. I know it's silly, but it's the MS way.
  name += "\\My BZFlag Files\\";

  return name;

#elif defined(__APPLE__)
  std::string name;
  ::FSRef libraryFolder;
  ::OSErr err;
  err = ::FSFindFolder(::kUserDomain, ::kApplicationSupportFolderType, true, &libraryFolder);
  if(err == ::noErr) {
    char buff[1024];
    err = ::FSRefMakePath(&libraryFolder, (UInt8*)buff, sizeof(buff));
    if(err == ::noErr) {
      std::strcat(buff, "/BZFlag/");
      name = buff;
    }
  }
  return name;
#else
  std::string name;
  struct passwd *pwent = getpwuid(getuid());
  if (pwent && pwent->pw_dir) {
    name += std::string(pwent->pw_dir);
    name += "/";
  }
  name += ".bzf/";

  return name;
#endif
}

extern std::string		getCacheDirName()
{
  std::string name = getConfigDirName();
  name += "cache";
#if !defined (_WIN32) && !defined (__APPLE__)
  // add in hostname on UNIX
  if (getenv("HOST")) {
    name += ".";
    name += getenv("HOST");
    name += "/";
  }
#endif
  return name;
}

extern std::string		getRecordDirName()
{
  std::string name = getConfigDirName();
  name += "captured";
  return name;
}

extern std::string		getScreenShotDirName()
{
  std::string name = getConfigDirName();
  name += "screenshots";
  return name;
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>missed the original "captured" to "recordings" rename<commit_after>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "DirectoryNames.h"

/* implementation system headers */
#ifndef _WIN32
#  include <stdlib.h>
#  include <unistd.h>
#  include <sys/types.h>
#  include <pwd.h>
#else   // _WIN32
#  include <sys/types.h>
#  include <sys/stat.h>
#  include <stdio.h>
#  include <direct.h>
#  include <shlobj.h>
#endif  // _WIN32
#if defined(__APPLE__)
#  include <CoreServices/CoreServices.h>
#endif

// NOTE: terminate all strings with either '/' or '\\'

std::string		getConfigDirName()
{
#if defined(_WIN32)
  std::string name("C:");
  char dir[MAX_PATH];
  ITEMIDLIST* idl;
  if (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_PERSONAL, &idl))) {
    if (SHGetPathFromIDList(idl, dir)) {
      struct stat statbuf;
      if (stat(dir, &statbuf) == 0 && (statbuf.st_mode & _S_IFDIR) != 0)
	name = dir;
    }

    IMalloc* shalloc;
    if (SUCCEEDED(SHGetMalloc(&shalloc))) {
      shalloc->Free(idl);
      shalloc->Release();
    }
  }

  // yes your suposed to have the "my" in front of it. I know it's silly, but it's the MS way.
  name += "\\My BZFlag Files\\";

  return name;

#elif defined(__APPLE__)
  std::string name;
  ::FSRef libraryFolder;
  ::OSErr err;
  err = ::FSFindFolder(::kUserDomain, ::kApplicationSupportFolderType, true, &libraryFolder);
  if(err == ::noErr) {
    char buff[1024];
    err = ::FSRefMakePath(&libraryFolder, (UInt8*)buff, sizeof(buff));
    if(err == ::noErr) {
      std::strcat(buff, "/BZFlag/");
      name = buff;
    }
  }
  return name;
#else
  std::string name;
  struct passwd *pwent = getpwuid(getuid());
  if (pwent && pwent->pw_dir) {
    name += std::string(pwent->pw_dir);
    name += "/";
  }
  name += ".bzf/";

  return name;
#endif
}

extern std::string		getCacheDirName()
{
  std::string name = getConfigDirName();
  name += "cache";
#if !defined (_WIN32) && !defined (__APPLE__)
  // add in hostname on UNIX
  if (getenv("HOST")) {
    name += ".";
    name += getenv("HOST");
    name += "/";
  }
#endif
  return name;
}

extern std::string		getRecordDirName()
{
  std::string name = getConfigDirName();
  name += "recordings";
  return name;
}

extern std::string		getScreenShotDirName()
{
  std::string name = getConfigDirName();
  name += "screenshots";
  return name;
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <actionlib/client/simple_action_client.h>
#include <geometry_msgs/PoseStamped.h>
#include <boost/thread/mutex.hpp>
#include "std_msgs/Int32.h"

// The global planner uses the actionlib to do the following:
// Start in safe mode
//
// In safe state
//  cancel all goals and no april tag callbacks
//  if start command:
//   Transition to search state
//  if goto state command:
//   Transition to given state
//
// In search state
//  travel to poses A,B,etc... on known map
//  If a trashcan is found at any time:
//   Transition to approach_trash state
//  else if hit final search state:
//   Transition to end state
//
// In approach_trash state
//  travel to infront of trashcan
//  if reach trash pose:
//   transition to dump trash state
//
// In dump trash state
//  travel to dump trash position
//  if reach dump trash position:
//   transition to end state
//
// In end state
//  travel to final pose
//  if reaach final pose:
//   transition to safe state

// Convenience Typedef
typedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient;

boost::shared_ptr<MoveBaseClient> action_client_ptr;

// April tag subscriber
ros::Subscriber sub;

// State Machine for Fall Demo #2
enum State { SAFE, SEARCH_A, SEARCH_B, SEARCH_C, SEARCH_D, SEARCH_E, APPROACH_TRASH, DUMP_TRASH, END};
State currState = SAFE;

// Search poses
struct search_pose
{
  // x, y, rot
  double x, y, rz, rw;
};
search_pose search_poses[] = { {0.5, -1, 0, 1},
                               {2, 1, 1, 0},
                               {-1.8, .9, -.73, .68},
                               {-2, -1, 0, 1},
                               {0, -1, 0.67, 0.72},
                               {0, 0, 0, 1}};

// Sets given goal to given x,y and rotation quat rz,rw
void setGoalPoseRaw(double x, double y, double rz, double rw,
                 move_base_msgs::MoveBaseGoal &goal) {
  goal.target_pose.pose.position.x = x;
  goal.target_pose.pose.position.y = y;
  goal.target_pose.pose.orientation.z = rz;
  goal.target_pose.pose.orientation.w = rw;
}
void setGoalPose(const search_pose &s,
                 move_base_msgs::MoveBaseGoal &goal) {
  setGoalPoseRaw(s.x, s.y, s.rz, s.rw, goal);
}

// Given a trashcan as a PoseStamped messge, returns the goal pose in front of it
void getGoalPoseFromTrashcan(const geometry_msgs::PoseStamped::ConstPtr& msg,
                             move_base_msgs::MoveBaseGoal &goal) {
  setGoalPoseRaw(msg->pose.position.x - 0.5*cos(msg->pose.orientation.z),
                 msg->pose.position.y - 0.5*sin(msg->pose.orientation.z),
                 msg->pose.orientation.z,
                 msg->pose.orientation.w,
                 goal);
  goal.target_pose.header.frame_id = "map";
  goal.target_pose.header.stamp = ros::Time::now();
}

// Callback for new april tags
void trashcanTagSearcherCallback(const geometry_msgs::PoseStamped::ConstPtr& msg) {
  ROS_INFO("April Tag Callback!");

  ROS_INFO("Header : %s", msg->header.frame_id.c_str());

  // If april tag is id 6 (trashcan)
  if (msg->header.frame_id.c_str()[0] == '6') {
    ROS_INFO("Header Match!");
    geometry_msgs::PoseStamped goal_pose;

    move_base_msgs::MoveBaseGoal goal;

    if (currState == APPROACH_TRASH) {
      // Set goal position to in front of april tag
      getGoalPoseFromTrashcan(msg, goal);

      // http://mirror.umd.edu/roswiki/doc/diamondback/api/actionlib/html/classactionlib_1_1simple__action__client_1_1SimpleActionClient.html#a6bdebdd9f43a470ecd361d2c8b743188
      // If a previous goal is already active when this is called.
      // We simply forget about that goal and start tracking the new goal.
      // No cancel requests are made.
      action_client_ptr->sendGoal(goal);
    }
  }
}

void transition(State state, ros::NodeHandle &n) {
  if (currState != state) {
    currState = state;
    ROS_INFO("-- STATE TRANSITION %d --", currState);

    int chosen_search_pose = -1;
    switch(currState) {
      case SAFE:
      sub.shutdown();
      break;

      case SEARCH_A:
      chosen_search_pose = 0;
      ROS_INFO("SENDING POSE SEARCH_A to /move_base/goal");
      break;

      case SEARCH_B:
      chosen_search_pose = 1;
      ROS_INFO("SENDING POSE SEARCH_B to /move_base/goal");
      break;

      case SEARCH_C:
      chosen_search_pose = 2;
      ROS_INFO("SENDING POSE SEARCH_C to /move_base/goal");
      break;

      case SEARCH_D:
      chosen_search_pose = 3;
      ROS_INFO("SENDING POSE SEARCH_D to /move_base/goal");
      break;

      case SEARCH_E:
      chosen_search_pose = 4;
      ROS_INFO("SENDING POSE SEARCH_E to /move_base/goal");
      break;

      case APPROACH_TRASH:
      break;

      case DUMP_TRASH:
      sub.shutdown();
      break;

      case END:
      sub.shutdown();
      break;
    }

    // If searching
    if (chosen_search_pose >= 0) {
      // Subscribe to trashcan searcher
      sub = n.subscribe("apriltags", 1000, trashcanTagSearcherCallback);

      // Set goal to search pose
      move_base_msgs::MoveBaseGoal goal;
      setGoalPose(search_poses[chosen_search_pose], goal);
      goal.target_pose.header.frame_id = "map";
      goal.target_pose.header.stamp = ros::Time::now();

      // Send goal to action client
      action_client_ptr->sendGoal(goal);
      ROS_INFO("GOAL SENT");
    }
  }
}

int command_value = 0;
void commandCallback(const std_msgs::Int32::ConstPtr& msg) {
  command_value = msg->data;
  ROS_INFO("Received command %d", command_value);
}

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

  // ROS Node Initialization
  ros::init(argc, argv, "global_planner");
  ros::NodeHandle n;

  // Subscribe to command node
  ros::Subscriber cmd_sub = n.subscribe("cmd_state", 10, commandCallback);

  action_client_ptr.reset( new MoveBaseClient("move_base", false) );

  // Create Rate Object for sleeping
  ros::Rate r(1);

  // Wait for the action server to come up
  // while(ros::ok() && !action_client_ptr->waitForServer(ros::Duration(1.0))){
  //   ROS_INFO("Waiting for the move_base action server to come up");
  // }

  ROS_INFO("Starting global planner.");

  while(ros::ok()){
    if (command_value == 0) {
      transition(SAFE, n);
    }
    // State machine command override from safe to chosen state
    switch(currState) {
      case SAFE:
      switch (command_value) {
        case 1:
        transition(SEARCH_A, n);
        break;
        case 2:
        transition(SEARCH_B, n);
        break;
        case 3:
        transition(SEARCH_C, n);
        break;
        case 4:
        transition(SEARCH_D, n);
        break;
        case 5:
        transition(SEARCH_E, n);
        break;
        case 6:
        transition(APPROACH_TRASH, n);
        break;
        case 7:
        transition(DUMP_TRASH, n);
        break;
        case 8:
        transition(END, n);
        break;
      }
      break;

      case SEARCH_A:
      ROS_INFO("Status : %s", action_client_ptr->getState().toString().c_str());
      if (action_client_ptr->getState() == actionlib::SimpleClientGoalState::SUCCEEDED ||
          command_value == 2) {
        transition(SEARCH_B, n);
      }
      break;

      case SEARCH_B:
      ROS_INFO("Status : %s", action_client_ptr->getState().toString().c_str());
      if (action_client_ptr->getState() == actionlib::SimpleClientGoalState::SUCCEEDED ||
          command_value == 3) {
        transition(SEARCH_C, n);
      }
      break;

      case SEARCH_C:
      ROS_INFO("Status : %s", action_client_ptr->getState().toString().c_str());
      if (action_client_ptr->getState() == actionlib::SimpleClientGoalState::SUCCEEDED ||
          command_value == 4) {
        transition(SEARCH_D, n);
      }
      break;

      case SEARCH_D:
      ROS_INFO("Status : %s", action_client_ptr->getState().toString().c_str());
      if (action_client_ptr->getState() == actionlib::SimpleClientGoalState::SUCCEEDED ||
          command_value == 5) {
        transition(SEARCH_E, n);
      }
      break;

      case SEARCH_E:
      ROS_INFO("Status : %s", action_client_ptr->getState().toString().c_str());
      if (action_client_ptr->getState() == actionlib::SimpleClientGoalState::SUCCEEDED ||
          command_value == 6) {
        transition(END, n);
      }
      break;

      case APPROACH_TRASH:
      if (action_client_ptr->getState() == actionlib::SimpleClientGoalState::SUCCEEDED ||
          command_value == 7) {
        transition(DUMP_TRASH, n);
      }
      break;

      case DUMP_TRASH:
      // Placeholder transition for now
      transition(END, n);
      break;

      case END:
      break;
    }

    // Update callbacks after the fact, for next loop iteration.
    ros::spinOnce();

    r.sleep();

  }
}<commit_msg>added wait, not working yet<commit_after>#include <ros/ros.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <actionlib/client/simple_action_client.h>
#include <geometry_msgs/PoseStamped.h>
#include <boost/thread/mutex.hpp>
#include "std_msgs/Int32.h"

// The global planner uses the actionlib to do the following:
// Start in safe mode
//
// In safe state
//  cancel all goals and no april tag callbacks
//  if start command:
//   Transition to search state
//  if goto state command:
//   Transition to given state
//
// In search state
//  travel to poses A,B,etc... on known map
//  If a trashcan is found at any time:
//   Transition to approach_trash state
//  else if hit final search state:
//   Transition to end state
//
// In approach_trash state
//  travel to infront of trashcan
//  if reach trash pose:
//   transition to dump trash state
//
// In dump trash state
//  travel to dump trash position
//  if reach dump trash position:
//   transition to end state
//
// In end state
//  travel to final pose
//  if reaach final pose:
//   transition to safe state

// Convenience Typedef
typedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient;

boost::shared_ptr<MoveBaseClient> action_client_ptr;

// April tag subscriber
ros::Subscriber sub;

// State Machine for Fall Demo #2
enum State { SAFE, SEARCH_A, SEARCH_B, SEARCH_C, SEARCH_D, SEARCH_E, APPROACH_TRASH, DUMP_TRASH, END};
State currState = SAFE;

// Search poses
struct search_pose
{
  // x, y, rot
  double x, y, rz, rw;
};
search_pose search_poses[] = { {0.5, -1, 0, 1},
                               {2, 1, 1, 0},
                               {-1.8, .9, -.73, .68},
                               {-2, -1, 0, 1},
                               {0, -1, 0.67, 0.72},
                               {0, 0, 0, 1}};

// Sets given goal to given x,y and rotation quat rz,rw
void setGoalPoseRaw(double x, double y, double rz, double rw,
                 move_base_msgs::MoveBaseGoal &goal) {
  goal.target_pose.pose.position.x = x;
  goal.target_pose.pose.position.y = y;
  goal.target_pose.pose.orientation.z = rz;
  goal.target_pose.pose.orientation.w = rw;
}
void setGoalPose(const search_pose &s,
                 move_base_msgs::MoveBaseGoal &goal) {
  setGoalPoseRaw(s.x, s.y, s.rz, s.rw, goal);
}

// Given a trashcan as a PoseStamped messge, returns the goal pose in front of it
void getGoalPoseFromTrashcan(const geometry_msgs::PoseStamped::ConstPtr& msg,
                             move_base_msgs::MoveBaseGoal &goal) {
  setGoalPoseRaw(msg->pose.position.x - 0.5*cos(msg->pose.orientation.z),
                 msg->pose.position.y - 0.5*sin(msg->pose.orientation.z),
                 msg->pose.orientation.z,
                 msg->pose.orientation.w,
                 goal);
  goal.target_pose.header.frame_id = "map";
  goal.target_pose.header.stamp = ros::Time::now();
}

// Callback for new april tags
void trashcanTagSearcherCallback(const geometry_msgs::PoseStamped::ConstPtr& msg) {
  ROS_INFO("April Tag Callback!");

  ROS_INFO("Header : %s", msg->header.frame_id.c_str());

  // If april tag is id 6 (trashcan)
  if (msg->header.frame_id.c_str()[0] == '6') {
    ROS_INFO("Header Match!");
    geometry_msgs::PoseStamped goal_pose;

    move_base_msgs::MoveBaseGoal goal;

    if (currState == APPROACH_TRASH) {
      // Set goal position to in front of april tag
      getGoalPoseFromTrashcan(msg, goal);

      // http://mirror.umd.edu/roswiki/doc/diamondback/api/actionlib/html/classactionlib_1_1simple__action__client_1_1SimpleActionClient.html#a6bdebdd9f43a470ecd361d2c8b743188
      // If a previous goal is already active when this is called.
      // We simply forget about that goal and start tracking the new goal.
      // No cancel requests are made.
      action_client_ptr->sendGoal(goal);
    }
  }
}

void transition(State state, ros::NodeHandle &n) {
  if (currState != state) {
    currState = state;
    ROS_INFO("-- STATE TRANSITION %d --", currState);

    int chosen_search_pose = -1;
    switch(currState) {
      case SAFE:
      sub.shutdown();
      break;

      case SEARCH_A:
      chosen_search_pose = 0;
      ROS_INFO("SENDING POSE SEARCH_A to /move_base/goal");
      break;

      case SEARCH_B:
      chosen_search_pose = 1;
      ROS_INFO("SENDING POSE SEARCH_B to /move_base/goal");
      break;

      case SEARCH_C:
      chosen_search_pose = 2;
      ROS_INFO("SENDING POSE SEARCH_C to /move_base/goal");
      break;

      case SEARCH_D:
      chosen_search_pose = 3;
      ROS_INFO("SENDING POSE SEARCH_D to /move_base/goal");
      break;

      case SEARCH_E:
      chosen_search_pose = 4;
      ROS_INFO("SENDING POSE SEARCH_E to /move_base/goal");
      break;

      case APPROACH_TRASH:
      break;

      case DUMP_TRASH:
      sub.shutdown();
      break;

      case END:
      sub.shutdown();
      break;
    }

    // If searching
    if (chosen_search_pose >= 0) {
      // Subscribe to trashcan searcher
      sub = n.subscribe("apriltags", 1000, trashcanTagSearcherCallback);

      // Set goal to search pose
      move_base_msgs::MoveBaseGoal goal;
      setGoalPose(search_poses[chosen_search_pose], goal);
      goal.target_pose.header.frame_id = "map";
      goal.target_pose.header.stamp = ros::Time::now();

      // Send goal to action client
      action_client_ptr->sendGoal(goal);
      ROS_INFO("GOAL SENT");
    }
  }
}

int command_value = 0;
void commandCallback(const std_msgs::Int32::ConstPtr& msg) {
  command_value = msg->data;
  ROS_INFO("Received command %d", command_value);
}

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

  // ROS Node Initialization
  ros::init(argc, argv, "global_planner");
  ros::NodeHandle n;

  // Subscribe to command node
  ros::Subscriber cmd_sub = n.subscribe("cmd_state", 10, commandCallback);

  action_client_ptr.reset( new MoveBaseClient("move_base", false) );

  // Create Rate Object for sleeping
  ros::Rate r(1);

  // Wait for the action server to come up
  while(ros::ok() && !action_client_ptr->waitForServer(ros::Duration(1.0))){
    ROS_INFO("Waiting for the move_base action server to come up");
  }

  ROS_INFO("Starting global planner.");

  while(ros::ok()){
    if (command_value == 0) {
      transition(SAFE, n);
    }
    // State machine command override from safe to chosen state
    switch(currState) {
      case SAFE:
      switch (command_value) {
        case 1:
        transition(SEARCH_A, n);
        break;
        case 2:
        transition(SEARCH_B, n);
        break;
        case 3:
        transition(SEARCH_C, n);
        break;
        case 4:
        transition(SEARCH_D, n);
        break;
        case 5:
        transition(SEARCH_E, n);
        break;
        case 6:
        transition(APPROACH_TRASH, n);
        break;
        case 7:
        transition(DUMP_TRASH, n);
        break;
        case 8:
        transition(END, n);
        break;
      }
      break;

      case SEARCH_A:
      ROS_INFO("Status : %s", action_client_ptr->getState().toString().c_str());
      if (action_client_ptr->getState() == actionlib::SimpleClientGoalState::SUCCEEDED ||
          command_value == 2) {
        transition(SEARCH_B, n);
      }
      break;

      case SEARCH_B:
      ROS_INFO("Status : %s", action_client_ptr->getState().toString().c_str());
      if (action_client_ptr->getState() == actionlib::SimpleClientGoalState::SUCCEEDED ||
          command_value == 3) {
        transition(SEARCH_C, n);
      }
      break;

      case SEARCH_C:
      ROS_INFO("Status : %s", action_client_ptr->getState().toString().c_str());
      if (action_client_ptr->getState() == actionlib::SimpleClientGoalState::SUCCEEDED ||
          command_value == 4) {
        transition(SEARCH_D, n);
      }
      break;

      case SEARCH_D:
      ROS_INFO("Status : %s", action_client_ptr->getState().toString().c_str());
      if (action_client_ptr->getState() == actionlib::SimpleClientGoalState::SUCCEEDED ||
          command_value == 5) {
        transition(SEARCH_E, n);
      }
      break;

      case SEARCH_E:
      ROS_INFO("Status : %s", action_client_ptr->getState().toString().c_str());
      if (action_client_ptr->getState() == actionlib::SimpleClientGoalState::SUCCEEDED ||
          command_value == 6) {
        transition(END, n);
      }
      break;

      case APPROACH_TRASH:
      if (action_client_ptr->getState() == actionlib::SimpleClientGoalState::SUCCEEDED ||
          command_value == 7) {
        transition(DUMP_TRASH, n);
      }
      break;

      case DUMP_TRASH:
      // Placeholder transition for now
      transition(END, n);
      break;

      case END:
      break;
    }

    // Update callbacks after the fact, for next loop iteration.
    ros::spinOnce();

    r.sleep();

  }
}<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * Copyright (C) 2002-2017 Németh László
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Hunspell is based on MySpell which is Copyright (C) 2002 Kevin Hendricks.
 *
 * Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,
 * Gianluca Turconi, Simon Brouwer, Noll János, Bíró Árpád,
 * Goldman Eleonóra, Sarlós Tamás, Bencsáth Boldizsár, Halácsy Péter,
 * Dvornik László, Gefferth András, Nagy Viktor, Varga Dániel, Chris Halls,
 * Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitkänen
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
/*
 * Copyright 2002 Kevin B. Hendricks, Stratford, Ontario, Canada
 * And Contributors.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. All modifications to the source code must be clearly marked as
 *    such.  Binary redistributions based on modified source code
 *    must be clearly marked as modified versions in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY KEVIN B. HENDRICKS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * KEVIN B. HENDRICKS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef SUGGESTMGR_HXX_
#define SUGGESTMGR_HXX_

#define MAX_ROOTS 100
#define MAX_WORDS 100
#define MAX_GUESS 200
#define MAXNGRAMSUGS 4
#define MAXPHONSUGS 2
#define MAXCOMPOUNDSUGS 3

// timelimit: max ~1/4 sec (process time on Linux) for a time consuming function
#define TIMELIMIT (CLOCKS_PER_SEC >> 2)
#define MINTIMER 100
#define MAXPLUSTIMER 100

#define NGRAM_LONGER_WORSE (1 << 0)
#define NGRAM_ANY_MISMATCH (1 << 1)
#define NGRAM_LOWERING (1 << 2)
#define NGRAM_WEIGHTED (1 << 3)

#include "atypes.hxx"
#include "affixmgr.hxx"
#include "hashmgr.hxx"
#include "langnum.hxx"
#include <time.h>

enum { LCS_UP, LCS_LEFT, LCS_UPLEFT };

class SuggestMgr {
 private:
  SuggestMgr(const SuggestMgr&);
  SuggestMgr& operator=(const SuggestMgr&);

 private:
  char* ckey;
  size_t ckeyl;
  std::vector<w_char> ckey_utf;

  char* ctry;
  size_t ctryl;
  std::vector<w_char> ctry_utf;

  AffixMgr* pAMgr;
  unsigned int maxSug;
  struct cs_info* csconv;
  int utf8;
  int langnum;
  int nosplitsugs;
  int maxngramsugs;
  int maxcpdsugs;
  int complexprefixes;

 public:
  SuggestMgr(const char* tryme, unsigned int maxn, AffixMgr* aptr);
  ~SuggestMgr();

  void suggest(std::vector<std::string>& slst, const char* word, int* onlycmpdsug);
  void ngsuggest(std::vector<std::string>& slst, const char* word, const std::vector<HashMgr*>& rHMgr);

  std::string suggest_morph(const std::string& word);
  std::string suggest_gen(const std::vector<std::string>& pl, const std::string& pattern);

 private:
  void testsug(std::vector<std::string>& wlst,
               const std::string& candidate,
               int cpdsuggest,
               int* timer,
               clock_t* timelimit);
  int checkword(const std::string& word, int, int*, clock_t*);
  int check_forbidden(const char*, int);

  void capchars(std::vector<std::string>&, const char*, int);
  int replchars(std::vector<std::string>&, const char*, int);
  int doubletwochars(std::vector<std::string>&, const char*, int);
  int forgotchar(std::vector<std::string>&, const char*, int);
  int swapchar(std::vector<std::string>&, const char*, int);
  int longswapchar(std::vector<std::string>&, const char*, int);
  int movechar(std::vector<std::string>&, const char*, int);
  int extrachar(std::vector<std::string>&, const char*, int);
  int badcharkey(std::vector<std::string>&, const char*, int);
  int badchar(std::vector<std::string>&, const char*, int);
  int twowords(std::vector<std::string>&, const char*, int);

  void capchars_utf(std::vector<std::string>&, const w_char*, int wl, int);
  int doubletwochars_utf(std::vector<std::string>&, const w_char*, int wl, int);
  int forgotchar_utf(std::vector<std::string>&, const w_char*, int wl, int);
  int extrachar_utf(std::vector<std::string>&, const w_char*, int wl, int);
  int badcharkey_utf(std::vector<std::string>&, const w_char*, int wl, int);
  int badchar_utf(std::vector<std::string>&, const w_char*, int wl, int);
  int swapchar_utf(std::vector<std::string>&, const w_char*, int wl, int);
  int longswapchar_utf(std::vector<std::string>&, const w_char*, int, int);
  int movechar_utf(std::vector<std::string>&, const w_char*, int, int);

  int mapchars(std::vector<std::string>&, const char*, int);
  int map_related(const char*,
                  std::string&,
                  int,
                  std::vector<std::string>& wlst,
                  int,
                  const std::vector<mapentry>&,
                  int*,
                  clock_t*);
  int ngram(int n, const std::vector<w_char>& su1,
            const std::vector<w_char>& su2, int opt);
  int ngram(int n, const std::string& s1, const std::string& s2, int opt);
  int mystrlen(const char* word);
  int leftcommonsubstring(const std::vector<w_char>& su1,
                          const std::vector<w_char>& su2);
  int leftcommonsubstring(const char* s1, const char* s2);
  int commoncharacterpositions(const char* s1, const char* s2, int* is_swap);
  void bubblesort(char** rwd, char** rwd2, int* rsc, int n);
  void lcs(const char* s, const char* s2, int* l1, int* l2, char** result);
  int lcslen(const char* s, const char* s2);
  int lcslen(const std::string& s, const std::string& s2);
  std::string suggest_hentry_gen(hentry* rv, const char* pattern);
};

#endif
<commit_msg>Fix assumption of clock_t being integral<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * Copyright (C) 2002-2017 Németh László
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Hunspell is based on MySpell which is Copyright (C) 2002 Kevin Hendricks.
 *
 * Contributor(s): David Einstein, Davide Prina, Giuseppe Modugno,
 * Gianluca Turconi, Simon Brouwer, Noll János, Bíró Árpád,
 * Goldman Eleonóra, Sarlós Tamás, Bencsáth Boldizsár, Halácsy Péter,
 * Dvornik László, Gefferth András, Nagy Viktor, Varga Dániel, Chris Halls,
 * Rene Engelhard, Bram Moolenaar, Dafydd Jones, Harri Pitkänen
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
/*
 * Copyright 2002 Kevin B. Hendricks, Stratford, Ontario, Canada
 * And Contributors.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. All modifications to the source code must be clearly marked as
 *    such.  Binary redistributions based on modified source code
 *    must be clearly marked as modified versions in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY KEVIN B. HENDRICKS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * KEVIN B. HENDRICKS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef SUGGESTMGR_HXX_
#define SUGGESTMGR_HXX_

#define MAX_ROOTS 100
#define MAX_WORDS 100
#define MAX_GUESS 200
#define MAXNGRAMSUGS 4
#define MAXPHONSUGS 2
#define MAXCOMPOUNDSUGS 3

// timelimit: max ~1/4 sec (process time on Linux) for a time consuming function
#define TIMELIMIT (CLOCKS_PER_SEC / 4)
#define MINTIMER 100
#define MAXPLUSTIMER 100

#define NGRAM_LONGER_WORSE (1 << 0)
#define NGRAM_ANY_MISMATCH (1 << 1)
#define NGRAM_LOWERING (1 << 2)
#define NGRAM_WEIGHTED (1 << 3)

#include "atypes.hxx"
#include "affixmgr.hxx"
#include "hashmgr.hxx"
#include "langnum.hxx"
#include <time.h>

enum { LCS_UP, LCS_LEFT, LCS_UPLEFT };

class SuggestMgr {
 private:
  SuggestMgr(const SuggestMgr&);
  SuggestMgr& operator=(const SuggestMgr&);

 private:
  char* ckey;
  size_t ckeyl;
  std::vector<w_char> ckey_utf;

  char* ctry;
  size_t ctryl;
  std::vector<w_char> ctry_utf;

  AffixMgr* pAMgr;
  unsigned int maxSug;
  struct cs_info* csconv;
  int utf8;
  int langnum;
  int nosplitsugs;
  int maxngramsugs;
  int maxcpdsugs;
  int complexprefixes;

 public:
  SuggestMgr(const char* tryme, unsigned int maxn, AffixMgr* aptr);
  ~SuggestMgr();

  void suggest(std::vector<std::string>& slst, const char* word, int* onlycmpdsug);
  void ngsuggest(std::vector<std::string>& slst, const char* word, const std::vector<HashMgr*>& rHMgr);

  std::string suggest_morph(const std::string& word);
  std::string suggest_gen(const std::vector<std::string>& pl, const std::string& pattern);

 private:
  void testsug(std::vector<std::string>& wlst,
               const std::string& candidate,
               int cpdsuggest,
               int* timer,
               clock_t* timelimit);
  int checkword(const std::string& word, int, int*, clock_t*);
  int check_forbidden(const char*, int);

  void capchars(std::vector<std::string>&, const char*, int);
  int replchars(std::vector<std::string>&, const char*, int);
  int doubletwochars(std::vector<std::string>&, const char*, int);
  int forgotchar(std::vector<std::string>&, const char*, int);
  int swapchar(std::vector<std::string>&, const char*, int);
  int longswapchar(std::vector<std::string>&, const char*, int);
  int movechar(std::vector<std::string>&, const char*, int);
  int extrachar(std::vector<std::string>&, const char*, int);
  int badcharkey(std::vector<std::string>&, const char*, int);
  int badchar(std::vector<std::string>&, const char*, int);
  int twowords(std::vector<std::string>&, const char*, int);

  void capchars_utf(std::vector<std::string>&, const w_char*, int wl, int);
  int doubletwochars_utf(std::vector<std::string>&, const w_char*, int wl, int);
  int forgotchar_utf(std::vector<std::string>&, const w_char*, int wl, int);
  int extrachar_utf(std::vector<std::string>&, const w_char*, int wl, int);
  int badcharkey_utf(std::vector<std::string>&, const w_char*, int wl, int);
  int badchar_utf(std::vector<std::string>&, const w_char*, int wl, int);
  int swapchar_utf(std::vector<std::string>&, const w_char*, int wl, int);
  int longswapchar_utf(std::vector<std::string>&, const w_char*, int, int);
  int movechar_utf(std::vector<std::string>&, const w_char*, int, int);

  int mapchars(std::vector<std::string>&, const char*, int);
  int map_related(const char*,
                  std::string&,
                  int,
                  std::vector<std::string>& wlst,
                  int,
                  const std::vector<mapentry>&,
                  int*,
                  clock_t*);
  int ngram(int n, const std::vector<w_char>& su1,
            const std::vector<w_char>& su2, int opt);
  int ngram(int n, const std::string& s1, const std::string& s2, int opt);
  int mystrlen(const char* word);
  int leftcommonsubstring(const std::vector<w_char>& su1,
                          const std::vector<w_char>& su2);
  int leftcommonsubstring(const char* s1, const char* s2);
  int commoncharacterpositions(const char* s1, const char* s2, int* is_swap);
  void bubblesort(char** rwd, char** rwd2, int* rsc, int n);
  void lcs(const char* s, const char* s2, int* l1, int* l2, char** result);
  int lcslen(const char* s, const char* s2);
  int lcslen(const std::string& s, const std::string& s2);
  std::string suggest_hentry_gen(hentry* rv, const char* pattern);
};

#endif
<|endoftext|>