<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: bootstrap.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 09:03:32 $
 *
 *  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 _CPPUHELPER_BOOTSTRAP_HXX_
#define _CPPUHELPER_BOOTSTRAP_HXX_

#include <com/sun/star/container/XHierarchicalNameAccess.hpp>
#include <com/sun/star/registry/XSimpleRegistry.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>

namespace cppu
{

/** Creates a simple registry service instance.

    @rBootstrapPath optional bootstrap path for initial components
    @return simple registry service instance
*/
::com::sun::star::uno::Reference< ::com::sun::star::registry::XSimpleRegistry >
SAL_CALL createSimpleRegistry(
    const ::rtl::OUString & rBootstrapPath = ::rtl::OUString() )
    SAL_THROW( () );

/** Creates a nested registry service instance.

    @rBootstrapPath optional bootstrap path for initial components
    @return nested registry service instance
*/
::com::sun::star::uno::Reference< ::com::sun::star::registry::XSimpleRegistry >
SAL_CALL createNestedRegistry(
    const ::rtl::OUString & rBootstrapPath = ::rtl::OUString() )
    SAL_THROW( () );

/** Installs type description manager instance, i.e. registers a callback at cppu core.

    @param xTDMgr manager instance
    @return true, if successfully registered
*/
sal_Bool SAL_CALL installTypeDescriptionManager(
    ::com::sun::star::uno::Reference< ::com::sun::star::container::XHierarchicalNameAccess > const & xTDMgr )
    SAL_THROW( () );

/** Bootstraps an initial component context with service manager upon a given registry.
    This includes insertion of initial services:
      - (registry) service manager, shared lib loader,
      - simple registry, nested registry,
      - implementation registration
      - registry typedescription provider, typedescription manager (also installs it into cppu core)

    @param xRegistry registry for service manager and singleton objects of context (may be null)
    @param rBootstrapPath optional bootstrap path for initial components
    @return component context
*/
::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > SAL_CALL
bootstrap_InitialComponentContext(
    ::com::sun::star::uno::Reference< ::com::sun::star::registry::XSimpleRegistry > const & xRegistry,
    ::rtl::OUString const & rBootstrapPath = ::rtl::OUString() )
    SAL_THROW( (::com::sun::star::uno::Exception) );

/** Bootstraps an initial component context with service manager upon default types and
    services registry.
    This includes insertion of initial services:
      - (registry) service manager, shared lib loader,
      - simple registry, nested registry,
      - implementation registration
      - registry typedescription provider, typedescription manager (also installs it into cppu core)

    This function tries to find its parameters via these bootstrap variables:

      - UNO_TYPES         -- a space separated list of file urls of type rdbs
      - UNO_SERVICES      -- a space separated list of file urls of service rdbs
      - UNO_WRITERDB      -- a file url of a write rdb (e.g. user.rdb)

    Please look at http://udk.openoffice.org/common/man/concept/uno_default_bootstrapping.html
    for further info.

    @return component context
*/
::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > SAL_CALL
defaultBootstrap_InitialComponentContext() SAL_THROW( (::com::sun::star::uno::Exception) );

/** Bootstraps an initial component context with service manager upon default types and
    services registry.
    This includes insertion of initial services:
      - (registry) service manager, shared lib loader,
      - simple registry, nested registry,
      - implementation registration
      - registry typedescription provider, typedescription manager (also installs it into cppu core)

    This function tries to find its parameters via these bootstrap variables:

      - UNO_TYPES         -- a space separated list of file urls of type rdbs
      - UNO_SERVICES      -- a space separated list of file urls of service rdbs
      - UNO_WRITERDB      -- a file url of a write rdb (e.g. user.rdb)

    Please look at http://udk.openoffice.org/common/man/concept/uno_default_bootstrapping.html
    for further info.

    @param iniFile ini filename to get bootstrap variables
    @return component context
*/
::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > SAL_CALL
defaultBootstrap_InitialComponentContext(const ::rtl::OUString & iniFile) SAL_THROW( (::com::sun::star::uno::Exception) );

/**
 * An exception indicating a bootstrap error.
 *
 * @since UDK 3.2.0
 */
class BootstrapException
{
public:
    /**
     * Constructs a BootstrapException.
     */
    BootstrapException();

    /**
     * Constructs a BootstrapException with the specified detail message.
     *
     * @param rMessage
     * A message containing any details about the exception.
     */
    BootstrapException( const ::rtl::OUString & rMessage );

    /**
     * Copy constructs a BootstrapException.
     */
    BootstrapException( const BootstrapException & e );

    /**
     * Destructs a BootstrapException.
     */
    virtual ~BootstrapException();

    /**
     * Assigns a BootstrapException.
     */
    BootstrapException & operator=( const BootstrapException & e );

    /** Gets the message.

        @return
        A reference to the message. The reference is valid for the lifetime of
        this BootstrapException.
     */
    const ::rtl::OUString & getMessage() const;

private:
    ::rtl::OUString m_aMessage;
};

/**
 * Bootstraps the component context from a UNO installation.
 *
 * @return a bootstrapped component context
 * @exception BootstrapException
 * Thrown in case bootstrap() signals an exception due to a
 * bootstrap error.
 *
 * @since UDK 3.2.0
 */
::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >
SAL_CALL bootstrap();

} // end namespace cppu

#endif
<commit_msg>INTEGRATION: CWS sb71 (1.10.96); FILE MERGED 2007/06/26 15:24:33 sb 1.10.96.2: #i75466# Retargeted from OOo 2.3 to 2.4. 2007/04/16 13:22:01 sb 1.10.96.1: #i75466# New bootstrap_expandUri helper.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: bootstrap.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: vg $ $Date: 2007-10-15 11:51:59 $
 *
 *  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 _CPPUHELPER_BOOTSTRAP_HXX_
#define _CPPUHELPER_BOOTSTRAP_HXX_

#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif

#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_
#include "com/sun/star/uno/Exception.hpp"
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include "com/sun/star/uno/Reference.hxx"
#endif
#ifndef _RTL_USTRING_HXX_
#include "rtl/ustring.hxx"
#endif
#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif

namespace com { namespace sun { namespace star {
    namespace container { class XHierarchicalNameAccess; }
    namespace registry { class XSimpleRegistry; }
    namespace uno { class XComponentContext; }
} } }

namespace cppu
{

/** Creates a simple registry service instance.

    @rBootstrapPath optional bootstrap path for initial components
    @return simple registry service instance
*/
::com::sun::star::uno::Reference< ::com::sun::star::registry::XSimpleRegistry >
SAL_CALL createSimpleRegistry(
    const ::rtl::OUString & rBootstrapPath = ::rtl::OUString() )
    SAL_THROW( () );

/** Creates a nested registry service instance.

    @rBootstrapPath optional bootstrap path for initial components
    @return nested registry service instance
*/
::com::sun::star::uno::Reference< ::com::sun::star::registry::XSimpleRegistry >
SAL_CALL createNestedRegistry(
    const ::rtl::OUString & rBootstrapPath = ::rtl::OUString() )
    SAL_THROW( () );

/** Installs type description manager instance, i.e. registers a callback at cppu core.

    @param xTDMgr manager instance
    @return true, if successfully registered
*/
sal_Bool SAL_CALL installTypeDescriptionManager(
    ::com::sun::star::uno::Reference< ::com::sun::star::container::XHierarchicalNameAccess > const & xTDMgr )
    SAL_THROW( () );

/** Bootstraps an initial component context with service manager upon a given registry.
    This includes insertion of initial services:
      - (registry) service manager, shared lib loader,
      - simple registry, nested registry,
      - implementation registration
      - registry typedescription provider, typedescription manager (also installs it into cppu core)

    @param xRegistry registry for service manager and singleton objects of context (may be null)
    @param rBootstrapPath optional bootstrap path for initial components
    @return component context
*/
::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > SAL_CALL
bootstrap_InitialComponentContext(
    ::com::sun::star::uno::Reference< ::com::sun::star::registry::XSimpleRegistry > const & xRegistry,
    ::rtl::OUString const & rBootstrapPath = ::rtl::OUString() )
    SAL_THROW( (::com::sun::star::uno::Exception) );

/** Bootstraps an initial component context with service manager upon default types and
    services registry.
    This includes insertion of initial services:
      - (registry) service manager, shared lib loader,
      - simple registry, nested registry,
      - implementation registration
      - registry typedescription provider, typedescription manager (also installs it into cppu core)

    This function tries to find its parameters via these bootstrap variables:

      - UNO_TYPES         -- a space separated list of file urls of type rdbs
      - UNO_SERVICES      -- a space separated list of file urls of service rdbs
      - UNO_WRITERDB      -- a file url of a write rdb (e.g. user.rdb)

    Please look at http://udk.openoffice.org/common/man/concept/uno_default_bootstrapping.html
    for further info.

    @return component context
*/
::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > SAL_CALL
defaultBootstrap_InitialComponentContext() SAL_THROW( (::com::sun::star::uno::Exception) );

/** Bootstraps an initial component context with service manager upon default types and
    services registry.
    This includes insertion of initial services:
      - (registry) service manager, shared lib loader,
      - simple registry, nested registry,
      - implementation registration
      - registry typedescription provider, typedescription manager (also installs it into cppu core)

    This function tries to find its parameters via these bootstrap variables:

      - UNO_TYPES         -- a space separated list of file urls of type rdbs
      - UNO_SERVICES      -- a space separated list of file urls of service rdbs
      - UNO_WRITERDB      -- a file url of a write rdb (e.g. user.rdb)

    Please look at http://udk.openoffice.org/common/man/concept/uno_default_bootstrapping.html
    for further info.

    @param iniFile ini filename to get bootstrap variables
    @return component context
*/
::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > SAL_CALL
defaultBootstrap_InitialComponentContext(const ::rtl::OUString & iniFile) SAL_THROW( (::com::sun::star::uno::Exception) );

/**
 * An exception indicating a bootstrap error.
 *
 * @since UDK 3.2.0
 */
class BootstrapException
{
public:
    /**
     * Constructs a BootstrapException.
     */
    BootstrapException();

