<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: richtextimplcontrol.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 13:00:44 $
 *
 *  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 FORMS_SOURCE_RICHTEXT_RICHTEXTIMPLCONTOL_HXX
#define FORMS_SOURCE_RICHTEXT_RICHTEXTIMPLCONTOL_HXX

#ifndef FORMS_SOURCE_COMPONENT_RTATTRIBUTEHANDLER_HXX
#include "rtattributehandler.hxx"
#endif
#ifndef FORMS_SOURCE_RICHTEXT_RICHTEXTVIEWPORT_HXX
#include "richtextviewport.hxx"
#endif
#ifndef FORMS_SOURCE_RICHTEXT_RICHTEXTENGINE_HXX
#include "richtextengine.hxx"
#endif

#ifndef _SV_SCRBAR_HXX
#include <vcl/scrbar.hxx>
#endif

#ifndef _MyEDITDATA_HXX
#include <svx/editdata.hxx>
#endif

#include <map>

class EditView;
class EditStatus;
class Window;
class SvxScriptSetItem;
//........................................................................
namespace frm
{
//........................................................................

    class ITextAttributeListener;
    class ITextSelectionListener;
    class RichTextViewPort;
    //====================================================================
    //= RichTextControlImpl
    //====================================================================
    class RichTextControlImpl : public IEngineStatusListener
    {
        typedef ::std::map< AttributeId, AttributeState >                           StateCache;
        typedef ::std::map< AttributeId, ::rtl::Reference< IAttributeHandler > >    AttributeHandlerPool;
        typedef ::std::map< AttributeId, ITextAttributeListener* >                  AttributeListenerPool;

        StateCache              m_aLastKnownStates;
        AttributeHandlerPool    m_aAttributeHandlers;
        AttributeListenerPool   m_aAttributeListeners;

        ESelection              m_aLastKnownSelection;

        Control*                m_pAntiImpl;
        RichTextViewPort*       m_pViewport;
        ScrollBar*              m_pHScroll;
        ScrollBar*              m_pVScroll;
        ScrollBarBox*           m_pScrollCorner;
        RichTextEngine*         m_pEngine;
        EditView*               m_pView;
        ITextAttributeListener* m_pTextAttrListener;
        ITextSelectionListener* m_pSelectionListener;
        bool                    m_bHasEverBeenShown;

    public:
        struct GrantAccess { friend class RichTextControl; private: GrantAccess() { } };
        inline EditView*        getView( const GrantAccess& ) const     { return m_pView; }
        inline RichTextEngine*  getEngine( const GrantAccess& ) const   { return m_pEngine; }
        inline Window*          getViewport( const GrantAccess& ) const { return m_pViewport; }

    public:
        RichTextControlImpl( Control* _pAntiImpl, RichTextEngine* _pEngine,
            ITextAttributeListener* _pTextAttrListener, ITextSelectionListener* _pSelectionListener );
        ~RichTextControlImpl();

        /** updates the cache with the state of all attribute values from the given set, notifies
            the listener if the state changed
        */
        void    updateAllAttributes( );

        /** updates the cache with the state of the attribute given by which id, notifies
            the listener if the state changed
        */
        void    updateAttribute( AttributeId _nAttribute );

        /// enables the callback for a particular attribute
        void    enableAttributeNotification( AttributeId _nAttributeId, ITextAttributeListener* _pListener = NULL );

        /// disables the change notifications for a particular attribute
        void    disableAttributeNotification( AttributeId _nAttributeId );

        /// executes a toggle of the given attribute
        bool    executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, AttributeId _nAttribute, const SfxPoolItem* _pArgument, ScriptType _nForScriptType );

        /// retrieves the state of the given attribute from the cache
        AttributeState  getAttributeState( AttributeId _nAttributeId ) const;

        /** normalizes the given item so that the state of script dependent attributes
            is correct considering the current script type

            There are some attributes which are script dependent, e.g. the CharPosture. This means
            that in real, there are 3 attributes for this, one for every possible script type (latin,
            asian, complex). However, to the out world, we behave as if there is only one attribute:
            E.g., if the outter world asks for the state of the "CharPosture" attribute, we return
            the state of either CharPostureLatin, CharPostureAsian, or CharPostureComplex, depending
            on the script type of the current selection. (In real, it may be more complex since
            the current selection may contain more than one script type.)

            This method normalizes a script dependent attribute, so that it's state takes into account
            the currently selected script type.
        */
        void        normalizeScriptDependentAttribute( SvxScriptSetItem& _rScriptSetItem );

        // gets the script type of the selection in our edit view (with fallback)
        ScriptType  getSelectedScriptType() const;

        /** re-arranges the view and the scrollbars
        */
        void    layoutWindow();

        /** to be called when the style of our window changed
        */
        void    notifyStyleChanged();

        /** to be called when the zoom of our window changed
        */
        void    notifyZoomChanged();

        /** to be called when the STATE_CHANGE_INITSHOW event arrives
        */
        void    notifyInitShow();

        // VCL "overrides"
        void    SetBackgroundColor( );
        void    SetBackgroundColor( const Color& _rColor );

        void    SetReadOnly( bool _bReadOnly );
        bool    IsReadOnly() const;

        void    SetHideInactiveSelection( bool _bHide );
        bool    GetHideInactiveSelection() const;

        /// draws the control onto a given output device
        void    Draw( OutputDevice* _pDev, const Point& _rPos, const Size& _rSize, ULONG _nFlags );

        /// handles command events arrived at the anti-impl control
        long    HandleCommand( const CommandEvent& _rEvent );

    private:
        // updates the cache with the state provided by the given attribut handler
        void    implUpdateAttribute( AttributeHandlerPool::const_iterator _pHandler );

        // updates the cache with the given state, and calls listeners (if necessary)
        void    implCheckUpdateCache( AttributeId _nAttribute, const AttributeState& _rState );

        // updates range and position of our scrollbars
        void    updateScrollbars();

        // determines whether automatic (soft) line breaks are ON
        bool    windowHasAutomaticLineBreak();

        /// hides or shows our scrollbars, according to the current WinBits of the window
        void    ensureScrollbars();

        /// ensures that our "automatic line break" setting matches the current WinBits of the window
        void    ensureLineBreakSetting();

        inline  bool    hasVScrollBar( ) const { return m_pVScroll != NULL; }
        inline  bool    hasHScrollBar( ) const { return m_pHScroll != NULL; }

        // IEngineStatusListener overridables
        virtual void EditEngineStatusChanged( const EditStatus& _rStatus );

    private:
        DECL_LINK( OnInvalidateAllAttributes, void* );
        DECL_LINK( OnHScroll, ScrollBar* );
        DECL_LINK( OnVScroll, ScrollBar* );
    };

//........................................................................
} // namespace frm
//........................................................................

#endif // FORMS_SOURCE_RICHTEXT_RICHTEXTIMPLCONTOL_HXX

<commit_msg>INTEGRATION: CWS sb59 (1.5.28); FILE MERGED 2006/08/29 16:11:01 sb 1.5.28.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: richtextimplcontrol.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 11:14:38 $
 *
 *  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 FORMS_SOURCE_RICHTEXT_RICHTEXTIMPLCONTOL_HXX
#define FORMS_SOURCE_RICHTEXT_RICHTEXTIMPLCONTOL_HXX

#ifndef FORMS_SOURCE_COMPONENT_RTATTRIBUTEHANDLER_HXX
#include "rtattributehandler.hxx"
#endif
#ifndef FORMS_SOURCE_RICHTEXT_RICHTEXTVIEWPORT_HXX
#include "richtextviewport.hxx"
#endif
#ifndef FORMS_SOURCE_RICHTEXT_RICHTEXTENGINE_HXX
#include "richtextengine.hxx"
#endif

#ifndef _SV_SCRBAR_HXX
#include <vcl/scrbar.hxx>
#endif

#ifndef _MyEDITDATA_HXX
#include <svx/editdata.hxx>
#endif

#include <map>

class EditView;
class EditStatus;
class Window;
class SvxScriptSetItem;
//........................................................................
namespace frm
{
//........................................................................

    class ITextAttributeListener;
    class ITextSelectionListener;
    class RichTextViewPort;
    //====================================================================
    //= RichTextControlImpl
    //====================================================================
    class RichTextControlImpl : public IEngineStatusListener
    {
        typedef ::std::map< AttributeId, AttributeState >                           StateCache;
        typedef ::std::map< AttributeId, ::rtl::Reference< IAttributeHandler > >    AttributeHandlerPool;
        typedef ::std::map< AttributeId, ITextAttributeListener* >                  AttributeListenerPool;

        StateCache              m_aLastKnownStates;
        AttributeHandlerPool    m_aAttributeHandlers;
        AttributeListenerPool   m_aAttributeListeners;

        ESelection              m_aLastKnownSelection;

        Control*                m_pAntiImpl;
        RichTextViewPort*       m_pViewport;
        ScrollBar*              m_pHScroll;
        ScrollBar*              m_pVScroll;
        ScrollBarBox*           m_pScrollCorner;
        RichTextEngine*         m_pEngine;
        EditView*               m_pView;
        ITextAttributeListener* m_pTextAttrListener;
        ITextSelectionListener* m_pSelectionListener;
        bool                    m_bHasEverBeenShown;

    public:
        struct GrantAccess { friend class RichTextControl; private: GrantAccess() { } };
        inline EditView*        getView( const GrantAccess& ) const     { return m_pView; }
        inline RichTextEngine*  getEngine( const GrantAccess& ) const   { return m_pEngine; }
        inline Window*          getViewport( const GrantAccess& ) const { return m_pViewport; }

    public:
        RichTextControlImpl( Control* _pAntiImpl, RichTextEngine* _pEngine,
            ITextAttributeListener* _pTextAttrListener, ITextSelectionListener* _pSelectionListener );
        virtual ~RichTextControlImpl();

        /** updates the cache with the state of all attribute values from the given set, notifies
            the listener if the state changed
        */
        void    updateAllAttributes( );

        /** updates the cache with the state of the attribute given by which id, notifies
            the listener if the state changed
        */
        void    updateAttribute( AttributeId _nAttribute );

        /// enables the callback for a particular attribute
        void    enableAttributeNotification( AttributeId _nAttributeId, ITextAttributeListener* _pListener = NULL );

        /// disables the change notifications for a particular attribute
        void    disableAttributeNotification( AttributeId _nAttributeId );

        /// executes a toggle of the given attribute
        bool    executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, AttributeId _nAttribute, const SfxPoolItem* _pArgument, ScriptType _nForScriptType );

        /// retrieves the state of the given attribute from the cache
        AttributeState  getAttributeState( AttributeId _nAttributeId ) const;

        /** normalizes the given item so that the state of script dependent attributes
            is correct considering the current script type

            There are some attributes which are script dependent, e.g. the CharPosture. This means
            that in real, there are 3 attributes for this, one for every possible script type (latin,
            asian, complex). However, to the out world, we behave as if there is only one attribute:
            E.g., if the outter world asks for the state of the "CharPosture" attribute, we return
            the state of either CharPostureLatin, CharPostureAsian, or CharPostureComplex, depending
            on the script type of the current selection. (In real, it may be more complex since
            the current selection may contain more than one script type.)

            This method normalizes a script dependent attribute, so that it's state takes into account
            the currently selected script type.
        */
        void        normalizeScriptDependentAttribute( SvxScriptSetItem& _rScriptSetItem );

