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

#ifndef CONFIGMGR_API_TRANSLATECHANGES_HXX_
#define CONFIGMGR_API_TRANSLATECHANGES_HXX_

#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/beans/XVetoableChangeListener.hpp>
#include <com/sun/star/beans/XPropertiesChangeListener.hpp>
#include <com/sun/star/container/XContainerListener.hpp>
#include <com/sun/star/util/XChangesListener.hpp>

namespace configmgr
{
// ---------------------------------------------------------------------------------------------------
    namespace css = ::com::sun::star;
    namespace uno       = css::uno;
    namespace lang      = css::lang;
    namespace util      = css::util;
    namespace beans     = css::beans;
    namespace container = css::container;
// ---------------------------------------------------------------------------------------------------

    namespace configuration
    {
        class NodeChangeInformation;
        class NodeChangeData;
        class NodeChangeLocation;

        //class NodeChange;
        //class NodeChanges;
        class Tree;
        class TreeRef;
        class NodeRef;
        class NodeID;
        class RelativePath;
    }
// ---------------------------------------------------------------------------------------------------

    namespace configapi
    {
        class NotifierImpl;
        class Factory;

        struct UnoChange { uno::Any newValue, oldValue; };

    //interpreting NodeChanges
        // resolve the relative path from a given base tree (root) to the changed node
        bool resolveChangeLocation( configuration::RelativePath& aPath,
                                    configuration::NodeChangeLocation const& aChange,
                                    configuration::Tree const& aBaseTree);
        // resolve the relative path from a given base node to the changed node
        bool resolveChangeLocation( configuration::RelativePath& aPath,
                                    configuration::NodeChangeLocation const& aChange,
                                    configuration::Tree const& aBaseTree,
                                    configuration::NodeRef const& aBaseNode);

        // change path and base settings to start from the given base tree (root)
        bool rebaseChange(  configuration::NodeChangeLocation& aChange,
                            configuration::TreeRef const& _aBaseTreeRef);
        // change path and base settings to start from the given base node
        bool rebaseChange(  configuration::NodeChangeLocation& aChange,
                            configuration::TreeRef const& _aBaseTreeRef,
                            configuration::NodeRef const& aBaseNode);
        // resolve non-uno elements to Uno Objects
        bool resolveUnoObjects(UnoChange& aUnoChange,
                               configuration::NodeChangeData const& aChange,
                               Factory& rFactory);
        // resolve non-uno elements to Uno Objects inplace
        bool resolveToUno(configuration::NodeChangeData& aChange,
                          Factory& rFactory);

    // building events
        /// find the sending api object
        void fillEventSource(lang::EventObject& rEvent, configuration::Tree const& aTree, configuration::NodeRef const& aNode, Factory& rFactory);

        /// fill a change info from a NodeChangeInfo
        void fillChange(util::ElementChange& rChange,
                        configuration::NodeChangeInformation const& aInfo,
                        configuration::Tree const& aBaseTree,
                        Factory& rFactory);
        /// fill a change info from a NodeChangeInfo
        void fillChange(util::ElementChange& rChange,
                        configuration::NodeChangeInformation const& aInfo,
                        configuration::Tree const& aBaseTree,
                        configuration::NodeRef const& aBaseNode,
                        Factory& rFactory);
        /// fill a change info from a NodeChangeInfo (base,path and uno objects are assumed to be resolved already)
        void fillChangeFromResolved(util::ElementChange& rChange, configuration::NodeChangeInformation const& aInfo);

        /// fill a event from a NodeChangeInfo
        bool fillEventData(container::ContainerEvent& rEvent, configuration::NodeChangeInformation const& aInfo, Factory& rFactory);
        /// fill a event from a NodeChangeInfo (uno objects are assumed to be resolved already)
        bool fillEventDataFromResolved(container::ContainerEvent& rEvent, configuration::NodeChangeInformation const& aInfo);
        /// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already) - returns false if this isn't a property change
        bool fillEventData(beans::PropertyChangeEvent& rEvent, configuration::NodeChangeInformation const& aInfo, Factory& rFactory, bool bMore);
        /// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already) - returns false if this isn't a property change
        bool fillEventDataFromResolved(beans::PropertyChangeEvent& rEvent, configuration::NodeChangeInformation const& aInfo, bool bMore);
    }
// ---------------------------------------------------------------------------------------------------
}

#endif // CONFIGMGR_API_TRANSLATECHANGES_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.9.16); FILE MERGED 2008/03/31 12:22:38 rt 1.9.16.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: translatechanges.hxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef CONFIGMGR_API_TRANSLATECHANGES_HXX_
#define CONFIGMGR_API_TRANSLATECHANGES_HXX_

#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/beans/XVetoableChangeListener.hpp>
#include <com/sun/star/beans/XPropertiesChangeListener.hpp>
#include <com/sun/star/container/XContainerListener.hpp>
#include <com/sun/star/util/XChangesListener.hpp>

namespace configmgr
{
// ---------------------------------------------------------------------------------------------------
    namespace css = ::com::sun::star;
    namespace uno       = css::uno;
    namespace lang      = css::lang;
    namespace util      = css::util;
    namespace beans     = css::beans;
    namespace container = css::container;
// ---------------------------------------------------------------------------------------------------

    namespace configuration
    {
        class NodeChangeInformation;
        class NodeChangeData;
        class NodeChangeLocation;

        //class NodeChange;
        //class NodeChanges;
        class Tree;
        class TreeRef;
        class NodeRef;
        class NodeID;
        class RelativePath;
    }
// ---------------------------------------------------------------------------------------------------

    namespace configapi
    {
        class NotifierImpl;
        class Factory;

        struct UnoChange { uno::Any newValue, oldValue; };

    //interpreting NodeChanges
        // resolve the relative path from a given base tree (root) to the changed node
        bool resolveChangeLocation( configuration::RelativePath& aPath,
                                    configuration::NodeChangeLocation const& aChange,
                                    configuration::Tree const& aBaseTree);
        // resolve the relative path from a given base node to the changed node
        bool resolveChangeLocation( configuration::RelativePath& aPath,
                                    configuration::NodeChangeLocation const& aChange,
                                    configuration::Tree const& aBaseTree,
                                    configuration::NodeRef const& aBaseNode);

        // change path and base settings to start from the given base tree (root)
        bool rebaseChange(  configuration::NodeChangeLocation& aChange,
                            configuration::TreeRef const& _aBaseTreeRef);
        // change path and base settings to start from the given base node
        bool rebaseChange(  configuration::NodeChangeLocation& aChange,
                            configuration::TreeRef const& _aBaseTreeRef,
                            configuration::NodeRef const& aBaseNode);
        // resolve non-uno elements to Uno Objects
        bool resolveUnoObjects(UnoChange& aUnoChange,
                               configuration::NodeChangeData const& aChange,
                               Factory& rFactory);
        // resolve non-uno elements to Uno Objects inplace
        bool resolveToUno(configuration::NodeChangeData& aChange,
                          Factory& rFactory);

    // building events
        /// find the sending api object
        void fillEventSource(lang::EventObject& rEvent, configuration::Tree const& aTree, configuration::NodeRef const& aNode, Factory& rFactory);

        /// fill a change info from a NodeChangeInfo
        void fillChange(util::ElementChange& rChange,
                        configuration::NodeChangeInformation const& aInfo,
                        configuration::Tree const& aBaseTree,
                        Factory& rFactory);
        /// fill a change info from a NodeChangeInfo
        void fillChange(util::ElementChange& rChange,
                        configuration::NodeChangeInformation const& aInfo,
                        configuration::Tree const& aBaseTree,
                        configuration::NodeRef const& aBaseNode,
                        Factory& rFactory);
        /// fill a change info from a NodeChangeInfo (base,path and uno objects are assumed to be resolved already)
        void fillChangeFromResolved(util::ElementChange& rChange, configuration::NodeChangeInformation const& aInfo);

        /// fill a event from a NodeChangeInfo
        bool fillEventData(container::ContainerEvent& rEvent, configuration::NodeChangeInformation const& aInfo, Factory& rFactory);
        /// fill a event from a NodeChangeInfo (uno objects are assumed to be resolved already)
        bool fillEventDataFromResolved(container::ContainerEvent& rEvent, configuration::NodeChangeInformation const& aInfo);
        /// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already) - returns false if this isn't a property change
        bool fillEventData(beans::PropertyChangeEvent& rEvent, configuration::NodeChangeInformation const& aInfo, Factory& rFactory, bool bMore);
        /// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already) - returns false if this isn't a property change
        bool fillEventDataFromResolved(beans::PropertyChangeEvent& rEvent, configuration::NodeChangeInformation const& aInfo, bool bMore);
    }
// ---------------------------------------------------------------------------------------------------
}

#endif // CONFIGMGR_API_TRANSLATECHANGES_HXX_
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <string.h>
#include <cstdarg>
#include "java/tools.hxx"
#include "java/lang/String.hxx"
#include "java/lang/Class.hxx"
#include "java/util/Property.hxx"
#include <com/sun/star/sdbc/DriverPropertyInfo.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <connectivity/dbexception.hxx>

using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;

void java_util_Properties::setProperty(const OUString& key, const OUString& value)
{
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    jobject out(0);

    {
        jvalue args[2];
        // Convert Parameter
        args[0].l = convertwchar_tToJavaString(t.pEnv,key);
        args[1].l = convertwchar_tToJavaString(t.pEnv,value);
        // Initialize temporary Variables
        static const char * cSignature = "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;";
        static const char * cMethodName = "setProperty";
        // Turn off Java-Call
        static jmethodID mID(NULL);
        obtainMethodId(t.pEnv, cMethodName,cSignature, mID);
        out = t.pEnv->CallObjectMethod(object, mID, args[0].l,args[1].l);
        ThrowSQLException(t.pEnv,NULL);
        t.pEnv->DeleteLocalRef((jstring)args[1].l);
        t.pEnv->DeleteLocalRef((jstring)args[0].l);
        ThrowSQLException(t.pEnv,0);
        if(out)
            t.pEnv->DeleteLocalRef(out);
    } //t.pEnv
    // WARNING: The caller will be owner of the returned pointers!!!
}
jclass java_util_Properties::theClass = 0;

java_util_Properties::~java_util_Properties()
{}

jclass java_util_Properties::getMyClass() const
{
    // the class needs only be called once, that is why it is static
    if( !theClass )
        theClass = findMyClass("java/util/Properties");
    return theClass;
}

java_util_Properties::java_util_Properties( ): java_lang_Object( NULL, (jobject)NULL )
{
    SDBThreadAttach t;
    if( !t.pEnv )
        return;
    // Turn off Java-Call for the constructor
    // Initialize temperary Variables
    static const char * cSignature = "()V";
    jobject tempObj;
    static jmethodID mID(NULL);
    obtainMethodId(t.pEnv, "<init>",cSignature, mID);
    tempObj = t.pEnv->NewObject( getMyClass(), mID);
    saveRef( t.pEnv, tempObj );
    t.pEnv->DeleteLocalRef( tempObj );
}

jstring connectivity::convertwchar_tToJavaString(JNIEnv *pEnv,const OUString& _rTemp)
{
    OSL_ENSURE(pEnv,"Environment is NULL!");
    jstring pStr = pEnv->NewString(_rTemp.getStr(), _rTemp.getLength());
    pEnv->ExceptionClear();
    OSL_ENSURE(pStr,"Could not create a jsstring object!");
    return pStr;
}

