<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tbxctl.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-26 16:52:41 $
 *
 *  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 _BASIDE_TBXCTL_HXX
#define _BASIDE_TBXCTL_HXX

#ifndef _SFXTBXCTRL_HXX //autogen
#include <sfx2/tbxctrl.hxx>
#endif

#ifndef _COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_
#include <com/sun/star/frame/XLayoutManager.hpp>
#endif

/*
#ifdef _BASIDE_POPUPWINDOWTBX

// class PopupWindowTbx --------------------------------------------------

class PopupWindowTbx : public SfxPopupWindow
{
private:
    SfxToolBoxManager   aTbx;
    Link                aSelectLink;

    DECL_LINK( SelectHdl, void* );

public:
    PopupWindowTbx( USHORT nId, WindowAlign eAlign,
                    ResId aRIdWin, ResId aRIdTbx, SfxBindings& rBind );
    ~PopupWindowTbx();

    void                    StartSelection()
                                { aTbx.GetToolBox().StartSelection(); }
    void                    Update();

    virtual SfxPopupWindow* Clone() const;
    virtual void            PopupModeEnd();
};
#endif
*/
//-------------------
// class TbxControls
//-------------------
class TbxControls : public SfxToolBoxControl
{
private:

    struct StateChangedInfo
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager > xLayoutManager;
        bool bDisabled;
    };

    USHORT                  nLastSlot;

protected:
    virtual void            StateChanged( USHORT nSID, SfxItemState eState,
                                          const SfxPoolItem* pState );
public:
    SFX_DECL_TOOLBOX_CONTROL();

    TbxControls(USHORT nSlotId, USHORT nId, ToolBox& rTbx );
    ~TbxControls() {}

    virtual SfxPopupWindowType  GetPopupWindowType() const;
    virtual SfxPopupWindow*     CreatePopupWindow();

    using                       SfxToolBoxControl::Select;
    void                        Select( USHORT nModifier );
};

#endif // _BASIDE_TBXCTL_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.9.62); FILE MERGED 2008/04/01 15:00:39 thb 1.9.62.3: #i85898# Stripping all external header guards 2008/04/01 10:47:46 thb 1.9.62.2: #i85898# Stripping all external header guards 2008/03/28 16:04:50 rt 1.9.62.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: tbxctl.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 _BASIDE_TBXCTL_HXX
#define _BASIDE_TBXCTL_HXX

#include <sfx2/tbxctrl.hxx>
#include <com/sun/star/frame/XLayoutManager.hpp>

/*
#ifdef _BASIDE_POPUPWINDOWTBX

// class PopupWindowTbx --------------------------------------------------

class PopupWindowTbx : public SfxPopupWindow
{
private:
    SfxToolBoxManager   aTbx;
    Link                aSelectLink;

    DECL_LINK( SelectHdl, void* );

public:
    PopupWindowTbx( USHORT nId, WindowAlign eAlign,
                    ResId aRIdWin, ResId aRIdTbx, SfxBindings& rBind );
    ~PopupWindowTbx();

    void                    StartSelection()
                                { aTbx.GetToolBox().StartSelection(); }
    void                    Update();

    virtual SfxPopupWindow* Clone() const;
    virtual void            PopupModeEnd();
};
#endif
*/
//-------------------
// class TbxControls
//-------------------
class TbxControls : public SfxToolBoxControl
{
private:

    struct StateChangedInfo
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager > xLayoutManager;
        bool bDisabled;
    };

    USHORT                  nLastSlot;

protected:
    virtual void            StateChanged( USHORT nSID, SfxItemState eState,
                                          const SfxPoolItem* pState );
public:
    SFX_DECL_TOOLBOX_CONTROL();

    TbxControls(USHORT nSlotId, USHORT nId, ToolBox& rTbx );
    ~TbxControls() {}

    virtual SfxPopupWindowType  GetPopupWindowType() const;
    virtual SfxPopupWindow*     CreatePopupWindow();

    using                       SfxToolBoxControl::Select;
    void                        Select( USHORT nModifier );
};

#endif // _BASIDE_TBXCTL_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 "dlgedpage.hxx"
#include "dlged.hxx"
#include "dlgedmod.hxx"
#include "dlgedobj.hxx"

namespace basctl
{

TYPEINIT1( DlgEdPage, SdrPage );

//----------------------------------------------------------------------------

DlgEdPage::DlgEdPage( DlgEdModel& rModel, bool bMasterPage )
    :SdrPage( rModel, bMasterPage )
{
}

//----------------------------------------------------------------------------

DlgEdPage::~DlgEdPage()
{
    Clear();
}

//----------------------------------------------------------------------------

SdrPage* DlgEdPage::Clone() const
{
    return new DlgEdPage( *this );
}

//----------------------------------------------------------------------------

SdrObject* DlgEdPage::SetObjectOrdNum(sal_uLong nOldObjNum, sal_uLong nNewObjNum)
{
    SdrObject* pObj = SdrPage::SetObjectOrdNum( nOldObjNum, nNewObjNum );

    DlgEdHint aHint( DlgEdHint::OBJORDERCHANGED );
    if ( pDlgEdForm )
        pDlgEdForm->GetDlgEditor().Broadcast( aHint );

    return pObj;
}

//----------------------------------------------------------------------------

} // namespace basctl

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>CID#738562 uninitialized member<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 "dlgedpage.hxx"
#include "dlged.hxx"
#include "dlgedmod.hxx"
#include "dlgedobj.hxx"

namespace basctl
{

TYPEINIT1( DlgEdPage, SdrPage );

//----------------------------------------------------------------------------

DlgEdPage::DlgEdPage(DlgEdModel& rModel, bool bMasterPage)
    : SdrPage(rModel, bMasterPage)
    , pDlgEdForm(0)
{
}

//----------------------------------------------------------------------------

DlgEdPage::~DlgEdPage()
{
    Clear();
}

//----------------------------------------------------------------------------

SdrPage* DlgEdPage::Clone() const
{
    return new DlgEdPage( *this );
}

//----------------------------------------------------------------------------

SdrObject* DlgEdPage::SetObjectOrdNum(sal_uLong nOldObjNum, sal_uLong nNewObjNum)
{
    SdrObject* pObj = SdrPage::SetObjectOrdNum( nOldObjNum, nNewObjNum );

    DlgEdHint aHint( DlgEdHint::OBJORDERCHANGED );
    if ( pDlgEdForm )
        pDlgEdForm->GetDlgEditor().Broadcast( aHint );

    return pObj;
}

//----------------------------------------------------------------------------

} // namespace basctl

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


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tcommuni.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:33:40 $
 *
 *  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 _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _TOOLS_TIME_HXX //autogen
#include <tools/time.hxx>
#endif
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#include <vcl/timer.hxx>

#ifndef _BASIC_TTRESHLP_HXX
#include <basic/ttstrhlp.hxx>
#endif

#include "rcontrol.hxx"
#include "tcommuni.hxx"
#include <basic/testtool.hxx>

CommunicationManagerClientViaSocketTT::CommunicationManagerClientViaSocketTT()
: CommunicationManagerClientViaSocket( TRUE )
, aAppPath()
, aAppParams()
, pProcess( NULL )
{
}

BOOL CommunicationManagerClientViaSocketTT::StartCommunication()
{
    bApplicationStarted = FALSE;
    return CommunicationManagerClientViaSocket::StartCommunication( ByteString( GetHostConfig(), RTL_TEXTENCODING_UTF8 ), GetTTPortConfig() );
}

BOOL CommunicationManagerClientViaSocketTT::StartCommunication( String aApp, String aParams, Environment *pChildEnv )
{
    aAppPath = aApp;
    aAppParams = aParams;
    aAppEnv = (*pChildEnv);
    return StartCommunication();
}

BOOL CommunicationManagerClientViaSocketTT::RetryConnect()
{
    if ( !bApplicationStarted )
    {
        // Die App ist wohl nicht da. Starten wir sie mal.
        if ( aAppPath.Len() )
        {
            delete pProcess;

            pProcess = new Process();
            pProcess->SetImage( aAppPath, aAppParams, &aAppEnv );

            BOOL bSucc = pProcess->Start();
            bApplicationStarted = TRUE;

            if ( bSucc )
            {
                aFirstRetryCall = Time() + Time( 0, 1 );    // Max eine Minute Zeit
                for ( int i = 10 ; i-- ; )
                    GetpApp()->Reschedule();
            }
            return bSucc;
        }
        return FALSE;
    }
    else
    {
        if ( aFirstRetryCall > Time() )
        {
            Timer aWait;
            aWait.SetTimeout( 500 );         // Max 500 mSec
            aWait.Start();
            while ( aWait.IsActive() )
                GetpApp()->Yield();
            return TRUE;
        }
        else
            return FALSE;
    }
}

BOOL CommunicationManagerClientViaSocketTT::KillApplication()
{
    if ( pProcess )
        return pProcess->Terminate();
    return TRUE;
}

#define GETSET(aVar, KeyName, Dafault)                 \
    aVar = aConf.ReadKey(KeyName,"No Entry");          \
    if ( aVar.CompareTo("No Entry") == COMPARE_EQUAL ) \
    {                                                  \
        aVar = ByteString(Dafault);                    \
        aConf.WriteKey(KeyName, aVar);                 \
    }

String GetHostConfig()
{
    String aHostToTalk;

    for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )
    {
        if ( Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("-host=") == COMPARE_EQUAL
#ifndef UNX
          || Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("/host=") == COMPARE_EQUAL
#endif
          )
            return Application::GetCommandLineParam( i ).Copy(6);
    }

    ByteString abHostToTalk;
    Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));
    aConf.SetGroup("Communication");

    GETSET( abHostToTalk, "Host", DEFAULT_HOST );
    return UniString( abHostToTalk, RTL_TEXTENCODING_UTF8 );
}

ULONG GetTTPortConfig()
{
    String aPortToTalk;

    for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )
    {
        if ( Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("-port=") == COMPARE_EQUAL
#ifndef UNX
          || Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("/port=") == COMPARE_EQUAL
#endif
          )
        {
            aPortToTalk = Application::GetCommandLineParam( i ).Copy(6);
            return (ULONG)aPortToTalk.ToInt64();
        }
    }

    ByteString abPortToTalk;
    Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));
    aConf.SetGroup("Communication");

    GETSET( abPortToTalk, "TTPort", ByteString::CreateFromInt32( TESTTOOL_DEFAULT_PORT ) );
    return (ULONG)abPortToTalk.ToInt64();
}

ULONG GetUnoPortConfig()
{
    String aPortToTalk;

    for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )
    {
        if ( Application::GetCommandLineParam( i ).Copy(0,9).CompareIgnoreCaseToAscii("-unoport=") == COMPARE_EQUAL
#ifndef UNX
          || Application::GetCommandLineParam( i ).Copy(0,9).CompareIgnoreCaseToAscii("/unoport=") == COMPARE_EQUAL
#endif
          )
        {
            aPortToTalk = Application::GetCommandLineParam( i ).Copy(6);
            return (ULONG)aPortToTalk.ToInt64();
        }
    }

    ByteString abPortToTalk;
    Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));
    aConf.SetGroup("Communication");

    GETSET( abPortToTalk, "UnoPort", ByteString::CreateFromInt32( UNO_DEFAULT_PORT ) );
    return (ULONG)abPortToTalk.ToInt64();
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.8.56); FILE MERGED 2006/09/01 17:16:08 kaib 1.8.56.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tcommuni.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 00:39:39 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_automation.hxx"

#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _TOOLS_TIME_HXX //autogen
#include <tools/time.hxx>
#endif
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#include <vcl/timer.hxx>

#ifndef _BASIC_TTRESHLP_HXX
#include <basic/ttstrhlp.hxx>
#endif

#include "rcontrol.hxx"
#include "tcommuni.hxx"
#include <basic/testtool.hxx>

CommunicationManagerClientViaSocketTT::CommunicationManagerClientViaSocketTT()
: CommunicationManagerClientViaSocket( TRUE )
, aAppPath()
, aAppParams()
, pProcess( NULL )
{
}

