<commit_before>/*************************************************************************
 *
 *  $RCSfile: actiontriggerpropertyset.hxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: cd $ $Date: 2001-12-04 07:37: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 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 __FRAMEWORK_CLASSES_ACTIONTRIGGERPROPERTYSET_HXX_
#define __FRAMEWORK_CLASSES_ACTIONTRIGGERPROPERTYSET_HXX_

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef _CPPUHELPER_PROPSHLP_HXX
#include <cppuhelper/propshlp.hxx>
#endif

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

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

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef __COM_SUN_STAR_AWT_XBITMAP_HPP_
#include <com/sun/star/awt/XBitmap.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif

#define SERVICENAME_ACTIONTRIGGER "com.sun.star.ui.ActionTrigger"
#define IMPLEMENTATIONNAME_ACTIONTRIGGER "com.sun.star.comp.ui.ActionTrigger"

namespace framework
{

class ActionTriggerPropertySet :    public ThreadHelpBase                       ,   // Struct for right initalization of mutex member! Must be first of baseclasses.
                                    public ::com::sun::star::lang::XServiceInfo ,
                                    public ::com::sun::star::lang::XTypeProvider,
                                    public ::cppu::OBroadcastHelper             ,
                                    public ::cppu::OPropertySetHelper           ,   // -> XPropertySet, XFastPropertySet, XMultiPropertySet
                                    public ::cppu::OWeakObject
{
    public:
        ActionTriggerPropertySet( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
        virtual ~ActionTriggerPropertySet();

        // XInterface
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType )
            throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL acquire() throw ();
        virtual void SAL_CALL release() throw ();

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw (::com::sun::star::uno::RuntimeException);

        // XTypeProvider
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId(  ) throw (::com::sun::star::uno::RuntimeException);

    private:
        //---------------------------------------------------------------------------------------------------------
        //  OPropertySetHelper
        //---------------------------------------------------------------------------------------------------------
        virtual sal_Bool SAL_CALL convertFastPropertyValue( com::sun::star::uno::Any&       aConvertedValue,
                                                            com::sun::star::uno::Any&       aOldValue,
                                                            sal_Int32                       nHandle,
                                                            const com::sun::star::uno::Any& aValue          )
            throw( com::sun::star::lang::IllegalArgumentException );

        virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const com::sun::star::uno::Any& aValue )
            throw( com::sun::star::uno::Exception );

        virtual void SAL_CALL getFastPropertyValue( com::sun::star::uno::Any& aValue, sal_Int32 nHandle ) const;

        virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

        virtual com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo()
            throw (::com::sun::star::uno::RuntimeException);

        static const com::sun::star::uno::Sequence< com::sun::star::beans::Property > impl_getStaticPropertyDescriptor();

        //---------------------------------------------------------------------------------------------------------
        //  helper
        //---------------------------------------------------------------------------------------------------------

        sal_Bool impl_tryToChangeProperty(  const   rtl::OUString&              aCurrentValue   ,
                                            const   com::sun::star::uno::Any&   aNewValue       ,
                                            com::sun::star::uno::Any&           aOldValue       ,
                                            com::sun::star::uno::Any&           aConvertedValue ) throw( com::sun::star::lang::IllegalArgumentException );

        sal_Bool impl_tryToChangeProperty(  const   com::sun::star::uno::Reference< com::sun::star::awt::XBitmap >  xBitmap,
                                            const   com::sun::star::uno::Any&   aNewValue       ,
                                            com::sun::star::uno::Any&           aOldValue       ,
                                            com::sun::star::uno::Any&           aConvertedValue ) throw( com::sun::star::lang::IllegalArgumentException );

        sal_Bool impl_tryToChangeProperty(  const   com::sun::star::uno::Reference< com::sun::star::uno::XInterface > xInterface,
                                            const   com::sun::star::uno::Any&   aNewValue       ,
                                            com::sun::star::uno::Any&           aOldValue       ,
                                            com::sun::star::uno::Any&           aConvertedValue ) throw( com::sun::star::lang::IllegalArgumentException );

        //---------------------------------------------------------------------------------------------------------
        //  members
        //---------------------------------------------------------------------------------------------------------

        rtl::OUString                                                           m_aCommandURL;
        rtl::OUString                                                           m_aHelpURL;
        rtl::OUString                                                           m_aText;
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XBitmap >      m_xBitmap;
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >   m_xActionTriggerContainer;
};

}

#endif // __FRAMEWORK_CLASSES_ACTIONTRIGGERPROPERTYSET_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.572); FILE MERGED 2005/09/05 13:04:06 rt 1.1.572.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: actiontriggerpropertyset.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 00:01:19 $
 *
 *  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 __FRAMEWORK_CLASSES_ACTIONTRIGGERPROPERTYSET_HXX_
#define __FRAMEWORK_CLASSES_ACTIONTRIGGERPROPERTYSET_HXX_

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef _CPPUHELPER_PROPSHLP_HXX
#include <cppuhelper/propshlp.hxx>
#endif

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

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

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef __COM_SUN_STAR_AWT_XBITMAP_HPP_
#include <com/sun/star/awt/XBitmap.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif

#define SERVICENAME_ACTIONTRIGGER "com.sun.star.ui.ActionTrigger"
#define IMPLEMENTATIONNAME_ACTIONTRIGGER "com.sun.star.comp.ui.ActionTrigger"

namespace framework
{

class ActionTriggerPropertySet :    public ThreadHelpBase                       ,   // Struct for right initalization of mutex member! Must be first of baseclasses.
                                    public ::com::sun::star::lang::XServiceInfo ,
                                    public ::com::sun::star::lang::XTypeProvider,
                                    public ::cppu::OBroadcastHelper             ,
                                    public ::cppu::OPropertySetHelper           ,   // -> XPropertySet, XFastPropertySet, XMultiPropertySet
                                    public ::cppu::OWeakObject
{
    public:
        ActionTriggerPropertySet( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
        virtual ~ActionTriggerPropertySet();

        // XInterface
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType )
            throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL acquire() throw ();
        virtual void SAL_CALL release() throw ();

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw (::com::sun::star::uno::RuntimeException);

        // XTypeProvider
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId(  ) throw (::com::sun::star::uno::RuntimeException);

    private:
        //---------------------------------------------------------------------------------------------------------
        //  OPropertySetHelper
        //---------------------------------------------------------------------------------------------------------
        virtual sal_Bool SAL_CALL convertFastPropertyValue( com::sun::star::uno::Any&       aConvertedValue,
                                                            com::sun::star::uno::Any&       aOldValue,
                                                            sal_Int32                       nHandle,
                                                            const com::sun::star::uno::Any& aValue          )
            throw( com::sun::star::lang::IllegalArgumentException );

        virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const com::sun::star::uno::Any& aValue )
            throw( com::sun::star::uno::Exception );

        virtual void SAL_CALL getFastPropertyValue( com::sun::star::uno::Any& aValue, sal_Int32 nHandle ) const;

        virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

        virtual com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo()
            throw (::com::sun::star::uno::RuntimeException);

        static const com::sun::star::uno::Sequence< com::sun::star::beans::Property > impl_getStaticPropertyDescriptor();

        //---------------------------------------------------------------------------------------------------------
        //  helper
        //---------------------------------------------------------------------------------------------------------

        sal_Bool impl_tryToChangeProperty(  const   rtl::OUString&              aCurrentValue   ,
                                            const   com::sun::star::uno::Any&   aNewValue       ,
                                            com::sun::star::uno::Any&           aOldValue       ,
                                            com::sun::star::uno::Any&           aConvertedValue ) throw( com::sun::star::lang::IllegalArgumentException );

        sal_Bool impl_tryToChangeProperty(  const   com::sun::star::uno::Reference< com::sun::star::awt::XBitmap >  xBitmap,
                                            const   com::sun::star::uno::Any&   aNewValue       ,
                                            com::sun::star::uno::Any&           aOldValue       ,
                                            com::sun::star::uno::Any&           aConvertedValue ) throw( com::sun::star::lang::IllegalArgumentException );

        sal_Bool impl_tryToChangeProperty(  const   com::sun::star::uno::Reference< com::sun::star::uno::XInterface > xInterface,
                                            const   com::sun::star::uno::Any&   aNewValue       ,
                                            com::sun::star::uno::Any&           aOldValue       ,
                                            com::sun::star::uno::Any&           aConvertedValue ) throw( com::sun::star::lang::IllegalArgumentException );

        //---------------------------------------------------------------------------------------------------------
        //  members
        //---------------------------------------------------------------------------------------------------------

        rtl::OUString                                                           m_aCommandURL;
        rtl::OUString                                                           m_aHelpURL;
        rtl::OUString                                                           m_aText;
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XBitmap >      m_xBitmap;
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >   m_xActionTriggerContainer;
};

}

#endif // __FRAMEWORK_CLASSES_ACTIONTRIGGERPROPERTYSET_HXX_
<|endoftext|>


<commit_before>#include "osg/ProxyNode"
#include "osg/Notify"
#include <osg/io_utils>

#include "osgDB/Registry"
#include "osgDB/Input"
#include "osgDB/Output"
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>

using namespace osg;
using namespace osgDB;

// forward declare functions to use later.
bool ProxyNode_readLocalData(Object& obj, Input& fr);
bool ProxyNode_writeLocalData(const Object& obj, Output& fw);

// register the read and write functions with the osgDB::Registry.
REGISTER_DOTOSGWRAPPER(ProxyNode)
(
    new osg::ProxyNode,
    "ProxyNode",
    "Object Node ProxyNode",
    &ProxyNode_readLocalData,
    &ProxyNode_writeLocalData
);

bool ProxyNode_readLocalData(Object& obj, Input& fr)
{
    bool iteratorAdvanced = false;

    ProxyNode& proxyNode = static_cast<ProxyNode&>(obj);

    if (fr.matchSequence("Center %f %f %f"))
    {
        Vec3 center;
        fr[1].getFloat(center[0]);
        fr[2].getFloat(center[1]);
        fr[3].getFloat(center[2]);
        proxyNode.setCenter(center);

        iteratorAdvanced = true;
        fr+=4;
    }
    else
        proxyNode.setCenterMode(osg::ProxyNode::USE_BOUNDING_SPHERE_CENTER);

    if (fr.matchSequence("ExtRefMode %s") || fr.matchSequence("ExtRefMode %w"))
    {
        if      (fr[1].matchWord("LOAD_IMMEDIATELY"))
            proxyNode.setLoadingExternalReferenceMode(ProxyNode::LOAD_IMMEDIATELY);
        else if (fr[1].matchWord("DEFER_LOADING_TO_DATABASE_PAGER"))
            proxyNode.setLoadingExternalReferenceMode(ProxyNode::DEFER_LOADING_TO_DATABASE_PAGER);
        else if (fr[1].matchWord("NO_AUTOMATIC_LOADING"))
            proxyNode.setLoadingExternalReferenceMode(ProxyNode::NO_AUTOMATIC_LOADING);

        fr+=2;
        iteratorAdvanced = true;
    }

    float radius;
    if (fr[0].matchWord("Radius") && fr[1].getFloat(radius))
    {
        proxyNode.setRadius(radius);
        fr+=2;
        iteratorAdvanced = true;
    }

    if (fr.getOptions() && !fr.getOptions()->getDatabasePathList().empty())
    {
        const std::string& path = fr.getOptions()->getDatabasePathList().front();
        if (!path.empty())
        {
            proxyNode.setDatabasePath(path);
        }
    }

    bool matchFirst;
    if ((matchFirst=fr.matchSequence("FileNameList {")) || fr.matchSequence("FileNameList %i {"))
    {

        // set up coordinates.
        int entry = fr[0].getNoNestedBrackets();
        if (matchFirst)
        {
            fr += 2;
        }
        else
        {
            fr += 3;
        }

        unsigned int i=0;
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            if (fr[0].isString() || fr[0].isQuotedString())
            {
                if (fr[0].getStr()) proxyNode.setFileName(i,fr[0].getStr());
                else proxyNode.setFileName(i,"");

                ++fr;
                ++i;
            }
            else
            {
                ++fr;
            }
        }

        iteratorAdvanced = true;
        ++fr;

    }

    unsigned int num_children = 0;
    if (fr[0].matchWord("num_children") &&
        fr[1].getUInt(num_children))
    {
        // could allocate space for children here...
        fr+=2;
        iteratorAdvanced = true;
    }

    unsigned int i;
    for(i=0; i<num_children; i++)
    {
        osgDB::FilePathList& fpl = ((osgDB::ReaderWriter::Options*)fr.getOptions())->getDatabasePathList();
        fpl.push_front( fpl.empty() ? osgDB::getFilePath(proxyNode.getFileName(i)) : fpl.front()+'/'+ osgDB::getFilePath(proxyNode.getFileName(i)));
        Node* node = NULL;
        if((node=fr.readNode())!=NULL)
        {
            proxyNode.addChild(node);
            iteratorAdvanced = true;
        }
        fpl.pop_front();
    }

    if(proxyNode.getLoadingExternalReferenceMode() == ProxyNode::LOAD_IMMEDIATELY)
    {
        for(i=0; i<proxyNode.getNumFileNames(); i++)
        {
            if(i>=proxyNode.getNumChildren() && !proxyNode.getFileName(i).empty())
            {
                osgDB::FilePathList& fpl = ((osgDB::ReaderWriter::Options*)fr.getOptions())->getDatabasePathList();
                fpl.push_front( fpl.empty() ? osgDB::getFilePath(proxyNode.getFileName(i)) : fpl.front()+'/'+ osgDB::getFilePath(proxyNode.getFileName(i)));
                osg::Node *node = osgDB::readNodeFile(proxyNode.getFileName(i), fr.getOptions());
                fpl.pop_front();
                if(node)
                {
                    proxyNode.insertChild(i, node);
                }
            }
        }
    }

    return iteratorAdvanced;
}

bool ProxyNode_writeLocalData(const Object& obj, Output& fw)
{
    bool includeExternalReferences = false;
    bool useOriginalExternalReferences = true;
    bool writeExternalReferenceFiles = false;
    if (fw.getOptions())
    {
        std::string optionsString = fw.getOptions()->getOptionString();
        includeExternalReferences = optionsString.find("includeExternalReferences")!=std::string::npos;
        bool newExternals = optionsString.find("writeExternalReferenceFiles")!=std::string::npos;
        if (newExternals)
        {
            useOriginalExternalReferences = false;
            writeExternalReferenceFiles = true;
        }
    }
    const ProxyNode& proxyNode = static_cast<const ProxyNode&>(obj);

    if (proxyNode.getCenterMode()==osg::ProxyNode::USER_DEFINED_CENTER) fw.indent() << "Center "<< proxyNode.getCenter() << std::endl;

    fw.indent() << "ExtRefMode ";

    switch(proxyNode.getLoadingExternalReferenceMode())
    {
    case ProxyNode::LOAD_IMMEDIATELY:
        fw.indent() << "LOAD_IMMEDIATELY" <<std::endl;
        break;
    case ProxyNode::DEFER_LOADING_TO_DATABASE_PAGER:
        fw.indent() << "DEFER_LOADING_TO_DATABASE_PAGER" <<std::endl;
        break;
    case ProxyNode::NO_AUTOMATIC_LOADING:
        fw.indent() << "NO_AUTOMATIC_LOADING" <<std::endl;
        break;
    }

    fw.indent() << "Radius "<<proxyNode.getRadius()<<std::endl;

    fw.indent() << "FileNameList "<<proxyNode.getNumFileNames()<<" {"<< std::endl;
    fw.moveIn();

    unsigned int numChildrenToWriteOut = 0;

    for(unsigned int i=0; i<proxyNode.getNumFileNames();++i)
    {
        if (proxyNode.getFileName(i).empty())
        {
            fw.indent() << "\"\"" << std::endl;
            ++numChildrenToWriteOut;
        }
        else
        {
            if(useOriginalExternalReferences)
            {
                fw.indent() << proxyNode.getFileName(i) << std::endl;
            }
            else
            {
                std::string path = osgDB::getFilePath(fw.getFileName());
                std::string new_filename = osgDB::getStrippedName(proxyNode.getFileName(i)) +".osg";
                std::string osgname = path.empty() ? new_filename :  (path +"/"+ new_filename) ;
                fw.indent() << osgname << std::endl;
            }
        }
    }
    fw.moveOut();
    fw.indent() << "}"<< std::endl;

    if(includeExternalReferences) //out->getIncludeExternalReferences()) // inlined mode
    {
        fw.indent() << "num_children " << proxyNode.getNumChildren() << std::endl;
        for(unsigned int i=0; i<proxyNode.getNumChildren(); i++)
        {
            fw.writeObject(*proxyNode.getChild(i));
        }
    }
    else //----------------------------------------- no inlined mode
    {
        fw.indent() << "num_children " << numChildrenToWriteOut << std::endl;
        for(unsigned int i=0; i<proxyNode.getNumChildren(); ++i)
        {
            if (proxyNode.getFileName(i).empty())
            {
                fw.writeObject(*proxyNode.getChild(i));
            }
            else if(writeExternalReferenceFiles) //out->getWriteExternalReferenceFiles())
            {
                if(useOriginalExternalReferences) //out->getUseOriginalExternalReferences())
                {
                    std::string origname = proxyNode.getFileName(i);
                    if (!fw.getExternalFileWritten(origname))
                    {
                        osgDB::writeNodeFile(*proxyNode.getChild(i), origname);
                        fw.setExternalFileWritten(origname, true);
                    }
                }
                else
                {
                    std::string path = osgDB::getFilePath(fw.getFileName());
                    std::string new_filename = osgDB::getStrippedName(proxyNode.getFileName(i)) +".osg";
                    std::string osgname = path.empty() ? new_filename :  (path +"/"+ new_filename) ;
                    if (!fw.getExternalFileWritten(osgname))
                    {
                        osgDB::writeNodeFile(*proxyNode.getChild(i), osgname);
                        fw.setExternalFileWritten(osgname, true);
                    }
                }
            }
        }
    }

    return true;
}
<commit_msg>From Laurens Voerman, "I found a new way to crach the osgviewer: osgviewer "ProxyNode { FileNameList { cow.osgt } num_children 1 }".osgs<commit_after>#include "osg/ProxyNode"
#include "osg/Notify"
#include <osg/io_utils>

#include "osgDB/Registry"
#include "osgDB/Input"
#include "osgDB/Output"
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>

using namespace osg;
using namespace osgDB;

// forward declare functions to use later.
bool ProxyNode_readLocalData(Object& obj, Input& fr);
bool ProxyNode_writeLocalData(const Object& obj, Output& fw);

// register the read and write functions with the osgDB::Registry.
REGISTER_DOTOSGWRAPPER(ProxyNode)
(
    new osg::ProxyNode,
    "ProxyNode",
    "Object Node ProxyNode",
    &ProxyNode_readLocalData,
    &ProxyNode_writeLocalData
);

bool ProxyNode_readLocalData(Object& obj, Input& fr)
{
    bool iteratorAdvanced = false;

    ProxyNode& proxyNode = static_cast<ProxyNode&>(obj);

    if (fr.matchSequence("Center %f %f %f"))
    {
        Vec3 center;
        fr[1].getFloat(center[0]);
        fr[2].getFloat(center[1]);
        fr[3].getFloat(center[2]);
        proxyNode.setCenter(center);

        iteratorAdvanced = true;
        fr+=4;
    }
    else
        proxyNode.setCenterMode(osg::ProxyNode::USE_BOUNDING_SPHERE_CENTER);

    if (fr.matchSequence("ExtRefMode %s") || fr.matchSequence("ExtRefMode %w"))
    {
        if      (fr[1].matchWord("LOAD_IMMEDIATELY"))
            proxyNode.setLoadingExternalReferenceMode(ProxyNode::LOAD_IMMEDIATELY);
        else if (fr[1].matchWord("DEFER_LOADING_TO_DATABASE_PAGER"))
            proxyNode.setLoadingExternalReferenceMode(ProxyNode::DEFER_LOADING_TO_DATABASE_PAGER);
        else if (fr[1].matchWord("NO_AUTOMATIC_LOADING"))
            proxyNode.setLoadingExternalReferenceMode(ProxyNode::NO_AUTOMATIC_LOADING);

        fr+=2;
        iteratorAdvanced = true;
    }

    float radius;
    if (fr[0].matchWord("Radius") && fr[1].getFloat(radius))
    {
        proxyNode.setRadius(radius);
        fr+=2;
        iteratorAdvanced = true;
    }

    if (fr.getOptions() && !fr.getOptions()->getDatabasePathList().empty())
    {
        const std::string& path = fr.getOptions()->getDatabasePathList().front();
        if (!path.empty())
        {
            proxyNode.setDatabasePath(path);
        }
    }

    bool matchFirst;
    if ((matchFirst=fr.matchSequence("FileNameList {")) || fr.matchSequence("FileNameList %i {"))
    {

        // set up coordinates.
        int entry = fr[0].getNoNestedBrackets();
        if (matchFirst)
        {
            fr += 2;
        }
        else
        {
            fr += 3;
        }

        unsigned int i=0;
        while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
        {
            if (fr[0].isString() || fr[0].isQuotedString())
            {
                if (fr[0].getStr()) proxyNode.setFileName(i,fr[0].getStr());
                else proxyNode.setFileName(i,"");

                ++fr;
                ++i;
            }
            else
            {
                ++fr;
            }
        }

        iteratorAdvanced = true;
        ++fr;

    }

    unsigned int num_children = 0;
    if (fr[0].matchWord("num_children") &&
        fr[1].getUInt(num_children))
    {
        // could allocate space for children here...
        fr+=2;
        iteratorAdvanced = true;
    }

    bool make_options = (fr.getOptions() == NULL);
    if (make_options) fr.setOptions(new osgDB::Options()); //need valid options
    unsigned int i;
    for(i=0; i<num_children; i++)
    {
        osgDB::FilePathList& fpl = ((osgDB::ReaderWriter::Options*)fr.getOptions())->getDatabasePathList();
        fpl.push_front( fpl.empty() ? osgDB::getFilePath(proxyNode.getFileName(i)) : fpl.front()+'/'+ osgDB::getFilePath(proxyNode.getFileName(i)));
        Node* node = NULL;
        if((node=fr.readNode())!=NULL)
        {
            proxyNode.addChild(node);
            iteratorAdvanced = true;
        }
        fpl.pop_front();
    }

    if(proxyNode.getLoadingExternalReferenceMode() == ProxyNode::LOAD_IMMEDIATELY)
    {
        for(i=0; i<proxyNode.getNumFileNames(); i++)
        {
            if(i>=proxyNode.getNumChildren() && !proxyNode.getFileName(i).empty())
            {
                osgDB::FilePathList& fpl = ((osgDB::ReaderWriter::Options*)fr.getOptions())->getDatabasePathList();
                fpl.push_front( fpl.empty() ? osgDB::getFilePath(proxyNode.getFileName(i)) : fpl.front()+'/'+ osgDB::getFilePath(proxyNode.getFileName(i)));
                osg::Node *node = osgDB::readNodeFile(proxyNode.getFileName(i), fr.getOptions());
                fpl.pop_front();
                if(node)
                {
                    proxyNode.insertChild(i, node);
                }
            }
        }
    }
    if (make_options) fr.setOptions(NULL);
    return iteratorAdvanced;
}

bool ProxyNode_writeLocalData(const Object& obj, Output& fw)
{
    bool includeExternalReferences = false;
    bool useOriginalExternalReferences = true;
    bool writeExternalReferenceFiles = false;
    if (fw.getOptions())
    {
        std::string optionsString = fw.getOptions()->getOptionString();
        includeExternalReferences = optionsString.find("includeExternalReferences")!=std::string::npos;
        bool newExternals = optionsString.find("writeExternalReferenceFiles")!=std::string::npos;
        if (newExternals)
        {
            useOriginalExternalReferences = false;
            writeExternalReferenceFiles = true;
        }
    }
    const ProxyNode& proxyNode = static_cast<const ProxyNode&>(obj);

    if (proxyNode.getCenterMode()==osg::ProxyNode::USER_DEFINED_CENTER) fw.indent() << "Center "<< proxyNode.getCenter() << std::endl;

    fw.indent() << "ExtRefMode ";

    switch(proxyNode.getLoadingExternalReferenceMode())
    {
    case ProxyNode::LOAD_IMMEDIATELY:
        fw.indent() << "LOAD_IMMEDIATELY" <<std::endl;
        break;
    case ProxyNode::DEFER_LOADING_TO_DATABASE_PAGER:
        fw.indent() << "DEFER_LOADING_TO_DATABASE_PAGER" <<std::endl;
        break;
    case ProxyNode::NO_AUTOMATIC_LOADING:
        fw.indent() << "NO_AUTOMATIC_LOADING" <<std::endl;
        break;
    }

    fw.indent() << "Radius "<<proxyNode.getRadius()<<std::endl;

    fw.indent() << "FileNameList "<<proxyNode.getNumFileNames()<<" {"<< std::endl;
    fw.moveIn();

    unsigned int numChildrenToWriteOut = 0;

    for(unsigned int i=0; i<proxyNode.getNumFileNames();++i)
    {
        if (proxyNode.getFileName(i).empty())
        {
            fw.indent() << "\"\"" << std::endl;
            ++numChildrenToWriteOut;
        }
        else
        {
            if(useOriginalExternalReferences)
            {
                fw.indent() << proxyNode.getFileName(i) << std::endl;
            }
            else
            {
                std::string path = osgDB::getFilePath(fw.getFileName());
                std::string new_filename = osgDB::getStrippedName(proxyNode.getFileName(i)) +".osg";
                std::string osgname = path.empty() ? new_filename :  (path +"/"+ new_filename) ;
                fw.indent() << osgname << std::endl;
            }
        }
    }
    fw.moveOut();
    fw.indent() << "}"<< std::endl;

    if(includeExternalReferences) //out->getIncludeExternalReferences()) // inlined mode
    {
        fw.indent() << "num_children " << proxyNode.getNumChildren() << std::endl;
        for(unsigned int i=0; i<proxyNode.getNumChildren(); i++)
        {
            fw.writeObject(*proxyNode.getChild(i));
        }
    }
    else //----------------------------------------- no inlined mode
    {
        fw.indent() << "num_children " << numChildrenToWriteOut << std::endl;
        for(unsigned int i=0; i<proxyNode.getNumChildren(); ++i)
        {
            if (proxyNode.getFileName(i).empty())
            {
                fw.writeObject(*proxyNode.getChild(i));
            }
            else if(writeExternalReferenceFiles) //out->getWriteExternalReferenceFiles())
            {
                if(useOriginalExternalReferences) //out->getUseOriginalExternalReferences())
                {
                    std::string origname = proxyNode.getFileName(i);
                    if (!fw.getExternalFileWritten(origname))
                    {
                        osgDB::writeNodeFile(*proxyNode.getChild(i), origname);
                        fw.setExternalFileWritten(origname, true);
                    }
                }
                else
                {
                    std::string path = osgDB::getFilePath(fw.getFileName());
                    std::string new_filename = osgDB::getStrippedName(proxyNode.getFileName(i)) +".osg";
                    std::string osgname = path.empty() ? new_filename :  (path +"/"+ new_filename) ;
                    if (!fw.getExternalFileWritten(osgname))
                    {
                        osgDB::writeNodeFile(*proxyNode.getChild(i), osgname);
                        fw.setExternalFileWritten(osgname, true);
                    }
                }
            }
        }
    }

    return true;
}
<|endoftext|>


<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "recoveryvisitor.h"

#include <vespa/documentapi/messagebus/messages/visitor.h>
#include <vespa/vespalib/stllike/hash_map.hpp>

#include <vespa/log/log.h>
LOG_SETUP(".visitor.instance.recoveryvisitor");

namespace storage {

RecoveryVisitor::RecoveryVisitor(StorageComponent& component,
                                 const vdslib::Parameters& params)
    : Visitor(component)
{
    if (params.hasValue("requestfields")) {
        std::string fields = params.get("requestfields");

        vespalib::StringTokenizer tokenizer(fields);
        for (uint32_t i = 0; i < tokenizer.size(); i++) {
            _requestedFields.insert(tokenizer[i]);
        }
    }

    LOG(debug, "Created RecoveryVisitor with %d requested fields", (int)_requestedFields.size());
}

void
RecoveryVisitor::handleDocuments(const document::BucketId& bid,
                                 std::vector<spi::DocEntry::LP>& entries,
                                 HitCounter& hitCounter)
{
    vespalib::LockGuard guard(_mutex);

    LOG(debug, "Visitor %s handling block of %zu documents.",
               _id.c_str(), entries.size());

    documentapi::DocumentListMessage* cmd = NULL;

    {
        CommandMap::iterator iter = _activeCommands.find(bid);

        if (iter == _activeCommands.end()) {
            CommandPtr ptr(new documentapi::DocumentListMessage(bid));
            cmd = ptr.get();
            _activeCommands[bid] = ptr;
        } else {
            cmd = iter->second.get();
        }
    }

    // Remove all fields from the document that are not listed in requestedFields.
    for (size_t i = 0; i < entries.size(); ++i) {
        const spi::DocEntry& entry(*entries[i]);
        std::unique_ptr<document::Document> doc(entry.getDocument()->clone());
        if (_requestedFields.empty()) {
            doc->clear();
        } else {
            for (document::Document::const_iterator docIter = doc->begin();
                 docIter != doc->end();
                 docIter++) {
                if (_requestedFields.find(docIter.field().getName())
                    == _requestedFields.end())
                {
                    doc->remove(docIter.field());
                }
            }
        }

        hitCounter.addHit(doc->getId(), doc->serialize()->getLength());

        int64_t timestamp = doc->getLastModified();
        cmd->getDocuments().push_back(documentapi::DocumentListMessage::Entry(
                                                 timestamp,
                                                 document::Document::SP(doc.release()),
                                                 entry.isRemove()));
    }
}

void RecoveryVisitor::completedBucket(const document::BucketId& bid, HitCounter&)
{
    documentapi::DocumentMessage::UP _msgToSend;

    LOG(debug, "Finished bucket %s", bid.toString().c_str());

    {
        vespalib::LockGuard guard(_mutex);

        CommandMap::iterator iter = _activeCommands.find(bid);

        if (iter != _activeCommands.end()) {
            _msgToSend.reset(iter->second.release());
            _activeCommands.erase(iter);
        }
    }

    if (_msgToSend.get()) {
        sendMessage(std::move(_msgToSend));
    }
}

}
<commit_msg>No more postfix operator.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "recoveryvisitor.h"

#include <vespa/documentapi/messagebus/messages/visitor.h>
#include <vespa/vespalib/stllike/hash_map.hpp>

#include <vespa/log/log.h>
LOG_SETUP(".visitor.instance.recoveryvisitor");

namespace storage {

RecoveryVisitor::RecoveryVisitor(StorageComponent& component,
                                 const vdslib::Parameters& params)
    : Visitor(component)
{
    if (params.hasValue("requestfields")) {
        std::string fields = params.get("requestfields");

        vespalib::StringTokenizer tokenizer(fields);
        for (uint32_t i = 0; i < tokenizer.size(); i++) {
            _requestedFields.insert(tokenizer[i]);
        }
    }

    LOG(debug, "Created RecoveryVisitor with %d requested fields", (int)_requestedFields.size());
}

void
RecoveryVisitor::handleDocuments(const document::BucketId& bid,
                                 std::vector<spi::DocEntry::LP>& entries,
                                 HitCounter& hitCounter)
{
    vespalib::LockGuard guard(_mutex);

    LOG(debug, "Visitor %s handling block of %zu documents.",
               _id.c_str(), entries.size());

    documentapi::DocumentListMessage* cmd = NULL;

    {
        CommandMap::iterator iter = _activeCommands.find(bid);

        if (iter == _activeCommands.end()) {
            CommandPtr ptr(new documentapi::DocumentListMessage(bid));
            cmd = ptr.get();
            _activeCommands[bid] = ptr;
        } else {
            cmd = iter->second.get();
        }
    }

    // Remove all fields from the document that are not listed in requestedFields.
    for (size_t i = 0; i < entries.size(); ++i) {
        const spi::DocEntry& entry(*entries[i]);
        std::unique_ptr<document::Document> doc(entry.getDocument()->clone());
        if (_requestedFields.empty()) {
            doc->clear();
        } else {
            for (document::Document::const_iterator docIter = doc->begin();
                 docIter != doc->end();
                 ++docIter) {
                if (_requestedFields.find(docIter.field().getName())
                    == _requestedFields.end())
                {
                    doc->remove(docIter.field());
                }
            }
        }

        hitCounter.addHit(doc->getId(), doc->serialize()->getLength());

        int64_t timestamp = doc->getLastModified();
        cmd->getDocuments().push_back(documentapi::DocumentListMessage::Entry(
                                                 timestamp,
                                                 document::Document::SP(doc.release()),
                                                 entry.isRemove()));
    }
}

void RecoveryVisitor::completedBucket(const document::BucketId& bid, HitCounter&)
{
    documentapi::DocumentMessage::UP _msgToSend;

    LOG(debug, "Finished bucket %s", bid.toString().c_str());

    {
        vespalib::LockGuard guard(_mutex);

        CommandMap::iterator iter = _activeCommands.find(bid);

        if (iter != _activeCommands.end()) {
            _msgToSend.reset(iter->second.release());
            _activeCommands.erase(iter);
        }
    }

    if (_msgToSend.get()) {
        sendMessage(std::move(_msgToSend));
    }
}

}
<|endoftext|>


<commit_before>#include <windows.h>
#include "PopupMenu.hpp"

#define TRAY_ID 666
#define TRAY_MSG 666

struct WindowData
{
    PopupMenu* menu;
};

void HandleMenuSelection(PopupMenu::MenuItem item, HWND window)
{
    WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA);
    if(item.id == data->menu->GetIdByTitle("exit"))
        SendMessage(window, WM_CLOSE, 0, 0);
}

LRESULT CALLBACK HitmonWindowProc(
    HWND   window,
    UINT   msg,
    WPARAM wParam,
    LPARAM lParam)
{
    switch(msg)
    {
        // Handle messages from tray icon
        case TRAY_MSG:
        {
            switch(lParam)
            {
                case WM_LBUTTONDOWN:
                {
                    WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA);
                    data->menu->Show();
                }break;
            }
        }break;

        case WM_CREATE:
        {
            // Configure window data
            WindowData* data = new WindowData();
            data->menu = new PopupMenu(window, HandleMenuSelection);
            data->menu->AddItem(1, "Do something");
            data->menu->AddItem(2, "Do something else");
            data->menu->AddItem(3, "exit");

            // Set userdata
            SetWindowLongPtr(window, GWLP_USERDATA, (LONG_PTR)data);
        }break;

        case WM_DESTROY:
        {
            WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA);
            delete data->menu;
            delete data;
            PostQuitMessage(0);
        }break;

        default:
        {
            return DefWindowProc(window, msg, wParam, lParam);
        }
    }

    return 0;
}

WNDCLASSEX CreateWindowClass(HINSTANCE instance)
{
    WNDCLASSEX mainWClass;
    mainWClass.cbSize = sizeof(WNDCLASSEX);
    mainWClass.style = CS_HREDRAW | CS_VREDRAW;
    mainWClass.lpfnWndProc = HitmonWindowProc;
    mainWClass.cbClsExtra = 0;
    mainWClass.cbWndExtra = 0;
    mainWClass.hInstance = instance;
    mainWClass.hIcon = LoadIcon(0, IDI_SHIELD);
    mainWClass.hCursor = LoadCursor(0, IDC_CROSS);
    mainWClass.hbrBackground = 0;
    mainWClass.lpszMenuName = 0;
    mainWClass.lpszClassName = "MainWClass";
    mainWClass.hIconSm = 0;

    return mainWClass;
}

NOTIFYICONDATA ShowTrayIcon(HWND window)
{
    NOTIFYICONDATA rVal;
    rVal.cbSize = sizeof(rVal);
    rVal.hWnd = window;
    rVal.uID = TRAY_ID;
    rVal.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
    rVal.uCallbackMessage = TRAY_MSG;
    rVal.hIcon = LoadIcon(0, IDI_SHIELD);
    strncpy(rVal.szTip, "Hitmon is running...", 128);
    // Set guid later
    //rVal.guidItem = ...;

    Shell_NotifyIcon(NIM_ADD, &rVal);

    return rVal;
}

int CALLBACK WinMain(
    HINSTANCE instance,
    HINSTANCE prevInstance,
    LPSTR     cmdArgs,
    int       cmdShow)
{
    (void)prevInstance;
    (void)cmdArgs;
    (void)cmdShow;

    // Create window class
    WNDCLASSEX mainWClass = CreateWindowClass(instance);

    // Register window class
    if(RegisterClassEx(&mainWClass) == 0)
        return -1;

    // Create window
    HWND window = CreateWindowEx(
        0,                              // Extended window style of the window created
        "MainWClass",                   // Class name from previous call to RegisterClass[Ex]
        "Hitmon",                       // Window Name
        0,                              // Window style
        64,                             // Initial x position for window
        64,                             // Initial y position for window
        640,                            // Window width
        480,                            // Window height
        0,                              // Handle to parent window
        0,                              // Handle to menu
        instance,                       // A handle to the instance of the module to be associated with the window.
        0);                             // Pointer to params for the window

    if(window == 0)
        return -1;

    // Show tray icon
    NOTIFYICONDATA trayData = ShowTrayIcon(window);

    MSG msg;
    int getMsgRVal;
    while((getMsgRVal = GetMessage(&msg, 0, 0, 0)) != 0)
    {
        if(getMsgRVal == -1)
            return -1;

        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    // Hide tray icon
    Shell_NotifyIcon(NIM_DELETE, &trayData);
    return 0;
}<commit_msg>Fixed message loop and pre-defined message IDs<commit_after>#include <windows.h>
#include "PopupMenu.hpp"

#define TRAY_ID WM_USER + 1
#define TRAY_MSG WM_USER + 2

struct WindowData
{
    PopupMenu* menu;
};

void HandleMenuSelection(PopupMenu::MenuItem item, HWND window)
{
    WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA);
    if(item.id == data->menu->GetIdByTitle("exit"))
        SendMessage(window, WM_CLOSE, 0, 0);
}

LRESULT CALLBACK HitmonWindowProc(
    HWND   window,
    UINT   msg,
    WPARAM wParam,
    LPARAM lParam)
{
    switch(msg)
    {
        // Handle messages from tray icon
        case TRAY_MSG:
        {
            switch(lParam)
            {
                case WM_LBUTTONDOWN:
                {
                    WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA);
                    data->menu->Show();
                }break;
            }
        }break;

        case WM_CREATE:
        {
            // Configure window data
            WindowData* data = new WindowData();
            data->menu = new PopupMenu(window, HandleMenuSelection);
            data->menu->AddItem(1, "Do something");
            data->menu->AddItem(2, "Do something else");
            data->menu->AddItem(3, "exit");

            // Set userdata
            SetWindowLongPtr(window, GWLP_USERDATA, (LONG_PTR)data);
        }break;

        case WM_DESTROY:
        {
            WindowData* data = (WindowData*)GetWindowLongPtr(window, GWLP_USERDATA);
            delete data->menu;
            delete data;
            PostQuitMessage(0);
        }break;

        default:
        {
            return DefWindowProc(window, msg, wParam, lParam);
        }
    }

    return 0;
}

WNDCLASSEX CreateWindowClass(HINSTANCE instance)
{
    WNDCLASSEX mainWClass;
    mainWClass.cbSize = sizeof(WNDCLASSEX);
    mainWClass.style = CS_HREDRAW | CS_VREDRAW;
    mainWClass.lpfnWndProc = HitmonWindowProc;
    mainWClass.cbClsExtra = 0;
    mainWClass.cbWndExtra = 0;
    mainWClass.hInstance = instance;
    mainWClass.hIcon = LoadIcon(0, IDI_SHIELD);
    mainWClass.hCursor = LoadCursor(0, IDC_CROSS);
    mainWClass.hbrBackground = 0;
    mainWClass.lpszMenuName = 0;
    mainWClass.lpszClassName = "MainWClass";
    mainWClass.hIconSm = 0;

    return mainWClass;
}

NOTIFYICONDATA ShowTrayIcon(HWND window)
{
    NOTIFYICONDATA rVal;
    rVal.cbSize = sizeof(rVal);
    rVal.hWnd = window;
    rVal.uID = TRAY_ID;
    rVal.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
    rVal.uCallbackMessage = TRAY_MSG;
    rVal.hIcon = LoadIcon(0, IDI_SHIELD);
    strncpy(rVal.szTip, "Hitmon is running...", 128);
    // Set guid later
    //rVal.guidItem = ...;

    Shell_NotifyIcon(NIM_ADD, &rVal);

    return rVal;
}

int CALLBACK WinMain(
    HINSTANCE instance,
    HINSTANCE prevInstance,
    LPSTR     cmdArgs,
    int       cmdShow)
{
    (void)prevInstance;
    (void)cmdArgs;
    (void)cmdShow;

    // Create window class
    WNDCLASSEX mainWClass = CreateWindowClass(instance);

    // Register window class
    if(RegisterClassEx(&mainWClass) == 0)
        return -1;

    // Create window
    HWND window = CreateWindowEx(
        0,                              // Extended window style of the window created
        "MainWClass",                   // Class name from previous call to RegisterClass[Ex]
        "Hitmon",                       // Window Name
        0,                              // Window style
        64,                             // Initial x position for window
        64,                             // Initial y position for window
        640,                            // Window width
        480,                            // Window height
        0,                              // Handle to parent window
        0,                              // Handle to menu
        instance,                       // A handle to the instance of the module to be associated with the window.
        0);                             // Pointer to params for the window

    if(window == 0)
        return -1;

    // Show tray icon
    NOTIFYICONDATA trayData = ShowTrayIcon(window);

    MSG msg;
    int getMsgRVal;
    while((getMsgRVal = GetMessage(&msg, 0, 0, 0)) > 0)
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    // Hide tray icon
    Shell_NotifyIcon(NIM_DELETE, &trayData);
    return 0;
}<|endoftext|>


<commit_before>/*
  Copyright(C) 2014 Naoya Murakami <naoya@createfield.com>

  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., 51 Franklin Street, Fifth Floor, Boston, MA
  02110-1301  USA
*/