    /**
     * Constructs a BootstrapException with the specified detail message.
     *
     * @param rMessage
     * A message containing any details about the exception.
     */
    BootstrapException( const ::rtl::OUString & rMessage );

    /**
     * Copy constructs a BootstrapException.
     */
    BootstrapException( const BootstrapException & e );

    /**
     * Destructs a BootstrapException.
     */
    virtual ~BootstrapException();

    /**
     * Assigns a BootstrapException.
     */
    BootstrapException & operator=( const BootstrapException & e );

    /** Gets the message.

        @return
        A reference to the message. The reference is valid for the lifetime of
        this BootstrapException.
     */
    const ::rtl::OUString & getMessage() const;

private:
    ::rtl::OUString m_aMessage;
};

/**
 * Bootstraps the component context from a UNO installation.
 *
 * @return a bootstrapped component context
 * @exception BootstrapException
 * Thrown in case bootstrap() signals an exception due to a
 * bootstrap error.
 *
 * @since UDK 3.2.0
 */
::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >
SAL_CALL bootstrap();

/**
 * Helper function to expand vnd.sun.star.expand URLs in contexts where no
 * properly bootstrapped UNO is (yet) available.
 *
 * @internal
 *
 * @param uri
 * Some URI (but not a URI reference).
 *
 * @return
 * If uri is a vnd.sun.star.expand URL, then the expansion of that URL is
 * returned; expansion may lead to a string that is not a legal URI. Otherwise,
 * the uri is returned unchanged.
 *
 * @exception com::sun::star::lang::IllegalArgumentException
 * If uri is a vnd.sun.star.expand URL that contains unknown macros.
 *
 * @since UDK 3.2.8
 */
::rtl::OUString
SAL_CALL bootstrap_expandUri(::rtl::OUString const & uri);

} // end namespace cppu

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: marktree.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: oj $ $Date: 2002-04-29 08:49:26 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBAUI_MARKTREE_HXX_
#include "marktree.hxx"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_RESOURCE_HRC_
#include "dbu_resource.hrc"
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

//.........................................................................
namespace dbaui
{
//.........................................................................

//========================================================================
//= OMarkableTreeListBox
//========================================================================
//------------------------------------------------------------------------
OMarkableTreeListBox::OMarkableTreeListBox( Window* pParent, WinBits nWinStyle ) : SvTreeListBox(pParent,nWinStyle)
{
    InitButtonData();
}
//------------------------------------------------------------------------
OMarkableTreeListBox::OMarkableTreeListBox( Window* pParent, const ResId& rResId) : SvTreeListBox(pParent,rResId)
{
    InitButtonData();
}
//------------------------------------------------------------------------
OMarkableTreeListBox::~OMarkableTreeListBox()
{
    delete m_pCheckButton;
}
// -----------------------------------------------------------------------------
void OMarkableTreeListBox::notifyHiContrastChanged()
{
    OSL_ENSURE(m_pCheckButton,"No CheckButton!");
    sal_Bool bHiContrast = GetBackground().GetColor().IsDark();
    m_pCheckButton->aBmps[SV_BMP_UNCHECKED]     = Bitmap( ResId( bHiContrast ? BMP_CHECKBUTTON_UNCHECKED_SCH  : BMP_CHECKBUTTON_UNCHECKED ) );
    m_pCheckButton->aBmps[SV_BMP_CHECKED]       = Bitmap( ResId( bHiContrast ? BMP_CHECKBUTTON_CHECKED_SCH    : BMP_CHECKBUTTON_CHECKED ) );
    m_pCheckButton->aBmps[SV_BMP_HICHECKED]     = Bitmap( ResId( bHiContrast ? BMP_CHECKBUTTON_HICHECKED_SCH  : BMP_CHECKBUTTON_HICHECKED ) );
    m_pCheckButton->aBmps[SV_BMP_HIUNCHECKED]   = Bitmap( ResId( bHiContrast ? BMP_CHECKBUTTON_UNCHECKED_SCH  : BMP_CHECKBUTTON_UNCHECKED ) );
    m_pCheckButton->aBmps[SV_BMP_TRISTATE]      = Bitmap( ResId( bHiContrast ? BMP_CHECKBUTTON_TRISTATE_SCH   : BMP_CHECKBUTTON_TRISTATE ) );
    m_pCheckButton->aBmps[SV_BMP_HITRISTATE]    = Bitmap( ResId( bHiContrast ? BMP_CHECKBUTTON_HITRISTATE_SCH : BMP_CHECKBUTTON_HITRISTATE ) );
}
//------------------------------------------------------------------------
void OMarkableTreeListBox::Paint(const Rectangle& _rRect)
{
    if (!IsEnabled())
    {
        Font aOldFont = GetFont();
        Font aNewFont(aOldFont);

        StyleSettings aSystemStyle = Application::GetSettings().GetStyleSettings();
        aNewFont.SetColor(aSystemStyle.GetDisableColor());

        SetFont(aNewFont);
        SvTreeListBox::Paint(_rRect);
        SetFont(aOldFont);
    }
    else
        SvTreeListBox::Paint(_rRect);
}
//------------------------------------------------------------------------
void OMarkableTreeListBox::InitButtonData()
{
    sal_Bool bHiContrast = GetBackground().GetColor().IsDark();
    SetNodeBitmaps( Bitmap(ModuleRes( bHiContrast ? BMP_PLUSBUTTON_SCH : BMP_PLUSBUTTON)),
        Bitmap(ModuleRes( bHiContrast ? BMP_MINUSBUTTON_SCH : BMP_MINUSBUTTON)));

    m_pCheckButton = new SvLBoxButtonData();
    OMarkableTreeListBox::notifyHiContrastChanged();
    EnableCheckButton( m_pCheckButton );
}
//------------------------------------------------------------------------
void OMarkableTreeListBox::KeyInput( const KeyEvent& rKEvt )
{
    // nur wenn space
    if (rKEvt.GetKeyCode().GetCode() == KEY_SPACE && !rKEvt.GetKeyCode().IsShift() && !rKEvt.GetKeyCode().IsMod1())
    {
        SvLBoxEntry* pHdlEntry = GetHdlEntry();
        if(pHdlEntry)
        {
            SvButtonState eState = GetCheckButtonState( pHdlEntry);
            if(eState == SV_BUTTON_CHECKED)
                SetCheckButtonState( pHdlEntry,SV_BUTTON_UNCHECKED);
            else
                SetCheckButtonState( pHdlEntry,SV_BUTTON_CHECKED);

            CheckButtonHdl();
        }
        else
            SvTreeListBox::KeyInput(rKEvt);
    }
    else
        SvTreeListBox::KeyInput(rKEvt);

}
//------------------------------------------------------------------------
SvButtonState OMarkableTreeListBox::implDetermineState(SvLBoxEntry* _pEntry)
{
    SvButtonState eState = GetCheckButtonState(_pEntry);
    if (!GetModel()->HasChilds(_pEntry))
        // nothing to do in this bottom-up routine if there are no children ...
        return eState;
#ifdef DBG_UTIL
    String sEntryText = GetEntryText(_pEntry);
#endif

    // loop through the children and check their states
    sal_uInt16 nCheckedChildren = 0;
    sal_uInt16 nChildrenOverall = 0;

    SvLBoxEntry* pChildLoop = GetModel()->FirstChild(_pEntry);
    while (pChildLoop)
    {
#ifdef DBG_UTIL
        String sChildText = GetEntryText(pChildLoop);
#endif
        SvButtonState eChildState = implDetermineState(pChildLoop);
        if (SV_BUTTON_TRISTATE == eChildState)
            break;

        if (SV_BUTTON_CHECKED == eChildState)
            ++nCheckedChildren;
        ++nChildrenOverall;

        pChildLoop = GetModel()->NextSibling(pChildLoop);
    }

    if (pChildLoop)
    {
        // we did not finish the loop because at least one of the children is in tristate
        eState = SV_BUTTON_TRISTATE;

        // but this means that we did not finish all the siblings of pChildLoop, so their checking may be
        // incorrect at the moment
        // -> correct this
        // 88485 - 20.06.2001 - frank.schoenheit@sun.com
        while (pChildLoop)
        {
            implDetermineState(pChildLoop);
            pChildLoop = GetModel()->NextSibling(pChildLoop);
        }
    }
    else
        // none if the children is in tristate
        if (nCheckedChildren)
            // we have at least one chil checked
            if (nCheckedChildren != nChildrenOverall)
                // not all children are checked
                eState = SV_BUTTON_TRISTATE;
            else
                // all children are checked
                eState = SV_BUTTON_CHECKED;
        else
            // no children are checked
            eState = SV_BUTTON_UNCHECKED;

    // finally set the entry to the state we just determined
    SetCheckButtonState(_pEntry, eState);

    // outta here
    return eState;
}

//------------------------------------------------------------------------
void OMarkableTreeListBox::CheckButtons()
{
    SvLBoxEntry* pEntry = GetModel()->First();
    while (pEntry)
    {
        implDetermineState(pEntry);
        pEntry = GetModel()->NextSibling(pEntry);
    }

#if 0
    // Plausibilit"atspr"ufung
    SvButtonState eState;
    SvLBoxEntry* pEntry = GetModel()->First();
    while(pEntry)
    {
        if(!GetModel()->HasChilds(pEntry))
        {
            sal_uInt16 nCheck=0;
            sal_uInt16 nCount=0;
            SvLBoxEntry* pChildEntry = pEntry;
            while(pChildEntry)
            {
                if(GetCheckButtonState(pChildEntry) == SV_BUTTON_CHECKED)
                    nCheck++;
                nCount++;
                pChildEntry = GetModel()->NextSibling(pChildEntry);
            }

            if(nCheck && nCount != nCheck)
                eState = SV_BUTTON_TRISTATE;
            else if(nCheck)
                eState = SV_BUTTON_CHECKED;
            else
                eState = SV_BUTTON_UNCHECKED;

            SvLBoxEntry* pSchema = GetModel()->GetParent(pEntry);
            if(pSchema)
            {
                pEntry = GetModel()->NextSibling(pSchema);
                SetCheckButtonState(pSchema, eState);
            }
            else
                pEntry = NULL; // wenn kein Schema dann sind bereits alle pEntry's durchlaufen worden
        }
        else
            pEntry = GetModel()->Next(pEntry);
    }

    SvLBoxEntry* pCatalog = GetModel()->First();
    SvLBoxEntry* pSchema = NULL;
    if(GetModel()->HasChilds(pCatalog) && GetModel()->HasChilds(pSchema = GetModel()->Next(pCatalog)))
    {
        sal_uInt16 nCheck   =0;
        sal_uInt16 nTri     =0;
        sal_uInt16 nCount   =0;
        while(pSchema)
        {
            if((eState = GetCheckButtonState(pSchema)) == SV_BUTTON_TRISTATE)
                break;

            if(eState == SV_BUTTON_CHECKED)
                nCheck++;
            nCount++;
            pSchema = GetModel()->NextSibling(pSchema);
        }

        if(eState != SV_BUTTON_TRISTATE)
        {
            if(nCheck && nCount == nCheck)
                eState = SV_BUTTON_CHECKED;
            else if(nCheck)
                eState = SV_BUTTON_TRISTATE;
            else
                eState = SV_BUTTON_UNCHECKED;
        }
        SetCheckButtonState( pCatalog,eState);
    }
#endif
}
//------------------------------------------------------------------------
void OMarkableTreeListBox::CheckButtonHdl()
{
    checkedButton_noBroadcast(GetHdlEntry());
    if (m_aCheckButtonHandler.IsSet())
        m_aCheckButtonHandler.Call(this);
}

//------------------------------------------------------------------------
void OMarkableTreeListBox::checkedButton_noBroadcast(SvLBoxEntry* _pEntry)
{
    SvButtonState eState = GetCheckButtonState( _pEntry);
    if (GetModel()->HasChilds(_pEntry)) // Falls Kinder, dann diese auch checken
    {
        SvLBoxEntry* pChildEntry = GetModel()->Next(_pEntry);
        SvLBoxEntry* pSiblingEntry = GetModel()->NextSibling(_pEntry);
        while(pChildEntry && pChildEntry != pSiblingEntry)
        {
            SetCheckButtonState(pChildEntry, eState);
            pChildEntry = GetModel()->Next(pChildEntry);
        }
    }

    SvLBoxEntry* pEntry = IsSelected(_pEntry) ? FirstSelected() : NULL;
    while(pEntry)
    {
        SetCheckButtonState(pEntry,eState);
        if(GetModel()->HasChilds(pEntry))   // Falls Kinder, dann diese auch checken
        {
            SvLBoxEntry* pChildEntry = GetModel()->Next(pEntry);
            SvLBoxEntry* pSiblingEntry = GetModel()->NextSibling(pEntry);
            while(pChildEntry && pChildEntry != pSiblingEntry)
            {
                SetCheckButtonState(pChildEntry,eState);
                pChildEntry = GetModel()->Next(pChildEntry);
            }
        }
        pEntry = NextSelected(pEntry);
    }
    CheckButtons();
}

//------------------------------------------------------------------------
SvLBoxEntry* OMarkableTreeListBox::GetEntryPosByName(const String& aName,SvLBoxEntry* pStart) const
{
    SvLBoxEntry* pEntry = pStart ? GetModel()->FirstChild(pStart) : GetModel()->First();
    while(pEntry && !GetEntryText(pEntry).Equals(aName))
        pEntry = GetModel()->Next(pEntry);

    return pEntry;
}

//.........................................................................
}   // namespace dbaui
//.........................................................................

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.5  2001/06/20 09:53:46  fs
 *  #88485# corrected implDetermineState for a special case
 *
 *  Revision 1.4  2001/04/27 08:10:27  fs
 *  +implDeterminedState - needed to correctly implement CheckButtons
 *
 *  Revision 1.3  2001/01/30 08:30:11  fs
 *  +checkedButton_noBroadcast
 *
 *  Revision 1.2  2000/10/09 12:34:33  fs
 *  use a different font when painting a disabled control
 *
 *  Revision 1.1  2000/10/05 10:00:43  fs
 *  initial checkin
 *
 *
 *  Revision 1.0 28.09.00 13:22:30  fs
 ************************************************************************/