BOOL CommunicationManagerClientViaSocketTT::StartCommunication()
{
    bApplicationStarted = FALSE;
    return CommunicationManagerClientViaSocket::StartCommunication( ByteString( GetHostConfig(), RTL_TEXTENCODING_UTF8 ), GetTTPortConfig() );
}

BOOL CommunicationManagerClientViaSocketTT::StartCommunication( String aApp, String aParams, Environment *pChildEnv )
{
    aAppPath = aApp;
    aAppParams = aParams;
    aAppEnv = (*pChildEnv);
    return StartCommunication();
}

BOOL CommunicationManagerClientViaSocketTT::RetryConnect()
{
    if ( !bApplicationStarted )
    {
        // Die App ist wohl nicht da. Starten wir sie mal.
        if ( aAppPath.Len() )
        {
            delete pProcess;

            pProcess = new Process();
            pProcess->SetImage( aAppPath, aAppParams, &aAppEnv );

            BOOL bSucc = pProcess->Start();
            bApplicationStarted = TRUE;

            if ( bSucc )
            {
                aFirstRetryCall = Time() + Time( 0, 1 );    // Max eine Minute Zeit
                for ( int i = 10 ; i-- ; )
                    GetpApp()->Reschedule();
            }
            return bSucc;
        }
        return FALSE;
    }
    else
    {
        if ( aFirstRetryCall > Time() )
        {
            Timer aWait;
            aWait.SetTimeout( 500 );         // Max 500 mSec
            aWait.Start();
            while ( aWait.IsActive() )
                GetpApp()->Yield();
            return TRUE;
        }
        else
            return FALSE;
    }
}

BOOL CommunicationManagerClientViaSocketTT::KillApplication()
{
    if ( pProcess )
        return pProcess->Terminate();
    return TRUE;
}

#define GETSET(aVar, KeyName, Dafault)                 \
    aVar = aConf.ReadKey(KeyName,"No Entry");          \
    if ( aVar.CompareTo("No Entry") == COMPARE_EQUAL ) \
    {                                                  \
        aVar = ByteString(Dafault);                    \
        aConf.WriteKey(KeyName, aVar);                 \
    }

String GetHostConfig()
{
    String aHostToTalk;

    for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )
    {
        if ( Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("-host=") == COMPARE_EQUAL
#ifndef UNX
          || Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("/host=") == COMPARE_EQUAL
#endif
          )
            return Application::GetCommandLineParam( i ).Copy(6);
    }

    ByteString abHostToTalk;
    Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));
    aConf.SetGroup("Communication");

    GETSET( abHostToTalk, "Host", DEFAULT_HOST );
    return UniString( abHostToTalk, RTL_TEXTENCODING_UTF8 );
}

ULONG GetTTPortConfig()
{
    String aPortToTalk;

    for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )
    {
        if ( Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("-port=") == COMPARE_EQUAL
#ifndef UNX
          || Application::GetCommandLineParam( i ).Copy(0,6).CompareIgnoreCaseToAscii("/port=") == COMPARE_EQUAL
#endif
          )
        {
            aPortToTalk = Application::GetCommandLineParam( i ).Copy(6);
            return (ULONG)aPortToTalk.ToInt64();
        }
    }

    ByteString abPortToTalk;
    Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));
    aConf.SetGroup("Communication");

    GETSET( abPortToTalk, "TTPort", ByteString::CreateFromInt32( TESTTOOL_DEFAULT_PORT ) );
    return (ULONG)abPortToTalk.ToInt64();
}

ULONG GetUnoPortConfig()
{
    String aPortToTalk;

    for ( int i = 0 ; i < Application::GetCommandLineParamCount() ; i++ )
    {
        if ( Application::GetCommandLineParam( i ).Copy(0,9).CompareIgnoreCaseToAscii("-unoport=") == COMPARE_EQUAL
#ifndef UNX
          || Application::GetCommandLineParam( i ).Copy(0,9).CompareIgnoreCaseToAscii("/unoport=") == COMPARE_EQUAL
#endif
          )
        {
            aPortToTalk = Application::GetCommandLineParam( i ).Copy(6);
            return (ULONG)aPortToTalk.ToInt64();
        }
    }

    ByteString abPortToTalk;
    Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));
    aConf.SetGroup("Communication");

    GETSET( abPortToTalk, "UnoPort", ByteString::CreateFromInt32( UNO_DEFAULT_PORT ) );
    return (ULONG)abPortToTalk.ToInt64();
}
<|endoftext|>


<commit_before>// Copyright 2013 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/child/runtime_features.h"

#include <vector>

#include "base/command_line.h"
#include "base/metrics/field_trial.h"
#include "base/strings/string_split.h"
#include "components/scheduler/common/scheduler_switches.h"
#include "content/common/content_switches_internal.h"
#include "content/public/common/content_switches.h"
#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
#include "ui/gl/gl_switches.h"
#include "ui/native_theme/native_theme_switches.h"

#if defined(OS_ANDROID)
#include <cpu-features.h>
#include "base/android/build_info.h"
#include "base/metrics/field_trial.h"
#include "media/base/android/media_codec_bridge.h"
#elif defined(OS_WIN)
#include "base/win/windows_version.h"
#endif

using blink::WebRuntimeFeatures;

namespace content {

static void SetRuntimeFeatureDefaultsForPlatform() {
  // Enable non-standard "apple-touch-icon" and "apple-touch-icon-precomposed".
  WebRuntimeFeatures::enableTouchIconLoading(true);

#if defined(OS_ANDROID)
  // MSE/EME implementation needs Android MediaCodec API.
  if (!media::MediaCodecBridge::IsAvailable()) {
    WebRuntimeFeatures::enableMediaSource(false);
    WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);
    WebRuntimeFeatures::enableEncryptedMedia(false);
  }
  // WebAudio is enabled by default but only when the MediaCodec API
  // is available.
  AndroidCpuFamily cpu_family = android_getCpuFamily();
  WebRuntimeFeatures::enableWebAudio(
      media::MediaCodecBridge::IsAvailable() &&
      ((cpu_family == ANDROID_CPU_FAMILY_ARM) ||
       (cpu_family == ANDROID_CPU_FAMILY_ARM64) ||
       (cpu_family == ANDROID_CPU_FAMILY_X86) ||
       (cpu_family == ANDROID_CPU_FAMILY_MIPS)));

  // Android does not have support for PagePopup
  WebRuntimeFeatures::enablePagePopup(false);
  // Android does not yet support SharedWorker. crbug.com/154571
  WebRuntimeFeatures::enableSharedWorker(false);
  // Android does not yet support NavigatorContentUtils.
  WebRuntimeFeatures::enableNavigatorContentUtils(false);
  WebRuntimeFeatures::enableOrientationEvent(true);
  WebRuntimeFeatures::enableFastMobileScrolling(true);
  WebRuntimeFeatures::enableMediaCapture(true);
  WebRuntimeFeatures::enableCompositedSelectionUpdate(true);
  // Android won't be able to reliably support non-persistent notifications, the
  // intended behavior for which is in flux by itself.
  WebRuntimeFeatures::enableNotificationConstructor(false);
#else
  WebRuntimeFeatures::enableNavigatorContentUtils(true);
#endif  // defined(OS_ANDROID)

#if !(defined OS_ANDROID || defined OS_CHROMEOS || defined OS_IOS)
    // Only Android, ChromeOS, and IOS support NetInfo right now.
    WebRuntimeFeatures::enableNetworkInformation(false);
#endif

#if defined(OS_WIN)
  // Screen Orientation API is currently broken on Windows 8 Metro mode and
  // until we can find how to disable it only for Blink instances running in a
  // renderer process in Metro, we need to disable the API altogether for Win8.
  // See http://crbug.com/400846
  if (base::win::OSInfo::GetInstance()->version() >= base::win::VERSION_WIN8)
    WebRuntimeFeatures::enableScreenOrientation(false);
#endif // OS_WIN
}

void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
    const base::CommandLine& command_line) {
  if (command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures))
    WebRuntimeFeatures::enableExperimentalFeatures(true);

  if (command_line.HasSwitch(switches::kEnableWebBluetooth))
    WebRuntimeFeatures::enableWebBluetooth(true);

  SetRuntimeFeatureDefaultsForPlatform();

  if (command_line.HasSwitch(switches::kDisableDatabases))
    WebRuntimeFeatures::enableDatabase(false);

  if (command_line.HasSwitch(scheduler::switches::kDisableBlinkScheduler))
    WebRuntimeFeatures::enableBlinkScheduler(false);

  if (command_line.HasSwitch(switches::kDisableMediaSource))
    WebRuntimeFeatures::enableMediaSource(false);

  if (command_line.HasSwitch(switches::kDisableNotifications)) {
    WebRuntimeFeatures::enableNotifications(false);

    // Chrome's Push Messaging implementation relies on Web Notifications.
    WebRuntimeFeatures::enablePushMessaging(false);
  }

  if (command_line.HasSwitch(switches::kDisableSharedWorkers))
    WebRuntimeFeatures::enableSharedWorker(false);

#if defined(OS_ANDROID)
  // WebAudio is enabled by default on ARM and X86, if the MediaCodec
  // API is available.
  WebRuntimeFeatures::enableWebAudio(
      !command_line.HasSwitch(switches::kDisableWebAudio) &&
      media::MediaCodecBridge::IsAvailable());
#else
  if (command_line.HasSwitch(switches::kDisableWebAudio))
    WebRuntimeFeatures::enableWebAudio(false);