#include <groonga/tokenizer.h>

#include <string.h>
#include <ctype.h>

#include <iostream>
#include <string>
#include <vector>
#include "tinysegmenter.hpp"

using namespace std;

#ifdef __GNUC__
#  define GNUC_UNUSED __attribute__((__unused__))
#else
#  define GNUC_UNUSED
#endif

typedef struct {
  grn_tokenizer_token token;
  grn_tokenizer_query *query;
  vector<string> parsed_vector;
  unsigned int next;
  unsigned int end;
} grn_tinysegmenter_tokenizer;

static grn_obj *
tinysegmenter_init(grn_ctx *ctx, int nargs, grn_obj **args, grn_user_data *user_data)
{
  grn_tokenizer_query *query;
  unsigned int normalize_flags = 0;
  const char *normalized;
  unsigned int normalized_length_in_bytes;
  grn_tinysegmenter_tokenizer *tokenizer;
  TinySegmenter segmenter;

  query = grn_tokenizer_query_open(ctx, nargs, args, normalize_flags);
  if (!query) {
    return NULL;
  }

  tokenizer = static_cast<grn_tinysegmenter_tokenizer *>(
    GRN_PLUGIN_MALLOC(ctx, sizeof(grn_tinysegmenter_tokenizer)));
  if (!tokenizer) {
    GRN_PLUGIN_ERROR(ctx,GRN_NO_MEMORY_AVAILABLE,
                     "[tokenizer][tinysegmenter] "
                     "memory allocation to grn_tinysegmenter_tokenizer failed");
    grn_tokenizer_query_close(ctx, query);
    return NULL;
  }
  user_data->ptr = tokenizer;
  grn_tokenizer_token_init(ctx, &(tokenizer->token));
  tokenizer->query = query;
  grn_string_get_normalized(ctx, tokenizer->query->normalized_query,
                            &normalized, &normalized_length_in_bytes,
                            NULL);

  tokenizer->parsed_vector = segmenter.segment(normalized);
  tokenizer->next = 0;
  tokenizer->end = tokenizer->parsed_vector.size();

  return NULL;
}