<commit_msg>#99251# use of default images from SvLBoxButtonData<commit_after>/*************************************************************************
 *
 *  $RCSfile: marktree.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: gt $ $Date: 2002-05-24 09:54:45 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBAUI_MARKTREE_HXX_
#include "marktree.hxx"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_RESOURCE_HRC_
#include "dbu_resource.hrc"
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

//.........................................................................
namespace dbaui
{
//.........................................................................

//========================================================================
//= OMarkableTreeListBox
//========================================================================
//------------------------------------------------------------------------
OMarkableTreeListBox::OMarkableTreeListBox( Window* pParent, WinBits nWinStyle ) : SvTreeListBox(pParent,nWinStyle)
{
    InitButtonData();
}
//------------------------------------------------------------------------
OMarkableTreeListBox::OMarkableTreeListBox( Window* pParent, const ResId& rResId) : SvTreeListBox(pParent,rResId)
{
    InitButtonData();
}
//------------------------------------------------------------------------
OMarkableTreeListBox::~OMarkableTreeListBox()
{
    delete m_pCheckButton;
}
// -----------------------------------------------------------------------------
void OMarkableTreeListBox::notifyHiContrastChanged()
{
    // old actions now done in SvTreeListBox::DataChanged() / InitSettings()
}
//------------------------------------------------------------------------
void OMarkableTreeListBox::Paint(const Rectangle& _rRect)
{
    if (!IsEnabled())
    {
        Font aOldFont = GetFont();
        Font aNewFont(aOldFont);

        StyleSettings aSystemStyle = Application::GetSettings().GetStyleSettings();
        aNewFont.SetColor(aSystemStyle.GetDisableColor());

        SetFont(aNewFont);
        SvTreeListBox::Paint(_rRect);
        SetFont(aOldFont);
    }
    else
        SvTreeListBox::Paint(_rRect);
}
//------------------------------------------------------------------------
void OMarkableTreeListBox::InitButtonData()
{
    sal_Bool bHiContrast = GetBackground().GetColor().IsDark();
    SetNodeBitmaps( Bitmap(ModuleRes( bHiContrast ? BMP_PLUSBUTTON_SCH : BMP_PLUSBUTTON)),
        Bitmap(ModuleRes( bHiContrast ? BMP_MINUSBUTTON_SCH : BMP_MINUSBUTTON)));

    m_pCheckButton = new SvLBoxButtonData( this );
    OMarkableTreeListBox::notifyHiContrastChanged();
    EnableCheckButton( m_pCheckButton );
}
//------------------------------------------------------------------------
void OMarkableTreeListBox::KeyInput( const KeyEvent& rKEvt )
{
    // nur wenn space
    if (rKEvt.GetKeyCode().GetCode() == KEY_SPACE && !rKEvt.GetKeyCode().IsShift() && !rKEvt.GetKeyCode().IsMod1())
    {
        SvLBoxEntry* pHdlEntry = GetHdlEntry();
        if(pHdlEntry)
        {
            SvButtonState eState = GetCheckButtonState( pHdlEntry);
            if(eState == SV_BUTTON_CHECKED)
                SetCheckButtonState( pHdlEntry,SV_BUTTON_UNCHECKED);
            else
                SetCheckButtonState( pHdlEntry,SV_BUTTON_CHECKED);

            CheckButtonHdl();
        }
        else
            SvTreeListBox::KeyInput(rKEvt);
    }
    else
        SvTreeListBox::KeyInput(rKEvt);

}
//------------------------------------------------------------------------
SvButtonState OMarkableTreeListBox::implDetermineState(SvLBoxEntry* _pEntry)
{
    SvButtonState eState = GetCheckButtonState(_pEntry);
    if (!GetModel()->HasChilds(_pEntry))
        // nothing to do in this bottom-up routine if there are no children ...
        return eState;
#ifdef DBG_UTIL
    String sEntryText = GetEntryText(_pEntry);
#endif

    // loop through the children and check their states
    sal_uInt16 nCheckedChildren = 0;
    sal_uInt16 nChildrenOverall = 0;

    SvLBoxEntry* pChildLoop = GetModel()->FirstChild(_pEntry);
    while (pChildLoop)
    {
#ifdef DBG_UTIL
        String sChildText = GetEntryText(pChildLoop);
#endif
        SvButtonState eChildState = implDetermineState(pChildLoop);
        if (SV_BUTTON_TRISTATE == eChildState)
            break;

        if (SV_BUTTON_CHECKED == eChildState)
            ++nCheckedChildren;
        ++nChildrenOverall;

        pChildLoop = GetModel()->NextSibling(pChildLoop);
    }

    if (pChildLoop)
    {
        // we did not finish the loop because at least one of the children is in tristate
        eState = SV_BUTTON_TRISTATE;

        // but this means that we did not finish all the siblings of pChildLoop, so their checking may be
        // incorrect at the moment
        // -> correct this
        // 88485 - 20.06.2001 - frank.schoenheit@sun.com
        while (pChildLoop)
        {
            implDetermineState(pChildLoop);
            pChildLoop = GetModel()->NextSibling(pChildLoop);
        }
    }
    else
        // none if the children is in tristate
        if (nCheckedChildren)
            // we have at least one chil checked
            if (nCheckedChildren != nChildrenOverall)
                // not all children are checked
                eState = SV_BUTTON_TRISTATE;
            else
                // all children are checked
                eState = SV_BUTTON_CHECKED;
        else
            // no children are checked
            eState = SV_BUTTON_UNCHECKED;

    // finally set the entry to the state we just determined
    SetCheckButtonState(_pEntry, eState);

    // outta here
    return eState;
}

//------------------------------------------------------------------------
void OMarkableTreeListBox::CheckButtons()
{
    SvLBoxEntry* pEntry = GetModel()->First();
    while (pEntry)
    {
        implDetermineState(pEntry);
        pEntry = GetModel()->NextSibling(pEntry);
    }

#if 0
    // Plausibilit"atspr"ufung
    SvButtonState eState;
    SvLBoxEntry* pEntry = GetModel()->First();
    while(pEntry)
    {
        if(!GetModel()->HasChilds(pEntry))
        {
            sal_uInt16 nCheck=0;
            sal_uInt16 nCount=0;
            SvLBoxEntry* pChildEntry = pEntry;
            while(pChildEntry)
            {
                if(GetCheckButtonState(pChildEntry) == SV_BUTTON_CHECKED)
                    nCheck++;
                nCount++;
                pChildEntry = GetModel()->NextSibling(pChildEntry);
            }

            if(nCheck && nCount != nCheck)
                eState = SV_BUTTON_TRISTATE;
            else if(nCheck)
                eState = SV_BUTTON_CHECKED;
            else
                eState = SV_BUTTON_UNCHECKED;

            SvLBoxEntry* pSchema = GetModel()->GetParent(pEntry);
            if(pSchema)
            {
                pEntry = GetModel()->NextSibling(pSchema);
                SetCheckButtonState(pSchema, eState);
            }
            else
                pEntry = NULL; // wenn kein Schema dann sind bereits alle pEntry's durchlaufen worden
        }
        else
            pEntry = GetModel()->Next(pEntry);
    }

    SvLBoxEntry* pCatalog = GetModel()->First();
    SvLBoxEntry* pSchema = NULL;
    if(GetModel()->HasChilds(pCatalog) && GetModel()->HasChilds(pSchema = GetModel()->Next(pCatalog)))
    {
        sal_uInt16 nCheck   =0;
        sal_uInt16 nTri     =0;
        sal_uInt16 nCount   =0;
        while(pSchema)
        {
            if((eState = GetCheckButtonState(pSchema)) == SV_BUTTON_TRISTATE)
                break;

            if(eState == SV_BUTTON_CHECKED)
                nCheck++;
            nCount++;
            pSchema = GetModel()->NextSibling(pSchema);
        }

        if(eState != SV_BUTTON_TRISTATE)
        {
            if(nCheck && nCount == nCheck)
                eState = SV_BUTTON_CHECKED;
            else if(nCheck)
                eState = SV_BUTTON_TRISTATE;
            else
                eState = SV_BUTTON_UNCHECKED;
        }
        SetCheckButtonState( pCatalog,eState);
    }
#endif
}
//------------------------------------------------------------------------
void OMarkableTreeListBox::CheckButtonHdl()
{
    checkedButton_noBroadcast(GetHdlEntry());
    if (m_aCheckButtonHandler.IsSet())
        m_aCheckButtonHandler.Call(this);
}

//------------------------------------------------------------------------
void OMarkableTreeListBox::checkedButton_noBroadcast(SvLBoxEntry* _pEntry)
{
    SvButtonState eState = GetCheckButtonState( _pEntry);
    if (GetModel()->HasChilds(_pEntry)) // Falls Kinder, dann diese auch checken
    {
        SvLBoxEntry* pChildEntry = GetModel()->Next(_pEntry);
        SvLBoxEntry* pSiblingEntry = GetModel()->NextSibling(_pEntry);
        while(pChildEntry && pChildEntry != pSiblingEntry)
        {
            SetCheckButtonState(pChildEntry, eState);
            pChildEntry = GetModel()->Next(pChildEntry);
        }
    }

    SvLBoxEntry* pEntry = IsSelected(_pEntry) ? FirstSelected() : NULL;
    while(pEntry)
    {
        SetCheckButtonState(pEntry,eState);
        if(GetModel()->HasChilds(pEntry))   // Falls Kinder, dann diese auch checken
        {
            SvLBoxEntry* pChildEntry = GetModel()->Next(pEntry);
            SvLBoxEntry* pSiblingEntry = GetModel()->NextSibling(pEntry);
            while(pChildEntry && pChildEntry != pSiblingEntry)
            {
                SetCheckButtonState(pChildEntry,eState);
                pChildEntry = GetModel()->Next(pChildEntry);
            }
        }
        pEntry = NextSelected(pEntry);
    }
    CheckButtons();
}

//------------------------------------------------------------------------
SvLBoxEntry* OMarkableTreeListBox::GetEntryPosByName(const String& aName,SvLBoxEntry* pStart) const
{
    SvLBoxEntry* pEntry = pStart ? GetModel()->FirstChild(pStart) : GetModel()->First();
    while(pEntry && !GetEntryText(pEntry).Equals(aName))
        pEntry = GetModel()->Next(pEntry);

    return pEntry;
}

//.........................................................................
}   // namespace dbaui
//.........................................................................

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.6  2002/04/29 08:49:26  oj
 *  #98772# hi contrast changes
 *
 *  Revision 1.5  2001/06/20 09:53:46  fs
 *  #88485# corrected implDetermineState for a special case
 *
 *  Revision 1.4  2001/04/27 08:10:27  fs
 *  +implDeterminedState - needed to correctly implement CheckButtons
 *
 *  Revision 1.3  2001/01/30 08:30:11  fs
 *  +checkedButton_noBroadcast
 *
 *  Revision 1.2  2000/10/09 12:34:33  fs
 *  use a different font when painting a disabled control
 *
 *  Revision 1.1  2000/10/05 10:00:43  fs
 *  initial checkin
 *
 *
 *  Revision 1.0 28.09.00 13:22:30  fs
 ************************************************************************/