#endif

  if (command_line.HasSwitch(switches::kDisableSpeechAPI))
    WebRuntimeFeatures::enableScriptedSpeech(false);

  if (command_line.HasSwitch(switches::kDisableEncryptedMedia))
    WebRuntimeFeatures::enableEncryptedMedia(false);

  if (command_line.HasSwitch(switches::kDisablePrefixedEncryptedMedia))
    WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);

  if (command_line.HasSwitch(switches::kDisableFileSystem))
    WebRuntimeFeatures::enableFileSystem(false);

  if (command_line.HasSwitch(switches::kEnableExperimentalCanvasFeatures))
    WebRuntimeFeatures::enableExperimentalCanvasFeatures(true);

  if (!command_line.HasSwitch(switches::kDisableAcceleratedJpegDecoding))
    WebRuntimeFeatures::enableDecodeToYUV(true);

  if (command_line.HasSwitch(switches::kEnableDisplayList2dCanvas))
    WebRuntimeFeatures::enableDisplayList2dCanvas(true);

  if (command_line.HasSwitch(switches::kDisableDisplayList2dCanvas))
    WebRuntimeFeatures::enableDisplayList2dCanvas(false);

  if (command_line.HasSwitch(switches::kForceDisplayList2dCanvas))
    WebRuntimeFeatures::forceDisplayList2dCanvas(true);

  if (command_line.HasSwitch(switches::kEnableWebGLDraftExtensions))
    WebRuntimeFeatures::enableWebGLDraftExtensions(true);

  if (command_line.HasSwitch(switches::kEnableWebGLImageChromium))
    WebRuntimeFeatures::enableWebGLImageChromium(true);

  if (command_line.HasSwitch(switches::kEnableOverlayFullscreenVideo))
    WebRuntimeFeatures::enableOverlayFullscreenVideo(true);

  if (ui::IsOverlayScrollbarEnabled())
    WebRuntimeFeatures::enableOverlayScrollbars(true);

  if (command_line.HasSwitch(switches::kEnableBleedingEdgeRenderingFastPaths))
    WebRuntimeFeatures::enableBleedingEdgeFastPaths(true);

  if (command_line.HasSwitch(switches::kEnablePreciseMemoryInfo))
    WebRuntimeFeatures::enablePreciseMemoryInfo(true);

  if (command_line.HasSwitch(switches::kEnableNetworkInformation) ||
      command_line.HasSwitch(
          switches::kEnableExperimentalWebPlatformFeatures)) {
    WebRuntimeFeatures::enableNetworkInformation(true);
  }

  if (command_line.HasSwitch(switches::kEnableCredentialManagerAPI))
    WebRuntimeFeatures::enableCredentialManagerAPI(true);

  if (command_line.HasSwitch(switches::kDisableSVG1DOM)) {
    WebRuntimeFeatures::enableSVG1DOM(false);
  }

  if (command_line.HasSwitch(switches::kReducedReferrerGranularity))
    WebRuntimeFeatures::enableReducedReferrerGranularity(true);

  if (command_line.HasSwitch(switches::kEnablePushMessagePayload))
    WebRuntimeFeatures::enablePushMessagingData(true);

  if (command_line.HasSwitch(switches::kDisablePermissionsAPI))
    WebRuntimeFeatures::enablePermissionsAPI(false);

  // Delete "StaleWhileRevalidate" line from chrome_browser_field_trials.cc
  // when this experiment is done.
  if (base::FieldTrialList::FindFullName("StaleWhileRevalidate") == "Enabled" ||
      command_line.HasSwitch(switches::kEnableStaleWhileRevalidate))
    WebRuntimeFeatures::enableStaleWhileRevalidateCacheControl(true);

  if (command_line.HasSwitch(switches::kDisableV8IdleTasks))
    WebRuntimeFeatures::enableV8IdleTasks(false);
  else
    WebRuntimeFeatures::enableV8IdleTasks(true);

  if (command_line.HasSwitch(switches::kEnableUnsafeES3APIs))
    WebRuntimeFeatures::enableUnsafeES3APIs(true);

  if (command_line.HasSwitch(switches::kEnableWebVR)) {
    WebRuntimeFeatures::enableWebVR(true);
    WebRuntimeFeatures::enableFeatureFromString("GeometryInterfaces", true);
  }

  // Enable explicitly enabled features, and then disable explicitly disabled
  // ones.
  if (command_line.HasSwitch(switches::kEnableBlinkFeatures)) {
    std::vector<std::string> enabled_features;
    base::SplitString(
        command_line.GetSwitchValueASCII(switches::kEnableBlinkFeatures), ',',
        &enabled_features);
    for (const std::string& feature : enabled_features) {
      WebRuntimeFeatures::enableFeatureFromString(
          blink::WebString::fromLatin1(feature), true);
    }
  }
  if (command_line.HasSwitch(switches::kDisableBlinkFeatures)) {
    std::vector<std::string> disabled_features;
    base::SplitString(
        command_line.GetSwitchValueASCII(switches::kDisableBlinkFeatures), ',',
        &disabled_features);
    for (const std::string& feature : disabled_features) {
      WebRuntimeFeatures::enableFeatureFromString(
          blink::WebString::fromLatin1(feature), false);
    }
  }
}

}  // namespace content
<commit_msg>[Android] Allow constructor of Notifications on Android.<commit_after>// Copyright 2013 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/child/runtime_features.h"

#include <vector>

#include "base/command_line.h"
#include "base/metrics/field_trial.h"
#include "base/strings/string_split.h"
#include "components/scheduler/common/scheduler_switches.h"
#include "content/common/content_switches_internal.h"
#include "content/public/common/content_switches.h"
#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
#include "ui/gl/gl_switches.h"
#include "ui/native_theme/native_theme_switches.h"

#if defined(OS_ANDROID)
#include <cpu-features.h>
#include "base/android/build_info.h"
#include "base/metrics/field_trial.h"
#include "media/base/android/media_codec_bridge.h"
#elif defined(OS_WIN)
#include "base/win/windows_version.h"
#endif

using blink::WebRuntimeFeatures;

namespace content {

static void SetRuntimeFeatureDefaultsForPlatform() {
  // Enable non-standard "apple-touch-icon" and "apple-touch-icon-precomposed".
  WebRuntimeFeatures::enableTouchIconLoading(true);

#if defined(OS_ANDROID)
  // MSE/EME implementation needs Android MediaCodec API.
  if (!media::MediaCodecBridge::IsAvailable()) {
    WebRuntimeFeatures::enableMediaSource(false);
    WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);
    WebRuntimeFeatures::enableEncryptedMedia(false);
  }
  // WebAudio is enabled by default but only when the MediaCodec API
  // is available.
  AndroidCpuFamily cpu_family = android_getCpuFamily();
  WebRuntimeFeatures::enableWebAudio(
      media::MediaCodecBridge::IsAvailable() &&
      ((cpu_family == ANDROID_CPU_FAMILY_ARM) ||
       (cpu_family == ANDROID_CPU_FAMILY_ARM64) ||
       (cpu_family == ANDROID_CPU_FAMILY_X86) ||
       (cpu_family == ANDROID_CPU_FAMILY_MIPS)));

  // Android does not have support for PagePopup
  WebRuntimeFeatures::enablePagePopup(false);
  // Android does not yet support SharedWorker. crbug.com/154571
  WebRuntimeFeatures::enableSharedWorker(false);
  // Android does not yet support NavigatorContentUtils.
  WebRuntimeFeatures::enableNavigatorContentUtils(false);
  WebRuntimeFeatures::enableOrientationEvent(true);
  WebRuntimeFeatures::enableFastMobileScrolling(true);
  WebRuntimeFeatures::enableMediaCapture(true);
  WebRuntimeFeatures::enableCompositedSelectionUpdate(true);
#else
  WebRuntimeFeatures::enableNavigatorContentUtils(true);
#endif  // defined(OS_ANDROID)

#if !(defined OS_ANDROID || defined OS_CHROMEOS || defined OS_IOS)
    // Only Android, ChromeOS, and IOS support NetInfo right now.
    WebRuntimeFeatures::enableNetworkInformation(false);
#endif

#if defined(OS_WIN)
  // Screen Orientation API is currently broken on Windows 8 Metro mode and
  // until we can find how to disable it only for Blink instances running in a
  // renderer process in Metro, we need to disable the API altogether for Win8.
  // See http://crbug.com/400846
  if (base::win::OSInfo::GetInstance()->version() >= base::win::VERSION_WIN8)
    WebRuntimeFeatures::enableScreenOrientation(false);
#endif // OS_WIN
}

void SetRuntimeFeaturesDefaultsAndUpdateFromArgs(
    const base::CommandLine& command_line) {
  if (command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures))
    WebRuntimeFeatures::enableExperimentalFeatures(true);

  if (command_line.HasSwitch(switches::kEnableWebBluetooth))
    WebRuntimeFeatures::enableWebBluetooth(true);

  SetRuntimeFeatureDefaultsForPlatform();

  if (command_line.HasSwitch(switches::kDisableDatabases))
    WebRuntimeFeatures::enableDatabase(false);

  if (command_line.HasSwitch(scheduler::switches::kDisableBlinkScheduler))
    WebRuntimeFeatures::enableBlinkScheduler(false);

  if (command_line.HasSwitch(switches::kDisableMediaSource))
    WebRuntimeFeatures::enableMediaSource(false);

  if (command_line.HasSwitch(switches::kDisableNotifications)) {
    WebRuntimeFeatures::enableNotifications(false);

    // Chrome's Push Messaging implementation relies on Web Notifications.
    WebRuntimeFeatures::enablePushMessaging(false);
  }

  if (command_line.HasSwitch(switches::kDisableSharedWorkers))
    WebRuntimeFeatures::enableSharedWorker(false);

#if defined(OS_ANDROID)
  // WebAudio is enabled by default on ARM and X86, if the MediaCodec
  // API is available.
  WebRuntimeFeatures::enableWebAudio(
      !command_line.HasSwitch(switches::kDisableWebAudio) &&
      media::MediaCodecBridge::IsAvailable());
#else
  if (command_line.HasSwitch(switches::kDisableWebAudio))
    WebRuntimeFeatures::enableWebAudio(false);
#endif

  if (command_line.HasSwitch(switches::kDisableSpeechAPI))
    WebRuntimeFeatures::enableScriptedSpeech(false);

  if (command_line.HasSwitch(switches::kDisableEncryptedMedia))
    WebRuntimeFeatures::enableEncryptedMedia(false);

  if (command_line.HasSwitch(switches::kDisablePrefixedEncryptedMedia))
    WebRuntimeFeatures::enablePrefixedEncryptedMedia(false);

  if (command_line.HasSwitch(switches::kDisableFileSystem))
    WebRuntimeFeatures::enableFileSystem(false);

  if (command_line.HasSwitch(switches::kEnableExperimentalCanvasFeatures))
    WebRuntimeFeatures::enableExperimentalCanvasFeatures(true);

  if (!command_line.HasSwitch(switches::kDisableAcceleratedJpegDecoding))
    WebRuntimeFeatures::enableDecodeToYUV(true);

  if (command_line.HasSwitch(switches::kEnableDisplayList2dCanvas))
    WebRuntimeFeatures::enableDisplayList2dCanvas(true);

  if (command_line.HasSwitch(switches::kDisableDisplayList2dCanvas))
    WebRuntimeFeatures::enableDisplayList2dCanvas(false);

  if (command_line.HasSwitch(switches::kForceDisplayList2dCanvas))
    WebRuntimeFeatures::forceDisplayList2dCanvas(true);

  if (command_line.HasSwitch(switches::kEnableWebGLDraftExtensions))
    WebRuntimeFeatures::enableWebGLDraftExtensions(true);

  if (command_line.HasSwitch(switches::kEnableWebGLImageChromium))
    WebRuntimeFeatures::enableWebGLImageChromium(true);

  if (command_line.HasSwitch(switches::kEnableOverlayFullscreenVideo))
    WebRuntimeFeatures::enableOverlayFullscreenVideo(true);

  if (ui::IsOverlayScrollbarEnabled())
    WebRuntimeFeatures::enableOverlayScrollbars(true);

  if (command_line.HasSwitch(switches::kEnableBleedingEdgeRenderingFastPaths))
    WebRuntimeFeatures::enableBleedingEdgeFastPaths(true);

  if (command_line.HasSwitch(switches::kEnablePreciseMemoryInfo))
    WebRuntimeFeatures::enablePreciseMemoryInfo(true);

  if (command_line.HasSwitch(switches::kEnableNetworkInformation) ||
      command_line.HasSwitch(
          switches::kEnableExperimentalWebPlatformFeatures)) {
    WebRuntimeFeatures::enableNetworkInformation(true);
  }

  if (command_line.HasSwitch(switches::kEnableCredentialManagerAPI))
    WebRuntimeFeatures::enableCredentialManagerAPI(true);

  if (command_line.HasSwitch(switches::kDisableSVG1DOM)) {
    WebRuntimeFeatures::enableSVG1DOM(false);
  }

  if (command_line.HasSwitch(switches::kReducedReferrerGranularity))
    WebRuntimeFeatures::enableReducedReferrerGranularity(true);

  if (command_line.HasSwitch(switches::kEnablePushMessagePayload))
    WebRuntimeFeatures::enablePushMessagingData(true);

  if (command_line.HasSwitch(switches::kDisablePermissionsAPI))
    WebRuntimeFeatures::enablePermissionsAPI(false);

  // Delete "StaleWhileRevalidate" line from chrome_browser_field_trials.cc
  // when this experiment is done.
  if (base::FieldTrialList::FindFullName("StaleWhileRevalidate") == "Enabled" ||
      command_line.HasSwitch(switches::kEnableStaleWhileRevalidate))
    WebRuntimeFeatures::enableStaleWhileRevalidateCacheControl(true);

  if (command_line.HasSwitch(switches::kDisableV8IdleTasks))
    WebRuntimeFeatures::enableV8IdleTasks(false);
  else
    WebRuntimeFeatures::enableV8IdleTasks(true);

  if (command_line.HasSwitch(switches::kEnableUnsafeES3APIs))
    WebRuntimeFeatures::enableUnsafeES3APIs(true);

  if (command_line.HasSwitch(switches::kEnableWebVR)) {
    WebRuntimeFeatures::enableWebVR(true);
    WebRuntimeFeatures::enableFeatureFromString("GeometryInterfaces", true);
  }

  // Enable explicitly enabled features, and then disable explicitly disabled
  // ones.
  if (command_line.HasSwitch(switches::kEnableBlinkFeatures)) {
    std::vector<std::string> enabled_features;
    base::SplitString(
        command_line.GetSwitchValueASCII(switches::kEnableBlinkFeatures), ',',
        &enabled_features);
    for (const std::string& feature : enabled_features) {
      WebRuntimeFeatures::enableFeatureFromString(
          blink::WebString::fromLatin1(feature), true);
    }
  }
  if (command_line.HasSwitch(switches::kDisableBlinkFeatures)) {
    std::vector<std::string> disabled_features;
    base::SplitString(
        command_line.GetSwitchValueASCII(switches::kDisableBlinkFeatures), ',',
        &disabled_features);
    for (const std::string& feature : disabled_features) {
      WebRuntimeFeatures::enableFeatureFromString(
          blink::WebString::fromLatin1(feature), false);
    }
  }
}

}  // namespace content
<|endoftext|>