static grn_obj *
tinysegmenter_next(grn_ctx *ctx, GNUC_UNUSED int nargs, GNUC_UNUSED grn_obj **args,
               grn_user_data *user_data)
{
  grn_tinysegmenter_tokenizer *tokenizer =
    static_cast<grn_tinysegmenter_tokenizer *>(user_data->ptr);

  grn_tokenizer_status status;

  if (tokenizer->next == tokenizer->end - 1) {
    status = GRN_TOKENIZER_LAST;
  } else {
    status = GRN_TOKENIZER_CONTINUE;
  }
  grn_tokenizer_token_push(ctx, &(tokenizer->token),
                           tokenizer->parsed_vector[tokenizer->next].c_str(),
                           tokenizer->parsed_vector[tokenizer->next].length(),
                           status);
  tokenizer->next++;

  return NULL;
}

static grn_obj *
tinysegmenter_fin(grn_ctx *ctx, GNUC_UNUSED int nargs, GNUC_UNUSED grn_obj **args,
              grn_user_data *user_data)
{
  grn_tinysegmenter_tokenizer *tokenizer =
    static_cast<grn_tinysegmenter_tokenizer *>(user_data->ptr);
  if (!tokenizer) {
    return NULL;
  }
  grn_tokenizer_query_close(ctx, tokenizer->query);
  grn_tokenizer_token_fin(ctx, &(tokenizer->token));
  GRN_PLUGIN_FREE(ctx,tokenizer);
  return NULL;
}