<|endoftext|>


<commit_before>#include "ComputerPlayer/ComputerPlayer.h"
#include "GameState/ChessTypes.h"
#include "GameState/GameState.h"

#include <cstdio>

// static void drawBoard(Board const & b);

int main(int argc, char ** argv)
{
    GameState s0;
    if (!s0.initializeFromFen(argv[1]))
    {
        fprintf(stderr, "Unable to parse input: %s\n", argv[1]);
        exit(1);
    }
    ComputerPlayer computer(Color::BLACK, 7);
    GameState      s1 = computer.myTurn(s0);
    printf("%s", s1.move_.notation().c_str());

    return 0;
}

#if 0

static void drawBoard(Board const & b)
{
    for (int row = 0; row < Board::SIZE; ++row)
    {
        puts("   +---+---+---+---+---+---+---+---+");
        char buffer[] = "|   |   |   |   |   |   |   |   |";
        for (int column = 0; column < Board::SIZE; ++column)
        {
            Piece const * piece = b.pieceAt(row, column);
            if (piece == NO_PIECE)
                buffer[column * 4 + 2] = ' ';
            else
                buffer[column * 4 + 2] = piece->symbol()[0];
        }
        printf(" %1d %s\n", 8 - row, buffer);
    }
    puts("   +---+---+---+---+---+---+---+---+");
    puts("     a   b   c   d   e   f   g   h");
}

#endif // if 0
<commit_msg>Now get computer player color from inputted state rather than assuming black.<commit_after>#include "ComputerPlayer/ComputerPlayer.h"
#include "GameState/ChessTypes.h"
#include "GameState/GameState.h"

#include <cstdio>

// static void drawBoard(Board const & b);

int main(int argc, char ** argv)
{
    GameState s0;
    if (!s0.initializeFromFen(argv[1]))
    {
        fprintf(stderr, "Unable to parse input: %s\n", argv[1]);
        exit(1);
    }
    ComputerPlayer computer(s0.whoseTurn_, 7);
    GameState      s1 = computer.myTurn(s0);
    printf("%s", s1.move_.notation().c_str());

    return 0;
}

#if 0

static void drawBoard(Board const & b)
{
    for (int row = 0; row < Board::SIZE; ++row)
    {
        puts("   +---+---+---+---+---+---+---+---+");
        char buffer[] = "|   |   |   |   |   |   |   |   |";
        for (int column = 0; column < Board::SIZE; ++column)
        {
            Piece const * piece = b.pieceAt(row, column);
            if (piece == NO_PIECE)
                buffer[column * 4 + 2] = ' ';
            else
                buffer[column * 4 + 2] = piece->symbol()[0];
        }
        printf(" %1d %s\n", 8 - row, buffer);
    }
    puts("   +---+---+---+---+---+---+---+---+");
    puts("     a   b   c   d   e   f   g   h");
}

#endif // if 0
<|endoftext|>


<commit_before>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#include <climits>
#include <list>
#include <functional>

using namespace std;

typedef long long llint;
typedef unsigned long long ullint;

class GraphNode {

private:
	ullint  _id;
	llint _value;
	bool _visit;
	bool _hasParentId;
	ullint _parentId;

public:
	GraphNode(ullint id, llint value) {
		setId(id);
		setValue(value);
		setVisit(false);
		setHasParentId(false);
		setParentId(0);
	}

	~GraphNode() {
	}

	//----- Getters and Setters

	//----- Id
	ullint getId() const { return _id; }
	void setId(ullint id) { _id = id; }

	//----- Value
	llint getValue() const { return _value; }
	void setValue(llint value) { _value = value; }

	//----- Visit
	bool getVisit() { return _visit; }
	void setVisit(bool visit) { _visit = visit; }

	//----- Has Parent Id
	bool getHasParentId() { return _hasParentId; }
	void setHasParentId(bool hasParentId) { _hasParentId = hasParentId; }