<commit_before>// Copyright 2020 The TensorFlow Runtime Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Implementation of the MIOpen API forwarding calls to symbols dynamically
// loaded from the real library.
#include "tfrt/gpu/wrapper/miopen_stub.h"

#include "symbol_loader.h"

// Memoizes load of the .so for this ROCm library.
static void *LoadSymbol(const char *symbol_name) {
  static SymbolLoader loader("libmiopen.so");
  return loader.GetAddressOfSymbol(symbol_name);
}

template <typename Func>
static Func *GetFunctionPointer(const char *symbol_name, Func *func = nullptr) {
  return reinterpret_cast<Func *>(LoadSymbol(symbol_name));
}

// Calls function 'symbol_name' in shared library with 'args'.
// TODO(csigg): Change to 'auto Func' when C++17 is allowed.
template <typename Func, Func *, typename... Args>
static miopenStatus_t DynamicCall(const char *symbol_name, Args &&...args) {
  static auto func_ptr = GetFunctionPointer<Func>(symbol_name);
  if (!func_ptr) return miopenStatusNotInitialized;
  return func_ptr(std::forward<Args>(args)...);
}

extern "C" {
#include "miopen_stub.cc.inc"
}

// The functions below have a different return type and therefore don't fit
// the code generator patterns.

const char *miopenGetErrorString(miopenStatus_t error) {
  static auto func_ptr =
      GetFunctionPointer("miopenGetErrorString", miopenGetErrorString);
  if (!func_ptr) return "FAILED_TO_LOAD_FUNCTION_SYMBOL";
  return func_ptr(error);
}
<commit_msg>Correct the name of the MIOpen library in miopen_stub.cc<commit_after>// Copyright 2020 The TensorFlow Runtime Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Implementation of the MIOpen API forwarding calls to symbols dynamically
// loaded from the real library.
#include "tfrt/gpu/wrapper/miopen_stub.h"

#include "symbol_loader.h"

// Memoizes load of the .so for this ROCm library.
static void *LoadSymbol(const char *symbol_name) {
  static SymbolLoader loader("libMIOpen.so");
  return loader.GetAddressOfSymbol(symbol_name);
}

template <typename Func>
static Func *GetFunctionPointer(const char *symbol_name, Func *func = nullptr) {
  return reinterpret_cast<Func *>(LoadSymbol(symbol_name));
}

// Calls function 'symbol_name' in shared library with 'args'.
// TODO(csigg): Change to 'auto Func' when C++17 is allowed.
template <typename Func, Func *, typename... Args>
static miopenStatus_t DynamicCall(const char *symbol_name, Args &&...args) {
  static auto func_ptr = GetFunctionPointer<Func>(symbol_name);
  if (!func_ptr) return miopenStatusNotInitialized;
  return func_ptr(std::forward<Args>(args)...);
}

extern "C" {
#include "miopen_stub.cc.inc"
}

// The functions below have a different return type and therefore don't fit
// the code generator patterns.

const char *miopenGetErrorString(miopenStatus_t error) {
  static auto func_ptr =
      GetFunctionPointer("miopenGetErrorString", miopenGetErrorString);
  if (!func_ptr) return "FAILED_TO_LOAD_FUNCTION_SYMBOL";
  return func_ptr(error);
}
<|endoftext|>


<commit_before>#include "dhash.h"
#include "ddns.h"
#include <iostream>

#define nelem(a) (sizeof(a)/sizeof((a)[0]))
#define nil 0

ptr<ddns> ddns_clnt;

static int
splitfields(char *s, char **f, int mf, int sep)
{
  char *p;
  int infield, nf;

  infield = 0;
  nf = 0;
  for(p=s; *p; p++){
    if(*p == sep){
      *p = '\0';
      infield = 0;
    }else if(!infield){
      f[nf++] = p;
      if(nf >= mf)
        return nf;
      infield = 1;
    }
  }
  return nf;
}

static int
mkaddress(unsigned char *a, char *s)
{
  char *f[5];
  int i, nf;

  nf = splitfields(s, f, nelem(f), '.');
  if(nf != 4){
    cerr << "bad ip address format";
    return -1;
  }
  for(i=0; i<4; i++)
    a[i] = atoi(f[i]);
  return 0;
}

static ptr<ddnsRR>
mkrr(char *name, dns_type t, int nval, char **val)
{
  char *f[10];
  int nf, i;
  ptr<ddnsRR> *last, rr, rrlist;

  rrlist = nil;
  last = &rrlist;

  for(i=0; i<nval; i++){
	rr = New refcounted<ddnsRR>;
	rr->dname = strdup(name);
	rr->type = t;
	switch(t){
	case A:
	  rr->rdlength = 4;
	  if(mkaddress(rr->rdata.address, val[i]) < 0)
	    return nil;
	  break;
	case NS:
	case CNAME:
	case MD:
	case MF:
	case MG:
	case MR:
	case PTR:
	default:
	  rr->rdata.hostname = strdup(val[i]);
	  rr->rdlength = strlen(val[i])+1;
	  break;
	case SOA:
	  nf = splitfields(val[i], f, nelem(f), ';');
	  if(nf != 7){
	    cerr << "soa format: mname;rname;serial;refresh;retry;expire;minttl";
	    return nil;
	  }
	  rr->rdata.soa.mname = strdup(f[0]);
	  rr->rdata.soa.rname = strdup(f[1]);
	  rr->rdata.soa.serial = atoi(f[2]);
	  rr->rdata.soa.refresh = atoi(f[3]);
	  rr->rdata.soa.retry = atoi(f[4]);
	  rr->rdata.soa.expire = atoi(f[5]);
	  rr->rdata.soa.minttl = atoi(f[6]);
      rr->rdlength = strlen(f[0])+1 + strlen(f[1])+1 + 5*4;
      break;
    case WKS:
	  nf = splitfields(val[i], f, nelem(f), ';');
	  if(nf != 3){
	    cerr << "wks format: ipaddress;protocol";
	    return nil;
	  }
      if(mkaddress(rr->rdata.wks.address, f[0]) < 0)
        return nil;
      rr->rdata.wks.protocol = atoi(f[1]);
      rr->rdata.wks.bitmap = (char*)malloc(8);
      strcpy(rr->rdata.wks.bitmap, "Athicha!");
      rr->rdlength = 4+4+9;
      break;
    case HINFO:
	  nf = splitfields(val[i], f, nelem(f), ';');
	  if(nf != 2){
	    cerr << "hinfo format: cpu;os";
	    return nil;
	  }
	  rr->rdata.hinfo.cpu = strdup(f[0]);
	  rr->rdata.hinfo.os = strdup(f[1]);
	  rr->rdlength = strlen(f[0])+1 + strlen(f[1])+1;
	  break;
	case MINFO:
	  nf = splitfields(val[i], f, nelem(f), ';');
	  if(nf != 2){
	    cerr << "minfo format: rmailbx;emailbx";
	    return nil;
	  }
	  rr->rdata.minfo.rmailbx = strdup(f[0]);
	  rr->rdata.minfo.emailbx = strdup(f[1]);
	  rr->rdlength = strlen(f[0])+1 + strlen(f[1])+1;
	  break;
    case MX:
	  nf = splitfields(val[i], f, nelem(f), ';');
	  if(nf != 2){
	    cerr << "mx format: pref;exchange";
	    return nil;
	  }
	  rr->rdata.mx.pref = atoi(f[0]);
	  rr->rdata.mx.exchange = strdup(f[1]);
	  rr->rdlength = 4 + strlen(f[1])+1;
	  break;
	case TXT:
	  rr->rdata.txt_data = strdup(val[i]);
	  rr->rdlength = strlen(val[i])+1;
	  break;
    case DNULL:
      break;
	}
	*last = rr;
	last = &rr->next;
  }
  return rrlist;
}

static char*
cmdinsert(int argc, char **argv)
{
  if(argc < 3)
    return "usage: insert name type val...";

  ptr<ddnsRR> rr = mkrr(strdup(argv[0]), get_dtype(argv[1]), argc-2, &argv[2]);
  if(rr == nil)
    return "parse error";
  ddns_clnt->store(strdup(argv[0]), rr);
  return nil;
}

static char*
cmddelete(int, char**)
{
  return "delete not implemented";
}

static char*
typestr(dns_type t)
{
  static char buf[20];

  switch(t){
  case A:
    return "a";
  case NS:
    return "ns";
  case CNAME:
    return "cname";
  case MD:
    return "md";
  case MF:
    return "mf";
  case MB:
    return "mb";
  case MG:
    return "mg";
  case MR:
    return "mr";
  case PTR:
    return "ptr";
  case SOA:
    return "soa";
  default:
    snprintf(buf, sizeof buf, "dnstype%d", t);
    return buf;
  }
}

static void
printrr(ptr<ddnsRR> rr)
{
  unsigned char *a;

  cout << rr->dname << " " << typestr(rr->type);
  for(; rr; rr=rr->next){
    cout << " ";
    switch(rr->type){
    case A:
      a = rr->rdata.address;
      cout << (int)a[0] << "." << (int)a[1] << "." << (int)a[2] << "." << (int)a[3];
      break;
    case NS:
    case CNAME:
    case MD:
    case MF:
    case MB:
    case MG:
    case MR:
    case PTR:
      cout << rr->rdata.hostname;
      break;
    case SOA:
      cout << rr->rdata.soa.mname << ";";
      cout << rr->rdata.soa.rname << ";";
      cout << rr->rdata.soa.serial << ";";
      cout << rr->rdata.soa.refresh << ";";
      cout << rr->rdata.soa.retry << ";";
      cout << rr->rdata.soa.expire << ";";
      cout << rr->rdata.soa.minttl;
      break;
    case WKS:
      a = rr->rdata.wks.address;
      cout << (int)a[0] << "." << (int)a[1] << "." << (int)a[2] << "." << (int)a[3] << ";";
      cout << rr->rdata.wks.protocol << ";";
      cout << rr->rdata.wks.bitmap;
      break;
    case HINFO:
      cout << rr->rdata.hinfo.cpu << ";" << rr->rdata.hinfo.os;
      break;
    case MINFO:
      cout << rr->rdata.minfo.rmailbx << ";" << rr->rdata.minfo.emailbx;
      break;
    case MX:
      cout << rr->rdata.mx.pref << ";" << rr->rdata.mx.exchange;
      break;
    case TXT:
      cout << rr->rdata.txt_data;
      break;
    case DNULL:
      break;
    default:
      cout << "\tunknown type\n";
      break;
    }
  }
  cout << "\n";
}

static char*
cmdlookup(int argc, char **argv)
{
  if(argc != 2)
    return "usage: lookup name type";
  ddns_clnt->lookup(strdup(argv[0]), get_dtype(argv[1]), wrap(printrr));
  return nil;
}

static struct {
  char *cmd;
  char *(*fn)(int, char**);
} tab[] = {
  {"insert", cmdinsert},
  {"delete", cmddelete},
  {"lookup", cmdlookup},
};