        // gets the script type of the selection in our edit view (with fallback)
        ScriptType  getSelectedScriptType() const;

        /** re-arranges the view and the scrollbars
        */
        void    layoutWindow();

        /** to be called when the style of our window changed
        */
        void    notifyStyleChanged();

        /** to be called when the zoom of our window changed
        */
        void    notifyZoomChanged();

        /** to be called when the STATE_CHANGE_INITSHOW event arrives
        */
        void    notifyInitShow();

        // VCL "overrides"
        void    SetBackgroundColor( );
        void    SetBackgroundColor( const Color& _rColor );

        void    SetReadOnly( bool _bReadOnly );
        bool    IsReadOnly() const;

        void    SetHideInactiveSelection( bool _bHide );
        bool    GetHideInactiveSelection() const;

        /// draws the control onto a given output device
        void    Draw( OutputDevice* _pDev, const Point& _rPos, const Size& _rSize, ULONG _nFlags );

        /// handles command events arrived at the anti-impl control
        long    HandleCommand( const CommandEvent& _rEvent );

    private:
        // updates the cache with the state provided by the given attribut handler
        void    implUpdateAttribute( AttributeHandlerPool::const_iterator _pHandler );

        // updates the cache with the given state, and calls listeners (if necessary)
        void    implCheckUpdateCache( AttributeId _nAttribute, const AttributeState& _rState );

        // updates range and position of our scrollbars
        void    updateScrollbars();

        // determines whether automatic (soft) line breaks are ON
        bool    windowHasAutomaticLineBreak();

        /// hides or shows our scrollbars, according to the current WinBits of the window
        void    ensureScrollbars();

        /// ensures that our "automatic line break" setting matches the current WinBits of the window
        void    ensureLineBreakSetting();

        inline  bool    hasVScrollBar( ) const { return m_pVScroll != NULL; }
        inline  bool    hasHScrollBar( ) const { return m_pHScroll != NULL; }

        // IEngineStatusListener overridables
        virtual void EditEngineStatusChanged( const EditStatus& _rStatus );

    private:
        DECL_LINK( OnInvalidateAllAttributes, void* );
        DECL_LINK( OnHScroll, ScrollBar* );
        DECL_LINK( OnVScroll, ScrollBar* );
    };

//........................................................................
} // namespace frm
//........................................................................

#endif // FORMS_SOURCE_RICHTEXT_RICHTEXTIMPLCONTOL_HXX

<|endoftext|>


<commit_before>#ifndef STAN_MCMC_HMC_NUTS_ADAPT_DIAG_E_NUTS_HPP
#define STAN_MCMC_HMC_NUTS_ADAPT_DIAG_E_NUTS_HPP

#include <stan/callbacks/writer.hpp>
#include <stan/mcmc/stepsize_var_adapter.hpp>
#include <stan/mcmc/hmc/nuts/diag_e_nuts.hpp>

namespace stan {
  namespace mcmc {
    /**
     * The No-U-Turn sampler (NUTS) with multinomial sampling
     * with a Gaussian-Euclidean disintegration and adaptive
     * diagonal metric and adaptive step size
     */
    template <class Model, class BaseRNG>
    class adapt_diag_e_nuts: public diag_e_nuts<Model, BaseRNG>,
                             public stepsize_var_adapter {
    public:
      adapt_diag_e_nuts(const Model& model, BaseRNG& rng)
        : diag_e_nuts<Model, BaseRNG>(model, rng),
        stepsize_var_adapter(model.num_params_r()) {}

      /**
       * specialized constructor for specified diag mass matrix
       */
      adapt_diag_e_nuts(const Model& model, BaseRNG& rng,
                   Eigen::VectorXd inv_mass_matrix)
        : diag_e_nuts<Model, BaseRNG>(model, rng, inv_mass_matrix),
        stepsize_var_adapter(model.num_params_r()) {}

      ~adapt_diag_e_nuts() {}

      sample
      transition(sample& init_sample,
                 callbacks::writer& info_writer,
                 callbacks::writer& error_writer) {
        sample s = diag_e_nuts<Model, BaseRNG>::transition(init_sample,
                                                           info_writer,
                                                           error_writer);

        if (this->adapt_flag_) {
          this->stepsize_adaptation_.learn_stepsize(this->nom_epsilon_,
                                                    s.accept_stat());

          bool update = this->var_adaptation_.learn_variance(
                                              this->z_.inv_mass_matrix_,
                                              this->z_.q);

          if (update) {
            this->init_stepsize(info_writer, error_writer);

            this->stepsize_adaptation_.set_mu(log(10 * this->nom_epsilon_));
            this->stepsize_adaptation_.restart();
          }
        }
        return s;
      }

      void disengage_adaptation() {
        base_adapter::disengage_adaptation();
        this->stepsize_adaptation_.complete_adaptation(this->nom_epsilon_);
      }
    };

  }  // mcmc
}  // stan
#endif
<commit_msg>code cleanup<commit_after>#ifndef STAN_MCMC_HMC_NUTS_ADAPT_DIAG_E_NUTS_HPP
#define STAN_MCMC_HMC_NUTS_ADAPT_DIAG_E_NUTS_HPP

#include <stan/callbacks/writer.hpp>
#include <stan/mcmc/stepsize_var_adapter.hpp>
#include <stan/mcmc/hmc/nuts/diag_e_nuts.hpp>

namespace stan {
  namespace mcmc {
    /**
     * The No-U-Turn sampler (NUTS) with multinomial sampling
     * with a Gaussian-Euclidean disintegration and adaptive
     * diagonal metric and adaptive step size
     */
    template <class Model, class BaseRNG>
    class adapt_diag_e_nuts: public diag_e_nuts<Model, BaseRNG>,
                             public stepsize_var_adapter {
    public:
      adapt_diag_e_nuts(const Model& model, BaseRNG& rng)
        : diag_e_nuts<Model, BaseRNG>(model, rng),
        stepsize_var_adapter(model.num_params_r()) {}

      /**
       * specialized constructor for specified diag mass matrix
       */
      adapt_diag_e_nuts(const Model& model, BaseRNG& rng,
                   Eigen::VectorXd& inv_mass_matrix)
        : diag_e_nuts<Model, BaseRNG>(model, rng, inv_mass_matrix),
        stepsize_var_adapter(model.num_params_r()) {}

      ~adapt_diag_e_nuts() {}

      sample
      transition(sample& init_sample,
                 callbacks::writer& info_writer,
                 callbacks::writer& error_writer) {
        sample s = diag_e_nuts<Model, BaseRNG>::transition(init_sample,
                                                           info_writer,
                                                           error_writer);

        if (this->adapt_flag_) {
          this->stepsize_adaptation_.learn_stepsize(this->nom_epsilon_,
                                                    s.accept_stat());

          bool update = this->var_adaptation_.learn_variance(
                                              this->z_.inv_mass_matrix_,
                                              this->z_.q);

          if (update) {
            this->init_stepsize(info_writer, error_writer);

            this->stepsize_adaptation_.set_mu(log(10 * this->nom_epsilon_));
            this->stepsize_adaptation_.restart();
          }
        }
        return s;
      }

      void disengage_adaptation() {
        base_adapter::disengage_adaptation();
        this->stepsize_adaptation_.complete_adaptation(this->nom_epsilon_);
      }
    };

  }  // mcmc
}  // stan
#endif
<|endoftext|>


<commit_before>#pragma once

#include "types.hh"
#include "config.hh"
#include "util.hh"

#include <map>
#include <limits>

#include <sys/types.h>

namespace nix {

typedef enum { smEnabled, smRelaxed, smDisabled } SandboxMode;

struct MaxBuildJobsSetting : public BaseSetting<unsigned int>
{
    MaxBuildJobsSetting(Config * options,
        unsigned int def,
        const std::string & name,
        const std::string & description,
        const std::set<std::string> & aliases = {})
        : BaseSetting<unsigned int>(def, name, description, aliases)
    {
        options->addSetting(this);
    }

    void set(const std::string & str) override;
};

class Settings : public Config {

    unsigned int getDefaultCores();

    StringSet getDefaultSystemFeatures();

public:

    Settings();

    Path nixPrefix;

    /* The directory where we store sources and derived files. */
    Path nixStore;

    Path nixDataDir; /* !!! fix */

    /* The directory where we log various operations. */
    Path nixLogDir;

    /* The directory where state is stored. */
    Path nixStateDir;

    /* The directory where configuration files are stored. */
    Path nixConfDir;

    /* The directory where internal helper programs are stored. */
    Path nixLibexecDir;

    /* The directory where the main programs are stored. */
    Path nixBinDir;

    /* The directory where the man pages are stored. */
    Path nixManDir;

    /* File name of the socket the daemon listens to.  */
    Path nixDaemonSocketFile;

    Setting<std::string> storeUri{this, getEnv("NIX_REMOTE", "auto"), "store",
        "The default Nix store to use."};

    Setting<bool> keepFailed{this, false, "keep-failed",
        "Whether to keep temporary directories of failed builds."};

    Setting<bool> keepGoing{this, false, "keep-going",
        "Whether to keep building derivations when another build fails."};

    Setting<bool> tryFallback{this, false, "fallback",
        "Whether to fall back to building when substitution fails.",
        {"build-fallback"}};

    /* Whether to show build log output in real time. */
    bool verboseBuild = true;

    Setting<size_t> logLines{this, 10, "log-lines",
        "If verbose-build is false, the number of lines of the tail of "
        "the log to show if a build fails."};

    MaxBuildJobsSetting maxBuildJobs{this, 1, "max-jobs",
        "Maximum number of parallel build jobs. \"auto\" means use number of cores.",
        {"build-max-jobs"}};

    Setting<unsigned int> buildCores{this, getDefaultCores(), "cores",
        "Number of CPU cores to utilize in parallel within a build, "
        "i.e. by passing this number to Make via '-j'. 0 means that the "
        "number of actual CPU cores on the local host ought to be "
        "auto-detected.", {"build-cores"}};

    /* Read-only mode.  Don't copy stuff to the store, don't change
       the database. */
    bool readOnlyMode = false;

    Setting<std::string> thisSystem{this, SYSTEM, "system",
        "The canonical Nix system name."};

    Setting<time_t> maxSilentTime{this, 0, "max-silent-time",
        "The maximum time in seconds that a builer can go without "
        "producing any output on stdout/stderr before it is killed. "
        "0 means infinity.",
        {"build-max-silent-time"}};

    Setting<time_t> buildTimeout{this, 0, "timeout",
        "The maximum duration in seconds that a builder can run. "
        "0 means infinity.", {"build-timeout"}};

    PathSetting buildHook{this, true, nixLibexecDir + "/nix/build-remote", "build-hook",
        "The path of the helper program that executes builds to remote machines."};

    Setting<std::string> builders{this, "@" + nixConfDir + "/machines", "builders",
        "A semicolon-separated list of build machines, in the format of nix.machines."};

    Setting<bool> buildersUseSubstitutes{this, false, "builders-use-substitutes",
        "Whether build machines should use their own substitutes for obtaining "
        "build dependencies if possible, rather than waiting for this host to "
        "upload them."};

    Setting<off_t> reservedSize{this, 8 * 1024 * 1024, "gc-reserved-space",
        "Amount of reserved disk space for the garbage collector."};