	//----- Parent Id
	ullint getParentId() { return _parentId; }
	void setParentId(ullint parentId) { _parentId = parentId; }
};

class GraphEdge {
private:
	const GraphNode* _source;
	const GraphNode* _destination;
	double _weight;

public:
	GraphEdge(const GraphNode* source, const GraphNode* destination,
			double weight) {
		_source = source;
		_destination = destination;
		_weight = weight;
	}

	~GraphEdge() {
	}

	//----- Getters and Setters
	//----- Source
	const GraphNode* getSource() const { return _source; }

	//----- Destination
	const GraphNode* getDestination() const { return _destination; }

	//----- Weight
	double getWeight() { return _weight; }
	void setWeight(double weight) { _weight = weight; }
};

class Graph {

protected:
	//----- Attributes
	list<GraphNode*> _nodes;
	list<GraphEdge*> _edges;
	list<GraphEdge*> _pathEdges;

	bool _isDirected;
	ullint _id;

public:
	Graph(bool isDirected = false) {
		setIsDirected(isDirected);
		_id = 0;
	}

	~Graph() {
		clear();
	}

	//----- Getters and Setters
	//----- Is Directed
	bool getIsDirected() { return _isDirected; }
	void setIsDirected(bool isDirected) { _isDirected = isDirected; }

	//----- Methods
	void clear() {
		// Clear Edges
		list<GraphEdge*>::iterator positionEdge = _edges.begin();

		while (positionEdge != _edges.end()) {
			delete *positionEdge;
			*positionEdge = NULL;
			positionEdge++;
		}

		_edges.clear();

		// Clear Nodes
		list<GraphNode*>:: iterator positionNode = _nodes.begin();
		while (positionNode != _nodes.end()) {
			delete *positionNode;
			*positionNode = NULL;
			positionNode++;
		}

		_nodes.clear();
	}

	bool isEmpty() {
		return _nodes.empty();
	}

	ullint getNumberOfNodes() {
		return _nodes.size();
	}

	ullint getNumberOfEdges() {
		return _edges.size();
	}

	void addNode(llint value) {
		_id++;
		GraphNode* node = new GraphNode(_id, value);
		_nodes.push_back(node);
	}

	void removeNodeById(ullint nodeId) {
		list<GraphEdge*>::iterator positionEdge = _edges.begin();
		const GraphNode* source;
		const GraphNode* destination;

		// Remove edges where node is involved
		while (positionEdge != _edges.end()) {
			source = (*positionEdge)->getSource();
			destination = (*positionEdge)->getDestination();

			if ( ( source->getId() == nodeId )
				|| ( destination->getId() == nodeId ) ) {

				delete *positionEdge;
				*positionEdge = NULL;
				_edges.erase(positionEdge);
			}

			positionEdge++;
		}

		source = NULL;
		destination = NULL;

		// Remove nodes with the given id
		list<GraphNode*>:: iterator positionNode = _nodes.begin();

		while (positionNode != _nodes.end()) {
			if ( (*positionNode)->getId() == nodeId ) {
				delete *positionNode;
				*positionNode = NULL;
				_nodes.erase(positionNode);
				break;
			}

			positionNode++;
		}
	}

	bool removeNodeByValue(llint nodeValue) {
		auto node = searchNodeByValue(nodeValue);
		if (node != NULL) {
			removeNodeById(node->getId());
			return true;
		}

		return false;
	}

	bool removeNodesByValue(llint nodeValue) {
		auto isSuccess = false;

		// Not the best solution, but I will rarely use this
		while (removeNodeByValue(nodeValue))
			isSuccess = true;

		return isSuccess;
	}

	llint getNodesLeastValue() {
		llint leastValue = LLONG_MAX;

		for (GraphNode* currentNode : _nodes)
			if (currentNode->getValue() < leastValue)
				leastValue = currentNode->getValue();

		return leastValue;
	}

	void removeNodeLeastValue() {
		if (isEmpty()) return;
		removeNodeByValue(getNodesLeastValue());
	}

	llint getNodesMaxValue() {
		llint maxValue = LLONG_MIN;

		for (GraphNode* currentNode : _nodes)
			if (currentNode->getValue() > maxValue)
				maxValue = currentNode->getValue();

		return maxValue;
	}

	void removeNodeMaxValue() {
		if (isEmpty()) return;
		removeNodeByValue(getNodesMaxValue());
	}

	GraphNode* searchNodeByValue(llint nodeValue) {
		GraphNode* nodeOutput = NULL;
		list<GraphNode*>::iterator positionNode = _nodes.begin();

		while (positionNode != _nodes.end()) {
			if ( (*positionNode)->getValue() == nodeValue ) {
				nodeOutput = (*positionNode);
				break;
			}
			positionNode++;
		}

		return nodeOutput;
	}

	GraphNode* searchNodeById(ullint nodeId) {
		GraphNode* nodeOutput = NULL;
		list<GraphNode*>::iterator positionNode = _nodes.begin();

		while (positionNode != _nodes.end()) {
			if ( (*positionNode)->getId() == nodeId ) {
				nodeOutput = (*positionNode);
				break;
			}
			positionNode++;
		}

		return nodeOutput;
	}

	bool hasNodeWithValue(llint nodeValue) {
		return searchNodeByValue(nodeValue) != NULL;
	}

	bool hasNodeWithId(ullint nodeId) {
		return searchNodeById(nodeId) != NULL;
	}

	void addEdge(ullint sourceId, ullint destinationId, double weight) {
		const GraphNode* sourceNode = searchNodeById(sourceId);
		const GraphNode* destinationNode = searchNodeById(destinationId);

		if ( ( sourceNode != NULL ) && ( destinationNode != NULL ) ) {
			GraphEdge* newEdge = new GraphEdge(sourceNode, destinationNode, weight);
			_edges.push_back(newEdge);
		}
	}

	GraphEdge* searchEdgeByWeight(double weight) {
		for (GraphEdge* currentEdge : _edges)
			if (currentEdge->getWeight() == weight)
				return currentEdge;

		return NULL;
	}

	GraphEdge* searchEdgeByNodePath(ullint sourceId, ullint destinationId) {
		for (auto currentEdge : _edges)
			if (currentEdge->getSource()->getId() == sourceId
				&& currentEdge->getDestination()->getId() == destinationId)
				return currentEdge;

		return NULL;
	}

	void removeEdgesByWeight(double weight) {
		vector<GraphEdge*> edgesWithGivenWeight;

		for (auto currentEdge : _edges)
			if (currentEdge->getWeight() == weight)
				edgesWithGivenWeight.push_back(currentEdge);

		for (auto currentEdge : edgesWithGivenWeight) {
			_edges.remove(currentEdge);
			delete currentEdge;
		}
	}

	void removeEdgeByNodePath(ullint sourceId, ullint destinationId) {
		vector<GraphEdge*> edgesWithGivenNodePath;

		for (auto currentEdge : _edges)
			if (currentEdge->getSource()->getId() == sourceId
				&& currentEdge->getDestination()->getId() == destinationId)
				edgesWithGivenNodePath.push_back(currentEdge);

		for (auto currentEdge : edgesWithGivenNodePath) {
			_edges.remove(currentEdge);
			delete currentEdge;
		}
	}

	vector<GraphEdge*> getEdgesWhereNodeIsSource(ullint nodeId) {
		vector<GraphEdge*> destinations;

		for (auto currentEdge : _edges)
			if (currentEdge->getSource()->getId() == nodeId)
				destinations.push_back(currentEdge);

		return destinations;
	}

	vector<GraphEdge*> getEdgesWhereNodeIsDestination(ullint nodeId) {
		vector<GraphEdge*> sources;

		for (auto currentEdge : _edges)
			if (currentEdge->getDestination()->getId() == nodeId)
				sources.push_back(currentEdge);

		return sources;
	}

	typedef pair<int, int> pp;
	map<ullint, llint> djikstra(int source) {
		priority_queue<pp, vector<pp>, greater<pp>> costs;
		map<ullint, llint> distances;

		for (auto currNode : _nodes) {
			distances[currNode->getId()] = LLONG_MAX;
		}

		distances[source] = 0;
		costs.push(make_pair(0, source));

		while (!costs.empty()) {
			int dis = costs.top().first;
			int nodeId = costs.top().second;
			costs.pop();

			if (dis > distances[nodeId]) continue;

			for (auto currentEdge : getEdgesWhereNodeIsSource(nodeId)) {
				auto newWeight = dis + currentEdge->getWeight();
				auto oldWeight = distances[currentEdge->getDestination()->getId()];
				auto destinationId = currentEdge->getDestination()->getId();

				if (nodeId == source - 1 || newWeight < oldWeight) {
					distances[destinationId] = newWeight;
					costs.push(make_pair(newWeight, destinationId));
				}
			}
		}

		return distances;
	}

};
<commit_msg>Reduced lines to 80 characters only<commit_after>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#include <climits>
#include <list>
#include <functional>

using namespace std;

typedef long long llint;
typedef unsigned long long ullint;

class GraphNode {

private:
	ullint  _id;
	llint _value;
	bool _visit;
	bool _hasParentId;
	ullint _parentId;

public:
	GraphNode(ullint id, llint value) {
		setId(id);
		setValue(value);
		setVisit(false);
		setHasParentId(false);
		setParentId(0);
	}

	~GraphNode() {
	}

	//----- Getters and Setters

	//----- Id
	ullint getId() const { return _id; }
	void setId(ullint id) { _id = id; }

	//----- Value
	llint getValue() const { return _value; }
	void setValue(llint value) { _value = value; }

	//----- Visit
	bool getVisit() { return _visit; }
	void setVisit(bool visit) { _visit = visit; }

	//----- Has Parent Id
	bool getHasParentId() { return _hasParentId; }
	void setHasParentId(bool hasParentId) { _hasParentId = hasParentId; }