static void
usage ()
{
  warnx << "usage: ddnscmd\n";
  exit (1);
}

int
main (int argc, char **argv)
{
  char line[256], *err, *f[20];
  int i, nf;

  if(argc != 1)
    usage ();

  sfsconst_init ();
  const char *control_socket = "/tmp/chord-sock";
  ddns_clnt = New refcounted<ddns> (control_socket, 0);
  for(;;){
    cerr << ">>> ";
    cin.getline(line, sizeof line);
    if(cin.eof())
      break;
    nf = splitfields(line, f, nelem(f), ' ');
    if(nf == 0)
      continue;
    for(i=0; i<(int)nelem(tab); i++)
      if(strcmp(tab[i].cmd, f[0]) == 0)
        break;
    if(i==nelem(tab)){
      cerr << "?unknown command\n";
      continue;
    }
    if((err = tab[i].fn(nf-1, f+1)) != nil)
      cerr << "?" << err << "\n";
  }
  return 0;
}

<commit_msg>wks argument count bug fix<commit_after>#include "dhash.h"
#include "ddns.h"
#include <iostream>

#define nelem(a) (sizeof(a)/sizeof((a)[0]))
#define nil 0

ptr<ddns> ddns_clnt;

static int
splitfields(char *s, char **f, int mf, int sep)
{
  char *p;
  int infield, nf;

  infield = 0;
  nf = 0;
  for(p=s; *p; p++){
    if(*p == sep){
      *p = '\0';
      infield = 0;
    }else if(!infield){
      f[nf++] = p;
      if(nf >= mf)
        return nf;
      infield = 1;
    }
  }
  return nf;
}

static int
mkaddress(unsigned char *a, char *s)
{
  char *f[5];
  int i, nf;

  nf = splitfields(s, f, nelem(f), '.');
  if(nf != 4){
    cerr << "bad ip address format";
    return -1;
  }
  for(i=0; i<4; i++)
    a[i] = atoi(f[i]);
  return 0;
}

static ptr<ddnsRR>
mkrr(char *name, dns_type t, int nval, char **val)
{
  char *f[10];
  int nf, i;
  ptr<ddnsRR> *last, rr, rrlist;

  rrlist = nil;
  last = &rrlist;

  for(i=0; i<nval; i++){
	rr = New refcounted<ddnsRR>;
	rr->dname = strdup(name);
	rr->type = t;
	switch(t){
	case A:
	  rr->rdlength = 4;
	  if(mkaddress(rr->rdata.address, val[i]) < 0)
	    return nil;
	  break;
	case NS:
	case CNAME:
	case MD:
	case MF:
	case MG:
	case MR:
	case PTR:
	default:
	  rr->rdata.hostname = strdup(val[i]);
	  rr->rdlength = strlen(val[i])+1;
	  break;
	case SOA:
	  nf = splitfields(val[i], f, nelem(f), ';');
	  if(nf != 7){
	    cerr << "soa format: mname;rname;serial;refresh;retry;expire;minttl";
	    return nil;
	  }
	  rr->rdata.soa.mname = strdup(f[0]);
	  rr->rdata.soa.rname = strdup(f[1]);
	  rr->rdata.soa.serial = atoi(f[2]);
	  rr->rdata.soa.refresh = atoi(f[3]);
	  rr->rdata.soa.retry = atoi(f[4]);
	  rr->rdata.soa.expire = atoi(f[5]);
	  rr->rdata.soa.minttl = atoi(f[6]);
      rr->rdlength = strlen(f[0])+1 + strlen(f[1])+1 + 5*4;
      break;
    case WKS:
	  nf = splitfields(val[i], f, nelem(f), ';');
	  if(nf != 2){
	    cerr << "wks format: ipaddress;protocol";
	    return nil;
	  }
      if(mkaddress(rr->rdata.wks.address, f[0]) < 0)
        return nil;
      rr->rdata.wks.protocol = atoi(f[1]);
      rr->rdata.wks.bitmap = (char*)malloc(8);
      strcpy(rr->rdata.wks.bitmap, "Athicha!");
      rr->rdlength = 4+4+9;
      break;
    case HINFO:
	  nf = splitfields(val[i], f, nelem(f), ';');
	  if(nf != 2){
	    cerr << "hinfo format: cpu;os";
	    return nil;
	  }
	  rr->rdata.hinfo.cpu = strdup(f[0]);
	  rr->rdata.hinfo.os = strdup(f[1]);
	  rr->rdlength = strlen(f[0])+1 + strlen(f[1])+1;
	  break;
	case MINFO:
	  nf = splitfields(val[i], f, nelem(f), ';');
	  if(nf != 2){
	    cerr << "minfo format: rmailbx;emailbx";
	    return nil;
	  }
	  rr->rdata.minfo.rmailbx = strdup(f[0]);
	  rr->rdata.minfo.emailbx = strdup(f[1]);
	  rr->rdlength = strlen(f[0])+1 + strlen(f[1])+1;
	  break;
    case MX:
	  nf = splitfields(val[i], f, nelem(f), ';');
	  if(nf != 2){
	    cerr << "mx format: pref;exchange";
	    return nil;
	  }
	  rr->rdata.mx.pref = atoi(f[0]);
	  rr->rdata.mx.exchange = strdup(f[1]);
	  rr->rdlength = 4 + strlen(f[1])+1;
	  break;
	case TXT:
	  rr->rdata.txt_data = strdup(val[i]);
	  rr->rdlength = strlen(val[i])+1;
	  break;
    case DNULL:
      break;
	}
	*last = rr;
	last = &rr->next;
  }
  return rrlist;
}

static char*
cmdinsert(int argc, char **argv)
{
  if(argc < 3)
    return "usage: insert name type val...";

  ptr<ddnsRR> rr = mkrr(strdup(argv[0]), get_dtype(argv[1]), argc-2, &argv[2]);
  if(rr == nil)
    return "parse error";
  ddns_clnt->store(strdup(argv[0]), rr);
  return nil;
}

static char*
cmddelete(int, char**)
{
  return "delete not implemented";
}

static char*
typestr(dns_type t)
{
  static char buf[20];

  switch(t){
  case A:
    return "a";
  case NS:
    return "ns";
  case CNAME:
    return "cname";
  case MD:
    return "md";
  case MF:
    return "mf";
  case MB:
    return "mb";
  case MG:
    return "mg";
  case MR:
    return "mr";
  case PTR:
    return "ptr";
  case SOA:
    return "soa";
  default:
    snprintf(buf, sizeof buf, "dnstype%d", t);
    return buf;
  }
}

static void
printrr(ptr<ddnsRR> rr)
{
  unsigned char *a;

  cout << rr->dname << " " << typestr(rr->type);
  for(; rr; rr=rr->next){
    cout << " ";
    switch(rr->type){
    case A:
      a = rr->rdata.address;
      cout << (int)a[0] << "." << (int)a[1] << "." << (int)a[2] << "." << (int)a[3];
      break;
    case NS:
    case CNAME:
    case MD:
    case MF:
    case MB:
    case MG:
    case MR:
    case PTR:
      cout << rr->rdata.hostname;
      break;
    case SOA:
      cout << rr->rdata.soa.mname << ";";
      cout << rr->rdata.soa.rname << ";";
      cout << rr->rdata.soa.serial << ";";
      cout << rr->rdata.soa.refresh << ";";
      cout << rr->rdata.soa.retry << ";";
      cout << rr->rdata.soa.expire << ";";
      cout << rr->rdata.soa.minttl;
      break;
    case WKS:
      a = rr->rdata.wks.address;
      cout << (int)a[0] << "." << (int)a[1] << "." << (int)a[2] << "." << (int)a[3] << ";";
      cout << rr->rdata.wks.protocol << ";";
      cout << rr->rdata.wks.bitmap;
      break;
    case HINFO:
      cout << rr->rdata.hinfo.cpu << ";" << rr->rdata.hinfo.os;
      break;
    case MINFO:
      cout << rr->rdata.minfo.rmailbx << ";" << rr->rdata.minfo.emailbx;
      break;
    case MX:
      cout << rr->rdata.mx.pref << ";" << rr->rdata.mx.exchange;
      break;
    case TXT:
      cout << rr->rdata.txt_data;
      break;
    case DNULL:
      break;
    default:
      cout << "\tunknown type\n";
      break;
    }
  }
  cout << "\n";
}

static char*
cmdlookup(int argc, char **argv)
{
  if(argc != 2)
    return "usage: lookup name type";
  ddns_clnt->lookup(strdup(argv[0]), get_dtype(argv[1]), wrap(printrr));
  return nil;
}

static struct {
  char *cmd;
  char *(*fn)(int, char**);
} tab[] = {
  {"insert", cmdinsert},
  {"delete", cmddelete},
  {"lookup", cmdlookup},
};

static void
usage ()
{
  warnx << "usage: ddnscmd\n";
  exit (1);
}

int
main (int argc, char **argv)
{
  char line[256], *err, *f[20];
  int i, nf;

  if(argc != 1)
    usage ();

  sfsconst_init ();
  const char *control_socket = "/tmp/chord-sock";
  ddns_clnt = New refcounted<ddns> (control_socket, 0);
  for(;;){
    cerr << ">>> ";
    cin.getline(line, sizeof line);
    if(cin.eof())
      break;
    nf = splitfields(line, f, nelem(f), ' ');
    if(nf == 0)
      continue;
    for(i=0; i<(int)nelem(tab); i++)
      if(strcmp(tab[i].cmd, f[0]) == 0)
        break;
    if(i==nelem(tab)){
      cerr << "?unknown command\n";
      continue;
    }
    if((err = tab[i].fn(nf-1, f+1)) != nil)
      cerr << "?" << err << "\n";
  }
  return 0;
}

<|endoftext|>


<commit_before>/**
 * @file
 */
#pragma once

namespace libbirch {
/**
 * Shape and layout of an array.
 *
 * @ingroup libbirch
 *
 * @tparam D Number of dimensions.
 */
template<int D>
class ArrayShape {
  static_assert(D <= 2, "arrays support only up to two dimensions");
};

/**
 * Shape and layout of a vector (one-dimensional array).
 */
template<>
class ArrayShape<1> {
public:
  ArrayShape(const int n = 0, const int inc = 1) :
      n(n),
      inc(inc) {
    //
  }

  int64_t size() const {
    return n;
  }

  int64_t volume() const {
    return int64_t(inc)*n;
  }

  int rows() const {
    return n;
  }

  static constexpr int columns() {
    return 1;
  }

  int stride() const {
    return inc;
  }

  int width() const {
    return 1;
  }

  int height() const {
    return n;
  }

  bool conforms(const ArrayShape<1>& o) const {
    return n == o.n;
  }

  void compact() {
    inc = 1;
  }

  template<class T>
  auto slice(T* buffer, const std::pair<int,int>& range) const {
    assert(range.first <= range.second && "invalid range");
    assert(1 <= range.first && range.first <= n && "start of range out of bounds");
    assert(1 <= range.second && range.second <= n && "end of range out of bounds");

    using U = typename std::remove_const<T>::type;
    U* buf = const_cast<U*>(buffer);

    int i = range.first;
    int len = range.second - range.first + 1;

    return Array<U,1>(buf + (i - 1)*int64_t(inc), ArrayShape<1>(len, inc));
  }

  template<class T>
  T& slice(T* buffer, const int i) const {
    assert(1 <= i && i <= n && "index out of bounds");
    return buffer[(i - 1)*int64_t(inc)];
  }

  /**
   * Compute the 0-based offset to the @p s th element in serial storage
   * order.
   *
   * @param s Serial index, 0-based.
   */
  int64_t offset(const int64_t s) const {
    return s*inc;
  }

  /**
   * Compute the 0-based offset to the @p t th element in transpose storage
   * order.
   *
   * @param t Transpose index, 0-based.
   */
  int64_t transpose(const int64_t t) const {
    return t*inc;
  }

private:
  /**
   * Number of elements.
   */
  int n;