    Setting<bool> fsyncMetadata{this, true, "fsync-metadata",
        "Whether SQLite should use fsync()."};

    Setting<bool> useSQLiteWAL{this, true, "use-sqlite-wal",
        "Whether SQLite should use WAL mode."};

    Setting<bool> syncBeforeRegistering{this, false, "sync-before-registering",
        "Whether to call sync() before registering a path as valid."};

    Setting<bool> useSubstitutes{this, true, "substitute",
        "Whether to use substitutes.",
        {"build-use-substitutes"}};

    Setting<std::string> buildUsersGroup{this, "", "build-users-group",
        "The Unix group that contains the build users."};

    Setting<bool> impersonateLinux26{this, false, "impersonate-linux-26",
        "Whether to impersonate a Linux 2.6 machine on newer kernels.",
        {"build-impersonate-linux-26"}};

    Setting<bool> keepLog{this, true, "keep-build-log",
        "Whether to store build logs.",
        {"build-keep-log"}};

    Setting<bool> compressLog{this, true, "compress-build-log",
        "Whether to compress logs.",
        {"build-compress-log"}};

    Setting<unsigned long> maxLogSize{this, 0, "max-build-log-size",
        "Maximum number of bytes a builder can write to stdout/stderr "
        "before being killed (0 means no limit).",
        {"build-max-log-size"}};

    /* When buildRepeat > 0 and verboseBuild == true, whether to print
       repeated builds (i.e. builds other than the first one) to
       stderr. Hack to prevent Hydra logs from being polluted. */
    bool printRepeatedBuilds = true;

    Setting<unsigned int> pollInterval{this, 5, "build-poll-interval",
        "How often (in seconds) to poll for locks."};

    Setting<bool> checkRootReachability{this, false, "gc-check-reachability",
        "Whether to check if new GC roots can in fact be found by the "
        "garbage collector."};

    Setting<bool> gcKeepOutputs{this, false, "keep-outputs",
        "Whether the garbage collector should keep outputs of live derivations.",
        {"gc-keep-outputs"}};

    Setting<bool> gcKeepDerivations{this, true, "keep-derivations",
        "Whether the garbage collector should keep derivers of live paths.",
        {"gc-keep-derivations"}};

    Setting<bool> autoOptimiseStore{this, false, "auto-optimise-store",
        "Whether to automatically replace files with identical contents with hard links."};

    Setting<bool> envKeepDerivations{this, false, "keep-env-derivations",
        "Whether to add derivations as a dependency of user environments "
        "(to prevent them from being GCed).",
        {"env-keep-derivations"}};

    /* Whether to lock the Nix client and worker to the same CPU. */
    bool lockCPU;

    /* Whether to show a stack trace if Nix evaluation fails. */
    Setting<bool> showTrace{this, false, "show-trace",
        "Whether to show a stack trace on evaluation errors."};

    Setting<SandboxMode> sandboxMode{this,
        #if __linux__
          smEnabled
        #else
          smDisabled
        #endif
        , "sandbox",
        "Whether to enable sandboxed builds. Can be \"true\", \"false\" or \"relaxed\".",
        {"build-use-chroot", "build-use-sandbox"}};

    Setting<PathSet> sandboxPaths{this, {}, "sandbox-paths",
        "The paths to make available inside the build sandbox.",
        {"build-chroot-dirs", "build-sandbox-paths"}};

    Setting<bool> sandboxFallback{this, true, "sandbox-fallback",
        "Whether to disable sandboxing when the kernel doesn't allow it."};

    Setting<PathSet> extraSandboxPaths{this, {}, "extra-sandbox-paths",
        "Additional paths to make available inside the build sandbox.",
        {"build-extra-chroot-dirs", "build-extra-sandbox-paths"}};

    Setting<size_t> buildRepeat{this, 0, "repeat",
        "The number of times to repeat a build in order to verify determinism.",
        {"build-repeat"}};

#if __linux__
    Setting<std::string> sandboxShmSize{this, "50%", "sandbox-dev-shm-size",
        "The size of /dev/shm in the build sandbox."};

    Setting<Path> sandboxBuildDir{this, "/build", "sandbox-build-dir",
        "The build directory inside the sandbox."};
#endif

    Setting<PathSet> allowedImpureHostPrefixes{this, {}, "allowed-impure-host-deps",
        "Which prefixes to allow derivations to ask for access to (primarily for Darwin)."};

#if __APPLE__
    Setting<bool> darwinLogSandboxViolations{this, false, "darwin-log-sandbox-violations",
        "Whether to log Darwin sandbox access violations to the system log."};
#endif

    Setting<bool> runDiffHook{this, false, "run-diff-hook",
        "Whether to run the program specified by the diff-hook setting "
        "repeated builds produce a different result. Typically used to "
        "plug in diffoscope."};

    PathSetting diffHook{this, true, "", "diff-hook",
        "A program that prints out the differences between the two paths "
        "specified on its command line."};

    Setting<bool> enforceDeterminism{this, true, "enforce-determinism",
        "Whether to fail if repeated builds produce different output."};

    Setting<Strings> trustedPublicKeys{this,
        {"cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="},
        "trusted-public-keys",
        "Trusted public keys for secure substitution.",
        {"binary-cache-public-keys"}};

    Setting<Strings> secretKeyFiles{this, {}, "secret-key-files",
        "Secret keys with which to sign local builds."};

    Setting<unsigned int> tarballTtl{this, 60 * 60, "tarball-ttl",
        "How long downloaded files are considered up-to-date."};

    Setting<bool> requireSigs{this, true, "require-sigs",
        "Whether to check that any non-content-addressed path added to the "
        "Nix store has a valid signature (that is, one signed using a key "
        "listed in 'trusted-public-keys'."};

    Setting<StringSet> extraPlatforms{this,
        std::string{SYSTEM} == "x86_64-linux" ? StringSet{"i686-linux"} : StringSet{},
        "extra-platforms",
        "Additional platforms that can be built on the local system. "
        "These may be supported natively (e.g. armv7 on some aarch64 CPUs "
        "or using hacks like qemu-user."};

    Setting<StringSet> systemFeatures{this, getDefaultSystemFeatures(),
        "system-features",
        "Optional features that this system implements (like \"kvm\")."};

    Setting<Strings> substituters{this,
        nixStore == "/nix/store" ? Strings{"https://cache.nixos.org/"} : Strings(),
        "substituters",
        "The URIs of substituters (such as https://cache.nixos.org/).",
        {"binary-caches"}};

    // FIXME: provide a way to add to option values.
    Setting<Strings> extraSubstituters{this, {}, "extra-substituters",
        "Additional URIs of substituters.",
        {"extra-binary-caches"}};

    Setting<StringSet> trustedSubstituters{this, {}, "trusted-substituters",
        "Disabled substituters that may be enabled via the substituters option by untrusted users.",
        {"trusted-binary-caches"}};

    Setting<Strings> trustedUsers{this, {"root"}, "trusted-users",
        "Which users or groups are trusted to ask the daemon to do unsafe things."};

    Setting<unsigned int> ttlNegativeNarInfoCache{this, 3600, "narinfo-cache-negative-ttl",
        "The TTL in seconds for negative lookups in the disk cache i.e binary cache lookups that "
        "return an invalid path result"};

    Setting<unsigned int> ttlPositiveNarInfoCache{this, 30 * 24 * 3600, "narinfo-cache-positive-ttl",
        "The TTL in seconds for positive lookups in the disk cache i.e binary cache lookups that "
        "return a valid path result."};

    /* ?Who we trust to use the daemon in safe ways */
    Setting<Strings> allowedUsers{this, {"*"}, "allowed-users",
        "Which users or groups are allowed to connect to the daemon."};

    Setting<bool> printMissing{this, true, "print-missing",
        "Whether to print what paths need to be built or downloaded."};

    Setting<std::string> preBuildHook{this,
#if __APPLE__
        nixLibexecDir + "/nix/resolve-system-dependencies",
#else
        "",
#endif
        "pre-build-hook",
        "A program to run just before a build to set derivation-specific build settings."};

    Setting<std::string> postBuildHook{this, "", "post-build-hook",
        "A program to run just after each succesful build."};

    Setting<std::string> netrcFile{this, fmt("%s/%s", nixConfDir, "netrc"), "netrc-file",
        "Path to the netrc file used to obtain usernames/passwords for downloads."};

    /* Path to the SSL CA file used */
    Path caFile;

#if __linux__
    Setting<bool> filterSyscalls{this, true, "filter-syscalls",
            "Whether to prevent certain dangerous system calls, such as "
            "creation of setuid/setgid files or adding ACLs or extended "
            "attributes. Only disable this if you're aware of the "
            "security implications."};

    Setting<bool> allowNewPrivileges{this, false, "allow-new-privileges",
        "Whether builders can acquire new privileges by calling programs with "
        "setuid/setgid bits or with file capabilities."};
#endif

    Setting<Strings> hashedMirrors{this, {"http://tarballs.nixos.org/"}, "hashed-mirrors",
        "A list of servers used by builtins.fetchurl to fetch files by hash."};

    Setting<uint64_t> minFree{this, 0, "min-free",
        "Automatically run the garbage collector when free disk space drops below the specified amount."};

    Setting<uint64_t> maxFree{this, std::numeric_limits<uint64_t>::max(), "max-free",
        "Stop deleting garbage when free disk space is above the specified amount."};

    Setting<uint64_t> minFreeCheckInterval{this, 5, "min-free-check-interval",
        "Number of seconds between checking free disk space."};

    Setting<Paths> pluginFiles{this, {}, "plugin-files",
        "Plugins to dynamically load at nix initialization time."};

    Setting<Strings> experimentalFeatures{this, {}, "experimental-features",
        "Experimental Nix features to enable."};

    void requireExperimentalFeature(const std::string & name);
};

// FIXME: don't use a global variable.
extern Settings settings;

/* This should be called after settings are initialized, but before
   anything else */
void initPlugins();

void loadConfFile();

extern const string nixVersion;

}
<commit_msg>experimental-features: enable nix-command by default, avoid breakage<commit_after>#pragma once

#include "types.hh"
#include "config.hh"
#include "util.hh"

#include <map>
#include <limits>

#include <sys/types.h>

namespace nix {

typedef enum { smEnabled, smRelaxed, smDisabled } SandboxMode;

struct MaxBuildJobsSetting : public BaseSetting<unsigned int>
{
    MaxBuildJobsSetting(Config * options,
        unsigned int def,
        const std::string & name,
        const std::string & description,
        const std::set<std::string> & aliases = {})
        : BaseSetting<unsigned int>(def, name, description, aliases)
    {
        options->addSetting(this);
    }

    void set(const std::string & str) override;
};

class Settings : public Config {

    unsigned int getDefaultCores();

    StringSet getDefaultSystemFeatures();

public:

    Settings();

    Path nixPrefix;

    /* The directory where we store sources and derived files. */
    Path nixStore;

    Path nixDataDir; /* !!! fix */

    /* The directory where we log various operations. */
    Path nixLogDir;

    /* The directory where state is stored. */
    Path nixStateDir;

    /* The directory where configuration files are stored. */
    Path nixConfDir;

    /* The directory where internal helper programs are stored. */
    Path nixLibexecDir;

    /* The directory where the main programs are stored. */
    Path nixBinDir;

    /* The directory where the man pages are stored. */
    Path nixManDir;