extern "C" {

grn_rc
GRN_PLUGIN_INIT(grn_ctx *ctx)
{
  return ctx->rc;
}

grn_rc
GRN_PLUGIN_REGISTER(grn_ctx *ctx)
{
  grn_rc rc;
  rc = grn_tokenizer_register(ctx, "TokenTinySegmenter", -1,
                              tinysegmenter_init, tinysegmenter_next, tinysegmenter_fin);
  return rc;
}

grn_rc GRN_PLUGIN_FIN(grn_ctx *ctx) {
  return GRN_SUCCESS;
}

}

<commit_msg>Indent<commit_after>/*
  Copyright(C) 2014 Naoya Murakami <naoya@createfield.com>

  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., 51 Franklin Street, Fifth Floor, Boston, MA
  02110-1301  USA
*/

#include <groonga/tokenizer.h>

#include <string.h>
#include <ctype.h>

#include <iostream>
#include <string>
#include <vector>
#include "tinysegmenter.hpp"

using namespace std;

#ifdef __GNUC__
#  define GNUC_UNUSED __attribute__((__unused__))
#else
#  define GNUC_UNUSED
#endif

typedef struct {
  grn_tokenizer_token token;
  grn_tokenizer_query *query;
  vector<string> parsed_vector;
  unsigned int next;
  unsigned int end;
} grn_tinysegmenter_tokenizer;