	//----- Parent Id
	ullint getParentId() { return _parentId; }
	void setParentId(ullint parentId) { _parentId = parentId; }
};

class GraphEdge {
private:
	const GraphNode* _source;
	const GraphNode* _destination;
	double _weight;

public:
	GraphEdge(const GraphNode* source, const GraphNode* destination,
			double weight) {
		_source = source;
		_destination = destination;
		_weight = weight;
	}

	~GraphEdge() {
	}

	//----- Getters and Setters
	//----- Source
	const GraphNode* getSource() const { return _source; }

	//----- Destination
	const GraphNode* getDestination() const { return _destination; }

	//----- Weight
	double getWeight() { return _weight; }
	void setWeight(double weight) { _weight = weight; }
};

class Graph {

protected:
	//----- Attributes
	list<GraphNode*> _nodes;
	list<GraphEdge*> _edges;
	list<GraphEdge*> _pathEdges;

	bool _isDirected;
	ullint _id;

public:
	Graph(bool isDirected = false) {
		setIsDirected(isDirected);
		_id = 0;
	}

	~Graph() {
		clear();
	}

	//----- Getters and Setters
	//----- Is Directed
	bool getIsDirected() { return _isDirected; }
	void setIsDirected(bool isDirected) { _isDirected = isDirected; }

	//----- Methods
	void clear() {
		// Clear Edges
		list<GraphEdge*>::iterator positionEdge = _edges.begin();

		while (positionEdge != _edges.end()) {
			delete *positionEdge;
			*positionEdge = NULL;
			positionEdge++;
		}

		_edges.clear();

		// Clear Nodes
		list<GraphNode*>:: iterator positionNode = _nodes.begin();
		while (positionNode != _nodes.end()) {
			delete *positionNode;
			*positionNode = NULL;
			positionNode++;
		}

		_nodes.clear();
	}

	bool isEmpty() {
		return _nodes.empty();
	}

	ullint getNumberOfNodes() {
		return _nodes.size();
	}

	ullint getNumberOfEdges() {
		return _edges.size();
	}

	void addNode(llint value) {
		_id++;
		GraphNode* node = new GraphNode(_id, value);
		_nodes.push_back(node);
	}

	void removeNodeById(ullint nodeId) {
		list<GraphEdge*>::iterator positionEdge = _edges.begin();
		const GraphNode* source;
		const GraphNode* destination;

		// Remove edges where node is involved
		while (positionEdge != _edges.end()) {
			source = (*positionEdge)->getSource();
			destination = (*positionEdge)->getDestination();

			if ( ( source->getId() == nodeId )
				|| ( destination->getId() == nodeId ) ) {

				delete *positionEdge;
				*positionEdge = NULL;
				_edges.erase(positionEdge);
			}

			positionEdge++;
		}

		source = NULL;
		destination = NULL;

		// Remove nodes with the given id
		list<GraphNode*>:: iterator positionNode = _nodes.begin();

		while (positionNode != _nodes.end()) {
			if ( (*positionNode)->getId() == nodeId ) {
				delete *positionNode;
				*positionNode = NULL;
				_nodes.erase(positionNode);
				break;
			}

			positionNode++;
		}
	}

	bool removeNodeByValue(llint nodeValue) {
		auto node = searchNodeByValue(nodeValue);
		if (node != NULL) {
			removeNodeById(node->getId());
			return true;
		}

		return false;
	}

	bool removeNodesByValue(llint nodeValue) {
		auto isSuccess = false;

		// Not the best solution, but I will rarely use this
		while (removeNodeByValue(nodeValue))
			isSuccess = true;

		return isSuccess;
	}

	llint getNodesLeastValue() {
		llint leastValue = LLONG_MAX;

		for (GraphNode* currentNode : _nodes)
			if (currentNode->getValue() < leastValue)
				leastValue = currentNode->getValue();

		return leastValue;
	}

	void removeNodeLeastValue() {
		if (isEmpty()) return;
		removeNodeByValue(getNodesLeastValue());
	}

	llint getNodesMaxValue() {
		llint maxValue = LLONG_MIN;

		for (GraphNode* currentNode : _nodes)
			if (currentNode->getValue() > maxValue)
				maxValue = currentNode->getValue();

		return maxValue;
	}

	void removeNodeMaxValue() {
		if (isEmpty()) return;
		removeNodeByValue(getNodesMaxValue());
	}

	GraphNode* searchNodeByValue(llint nodeValue) {
		GraphNode* nodeOutput = NULL;
		list<GraphNode*>::iterator positionNode = _nodes.begin();

		while (positionNode != _nodes.end()) {
			if ( (*positionNode)->getValue() == nodeValue ) {
				nodeOutput = (*positionNode);
				break;
			}
			positionNode++;
		}

		return nodeOutput;
	}

	GraphNode* searchNodeById(ullint nodeId) {
		GraphNode* nodeOutput = NULL;
		list<GraphNode*>::iterator positionNode = _nodes.begin();

		while (positionNode != _nodes.end()) {
			if ( (*positionNode)->getId() == nodeId ) {
				nodeOutput = (*positionNode);
				break;
			}
			positionNode++;
		}

		return nodeOutput;
	}

	bool hasNodeWithValue(llint nodeValue) {
		return searchNodeByValue(nodeValue) != NULL;
	}

	bool hasNodeWithId(ullint nodeId) {
		return searchNodeById(nodeId) != NULL;
	}

	void addEdge(ullint sourceId, ullint destinationId, double weight) {
		const GraphNode* sourceNode = searchNodeById(sourceId);
		const GraphNode* destinationNode = searchNodeById(destinationId);

		if ( ( sourceNode != NULL ) && ( destinationNode != NULL ) ) {
			auto newEdge = new GraphEdge(sourceNode, destinationNode, weight);
			_edges.push_back(newEdge);
		}
	}

	GraphEdge* searchEdgeByWeight(double weight) {
		for (GraphEdge* currentEdge : _edges)
			if (currentEdge->getWeight() == weight)
				return currentEdge;

		return NULL;
	}

	GraphEdge* searchEdgeByNodePath(ullint sourceId, ullint destinationId) {
		for (auto currentEdge : _edges)
			if (currentEdge->getSource()->getId() == sourceId
				&& currentEdge->getDestination()->getId() == destinationId)
				return currentEdge;

		return NULL;
	}

	void removeEdgesByWeight(double weight) {
		vector<GraphEdge*> edgesWithGivenWeight;

		for (auto currentEdge : _edges)
			if (currentEdge->getWeight() == weight)
				edgesWithGivenWeight.push_back(currentEdge);

		for (auto currentEdge : edgesWithGivenWeight) {
			_edges.remove(currentEdge);
			delete currentEdge;
		}
	}

	void removeEdgeByNodePath(ullint sourceId, ullint destinationId) {
		vector<GraphEdge*> edgesWithGivenNodePath;

		for (auto currentEdge : _edges)
			if (currentEdge->getSource()->getId() == sourceId
				&& currentEdge->getDestination()->getId() == destinationId)
				edgesWithGivenNodePath.push_back(currentEdge);

		for (auto currentEdge : edgesWithGivenNodePath) {
			_edges.remove(currentEdge);
			delete currentEdge;
		}
	}

	vector<GraphEdge*> getEdgesWhereNodeIsSource(ullint nodeId) {
		vector<GraphEdge*> destinations;

		for (auto currentEdge : _edges)
			if (currentEdge->getSource()->getId() == nodeId)
				destinations.push_back(currentEdge);

		return destinations;
	}

	vector<GraphEdge*> getEdgesWhereNodeIsDestination(ullint nodeId) {
		vector<GraphEdge*> sources;

		for (auto currentEdge : _edges)
			if (currentEdge->getDestination()->getId() == nodeId)
				sources.push_back(currentEdge);

		return sources;
	}

	typedef pair<int, int> pp;
	map<ullint, llint> djikstra(int source) {
		priority_queue<pp, vector<pp>, greater<pp>> costs;
		map<ullint, llint> distances;

		for (auto currNode : _nodes) {
			distances[currNode->getId()] = LLONG_MAX;
		}

		distances[source] = 0;
		costs.push(make_pair(0, source));

		while (!costs.empty()) {
			int dis = costs.top().first;
			int nodeId = costs.top().second;
			costs.pop();

			if (dis > distances[nodeId]) continue;

			for (auto currentEdge : getEdgesWhereNodeIsSource(nodeId)) {
				auto newWeight = dis + currentEdge->getWeight();
				auto destinationId = currentEdge->getDestination()->getId();
				auto oldWeight = distances[destinationId];

				if (nodeId == source - 1 || newWeight < oldWeight) {
					distances[destinationId] = newWeight;
					costs.push(make_pair(newWeight, destinationId));
				}
			}
		}

		return distances;
	}

};
<|endoftext|>


<commit_before>/**
 *
 * HX711 library for Arduino
 * https://github.com/bogde/HX711
 *
 * MIT License
 * (c) 2018 Bogdan Necula
 *
**/
#include <Arduino.h>
#include <HX711.h>

#ifndef ESP_H
	#if ARDUINO <= 106
    // "yield" is not implemented as noop in older Arduino Core releases, so let's define it.
    // See also: https://stackoverflow.com/questions/34497758/what-is-the-secret-of-the-arduino-yieldfunction/34498165#34498165
   	void yield(void) {};
	#endif
#endif

HX711::HX711() {
}

HX711::~HX711() {
}

void HX711::begin(byte dout, byte pd_sck, byte gain) {
	PD_SCK = pd_sck;
	DOUT = dout;

	pinMode(PD_SCK, OUTPUT);
	pinMode(DOUT, INPUT);

	set_gain(gain);
}

bool HX711::is_ready() {
	return digitalRead(DOUT) == LOW;
}