    /* File name of the socket the daemon listens to.  */
    Path nixDaemonSocketFile;

    Setting<std::string> storeUri{this, getEnv("NIX_REMOTE", "auto"), "store",
        "The default Nix store to use."};

    Setting<bool> keepFailed{this, false, "keep-failed",
        "Whether to keep temporary directories of failed builds."};

    Setting<bool> keepGoing{this, false, "keep-going",
        "Whether to keep building derivations when another build fails."};

    Setting<bool> tryFallback{this, false, "fallback",
        "Whether to fall back to building when substitution fails.",
        {"build-fallback"}};

    /* Whether to show build log output in real time. */
    bool verboseBuild = true;

    Setting<size_t> logLines{this, 10, "log-lines",
        "If verbose-build is false, the number of lines of the tail of "
        "the log to show if a build fails."};

    MaxBuildJobsSetting maxBuildJobs{this, 1, "max-jobs",
        "Maximum number of parallel build jobs. \"auto\" means use number of cores.",
        {"build-max-jobs"}};

    Setting<unsigned int> buildCores{this, getDefaultCores(), "cores",
        "Number of CPU cores to utilize in parallel within a build, "
        "i.e. by passing this number to Make via '-j'. 0 means that the "
        "number of actual CPU cores on the local host ought to be "
        "auto-detected.", {"build-cores"}};

    /* Read-only mode.  Don't copy stuff to the store, don't change
       the database. */
    bool readOnlyMode = false;

    Setting<std::string> thisSystem{this, SYSTEM, "system",
        "The canonical Nix system name."};

    Setting<time_t> maxSilentTime{this, 0, "max-silent-time",
        "The maximum time in seconds that a builer can go without "
        "producing any output on stdout/stderr before it is killed. "
        "0 means infinity.",
        {"build-max-silent-time"}};

    Setting<time_t> buildTimeout{this, 0, "timeout",
        "The maximum duration in seconds that a builder can run. "
        "0 means infinity.", {"build-timeout"}};

    PathSetting buildHook{this, true, nixLibexecDir + "/nix/build-remote", "build-hook",
        "The path of the helper program that executes builds to remote machines."};

    Setting<std::string> builders{this, "@" + nixConfDir + "/machines", "builders",
        "A semicolon-separated list of build machines, in the format of nix.machines."};

    Setting<bool> buildersUseSubstitutes{this, false, "builders-use-substitutes",
        "Whether build machines should use their own substitutes for obtaining "
        "build dependencies if possible, rather than waiting for this host to "
        "upload them."};

    Setting<off_t> reservedSize{this, 8 * 1024 * 1024, "gc-reserved-space",
        "Amount of reserved disk space for the garbage collector."};

    Setting<bool> fsyncMetadata{this, true, "fsync-metadata",
        "Whether SQLite should use fsync()."};

    Setting<bool> useSQLiteWAL{this, true, "use-sqlite-wal",
        "Whether SQLite should use WAL mode."};

    Setting<bool> syncBeforeRegistering{this, false, "sync-before-registering",
        "Whether to call sync() before registering a path as valid."};

    Setting<bool> useSubstitutes{this, true, "substitute",
        "Whether to use substitutes.",
        {"build-use-substitutes"}};

    Setting<std::string> buildUsersGroup{this, "", "build-users-group",
        "The Unix group that contains the build users."};

    Setting<bool> impersonateLinux26{this, false, "impersonate-linux-26",
        "Whether to impersonate a Linux 2.6 machine on newer kernels.",
        {"build-impersonate-linux-26"}};

    Setting<bool> keepLog{this, true, "keep-build-log",
        "Whether to store build logs.",
        {"build-keep-log"}};

    Setting<bool> compressLog{this, true, "compress-build-log",
        "Whether to compress logs.",
        {"build-compress-log"}};

    Setting<unsigned long> maxLogSize{this, 0, "max-build-log-size",
        "Maximum number of bytes a builder can write to stdout/stderr "
        "before being killed (0 means no limit).",
        {"build-max-log-size"}};

    /* When buildRepeat > 0 and verboseBuild == true, whether to print
       repeated builds (i.e. builds other than the first one) to
       stderr. Hack to prevent Hydra logs from being polluted. */
    bool printRepeatedBuilds = true;

    Setting<unsigned int> pollInterval{this, 5, "build-poll-interval",
        "How often (in seconds) to poll for locks."};

    Setting<bool> checkRootReachability{this, false, "gc-check-reachability",
        "Whether to check if new GC roots can in fact be found by the "
        "garbage collector."};

    Setting<bool> gcKeepOutputs{this, false, "keep-outputs",
        "Whether the garbage collector should keep outputs of live derivations.",
        {"gc-keep-outputs"}};

    Setting<bool> gcKeepDerivations{this, true, "keep-derivations",
        "Whether the garbage collector should keep derivers of live paths.",
        {"gc-keep-derivations"}};

    Setting<bool> autoOptimiseStore{this, false, "auto-optimise-store",
        "Whether to automatically replace files with identical contents with hard links."};

    Setting<bool> envKeepDerivations{this, false, "keep-env-derivations",
        "Whether to add derivations as a dependency of user environments "
        "(to prevent them from being GCed).",
        {"env-keep-derivations"}};

    /* Whether to lock the Nix client and worker to the same CPU. */
    bool lockCPU;

    /* Whether to show a stack trace if Nix evaluation fails. */
    Setting<bool> showTrace{this, false, "show-trace",
        "Whether to show a stack trace on evaluation errors."};

    Setting<SandboxMode> sandboxMode{this,
        #if __linux__
          smEnabled
        #else
          smDisabled
        #endif
        , "sandbox",
        "Whether to enable sandboxed builds. Can be \"true\", \"false\" or \"relaxed\".",
        {"build-use-chroot", "build-use-sandbox"}};

    Setting<PathSet> sandboxPaths{this, {}, "sandbox-paths",
        "The paths to make available inside the build sandbox.",
        {"build-chroot-dirs", "build-sandbox-paths"}};

    Setting<bool> sandboxFallback{this, true, "sandbox-fallback",
        "Whether to disable sandboxing when the kernel doesn't allow it."};

    Setting<PathSet> extraSandboxPaths{this, {}, "extra-sandbox-paths",
        "Additional paths to make available inside the build sandbox.",
        {"build-extra-chroot-dirs", "build-extra-sandbox-paths"}};

    Setting<size_t> buildRepeat{this, 0, "repeat",
        "The number of times to repeat a build in order to verify determinism.",
        {"build-repeat"}};

#if __linux__
    Setting<std::string> sandboxShmSize{this, "50%", "sandbox-dev-shm-size",
        "The size of /dev/shm in the build sandbox."};

    Setting<Path> sandboxBuildDir{this, "/build", "sandbox-build-dir",
        "The build directory inside the sandbox."};
#endif

    Setting<PathSet> allowedImpureHostPrefixes{this, {}, "allowed-impure-host-deps",
        "Which prefixes to allow derivations to ask for access to (primarily for Darwin)."};

#if __APPLE__
    Setting<bool> darwinLogSandboxViolations{this, false, "darwin-log-sandbox-violations",
        "Whether to log Darwin sandbox access violations to the system log."};
#endif

    Setting<bool> runDiffHook{this, false, "run-diff-hook",
        "Whether to run the program specified by the diff-hook setting "
        "repeated builds produce a different result. Typically used to "
        "plug in diffoscope."};

    PathSetting diffHook{this, true, "", "diff-hook",
        "A program that prints out the differences between the two paths "
        "specified on its command line."};

    Setting<bool> enforceDeterminism{this, true, "enforce-determinism",
        "Whether to fail if repeated builds produce different output."};

    Setting<Strings> trustedPublicKeys{this,
        {"cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="},
        "trusted-public-keys",
        "Trusted public keys for secure substitution.",
        {"binary-cache-public-keys"}};

    Setting<Strings> secretKeyFiles{this, {}, "secret-key-files",
        "Secret keys with which to sign local builds."};

    Setting<unsigned int> tarballTtl{this, 60 * 60, "tarball-ttl",
        "How long downloaded files are considered up-to-date."};

    Setting<bool> requireSigs{this, true, "require-sigs",
        "Whether to check that any non-content-addressed path added to the "
        "Nix store has a valid signature (that is, one signed using a key "
        "listed in 'trusted-public-keys'."};

    Setting<StringSet> extraPlatforms{this,
        std::string{SYSTEM} == "x86_64-linux" ? StringSet{"i686-linux"} : StringSet{},
        "extra-platforms",
        "Additional platforms that can be built on the local system. "
        "These may be supported natively (e.g. armv7 on some aarch64 CPUs "
        "or using hacks like qemu-user."};

    Setting<StringSet> systemFeatures{this, getDefaultSystemFeatures(),
        "system-features",
        "Optional features that this system implements (like \"kvm\")."};

    Setting<Strings> substituters{this,
        nixStore == "/nix/store" ? Strings{"https://cache.nixos.org/"} : Strings(),
        "substituters",
        "The URIs of substituters (such as https://cache.nixos.org/).",
        {"binary-caches"}};

    // FIXME: provide a way to add to option values.
    Setting<Strings> extraSubstituters{this, {}, "extra-substituters",
        "Additional URIs of substituters.",
        {"extra-binary-caches"}};

    Setting<StringSet> trustedSubstituters{this, {}, "trusted-substituters",
        "Disabled substituters that may be enabled via the substituters option by untrusted users.",
        {"trusted-binary-caches"}};

    Setting<Strings> trustedUsers{this, {"root"}, "trusted-users",
        "Which users or groups are trusted to ask the daemon to do unsafe things."};

    Setting<unsigned int> ttlNegativeNarInfoCache{this, 3600, "narinfo-cache-negative-ttl",
        "The TTL in seconds for negative lookups in the disk cache i.e binary cache lookups that "
        "return an invalid path result"};

    Setting<unsigned int> ttlPositiveNarInfoCache{this, 30 * 24 * 3600, "narinfo-cache-positive-ttl",
        "The TTL in seconds for positive lookups in the disk cache i.e binary cache lookups that "
        "return a valid path result."};

    /* ?Who we trust to use the daemon in safe ways */
    Setting<Strings> allowedUsers{this, {"*"}, "allowed-users",
        "Which users or groups are allowed to connect to the daemon."};

    Setting<bool> printMissing{this, true, "print-missing",
        "Whether to print what paths need to be built or downloaded."};

    Setting<std::string> preBuildHook{this,
#if __APPLE__
        nixLibexecDir + "/nix/resolve-system-dependencies",
#else
        "",
#endif
        "pre-build-hook",
        "A program to run just before a build to set derivation-specific build settings."};

    Setting<std::string> postBuildHook{this, "", "post-build-hook",
        "A program to run just after each succesful build."};

    Setting<std::string> netrcFile{this, fmt("%s/%s", nixConfDir, "netrc"), "netrc-file",
        "Path to the netrc file used to obtain usernames/passwords for downloads."};

    /* Path to the SSL CA file used */
    Path caFile;

#if __linux__
    Setting<bool> filterSyscalls{this, true, "filter-syscalls",
            "Whether to prevent certain dangerous system calls, such as "
            "creation of setuid/setgid files or adding ACLs or extended "
            "attributes. Only disable this if you're aware of the "
            "security implications."};