static grn_obj *
tinysegmenter_init(grn_ctx *ctx, int nargs, grn_obj **args, grn_user_data *user_data)
{
  grn_tokenizer_query *query;
  unsigned int normalize_flags = 0;
  const char *normalized;
  unsigned int normalized_length_in_bytes;
  grn_tinysegmenter_tokenizer *tokenizer;
  TinySegmenter segmenter;

  query = grn_tokenizer_query_open(ctx, nargs, args, normalize_flags);
  if (!query) {
    return NULL;
  }

  tokenizer = static_cast<grn_tinysegmenter_tokenizer *>(
    GRN_PLUGIN_MALLOC(ctx, sizeof(grn_tinysegmenter_tokenizer)));
  if (!tokenizer) {
    GRN_PLUGIN_ERROR(ctx,GRN_NO_MEMORY_AVAILABLE,
                     "[tokenizer][tinysegmenter] "
                     "memory allocation to grn_tinysegmenter_tokenizer failed");
    grn_tokenizer_query_close(ctx, query);
    return NULL;
  }
  user_data->ptr = tokenizer;
  grn_tokenizer_token_init(ctx, &(tokenizer->token));
  tokenizer->query = query;
  grn_string_get_normalized(ctx, tokenizer->query->normalized_query,
                            &normalized, &normalized_length_in_bytes,
                            NULL);

  tokenizer->parsed_vector = segmenter.segment(normalized);
  tokenizer->next = 0;
  tokenizer->end = tokenizer->parsed_vector.size();

  return NULL;
}

static grn_obj *
tinysegmenter_next(grn_ctx *ctx, GNUC_UNUSED int nargs, GNUC_UNUSED grn_obj **args,
                   grn_user_data *user_data)
{
  grn_tinysegmenter_tokenizer *tokenizer =
    static_cast<grn_tinysegmenter_tokenizer *>(user_data->ptr);

  grn_tokenizer_status status;

  if (tokenizer->next == tokenizer->end - 1) {
    status = GRN_TOKENIZER_LAST;
  } else {
    status = GRN_TOKENIZER_CONTINUE;
  }
  grn_tokenizer_token_push(ctx, &(tokenizer->token),
                           tokenizer->parsed_vector[tokenizer->next].c_str(),
                           tokenizer->parsed_vector[tokenizer->next].length(),
                           status);
  tokenizer->next++;

  return NULL;
}

static grn_obj *
tinysegmenter_fin(grn_ctx *ctx, GNUC_UNUSED int nargs, GNUC_UNUSED grn_obj **args,
                  grn_user_data *user_data)
{
  grn_tinysegmenter_tokenizer *tokenizer =
    static_cast<grn_tinysegmenter_tokenizer *>(user_data->ptr);
  if (!tokenizer) {
    return NULL;
  }
  grn_tokenizer_query_close(ctx, tokenizer->query);
  grn_tokenizer_token_fin(ctx, &(tokenizer->token));
  GRN_PLUGIN_FREE(ctx,tokenizer);
  return NULL;
}

extern "C" {

grn_rc
GRN_PLUGIN_INIT(grn_ctx *ctx)
{
  return ctx->rc;
}

grn_rc
GRN_PLUGIN_REGISTER(grn_ctx *ctx)
{
  grn_rc rc;
  rc = grn_tokenizer_register(ctx, "TokenTinySegmenter", -1,
                              tinysegmenter_init, tinysegmenter_next, tinysegmenter_fin);
  return rc;
}

grn_rc
GRN_PLUGIN_FIN(grn_ctx *ctx)
{
  return GRN_SUCCESS;
}

}

<|endoftext|>


<commit_before>/*
 * Main.cpp
 *
 *  Created on: Mar 17, 2015
 *      Author: jonno
 */
#include <iostream>
#include <cstdio>
#include <sha.h>
#include <memory>
#include "Chord.h"

using namespace std;

void showUsageMessage(string procname) {
	cerr << "To run Chord, you need to provide a port to listen on." << endl;
	cerr << "\tUsage: " << procname << " port" << endl;
	cerr << "\tExample: " << procname << " 8001" << endl;
	cerr
			<< "If you are connecting to an existing Chord network, use the following:"
			<< endl;
	cerr << "\t" << procname
			<< " port [entry point IP address] [entry point port]" << endl;
	cerr << "\tExample: " << procname << " 8001 128.2.205.42 8010" << endl;
	exit(1);
}

int main(int argc, const char* argv[]) {
	string port;
	string entry_ip, entry_port;

	unique_ptr<Chord> chord;

	int listen_port;

	if (argc < 2) {
		showUsageMessage(argv[0]);
	}

	// port to listen on
	if (argc > 1) {
		port = argv[1];
	}
	// connecting to an entry point
	if (argc > 2) {
		entry_ip = argv[2];
	}
	// entry point port
	if (argc > 3) {
		entry_port = argv[3];
	}

	if (!entry_ip.empty() && entry_port.empty()) {
		showUsageMessage(argv[0]);
	}

	listen_port = atoi(port.c_str());

	chord = unique_ptr<Chord>(new Chord(listen_port));

	if (entry_ip.empty()) {

	}

	if (!entry_ip.empty() && !entry_port.empty()) {
		int entry_port_i = atoi(entry_port.c_str());
		chord->JoinRing(entry_ip, entry_port_i);
	}

	chord->Listen();

	return 0;
}

<commit_msg>MAde Main work with Singleton<commit_after>/*
 * Main.cpp
 *
 *  Created on: Mar 17, 2015
 *      Author: jonno
 */
#include <iostream>
#include <cstdio>
#include <sha.h>
#include <memory>
#include "Chord.h"

using namespace std;

void showUsageMessage(string procname) {
	cerr << "To run Chord, you need to provide a port to listen on." << endl;
	cerr << "\tUsage: " << procname << " port" << endl;
	cerr << "\tExample: " << procname << " 8001" << endl;
	cerr
			<< "If you are connecting to an existing Chord network, use the following:"
			<< endl;
	cerr << "\t" << procname
			<< " port [entry point IP address] [entry point port]" << endl;
	cerr << "\tExample: " << procname << " 8001 128.2.205.42 8010" << endl;
	exit(1);
}

int main(int argc, const char* argv[]) {
	string port;
	string entry_ip, entry_port;

	shared_ptr<Chord> chord;

	int listen_port;

	if (argc < 2) {
		showUsageMessage(argv[0]);
	}

	// port to listen on
	if (argc > 1) {
		port = argv[1];
	}
	// connecting to an entry point
	if (argc > 2) {
		entry_ip = argv[2];
	}
	// entry point port
	if (argc > 3) {
		entry_port = argv[3];
	}

	if (!entry_ip.empty() && entry_port.empty()) {
		showUsageMessage(argv[0]);
	}

	listen_port = atoi(port.c_str());

	chord = Chord::getInstance();
	if (chord != nullptr) {
		chord->init(listen_port);
	}

	if (entry_ip.empty()) {

	}

	if (!entry_ip.empty() && !entry_port.empty()) {
		int entry_port_i = atoi(entry_port.c_str());
		chord->JoinRing(entry_ip, entry_port_i);
	}

	chord->Listen();

	return 0;
}

<|endoftext|>


<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <fstream>
#include "paddle/fluid/framework/data_type_transform.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/platform/device_context.h"