void HX711::set_gain(byte gain) {
	switch (gain) {
		case 128:		// channel A, gain factor 128
			GAIN = 1;
			break;
		case 64:		// channel A, gain factor 64
			GAIN = 3;
			break;
		case 32:		// channel B, gain factor 32
			GAIN = 2;
			break;
	}

	digitalWrite(PD_SCK, LOW);
	read();
}

long HX711::read() {
	// wait for the chip to become ready
	while (!is_ready()) {
		// Will do nothing on Arduino but prevent resets of ESP8266 (Watchdog Issue)
		yield();
	}

	unsigned long value = 0;
	uint8_t data[3] = { 0 };
	uint8_t filler = 0x00;

	// pulse the clock pin 24 times to read the data
	data[2] = shiftIn(DOUT, PD_SCK, MSBFIRST);
	data[1] = shiftIn(DOUT, PD_SCK, MSBFIRST);
	data[0] = shiftIn(DOUT, PD_SCK, MSBFIRST);

	// set the channel and the gain factor for the next reading using the clock pin
	for (unsigned int i = 0; i < GAIN; i++) {
		digitalWrite(PD_SCK, HIGH);
		digitalWrite(PD_SCK, LOW);
	}

	// Replicate the most significant bit to pad out a 32-bit signed integer
	if (data[2] & 0x80) {
		filler = 0xFF;
	} else {
		filler = 0x00;
	}

	// Construct a 32-bit signed integer
	value = ( static_cast<unsigned long>(filler) << 24
			| static_cast<unsigned long>(data[2]) << 16
			| static_cast<unsigned long>(data[1]) << 8
			| static_cast<unsigned long>(data[0]) );

	return static_cast<long>(value);
}

long HX711::read_average(byte times) {
	long sum = 0;
	for (byte i = 0; i < times; i++) {
		sum += read();
		yield();
	}
	return sum / times;
}

double HX711::get_value(byte times) {
	return read_average(times) - OFFSET;
}

float HX711::get_units(byte times) {
	return get_value(times) / SCALE;
}

void HX711::tare(byte times) {
	double sum = read_average(times);
	set_offset(sum);
}

void HX711::set_scale(float scale) {
	SCALE = scale;
}

float HX711::get_scale() {
	return SCALE;
}

void HX711::set_offset(long offset) {
	OFFSET = offset;
}

long HX711::get_offset() {
	return OFFSET;
}

void HX711::power_down() {
	digitalWrite(PD_SCK, LOW);
	digitalWrite(PD_SCK, HIGH);
}

void HX711::power_up() {
	digitalWrite(PD_SCK, LOW);
}
<commit_msg>Added speed support for the esp32 chip<commit_after>/**
 *
 * HX711 library for Arduino
 * https://github.com/bogde/HX711
 *
 * MIT License
 * (c) 2018 Bogdan Necula
 *
**/
#include <Arduino.h>
#include <HX711.h>

#ifndef ESP_H
	#if ARDUINO <= 106
    // "yield" is not implemented as noop in older Arduino Core releases, so let's define it.
    // See also: https://stackoverflow.com/questions/34497758/what-is-the-secret-of-the-arduino-yieldfunction/34498165#34498165
   	void yield(void) {};
	#endif
#endif

#ifdef ESP_H
uint8_t shiftInSlow(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) {
    uint8_t value = 0;
    uint8_t i;

    for(i = 0; i < 8; ++i) {
        digitalWrite(clockPin, HIGH);
        delayMicroseconds(1);
        if(bitOrder == LSBFIRST)
            value |= digitalRead(dataPin) << i;
        else
            value |= digitalRead(dataPin) << (7 - i);
        digitalWrite(clockPin, LOW);
        delayMicroseconds(1);
    }
    return value;
}
#define SHIFTIN_WITH_SPEED_SUPPORT(data,clock,order) shiftInSlow(data,clock,order)
#else
#define SHIFTIN_WITH_SPEED_SUPPORT(data,clock,order) shiftIn(data,clock,order)
#endif

HX711::HX711() {
}

HX711::~HX711() {
}

void HX711::begin(byte dout, byte pd_sck, byte gain) {
	PD_SCK = pd_sck;
	DOUT = dout;

	pinMode(PD_SCK, OUTPUT);
	pinMode(DOUT, INPUT);

	set_gain(gain);
}

bool HX711::is_ready() {
	return digitalRead(DOUT) == LOW;
}

void HX711::set_gain(byte gain) {
	switch (gain) {
		case 128:		// channel A, gain factor 128
			GAIN = 1;
			break;
		case 64:		// channel A, gain factor 64
			GAIN = 3;
			break;
		case 32:		// channel B, gain factor 32
			GAIN = 2;
			break;
	}

	digitalWrite(PD_SCK, LOW);
	read();
}

long HX711::read() {
	// wait for the chip to become ready
	while (!is_ready()) {
		// Will do nothing on Arduino but prevent resets of ESP8266 (Watchdog Issue)
		yield();
	}

	unsigned long value = 0;
	uint8_t data[3] = { 0 };
	uint8_t filler = 0x00;

	// pulse the clock pin 24 times to read the data
	data[2] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);
	data[1] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);
	data[0] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);

	// set the channel and the gain factor for the next reading using the clock pin
	for (unsigned int i = 0; i < GAIN; i++) {
		digitalWrite(PD_SCK, HIGH);
		#ifdef ESP_H
		delayMicroseconds(1);
		#endif
		digitalWrite(PD_SCK, LOW);
		#ifdef ESP_H
		delayMicroseconds(1);
		#endif
	}

	// Replicate the most significant bit to pad out a 32-bit signed integer
	if (data[2] & 0x80) {
		filler = 0xFF;
	} else {
		filler = 0x00;
	}

	// Construct a 32-bit signed integer
	value = ( static_cast<unsigned long>(filler) << 24
			| static_cast<unsigned long>(data[2]) << 16
			| static_cast<unsigned long>(data[1]) << 8
			| static_cast<unsigned long>(data[0]) );

	return static_cast<long>(value);
}

long HX711::read_average(byte times) {
	long sum = 0;
	for (byte i = 0; i < times; i++) {
		sum += read();
		yield();
	}
	return sum / times;
}

double HX711::get_value(byte times) {
	return read_average(times) - OFFSET;
}

float HX711::get_units(byte times) {
	return get_value(times) / SCALE;
}

void HX711::tare(byte times) {
	double sum = read_average(times);
	set_offset(sum);
}

void HX711::set_scale(float scale) {
	SCALE = scale;
}

float HX711::get_scale() {
	return SCALE;
}

void HX711::set_offset(long offset) {
	OFFSET = offset;
}

long HX711::get_offset() {
	return OFFSET;
}

void HX711::power_down() {
	digitalWrite(PD_SCK, LOW);
	digitalWrite(PD_SCK, HIGH);
}

void HX711::power_up() {
	digitalWrite(PD_SCK, LOW);
}
<|endoftext|>


<commit_before>#include <julia.h>
#include "JMain.h"

using namespace std;

shared_ptr<nj::Expr> JMain::eval(const shared_ptr<nj::Expr> &expr)
{
   shared_ptr<nj::Expr> result;

   return result;
}

JMain::JMain()
{
   initialized = false;
   deactivated = false;
}

void JMain::initialize(int argc,const char *argv[]) throw(nj::InitializationException)
{
   unique_lock<mutex> lock(m_state);

   if(argc >= 1) install_directory = argv[0];
   initialized = true;
}

shared_ptr<nj::Expr> JMain::de_queue(list<shared_ptr<nj::Expr>> &queue)
{
   bool done = false;
   shared_ptr<nj::Expr> expr;

   while(!done)
   {
      {
         unique_lock<mutex> lock(m_state);

         while(eval_queue.empty() && !done)
         {
            c_state.wait(lock);
            if(deactivated) done = true;
         }

         if(!deactivated)
         {
            expr = queue.back();
            queue.pop_back();
            if(expr.get()) done = true;
         }
         else done = true;
      }
   }
   return expr;
}

void JMain::operator()()
{
   bool done = false;

   while(!done)
   {
      unique_lock<mutex> lock(m_state);

      if(!initialized) c_state.wait(lock);
      if(initialized || deactivated) done = true;
   }

   if(!deactivated)
   {
      if(install_directory == "") jl_init(0);
      else jl_init((char*)install_directory.c_str());
      JL_SET_STACK_BASE;

      done = false;
      shared_ptr<nj::Expr> expr;

      while(!done)
      {
         expr = de_queue(eval_queue);

         if(expr.get())
         {
            shared_ptr<nj::Expr> result = eval(expr);

            if(result.get())
            {
              unique_lock<mutex> lock(m_state);

              if(!deactivated)
              {
                 result_queue.push_front(result);
                 c_state.notify_all();
              }
              else done = true;
            }
         }
         else done = true;
      }
   }
}

void JMain::evalQueuePut(const string &expressionText)
{
   unique_lock<mutex> lock(m_state);
   shared_ptr<nj::Expr> expr(new nj::Expr(expressionText));

   eval_queue.push_front(expr);
   c_state.notify_all();
}

string JMain::resultQueueGet()
{
   shared_ptr<nj::Expr> expr = de_queue(result_queue);

   if(expr.get()) return expr->getText();
   return "";
}

void JMain::stop()
{
   unique_lock<mutex> lock(m_state);

   deactivated = true;
   c_state.notify_all();
}

JMain::~JMain() {}
<commit_msg>Debugging...<commit_after>#include <julia.h>
#include "JMain.h"

using namespace std;

shared_ptr<nj::Expr> JMain::eval(const shared_ptr<nj::Expr> &expr)
{
   shared_ptr<nj::Expr> result;

   return result;
}

JMain::JMain()
{
   initialized = false;
   deactivated = false;
}

void JMain::initialize(int argc,const char *argv[]) throw(nj::InitializationException)
{
   unique_lock<mutex> lock(m_state);

   if(argc >= 1) install_directory = argv[0];
   initialized = true;
}