    Setting<bool> allowNewPrivileges{this, false, "allow-new-privileges",
        "Whether builders can acquire new privileges by calling programs with "
        "setuid/setgid bits or with file capabilities."};
#endif

    Setting<Strings> hashedMirrors{this, {"http://tarballs.nixos.org/"}, "hashed-mirrors",
        "A list of servers used by builtins.fetchurl to fetch files by hash."};

    Setting<uint64_t> minFree{this, 0, "min-free",
        "Automatically run the garbage collector when free disk space drops below the specified amount."};

    Setting<uint64_t> maxFree{this, std::numeric_limits<uint64_t>::max(), "max-free",
        "Stop deleting garbage when free disk space is above the specified amount."};

    Setting<uint64_t> minFreeCheckInterval{this, 5, "min-free-check-interval",
        "Number of seconds between checking free disk space."};

    Setting<Paths> pluginFiles{this, {}, "plugin-files",
        "Plugins to dynamically load at nix initialization time."};

    Setting<Strings> experimentalFeatures{this, {"nix-command"}, "experimental-features",
        "Experimental Nix features to enable."};

    void requireExperimentalFeature(const std::string & name);
};

// FIXME: don't use a global variable.
extern Settings settings;

/* This should be called after settings are initialized, but before
   anything else */
void initPlugins();

void loadConfFile();

extern const string nixVersion;

}
<|endoftext|>


<commit_before>#include <celero/Celero.h>

#include <algorithm>
#include <functional>

#ifndef WIN32
#include <cstdlib>
#include <cmath>
#endif

///
/// \class	DemoTransformFixture
///	\autho	John Farrier
///
///	\brief	A Celero Test Fixture for array transforms.
///
/// This test fixture will build a problem set of powers of two.  When executed,
/// the selected problem set is used to create an array of the given size, then
/// push random integers into the array.  Each transform function will then
/// modify the randomly generated array for timing.
///
///	This demo highlights how to use the ProblemSetValues to build automatic
/// test cases which can scale.  These test cases should ideally be written
/// to a file when executed.  The resulting CSV file can be easily plotted
/// in an application such as Microsoft Excel to show how various
/// tests performed as their problem set scaled.
///
/// \code
/// > celeroDemo outfile.csv
/// \endcode
///
class DemoTransformFixture : public celero::TestFixture
{
	public:
		enum Constants
		{
			Multiple = 2112
		};

		DemoTransformFixture()
		{
			// We will run some total number of sets of tests all together. Each one growing by a power of 2.
			const int totalNumberOfTests = 12;

			for(int i = 0; i < totalNumberOfTests; i++)
			{
				// ProblemSetValues is part of the base class and allows us to specify
				// some values to control various test runs to end up building a nice graph.
				this->ProblemSetValues.push_back(static_cast<int32_t>(pow(2, i+1)));
			}
		}

		/// Before each run, build a vector of random integers.
		virtual void SetUp(const int32_t problemSetValue)
		{
			this->arraySize = problemSetValue;

			for(int i = 0; i < this->arraySize; i++)
			{
				this->arrayIn.push_back(rand());
			}

			this->arrayOut.reserve(this->arraySize);
		}

		/// After each run, clear the vector of random integers.
		virtual void TearDown()
		{
			this->arrayIn.clear();
			this->arrayOut.clear();
		}

		std::vector<int> arrayIn;
		std::vector<int> arrayOut;
		int arraySize;
};

// For a baseline, I'll chose Bubble Sort.
BASELINE_F(DemoTransform, ForLoop, DemoTransformFixture, 0, 10000)
{
	for(int i = 0; i < this->arraySize; i++)
	{
		this->arrayOut[i] = this->arrayIn[i] * DemoTransformFixture::Multiple;
	}
}

BENCHMARK_F(DemoTransform, StdTransform, DemoTransformFixture, 0, 10000)
{
	std::transform(this->arrayIn.begin(), this->arrayIn.end(), this->arrayOut.begin(), std::bind1st(std::multiplies<int>(), DemoTransformFixture::Multiple));
}

BENCHMARK_F(DemoTransform, StdTransformLambda, DemoTransformFixture, 0, 10000)
{
	std::transform(this->arrayIn.begin(), this->arrayIn.end(), this->arrayOut.begin(),
		[](int in)->int
		{
			return in * DemoTransformFixture::Multiple;
		});
}

BENCHMARK_F(DemoTransform, SelfForLoop, DemoTransformFixture, 0, 10000)
{
	for(int i = 0; i < this->arraySize; i++)
	{
		this->arrayIn[i] *= DemoTransformFixture::Multiple;
	}
}

BENCHMARK_F(DemoTransform, SelfStdTransform, DemoTransformFixture, 0, 10000)
{
	std::transform(this->arrayIn.begin(), this->arrayIn.end(), this->arrayIn.begin(), std::bind1st(std::multiplies<int>(), DemoTransformFixture::Multiple));
}

BENCHMARK_F(DemoTransform, SelfStdTransformLambda, DemoTransformFixture, 0, 10000)
{
	std::transform(this->arrayIn.begin(), this->arrayIn.end(), this->arrayIn.begin(),
		[](int in)->int
		{
			return in * DemoTransformFixture::Multiple;
		});
}
<commit_msg>Fixed a bug in array size allocation.<commit_after>#include <celero/Celero.h>

#include <algorithm>
#include <functional>

#ifndef WIN32
#include <cstdlib>
#include <cmath>
#endif

///
/// \class	DemoTransformFixture
///	\autho	John Farrier
///
///	\brief	A Celero Test Fixture for array transforms.
///
/// This test fixture will build a problem set of powers of two.  When executed,
/// the selected problem set is used to create an array of the given size, then
/// push random integers into the array.  Each transform function will then
/// modify the randomly generated array for timing.
///
///	This demo highlights how to use the ProblemSetValues to build automatic
/// test cases which can scale.  These test cases should ideally be written
/// to a file when executed.  The resulting CSV file can be easily plotted
/// in an application such as Microsoft Excel to show how various
/// tests performed as their problem set scaled.
///
/// \code
/// celeroDemo outfile.csv
/// \endcode
///
class DemoTransformFixture : public celero::TestFixture
{
	public:
		enum Constants
		{
			Multiple = 2112
		};

		DemoTransformFixture()
		{
			// We will run some total number of sets of tests all together. Each one growing by a power of 2.
			const int totalNumberOfTests = 12;

			for(int i = 0; i < totalNumberOfTests; i++)
			{
				// ProblemSetValues is part of the base class and allows us to specify
				// some values to control various test runs to end up building a nice graph.
				this->ProblemSetValues.push_back(static_cast<int32_t>(pow(2, i+1)));
			}
		}

		/// Before each run, build a vector of random integers.
		virtual void SetUp(const int32_t problemSetValue)
		{
			this->arraySize = problemSetValue;

			for(int i = 0; i < this->arraySize; i++)
			{
				this->arrayIn.push_back(rand());
			}

			this->arrayOut.resize(this->arraySize);
		}

		/// After each run, clear the vector of random integers.
		virtual void TearDown()
		{
			this->arrayIn.clear();
			this->arrayOut.clear();
		}

		std::vector<int> arrayIn;
		std::vector<int> arrayOut;
		int arraySize;
};

// For a baseline, I'll chose Bubble Sort.
BASELINE_F(DemoTransform, ForLoop, DemoTransformFixture, 0, 10000)
{
	for(int i = 0; i < this->arraySize; i++)
	{
		this->arrayOut[i] = this->arrayIn[i] * DemoTransformFixture::Multiple;
	}
}

BENCHMARK_F(DemoTransform, StdTransform, DemoTransformFixture, 0, 10000)
{
	std::transform(this->arrayIn.begin(), this->arrayIn.end(), this->arrayOut.begin(), std::bind1st(std::multiplies<int>(), DemoTransformFixture::Multiple));
}

BENCHMARK_F(DemoTransform, StdTransformLambda, DemoTransformFixture, 0, 10000)
{
	std::transform(this->arrayIn.begin(), this->arrayIn.end(), this->arrayOut.begin(),
		[](int in)->int
		{
			return in * DemoTransformFixture::Multiple;
		});
}

BENCHMARK_F(DemoTransform, SelfForLoop, DemoTransformFixture, 0, 10000)
{
	for(int i = 0; i < this->arraySize; i++)
	{
		this->arrayIn[i] *= DemoTransformFixture::Multiple;
	}
}

BENCHMARK_F(DemoTransform, SelfStdTransform, DemoTransformFixture, 0, 10000)
{
	std::transform(this->arrayIn.begin(), this->arrayIn.end(), this->arrayIn.begin(), std::bind1st(std::multiplies<int>(), DemoTransformFixture::Multiple));
}

BENCHMARK_F(DemoTransform, SelfStdTransformLambda, DemoTransformFixture, 0, 10000)
{
	std::transform(this->arrayIn.begin(), this->arrayIn.end(), this->arrayIn.begin(),
		[](int in)->int
		{
			return in * DemoTransformFixture::Multiple;
		});
}
<|endoftext|>


<commit_before>#include "DotGraphOutput.hh"
#include "EdgeType.hh"

string getEdgeStyle(EdgeType t) {
  switch (t) {
  case EdgeType::Plane:
    return "[color=red]";
  case EdgeType::Train:
    return "[color=blue,style=dotted]";
  default:
    return "";
  }
}

template <typename V>
void DotGraphOutput<V>::output(string path) {

  cout << "Exporting " << this->graph_.name() << " to " << path << endl;

  ofstream st(path, ofstream::out);

  st << "digraph " << this->graph_.name() << " {" << endl;

  for (unsigned int i = 0; i < this->graph_.verticesNb(); i++)
    for (auto e : this->graph_.outgoingEdges(i)) {
      st << "\t" << i
	 << " -> " << e->getOtherEnd(i)
	 << " " << getEdgeStyle(e->type())
	 << ";" << endl;
    }

  st << "}" << endl;

  st.close();
}

template class DotGraphOutput<double>;
<commit_msg>Add the nodes name to the dot output<commit_after>#include "DotGraphOutput.hh"
#include "EdgeType.hh"

string getEdgeStyle(EdgeType t) {
  switch (t) {
  case EdgeType::Plane:
    return "[color=red]";
  case EdgeType::Train:
    return "[color=blue,style=dotted]";
  default:
    return "";
  }
}

template <typename V>
void DotGraphOutput<V>::output(string path) {

  cout << "Exporting " << this->graph_.name() << " to " << path << endl;

  ofstream st(path, ofstream::out);

  st << "digraph " << this->graph_.name() << " {" << endl;

  for (unsigned int i = 0; i < this->graph_.verticesNb(); i++)
    for (auto e : this->graph_.outgoingEdges(i)) {
      st << "\t" << this->graph_.getVertex(i).name()
	 << " -> " << this->graph_.getVertex(e->getOtherEnd(i)).name()
	 << " " << getEdgeStyle(e->type())
	 << ";" << endl;
    }

  st << "}" << endl;

  st.close();
}

template class DotGraphOutput<double>;
<|endoftext|>


<commit_before>/*
Copyright (c) 2013, William Magato
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ''AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holder(s) or contributors.
*/

#include <cstring>

#include <sstream>
#include <stdexcept>
#include <string>

template <typename T>
static T convert (const std::string &s)
{
   std::stringstream ss (s);
   T t;
   ss >> t;

   if (!ss.fail ())
   {
      return t;
   }

   std::stringstream err;
   err << "failed to convert string: " << s;
   throw std::runtime_error (err.str ());
}