  /**
   * Stride between elements.
   */
  int inc;
};

/**
 * Shape and layout of a matrix (two-dimensional array) in column-major order.
 */
template<>
class ArrayShape<2> {
public:
  ArrayShape() :
      m(0),
      n(0),
      ld(0) {
    //
  }

  ArrayShape(const int m, const int n) :
      m(m),
      n(n),
      ld(m) {
    //
  }

  ArrayShape(const int m, const int n, const int ld) :
      m(m),
      n(n),
      ld(ld) {
    //
  }

  int64_t size() const {
    return int64_t(m)*n;
  }

  int64_t volume() const {
    return int64_t(ld)*n;
  }

  int rows() const {
    return m;
  }

  int columns() const {
    return n;
  }

  int stride() const {
    return ld;
  }

  int width() const {
    return m;
  }

  int height() const {
    return n;
  }

  bool conforms(const ArrayShape<2>& o) const {
    return m == o.m && n == o.n;
  }

  void compact() {
    ld = m;
  }

  /**
   * Compute the 0-based offset to the @p s th element in serial storage
   * order.
   *
   * @param s Serial index, 0-based.
   */
  int64_t offset(const int64_t s) const {
    int64_t j = s/m;
    int64_t i = s - j*m;
    return i + ld*j;
  }

  /**
   * Compute the 0-based offset to the @p t th element in transpose storage
   * order.
   *
   * @param t Transpose index, 0-based.
   */
  int64_t transpose(const int64_t t) const {
    int64_t i = t/n;
    int64_t j = t - i*n;
    return i + ld*j;
  }

  template<class T>
  auto slice(T* buffer, const std::pair<int,int>& rows,
     const std::pair<int,int>& cols) const {
    assert(rows.first <= rows.second && "invalid row range");
    assert(1 <= rows.first && rows.first <= m && "start of row range out of bounds");
    assert(1 <= rows.second && rows.second <= m && "end of row range out of bounds");

    assert(cols.first <= cols.second && "invalid column range");
    assert(1 <= cols.first && cols.first <= n && "start of column range out of bounds");
    assert(1 <= cols.second && cols.second <= n && "end of column range out of bounds");

    using U = typename std::remove_const<T>::type;
    U* buf = const_cast<U*>(buffer);

    int i = rows.first;
    int r = rows.second - rows.first + 1;
    int j = cols.first;
    int c = cols.second - cols.first + 1;

    return Array<U,2>(buf + (i - 1) + int64_t(ld)*(j - 1),
        ArrayShape<2>(r, c, ld));
  }

  template<class T>
  auto slice(T* buffer, const std::pair<int,int>& rows, const int j) const {
    assert(rows.first <= rows.second && "invalid row range");
    assert(1 <= rows.first && rows.first <= m && "start of row range out of bounds");
    assert(1 <= rows.second && rows.second <= m && "end of row range out of bounds");

    assert(1 <= j && j <= n && "column index out of bounds");

    using U = typename std::remove_const<T>::type;
    U* buf = const_cast<U*>(buffer);

    int i = rows.first;
    int r = rows.second - rows.first + 1;

    return Array<U,1>(buf + (i - 1) + int64_t(ld)*(j - 1),
        ArrayShape<1>(r, 1));
  }

  template<class T>
  auto slice(T* buffer, const int i, const std::pair<int,int>& cols) const {
    assert(1 <= i && i <= m && "row index out of bounds");

    assert(cols.first <= cols.second && "invalid column range");
    assert(1 <= cols.first && cols.first <= n && "start of column range out of bounds");
    assert(1 <= cols.second && cols.second <= n && "end of column range out of bounds");

    using U = typename std::remove_const<T>::type;
    U* buf = const_cast<U*>(buffer);

    int j = cols.first;
    int c = cols.second - cols.first + 1;

    return Array<U,1>(buf + (i - 1) + int64_t(ld)*(j - 1),
        ArrayShape<1>(c, ld));
  }

  template<class T>
  T& slice(T* buffer, const int i, const int j) const {
    assert(1 <= i && i <= m && "row index out of bounds");
    assert(1 <= j && j <= n && "column index out of bounds");
    return buffer[(i - 1) + int64_t(ld)*(j - 1)];
  }

private:
  /**
   * Number of rows.
   */
  int m;

  /**
   * Number of columns.
   */
  int n;

  /**
   * Stride between columns.
   */
  int ld;
};
}
<commit_msg>Updated ranges to permit ending index to be less than starting index, with the interpretation that the range is then of zero length.<commit_after>/**
 * @file
 */
#pragma once

namespace libbirch {
/**
 * Shape and layout of an array.
 *
 * @ingroup libbirch
 *
 * @tparam D Number of dimensions.
 */
template<int D>
class ArrayShape {
  static_assert(D <= 2, "arrays support only up to two dimensions");
};

/**
 * Shape and layout of a vector (one-dimensional array).
 */
template<>
class ArrayShape<1> {
public:
  ArrayShape(const int n = 0, const int inc = 1) :
      n(n),
      inc(inc) {
    //
  }

  int64_t size() const {
    return n;
  }

  int64_t volume() const {
    return int64_t(inc)*n;
  }

  int rows() const {
    return n;
  }

  static constexpr int columns() {
    return 1;
  }

  int stride() const {
    return inc;
  }

  int width() const {
    return 1;
  }

  int height() const {
    return n;
  }

  bool conforms(const ArrayShape<1>& o) const {
    return n == o.n;
  }

  void compact() {
    inc = 1;
  }

  template<class T>
  auto slice(T* buffer, const std::pair<int,int>& range) const {
    assert(1 <= range.first && range.first <= n && "start of range out of bounds");
    assert(range.second <= n && "end of range out of bounds");

    using U = typename std::remove_const<T>::type;
    U* buf = const_cast<U*>(buffer);

    int i = range.first;
    int len = std::max(0, range.second - range.first + 1);

    return Array<U,1>(buf + (i - 1)*int64_t(inc), ArrayShape<1>(len, inc));
  }

  template<class T>
  T& slice(T* buffer, const int i) const {
    assert(1 <= i && i <= n && "index out of bounds");
    return buffer[(i - 1)*int64_t(inc)];
  }

  /**
   * Compute the 0-based offset to the @p s th element in serial storage
   * order.
   *
   * @param s Serial index, 0-based.
   */
  int64_t offset(const int64_t s) const {
    return s*inc;
  }

  /**
   * Compute the 0-based offset to the @p t th element in transpose storage
   * order.
   *
   * @param t Transpose index, 0-based.
   */
  int64_t transpose(const int64_t t) const {
    return t*inc;
  }

private:
  /**
   * Number of elements.
   */
  int n;

  /**
   * Stride between elements.
   */
  int inc;
};

/**
 * Shape and layout of a matrix (two-dimensional array) in column-major order.
 */
template<>
class ArrayShape<2> {
public:
  ArrayShape() :
      m(0),
      n(0),
      ld(0) {
    //
  }

  ArrayShape(const int m, const int n) :
      m(m),
      n(n),
      ld(m) {
    //
  }

  ArrayShape(const int m, const int n, const int ld) :
      m(m),
      n(n),
      ld(ld) {
    //
  }

  int64_t size() const {
    return int64_t(m)*n;
  }

  int64_t volume() const {
    return int64_t(ld)*n;
  }

  int rows() const {
    return m;
  }

  int columns() const {
    return n;
  }

  int stride() const {
    return ld;
  }

  int width() const {
    return m;
  }

  int height() const {
    return n;
  }

  bool conforms(const ArrayShape<2>& o) const {
    return m == o.m && n == o.n;
  }

  void compact() {
    ld = m;
  }

  /**
   * Compute the 0-based offset to the @p s th element in serial storage
   * order.
   *
   * @param s Serial index, 0-based.
   */
  int64_t offset(const int64_t s) const {
    int64_t j = s/m;
    int64_t i = s - j*m;
    return i + ld*j;
  }

  /**
   * Compute the 0-based offset to the @p t th element in transpose storage
   * order.
   *
   * @param t Transpose index, 0-based.
   */
  int64_t transpose(const int64_t t) const {
    int64_t i = t/n;
    int64_t j = t - i*n;
    return i + ld*j;
  }

  template<class T>
  auto slice(T* buffer, const std::pair<int,int>& rows,
     const std::pair<int,int>& cols) const {
    assert(1 <= rows.first && rows.first <= m && "start of row range out of bounds");
    assert(rows.second <= m && "end of row range out of bounds");
    assert(1 <= cols.first && cols.first <= n && "start of column range out of bounds");
    assert(cols.second <= n && "end of column range out of bounds");

    using U = typename std::remove_const<T>::type;
    U* buf = const_cast<U*>(buffer);

    int i = rows.first;
    int r = std::max(0, rows.second - rows.first + 1);
    int j = cols.first;
    int c = std::max(0, cols.second - cols.first + 1);

    return Array<U,2>(buf + (i - 1) + int64_t(ld)*(j - 1),
        ArrayShape<2>(r, c, ld));
  }

  template<class T>
  auto slice(T* buffer, const std::pair<int,int>& rows, const int j) const {
    assert(1 <= rows.first && rows.first <= m && "start of row range out of bounds");
    assert(rows.second <= m && "end of row range out of bounds");
    assert(1 <= j && j <= n && "column index out of bounds");

    using U = typename std::remove_const<T>::type;
    U* buf = const_cast<U*>(buffer);

    int i = rows.first;
    int r = std::max(0, rows.second - rows.first + 1);

    return Array<U,1>(buf + (i - 1) + int64_t(ld)*(j - 1),
        ArrayShape<1>(r, 1));
  }

  template<class T>
  auto slice(T* buffer, const int i, const std::pair<int,int>& cols) const {
    assert(1 <= i && i <= m && "row index out of bounds");
    assert(1 <= cols.first && cols.first <= n && "start of column range out of bounds");
    assert(cols.second <= n && "end of column range out of bounds");

    using U = typename std::remove_const<T>::type;
    U* buf = const_cast<U*>(buffer);

    int j = cols.first;
    int c = std::max(0, cols.second - cols.first + 1);

    return Array<U,1>(buf + (i - 1) + int64_t(ld)*(j - 1),
        ArrayShape<1>(c, ld));
  }

  template<class T>
  T& slice(T* buffer, const int i, const int j) const {
    assert(1 <= i && i <= m && "row index out of bounds");
    assert(1 <= j && j <= n && "column index out of bounds");
    return buffer[(i - 1) + int64_t(ld)*(j - 1)];
  }

private:
  /**
   * Number of rows.
   */
  int m;

  /**
   * Number of columns.
   */
  int n;

  /**
   * Stride between columns.
   */
  int ld;
};
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: inputbox.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 21:39:07 $
 *
 *  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 _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _SV_DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#include <sbx.hxx>
#include "runtime.hxx"
#pragma hdrstop
#include "stdobj.hxx"
#include "rtlproto.hxx"

class SvRTLInputBox : public ModalDialog
{
    Edit aEdit;
    OKButton aOk;
    CancelButton aCancel;
    FixedText aPromptText;
    String aText;