shared_ptr<nj::Expr> JMain::de_queue(list<shared_ptr<nj::Expr>> &queue)
{
   bool done = false;
   shared_ptr<nj::Expr> expr;

   while(!done)
   {
      {
         unique_lock<mutex> lock(m_state);

         while(eval_queue.empty() && !done)
         {
            c_state.wait(lock);
            if(deactivated) done = true;
         }

         if(!deactivated)
         {
            expr = queue.back();
            queue.pop_back();
            if(expr.get()) done = true;
         }
         else done = true;
      }
   }
   return expr;
}

void JMain::operator()()
{
   bool done = false;

   while(!done)
   {
      unique_lock<mutex> lock(m_state);

      if(!initialized) c_state.wait(lock);
      if(initialized || deactivated) done = true;
   }

   if(!deactivated)
   {
      if(install_directory == "") jl_init(0);
      else jl_init((char*)install_directory.c_str());
      JL_SET_STACK_BASE;

      done = false;
      shared_ptr<nj::Expr> expr;

      while(!done)
      {
         expr = de_queue(eval_queue);

printf("got an expr\n");

         if(expr.get())
         {
printf("expr text = %s\n",expr->getText());
            shared_ptr<nj::Expr> result = eval(expr);

printf("Got a result\n");
printf("Expr result = %s\n",result->getText());
            if(result.get())
            {
              unique_lock<mutex> lock(m_state);

              if(!deactivated)
              {
                 result_queue.push_front(result);
                 c_state.notify_all();
              }
              else done = true;
            }
         }
         else done = true;
      }
   }
}

void JMain::evalQueuePut(const string &expressionText)
{
   unique_lock<mutex> lock(m_state);
   shared_ptr<nj::Expr> expr(new nj::Expr(expressionText));

   eval_queue.push_front(expr);
   c_state.notify_all();
}

string JMain::resultQueueGet()
{
   shared_ptr<nj::Expr> expr = de_queue(result_queue);

   if(expr.get()) return expr->getText();
   return "";
}

void JMain::stop()
{
   unique_lock<mutex> lock(m_state);

   deactivated = true;
   c_state.notify_all();
}

JMain::~JMain() {}
<|endoftext|>


<commit_before>// RUN: %clang_cc1 %s -emit-llvm -o - -O2 | FileCheck %s
// XFAIL: *

struct B;
extern B x;
char y;
typedef __typeof(sizeof(int)) size_t;
struct A { int a; A() { y = ((size_t)this - (size_t)&x) / sizeof(void*); } };
struct B : virtual A { void* x; };
B x;

// CHECK: @y = global i8 2
<commit_msg>Fixed by r123477.<commit_after>// RUN: %clang_cc1 %s -emit-llvm -o - -O2 | FileCheck %s

struct B;
extern B x;
char y;
typedef __typeof(sizeof(int)) size_t;
struct A { int a; A() { y = ((size_t)this - (size_t)&x) / sizeof(void*); } };
struct B : virtual A { void* x; };
B x;

// CHECK: @y = global i8 2
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: simpleinteractionrequest.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kso $ $Date: 2001-05-28 12:42:46 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _UCBHELPER_SIMPLEINTERACTIONREQUEST_HXX
#include <ucbhelper/simpleinteractionrequest.hxx>
#endif

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

//=========================================================================
SimpleInteractionRequest::SimpleInteractionRequest(
                                    const uno::Any & rRequest,
                                    const sal_Int32 nContinuations )
: InteractionRequest( rRequest )
{
    // Set continuations.
    OSL_ENSURE( nContinuations != CONTINUATION_UNKNOWN,
                "SimpleInteractionRequest - No continuation!" );

    sal_Int32 nLength = 0;

    uno::Reference< task::XInteractionContinuation > xAbort;
    uno::Reference< task::XInteractionContinuation > xRetry;
    uno::Reference< task::XInteractionContinuation > xApprove;
    uno::Reference< task::XInteractionContinuation > xDisapprove;

    if ( nContinuations & CONTINUATION_ABORT )
    {
        ++nLength;
        xAbort = new InteractionAbort( this );
    }

    if ( nContinuations & CONTINUATION_RETRY )
    {
        ++nLength;
        xRetry = new InteractionRetry( this );
    }

    if ( nContinuations & CONTINUATION_APPROVE )
    {
        ++nLength;
        xApprove = new InteractionApprove( this );
    }

    if (  nContinuations & CONTINUATION_DISAPPROVE )
    {
        ++nLength;
        xDisapprove = new InteractionDisapprove( this );
    }

    OSL_ENSURE( nLength > 0,
                "SimpleInteractionRequest - No continuation!" );

    uno::Sequence< uno::Reference< task::XInteractionContinuation > >
        aContinuations( nLength );

    if ( xAbort.is() )
        aContinuations[ nLength++ ] = xAbort;

    if ( xRetry.is() )
        aContinuations[ nLength++ ] = xRetry;

    if ( xApprove.is() )
        aContinuations[ nLength++ ] = xApprove;

    if ( xDisapprove.is() )
        aContinuations[ nLength++ ] = xDisapprove;

    setContinuations( aContinuations );
}

//=========================================================================
const sal_Int32 SimpleInteractionRequest::getResponse() const
{
    rtl::Reference< InteractionContinuation > xSelection = getSelection();
    if ( xSelection.is() )
    {
        InteractionContinuation * pSelection = xSelection.get();

        uno::Reference< task::XInteractionAbort > xAbort(
                                        pSelection, uno::UNO_QUERY );
        if ( xAbort.is() )
            return CONTINUATION_ABORT;

        uno::Reference< task::XInteractionRetry > xRetry(
                                        pSelection, uno::UNO_QUERY );
        if ( xRetry.is() )
            return CONTINUATION_RETRY;

        uno::Reference< task::XInteractionApprove > xApprove(
                                        pSelection, uno::UNO_QUERY );
        if ( xApprove.is() )
            return CONTINUATION_APPROVE;

        uno::Reference< task::XInteractionDisapprove > xDisapprove(
                                        pSelection, uno::UNO_QUERY );
        if ( xDisapprove.is() )
            return CONTINUATION_DISAPPROVE;

        OSL_ENSURE( sal_False,
            "SimpleInteractionRequest::getResponse - Unknown continuation!" );
    }
    return CONTINUATION_UNKNOWN;
}

<commit_msg>#95029# - Fixed index-out-of-range condition in ctor.<commit_after>/*************************************************************************
 *
 *  $RCSfile: simpleinteractionrequest.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kso $ $Date: 2001-11-22 11:38:27 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _UCBHELPER_SIMPLEINTERACTIONREQUEST_HXX
#include <ucbhelper/simpleinteractionrequest.hxx>
#endif

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

//=========================================================================
SimpleInteractionRequest::SimpleInteractionRequest(
                                    const uno::Any & rRequest,
                                    const sal_Int32 nContinuations )
: InteractionRequest( rRequest )
{
    // Set continuations.
    OSL_ENSURE( nContinuations != CONTINUATION_UNKNOWN,
                "SimpleInteractionRequest - No continuation!" );

    sal_Int32 nLength = 0;

    uno::Reference< task::XInteractionContinuation > xAbort;
    uno::Reference< task::XInteractionContinuation > xRetry;
    uno::Reference< task::XInteractionContinuation > xApprove;
    uno::Reference< task::XInteractionContinuation > xDisapprove;

    if ( nContinuations & CONTINUATION_ABORT )
    {
        ++nLength;
        xAbort = new InteractionAbort( this );
    }

    if ( nContinuations & CONTINUATION_RETRY )
    {
        ++nLength;
        xRetry = new InteractionRetry( this );
    }

    if ( nContinuations & CONTINUATION_APPROVE )
    {
        ++nLength;
        xApprove = new InteractionApprove( this );
    }

    if (  nContinuations & CONTINUATION_DISAPPROVE )
    {
        ++nLength;
        xDisapprove = new InteractionDisapprove( this );
    }

    OSL_ENSURE( nLength > 0,
                "SimpleInteractionRequest - No continuation!" );

    uno::Sequence< uno::Reference< task::XInteractionContinuation > >
        aContinuations( nLength );

    nLength = 0;

    if ( xAbort.is() )
        aContinuations[ nLength++ ] = xAbort;

    if ( xRetry.is() )
        aContinuations[ nLength++ ] = xRetry;

    if ( xApprove.is() )
        aContinuations[ nLength++ ] = xApprove;

    if ( xDisapprove.is() )
        aContinuations[ nLength++ ] = xDisapprove;

    setContinuations( aContinuations );
}

//=========================================================================
const sal_Int32 SimpleInteractionRequest::getResponse() const
{
    rtl::Reference< InteractionContinuation > xSelection = getSelection();
    if ( xSelection.is() )
    {
        InteractionContinuation * pSelection = xSelection.get();

        uno::Reference< task::XInteractionAbort > xAbort(
                                        pSelection, uno::UNO_QUERY );
        if ( xAbort.is() )
            return CONTINUATION_ABORT;

        uno::Reference< task::XInteractionRetry > xRetry(
                                        pSelection, uno::UNO_QUERY );
        if ( xRetry.is() )
            return CONTINUATION_RETRY;

        uno::Reference< task::XInteractionApprove > xApprove(
                                        pSelection, uno::UNO_QUERY );
        if ( xApprove.is() )
            return CONTINUATION_APPROVE;

        uno::Reference< task::XInteractionDisapprove > xDisapprove(
                                        pSelection, uno::UNO_QUERY );
        if ( xDisapprove.is() )
            return CONTINUATION_DISAPPROVE;

        OSL_ENSURE( sal_False,
            "SimpleInteractionRequest::getResponse - Unknown continuation!" );
    }
    return CONTINUATION_UNKNOWN;
}

<|endoftext|>