template <typename T>
static T parse (int argc, char *argv [], const std::string &arg, const T &value)
{
   for (int i = 1; i < argc; i++)
   {
      if (arg == argv [i])
      {
         if ((i + 1) >= argc)
         {
            std::stringstream err;
            err << "missing argument value for " << arg;
            throw std::runtime_error (err.str ());
         }

         return convert<T> (argv [i + 1]);
      }
   }

   return value;
}

#include <llamaos/mpi/mpi.h>
#include <llamaos/net/llamaNET.h>
#include <llamaos/xen/Hypervisor.h>

using namespace std;
using namespace llamaos;
using namespace llamaos::xen;

static uint32_t seq = 1;

static domid_t get_domd_id (int node)
{
   // for now it's just self minus node % 6
   domid_t self_id = Hypervisor::get_instance ()->domid;

   return (self_id - 1 - (node % 6));
}

static net::llamaNET *interface = nullptr;
static int node;

int MPI_Init (int *argc, char ***argv)
{
   node = parse<int>(*argc, *argv, "--node", 0);
   interface = new net::llamaNET (get_domd_id (node), (node % 6));

   return MPI_SUCCESS;
}

int MPI_Finalize (void)
{
   delete interface;

   return MPI_SUCCESS;
}

int MPI_Comm_rank (MPI_Comm comm, int *rank)
{
   return node;
}

int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status)
{
   net::llamaNET::Protocol_header *header;

   for (;;)
   {
      header = interface->recv (node);

      if (header->src == static_cast<uint32_t>(source))
      {
         break;
      }
      else
      {
         interface->release_recv_buffer (header);
      }
   }

   if (header->len < static_cast<uint32_t>(count))
   {
      interface->release_recv_buffer (header);
      return -1;
   }

   unsigned char *data = reinterpret_cast<unsigned char *>(header + 1);

   memcpy (buf, data, header->len);
   status->count = header->len;
   status->MPI_SOURCE = header->src;
   interface->release_recv_buffer (header);

   return MPI_SUCCESS;
}

int MPI_Irecv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Request *request)
{
   return 0;
}

int MPI_Send(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm)
{
   net::llamaNET::Protocol_header *header = interface->get_send_buffer ();

   header->dest = dest;
   header->src = node;
   header->type = 1;
   header->seq = seq++;
   header->len = count;

   interface->send (header);

   return MPI_SUCCESS;
}

int MPI_Isend(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request)
{
   return 0;
}

int MPI_Test(MPI_Request *request, int *flag, MPI_Status *status)
{
   return 0;
}
<commit_msg>error in rank function<commit_after>/*
Copyright (c) 2013, William Magato
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ''AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holder(s) or contributors.
*/

#include <cstring>

#include <sstream>
#include <stdexcept>
#include <string>

template <typename T>
static T convert (const std::string &s)
{
   std::stringstream ss (s);
   T t;
   ss >> t;

   if (!ss.fail ())
   {
      return t;
   }

   std::stringstream err;
   err << "failed to convert string: " << s;
   throw std::runtime_error (err.str ());
}

template <typename T>
static T parse (int argc, char *argv [], const std::string &arg, const T &value)
{
   for (int i = 1; i < argc; i++)
   {
      if (arg == argv [i])
      {
         if ((i + 1) >= argc)
         {
            std::stringstream err;
            err << "missing argument value for " << arg;
            throw std::runtime_error (err.str ());
         }

         return convert<T> (argv [i + 1]);
      }
   }

   return value;
}

#include <llamaos/mpi/mpi.h>
#include <llamaos/net/llamaNET.h>
#include <llamaos/xen/Hypervisor.h>

using namespace std;
using namespace llamaos;
using namespace llamaos::xen;

static uint32_t seq = 1;

static domid_t get_domd_id (int node)
{
   // for now it's just self minus node % 6
   domid_t self_id = Hypervisor::get_instance ()->domid;

   return (self_id - 1 - (node % 6));
}

static net::llamaNET *interface = nullptr;
static int node;

int MPI_Init (int *argc, char ***argv)
{
   node = parse<int>(*argc, *argv, "--node", 0);
   interface = new net::llamaNET (get_domd_id (node), (node % 6));

   return MPI_SUCCESS;
}

int MPI_Finalize (void)
{
   delete interface;

   return MPI_SUCCESS;
}

int MPI_Comm_rank (MPI_Comm comm, int *rank)
{
   *rank = node;

   return MPI_SUCCESS;
}

int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status)
{
   net::llamaNET::Protocol_header *header;

   for (;;)
   {
      header = interface->recv (node);

      if (header->src == static_cast<uint32_t>(source))
      {
         break;
      }
      else
      {
         interface->release_recv_buffer (header);
      }
   }

   if (header->len < static_cast<uint32_t>(count))
   {
      interface->release_recv_buffer (header);
      return -1;
   }

   unsigned char *data = reinterpret_cast<unsigned char *>(header + 1);

   memcpy (buf, data, header->len);
   status->count = header->len;
   status->MPI_SOURCE = header->src;
   interface->release_recv_buffer (header);

   return MPI_SUCCESS;
}

int MPI_Irecv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Request *request)
{
   return 0;
}

int MPI_Send(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm)
{
   net::llamaNET::Protocol_header *header = interface->get_send_buffer ();

   header->dest = dest;
   header->src = node;
   header->type = 1;
   header->seq = seq++;
   header->len = count;

   interface->send (header);

   return MPI_SUCCESS;
}

int MPI_Isend(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request)
{
   return 0;
}

int MPI_Test(MPI_Request *request, int *flag, MPI_Status *status)
{
   return 0;
}
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2005 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 COPYING 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 "JoinMenu.h"

/* common implementation headers */
#include "FontManager.h"
#include "Protocol.h"
#include "StartupInfo.h"
#include "TimeKeeper.h"
#include "cURLManager.h"
#include "StateDatabase.h"
#include "Bundle.h"
#include "BundleMgr.h"

/* local implementation headers */
#include "HUDDialogStack.h"
#include "MainMenu.h"
#include "MenuDefaultKey.h"
#include "ServerMenu.h"
#include "ServerStartMenu.h"
#include "TextureManager.h"

/* from playing.h */
extern StartupInfo* getStartupInfo();
extern void joinGame();

JoinMenu* JoinMenu::activeMenu = NULL;

JoinMenu::JoinMenu() : serverStartMenu(NULL), serverMenu(NULL)
{
  // cache font face ID
  int fontFace = MainMenu::getFontFace();

  // add controls
  std::vector<HUDuiControl*>& listHUD = getControls();
  StartupInfo* info = getStartupInfo();

  HUDuiLabel* label = new HUDuiLabel;
  label->setFontFace(fontFace);
  label->setString("Join Game");
  listHUD.push_back(label);

  findServer = new HUDuiLabel;
  findServer->setFontFace(fontFace);
  findServer->setString("Find Server");
  listHUD.push_back(findServer);

  connectLabel = new HUDuiLabel;
  connectLabel->setFontFace(fontFace);
  connectLabel->setString("Connect");
  listHUD.push_back(connectLabel);

  callsign = new HUDuiTypeIn;
  callsign->setFontFace(fontFace);
  callsign->setLabel("Callsign:");
  callsign->setMaxLength(CallSignLen - 1);
  callsign->setString(info->callsign);
  listHUD.push_back(callsign);

  password = new HUDuiTypeIn;
  password->setObfuscation(true);
  password->setFontFace(fontFace);
  password->setLabel("Password:");
  password->setMaxLength(CallSignLen - 1);
  password->setString(info->password);
  listHUD.push_back(password);

  team = new HUDuiList;
  team->setFontFace(fontFace);
  team->setLabel("Team:");
  team->setCallback(teamCallback, this);
  std::vector<std::string>& teams = team->getList();
  // these do not need to be in enum order, but must match getTeam() & setTeam()
  teams.push_back(std::string(Team::getName(AutomaticTeam)));
  teams.push_back(std::string(Team::getName(RogueTeam)));
  teams.push_back(std::string(Team::getName(RedTeam)));
  teams.push_back(std::string(Team::getName(GreenTeam)));
  teams.push_back(std::string(Team::getName(BlueTeam)));
  teams.push_back(std::string(Team::getName(PurpleTeam)));
  teams.push_back(std::string(Team::getName(ObserverTeam)));
  team->update();
  setTeam(info->team);
  listHUD.push_back(team);

  teamIcon = new HUDuiTextureLabel;
  teamIcon->setFontFace(fontFace);
  teamIcon->setString(" ");
  updateTeamTexture();
  listHUD.push_back(teamIcon);

  server = new HUDuiTypeIn;
  server->setFontFace(fontFace);
  server->setLabel("Server:");
  server->setMaxLength(64);
  server->setString(info->serverName);
  listHUD.push_back(server);

  char buffer[10];
  sprintf(buffer, "%d", info->serverPort);
  port = new HUDuiTypeIn;
  port->setFontFace(fontFace);
  port->setLabel("Port:");
  port->setMaxLength(5);
  port->setString(buffer);
  listHUD.push_back(port);

  email = new HUDuiTypeIn;
  email->setFontFace(fontFace);
  email->setLabel("Email:");
  email->setMaxLength(EmailLen - 1);
  email->setString(info->email);
  listHUD.push_back(email);

  startServer = new HUDuiLabel;
  startServer->setFontFace(fontFace);
  startServer->setString("Start Server");
  listHUD.push_back(startServer);

  status = new HUDuiLabel;
  status->setFontFace(fontFace);
  status->setString("");
  listHUD.push_back(status);

  failedMessage = new HUDuiLabel;
  failedMessage->setFontFace(fontFace);
  failedMessage->setString("");
  listHUD.push_back(failedMessage);

  initNavigation(listHUD, 1, listHUD.size() - 3);

  // cut teamIcon out of the nav loop
  team->setNext(server);
  server->setPrev(team);
}

JoinMenu::~JoinMenu()
{
  delete serverStartMenu;
  delete serverMenu;
}

HUDuiDefaultKey* JoinMenu::getDefaultKey()
{
  return MenuDefaultKey::getInstance();
}

void JoinMenu::show()
{
  activeMenu = this;

  StartupInfo* info = getStartupInfo();

  // set fields
  callsign->setString(info->callsign);
  password->setString(info->password);
  setTeam(info->team);

  server->setString(info->serverName);
  char buffer[10];
  sprintf(buffer, "%d", info->serverPort);
  port->setString(buffer);

  // clear status
  setStatus("");
  setFailedMessage("");
}

void JoinMenu::dismiss()
{
  loadInfo();
  activeMenu = NULL;
}

void JoinMenu::loadInfo()
{
  // load startup info with current settings
  StartupInfo* info = getStartupInfo();
  strcpy(info->callsign, callsign->getString().c_str());
  strcpy(info->password, password->getString().c_str());
  info->team = getTeam();
  strcpy(info->serverName, server->getString().c_str());
  info->serverPort = atoi(port->getString().c_str());
  strcpy(info->email, email->getString().c_str());
}