    void PositionDialog( long nXTwips, long nYTwips, const Size& rDlgSize );
    void InitButtons( const Size& rDlgSize );
    void PositionEdit( const Size& rDlgSize );
    void PositionPrompt( const String& rPrompt, const Size& rDlgSize );
    DECL_LINK( OkHdl, Button * );
    DECL_LINK( CancelHdl, Button * );

public:
    SvRTLInputBox( Window* pParent, const String& rPrompt, const String& rTitle,
        const String& rDefault, long nXTwips = -1, long nYTwips = -1 );
    String GetText() const { return aText; }
};

SvRTLInputBox::SvRTLInputBox( Window* pParent, const String& rPrompt,
        const String& rTitle, const String& rDefault,
        long nXTwips, long nYTwips ) :
    ModalDialog( pParent,WB_3DLOOK | WB_MOVEABLE | WB_CLOSEABLE ),
    aEdit( this,  WB_LEFT | WB_BORDER ),
    aOk( this ), aCancel( this ), aPromptText( this, WB_WORDBREAK )
{
    SetMapMode( MapMode( MAP_APPFONT ) );
    Size aDlgSizeApp( 280, 80 );
    PositionDialog( nXTwips, nYTwips, aDlgSizeApp );
    InitButtons( aDlgSizeApp );
    PositionEdit( aDlgSizeApp );
    PositionPrompt( rPrompt, aDlgSizeApp );
    aOk.Show();
    aCancel.Show();
    aEdit.Show();
    aPromptText.Show();
    SetText( rTitle );
    Font aFont( GetFont());
    Color aColor( GetBackground().GetColor() );
    aFont.SetFillColor( aColor );
    aEdit.SetFont( aFont );
    aEdit.SetText( rDefault );
    aEdit.SetSelection( Selection( SELECTION_MIN, SELECTION_MAX ) );
}

void SvRTLInputBox::InitButtons( const Size& rDlgSize )
{
    aOk.SetSizePixel( LogicToPixel( Size( 45, 15) ));
    aCancel.SetSizePixel( LogicToPixel( Size( 45, 15) ));
    Point aPos( rDlgSize.Width()-45-10, 5 );
    aOk.SetPosPixel( LogicToPixel( Point(aPos) ));
    aPos.Y() += 16;
    aCancel.SetPosPixel( LogicToPixel( Point(aPos) ));
    aOk.SetClickHdl(LINK(this,SvRTLInputBox, OkHdl));
    aCancel.SetClickHdl(LINK(this,SvRTLInputBox,CancelHdl));
}

void SvRTLInputBox::PositionDialog(long nXTwips, long nYTwips, const Size& rDlgSize)
{
    SetSizePixel( LogicToPixel(rDlgSize) );
    if( nXTwips != -1 && nYTwips != -1 )
    {
        Point aDlgPosApp( nXTwips, nYTwips );
        SetPosPixel( LogicToPixel( aDlgPosApp, MAP_TWIP ) );
    }
}

void SvRTLInputBox::PositionEdit( const Size& rDlgSize )
{
    aEdit.SetPosPixel( LogicToPixel( Point( 5,rDlgSize.Height()-35)));
    aEdit.SetSizePixel( LogicToPixel( Size(rDlgSize.Width()-15,12)));
}

void SvRTLInputBox::PositionPrompt(const String& rPrompt,const Size& rDlgSize)
{
    if ( rPrompt.Len() == 0 )
        return;
    String aText( rPrompt );
    aText.ConvertLineEnd( LINEEND_CR );
    aPromptText.SetPosPixel( LogicToPixel(Point(5,5)));
    aPromptText.SetText( aText );
    Size aSize( rDlgSize );
    aSize.Width() -= 70;
    aSize.Height() -= 50;
    aPromptText.SetSizePixel( LogicToPixel(aSize));
}

IMPL_LINK_INLINE_START( SvRTLInputBox, OkHdl, Button *, pButton )
{
    aText = aEdit.GetText();
    EndDialog( 1 );
    return 0;
}
IMPL_LINK_INLINE_END( SvRTLInputBox, OkHdl, Button *, pButton )

IMPL_LINK_INLINE_START( SvRTLInputBox, CancelHdl, Button *, pButton )
{
    aText.Erase();
    EndDialog( 0 );
    return 0;
}
IMPL_LINK_INLINE_END( SvRTLInputBox, CancelHdl, Button *, pButton )

// *********************************************************************
// *********************************************************************
// *********************************************************************

// Syntax: String InputBox( Prompt, [Title], [Default] [, nXpos, nYpos ] )

RTLFUNC(InputBox)
{
    ULONG nArgCount = rPar.Count();
    if ( nArgCount < 2 )
        StarBASIC::Error( SbERR_BAD_ARGUMENT );
    else
    {
        String aTitle;
        String aDefault;
        INT32 nX = -1, nY = -1;  // zentrieren
        const String& rPrompt = rPar.Get(1)->GetString();
        if ( nArgCount > 2 )
            aTitle = rPar.Get(2)->GetString();
        if ( nArgCount > 3 )
            aDefault = rPar.Get(3)->GetString();
        if ( nArgCount > 4 )
        {
            if ( nArgCount != 6 )
            {
                StarBASIC::Error( SbERR_BAD_ARGUMENT );
                return;
            }
            nX = rPar.Get(4)->GetLong();
            nY = rPar.Get(5)->GetLong();
        }
        SvRTLInputBox *pDlg=new SvRTLInputBox(GetpApp()->GetDefDialogParent(),
                    rPrompt,aTitle,aDefault,nX,nY);
        pDlg->Execute();
        rPar.Get(0)->PutString( pDlg->GetText() );
        delete pDlg;
    }
}

<commit_msg>INTEGRATION: CWS ab19 (1.5.40); FILE MERGED 2006/03/03 10:45:10 ab 1.5.40.2: RESYNC: (1.5-1.6); FILE MERGED 2005/07/25 13:18:42 ab 1.5.40.1: #i35478# Check parameter error status for optional parameters<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: inputbox.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2006-04-07 14:02:53 $
 *
 *  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 _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _SV_DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#include <sbx.hxx>
#include "runtime.hxx"
#pragma hdrstop
#include "stdobj.hxx"
#include "rtlproto.hxx"

class SvRTLInputBox : public ModalDialog
{
    Edit aEdit;
    OKButton aOk;
    CancelButton aCancel;
    FixedText aPromptText;
    String aText;