namespace paddle {
namespace operators {

class LoadCombineOp : public framework::OperatorBase {
 public:
  LoadCombineOp(const std::string &type,
                const framework::VariableNameMap &inputs,
                const framework::VariableNameMap &outputs,
                const framework::AttributeMap &attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {
    auto filename = Attr<std::string>("file_path");
    auto load_as_fp16 = Attr<bool>("load_as_fp16");
    auto model_from_memory = Attr<bool>("model_from_memory");
    auto out_var_names = Outputs("Out");
    PADDLE_ENFORCE_GT(
        static_cast<int>(out_var_names.size()), 0,
        "The number of output variables should be greater than 0.");
    if (!model_from_memory) {
      std::ifstream fin(filename, std::ios::binary);
      PADDLE_ENFORCE(static_cast<bool>(fin),
                     "Cannot open file %s for load_combine op", filename);
      LoadParamsFromBuffer(scope, place, &fin, load_as_fp16, out_var_names);
    } else {
      PADDLE_ENFORCE(!filename.empty(), "Cannot load file from memory");
      std::stringstream fin(filename);
      LoadParamsFromBuffer(scope, place, &fin, load_as_fp16, out_var_names);
    }
  }
  void LoadParamsFromBuffer(
      const framework::Scope &scope, const platform::Place &place,
      std::istream *buffer, bool load_as_fp16,
      const std::vector<std::string> &out_var_names) const {
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(place);

    for (size_t i = 0; i < out_var_names.size(); i++) {
      auto *out_var = scope.FindVar(out_var_names[i]);

      PADDLE_ENFORCE(out_var != nullptr, "Output variable %s cannot be found",
                     out_var_names[i]);

      auto *tensor = out_var->GetMutable<framework::LoDTensor>();

      // Error checking
      PADDLE_ENFORCE(static_cast<bool>(buffer), "Cannot read more");

      // Get data from fin to tensor
      DeserializeFromStream(*buffer, tensor, dev_ctx);

      auto in_dtype = tensor->type();
      auto out_dtype =
          load_as_fp16 ? framework::proto::VarType::FP16 : in_dtype;

      if (in_dtype != out_dtype) {
        // convert to float16 tensor
        auto in_kernel_type = framework::OpKernelType(in_dtype, place);
        auto out_kernel_type = framework::OpKernelType(out_dtype, place);
        framework::LoDTensor fp16_tensor;
        // copy LoD info to the new tensor
        fp16_tensor.set_lod(tensor->lod());
        framework::TransDataType(in_kernel_type, out_kernel_type, *tensor,
                                 &fp16_tensor);

        // reset output tensor
        out_var->Clear();
        tensor = out_var->GetMutable<framework::LoDTensor>();
        tensor->set_lod(fp16_tensor.lod());
        tensor->ShareDataWith(fp16_tensor);
      }
    }
  }
};

class LoadCombineOpProtoMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddOutput(
        "Out",
        "(vector) The output LoDTensors that will be read from the input file.")
        .AsDuplicable();
    AddAttr<bool>(
        "load_as_fp16",
        "(boolean, default false)"
        "If true, the tensor will be first loaded and then "
        "converted to float16 data type. Otherwise, the tensor will be "
        "directly loaded without data type conversion.")
        .SetDefault(false);
    AddAttr<std::string>("file_path",
                         "(string) "
                         "LoDTensors will be loaded from \"file_path\".")
        .AddCustomChecker(
            [](const std::string &path) { return !path.empty(); });
    AddAttr<bool>("model_from_memory",
                  "(boolean, default false)"
                  "If true, file_path is in memory, and LoDTensors will be "
                  "loaded directly from memory")
        .SetDefault(false);
    AddComment(R"DOC(
LoadCombine Operator.

LoadCombine operator loads LoDTensor variables from a file, which could be
loaded in memory already. The file should contain one or more LoDTensors
serialized using the SaveCombine operator. The
LoadCombine operator applies a deserialization strategy to appropriately load
the LodTensors, and this strategy complements the serialization strategy used
in the SaveCombine operator. Hence, the LoadCombine operator is tightly coupled
with the SaveCombine operator, and can only deserialize one or more LoDTensors
that were saved using the SaveCombine operator.

)DOC");
  }
};
}  // namespace operators
}  // namespace paddle
namespace ops = paddle::operators;

REGISTER_OPERATOR(load_combine, ops::LoadCombineOp,
                  ops::LoadCombineOpProtoMaker);
<commit_msg>fix unittest test=develop<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <fstream>
#include "paddle/fluid/framework/data_type_transform.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/platform/device_context.h"

namespace paddle {
namespace operators {

class LoadCombineOp : public framework::OperatorBase {
 public:
  LoadCombineOp(const std::string &type,
                const framework::VariableNameMap &inputs,
                const framework::VariableNameMap &outputs,
                const framework::AttributeMap &attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {
    auto filename = Attr<std::string>("file_path");
    auto load_as_fp16 = Attr<bool>("load_as_fp16");
    auto model_from_memory = Attr<bool>("model_from_memory");
    auto out_var_names = Outputs("Out");
    PADDLE_ENFORCE_GT(
        static_cast<int>(out_var_names.size()), 0,
        "The number of output variables should be greater than 0.");
    if (!model_from_memory) {
      std::ifstream fin(filename, std::ios::binary);
      PADDLE_ENFORCE(static_cast<bool>(fin),
                     "Cannot open file %s for load_combine op", filename);
      LoadParamsFromBuffer(scope, place, &fin, load_as_fp16, out_var_names);
    } else {
      PADDLE_ENFORCE(!filename.empty(), "Cannot load file from memory");
      std::stringstream fin(filename, std::ios::in | std::ios::binary);
      LoadParamsFromBuffer(scope, place, &fin, load_as_fp16, out_var_names);
    }
  }
  void LoadParamsFromBuffer(
      const framework::Scope &scope, const platform::Place &place,
      std::istream *buffer, bool load_as_fp16,
      const std::vector<std::string> &out_var_names) const {
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(place);

    for (size_t i = 0; i < out_var_names.size(); i++) {
      auto *out_var = scope.FindVar(out_var_names[i]);

      PADDLE_ENFORCE(out_var != nullptr, "Output variable %s cannot be found",
                     out_var_names[i]);

      auto *tensor = out_var->GetMutable<framework::LoDTensor>();

      // Error checking
      PADDLE_ENFORCE(static_cast<bool>(buffer), "Cannot read more");

      // Get data from fin to tensor
      DeserializeFromStream(*buffer, tensor, dev_ctx);

      auto in_dtype = tensor->type();
      auto out_dtype =
          load_as_fp16 ? framework::proto::VarType::FP16 : in_dtype;

      if (in_dtype != out_dtype) {
        // convert to float16 tensor
        auto in_kernel_type = framework::OpKernelType(in_dtype, place);
        auto out_kernel_type = framework::OpKernelType(out_dtype, place);
        framework::LoDTensor fp16_tensor;
        // copy LoD info to the new tensor
        fp16_tensor.set_lod(tensor->lod());
        framework::TransDataType(in_kernel_type, out_kernel_type, *tensor,
                                 &fp16_tensor);

        // reset output tensor
        out_var->Clear();
        tensor = out_var->GetMutable<framework::LoDTensor>();
        tensor->set_lod(fp16_tensor.lod());
        tensor->ShareDataWith(fp16_tensor);
      }
    }
  }
};

class LoadCombineOpProtoMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddOutput(
        "Out",
        "(vector) The output LoDTensors that will be read from the input file.")
        .AsDuplicable();
    AddAttr<bool>(
        "load_as_fp16",
        "(boolean, default false)"
        "If true, the tensor will be first loaded and then "
        "converted to float16 data type. Otherwise, the tensor will be "
        "directly loaded without data type conversion.")
        .SetDefault(false);
    AddAttr<std::string>("file_path",
                         "(string) "
                         "LoDTensors will be loaded from \"file_path\".")
        .AddCustomChecker(
            [](const std::string &path) { return !path.empty(); });
    AddAttr<bool>("model_from_memory",
                  "(boolean, default false)"
                  "If true, file_path is in memory, and LoDTensors will be "
                  "loaded directly from memory")
        .SetDefault(false);
    AddComment(R"DOC(
LoadCombine Operator.

LoadCombine operator loads LoDTensor variables from a file, which could be
loaded in memory already. The file should contain one or more LoDTensors
serialized using the SaveCombine operator. The
LoadCombine operator applies a deserialization strategy to appropriately load
the LodTensors, and this strategy complements the serialization strategy used
in the SaveCombine operator. Hence, the LoadCombine operator is tightly coupled
with the SaveCombine operator, and can only deserialize one or more LoDTensors
that were saved using the SaveCombine operator.

)DOC");
  }
};
}  // namespace operators
}  // namespace paddle
namespace ops = paddle::operators;

REGISTER_OPERATOR(load_combine, ops::LoadCombineOp,
                  ops::LoadCombineOpProtoMaker);
<|endoftext|>


<commit_before>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include <vistk/scoring/scoring_result.h>

#include <vistk/python/any_conversion/prototypes.h>
#include <vistk/python/any_conversion/registration.h>

#include <boost/python/class.hpp>
#include <boost/python/module.hpp>
#include <boost/make_shared.hpp>

/**
 * \file scoring_result.cxx
 *
 * \brief Python bindings for scoring_result.
 */

using namespace boost::python;

static vistk::scoring_result_t new_result(vistk::scoring_result::count_t hit, vistk::scoring_result::count_t miss, vistk::scoring_result::count_t truth);
static vistk::scoring_result::count_t result_get_hit(vistk::scoring_result_t const& self);
static vistk::scoring_result::count_t result_get_miss(vistk::scoring_result_t const& self);
static vistk::scoring_result::count_t result_get_truth(vistk::scoring_result_t const& self);
static vistk::scoring_result::result_t result_get_percent_detection(vistk::scoring_result_t const& self);
static vistk::scoring_result::result_t result_get_precision(vistk::scoring_result_t const& self);

BOOST_PYTHON_MODULE(scoring_result)
{
  class_<vistk::scoring_result_t>("ScoringResult"
    , "A result from a scoring algorithm."
    , no_init)
    .def("__init__", &new_result
      , (arg("hit"), arg("miss"), arg("truth"))
      , "Constructor.")
    .def("hit_count", &result_get_hit)
    .def("miss_count", &result_get_miss)
    .def("truth_count", &result_get_truth)
    .def("percent_detection", &result_get_percent_detection)
    .def("precision", &result_get_precision)
  ;

  vistk::python::register_type<vistk::scoring_result_t>(20);
}

vistk::scoring_result_t
new_result(vistk::scoring_result::count_t hit, vistk::scoring_result::count_t miss, vistk::scoring_result::count_t truth)
{
  return boost::make_shared<vistk::scoring_result>(hit, miss, truth);
}

vistk::scoring_result::count_t
result_get_hit(vistk::scoring_result_t const& self)
{
  return self->hit_count;
}

vistk::scoring_result::count_t
result_get_miss(vistk::scoring_result_t const& self)
{
  return self->miss_count;
}

vistk::scoring_result::count_t
result_get_truth(vistk::scoring_result_t const& self)
{
  return self->truth_count;
}

vistk::scoring_result::result_t
result_get_percent_detection(vistk::scoring_result_t const& self)
{
  return self->percent_detection();
}

vistk::scoring_result::result_t
result_get_precision(vistk::scoring_result_t const& self)
{
  return self->precision();
}
<commit_msg>Bind scoring addition in Python<commit_after>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include <vistk/scoring/scoring_result.h>

#include <vistk/python/any_conversion/prototypes.h>
#include <vistk/python/any_conversion/registration.h>

#include <boost/python/class.hpp>
#include <boost/python/module.hpp>
#include <boost/make_shared.hpp>

/**
 * \file scoring_result.cxx
 *
 * \brief Python bindings for scoring_result.
 */

using namespace boost::python;