void JoinMenu::execute()
{
  HUDuiControl* _focus = HUDui::getFocus();
  if (_focus == startServer) {

    if (!serverStartMenu) serverStartMenu = new ServerStartMenu;
    HUDDialogStack::get()->push(serverStartMenu);

  } else if (_focus == findServer) {

    if (!serverMenu) serverMenu = new ServerMenu;
    HUDDialogStack::get()->push(serverMenu);

  } else if (_focus == connectLabel) {

    // load startup info
    loadInfo();

    // make sure we've got what we need
    StartupInfo* info = getStartupInfo();
    if (info->callsign[0] == '\0') {
      setStatus("You must enter a callsign.");
      return;
    }
    if (info->serverName[0] == '\0') {
      setStatus("You must enter a server.");
      return;
    }
    if (info->serverPort <= 0 || info->serverPort > 65535) {
      char buffer[60];
      sprintf(buffer, "Port is invalid.  Try %d.", ServerPort);
      setStatus(buffer);
      return;
    }

    // let user know we're trying
    setStatus("Trying...");

    // schedule attempt to join game
    joinGame();
  }
}

void JoinMenu::setFailedMessage(const char* msg)
{
  failedMessage->setString(msg);

  FontManager &fm = FontManager::instance();
  const float _width = fm.getStrLength(MainMenu::getFontFace(),
	failedMessage->getFontSize(), failedMessage->getString());
  failedMessage->setPosition(center - 0.5f * _width, failedMessage->getY());
}

TeamColor JoinMenu::getTeam() const
{
  return team->getIndex() == 0 ? AutomaticTeam : TeamColor(team->getIndex() - 1);
}

void JoinMenu::setTeam(TeamColor teamcol)
{
  team->setIndex(teamcol == AutomaticTeam ? 0 : int(teamcol) + 1);
}

void JoinMenu::setStatus(const char* msg, const std::vector<std::string> *)
{
  status->setString(msg);
  FontManager &fm = FontManager::instance();
  const float _width = fm.getStrLength(status->getFontFace(),
		status->getFontSize(), status->getString());
  status->setPosition(center - 0.5f * _width, status->getY());
}

void JoinMenu::teamCallback(HUDuiControl*, void* source)
{
  ((JoinMenu*)source)->updateTeamTexture();
}

void JoinMenu::updateTeamTexture()
{
  TextureManager &tm = TextureManager::instance();
  FontManager &fm = FontManager::instance();

  // load the appropriate texture
  std::string texture;
  if (getTeam() == AutomaticTeam)
    texture = "automatic_";
  else
    texture = Team::getImagePrefix(getTeam());
  texture += "icon";
  int id = tm.getTextureID(texture.c_str());
  teamIcon->setTexture(id);

  // make it big enough
  teamIcon->setFontSize(team->getFontSize() * 1.5f);

  // put it at the end of the text
  Bundle *bdl = BundleMgr::getCurrentBundle();
  const float x = team->getX() + fm.getStrLength(team->getFontFace(),
	  team->getFontSize(),
	  bdl->getLocalString(team->getList()[team->getIndex()]) + "x");
  teamIcon->setPosition(x, team->getY());
}

void JoinMenu::resize(int _width, int _height)
{
  HUDDialog::resize(_width, _height);

  // use a big font for title, smaller font for the rest
  const float titleFontSize = (float)_height / 15.0f;
  const float fontSize = (float)_height / 36.0f;
  center = 0.5f * (float)_width;

  FontManager &fm = FontManager::instance();

  // reposition title
  std::vector<HUDuiControl*>& listHUD = getControls();
  HUDuiLabel* title = (HUDuiLabel*)listHUD[0];
  title->setFontSize(titleFontSize);
  const float titleWidth = fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString());
  const float titleHeight = fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, "");
  float x = 0.5f * ((float)_width - titleWidth);
  float y = (float)_height - titleHeight;
  title->setPosition(x, y);

  // reposition options
  x = 0.5f * ((float)_width - 0.5f * titleWidth);
  y -= 0.6f * titleHeight;
  listHUD[1]->setFontSize(fontSize);
  const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, "");
  const int count = listHUD.size();
  for (int i = 1; i < count; i++) {
    listHUD[i]->setFontSize(fontSize);
    listHUD[i]->setPosition(x, y);
    if (i != 5)
      y -= 1.0f * h;
    if (i <= 2 || i == 9) y -= 0.5f * h;
  }

  updateTeamTexture();
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>invalidating token, when you change either callsign or password<commit_after>/* bzflag
 * Copyright (c) 1993 - 2005 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 COPYING 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 "JoinMenu.h"

/* common implementation headers */
#include "FontManager.h"
#include "Protocol.h"
#include "StartupInfo.h"
#include "TimeKeeper.h"
#include "cURLManager.h"
#include "StateDatabase.h"
#include "Bundle.h"
#include "BundleMgr.h"

/* local implementation headers */
#include "HUDDialogStack.h"
#include "MainMenu.h"
#include "MenuDefaultKey.h"
#include "ServerMenu.h"
#include "ServerStartMenu.h"
#include "TextureManager.h"

/* from playing.h */
extern StartupInfo* getStartupInfo();
extern void joinGame();

JoinMenu* JoinMenu::activeMenu = NULL;

JoinMenu::JoinMenu() : serverStartMenu(NULL), serverMenu(NULL)
{
  // cache font face ID
  int fontFace = MainMenu::getFontFace();

  // add controls
  std::vector<HUDuiControl*>& listHUD = getControls();
  StartupInfo* info = getStartupInfo();

  HUDuiLabel* label = new HUDuiLabel;
  label->setFontFace(fontFace);
  label->setString("Join Game");
  listHUD.push_back(label);

  findServer = new HUDuiLabel;
  findServer->setFontFace(fontFace);
  findServer->setString("Find Server");
  listHUD.push_back(findServer);

  connectLabel = new HUDuiLabel;
  connectLabel->setFontFace(fontFace);
  connectLabel->setString("Connect");
  listHUD.push_back(connectLabel);

  callsign = new HUDuiTypeIn;
  callsign->setFontFace(fontFace);
  callsign->setLabel("Callsign:");
  callsign->setMaxLength(CallSignLen - 1);
  callsign->setString(info->callsign);
  listHUD.push_back(callsign);

  password = new HUDuiTypeIn;
  password->setObfuscation(true);
  password->setFontFace(fontFace);
  password->setLabel("Password:");
  password->setMaxLength(CallSignLen - 1);
  password->setString(info->password);
  listHUD.push_back(password);

  team = new HUDuiList;
  team->setFontFace(fontFace);
  team->setLabel("Team:");
  team->setCallback(teamCallback, this);
  std::vector<std::string>& teams = team->getList();
  // these do not need to be in enum order, but must match getTeam() & setTeam()
  teams.push_back(std::string(Team::getName(AutomaticTeam)));
  teams.push_back(std::string(Team::getName(RogueTeam)));
  teams.push_back(std::string(Team::getName(RedTeam)));
  teams.push_back(std::string(Team::getName(GreenTeam)));
  teams.push_back(std::string(Team::getName(BlueTeam)));
  teams.push_back(std::string(Team::getName(PurpleTeam)));
  teams.push_back(std::string(Team::getName(ObserverTeam)));
  team->update();
  setTeam(info->team);
  listHUD.push_back(team);

  teamIcon = new HUDuiTextureLabel;
  teamIcon->setFontFace(fontFace);
  teamIcon->setString(" ");
  updateTeamTexture();
  listHUD.push_back(teamIcon);

  server = new HUDuiTypeIn;
  server->setFontFace(fontFace);
  server->setLabel("Server:");
  server->setMaxLength(64);
  server->setString(info->serverName);
  listHUD.push_back(server);

  char buffer[10];
  sprintf(buffer, "%d", info->serverPort);
  port = new HUDuiTypeIn;
  port->setFontFace(fontFace);
  port->setLabel("Port:");
  port->setMaxLength(5);
  port->setString(buffer);
  listHUD.push_back(port);

  email = new HUDuiTypeIn;
  email->setFontFace(fontFace);
  email->setLabel("Email:");
  email->setMaxLength(EmailLen - 1);
  email->setString(info->email);
  listHUD.push_back(email);

  startServer = new HUDuiLabel;
  startServer->setFontFace(fontFace);
  startServer->setString("Start Server");
  listHUD.push_back(startServer);

  status = new HUDuiLabel;
  status->setFontFace(fontFace);
  status->setString("");
  listHUD.push_back(status);

  failedMessage = new HUDuiLabel;
  failedMessage->setFontFace(fontFace);
  failedMessage->setString("");
  listHUD.push_back(failedMessage);

  initNavigation(listHUD, 1, listHUD.size() - 3);

  // cut teamIcon out of the nav loop
  team->setNext(server);
  server->setPrev(team);
}

JoinMenu::~JoinMenu()
{
  delete serverStartMenu;
  delete serverMenu;
}

HUDuiDefaultKey* JoinMenu::getDefaultKey()
{
  return MenuDefaultKey::getInstance();
}

void JoinMenu::show()
{
  activeMenu = this;

  StartupInfo* info = getStartupInfo();

  // set fields
  callsign->setString(info->callsign);
  password->setString(info->password);
  setTeam(info->team);

  server->setString(info->serverName);
  char buffer[10];
  sprintf(buffer, "%d", info->serverPort);
  port->setString(buffer);

  // clear status
  setStatus("");
  setFailedMessage("");
}

void JoinMenu::dismiss()
{
  loadInfo();
  activeMenu = NULL;
}

void JoinMenu::loadInfo()
{
  // load startup info with current settings
  StartupInfo* info = getStartupInfo();
  if (strcmp(info->callsign, callsign->getString().c_str())) {
    strcpy(info->callsign, callsign->getString().c_str());
    info->token[0] = '\0';
  }
  if (strcmp(info->password, password->getString().c_str())) {
    strcpy(info->password, password->getString().c_str());
    info->token[0] = '\0';
  }
  info->team = getTeam();
  strcpy(info->serverName, server->getString().c_str());
  info->serverPort = atoi(port->getString().c_str());
  strcpy(info->email, email->getString().c_str());
}

void JoinMenu::execute()
{
  HUDuiControl* _focus = HUDui::getFocus();
  if (_focus == startServer) {

    if (!serverStartMenu) serverStartMenu = new ServerStartMenu;
    HUDDialogStack::get()->push(serverStartMenu);

  } else if (_focus == findServer) {

    if (!serverMenu) serverMenu = new ServerMenu;
    HUDDialogStack::get()->push(serverMenu);

  } else if (_focus == connectLabel) {

    // load startup info
    loadInfo();

    // make sure we've got what we need
    StartupInfo* info = getStartupInfo();
    if (info->callsign[0] == '\0') {
      setStatus("You must enter a callsign.");
      return;
    }
    if (info->serverName[0] == '\0') {
      setStatus("You must enter a server.");
      return;
    }
    if (info->serverPort <= 0 || info->serverPort > 65535) {
      char buffer[60];
      sprintf(buffer, "Port is invalid.  Try %d.", ServerPort);
      setStatus(buffer);
      return;
    }

    // let user know we're trying
    setStatus("Trying...");

    // schedule attempt to join game
    joinGame();
  }
}

void JoinMenu::setFailedMessage(const char* msg)
{
  failedMessage->setString(msg);

  FontManager &fm = FontManager::instance();
  const float _width = fm.getStrLength(MainMenu::getFontFace(),
	failedMessage->getFontSize(), failedMessage->getString());
  failedMessage->setPosition(center - 0.5f * _width, failedMessage->getY());
}