java_util_Properties* connectivity::createStringPropertyArray(const Sequence< PropertyValue >& info )  throw(SQLException, RuntimeException)
{
    java_util_Properties* pProps = new java_util_Properties();
    const PropertyValue* pBegin = info.getConstArray();
    const PropertyValue* pEnd   = pBegin + info.getLength();

    for(;pBegin != pEnd;++pBegin)
    {
        // these are properties used internally by LibreOffice,
        // and should not be passed to the JDBC driver
        // (which probably does not know anything about them anyway).
        // FYI, OUString::compareToAscii() returns zero on equality, like strcmp()
        if  (   pBegin->Name.compareToAscii( "JavaDriverClass" )
            &&  pBegin->Name.compareToAscii( "JavaDriverClassPath" )
            &&  pBegin->Name.compareToAscii( "SystemProperties" )
            &&  pBegin->Name.compareToAscii( "CharSet" )
            &&  pBegin->Name.compareToAscii( "AppendTableAliasName" )
            &&  pBegin->Name.compareToAscii( "AddIndexAppendix" )
            &&  pBegin->Name.compareToAscii( "FormsCheckRequiredFields" )
            &&  pBegin->Name.compareToAscii( "GenerateASBeforeCorrelationName" )
            &&  pBegin->Name.compareToAscii( "EscapeDateTime" )
            &&  pBegin->Name.compareToAscii( "ParameterNameSubstitution" )
            &&  pBegin->Name.compareToAscii( "IsPasswordRequired" )
            &&  pBegin->Name.compareToAscii( "IsAutoRetrievingEnabled" )
            &&  pBegin->Name.compareToAscii( "AutoRetrievingStatement" )
            &&  pBegin->Name.compareToAscii( "UseCatalogInSelect" )
            &&  pBegin->Name.compareToAscii( "UseSchemaInSelect" )
            &&  pBegin->Name.compareToAscii( "AutoIncrementCreation" )
            &&  pBegin->Name.compareToAscii( "Extension" )
            &&  pBegin->Name.compareToAscii( "NoNameLengthLimit" )
            &&  pBegin->Name.compareToAscii( "EnableSQL92Check" )
            &&  pBegin->Name.compareToAscii( "EnableOuterJoinEscape" )
            &&  pBegin->Name.compareToAscii( "BooleanComparisonMode" )
            &&  pBegin->Name.compareToAscii( "IgnoreCurrency" )
            &&  pBegin->Name.compareToAscii( "TypeInfoSettings" )
            &&  pBegin->Name.compareToAscii( "IgnoreDriverPrivileges" )
            &&  pBegin->Name.compareToAscii( "ImplicitCatalogRestriction" )
            &&  pBegin->Name.compareToAscii( "ImplicitSchemaRestriction" )
            &&  pBegin->Name.compareToAscii( "SupportsTableCreation" )
            &&  pBegin->Name.compareToAscii( "UseJava" )
            &&  pBegin->Name.compareToAscii( "Authentication" )
            &&  pBegin->Name.compareToAscii( "PreferDosLikeLineEnds" )
            &&  pBegin->Name.compareToAscii( "PrimaryKeySupport" )
            &&  pBegin->Name.compareToAscii( "RespectDriverResultSetType" )
            )
        {
            OUString aStr;
            OSL_VERIFY( pBegin->Value >>= aStr );
            pProps->setProperty(pBegin->Name,aStr);
        }
    }
    return pProps;
}

OUString connectivity::JavaString2String(JNIEnv *pEnv,jstring _Str)
{
    OUString aStr;
    if(_Str)
    {
        jboolean bCopy(sal_True);
        const jchar* pChar = pEnv->GetStringChars(_Str,&bCopy);
        jsize len = pEnv->GetStringLength(_Str);
        aStr = OUString(pChar,len);

        if(bCopy)
            pEnv->ReleaseStringChars(_Str,pChar);
        pEnv->DeleteLocalRef(_Str);
    }
    return aStr;
}

jobject connectivity::convertTypeMapToJavaMap(JNIEnv* /*pEnv*/,const Reference< ::com::sun::star::container::XNameAccess > & _rMap)
{
    if ( _rMap.is() )
    {
        ::com::sun::star::uno::Sequence< OUString > aNames = _rMap->getElementNames();
        if ( aNames.getLength() > 0 )
            ::dbtools::throwFeatureNotImplementedException( "Type maps", NULL );
    }
    return 0;
}

bool connectivity::isExceptionOccurred(JNIEnv *pEnv,bool _bClear)
{
    if ( !pEnv )
        return false;

    jthrowable pThrowable = pEnv->ExceptionOccurred();
    bool bRet = pThrowable != NULL;
    if ( pThrowable )
    {
        if ( _bClear )
            pEnv->ExceptionClear();
#if OSL_DEBUG_LEVEL > 1
        if(pEnv->IsInstanceOf(pThrowable,java_sql_SQLException_BASE::st_getMyClass()))
        {

            java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,pThrowable);
            OUString sError = pException->getMessage();
            delete pException;
        }
#else
        pEnv->DeleteLocalRef(pThrowable);
#endif

    }

    return bRet;
}

jobject connectivity::createByteInputStream(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x,sal_Int32 length)
{
    SDBThreadAttach t;
    if( !t.pEnv || !x.is() )
        return NULL;
    // Turn off Java-Call for the constructor
    // Initialize temperary variables
    jclass clazz = java_lang_Object::findMyClass("java/io/ByteArrayInputStream");
    static jmethodID mID(NULL);
    if  ( !mID )
    {
        static const char * cSignature = "([B)V";
        mID  = t.pEnv->GetMethodID( clazz, "<init>", cSignature );
        OSL_ENSURE( mID, cSignature );
        if  ( !mID )
            throw SQLException();
    } // if  ( !_inout_MethodID )
    jbyteArray pByteArray = t.pEnv->NewByteArray(length);
    Sequence< sal_Int8 > aData;
    x->readBytes(aData,length);
    jboolean p = sal_False;
    memcpy(t.pEnv->GetByteArrayElements(pByteArray,&p),aData.getArray(),aData.getLength());
    jobject out = t.pEnv->NewObject( clazz, mID,pByteArray);
    t.pEnv->DeleteLocalRef((jbyteArray)pByteArray);
    return out;
}

jobject connectivity::createCharArrayReader(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x,sal_Int32 length)
{
    SDBThreadAttach t;
    if( !t.pEnv || !x.is() )
        return NULL;
    // Turn off Java-Call for the constructor
    // Initialize temperary Variables
    jclass clazz = java_lang_Object::findMyClass("java/io/CharArrayReader");
    static jmethodID mID(NULL);
    if  ( !mID )
    {
        static const char * cSignature = "([C)V";
        mID  = t.pEnv->GetMethodID( clazz, "<init>", cSignature );
        OSL_ENSURE( mID, cSignature );
        if  ( !mID )
            throw SQLException();
    } // if  ( !_inout_MethodID )
    jcharArray pCharArray = t.pEnv->NewCharArray(length);
    Sequence< sal_Int8 > aData;
    x->readBytes(aData,length);
    jboolean p = sal_False;
    memcpy(t.pEnv->GetCharArrayElements(pCharArray,&p),aData.getArray(),aData.getLength());
    jobject out = t.pEnv->NewObject( clazz, mID,pCharArray);
    t.pEnv->DeleteLocalRef((jcharArray)pCharArray);
    return out;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Replace "compareToAscii" by !=<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <string.h>
#include <cstdarg>
#include "java/tools.hxx"
#include "java/lang/String.hxx"
#include "java/lang/Class.hxx"
#include "java/util/Property.hxx"
#include <com/sun/star/sdbc/DriverPropertyInfo.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <connectivity/dbexception.hxx>

using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;

void java_util_Properties::setProperty(const OUString& key, const OUString& value)
{
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    jobject out(0);

    {
        jvalue args[2];
        // Convert Parameter
        args[0].l = convertwchar_tToJavaString(t.pEnv,key);
        args[1].l = convertwchar_tToJavaString(t.pEnv,value);
        // Initialize temporary Variables
        static const char * cSignature = "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;";
        static const char * cMethodName = "setProperty";
        // Turn off Java-Call
        static jmethodID mID(NULL);
        obtainMethodId(t.pEnv, cMethodName,cSignature, mID);
        out = t.pEnv->CallObjectMethod(object, mID, args[0].l,args[1].l);
        ThrowSQLException(t.pEnv,NULL);
        t.pEnv->DeleteLocalRef((jstring)args[1].l);
        t.pEnv->DeleteLocalRef((jstring)args[0].l);
        ThrowSQLException(t.pEnv,0);
        if(out)
            t.pEnv->DeleteLocalRef(out);
    } //t.pEnv
    // WARNING: The caller will be owner of the returned pointers!!!
}
jclass java_util_Properties::theClass = 0;

java_util_Properties::~java_util_Properties()
{}

jclass java_util_Properties::getMyClass() const
{
    // the class needs only be called once, that is why it is static
    if( !theClass )
        theClass = findMyClass("java/util/Properties");
    return theClass;
}

java_util_Properties::java_util_Properties( ): java_lang_Object( NULL, (jobject)NULL )
{
    SDBThreadAttach t;
    if( !t.pEnv )
        return;
    // Turn off Java-Call for the constructor
    // Initialize temperary Variables
    static const char * cSignature = "()V";
    jobject tempObj;
    static jmethodID mID(NULL);
    obtainMethodId(t.pEnv, "<init>",cSignature, mID);
    tempObj = t.pEnv->NewObject( getMyClass(), mID);
    saveRef( t.pEnv, tempObj );
    t.pEnv->DeleteLocalRef( tempObj );
}

jstring connectivity::convertwchar_tToJavaString(JNIEnv *pEnv,const OUString& _rTemp)
{
    OSL_ENSURE(pEnv,"Environment is NULL!");
    jstring pStr = pEnv->NewString(_rTemp.getStr(), _rTemp.getLength());
    pEnv->ExceptionClear();
    OSL_ENSURE(pStr,"Could not create a jsstring object!");
    return pStr;
}

java_util_Properties* connectivity::createStringPropertyArray(const Sequence< PropertyValue >& info )  throw(SQLException, RuntimeException)
{
    java_util_Properties* pProps = new java_util_Properties();
    const PropertyValue* pBegin = info.getConstArray();
    const PropertyValue* pEnd   = pBegin + info.getLength();

    for(;pBegin != pEnd;++pBegin)
    {
        // these are properties used internally by LibreOffice,
        // and should not be passed to the JDBC driver
        // (which probably does not know anything about them anyway).
        if  (   pBegin->Name != "JavaDriverClass"
            &&  pBegin->Name != "JavaDriverClassPath"
            &&  pBegin->Name != "SystemProperties"
            &&  pBegin->Name != "CharSet"
            &&  pBegin->Name != "AppendTableAliasName"
            &&  pBegin->Name != "AddIndexAppendix"
            &&  pBegin->Name != "FormsCheckRequiredFields"
            &&  pBegin->Name != "GenerateASBeforeCorrelationName"
            &&  pBegin->Name != "EscapeDateTime"
            &&  pBegin->Name != "ParameterNameSubstitution"
            &&  pBegin->Name != "IsPasswordRequired"
            &&  pBegin->Name != "IsAutoRetrievingEnabled"
            &&  pBegin->Name != "AutoRetrievingStatement"
            &&  pBegin->Name != "UseCatalogInSelect"
            &&  pBegin->Name != "UseSchemaInSelect"
            &&  pBegin->Name != "AutoIncrementCreation"
            &&  pBegin->Name != "Extension"
            &&  pBegin->Name != "NoNameLengthLimit"
            &&  pBegin->Name != "EnableSQL92Check"
            &&  pBegin->Name != "EnableOuterJoinEscape"
            &&  pBegin->Name != "BooleanComparisonMode"
            &&  pBegin->Name != "IgnoreCurrency"
            &&  pBegin->Name != "TypeInfoSettings"
            &&  pBegin->Name != "IgnoreDriverPrivileges"
            &&  pBegin->Name != "ImplicitCatalogRestriction"
            &&  pBegin->Name != "ImplicitSchemaRestriction"
            &&  pBegin->Name != "SupportsTableCreation"
            &&  pBegin->Name != "UseJava"
            &&  pBegin->Name != "Authentication"
            &&  pBegin->Name != "PreferDosLikeLineEnds"
            &&  pBegin->Name != "PrimaryKeySupport"
            &&  pBegin->Name != "RespectDriverResultSetType"
            )
        {
            OUString aStr;
            OSL_VERIFY( pBegin->Value >>= aStr );
            pProps->setProperty(pBegin->Name,aStr);
        }
    }
    return pProps;
}

OUString connectivity::JavaString2String(JNIEnv *pEnv,jstring _Str)
{
    OUString aStr;
    if(_Str)
    {
        jboolean bCopy(sal_True);
        const jchar* pChar = pEnv->GetStringChars(_Str,&bCopy);
        jsize len = pEnv->GetStringLength(_Str);
        aStr = OUString(pChar,len);

        if(bCopy)
            pEnv->ReleaseStringChars(_Str,pChar);
        pEnv->DeleteLocalRef(_Str);
    }
    return aStr;
}

jobject connectivity::convertTypeMapToJavaMap(JNIEnv* /*pEnv*/,const Reference< ::com::sun::star::container::XNameAccess > & _rMap)
{
    if ( _rMap.is() )
    {
        ::com::sun::star::uno::Sequence< OUString > aNames = _rMap->getElementNames();
        if ( aNames.getLength() > 0 )
            ::dbtools::throwFeatureNotImplementedException( "Type maps", NULL );
    }
    return 0;
}

bool connectivity::isExceptionOccurred(JNIEnv *pEnv,bool _bClear)
{
    if ( !pEnv )
        return false;

    jthrowable pThrowable = pEnv->ExceptionOccurred();
    bool bRet = pThrowable != NULL;
    if ( pThrowable )
    {
        if ( _bClear )
            pEnv->ExceptionClear();
#if OSL_DEBUG_LEVEL > 1
        if(pEnv->IsInstanceOf(pThrowable,java_sql_SQLException_BASE::st_getMyClass()))
        {

            java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,pThrowable);
            OUString sError = pException->getMessage();
            delete pException;
        }
#else
        pEnv->DeleteLocalRef(pThrowable);
#endif

    }

    return bRet;
}