static vistk::scoring_result_t new_result(vistk::scoring_result::count_t hit, vistk::scoring_result::count_t miss, vistk::scoring_result::count_t truth);
static vistk::scoring_result::count_t result_get_hit(vistk::scoring_result_t const& self);
static vistk::scoring_result::count_t result_get_miss(vistk::scoring_result_t const& self);
static vistk::scoring_result::count_t result_get_truth(vistk::scoring_result_t const& self);
static vistk::scoring_result::result_t result_get_percent_detection(vistk::scoring_result_t const& self);
static vistk::scoring_result::result_t result_get_precision(vistk::scoring_result_t const& self);
static vistk::scoring_result_t result_add(vistk::scoring_result_t const& lhs, vistk::scoring_result_t const& rhs);

BOOST_PYTHON_MODULE(scoring_result)
{
  class_<vistk::scoring_result_t>("ScoringResult"
    , "A result from a scoring algorithm."
    , no_init)
    .def("__init__", &new_result
      , (arg("hit"), arg("miss"), arg("truth"))
      , "Constructor.")
    .def("hit_count", &result_get_hit)
    .def("miss_count", &result_get_miss)
    .def("truth_count", &result_get_truth)
    .def("percent_detection", &result_get_percent_detection)
    .def("precision", &result_get_precision)
    .def("__add__", &result_add
      , (arg("lhs"), arg("rhs")))
  ;

  vistk::python::register_type<vistk::scoring_result_t>(20);
}

vistk::scoring_result_t
new_result(vistk::scoring_result::count_t hit, vistk::scoring_result::count_t miss, vistk::scoring_result::count_t truth)
{
  return boost::make_shared<vistk::scoring_result>(hit, miss, truth);
}

vistk::scoring_result::count_t
result_get_hit(vistk::scoring_result_t const& self)
{
  return self->hit_count;
}

vistk::scoring_result::count_t
result_get_miss(vistk::scoring_result_t const& self)
{
  return self->miss_count;
}

vistk::scoring_result::count_t
result_get_truth(vistk::scoring_result_t const& self)
{
  return self->truth_count;
}

vistk::scoring_result::result_t
result_get_percent_detection(vistk::scoring_result_t const& self)
{
  return self->percent_detection();
}

vistk::scoring_result::result_t
result_get_precision(vistk::scoring_result_t const& self)
{
  return self->precision();
}

vistk::scoring_result_t
result_add(vistk::scoring_result_t const& lhs, vistk::scoring_result_t const& rhs)
{
  return (lhs + rhs);
}
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010      Dennis Nienhüser <earthwings@gentoo.org>
//

#include "MarbleDeclarativePlugin.h"

#include "Coordinate.h"
#include "DeclarativeMapThemeManager.h"
#include "MarbleDeclarativeWidget.h"
#include "PositionSource.h"
#include "Tracking.h"
#include "Routing.h"
#include "Search.h"
#include "RouteRequestModel.h"
#include "ActivityModel.h"
#include "Activity.h"
#include "RelatedActivities.h"
#include "Settings.h"

#include <QtDeclarative/qdeclarative.h>
#include <QtDeclarative/QDeclarativeEngine>

namespace Marble
{
namespace Declarative
{

void MarbleDeclarativePlugin::registerTypes( const char * )
{
    const char* uri = "org.kde.edu.marble";

    qmlRegisterType<Marble::Declarative::Coordinate>( uri, 0, 11, "Coordinate" );
    qmlRegisterType<Marble::Declarative::PositionSource>( uri, 0, 11, "PositionSource" );
    qmlRegisterType<Marble::Declarative::Tracking>( uri, 0, 11, "Tracking" );
    qmlRegisterType<Marble::Declarative::Routing>( uri, 0, 11, "Routing" );
    qmlRegisterType<Marble::Declarative::Search>( uri, 0, 11, "Search" );
    qmlRegisterType<Marble::Declarative::RouteRequestModel>( uri, 0, 11, "RouteRequestModel" );
    qmlRegisterType<Marble::Declarative::ActivityModel>( uri, 0, 11, "ActivityModel" );
    qmlRegisterType<Marble::Declarative::Activity>( uri, 0, 11, "Activity" );
    qmlRegisterType<Marble::Declarative::RelatedActivities>( uri, 0, 11, "RelatedActivities" );
    qmlRegisterType<Marble::Declarative::Settings>( uri, 0, 11, "Settings" );

    qmlRegisterType<Marble::Declarative::MarbleWidget>( uri, 0, 11, "MarbleWidget" );
    qmlRegisterType<Marble::Declarative::MapThemeManager>( uri, 0, 11, "MapThemeManager" );
}

void MarbleDeclarativePlugin::initializeEngine( QDeclarativeEngine *engine, const char *)
{
    engine->addImageProvider( "maptheme", new MapThemeImageProvider );
}

}
}

#include "MarbleDeclarativePlugin.moc"

Q_EXPORT_PLUGIN2( MarbleDeclarativePlugin, Marble::Declarative::MarbleDeclarativePlugin )
<commit_msg>Help QtCreator parse the file<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010      Dennis Nienhüser <earthwings@gentoo.org>
//

#include "MarbleDeclarativePlugin.h"

#include "Coordinate.h"
#include "DeclarativeMapThemeManager.h"
#include "MarbleDeclarativeWidget.h"
#include "PositionSource.h"
#include "Tracking.h"
#include "Routing.h"
#include "Search.h"
#include "RouteRequestModel.h"
#include "ActivityModel.h"
#include "Activity.h"
#include "RelatedActivities.h"
#include "Settings.h"

#include <QtDeclarative/qdeclarative.h>
#include <QtDeclarative/QDeclarativeEngine>

namespace Marble
{
namespace Declarative
{

void MarbleDeclarativePlugin::registerTypes( const char * )
{
    const char* uri = "org.kde.edu.marble";

    //@uri org.kde.edu.marble
    qmlRegisterType<Marble::Declarative::Coordinate>( uri, 0, 11, "Coordinate" );
    qmlRegisterType<Marble::Declarative::PositionSource>( uri, 0, 11, "PositionSource" );
    qmlRegisterType<Marble::Declarative::Tracking>( uri, 0, 11, "Tracking" );
    qmlRegisterType<Marble::Declarative::Routing>( uri, 0, 11, "Routing" );
    qmlRegisterType<Marble::Declarative::Search>( uri, 0, 11, "Search" );
    qmlRegisterType<Marble::Declarative::RouteRequestModel>( uri, 0, 11, "RouteRequestModel" );
    qmlRegisterType<Marble::Declarative::ActivityModel>( uri, 0, 11, "ActivityModel" );
    qmlRegisterType<Marble::Declarative::Activity>( uri, 0, 11, "Activity" );
    qmlRegisterType<Marble::Declarative::RelatedActivities>( uri, 0, 11, "RelatedActivities" );
    qmlRegisterType<Marble::Declarative::Settings>( uri, 0, 11, "Settings" );

    qmlRegisterType<Marble::Declarative::MarbleWidget>( uri, 0, 11, "MarbleWidget" );
    qmlRegisterType<Marble::Declarative::MapThemeManager>( uri, 0, 11, "MapThemeManager" );
}

void MarbleDeclarativePlugin::initializeEngine( QDeclarativeEngine *engine, const char *)
{
    engine->addImageProvider( "maptheme", new MapThemeImageProvider );
}

}
}

#include "MarbleDeclarativePlugin.moc"

Q_EXPORT_PLUGIN2( MarbleDeclarativePlugin, Marble::Declarative::MarbleDeclarativePlugin )
<|endoftext|>


<commit_before>#define ProofTests_cxx

//////////////////////////////////////////////////////////
//
// Auxilliary TSelector used to test PROOF functionality
//
//////////////////////////////////////////////////////////

#include "ProofTests.h"
#include <TEnv.h>
#include <TH1F.h>
#include <TH1I.h>
#include <TMath.h>
#include <TString.h>
#include <TSystem.h>
#include <TParameter.h>

//_____________________________________________________________________________
ProofTests::ProofTests()
{
   // Constructor

   fTestType = 0;
   fStat = 0;
}

//_____________________________________________________________________________
ProofTests::~ProofTests()
{
   // Destructor

}

//_____________________________________________________________________________
void ProofTests::ParseInput()
{
   // This function sets some control member variables based on the input list
   // content. Called by Begin and SlaveBegin.

   // Determine the test type
   TNamed *ntype = dynamic_cast<TNamed*>(fInput->FindObject("ProofTests_Type"));
   if (ntype) {
      if (!strcmp(ntype->GetTitle(), "InputData")) {
         fTestType = 0;
      } else if (!strcmp(ntype->GetTitle(), "PackTest1")) {
         fTestType = 1;
      } else if (!strcmp(ntype->GetTitle(), "PackTest2")) {
         fTestType = 2;
      } else {
         Warning("ParseInput", "unknown type: '%s'", ntype->GetTitle());
      }
   }
   Info("ParseInput", "test type: %d (from '%s')", fTestType, ntype ? ntype->GetTitle() : "undef");
}

//_____________________________________________________________________________
void ProofTests::Begin(TTree * /*tree*/)
{
   // The Begin() function is called at the start of the query.
   // When running with PROOF Begin() is only called on the client.
   // The tree argument is deprecated (on PROOF 0 is passed).
}