TeamColor JoinMenu::getTeam() const
{
  return team->getIndex() == 0 ? AutomaticTeam : TeamColor(team->getIndex() - 1);
}

void JoinMenu::setTeam(TeamColor teamcol)
{
  team->setIndex(teamcol == AutomaticTeam ? 0 : int(teamcol) + 1);
}

void JoinMenu::setStatus(const char* msg, const std::vector<std::string> *)
{
  status->setString(msg);
  FontManager &fm = FontManager::instance();
  const float _width = fm.getStrLength(status->getFontFace(),
		status->getFontSize(), status->getString());
  status->setPosition(center - 0.5f * _width, status->getY());
}

void JoinMenu::teamCallback(HUDuiControl*, void* source)
{
  ((JoinMenu*)source)->updateTeamTexture();
}

void JoinMenu::updateTeamTexture()
{
  TextureManager &tm = TextureManager::instance();
  FontManager &fm = FontManager::instance();

  // load the appropriate texture
  std::string texture;
  if (getTeam() == AutomaticTeam)
    texture = "automatic_";
  else
    texture = Team::getImagePrefix(getTeam());
  texture += "icon";
  int id = tm.getTextureID(texture.c_str());
  teamIcon->setTexture(id);

  // make it big enough
  teamIcon->setFontSize(team->getFontSize() * 1.5f);

  // put it at the end of the text
  Bundle *bdl = BundleMgr::getCurrentBundle();
  const float x = team->getX() + fm.getStrLength(team->getFontFace(),
	  team->getFontSize(),
	  bdl->getLocalString(team->getList()[team->getIndex()]) + "x");
  teamIcon->setPosition(x, team->getY());
}

void JoinMenu::resize(int _width, int _height)
{
  HUDDialog::resize(_width, _height);

  // use a big font for title, smaller font for the rest
  const float titleFontSize = (float)_height / 15.0f;
  const float fontSize = (float)_height / 36.0f;
  center = 0.5f * (float)_width;

  FontManager &fm = FontManager::instance();

  // reposition title
  std::vector<HUDuiControl*>& listHUD = getControls();
  HUDuiLabel* title = (HUDuiLabel*)listHUD[0];
  title->setFontSize(titleFontSize);
  const float titleWidth = fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString());
  const float titleHeight = fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, "");
  float x = 0.5f * ((float)_width - titleWidth);
  float y = (float)_height - titleHeight;
  title->setPosition(x, y);

  // reposition options
  x = 0.5f * ((float)_width - 0.5f * titleWidth);
  y -= 0.6f * titleHeight;
  listHUD[1]->setFontSize(fontSize);
  const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, "");
  const int count = listHUD.size();
  for (int i = 1; i < count; i++) {
    listHUD[i]->setFontSize(fontSize);
    listHUD[i]->setPosition(x, y);
    if (i != 5)
      y -= 1.0f * h;
    if (i <= 2 || i == 9) y -= 0.5f * h;
  }

  updateTeamTexture();
}

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


<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 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 COPYING 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.
*/

#include "common.h"

/* class interface header */
#include "bzfs.h"
#include "bzfsEvents.h"
#include "GameKeeper.h"

extern void sendMessage(int playerIndex, PlayerId dstPlayer, const char *message);

// ----------------- SpreeTracker-----------------

/*typedef struct
{
	int playerID;
	std::string callsign;
	double		startTime;
	double		lastUpdateTime;
	int			spreeTotal;
}trPlayerHistoryRecord;

std::map<int, trPlayerHistoryRecord > playerList; */

PlayHistoryTracker::PlayHistoryTracker()
{

}

PlayHistoryTracker::~PlayHistoryTracker()
{

}

void PlayHistoryTracker::process ( BaseEventData *eventData )
{
	switch (eventData->eventType)
	{
		case eNullEvent:
		case eZoneEntryEvent:
		case eCaptureEvent:
		case eZoneExitEvent:
			// really WTF!!!!
			break;

		case ePlayerDieEvent:
			{
				PlayerDieEventData	*deathRecord = (PlayerDieEventData*)eventData;

				GameKeeper::Player *killerData = GameKeeper::Player::getPlayerByIndex(deathRecord->killerID);
				//GameKeeper::Player *victimData = GameKeeper::Player::getPlayerByIndex(deathRecord->playerID);

				// clear out the dude who got shot, since he won't be having any SPREEs
				if (playerList.find(deathRecord->playerID) != playerList.end())
				{
					trPlayerHistoryRecord	&record = playerList.find(deathRecord->playerID)->second;
					std::string message;
					if ( record.spreeTotal >= 5 && record.spreeTotal < 10 )
						message = record.callsign + std::string("'s rampage was stoped by ") + std::string(killerData->player.getCallSign());
					if ( record.spreeTotal >= 10 && record.spreeTotal < 20 )
						message = record.callsign + std::string("'s killing spree was halted by ") + std::string(killerData->player.getCallSign());
					if ( record.spreeTotal >= 20 )
						message = std::string("The unstopable reign of ") + record.callsign + std::string(" was ended by ") + std::string(killerData->player.getCallSign());

					if (message.size())
						sendMessage(ServerPlayer, AllPlayers, message.c_str());

					record.spreeTotal = 0;
					record.startTime = deathRecord->time;
					record.lastUpdateTime = deathRecord->time;

				}

				// chock up another win for our killer
				// if they weren't the same as the killer ( suicide ).
				if ( (deathRecord->playerID != deathRecord->killerID) && playerList.find(deathRecord->killerID) != playerList.end())
				{
					trPlayerHistoryRecord	&record = playerList.find(deathRecord->killerID)->second;
					record.spreeTotal++;
					record.lastUpdateTime = deathRecord->time;

					std::string message;

					if ( record.spreeTotal > 5 )
						message = record.callsign + std::string(" is on a Rampage!");
					if ( record.spreeTotal > 10 )
						message = record.callsign + std::string(" is on a Killing Spree!");
					if ( record.spreeTotal > 20 )
						message = record.callsign + std::string(" is Unstoppable!!");

					if (message.size())
						sendMessage(ServerPlayer, AllPlayers, message.c_str());
				}
			}
			break;

		case ePlayerSpawnEvent:
			// really WTF!!!!
			break;

		case ePlayerJoinEvent:
			{
				trPlayerHistoryRecord	playerRecord;

				playerRecord.playerID = ((PlayerJoinPartEventData*)eventData)->playerID;
				playerRecord.callsign = ((PlayerJoinPartEventData*)eventData)->callsign;
				playerRecord.spreeTotal = 0;
				playerRecord.lastUpdateTime = ((PlayerJoinPartEventData*)eventData)->time;
				playerRecord.startTime = playerRecord.lastUpdateTime;

				playerList[((PlayerJoinPartEventData*)eventData)->playerID] = playerRecord;
			}
			break;
		case ePlayerPartEvent:
			{
				std::map<int, trPlayerHistoryRecord >::iterator	itr = playerList.find( ((PlayerJoinPartEventData*)eventData)->playerID );
				if (itr != playerList.end())
					playerList.erase(itr);
			}
			break;
	}
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>make the play history messages come out on the right kill numbers.<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 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 COPYING 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.
*/

#include "common.h"

/* class interface header */
#include "bzfs.h"
#include "bzfsEvents.h"
#include "GameKeeper.h"

extern void sendMessage(int playerIndex, PlayerId dstPlayer, const char *message);

// ----------------- SpreeTracker-----------------

/*typedef struct
{
	int playerID;
	std::string callsign;
	double		startTime;
	double		lastUpdateTime;
	int			spreeTotal;
}trPlayerHistoryRecord;

std::map<int, trPlayerHistoryRecord > playerList; */

PlayHistoryTracker::PlayHistoryTracker()
{

}

PlayHistoryTracker::~PlayHistoryTracker()
{

}

void PlayHistoryTracker::process ( BaseEventData *eventData )
{
	switch (eventData->eventType)
	{
		case eNullEvent:
		case eZoneEntryEvent:
		case eCaptureEvent:
		case eZoneExitEvent:
			// really WTF!!!!
			break;

		case ePlayerDieEvent:
			{
				PlayerDieEventData	*deathRecord = (PlayerDieEventData*)eventData;

				GameKeeper::Player *killerData = GameKeeper::Player::getPlayerByIndex(deathRecord->killerID);
				//GameKeeper::Player *victimData = GameKeeper::Player::getPlayerByIndex(deathRecord->playerID);

				// clear out the dude who got shot, since he won't be having any SPREEs
				if (playerList.find(deathRecord->playerID) != playerList.end())
				{
					trPlayerHistoryRecord	&record = playerList.find(deathRecord->playerID)->second;
					std::string message;
					if ( record.spreeTotal >= 5 && record.spreeTotal < 10 )
						message = record.callsign + std::string("'s rampage was stoped by ") + std::string(killerData->player.getCallSign());
					if ( record.spreeTotal >= 10 && record.spreeTotal < 20 )
						message = record.callsign + std::string("'s killing spree was halted by ") + std::string(killerData->player.getCallSign());
					if ( record.spreeTotal >= 20 )
						message = std::string("The unstopable reign of ") + record.callsign + std::string(" was ended by ") + std::string(killerData->player.getCallSign());

					if (message.size())
						sendMessage(ServerPlayer, AllPlayers, message.c_str());

					record.spreeTotal = 0;
					record.startTime = deathRecord->time;
					record.lastUpdateTime = deathRecord->time;

				}

				// chock up another win for our killer
				// if they weren't the same as the killer ( suicide ).
				if ( (deathRecord->playerID != deathRecord->killerID) && playerList.find(deathRecord->killerID) != playerList.end())
				{
					trPlayerHistoryRecord	&record = playerList.find(deathRecord->killerID)->second;
					record.spreeTotal++;
					record.lastUpdateTime = deathRecord->time;

					std::string message;

					if ( record.spreeTotal == 5 )
						message = record.callsign + std::string(" is on a Rampage!");
					if ( record.spreeTotal == 10 )
						message = record.callsign + std::string(" is on a Killing Spree!");
					if ( record.spreeTotal == 20 )
						message = record.callsign + std::string(" is Unstoppable!!");
					if ( record.spreeTotal > 20 && record.spreeTotal%5 == 0 )
						message = record.callsign + std::string("'s continues rage");

					if (message.size())
						sendMessage(ServerPlayer, AllPlayers, message.c_str());
				}
			}
			break;

		case ePlayerSpawnEvent:
			// really WTF!!!!
			break;

		case ePlayerJoinEvent:
			{
				trPlayerHistoryRecord	playerRecord;

				playerRecord.playerID = ((PlayerJoinPartEventData*)eventData)->playerID;
				playerRecord.callsign = ((PlayerJoinPartEventData*)eventData)->callsign;
				playerRecord.spreeTotal = 0;
				playerRecord.lastUpdateTime = ((PlayerJoinPartEventData*)eventData)->time;
				playerRecord.startTime = playerRecord.lastUpdateTime;

				playerList[((PlayerJoinPartEventData*)eventData)->playerID] = playerRecord;
			}
			break;
		case ePlayerPartEvent:
			{
				std::map<int, trPlayerHistoryRecord >::iterator	itr = playerList.find( ((PlayerJoinPartEventData*)eventData)->playerID );
				if (itr != playerList.end())
					playerList.erase(itr);
			}
			break;
	}
}

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