jobject connectivity::createByteInputStream(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x,sal_Int32 length)
{
    SDBThreadAttach t;
    if( !t.pEnv || !x.is() )
        return NULL;
    // Turn off Java-Call for the constructor
    // Initialize temperary variables
    jclass clazz = java_lang_Object::findMyClass("java/io/ByteArrayInputStream");
    static jmethodID mID(NULL);
    if  ( !mID )
    {
        static const char * cSignature = "([B)V";
        mID  = t.pEnv->GetMethodID( clazz, "<init>", cSignature );
        OSL_ENSURE( mID, cSignature );
        if  ( !mID )
            throw SQLException();
    } // if  ( !_inout_MethodID )
    jbyteArray pByteArray = t.pEnv->NewByteArray(length);
    Sequence< sal_Int8 > aData;
    x->readBytes(aData,length);
    jboolean p = sal_False;
    memcpy(t.pEnv->GetByteArrayElements(pByteArray,&p),aData.getArray(),aData.getLength());
    jobject out = t.pEnv->NewObject( clazz, mID,pByteArray);
    t.pEnv->DeleteLocalRef((jbyteArray)pByteArray);
    return out;
}

jobject connectivity::createCharArrayReader(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x,sal_Int32 length)
{
    SDBThreadAttach t;
    if( !t.pEnv || !x.is() )
        return NULL;
    // Turn off Java-Call for the constructor
    // Initialize temperary Variables
    jclass clazz = java_lang_Object::findMyClass("java/io/CharArrayReader");
    static jmethodID mID(NULL);
    if  ( !mID )
    {
        static const char * cSignature = "([C)V";
        mID  = t.pEnv->GetMethodID( clazz, "<init>", cSignature );
        OSL_ENSURE( mID, cSignature );
        if  ( !mID )
            throw SQLException();
    } // if  ( !_inout_MethodID )
    jcharArray pCharArray = t.pEnv->NewCharArray(length);
    Sequence< sal_Int8 > aData;
    x->readBytes(aData,length);
    jboolean p = sal_False;
    memcpy(t.pEnv->GetCharArrayElements(pCharArray,&p),aData.getArray(),aData.getLength());
    jobject out = t.pEnv->NewObject( clazz, mID,pCharArray);
    t.pEnv->DeleteLocalRef((jcharArray)pCharArray);
    return out;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <stdio.h>

#include "Bytes.h"
#include "TBranch.h"
#include "TBufferFile.h"
#include "TFile.h"
#include "TTree.h"
#include "TStopwatch.h"
#include "TTreeReader.h"
#include "TTreeReaderValue.h"
#include "ROOT/TTreeReaderFast.hxx"
#include "ROOT/TTreeReaderValueFast.hxx"

#include "gtest/gtest.h"

class BulkApiTest : public ::testing::Test {
public:
   static constexpr Long64_t fEventCount = (Long64_t)1e7;
   const std::string fFileName = "BulkApiTest.root";

protected:
   virtual void SetUp()
   {
      auto hfile = TFile::Open(fFileName.c_str(), "recreate", "TTree float micro benchmark ROOT file");
      hfile->SetCompressionLevel(0); // No compression at all.

      // Otherwise, we keep with the current ROOT defaults.
      auto tree = new TTree("T", "A ROOT tree of floats.");
      float f = 2;
      tree->Branch("myFloat", &f, 320000, 1);
      for (Long64_t ev = 0; ev < fEventCount; ev++) {
         tree->Fill();
         ++f;
      }
      hfile = tree->GetCurrentFile();
      hfile->Write();
      tree->Print();
      printf("Successful write of all events.\n");

      // We also want a copy the TTree with a basket stored alongside the TTree
      // rather than on its own.
      for (Long64_t ev = 0; ev < 10; ev++) {
         tree->Fill();
         ++f;
      }
      hfile->WriteTObject(tree, "TwithBasket");
      hfile->Close();

      delete hfile;
   }
};

TEST_F(BulkApiTest, stdRead)
{
   auto hfile = TFile::Open(fFileName.c_str());
   printf("Starting read of file %s.\n", fFileName.c_str());
   TStopwatch sw;

   printf("Using standard read APIs.\n");
   // Read via standard APIs.
   TTreeReader myReader("T", hfile);
   TTreeReaderValue<float> myF(myReader, "myFloat");
   Long64_t idx = 0;
   float idx_f = 1;
   auto events = fEventCount;
   sw.Start();
   while (myReader.Next()) {
      if (R__unlikely(idx == events)) {
         break;
      }
      idx_f++;
      if (R__unlikely((idx < 16000000) && (abs((*myF) - idx_f) > std::numeric_limits<float>::epsilon()))) {
         printf("Incorrect value on myFloat branch: %f, expected %f (event %lld)\n", *myF, idx_f, idx);
         ASSERT_TRUE(false);
      }
      idx++;
   }
   sw.Stop();
   printf("TTreeReader: Successful read of all events.\n");
   printf("TTreeReader: Total elapsed time (seconds) for standard APIs: %.2f\n", sw.RealTime());
   delete hfile;
}

void SimpleReadFunc(const char *filename, const char *treename)
{
   auto hfile = TFile::Open(filename);
   printf("Starting read of file %s.\n", filename);
   TStopwatch sw;

   printf("Using inline bulk read APIs.\n");
   TBufferFile branchbuf(TBuffer::kWrite, 32 * 1024);
   TTree *tree = dynamic_cast<TTree *>(hfile->Get(treename));
   ASSERT_TRUE(tree);

   TBranch *branchF = tree->GetBranch("myFloat");
   ASSERT_TRUE(branchF);
   branchF->GetListOfBaskets()->ls();

   float idx_f = 1;
   Long64_t evt_idx = 0;
   Long64_t events = tree->GetEntries();
   while (events) {
      auto count = branchF->GetBulkRead().GetEntriesSerialized(evt_idx, branchbuf);
      ASSERT_GE(count, 0);
      events = events > count ? (events - count) : 0;

      float *entry = reinterpret_cast<float *>(branchbuf.GetCurrent());
      for (Int_t idx = 0; idx < count; idx++) {
         idx_f++;
         Int_t tmp = *reinterpret_cast<Int_t *>(&entry[idx]);
         char *tmp_ptr = reinterpret_cast<char *>(&tmp);
         frombuf(tmp_ptr, entry + idx);

         if (R__unlikely((evt_idx < 16000000) && (entry[idx] != idx_f))) {
            printf("in %s Incorrect value on myFloat branch: %f (event %lld)\n", treename, entry[idx], evt_idx + idx);
            ASSERT_TRUE(false);
         }
      }
      evt_idx += count;
   }
   sw.Stop();
   printf("GetEntriesSerialized: Successful read of all events in %s.\n", treename);
   printf("GetEntriesSerialized: Total elapsed time (seconds) for bulk APIs: %.2f\n", sw.RealTime());
   delete hfile;
}

TEST_F(BulkApiTest, simpleRead)
{
   SimpleReadFunc(fFileName.c_str(), "T");
}

TEST_F(BulkApiTest, simpleReadTrailingBasket)
{
   SimpleReadFunc(fFileName.c_str(), "TwithBasket");
}

void SimpleBulkReadFunc(const char *filename, const char *treename)
{
   auto hfile = TFile::Open(filename);
   printf("Starting read of file %s.\n", filename);
   TStopwatch sw;

   printf("Using outlined bulk read APIs.\n");
   TBufferFile branchbuf(TBuffer::kWrite, 32 * 1024);
   TTree *tree = dynamic_cast<TTree *>(hfile->Get(treename));
   ASSERT_TRUE(tree);

   TBranch *branchF = tree->GetBranch("myFloat");
   ASSERT_TRUE(branchF);
   branchF->GetListOfBaskets()->ls();

   float idx_f = 1;
   Long64_t evt_idx = 0;
   Long64_t events = tree->GetEntries();
   while (events) {
      auto count = branchF->GetBulkRead().GetBulkEntries(evt_idx, branchbuf);
      ASSERT_GE(count, 0);
      events = events > count ? (events - count) : 0;

      float *entry = reinterpret_cast<float *>(branchbuf.GetCurrent());
      for (Int_t idx = 0; idx < count; idx++) {
         idx_f++;
         if (R__unlikely((evt_idx < 16000000) && (entry[idx] != idx_f))) {
            printf("in %s Incorrect value on myFloat branch: %f (event %lld)\n", treename, entry[idx], evt_idx + idx);
            ASSERT_TRUE(false);
         }
      }
      evt_idx += count;
   }
   sw.Stop();
   printf("GetBulkEntries: Successful read of all events in %s.\n", treename);
   printf("GetBulkEntries: Total elapsed time (seconds) for bulk APIs: %.2f\n", sw.RealTime());
   delete hfile;
}

TEST_F(BulkApiTest, simpleBulkRead)
{
   SimpleBulkReadFunc(fFileName.c_str(), "T");
}

TEST_F(BulkApiTest, simpleBulkReadTrailingBasket)
{
   SimpleBulkReadFunc(fFileName.c_str(), "TwithBasket");
}

TEST_F(BulkApiTest, fastRead)
{
   auto hfile = TFile::Open(fFileName.c_str());
   printf("Starting read of file %s.\n", fFileName.c_str());
   TStopwatch sw;

   printf("Using TTreeReaderFast.\n");
   ROOT::Experimental::TTreeReaderFast myReader("T", hfile);
   ROOT::Experimental::TTreeReaderValueFast<float> myF(myReader, "myFloat");
   myReader.SetEntry(0);
   if (ROOT::Internal::TTreeReaderValueBase::kSetupMatch != myF.GetSetupStatus()) {
      printf("TTreeReaderValueFast<float> failed to initialize.  Status code: %d\n", myF.GetSetupStatus());
      ASSERT_TRUE(false);
   }
   if (myReader.GetEntryStatus() != TTreeReader::kEntryValid) {
      printf("TTreeReaderFast failed to initialize.  Entry status: %d\n", myReader.GetEntryStatus());
      ASSERT_TRUE(false);
   }
   auto events = fEventCount;
   Long64_t idx = 0;
   float idx_f = 1;
   for (auto reader_idx : myReader) {
      ASSERT_LT(reader_idx, events);
      ASSERT_EQ(reader_idx, idx);
      idx_f++;
      if (R__unlikely((idx < 16000000) && (abs((*myF) - idx_f) > std::numeric_limits<float>::epsilon()))) {
         printf("Incorrect value on myFloat branch: %f, expected %f (event %lld)\n", *myF, idx_f, idx);
         ASSERT_TRUE(false);
      }
      idx++;
   }
   sw.Stop();
   printf("TTreeReaderFast: Successful read of all events.\n");
   printf("TTreeReaderFast: Total elapsed time (seconds) for bulk APIs: %.2f\n", sw.RealTime());
   delete hfile;
}

TEST_F(BulkApiTest, BulkInMem)
{
   TTree t("t","t");
   int i = 3;
   t.Branch("fAlpha",&i);
   for(i = 0; i < 100000; ++i)
      t.Fill();

   TBufferFile buf(TBuffer::EMode::kWrite, 32*1024);
   auto &r = t.GetBranch("fAlpha")->GetBulkRead();

   {
      auto s = r.GetBulkEntries(0, buf);
      ASSERT_EQ(7982, s) << "Did not read the expected number of entries.";
      s = r.GetBulkEntries(0, buf);
      ASSERT_EQ(7982, s) << "Did not read the expected number of entries.";
   }

   int iteration = 0;
   Long64_t nentries = t.GetEntries();
   Long64_t event_idx = 0;
   while (nentries) {
      auto s = r.GetBulkEntries(event_idx, buf);
      if (iteration < 12)
         ASSERT_EQ(7982, s) << "Did not read the expected number of entries.";
      else
         ASSERT_EQ(4216, s) << "Did not read the expected number of entries.";
      nentries -= s;
      event_idx += s;
      ++iteration;
      if (s < 0)
         break;
   }
}
<commit_msg>[clang-]modernize BulkApi test<commit_after>#include <stdio.h>

#include "Bytes.h"
#include "TBranch.h"
#include "TBufferFile.h"
#include "TFile.h"
#include "TTree.h"
#include "TStopwatch.h"
#include "TTreeReader.h"
#include "TTreeReaderValue.h"
#include "ROOT/TTreeReaderFast.hxx"
#include "ROOT/TTreeReaderValueFast.hxx"

#include "gtest/gtest.h"

class BulkApiTest : public ::testing::Test {
public:
   static constexpr Long64_t fEventCount = (Long64_t)1e7;
   const std::string fFileName = "BulkApiTest.root";

protected:
   virtual void SetUp()
   {
      auto hfile = TFile::Open(fFileName.c_str(), "recreate", "TTree float micro benchmark ROOT file");
      hfile->SetCompressionLevel(0); // No compression at all.

      // Otherwise, we keep with the current ROOT defaults.
      auto tree = new TTree("T", "A ROOT tree of floats.");
      float f = 2;
      tree->Branch("myFloat", &f, 320000, 1);
      for (Long64_t ev = 0; ev < fEventCount; ev++) {
         tree->Fill();
         ++f;
      }
      hfile = tree->GetCurrentFile();
      hfile->Write();
      tree->Print();
      printf("Successful write of all events.\n");

      // We also want a copy the TTree with a basket stored alongside the TTree
      // rather than on its own.
      for (Long64_t ev = 0; ev < 10; ev++) {
         tree->Fill();
         ++f;
      }
      hfile->WriteTObject(tree, "TwithBasket");
      hfile->Close();

      delete hfile;
   }
};

TEST_F(BulkApiTest, stdRead)
{
   auto hfile = TFile::Open(fFileName.c_str());
   printf("Starting read of file %s.\n", fFileName.c_str());
   TStopwatch sw;

   printf("Using standard read APIs.\n");
   // Read via standard APIs.
   TTreeReader myReader("T", hfile);
   TTreeReaderValue<float> myF(myReader, "myFloat");
   Long64_t idx = 0;
   float idx_f = 1;
   auto events = fEventCount;
   sw.Start();
   while (myReader.Next()) {
      if (R__unlikely(idx == events)) {
         break;
      }
      idx_f++;
      if (R__unlikely((idx < 16000000) && (abs((*myF) - idx_f) > std::numeric_limits<float>::epsilon()))) {
         printf("Incorrect value on myFloat branch: %f, expected %f (event %lld)\n", *myF, idx_f, idx);
         ASSERT_TRUE(false);
      }
      idx++;
   }
   sw.Stop();
   printf("TTreeReader: Successful read of all events.\n");
   printf("TTreeReader: Total elapsed time (seconds) for standard APIs: %.2f\n", sw.RealTime());
   delete hfile;
}

void SimpleReadFunc(const char *filename, const char *treename)
{
   auto hfile = TFile::Open(filename);
   printf("Starting read of file %s.\n", filename);
   TStopwatch sw;

   printf("Using inline bulk read APIs.\n");
   TBufferFile branchbuf(TBuffer::kWrite, 32 * 1024);
   auto tree = hfile->Get<TTree>(treename);
   ASSERT_TRUE(tree);

   TBranch *branchF = tree->GetBranch("myFloat");
   ASSERT_TRUE(branchF);
   branchF->GetListOfBaskets()->ls();

   float idx_f = 1;
   Long64_t evt_idx = 0;
   Long64_t events = tree->GetEntries();
   while (events) {
      auto count = branchF->GetBulkRead().GetEntriesSerialized(evt_idx, branchbuf);
      ASSERT_GE(count, 0);
      events = events > count ? (events - count) : 0;

      auto entry = reinterpret_cast<float *>(branchbuf.GetCurrent());
      for (Int_t idx = 0; idx < count; idx++) {
         idx_f++;
         auto tmp = *reinterpret_cast<Int_t *>(&entry[idx]);
         auto tmp_ptr = reinterpret_cast<char *>(&tmp);
         frombuf(tmp_ptr, entry + idx);

         if (R__unlikely((evt_idx < 16000000) && (entry[idx] != idx_f))) {
            printf("in %s Incorrect value on myFloat branch: %f (event %lld)\n", treename, entry[idx], evt_idx + idx);
            ASSERT_TRUE(false);
         }
      }
      evt_idx += count;
   }
   sw.Stop();
   printf("GetEntriesSerialized: Successful read of all events in %s.\n", treename);
   printf("GetEntriesSerialized: Total elapsed time (seconds) for bulk APIs: %.2f\n", sw.RealTime());
   delete hfile;
}

TEST_F(BulkApiTest, simpleRead)
{
   SimpleReadFunc(fFileName.c_str(), "T");
}

TEST_F(BulkApiTest, simpleReadTrailingBasket)
{
   SimpleReadFunc(fFileName.c_str(), "TwithBasket");
}

void SimpleBulkReadFunc(const char *filename, const char *treename)
{
   auto hfile = TFile::Open(filename);
   printf("Starting read of file %s.\n", filename);
   TStopwatch sw;

   printf("Using outlined bulk read APIs.\n");
   TBufferFile branchbuf(TBuffer::kWrite, 32 * 1024);
   auto tree = hfile->Get<TTree>(treename);
   ASSERT_TRUE(tree);

   TBranch *branchF = tree->GetBranch("myFloat");
   ASSERT_TRUE(branchF);
   branchF->GetListOfBaskets()->ls();

   float idx_f = 1;
   Long64_t evt_idx = 0;
   Long64_t events = tree->GetEntries();
   while (events) {
      auto count = branchF->GetBulkRead().GetBulkEntries(evt_idx, branchbuf);
      ASSERT_GE(count, 0);
      events = events > count ? (events - count) : 0;

      auto entry = reinterpret_cast<float *>(branchbuf.GetCurrent());
      for (Int_t idx = 0; idx < count; idx++) {
         idx_f++;
         if (R__unlikely((evt_idx < 16000000) && (entry[idx] != idx_f))) {
            printf("in %s Incorrect value on myFloat branch: %f (event %lld)\n", treename, entry[idx], evt_idx + idx);
            ASSERT_TRUE(false);
         }
      }
      evt_idx += count;
   }
   sw.Stop();
   printf("GetBulkEntries: Successful read of all events in %s.\n", treename);
   printf("GetBulkEntries: Total elapsed time (seconds) for bulk APIs: %.2f\n", sw.RealTime());
   delete hfile;
}

TEST_F(BulkApiTest, simpleBulkRead)
{
   SimpleBulkReadFunc(fFileName.c_str(), "T");
}

TEST_F(BulkApiTest, simpleBulkReadTrailingBasket)
{
   SimpleBulkReadFunc(fFileName.c_str(), "TwithBasket");
}

TEST_F(BulkApiTest, fastRead)
{
   auto hfile = TFile::Open(fFileName.c_str());
   printf("Starting read of file %s.\n", fFileName.c_str());
   TStopwatch sw;

   printf("Using TTreeReaderFast.\n");
   ROOT::Experimental::TTreeReaderFast myReader("T", hfile);
   ROOT::Experimental::TTreeReaderValueFast<float> myF(myReader, "myFloat");
   myReader.SetEntry(0);
   if (ROOT::Internal::TTreeReaderValueBase::kSetupMatch != myF.GetSetupStatus()) {
      printf("TTreeReaderValueFast<float> failed to initialize.  Status code: %d\n", myF.GetSetupStatus());
      ASSERT_TRUE(false);
   }
   if (myReader.GetEntryStatus() != TTreeReader::kEntryValid) {
      printf("TTreeReaderFast failed to initialize.  Entry status: %d\n", myReader.GetEntryStatus());
      ASSERT_TRUE(false);
   }
   auto events = fEventCount;
   Long64_t idx = 0;
   float idx_f = 1;
   for (auto reader_idx : myReader) {
      ASSERT_LT(reader_idx, events);
      ASSERT_EQ(reader_idx, idx);
      idx_f++;
      if (R__unlikely((idx < 16000000) && (abs((*myF) - idx_f) > std::numeric_limits<float>::epsilon()))) {
         printf("Incorrect value on myFloat branch: %f, expected %f (event %lld)\n", *myF, idx_f, idx);
         ASSERT_TRUE(false);
      }
      idx++;
   }
   sw.Stop();
   printf("TTreeReaderFast: Successful read of all events.\n");
   printf("TTreeReaderFast: Total elapsed time (seconds) for bulk APIs: %.2f\n", sw.RealTime());
   delete hfile;
}

TEST_F(BulkApiTest, BulkInMem)
{
   TTree t("t","t");
   int i = 3;
   t.Branch("fAlpha",&i);
   for(i = 0; i < 100000; ++i)
      t.Fill();

   TBufferFile buf(TBuffer::EMode::kWrite, 32*1024);
   auto &r = t.GetBranch("fAlpha")->GetBulkRead();

   {
      auto s = r.GetBulkEntries(0, buf);
      ASSERT_EQ(7982, s) << "Did not read the expected number of entries.";
      s = r.GetBulkEntries(0, buf);
      ASSERT_EQ(7982, s) << "Did not read the expected number of entries.";
   }

   int iteration = 0;
   Long64_t nentries = t.GetEntries();
   Long64_t event_idx = 0;
   while (nentries) {
      auto s = r.GetBulkEntries(event_idx, buf);
      if (iteration < 12)
         ASSERT_EQ(7982, s) << "Did not read the expected number of entries.";
      else
         ASSERT_EQ(4216, s) << "Did not read the expected number of entries.";
      nentries -= s;
      event_idx += s;
      ++iteration;
      if (s < 0)
         break;
   }
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/public/common/content_constants.h"

namespace content {

const base::FilePath::CharType kAppCacheDirname[] =
    FILE_PATH_LITERAL("Application Cache");
const base::FilePath::CharType kPepperDataDirname[] =
    FILE_PATH_LITERAL("Pepper Data");

const char kBrowserPluginMimeType[] = "application/browser-plugin";

const char kFlashPluginName[] = "Shockwave Flash";
const char kFlashPluginSwfMimeType[] = "application/x-shockwave-flash";
const char kFlashPluginSwfExtension[] = "swf";
const char kFlashPluginSwfDescription[] = "Shockwave Flash";
const char kFlashPluginSplMimeType[] = "application/futuresplash";
const char kFlashPluginSplExtension[] = "spl";
const char kFlashPluginSplDescription[] = "FutureSplash Player";

// This number used to be limited to 32 in the past (see b/535234).
const size_t kMaxRendererProcessCount = 82;
const int kMaxSessionHistoryEntries = 50;
const size_t kMaxTitleChars = 4 * 1024;
const size_t kMaxURLChars = 2 * 1024 * 1024;
const size_t kMaxURLDisplayChars = 32 * 1024;

#if defined(GOOGLE_CHROME_BUILD)
const char kStatsFilename[] = "ChromeStats2";
#else
const char kStatsFilename[] = "ChromiumStats2";
#endif

const int kStatsMaxThreads = 32;
const int kStatsMaxCounters = 3000;

const int kHistogramSynchronizerReservedSequenceNumber = 0;

const char kGpuCompositingFieldTrialName[] = "ForceCompositingMode";
const char kGpuCompositingFieldTrialForceCompositingEnabledName[] = "enabled";
const char kGpuCompositingFieldTrialThreadEnabledName[] = "thread";

const char kLowLatencyFlashAudioFieldTrialName[] = "LowLatencyFlashAudio";
const char kLowLatencyFlashAudioFieldTrialEnabledName[] = "LowLatency";

}  // namespace content
<commit_msg>Chromium Fork: Increase URL length limit to 20MB<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/public/common/content_constants.h"

namespace content {

const base::FilePath::CharType kAppCacheDirname[] =
    FILE_PATH_LITERAL("Application Cache");
const base::FilePath::CharType kPepperDataDirname[] =
    FILE_PATH_LITERAL("Pepper Data");

const char kBrowserPluginMimeType[] = "application/browser-plugin";

const char kFlashPluginName[] = "Shockwave Flash";
const char kFlashPluginSwfMimeType[] = "application/x-shockwave-flash";
const char kFlashPluginSwfExtension[] = "swf";
const char kFlashPluginSwfDescription[] = "Shockwave Flash";
const char kFlashPluginSplMimeType[] = "application/futuresplash";
const char kFlashPluginSplExtension[] = "spl";
const char kFlashPluginSplDescription[] = "FutureSplash Player";

// This number used to be limited to 32 in the past (see b/535234).
const size_t kMaxRendererProcessCount = 82;
const int kMaxSessionHistoryEntries = 50;
const size_t kMaxTitleChars = 4 * 1024;
// === START ANDROID K-release fork  http://b/10742235
const size_t kMaxURLChars = 20 * 1024 * 1024;
// === END   ANDROID K-release fork  http://b/10742235
const size_t kMaxURLDisplayChars = 32 * 1024;

#if defined(GOOGLE_CHROME_BUILD)
const char kStatsFilename[] = "ChromeStats2";
#else
const char kStatsFilename[] = "ChromiumStats2";
#endif

const int kStatsMaxThreads = 32;
const int kStatsMaxCounters = 3000;

const int kHistogramSynchronizerReservedSequenceNumber = 0;

const char kGpuCompositingFieldTrialName[] = "ForceCompositingMode";
const char kGpuCompositingFieldTrialForceCompositingEnabledName[] = "enabled";
const char kGpuCompositingFieldTrialThreadEnabledName[] = "thread";

const char kLowLatencyFlashAudioFieldTrialName[] = "LowLatencyFlashAudio";
const char kLowLatencyFlashAudioFieldTrialEnabledName[] = "LowLatency";

}  // namespace content
<|endoftext|>


<commit_before>#include "copasi.h"
#include "utilities.h"
#include "CIndexedPriorityQueue.h"

CIndexedPriorityQueue::CIndexedPriorityQueue()
{}

CIndexedPriorityQueue::~CIndexedPriorityQueue()
{}

C_FLOAT64 CIndexedPriorityQueue::topKey()
{
    return mHeap[0].mKey;
}

C_INT32 CIndexedPriorityQueue::topIndex()
{
    return mHeap[0].mIndex;
}

C_INT32 CIndexedPriorityQueue::pushPair(C_INT32 index, C_FLOAT64 key)
{
    // Add an element to the priority queue. This merely pushes an item onto
    // the back of the vector corresponding to the heap, and pushes the index
    // onto the back of the vector corresponding to the index structure.
    // Implicit is the assumption that this is done in contiguous ascending order
    // for the index; i.e. in index order 0,1,2,3...
    // N.B. The structures are not yet ordered as an indexed priority queue; this must
    // be done using the buildHeap() method

    // First check that the index corresponds to the heap size before insertion
    if (static_cast<unsigned int>(index) != mHeap.size())
    {
        printf("Error inserting pair into priority queue\n");
        return -1;
    }
    PQNode heap_node(index, key);
    mHeap.push_back(heap_node);
    // at first, position == index
    C_INT32 position = index; // for clarity
    mIndexPointer.push_back(position);
    return 0;
}

void CIndexedPriorityQueue::buildHeap()
{
    for (C_INT32 i = mHeap.size()/2 -1 ; i >= 0; i--)
    {
        heapify(i);
    }
}

void CIndexedPriorityQueue::updateNode(C_INT32 index, C_FLOAT64 new_key)
{
    C_INT32 pos = mIndexPointer[index];
    mHeap[pos].mKey = new_key;
    updateAux(pos);
}

void CIndexedPriorityQueue::swapNodes(C_INT32 pos1, C_INT32 pos2)
{
    cout << "Swapping node " << pos1 << "(" << mHeap[pos1].mKey << ") with node ";
    cout << pos2 << "(" << mHeap[pos2].mKey << ")\n";
    C_FLOAT64 tempkey = mHeap[pos1].mKey;
    C_INT32 index1 = mHeap[pos1].mIndex;
    C_INT32 index2 = mHeap[pos2].mIndex;
    // Put the contents of the node at pos2 into the node at pos1
    mHeap[pos1].mIndex = index2;
    mHeap[pos1].mKey = mHeap[pos2].mKey;
    // Put the contents formerly in the node at pos1 into the node at pos2
    mHeap[pos2].mIndex = index1;
    mHeap[pos2].mKey = tempkey;
    // Swap the pointers in the index vector
    mIndexPointer[index1] = pos2;
    mIndexPointer[index2] = pos1;
}

void CIndexedPriorityQueue::heapify(C_INT32 current)
{
    C_INT32 left = leftChild(current);
    C_INT32 right = rightChild(current);
    C_INT32 highest_priority = current;
    cout << "Heapifying " << current << "(Currently " << mHeap[current].mKey << ")" << endl;
    if ( (static_cast<unsigned int>(left) < mHeap.size()) && (mHeap[left].mKey < mHeap[current].mKey) )
    {
        highest_priority = left;
    }
    if ( (static_cast<unsigned int>(right) < mHeap.size()) && (mHeap[right].mKey < mHeap[highest_priority].mKey) )
    {
        highest_priority = right;
    }
    if (highest_priority != current)
    {
        swapNodes(current, highest_priority);
        heapify(highest_priority);
    }
}

void CIndexedPriorityQueue::updateAux(C_INT32 pos)
{
    C_INT32 parent_pos = parent(pos);
    C_FLOAT64 keyval = mHeap[pos].mKey;
    if ((parent_pos >= 0) && (keyval < mHeap[parent_pos].mKey))
    {
        swapNodes(pos, parent_pos);
        updateAux(parent_pos);
    }
    else
    {
        C_INT32 left = leftChild(pos);
        C_INT32 right = rightChild(pos);
        C_FLOAT64 min;
        C_INT32 min_pos = 0;
        if (static_cast<unsigned int>(left) < mHeap.size())
        {
            min = mHeap[left].mKey;
            min_pos = left;
        }
        C_FLOAT64 val = mHeap[right].mKey;
        if ((static_cast<unsigned int>(right) < mHeap.size()) && ( val < min ) )
        {
            min = val;
            min_pos = right;
        }
        if ( (min_pos > 0) && (keyval > min) )
        {
            swapNodes(mHeap[pos].mIndex, min_pos);
            updateAux(min_pos);
        }
    }
}

#ifdef TEST_PRIORITY_QUEUE

int main(int argc, char **argv)
{
    // Generates a vector of pairs, with a size given by the first argument. Each element is added to a priority queue.
    if (argc != 2)
    {
        cout << "Usage: " << argv[0] << " <number of pairs to generate>" << endl;
        return -1;
    }
    int count = atoi(argv[1]);
    cout << "Creating priority queue of size " << count << endl;
    std::vector<C_FLOAT64> invec;
    CIndexedPriorityQueue pq;
    CRandom *rand = new CRandom(1);
    C_FLOAT64 rndval;
    cout << "Input vector:\n";
    for (int i = 0; i < count ; i++)
    {
        rndval = rand->getUniformRandom();
        invec.push_back(rndval);
        cout << "element " << i << ":" << rndval << endl;
        pq.pushPair(i, invec[i]);
    }
    cout << "Building heap\n";
    pq.buildHeap();
    cout << "Done building heap\n";
    // Display the priority queue
    cout << "\nPriority Queue:\n";
    for (int i = 0; i < count; i++)
    {
        cout << "Queue: ";
        for (int j = 0; j < count; j++) cout << " " << j << "-" << pq[j];
        cout << endl;
        cout << "Position: " << i;
        cout << " Index = " << pq.topIndex();
        cout << " Key = " << pq.topKey() << endl;
        pq.updateNode(pq.topIndex(), 10000000);
    }

    return 0;
}

#endif // TEST_PRIORITY_QUEUE

<commit_msg>fixed a bug<commit_after>#include "copasi.h"
#include "utilities.h"
#include "CIndexedPriorityQueue.h"

CIndexedPriorityQueue::CIndexedPriorityQueue()
{}

CIndexedPriorityQueue::~CIndexedPriorityQueue()
{}

C_FLOAT64 CIndexedPriorityQueue::topKey()
{
    return mHeap[0].mKey;
}

C_INT32 CIndexedPriorityQueue::topIndex()
{
    return mHeap[0].mIndex;
}

C_INT32 CIndexedPriorityQueue::pushPair(C_INT32 index, C_FLOAT64 key)
{
    // Add an element to the priority queue. This merely pushes an item onto
    // the back of the vector corresponding to the heap, and pushes the index
    // onto the back of the vector corresponding to the index structure.
    // Implicit is the assumption that this is done in contiguous ascending order
    // for the index; i.e. in index order 0,1,2,3...
    // N.B. The structures are not yet ordered as an indexed priority queue; this must
    // be done using the buildHeap() method

    // First check that the index corresponds to the heap size before insertion
    if (static_cast<unsigned int>(index) != mHeap.size())
    {
        CCopasiMessage(CCopasiMessage::ERROR, "Error inserting pair into priority queue");
        return -1;
    }
    PQNode heap_node(index, key);
    mHeap.push_back(heap_node);
    // at first, position == index
    C_INT32 position = index; // for clarity
    mIndexPointer.push_back(position);
    return 0;
}

void CIndexedPriorityQueue::buildHeap()
{
    for (C_INT32 i = mHeap.size()/2 -1 ; i >= 0; i--)
    {
        heapify(i);
    }
}

void CIndexedPriorityQueue::updateNode(C_INT32 index, C_FLOAT64 new_key)
{
    C_INT32 pos = mIndexPointer[index];
//    cout << "Setting heap at " << pos << " to be " << new_key << endl;
    mHeap[pos].mKey = new_key;
    updateAux(pos);
}

void CIndexedPriorityQueue::swapNodes(C_INT32 pos1, C_INT32 pos2)
{
//    cout << "Swapping node " << pos1 << "(" << mHeap[pos1].mKey << ") with node ";
//    cout << pos2 << "(" << mHeap[pos2].mKey << ")\n";
    C_FLOAT64 tempkey = mHeap[pos1].mKey;
    C_INT32 index1 = mHeap[pos1].mIndex;
    C_INT32 index2 = mHeap[pos2].mIndex;
    // Put the contents of the node at pos2 into the node at pos1
    mHeap[pos1].mIndex = index2;
    mHeap[pos1].mKey = mHeap[pos2].mKey;
    // Put the contents formerly in the node at pos1 into the node at pos2
    mHeap[pos2].mIndex = index1;
    mHeap[pos2].mKey = tempkey;
    // Swap the pointers in the index vector
    mIndexPointer[index1] = pos2;
    mIndexPointer[index2] = pos1;
}

void CIndexedPriorityQueue::heapify(C_INT32 current)
{
    C_INT32 left = leftChild(current);
    C_INT32 right = rightChild(current);
    C_INT32 highest_priority = current;
//    cout << "Heapifying " << current << "(Currently " << mHeap[current].mKey << ")" << endl;
    if ( (static_cast<unsigned int>(left) < mHeap.size()) && (mHeap[left].mKey < mHeap[current].mKey) )
    {
        highest_priority = left;
    }
    if ( (static_cast<unsigned int>(right) < mHeap.size()) && (mHeap[right].mKey < mHeap[highest_priority].mKey) )
    {
        highest_priority = right;
    }
    if (highest_priority != current)
    {
        swapNodes(current, highest_priority);
        heapify(highest_priority);
    }
}

void CIndexedPriorityQueue::updateAux(C_INT32 pos)
{
    C_INT32 parent_pos = parent(pos);
    C_FLOAT64 keyval = mHeap[pos].mKey;
    if ((parent_pos >= 0) && (keyval < mHeap[parent_pos].mKey))
    {
        swapNodes(pos, parent_pos);
        updateAux(parent_pos);
    }
    else
    {
        C_INT32 left = leftChild(pos);
        C_INT32 right = rightChild(pos);
        C_FLOAT64 min;
        C_INT32 min_pos = 0;
        if (static_cast<unsigned int>(left) < mHeap.size())
        {
            min = mHeap[left].mKey;
            min_pos = left;
        }
        C_FLOAT64 val = mHeap[right].mKey;
        if ((static_cast<unsigned int>(right) < mHeap.size()) && ( val < min ) )
        {
            min = val;
            min_pos = right;
        }
        if ( (min_pos > 0) && (keyval > min) )
        {
//            swapNodes(mHeap[pos].mIndex, min_pos);
            swapNodes(pos, min_pos);
            updateAux(min_pos);
        }
    }
}

#ifdef TEST_PRIORITY_QUEUE

int main(int argc, char **argv)
{
    // Generates a vector of pairs, with a size given by the first argument. Each element is added to a priority queue.
    if (argc != 2)
    {
        cout << "Usage: " << argv[0] << " <number of pairs to generate>" << endl;
        return -1;
    }
    int count = atoi(argv[1]);
    cout << "Creating priority queue of size " << count << endl;
    std::vector<C_FLOAT64> invec;
    CIndexedPriorityQueue pq;
    CRandom *rand = new CRandom(1);
    C_FLOAT64 rndval;
    cout << "Input vector:\n";
    for (int i = 0; i < count ; i++)
    {
        rndval = rand->getUniformRandom();
        invec.push_back(rndval);
        cout << "element " << i << ":" << rndval << endl;
        pq.pushPair(i, invec[i]);
    }
    cout << "Building heap\n";
    pq.buildHeap();
    cout << "Done building heap\n";
    // Display the priority queue
    cout << "\nPriority Queue:\n";
    for (int i = 0; i < count; i++)
    {
        cout << "Queue: ";
        for (int j = 0; j < count; j++) cout << " " << j << "-" << pq[j];
        cout << endl;
        cout << "Position: " << i;
        cout << " Index = " << pq.topIndex();
        cout << " Key = " << pq.topKey() << endl;
        pq.updateNode(pq.topIndex(), 10000000);
    }

    return 0;
}

#endif // TEST_PRIORITY_QUEUE

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xlescher.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2003-09-16 08:20:34 $
 *
 *  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 SC_XLESCHER_HXX
#define SC_XLESCHER_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

// (0x005D) OBJ ===============================================================

const sal_uInt16 EXC_ID_OBJ                 = 0x005D;

const sal_uInt16 EXC_OBJ_INVALID_ID         = 0x0000;

// sub records
const sal_uInt16 EXC_ID_OBJ_FTEND           = 0x0000;   /// End of OBJ.
const sal_uInt16 EXC_ID_OBJ_FTGMO           = 0x0006;   /// Group marker.
const sal_uInt16 EXC_ID_OBJ_FTCF            = 0x0007;   /// Clipboard format.
const sal_uInt16 EXC_ID_OBJ_FTPIOGRBIT      = 0x0008;   /// Option flags.
const sal_uInt16 EXC_ID_OBJ_FTPICTFMLA      = 0x0009;   /// OLE link formula.
const sal_uInt16 EXC_ID_OBJ_FTCBLS          = 0x000A;   /// Check box/radio button data.
const sal_uInt16 EXC_ID_OBJ_FTSBS           = 0x000C;   /// Scroll bar data.
const sal_uInt16 EXC_ID_OBJ_FTSBSFMLA       = 0x000E;   /// Scroll bar/list box/combo box cell link.
const sal_uInt16 EXC_ID_OBJ_FTLBSDATA       = 0x0013;   /// List box/combo box data.
const sal_uInt16 EXC_ID_OBJ_FTCBLSFMLA      = 0x0014;   /// Check box/radio button cell link.
const sal_uInt16 EXC_ID_OBJ_FTCMO           = 0x0015;   /// Common object settings.
const sal_uInt16 EXC_ID_OBJ_FTUNKNOWN       = 0xFFFF;   /// For internal use only.

// ftCmo: object types
const sal_uInt16 EXC_OBJ_CMO_GROUP          = 0x0000;
const sal_uInt16 EXC_OBJ_CMO_LINE           = 0x0001;
const sal_uInt16 EXC_OBJ_CMO_RECTANGLE      = 0x0002;
const sal_uInt16 EXC_OBJ_CMO_ELLIPSE        = 0x0003;
const sal_uInt16 EXC_OBJ_CMO_ARC            = 0x0004;
const sal_uInt16 EXC_OBJ_CMO_CHART          = 0x0005;
const sal_uInt16 EXC_OBJ_CMO_TEXT           = 0x0006;
const sal_uInt16 EXC_OBJ_CMO_BUTTON         = 0x0007;
const sal_uInt16 EXC_OBJ_CMO_PICTURE        = 0x0008;
const sal_uInt16 EXC_OBJ_CMO_POLYGON        = 0x0009;
const sal_uInt16 EXC_OBJ_CMO_CHECKBOX       = 0x000B;
const sal_uInt16 EXC_OBJ_CMO_OPTIONBUTTON   = 0x000C;
const sal_uInt16 EXC_OBJ_CMO_EDIT           = 0x000D;
const sal_uInt16 EXC_OBJ_CMO_LABEL          = 0x000E;
const sal_uInt16 EXC_OBJ_CMO_DIALOG         = 0x000F;
const sal_uInt16 EXC_OBJ_CMO_SPIN           = 0x0010;
const sal_uInt16 EXC_OBJ_CMO_SCROLLBAR      = 0x0011;
const sal_uInt16 EXC_OBJ_CMO_LISTBOX        = 0x0012;
const sal_uInt16 EXC_OBJ_CMO_GROUPBOX       = 0x0013;
const sal_uInt16 EXC_OBJ_CMO_COMBOBOX       = 0x0014;
const sal_uInt16 EXC_OBJ_CMO_NOTE           = 0x0019;
const sal_uInt16 EXC_OBJ_CMO_DRAWING        = 0x001E;
const sal_uInt16 EXC_OBJ_CMO_UNKNOWN        = 0xFFFF;   /// For internal use only.

// ftPioGrbit: flags
const sal_uInt16 EXC_OBJ_PIO_LINKED         = 0x0002;
const sal_uInt16 EXC_OBJ_PIO_SYMBOL         = 0x0008;

// ftCbls: Check box/radio button data
const sal_uInt16 EXC_OBJ_CBLS_STATEMASK     = 0x0003;
const sal_uInt16 EXC_OBJ_CBLS_STATE_UNCHECK = 0x0000;
const sal_uInt16 EXC_OBJ_CBLS_STATE_CHECK   = 0x0001;
const sal_uInt16 EXC_OBJ_CBLS_STATE_TRI     = 0x0002;
const sal_uInt16 EXC_OBJ_CBLS_3D            = 0x0001;

// ftLbsData: List box data
const sal_uInt16 EXC_OBJ_LBS_SELMASK        = 0x0030;
const sal_uInt16 EXC_OBJ_LBS_SEL_SIMPLE     = 0x0000;   /// Simple selection.
const sal_uInt16 EXC_OBJ_LBS_SEL_MULTI      = 0x0010;   /// Multi selection.
const sal_uInt16 EXC_OBJ_LBS_SEL_EXT        = 0x0020;   /// Extended selection.
const sal_uInt16 EXC_OBJ_LBS_3D             = 0x0008;

// (0x01B6) TXO ===============================================================

const sal_uInt16 EXC_ID_TXO                 = 0x01B6;

/** Horizontal alignment flags. */
enum XclTxoHorAlign
{
    xlTxoHAlignLeft                         = 0x01,
    xlTxoHAlignCenter                       = 0x02,
    xlTxoHAlignRight                        = 0x03,
    xlTxoHAlignJustify                      = 0x04,
    xlTxoHAlign_Default                     = xlTxoHAlignLeft
};

/** Vertical alignment flags. */
enum XclTxoVerAlign
{
    xlTxoVAlignTop                          = 0x01,
    xlTxoVAlignCenter                       = 0x02,
    xlTxoVAlignBottom                       = 0x03,
    xlTxoVAlignJustify                      = 0x04,
    xlTxoVAlign_Default                     = xlTxoVAlignTop
};

/** Rotation. */
enum XclTxoRotation
{
    xlTxoNoRot                              = 0x0000,       /// Not rotated.
    xlTxoRotStacked                         = 0x0001,       /// characters stacked.
    xlTxoRot90ccw                           = 0x0002,       /// 90 degr. counterclockwise.
    xlTxoRot90cw                            = 0x0003,       /// 90 degr. clockwise.
    xlTxoRot_Default                        = xlTxoNoRot
};

// ============================================================================

#endif

<commit_msg>INTEGRATION: CWS formcelllinkage (1.4.12); FILE MERGED 2003/10/01 09:50:22 fs 1.4.12.1: #i18994# merging the changes from the CWS fs002<commit_after>/*************************************************************************
 *
 *  $RCSfile: xlescher.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2003-10-21 08:49:14 $
 *
 *  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 SC_XLESCHER_HXX
#define SC_XLESCHER_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

// (0x005D) OBJ ===============================================================

const sal_uInt16 EXC_ID_OBJ                 = 0x005D;

const sal_uInt16 EXC_OBJ_INVALID_ID         = 0x0000;

// sub records
const sal_uInt16 EXC_ID_OBJ_FTEND           = 0x0000;   /// End of OBJ.
const sal_uInt16 EXC_ID_OBJ_FTGMO           = 0x0006;   /// Group marker.
const sal_uInt16 EXC_ID_OBJ_FTCF            = 0x0007;   /// Clipboard format.
const sal_uInt16 EXC_ID_OBJ_FTPIOGRBIT      = 0x0008;   /// Option flags.
const sal_uInt16 EXC_ID_OBJ_FTPICTFMLA      = 0x0009;   /// OLE link formula.
const sal_uInt16 EXC_ID_OBJ_FTCBLS          = 0x000A;   /// Check box/radio button data.
const sal_uInt16 EXC_ID_OBJ_FTSBS           = 0x000C;   /// Scroll bar data.
const sal_uInt16 EXC_ID_OBJ_FTSBSFMLA       = 0x000E;   /// Scroll bar/list box/combo box cell link.
const sal_uInt16 EXC_ID_OBJ_FTLBSDATA       = 0x0013;   /// List box/combo box data.
const sal_uInt16 EXC_ID_OBJ_FTCBLSFMLA      = 0x0014;   /// Check box/radio button cell link.
const sal_uInt16 EXC_ID_OBJ_FTCMO           = 0x0015;   /// Common object settings.
const sal_uInt16 EXC_ID_OBJ_FTUNKNOWN       = 0xFFFF;   /// For internal use only.

// ftCmo: object types
const sal_uInt16 EXC_OBJ_CMO_GROUP          = 0x0000;
const sal_uInt16 EXC_OBJ_CMO_LINE           = 0x0001;
const sal_uInt16 EXC_OBJ_CMO_RECTANGLE      = 0x0002;
const sal_uInt16 EXC_OBJ_CMO_ELLIPSE        = 0x0003;
const sal_uInt16 EXC_OBJ_CMO_ARC            = 0x0004;
const sal_uInt16 EXC_OBJ_CMO_CHART          = 0x0005;
const sal_uInt16 EXC_OBJ_CMO_TEXT           = 0x0006;
const sal_uInt16 EXC_OBJ_CMO_BUTTON         = 0x0007;
const sal_uInt16 EXC_OBJ_CMO_PICTURE        = 0x0008;
const sal_uInt16 EXC_OBJ_CMO_POLYGON        = 0x0009;
const sal_uInt16 EXC_OBJ_CMO_CHECKBOX       = 0x000B;
const sal_uInt16 EXC_OBJ_CMO_OPTIONBUTTON   = 0x000C;
const sal_uInt16 EXC_OBJ_CMO_EDIT           = 0x000D;
const sal_uInt16 EXC_OBJ_CMO_LABEL          = 0x000E;
const sal_uInt16 EXC_OBJ_CMO_DIALOG         = 0x000F;
const sal_uInt16 EXC_OBJ_CMO_SPIN           = 0x0010;
const sal_uInt16 EXC_OBJ_CMO_SCROLLBAR      = 0x0011;
const sal_uInt16 EXC_OBJ_CMO_LISTBOX        = 0x0012;
const sal_uInt16 EXC_OBJ_CMO_GROUPBOX       = 0x0013;
const sal_uInt16 EXC_OBJ_CMO_COMBOBOX       = 0x0014;
const sal_uInt16 EXC_OBJ_CMO_NOTE           = 0x0019;
const sal_uInt16 EXC_OBJ_CMO_DRAWING        = 0x001E;
const sal_uInt16 EXC_OBJ_CMO_UNKNOWN        = 0xFFFF;   /// For internal use only.

// ftPioGrbit: flags
const sal_uInt16 EXC_OBJ_PIO_LINKED         = 0x0002;
const sal_uInt16 EXC_OBJ_PIO_SYMBOL         = 0x0008;

// ftCbls: Check box/radio button data
const sal_uInt16 EXC_OBJ_CBLS_STATEMASK     = 0x0003;
const sal_uInt16 EXC_OBJ_CBLS_STATE_UNCHECK = 0x0000;
const sal_uInt16 EXC_OBJ_CBLS_STATE_CHECK   = 0x0001;
const sal_uInt16 EXC_OBJ_CBLS_STATE_TRI     = 0x0002;
const sal_uInt16 EXC_OBJ_CBLS_3D            = 0x0001;

// ftLbsData: List box data
const sal_uInt16 EXC_OBJ_LBS_SELMASK        = 0x0030;
const sal_uInt16 EXC_OBJ_LBS_SEL_SIMPLE     = 0x0000;   /// Simple selection.
const sal_uInt16 EXC_OBJ_LBS_SEL_MULTI      = 0x0010;   /// Multi selection.
const sal_uInt16 EXC_OBJ_LBS_SEL_EXT        = 0x0020;   /// Extended selection.
const sal_uInt16 EXC_OBJ_LBS_3D             = 0x0008;

/** Value binding mode for cells linked to form controls. */
enum XclCtrlBindMode
{
    xlBindContent,      /// Binds cell to content of control.
    xlBindPosition      /// Binds cell to position in control (i.e. listbox selection index).
};

// (0x01B6) TXO ===============================================================

const sal_uInt16 EXC_ID_TXO                 = 0x01B6;

/** Horizontal alignment flags. */
enum XclTxoHorAlign
{
    xlTxoHAlignLeft                         = 0x01,
    xlTxoHAlignCenter                       = 0x02,
    xlTxoHAlignRight                        = 0x03,
    xlTxoHAlignJustify                      = 0x04,
    xlTxoHAlign_Default                     = xlTxoHAlignLeft
};

/** Vertical alignment flags. */
enum XclTxoVerAlign
{
    xlTxoVAlignTop                          = 0x01,
    xlTxoVAlignCenter                       = 0x02,
    xlTxoVAlignBottom                       = 0x03,
    xlTxoVAlignJustify                      = 0x04,
    xlTxoVAlign_Default                     = xlTxoVAlignTop
};

/** Rotation. */
enum XclTxoRotation
{
    xlTxoNoRot                              = 0x0000,       /// Not rotated.
    xlTxoRotStacked                         = 0x0001,       /// characters stacked.
    xlTxoRot90ccw                           = 0x0002,       /// 90 degr. counterclockwise.
    xlTxoRot90cw                            = 0x0003,       /// 90 degr. clockwise.
    xlTxoRot_Default                        = xlTxoNoRot
};

// ============================================================================

#endif

<|endoftext|>


<commit_before>#include <QtCore/QCoreApplication>
#include <QtCore/QEvent>
#include <QtCore/QPointer>
#include <QtCore/QSocketNotifier>
#include <sys/epoll.h>
#include <errno.h>
#include "eventdispatcher_epoll_p.h"
#include "qt4compat.h"

void EventDispatcherEPollPrivate::registerSocketNotifier(QSocketNotifier* notifier)
{
	int events = 0;
	QSocketNotifier** n = 0;
	int fd = static_cast<int>(notifier->socket());

	epoll_event e;
	e.data.fd = fd;

	HandleData* data;
	HandleHash::Iterator it = this->m_handles.find(fd);

	if (it == this->m_handles.end()) {
		data        = new EventDispatcherEPollPrivate::HandleData();
		data->type  = EventDispatcherEPollPrivate::htSocketNotifier;
		data->sni.r = 0;
		data->sni.w = 0;
		data->sni.x = 0;

		switch (notifier->type()) {
			case QSocketNotifier::Read:      events = EPOLLIN;  n = &data->sni.r; break;
			case QSocketNotifier::Write:     events = EPOLLOUT; n = &data->sni.w; break;
			case QSocketNotifier::Exception: events = EPOLLPRI; n = &data->sni.x; break;
			default:
				Q_UNREACHABLE();
		}

		data->sni.events = events;
		e.events         = events;
		*n               = notifier;

		int res = epoll_ctl(this->m_epoll_fd, EPOLL_CTL_ADD, fd, &e);
		if (Q_UNLIKELY(res != 0)) {
			qErrnoWarning("%s: epoll_ctl() failed", Q_FUNC_INFO);
			delete data;
			return;
		}

		this->m_handles.insert(fd, data);
	}
	else {
		data = it.value();

		Q_ASSERT(data->type == EventDispatcherEPollPrivate::htSocketNotifier);
		if (data->type == EventDispatcherEPollPrivate::htSocketNotifier) {
			switch (notifier->type()) {
				case QSocketNotifier::Read:      events = EPOLLIN;  n = &data->sni.r; break;
				case QSocketNotifier::Write:     events = EPOLLOUT; n = &data->sni.w; break;
				case QSocketNotifier::Exception: events = EPOLLPRI; n = &data->sni.x; break;
				default:
					Q_UNREACHABLE();
			}

			Q_ASSERT(n != 0);
			if (Q_UNLIKELY(*n != 0)) {
				qWarning("%s: cannot add two socket notifiers of the same type for the same descriptor", Q_FUNC_INFO);
				return;
			}

			data->sni.events |= events;
			e.events          = data->sni.events;
			*n                = notifier;

			int res = epoll_ctl(this->m_epoll_fd, EPOLL_CTL_MOD, fd, &e);
			if (Q_UNLIKELY(res != 0)) {
				qErrnoWarning("%s: epoll_ctl() failed", Q_FUNC_INFO);
				return;
			}
		}
		else {
			Q_UNREACHABLE();
		}
	}

	this->m_notifiers.insert(notifier, data);
}

void EventDispatcherEPollPrivate::unregisterSocketNotifier(QSocketNotifier* notifier)
{
	SocketNotifierHash::Iterator it = this->m_notifiers.find(notifier);
	if (Q_LIKELY(it != this->m_notifiers.end())) {
		HandleData* info = it.value();
		int fd           = static_cast<int>(notifier->socket());

		this->m_notifiers.erase(it); // Hash is not rehashed

		HandleHash::Iterator hi = this->m_handles.find(fd);
		Q_ASSERT(hi != this->m_handles.end());

		struct epoll_event e;
		e.data.fd = fd;

		if (info->sni.r == notifier) {
			info->sni.events &= ~EPOLLIN;
			info->sni.r       = 0;
		}
		else if (info->sni.w == notifier) {
			info->sni.events &= ~EPOLLOUT;
			info->sni.w       = 0;
		}
		else if (info->sni.x == notifier) {
			info->sni.events &= ~EPOLLPRI;
			info->sni.x       = 0;
		}
		else {
			qCritical("%s: cannot find socket notifier %p", Q_FUNC_INFO, notifier);
		}

		e.events = info->sni.events;

		int res;

		if (info->sni.r || info->sni.w || info->sni.x) {
			res = epoll_ctl(this->m_epoll_fd, EPOLL_CTL_MOD, fd, &e);
		}
		else {
			res = epoll_ctl(this->m_epoll_fd, EPOLL_CTL_DEL, fd, &e);
			if (Q_UNLIKELY(res != 0 && EBADF == errno)) {
				res = 0;
			}

			this->m_handles.erase(hi);
			delete info;
		}

		if (Q_UNLIKELY(res != 0)) {
			qErrnoWarning("%s: epoll_ctl() failed", Q_FUNC_INFO);
		}
	}
}

void EventDispatcherEPollPrivate::socket_notifier_callback(SocketNotifierInfo* n, int events)
{
	Q_ASSERT(n != 0);
	QEvent e(QEvent::SockAct);

	QPointer<QSocketNotifier> r(n->r);
	QPointer<QSocketNotifier> w(n->w);
	QPointer<QSocketNotifier> x(n->x);

	if (r && (events & EPOLLIN)) {
		QCoreApplication::sendEvent(r, &e);
	}

	if (w && (events & EPOLLOUT)) {
		QCoreApplication::sendEvent(w, &e);
	}

	if (x && (events & EPOLLPRI)) {
		QCoreApplication::sendEvent(x, &e);
	}
}

void EventDispatcherEPollPrivate::disableSocketNotifiers(bool disable)
{
	epoll_event e;

	SocketNotifierHash::ConstIterator it = this->m_notifiers.constBegin();
	while (it != this->m_notifiers.constEnd()) {
		QSocketNotifier* notifier = it.key();
		HandleData* info          = it.value();
		int fd                    = static_cast<int>(notifier->socket());

		e.events  = disable ? 0 : info->sni.events;
		e.data.fd = fd;
		int res = epoll_ctl(this->m_epoll_fd, EPOLL_CTL_MOD, fd, &e);
		if (Q_UNLIKELY(res != 0)) {
			qErrnoWarning("%s: epoll_ctl() failed", Q_FUNC_INFO);
		}

		++it;
	}
}
<commit_msg>Inability to find the sockedt notifier is a fatal (internal) error<commit_after>#include <QtCore/QCoreApplication>
#include <QtCore/QEvent>
#include <QtCore/QPointer>
#include <QtCore/QSocketNotifier>
#include <sys/epoll.h>
#include <errno.h>
#include "eventdispatcher_epoll_p.h"
#include "qt4compat.h"

void EventDispatcherEPollPrivate::registerSocketNotifier(QSocketNotifier* notifier)
{
	int events = 0;
	QSocketNotifier** n = 0;
	int fd = static_cast<int>(notifier->socket());

	epoll_event e;
	e.data.fd = fd;

	HandleData* data;
	HandleHash::Iterator it = this->m_handles.find(fd);

	if (it == this->m_handles.end()) {
		data        = new EventDispatcherEPollPrivate::HandleData();
		data->type  = EventDispatcherEPollPrivate::htSocketNotifier;
		data->sni.r = 0;
		data->sni.w = 0;
		data->sni.x = 0;

		switch (notifier->type()) {
			case QSocketNotifier::Read:      events = EPOLLIN;  n = &data->sni.r; break;
			case QSocketNotifier::Write:     events = EPOLLOUT; n = &data->sni.w; break;
			case QSocketNotifier::Exception: events = EPOLLPRI; n = &data->sni.x; break;
			default:
				Q_UNREACHABLE();
		}

		data->sni.events = events;
		e.events         = events;
		*n               = notifier;

		int res = epoll_ctl(this->m_epoll_fd, EPOLL_CTL_ADD, fd, &e);
		if (Q_UNLIKELY(res != 0)) {
			qErrnoWarning("%s: epoll_ctl() failed", Q_FUNC_INFO);
			delete data;
			return;
		}

		this->m_handles.insert(fd, data);
	}
	else {
		data = it.value();

		Q_ASSERT(data->type == EventDispatcherEPollPrivate::htSocketNotifier);
		if (data->type == EventDispatcherEPollPrivate::htSocketNotifier) {
			switch (notifier->type()) {
				case QSocketNotifier::Read:      events = EPOLLIN;  n = &data->sni.r; break;
				case QSocketNotifier::Write:     events = EPOLLOUT; n = &data->sni.w; break;
				case QSocketNotifier::Exception: events = EPOLLPRI; n = &data->sni.x; break;
				default:
					Q_UNREACHABLE();
			}

			Q_ASSERT(n != 0);
			if (Q_UNLIKELY(*n != 0)) {
				qWarning("%s: cannot add two socket notifiers of the same type for the same descriptor", Q_FUNC_INFO);
				return;
			}

			data->sni.events |= events;
			e.events          = data->sni.events;
			*n                = notifier;

			int res = epoll_ctl(this->m_epoll_fd, EPOLL_CTL_MOD, fd, &e);
			if (Q_UNLIKELY(res != 0)) {
				qErrnoWarning("%s: epoll_ctl() failed", Q_FUNC_INFO);
				return;
			}
		}
		else {
			Q_UNREACHABLE();
		}
	}

	this->m_notifiers.insert(notifier, data);
}

void EventDispatcherEPollPrivate::unregisterSocketNotifier(QSocketNotifier* notifier)
{
	SocketNotifierHash::Iterator it = this->m_notifiers.find(notifier);
	if (Q_LIKELY(it != this->m_notifiers.end())) {
		HandleData* info = it.value();
		int fd           = static_cast<int>(notifier->socket());

		this->m_notifiers.erase(it); // Hash is not rehashed

		HandleHash::Iterator hi = this->m_handles.find(fd);
		Q_ASSERT(hi != this->m_handles.end());

		struct epoll_event e;
		e.data.fd = fd;

		if (info->sni.r == notifier) {
			info->sni.events &= ~EPOLLIN;
			info->sni.r       = 0;
		}
		else if (info->sni.w == notifier) {
			info->sni.events &= ~EPOLLOUT;
			info->sni.w       = 0;
		}
		else if (info->sni.x == notifier) {
			info->sni.events &= ~EPOLLPRI;
			info->sni.x       = 0;
		}
		else {
			qFatal("%s: internal error: cannot find socket notifier", Q_FUNC_INFO);
		}

		e.events = info->sni.events;

		int res;

		if (info->sni.r || info->sni.w || info->sni.x) {
			res = epoll_ctl(this->m_epoll_fd, EPOLL_CTL_MOD, fd, &e);
		}
		else {
			res = epoll_ctl(this->m_epoll_fd, EPOLL_CTL_DEL, fd, &e);
			if (Q_UNLIKELY(res != 0 && EBADF == errno)) {
				res = 0;
			}

			this->m_handles.erase(hi);
			delete info;
		}

		if (Q_UNLIKELY(res != 0)) {
			qErrnoWarning("%s: epoll_ctl() failed", Q_FUNC_INFO);
		}
	}
}

void EventDispatcherEPollPrivate::socket_notifier_callback(SocketNotifierInfo* n, int events)
{
	Q_ASSERT(n != 0);
	QEvent e(QEvent::SockAct);

	QPointer<QSocketNotifier> r(n->r);
	QPointer<QSocketNotifier> w(n->w);
	QPointer<QSocketNotifier> x(n->x);

	if (r && (events & EPOLLIN)) {
		QCoreApplication::sendEvent(r, &e);
	}

	if (w && (events & EPOLLOUT)) {
		QCoreApplication::sendEvent(w, &e);
	}

	if (x && (events & EPOLLPRI)) {
		QCoreApplication::sendEvent(x, &e);
	}
}

void EventDispatcherEPollPrivate::disableSocketNotifiers(bool disable)
{
	epoll_event e;

	SocketNotifierHash::ConstIterator it = this->m_notifiers.constBegin();
	while (it != this->m_notifiers.constEnd()) {
		QSocketNotifier* notifier = it.key();
		HandleData* info          = it.value();
		int fd                    = static_cast<int>(notifier->socket());

		e.events  = disable ? 0 : info->sni.events;
		e.data.fd = fd;
		int res = epoll_ctl(this->m_epoll_fd, EPOLL_CTL_MOD, fd, &e);
		if (Q_UNLIKELY(res != 0)) {
			qErrnoWarning("%s: epoll_ctl() failed", Q_FUNC_INFO);
		}

		++it;
	}
}
<|endoftext|>


<commit_before>///
/// @file  Li.cpp
///
/// Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <limits>

using namespace std;

namespace {

/// This calculates the logarithmic integral using Ramanujan's fast
/// converging formula (accurate up to 10^17).
// @see http://mathworld.wolfram.com/LogarithmicIntegral.html (15)
///
long double li(long double x)
{
  long double GAMMA = 0.57721566490153286061;
  long double logx = log(x);
  long double sum = 0;
  long double inner_sum = 0;
  long double factorial = 1;
  long double p = -1;
  long double power2 = 1;

  int k = 0;
  int terms = static_cast<int>(logx * 2) + 10;

  for (int n = 1; n < terms; n++)
  {
    factorial *= n;
    p *= -logx;
    long double q = factorial * power2;
    power2 *= 2;
    for (; k <= (n - 1) / 2; k++)
      inner_sum += 1.0 / (2 * k + 1);
    sum += (p / q) * inner_sum;
  }

  return GAMMA + log(logx) + sqrt(x) * sum;
}

} // namespace

namespace primecount {

/// This calculates the offset logarithmic integral which is a very
/// accurate approximation of the number of primes below x.
/// @post Li(x) > pi(x) for 24 <= x <= ~ 10^316
///
int64_t Li(int64_t x)
{
  if (x < 2)
    return 0;

  long double n = static_cast<long double>(x);
  return static_cast<int64_t>(
      li(n) - /* li(2) = */ 1.04516);
}

/// This calculates the inverse logarithmic integral Li^-1(x) which is
/// a very accurate approximation of the nth prime.
/// @post Li_inverse(x) < nth_prime(x) for 7 <= x <= ~ 10^316
///
int64_t Li_inverse(int64_t x)
{
  if (x < 1)
    return 0;

  double n = static_cast<double>(x);
  double logn = log(n);
  int64_t first = static_cast<int64_t>(n * logn);
  int64_t last  = static_cast<int64_t>(n * logn * 2 + 2);
  if (last <= first)
    last = std::numeric_limits<int64_t>::max();

  // find Li^-1(x) using binary search
  while (first < last)
  {
    int64_t mid = first + (last - first) / 2;

    if (Li(mid) < x)
      first = mid + 1;
    else
      last = mid;
  }

  return first;
}

} // namespace primecount
<commit_msg>Silence icpc warning<commit_after>///
/// @file  Li.cpp
///
/// Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount.h>

#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <limits>

using namespace std;

namespace {

/// This calculates the logarithmic integral using Ramanujan's fast
/// converging formula (accurate up to 10^17).
// @see http://mathworld.wolfram.com/LogarithmicIntegral.html (15)
///
long double li(long double x)
{
  long double GAMMA = 0.57721566490153286061;
  long double logx = log(x);
  long double sum = 0;
  long double inner_sum = 0;
  long double factorial = 1;
  long double p = -1;
  long double power2 = 1;

  int k = 0;
  int terms = static_cast<int>(logx * 2) + 10;

  for (int n = 1; n < terms; n++)
  {
    factorial *= n;
    p *= -logx;
    long double q = factorial * power2;
    power2 *= 2;
    for (; k <= (n - 1) / 2; k++)
      inner_sum += 1.0 / (2 * k + 1);
    sum += (p / q) * inner_sum;
  }

  return GAMMA + log(logx) + sqrt(x) * sum;
}

} // namespace

namespace primecount {

/// This calculates the offset logarithmic integral which is a very
/// accurate approximation of the number of primes below x.
/// @post Li(x) > pi(x) for 24 <= x <= ~ 10^316
///
int64_t Li(int64_t x)
{
  if (x < 2)
    return 0;

  long double n = static_cast<long double>(x);
  return static_cast<int64_t>(
      li(n) - /* li(2) = */ 1.04516);
}

/// This calculates the inverse logarithmic integral Li^-1(x) which is
/// a very accurate approximation of the nth prime.
/// @post Li_inverse(x) < nth_prime(x) for 7 <= x <= ~ 10^316
///
int64_t Li_inverse(int64_t x)
{
  if (x < 1)
    return 0;

  double n = static_cast<double>(x);
  double logn = log(n);
  int64_t first = static_cast<int64_t>(n * logn);
  int64_t last  = static_cast<int64_t>(n * logn * 2 + 2);
  if (last <= first)
    last = std::numeric_limits<int64_t>::max();

  // find Li^-1(x) using binary search
  while (first < last)
  {
    int64_t mid = first + (last - first) / 2;

    if (Li(mid) < x)
      first = mid + 1;
    else
      last = mid;
  }

  return first;
}

} // namespace primecount
<|endoftext|>


<commit_before>/*
 *  FullCoreEnvironmentTest.cpp
 *  MWorksCore
 *
 *  Created by David Cox on 9/19/06.
 *  Copyright 2006 __MyCompanyName__. All rights reserved.
 *
 */

#include "FullCoreEnvironmentTest.h"
#include <sstream>
#include "MWorksCore/CorebuilderForeman.h"
#include "MWorksCore/TestBedCoreBuilder.h"
#include "MWorksCore/Experiment.h"
#include "MWorksCore/EventBuffer.h"
#include "MWorksCore/PluginServices.h"
#include "MWorksCore/StandardVariables.h"
#include "MWorksCore/DataFileManager.h"
#include "MWorksCore/OpenALContextManager.h"

BEGIN_NAMESPACE_MW

void FullCoreEnvironmentTestFixture::setUp(){
	builder = new TestBedCoreBuilder();
	CoreBuilderForeman::constructCoreStandardOrder(builder);
}

void FullCoreEnvironmentTestFixture::tearDown(){
	// this is actually a touch tricky to do without leaking, and it
	// probably should be handlable by the builder in some way
	/*if(GlobalCurrentExperiment){
		delete GlobalCurrentExperiment;
		GlobalCurrentExperiment = 0;
	}*/

	/*if(global_variable_registry){
		delete global_variable_registry;
		global_variable_registry = 0;
	}*/

  ComponentRegistry::detachSharedRegistryPtr();

	if(GlobalDataFileManager) {
	  delete GlobalDataFileManager;
	  GlobalDataFileManager = 0;
	}

	OpenALContextManager::destroy();

	if(registries_are_initialized) {
		registries_are_initialized = false;
	}

	StateSystem::destroy();
	Scheduler::destroy();
	Clock::destroy();
}

END_NAMESPACE_MW
<commit_msg>Call stopClock in FullCoreEnvironmentTestFixture::tearDown<commit_after>/*
 *  FullCoreEnvironmentTest.cpp
 *  MWorksCore
 *
 *  Created by David Cox on 9/19/06.
 *  Copyright 2006 __MyCompanyName__. All rights reserved.
 *
 */

#include "FullCoreEnvironmentTest.h"
#include <sstream>
#include "MWorksCore/CorebuilderForeman.h"
#include "MWorksCore/TestBedCoreBuilder.h"
#include "MWorksCore/Experiment.h"
#include "MWorksCore/EventBuffer.h"
#include "MWorksCore/PluginServices.h"
#include "MWorksCore/StandardVariables.h"
#include "MWorksCore/DataFileManager.h"
#include "MWorksCore/OpenALContextManager.h"

BEGIN_NAMESPACE_MW

void FullCoreEnvironmentTestFixture::setUp(){
	builder = new TestBedCoreBuilder();
	CoreBuilderForeman::constructCoreStandardOrder(builder);
}

void FullCoreEnvironmentTestFixture::tearDown(){
	// this is actually a touch tricky to do without leaking, and it
	// probably should be handlable by the builder in some way
	/*if(GlobalCurrentExperiment){
		delete GlobalCurrentExperiment;
		GlobalCurrentExperiment = 0;
	}*/

	/*if(global_variable_registry){
		delete global_variable_registry;
		global_variable_registry = 0;
	}*/

  ComponentRegistry::detachSharedRegistryPtr();

	if(GlobalDataFileManager) {
	  delete GlobalDataFileManager;
	  GlobalDataFileManager = 0;
	}

	OpenALContextManager::destroy();

	if(registries_are_initialized) {
		registries_are_initialized = false;
	}

	StateSystem::destroy();
	Scheduler::destroy();
    Clock::instance()->stopClock();
	Clock::destroy();
}

END_NAMESPACE_MW
<|endoftext|>