//_____________________________________________________________________________
void ProofTests::SlaveBegin(TTree * /*tree*/)
{
   // The SlaveBegin() function is called after the Begin() function.
   // When running with PROOF SlaveBegin() is called on each slave server.
   // The tree argument is deprecated (on PROOF 0 is passed).

   TString option = GetOption();

   // Fill relevant members
   ParseInput();

   // Output histo
   fStat = new TH1I("TestStat", "Test results", 20, .5, 20.5);
   fOutput->Add(fStat);

   // We were started
   fStat->Fill(1.);

   // Depends on the test
   if (fTestType == 0) {
      // Retrieve objects from the input list and copy them to the output
      // H1
      TList *h1list = dynamic_cast<TList*>(fInput->FindObject("h1list"));
      if (h1list) {
         // Retrieve objects from the input list and copy them to the output
         TH1F *h1 = dynamic_cast<TH1F*>(h1list->FindObject("h1data"));
         if (h1) {
            TParameter<Double_t> *h1avg = dynamic_cast<TParameter<Double_t>*>(h1list->FindObject("h1avg"));
            TParameter<Double_t> *h1rms = dynamic_cast<TParameter<Double_t>*>(h1list->FindObject("h1rms"));
            if (h1avg && h1rms) {
               if (TMath::Abs(h1avg->GetVal() - h1->GetMean()) < 0.0001) {
                  if (TMath::Abs(h1rms->GetVal() - h1->GetRMS()) < 0.0001) {
                     fStat->Fill(2.);
                  }
               }
            } else {
               Info("SlaveBegin", "%d: info 'h1avg' or 'h1rms' not found!", fTestType);
            }
         } else {
            Info("SlaveBegin", "%d: input histo 'h1data' not found!", fTestType);
         }
      } else {
         Info("SlaveBegin", "%d: input list 'h1list' not found!", fTestType);
      }
      // H2
      TList *h2list = dynamic_cast<TList*>(fInput->FindObject("h2list"));
      if (h2list) {
         // Retrieve objects from the input list and copy them to the output
         TH1F *h2 = dynamic_cast<TH1F*>(h2list->FindObject("h2data"));
         if (h2) {
            TParameter<Double_t> *h2avg = dynamic_cast<TParameter<Double_t>*>(h2list->FindObject("h2avg"));
            TParameter<Double_t> *h2rms = dynamic_cast<TParameter<Double_t>*>(h2list->FindObject("h2rms"));
            if (h2avg && h2rms) {
               if (TMath::Abs(h2avg->GetVal() - h2->GetMean()) < 0.0001) {
                  if (TMath::Abs(h2rms->GetVal() - h2->GetRMS()) < 0.0001) {
                     fStat->Fill(3.);
                  }
               }
            } else {
               Info("SlaveBegin", "%d: info 'h2avg' or 'h2rms' not found!", fTestType);
            }
         } else {
            Info("SlaveBegin", "%d: input histo 'h2data' not found!", fTestType);
         }
      } else {
         Info("SlaveBegin", "%d: input list 'h2list' not found!", fTestType);
      }

      TNamed *iob = dynamic_cast<TNamed*>(fInput->FindObject("InputObject"));
      if (iob) {
         fStat->Fill(4.);
      } else {
         Info("SlaveBegin", "%d: input histo 'InputObject' not found!", fTestType);
      }
   } else if (fTestType == 1) {
      // We should find in the input list the name of a test variable which should exist
      // at this point in the gEnv table
      TNamed *nm = dynamic_cast<TNamed*>(fInput->FindObject("testenv"));
      if (nm) {
         if (gEnv->Lookup(nm->GetTitle())) fStat->Fill(2.);
      } else {
         Info("SlaveBegin", "%d: TNamed with the test env info not found!", fTestType);
      }
   } else if (fTestType == 2) {
      // We should find in the input list the list of names of test variables which should exist
      // at this point in the gEnv table
      TNamed *nm = dynamic_cast<TNamed*>(fInput->FindObject("testenv"));
      if (nm) {
         TString nms(nm->GetTitle()), nam;
         Int_t from = 0;
         while (nms.Tokenize(nam, from, ",")) {
            if (gEnv->Lookup(nam)) {
               Double_t xx = gEnv->GetValue(nam, -1.);
               if (xx > 1.) fStat->Fill(xx);
            }
         }
      } else {
         Info("SlaveBegin", "%d: TNamed with the test env info not found!", fTestType);
      }
   }
}

//_____________________________________________________________________________
Bool_t ProofTests::Process(Long64_t)
{
   // The Process() function is called for each entry in the tree (or possibly
   // keyed object in the case of PROOF) to be processed. The entry argument
   // specifies which entry in the currently loaded tree is to be processed.
   // It can be passed to either ProofTests::GetEntry() or TBranch::GetEntry()
   // to read either all or the required parts of the data. When processing
   // keyed objects with PROOF, the object is already loaded and is available
   // via the fObject pointer.
   //
   // This function should contain the "body" of the analysis. It can contain
   // simple or elaborate selection criteria, run algorithms on the data
   // of the event and typically fill histograms.
   //
   // The processing can be stopped by calling Abort().
   //
   // Use fStatus to set the return value of TTree::Process().
   //
   // The return value is currently not used.

   return kTRUE;
}

//_____________________________________________________________________________
void ProofTests::SlaveTerminate()
{
   // The SlaveTerminate() function is called after all entries or objects
   // have been processed. When running with PROOF SlaveTerminate() is called
   // on each slave server.

}

//_____________________________________________________________________________
void ProofTests::Terminate()
{
   // The Terminate() function is the last function to be called during
   // a query. It always runs on the client, it can be used to present
   // the results graphically or save the results to file.

}
<commit_msg>Improve on debug statements<commit_after>#define ProofTests_cxx

//////////////////////////////////////////////////////////
//
// Auxilliary TSelector used to test PROOF functionality
//
//////////////////////////////////////////////////////////

#include "ProofTests.h"
#include <TEnv.h>
#include <TH1F.h>
#include <TH1I.h>
#include <TMath.h>
#include <TString.h>
#include <TSystem.h>
#include <TParameter.h>

//_____________________________________________________________________________
ProofTests::ProofTests()
{
   // Constructor

   fTestType = 0;
   fStat = 0;
}

//_____________________________________________________________________________
ProofTests::~ProofTests()
{
   // Destructor

}

//_____________________________________________________________________________
void ProofTests::ParseInput()
{
   // This function sets some control member variables based on the input list
   // content. Called by Begin and SlaveBegin.

   // Determine the test type
   TNamed *ntype = dynamic_cast<TNamed*>(fInput->FindObject("ProofTests_Type"));
   if (ntype) {
      if (!strcmp(ntype->GetTitle(), "InputData")) {
         fTestType = 0;
      } else if (!strcmp(ntype->GetTitle(), "PackTest1")) {
         fTestType = 1;
      } else if (!strcmp(ntype->GetTitle(), "PackTest2")) {
         fTestType = 2;
      } else {
         Warning("ParseInput", "unknown type: '%s'", ntype->GetTitle());
      }
   }
   Info("ParseInput", "test type: %d (from '%s')", fTestType, ntype ? ntype->GetTitle() : "undef");
}

//_____________________________________________________________________________
void ProofTests::Begin(TTree * /*tree*/)
{
   // The Begin() function is called at the start of the query.
   // When running with PROOF Begin() is only called on the client.
   // The tree argument is deprecated (on PROOF 0 is passed).
}

//_____________________________________________________________________________
void ProofTests::SlaveBegin(TTree * /*tree*/)
{
   // The SlaveBegin() function is called after the Begin() function.
   // When running with PROOF SlaveBegin() is called on each slave server.
   // The tree argument is deprecated (on PROOF 0 is passed).

   TString option = GetOption();

   // Fill relevant members
   ParseInput();

   // Output histo
   fStat = new TH1I("TestStat", "Test results", 20, .5, 20.5);
   fOutput->Add(fStat);

   // We were started
   fStat->Fill(1.);

   // Depends on the test
   if (fTestType == 0) {
      // Retrieve objects from the input list and copy them to the output
      // H1
      TList *h1list = dynamic_cast<TList*>(fInput->FindObject("h1list"));
      if (h1list) {
         // Retrieve objects from the input list and copy them to the output
         TH1F *h1 = dynamic_cast<TH1F*>(h1list->FindObject("h1data"));
         if (h1) {
            TParameter<Double_t> *h1avg = dynamic_cast<TParameter<Double_t>*>(h1list->FindObject("h1avg"));
            TParameter<Double_t> *h1rms = dynamic_cast<TParameter<Double_t>*>(h1list->FindObject("h1rms"));
            if (h1avg && h1rms) {
               if (TMath::Abs(h1avg->GetVal() - h1->GetMean()) < 0.0001) {
                  if (TMath::Abs(h1rms->GetVal() - h1->GetRMS()) < 0.0001) {
                     fStat->Fill(2.);
                  }
               }
            } else {
               Warning("SlaveBegin", "%d: info 'h1avg' or 'h1rms' not found!", fTestType);
            }
         } else {
            Warning("SlaveBegin", "%d: input histo 'h1data' not found!", fTestType);
         }
      } else {
         Warning("SlaveBegin", "%d: input list 'h1list' not found!", fTestType);
      }
      // H2
      TList *h2list = dynamic_cast<TList*>(fInput->FindObject("h2list"));
      if (h2list) {
         // Retrieve objects from the input list and copy them to the output
         TH1F *h2 = dynamic_cast<TH1F*>(h2list->FindObject("h2data"));
         if (h2) {
            TParameter<Double_t> *h2avg = dynamic_cast<TParameter<Double_t>*>(h2list->FindObject("h2avg"));
            TParameter<Double_t> *h2rms = dynamic_cast<TParameter<Double_t>*>(h2list->FindObject("h2rms"));
            if (h2avg && h2rms) {
               if (TMath::Abs(h2avg->GetVal() - h2->GetMean()) < 0.0001) {
                  if (TMath::Abs(h2rms->GetVal() - h2->GetRMS()) < 0.0001) {
                     fStat->Fill(3.);
                  }
               }
            } else {
               Warning("SlaveBegin", "%d: info 'h2avg' or 'h2rms' not found!", fTestType);
            }
         } else {
            Warning("SlaveBegin", "%d: input histo 'h2data' not found!", fTestType);
         }
      } else {
         Warning("SlaveBegin", "%d: input list 'h2list' not found!", fTestType);
      }

      TNamed *iob = dynamic_cast<TNamed*>(fInput->FindObject("InputObject"));
      if (iob) {
         fStat->Fill(4.);
      } else {
         Warning("SlaveBegin", "%d: input histo 'InputObject' not found!", fTestType);
      }
   } else if (fTestType == 1) {
      // We should find in the input list the name of a test variable which should exist
      // at this point in the gEnv table
      TNamed *nm = dynamic_cast<TNamed*>(fInput->FindObject("testenv"));
      if (nm) {
         if (gEnv->Lookup(nm->GetTitle())) fStat->Fill(2.);
      } else {
         Warning("SlaveBegin", "%d: TNamed with the test env info not found!", fTestType);
      }
   } else if (fTestType == 2) {
      // We should find in the input list the list of names of test variables which should exist
      // at this point in the gEnv table
      TNamed *nm = dynamic_cast<TNamed*>(fInput->FindObject("testenv"));
      if (nm) {
         TString nms(nm->GetTitle()), nam;
         Int_t from = 0;
         while (nms.Tokenize(nam, from, ",")) {
            if (gEnv->Lookup(nam)) {
               Double_t xx = gEnv->GetValue(nam, -1.);
               if (xx > 1.) fStat->Fill(xx);
            } else {
               Warning("SlaveBegin", "RC-env '%s' not found!", nam.Data());
            }
         }
      } else {
         Warning("SlaveBegin", "%d: TNamed with the test env info not found!", fTestType);
      }
   }
}

//_____________________________________________________________________________
Bool_t ProofTests::Process(Long64_t)
{
   // The Process() function is called for each entry in the tree (or possibly
   // keyed object in the case of PROOF) to be processed. The entry argument
   // specifies which entry in the currently loaded tree is to be processed.
   // It can be passed to either ProofTests::GetEntry() or TBranch::GetEntry()
   // to read either all or the required parts of the data. When processing
   // keyed objects with PROOF, the object is already loaded and is available
   // via the fObject pointer.
   //
   // This function should contain the "body" of the analysis. It can contain
   // simple or elaborate selection criteria, run algorithms on the data
   // of the event and typically fill histograms.
   //
   // The processing can be stopped by calling Abort().
   //
   // Use fStatus to set the return value of TTree::Process().
   //
   // The return value is currently not used.

   return kTRUE;
}

//_____________________________________________________________________________
void ProofTests::SlaveTerminate()
{
   // The SlaveTerminate() function is called after all entries or objects
   // have been processed. When running with PROOF SlaveTerminate() is called
   // on each slave server.

}

//_____________________________________________________________________________
void ProofTests::Terminate()
{
   // The Terminate() function is the last function to be called during
   // a query. It always runs on the client, it can be used to present
   // the results graphically or save the results to file.

}
<|endoftext|>