    void PositionDialog( long nXTwips, long nYTwips, const Size& rDlgSize );
    void InitButtons( const Size& rDlgSize );
    void PositionEdit( const Size& rDlgSize );
    void PositionPrompt( const String& rPrompt, const Size& rDlgSize );
    DECL_LINK( OkHdl, Button * );
    DECL_LINK( CancelHdl, Button * );

public:
    SvRTLInputBox( Window* pParent, const String& rPrompt, const String& rTitle,
        const String& rDefault, long nXTwips = -1, long nYTwips = -1 );
    String GetText() const { return aText; }
};

SvRTLInputBox::SvRTLInputBox( Window* pParent, const String& rPrompt,
        const String& rTitle, const String& rDefault,
        long nXTwips, long nYTwips ) :
    ModalDialog( pParent,WB_3DLOOK | WB_MOVEABLE | WB_CLOSEABLE ),
    aEdit( this,  WB_LEFT | WB_BORDER ),
    aOk( this ), aCancel( this ), aPromptText( this, WB_WORDBREAK )
{
    SetMapMode( MapMode( MAP_APPFONT ) );
    Size aDlgSizeApp( 280, 80 );
    PositionDialog( nXTwips, nYTwips, aDlgSizeApp );
    InitButtons( aDlgSizeApp );
    PositionEdit( aDlgSizeApp );
    PositionPrompt( rPrompt, aDlgSizeApp );
    aOk.Show();
    aCancel.Show();
    aEdit.Show();
    aPromptText.Show();
    SetText( rTitle );
    Font aFont( GetFont());
    Color aColor( GetBackground().GetColor() );
    aFont.SetFillColor( aColor );
    aEdit.SetFont( aFont );
    aEdit.SetText( rDefault );
    aEdit.SetSelection( Selection( SELECTION_MIN, SELECTION_MAX ) );
}

void SvRTLInputBox::InitButtons( const Size& rDlgSize )
{
    aOk.SetSizePixel( LogicToPixel( Size( 45, 15) ));
    aCancel.SetSizePixel( LogicToPixel( Size( 45, 15) ));
    Point aPos( rDlgSize.Width()-45-10, 5 );
    aOk.SetPosPixel( LogicToPixel( Point(aPos) ));
    aPos.Y() += 16;
    aCancel.SetPosPixel( LogicToPixel( Point(aPos) ));
    aOk.SetClickHdl(LINK(this,SvRTLInputBox, OkHdl));
    aCancel.SetClickHdl(LINK(this,SvRTLInputBox,CancelHdl));
}

void SvRTLInputBox::PositionDialog(long nXTwips, long nYTwips, const Size& rDlgSize)
{
    SetSizePixel( LogicToPixel(rDlgSize) );
    if( nXTwips != -1 && nYTwips != -1 )
    {
        Point aDlgPosApp( nXTwips, nYTwips );
        SetPosPixel( LogicToPixel( aDlgPosApp, MAP_TWIP ) );
    }
}

void SvRTLInputBox::PositionEdit( const Size& rDlgSize )
{
    aEdit.SetPosPixel( LogicToPixel( Point( 5,rDlgSize.Height()-35)));
    aEdit.SetSizePixel( LogicToPixel( Size(rDlgSize.Width()-15,12)));
}

void SvRTLInputBox::PositionPrompt(const String& rPrompt,const Size& rDlgSize)
{
    if ( rPrompt.Len() == 0 )
        return;
    String aText( rPrompt );
    aText.ConvertLineEnd( LINEEND_CR );
    aPromptText.SetPosPixel( LogicToPixel(Point(5,5)));
    aPromptText.SetText( aText );
    Size aSize( rDlgSize );
    aSize.Width() -= 70;
    aSize.Height() -= 50;
    aPromptText.SetSizePixel( LogicToPixel(aSize));
}

IMPL_LINK_INLINE_START( SvRTLInputBox, OkHdl, Button *, pButton )
{
    aText = aEdit.GetText();
    EndDialog( 1 );
    return 0;
}
IMPL_LINK_INLINE_END( SvRTLInputBox, OkHdl, Button *, pButton )

IMPL_LINK_INLINE_START( SvRTLInputBox, CancelHdl, Button *, pButton )
{
    aText.Erase();
    EndDialog( 0 );
    return 0;
}
IMPL_LINK_INLINE_END( SvRTLInputBox, CancelHdl, Button *, pButton )

// *********************************************************************
// *********************************************************************
// *********************************************************************

// Syntax: String InputBox( Prompt, [Title], [Default] [, nXpos, nYpos ] )

RTLFUNC(InputBox)
{
    ULONG nArgCount = rPar.Count();
    if ( nArgCount < 2 )
        StarBASIC::Error( SbERR_BAD_ARGUMENT );
    else
    {
        String aTitle;
        String aDefault;
        INT32 nX = -1, nY = -1;  // zentrieren
        const String& rPrompt = rPar.Get(1)->GetString();
        if ( nArgCount > 2 && !rPar.Get(2)->IsErr() )
            aTitle = rPar.Get(2)->GetString();
        if ( nArgCount > 3 && !rPar.Get(3)->IsErr() )
            aDefault = rPar.Get(3)->GetString();
        if ( nArgCount > 4 )
        {
            if ( nArgCount != 6 )
            {
                StarBASIC::Error( SbERR_BAD_ARGUMENT );
                return;
            }
            nX = rPar.Get(4)->GetLong();
            nY = rPar.Get(5)->GetLong();
        }
        SvRTLInputBox *pDlg=new SvRTLInputBox(GetpApp()->GetDefDialogParent(),
                    rPrompt,aTitle,aDefault,nX,nY);
        pDlg->Execute();
        rPar.Get(0)->PutString( pDlg->GetText() );
        delete pDlg;
    }
}

<|endoftext|>


<commit_before>#include "mrmc.h"
#include "sparfun_util.h"
#include "tsqr_util.h"

void SerialTSQR::collect(typedbytes_opaque& key, std::vector<double>& value) {
  add_row(value);
  if (num_local_rows_ >= num_rows_) {
    hadoop_message("about to compress\n");
    compress();
    hadoop_message("compress appears successful\n");
    hadoop_counter("compress", 1);
  }
}

// compress the local QR factorization
void SerialTSQR::compress() {
  // compute a QR factorization
  double t0 = sf_time();
  if (lapack_qr(&local_matrix_[0], num_rows_, num_cols_, num_local_rows_)) {
    double dt = sf_time() - t0;
    hadoop_counter("lapack time (millisecs)", (int) (dt * 1000.));
  } else {
    hadoop_error("lapack error\n");
  }
  if (num_cols_ < num_local_rows_) {
    num_local_rows_ = num_cols_;
  }
}

// Output the matrix with random keys for the rows.
void SerialTSQR::output() {
  compress();
  for (size_t i = 0; i < num_local_rows_; ++i) {
    int rand_int = sf_randint(0, 2000000000);
    out_.write_int(rand_int);
    out_.write_list_start();
    for (size_t j = 0; j < num_cols_; ++j) {
      out_.write_double(local_matrix_[i + j * num_rows_]);
    }
    out_.write_list_end();
  }
}
<commit_msg>handle the case where no data is passed to the task<commit_after>#include "mrmc.h"
#include "sparfun_util.h"
#include "tsqr_util.h"

void SerialTSQR::collect(typedbytes_opaque& key, std::vector<double>& value) {
  add_row(value);
  if (num_local_rows_ >= num_rows_) {
    hadoop_message("about to compress\n");
    compress();
    hadoop_message("compress appears successful\n");
    hadoop_counter("compress", 1);
  }
}

// compress the local QR factorization
void SerialTSQR::compress() {
  // compute a QR factorization
  double t0 = sf_time();
  if (lapack_qr(&local_matrix_[0], num_rows_, num_cols_, num_local_rows_)) {
    double dt = sf_time() - t0;
    hadoop_counter("lapack time (millisecs)", (int) (dt * 1000.));
  } else {
    hadoop_error("lapack error\n");
  }
  if (num_cols_ < num_local_rows_) {
    num_local_rows_ = num_cols_;
  }
}

// Output the matrix with random keys for the rows.
void SerialTSQR::output() {
  if (num_cols_ == 0) {
    // no data was received on this task
    return;
  }
  compress();
  for (size_t i = 0; i < num_local_rows_; ++i) {
    int rand_int = sf_randint(0, 2000000000);
    out_.write_int(rand_int);
    out_.write_list_start();
    for (size_t j = 0; j < num_cols_; ++j) {
      out_.write_double(local_matrix_[i + j * num_rows_]);
    }
    out_.write_list_end();
  }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <algorithm>

#include "randgen.h"

using namespace std;

double randgen(char rand_type, double para1, double para2)
{
  switch (rand_type)
    {
    case 'U':
      {
	boost::random::uniform_01<boost::mt19937 &> zeroone(rng);
	return zeroone();
	break;
      }
    case 'N':
      {
	double mean = para1;
	double std_dev = para2;
	boost::normal_distribution<> nd(mean,std_dev);
	boost::variate_generator<boost::mt19937 &,boost::normal_distribution<> > norm_rnd(rng,nd);
	return norm_rnd();
	break;
      }
    case 'P':
      {
	double lambda = (para1 == 0? para2:para1);
	boost::poisson_distribution<> pd(lambda);
	boost::variate_generator<boost::mt19937 &,boost::poisson_distribution<> > poisson_rnd(rng,pd);
	return poisson_rnd();
	break;
      }
    case 'E':
      {
	double lambda = (para1 == 0? para2:para1);
	boost::exponential_distribution<> expd(lambda);
	boost::variate_generator<boost::mt19937 &,boost::exponential_distribution<> > exp_rnd(rng,expd);
	return exp_rnd();
	break;
      }
    default:
	  return -9999.0;
      break;
    }

	// EJF -- return dummy value to avoid warning
    return -9999.0;
}
<commit_msg>Remove consecutive `break`s after `return`s<commit_after>#include <iostream>
#include <vector>
#include <algorithm>

#include "randgen.h"

using namespace std;

double randgen(char rand_type, double para1, double para2)
{
  switch (rand_type)
    {
    case 'U':
      {
	boost::random::uniform_01<boost::mt19937 &> zeroone(rng);
	return zeroone();
      }
    case 'N':
      {
	double mean = para1;
	double std_dev = para2;
	boost::normal_distribution<> nd(mean,std_dev);
	boost::variate_generator<boost::mt19937 &,boost::normal_distribution<> > norm_rnd(rng,nd);
	return norm_rnd();
      }
    case 'P':
      {
	double lambda = (para1 == 0? para2:para1);
	boost::poisson_distribution<> pd(lambda);
	boost::variate_generator<boost::mt19937 &,boost::poisson_distribution<> > poisson_rnd(rng,pd);
	return poisson_rnd();
      }
    case 'E':
      {
	double lambda = (para1 == 0? para2:para1);
	boost::exponential_distribution<> expd(lambda);
	boost::variate_generator<boost::mt19937 &,boost::exponential_distribution<> > exp_rnd(rng,expd);
	return exp_rnd();
      }
    default:
	  return -9999.0;
    }

	// EJF -- return dummy value to avoid warning
    return -9999.0;
}
<|endoftext|>


<commit_before>#include "GUI.hpp"
#include "globals.hpp"
GUI::GUI()
{
	timeSprite = new sf::Sprite();
	timeSprite->setTexture(textureManager.timeBarTexture);
	timeSprite->setPosition(10, gridHeight-20);

	coinSprite = new sf::Sprite();
	coinSprite->setTexture(textureManager.itemsTexture);
	coinSprite->setTextureRect(sf::IntRect(0,80,16,16));

	keySprite = new sf::Sprite();
	keySprite->setTexture(textureManager.itemsTexture);
	keySprite->setTextureRect(sf::IntRect(0,32,16,16));

	timeoutClock = sf::Clock();
	timeoutClock.restart();
	coins=0;
	keys=0;
	pauseOffset = 0;
	loosed = false;
	lastEnable = false;
	smallTime = false;
	buffFactor = 20;
}
void GUI::setTimeout(int seconds)
{
	timeoutClock.restart();
	timeoutSeconds = seconds;
	timeBuff = 0;
}
void GUI::setTimebuffFactor(float factor)
{
	buffFactor = factor;
}
void GUI::applyTimeBufff(float seconds)
{
	timeBuff += seconds*buffFactor;
}
float GUI::timeLeft()
{
	float elapsedSeconds = (timeoutClock.getElapsedTime().asSeconds()+timeBuff+pauseOffset);
	float timeLeft = timeoutSeconds - elapsedSeconds;
	return timeLeft < 0 ? 0 : timeLeft;
}

void GUI::update (sf::Time deltaTime) {
	if (sceneManager.getCurrentScene().textBox->enabled()){
		if (!lastEnable)
		{
			pauseOffset += timeoutClock.getElapsedTime().asSeconds();
		}
		timeoutClock.restart();
		lastEnable = true;
	}
	else
	{
		lastEnable = false;
	}
	sf::Int32 currTime = globalClock.getElapsedTime().asMilliseconds();
	float elapsedSeconds = (timeoutClock.getElapsedTime().asSeconds()+timeBuff+pauseOffset);
	float progress = 1 - (elapsedSeconds / timeoutSeconds);
	//TODO: use min, max
	if (progress > 1)
	{
		progress = 1;
	}
	if (progress <= 0)
	{
		progress = 0;
		if (!loosed){
			sceneManager.getCurrentScene().textBox->triggerText("loose");
		}
		loosed = true;
		if (!sceneManager.getCurrentScene().textBox->enabled())
		{
			sceneManager.restartLevel();
		}
	}
	if (progress < 0.3)
	{
		if (!smallTime)
		{
			sceneManager.getCurrentScene().textBox->triggerText("smalltime");
		}
		smallTime = true;
	}
	int height = (1 - progress) * (gridHeight);
	timeSprite->setPosition(-15 , height);
	timeSprite->setTextureRect(sf::IntRect(0, int(elapsedSeconds) % 45 + 2 * height, 10, gridHeight - height));
	window.draw(*timeSprite);

	for (int i = 0;i < coins;i++)
	{
		//TODO: Draw coins
		coinSprite->setPosition(gridWidth, - i * 16);
		window.draw(*coinSprite);
	}

	for (int i = 0;i < keys;i++)
	{
		//TODO: Draw coins
		keySprite->setPosition(gridWidth, gridHeight - 42 + i*16);
		window.draw(*keySprite);
	}
}

void GUI::resetCoins()
{
	coins = 0;
}

void GUI::addCoins(int amount)
{
	coins += amount;
}

void GUI::resetKeys()
{
	keys = 0;
}

void GUI::addKeys(int amount)
{
	keys += amount;
}
<commit_msg>sound wenn Zeit knapp<commit_after>#include "GUI.hpp"
#include "globals.hpp"
GUI::GUI()
{
	timeSprite = new sf::Sprite();
	timeSprite->setTexture(textureManager.timeBarTexture);
	timeSprite->setPosition(10, gridHeight-20);

	coinSprite = new sf::Sprite();
	coinSprite->setTexture(textureManager.itemsTexture);
	coinSprite->setTextureRect(sf::IntRect(0,80,16,16));

	keySprite = new sf::Sprite();
	keySprite->setTexture(textureManager.itemsTexture);
	keySprite->setTextureRect(sf::IntRect(0,32,16,16));

	timeoutClock = sf::Clock();
	timeoutClock.restart();
	coins=0;
	keys=0;
	pauseOffset = 0;
	loosed = false;
	lastEnable = false;
	smallTime = false;
	buffFactor = 20;
}
void GUI::setTimeout(int seconds)
{
	timeoutClock.restart();
	timeoutSeconds = seconds;
	timeBuff = 0;
}
void GUI::setTimebuffFactor(float factor)
{
	buffFactor = factor;
}
void GUI::applyTimeBufff(float seconds)
{
	timeBuff += seconds*buffFactor;
}
float GUI::timeLeft()
{
	float elapsedSeconds = (timeoutClock.getElapsedTime().asSeconds()+timeBuff+pauseOffset);
	float timeLeft = timeoutSeconds - elapsedSeconds;
	return timeLeft < 0 ? 0 : timeLeft;
}

void GUI::update (sf::Time deltaTime) {
	if (sceneManager.getCurrentScene().textBox->enabled()){
		if (!lastEnable)
		{
			pauseOffset += timeoutClock.getElapsedTime().asSeconds();
		}
		timeoutClock.restart();
		lastEnable = true;
	}
	else
	{
		lastEnable = false;
	}
	sf::Int32 currTime = globalClock.getElapsedTime().asMilliseconds();
	float elapsedSeconds = (timeoutClock.getElapsedTime().asSeconds()+timeBuff+pauseOffset);
	float progress = 1 - (elapsedSeconds / timeoutSeconds);
	if (progress < 0.3 && progress > 0.28) {
		soundManager.playSound("sound/timeShort.ogg");
	}
	//TODO: use min, max
	if (progress > 1)
	{
		progress = 1;
	}
	if (progress <= 0)
	{
		progress = 0;
		if (!loosed){
			sceneManager.getCurrentScene().textBox->triggerText("loose");
		}
		loosed = true;
		if (!sceneManager.getCurrentScene().textBox->enabled())
		{
			sceneManager.restartLevel();
		}
	}
	if (progress < 0.3)
	{
		if (!smallTime)
		{
			sceneManager.getCurrentScene().textBox->triggerText("smalltime");
		}
		smallTime = true;
	}
	int height = (1 - progress) * (gridHeight);
	timeSprite->setPosition(-15 , height);
	timeSprite->setTextureRect(sf::IntRect(0, int(elapsedSeconds) % 45 + 2 * height, 10, gridHeight - height));
	window.draw(*timeSprite);

	for (int i = 0;i < coins;i++)
	{
		//TODO: Draw coins
		coinSprite->setPosition(gridWidth, - i * 16);
		window.draw(*coinSprite);
	}

	for (int i = 0;i < keys;i++)
	{
		//TODO: Draw coins
		keySprite->setPosition(gridWidth, gridHeight - 42 + i*16);
		window.draw(*keySprite);
	}
}

void GUI::resetCoins()
{
	coins = 0;
}

void GUI::addCoins(int amount)
{
	coins += amount;
}

void GUI::resetKeys()
{
	keys = 0;
}

void GUI::addKeys(int amount)
{
	keys += amount;
}
<|endoftext|>