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

#ifndef SC_XCLIMPCHANGETRACK_HXX
#define SC_XCLIMPCHANGETRACK_HXX

#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif

#ifndef SC_XLTOOLS_HXX
#include "xltools.hxx"
#endif
#ifndef SC_XISTREAM_HXX
#include "xistream.hxx"
#endif
#ifndef _EXCFORM_HXX
#include "excform.hxx"
#endif
#ifndef _FLTTOOLS_HXX
#include "flttools.hxx"
#endif
#ifndef _IMP_OP_HXX
#include "imp_op.hxx"
#endif
#ifndef _ROOT_HXX
#include "root.hxx"
#endif

//___________________________________________________________________

class ScBaseCell;
class ScChangeAction;
class ScChangeTrack;
class XclImpChTrFmlConverter;

//___________________________________________________________________

struct XclImpChTrRecHeader
{
    sal_uInt32                  nSize;
    sal_uInt32                  nIndex;
    sal_uInt16                  nOpCode;
    sal_uInt16                  nAccept;
};

inline XclImpStream& operator>>( XclImpStream& rStrm, XclImpChTrRecHeader& rRecHeader )
{
    rStrm >> rRecHeader.nSize >> rRecHeader.nIndex >> rRecHeader.nOpCode >> rRecHeader.nAccept;
    return rStrm;
}

//___________________________________________________________________

class XclImpChangeTrack : protected ExcRoot
{
private:
    XclImpChTrRecHeader         aRecHeader;
    String                      sOldUsername;

    ScChangeTrack*              pChangeTrack;
    SotStorageStreamRef          xInStrm;        // input stream
    XclImpStream*               pStrm;          // stream import class
    sal_uInt16                  nTabIdCount;
    sal_Bool                    bGlobExit;      // global exit loop

    enum { nmBase, nmFound, nmNested }
                                eNestedMode;    // action with nested content actions

    inline sal_Bool             FoundNestedMode() { return eNestedMode == nmFound; }

    void                        DoAcceptRejectAction( ScChangeAction* pAction );
    void                        DoAcceptRejectAction( sal_uInt32 nFirst, sal_uInt32 nLast );

    void                        DoInsertRange( const ScRange& rRange );
    void                        DoDeleteRange( const ScRange& rRange );

    inline sal_uInt8            LookAtuInt8();
    inline double               ReadRK();
    inline sal_Bool             ReadBool();
    inline void                 Read2DAddress( ScAddress& rAddress );
    inline void                 Read2DRange( ScRange& rRange );
    SCTAB                       ReadTabNum();
    void                        ReadDateTime( DateTime& rDateTime );

    inline void                 ReadString( String& rString );
    inline void                 IgnoreString();

    sal_Bool                    CheckRecord( sal_uInt16 nOpCode );

    void                        ReadFormula(
                                    ScTokenArray*& rpTokenArray,
                                    const ScAddress& rPosition );
    void                        ReadCell(
                                    ScBaseCell*& rpCell,
                                    sal_uInt32& rFormat,
                                    sal_uInt16 nFlags,
                                    const ScAddress& rPosition );

    void                        ReadChTrInsert();           // 0x0137
    void                        ReadChTrInfo();             // 0x0138
    void                        ReadChTrCellContent();      // 0x013B
    void                        ReadChTrTabId();            // 0x013D
    void                        ReadChTrMoveRange();        // 0x0140
    void                        ReadChTrInsertTab();        // 0x014D
    void                        InitNestedMode();           // 0x014E, 0x0150
    void                        ReadNestedRecords();
    sal_Bool                    EndNestedMode();            // 0x014F, 0x0151

    void                        ReadRecords();

public:
                                XclImpChangeTrack( RootData* pRootData, const XclImpStream& rBookStrm );
                                ~XclImpChangeTrack();

                                // reads extended 3D ref info following the formulas, returns sc tab nums
                                // ( called by XclImpChTrFmlConverter::Read3DTabReference() )
    sal_Bool                    Read3DTabRefInfo( SCTAB& rFirstTab, SCTAB& rLastTab );

    void                        Apply();
};

inline sal_uInt8 XclImpChangeTrack::LookAtuInt8()
{
    pStrm->PushPosition();
    sal_uInt8 nValue;
    *pStrm >> nValue;
    pStrm->PopPosition();
    return nValue;
}

inline double XclImpChangeTrack::ReadRK()
{
    return XclTools::GetDoubleFromRK( pStrm->ReadInt32() );
}

inline sal_Bool XclImpChangeTrack::ReadBool()
{
    return (pStrm->ReaduInt16() != 0);
}

inline void XclImpChangeTrack::Read2DAddress( ScAddress& rAddress )
{
    rAddress.SetRow( static_cast<SCROW>(pStrm->ReaduInt16()) );
    rAddress.SetCol( static_cast<SCCOL>(pStrm->ReaduInt16()) );
}

inline void XclImpChangeTrack::Read2DRange( ScRange& rRange )
{
    rRange.aStart.SetRow( static_cast<SCROW>(pStrm->ReaduInt16()) );
    rRange.aEnd.SetRow( static_cast<SCROW>(pStrm->ReaduInt16()) );
    rRange.aStart.SetCol( static_cast<SCCOL>(pStrm->ReaduInt16()) );
    rRange.aEnd.SetCol( static_cast<SCCOL>(pStrm->ReaduInt16()) );
}

inline void XclImpChangeTrack::ReadString( String& rString )
{
    rString = pStrm->ReadUniString();
}

inline void XclImpChangeTrack::IgnoreString()
{
    pStrm->IgnoreUniString();
}

//___________________________________________________________________
// derived class for special 3D ref handling

class XclImpChTrFmlConverter : public ExcelToSc8
{
private:
    XclImpChangeTrack&          rChangeTrack;

    virtual BOOL                Read3DTabReference( SCTAB& rFirstTab, SCTAB& rLastTab );

public:
    inline                      XclImpChTrFmlConverter(
                                    XclImpStream& rStrm,
                                    XclImpChangeTrack& rXclChTr );
    virtual                     ~XclImpChTrFmlConverter();
};

inline XclImpChTrFmlConverter::XclImpChTrFmlConverter(
        XclImpStream& rStrm,
        XclImpChangeTrack& rXclChTr ) :
    ExcelToSc8( rStrm ),
    rChangeTrack( rXclChTr )
{
}

//___________________________________________________________________

#endif

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

#ifndef SC_XCLIMPCHANGETRACK_HXX
#define SC_XCLIMPCHANGETRACK_HXX

#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif

#ifndef SC_XIROOT_HXX
#include "xiroot.hxx"
#endif
#ifndef SC_XISTREAM_HXX
#include "xistream.hxx"
#endif

#ifndef _EXCFORM_HXX
#include "excform.hxx"
#endif
#ifndef _IMP_OP_HXX
#include "imp_op.hxx"
#endif

//___________________________________________________________________

class ScBaseCell;
class ScChangeAction;
class ScChangeTrack;
class XclImpChTrFmlConverter;

//___________________________________________________________________

struct XclImpChTrRecHeader
{
    sal_uInt32                  nSize;
    sal_uInt32                  nIndex;
    sal_uInt16                  nOpCode;
    sal_uInt16                  nAccept;
};

inline XclImpStream& operator>>( XclImpStream& rStrm, XclImpChTrRecHeader& rRecHeader )
{
    rStrm >> rRecHeader.nSize >> rRecHeader.nIndex >> rRecHeader.nOpCode >> rRecHeader.nAccept;
    return rStrm;
}

//___________________________________________________________________

class XclImpChangeTrack : protected XclImpRoot
{
private:
    XclImpChTrRecHeader         aRecHeader;
    String                      sOldUsername;

    ScChangeTrack*              pChangeTrack;
    SotStorageStreamRef          xInStrm;        // input stream
    XclImpStream*               pStrm;          // stream import class
    sal_uInt16                  nTabIdCount;
    sal_Bool                    bGlobExit;      // global exit loop

    enum { nmBase, nmFound, nmNested }
                                eNestedMode;    // action with nested content actions

    inline sal_Bool             FoundNestedMode() { return eNestedMode == nmFound; }

    void                        DoAcceptRejectAction( ScChangeAction* pAction );
    void                        DoAcceptRejectAction( sal_uInt32 nFirst, sal_uInt32 nLast );

    void                        DoInsertRange( const ScRange& rRange );
    void                        DoDeleteRange( const ScRange& rRange );

    inline sal_uInt8            LookAtuInt8();
    inline double               ReadRK();
    inline sal_Bool             ReadBool();
    inline void                 Read2DAddress( ScAddress& rAddress );
    inline void                 Read2DRange( ScRange& rRange );
    SCTAB                       ReadTabNum();
    void                        ReadDateTime( DateTime& rDateTime );

    inline void                 ReadString( String& rString );
    inline void                 IgnoreString();

    sal_Bool                    CheckRecord( sal_uInt16 nOpCode );

    void                        ReadFormula(
                                    ScTokenArray*& rpTokenArray,
                                    const ScAddress& rPosition );
    void                        ReadCell(
                                    ScBaseCell*& rpCell,
                                    sal_uInt32& rFormat,
                                    sal_uInt16 nFlags,
                                    const ScAddress& rPosition );

    void                        ReadChTrInsert();           // 0x0137
    void                        ReadChTrInfo();             // 0x0138
    void                        ReadChTrCellContent();      // 0x013B
    void                        ReadChTrTabId();            // 0x013D
    void                        ReadChTrMoveRange();        // 0x0140
    void                        ReadChTrInsertTab();        // 0x014D
    void                        InitNestedMode();           // 0x014E, 0x0150
    void                        ReadNestedRecords();
    sal_Bool                    EndNestedMode();            // 0x014F, 0x0151

    void                        ReadRecords();

public:
                                XclImpChangeTrack( const XclImpRoot& rRoot, const XclImpStream& rBookStrm );
                                ~XclImpChangeTrack();

                                // reads extended 3D ref info following the formulas, returns sc tab nums
                                // ( called by XclImpChTrFmlConverter::Read3DTabReference() )
    sal_Bool                    Read3DTabRefInfo( SCTAB& rFirstTab, SCTAB& rLastTab );

    void                        Apply();
};

inline sal_uInt8 XclImpChangeTrack::LookAtuInt8()
{
    pStrm->PushPosition();
    sal_uInt8 nValue;
    *pStrm >> nValue;
    pStrm->PopPosition();
    return nValue;
}

inline double XclImpChangeTrack::ReadRK()
{
    return XclTools::GetDoubleFromRK( pStrm->ReadInt32() );
}

inline sal_Bool XclImpChangeTrack::ReadBool()
{
    return (pStrm->ReaduInt16() != 0);
}

inline void XclImpChangeTrack::Read2DAddress( ScAddress& rAddress )
{
    rAddress.SetRow( static_cast<SCROW>(pStrm->ReaduInt16()) );
    rAddress.SetCol( static_cast<SCCOL>(pStrm->ReaduInt16()) );
}

inline void XclImpChangeTrack::Read2DRange( ScRange& rRange )
{
    rRange.aStart.SetRow( static_cast<SCROW>(pStrm->ReaduInt16()) );
    rRange.aEnd.SetRow( static_cast<SCROW>(pStrm->ReaduInt16()) );
    rRange.aStart.SetCol( static_cast<SCCOL>(pStrm->ReaduInt16()) );
    rRange.aEnd.SetCol( static_cast<SCCOL>(pStrm->ReaduInt16()) );
}

inline void XclImpChangeTrack::ReadString( String& rString )
{
    rString = pStrm->ReadUniString();
}

inline void XclImpChangeTrack::IgnoreString()
{
    pStrm->IgnoreUniString();
}

//___________________________________________________________________
// derived class for special 3D ref handling

class XclImpChTrFmlConverter : public ExcelToSc8
{
private:
    XclImpChangeTrack&          rChangeTrack;

    virtual BOOL                Read3DTabReference( SCTAB& rFirstTab, SCTAB& rLastTab );

public:
    inline                      XclImpChTrFmlConverter(
                                    XclImpStream& rStrm,
                                    XclImpChangeTrack& rXclChTr );
    virtual                     ~XclImpChTrFmlConverter();
};

inline XclImpChTrFmlConverter::XclImpChTrFmlConverter(
        XclImpStream& rStrm,
        XclImpChangeTrack& rXclChTr ) :
    ExcelToSc8( rStrm ),
    rChangeTrack( rXclChTr )
{
}

//___________________________________________________________________

#endif

<|endoftext|>


<commit_before>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under both the Apache 2.0 license (found in the
 *  LICENSE file in the root directory of this source tree) and the GPLv2 (found
 *  in the COPYING file in the root directory of this source tree).
 *  You may select, at your option, one of the above-listed licenses.
 */

// Sanity check integration test for os_version
// Spec file: specs/os_version.table

#include <osquery/tests/integration/tables/helper.h>

namespace osquery {
namespace table_tests {

class OsVersion : public testing::Test {
  protected:
    void SetUp() override {
      setUpEnvironment();
    }
};

TEST_F(OsVersion, test_sanity) {
  QueryData data = execute_query("select * from os_version");

  ASSERT_EQ(data.size(), 1ul);

  ValidatatioMap row_map = {
      {"name", NonEmptyString},
      {"version", NonEmptyString},
      {"major", NonNegativeInt},
      {"minor", NonNegativeInt},
      {"patch", NonNegativeInt},
      {"build", NormalType},
      {"platform", NonEmptyString},
      {"platform_like", NonEmptyString},
      {"codename", NormalType},
#ifdef OSQUERY_WINDOWS
      {"installdate", NonEmptyString},
#endif
  };
  validate_rows(data, row_map);
}

} // namespace table_tests
} // namespace osquery
<commit_msg>Fix up os_version table integration test<commit_after>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under both the Apache 2.0 license (found in the
 *  LICENSE file in the root directory of this source tree) and the GPLv2 (found
 *  in the COPYING file in the root directory of this source tree).
 *  You may select, at your option, one of the above-listed licenses.
 */

// Sanity check integration test for os_version
// Spec file: specs/os_version.table

#include <osquery/tests/integration/tables/helper.h>

namespace osquery {
namespace table_tests {

class OsVersion : public testing::Test {
  protected:
    void SetUp() override {
      setUpEnvironment();
    }
};

TEST_F(OsVersion, test_sanity) {
  QueryData data = execute_query("select * from os_version");

  ASSERT_EQ(data.size(), 1ul);

  ValidatatioMap row_map = {
      {"name", NonEmptyString},
      {"version", NonEmptyString},
      {"major", NonNegativeInt},
      {"minor", NonNegativeInt},
      {"patch", NormalType},
      {"build", NormalType},
      {"platform", NonEmptyString},
      {"platform_like", NonEmptyString},
      {"codename", NormalType},
#ifdef OSQUERY_WINDOWS
      {"install_date", NonEmptyString},
#endif
  };
  validate_rows(data, row_map);
}

} // namespace table_tests
} // namespace osquery
<|endoftext|>


<commit_before>#ifdef BABYLON_BUILD_SANDBOX

// Adapted from RuntimeCompiledCPlusPlus/Aurora/Examples/ConsoleExample/ConsoleGame.cpp
#include <SamplesRunner/rtc/suppress_warnings.h>
#include <SamplesRunner/rtc/rtc_manager.h>
#include <SamplesRunner/rtc/log_system.h>

#include <RuntimeCompiler/AUArray.h>
#include <RuntimeCompiler/BuildTool.h>
#include <RuntimeCompiler/ICompilerLogger.h>
#include <RuntimeCompiler/FileChangeNotifier.h>
#include <RuntimeObjectSystem/IObjectFactorySystem.h>
#include <RuntimeObjectSystem/ObjectFactorySystem/ObjectFactorySystem.h>
#include <RuntimeObjectSystem/RuntimeObjectSystem.h>
#include <RuntimeObjectSystem/IObject.h>

#include <SamplesRunner/rtc/iscene_producer.h>
#include <SamplesRunner/rtc/interface_ids.h>
#include <babylon/core/system.h>
#include <babylon/core/filesystem.h>

#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <string>
#include <stdarg.h>

// Remove windows.h define of GetObject which conflicts with EntitySystem GetObject
#if defined _WINDOWS_ && defined GetObject
#undef GetObject
#endif
using FileSystemUtils::Path;

namespace BABYLON {
namespace rtc {

RtcManager::RtcManager()
	: _compilerLogger(0)
	, _runtimeObjectSystem(0)
	, _sceneProducer(0)
{
}

RtcManager::~RtcManager()
{
    if( _runtimeObjectSystem )
    {
        // clean temp object files
        _runtimeObjectSystem->CleanObjectFiles();
    }

    if( _runtimeObjectSystem && _runtimeObjectSystem->GetObjectFactorySystem() )
    {
        _runtimeObjectSystem->GetObjectFactorySystem()->RemoveListener(this);

        // delete object via correct interface
        IObject* pObj = _runtimeObjectSystem->GetObjectFactorySystem()->GetObject( _objectId );
        delete pObj;
    }

	delete _runtimeObjectSystem;
	delete _compilerLogger;
}

bool RtcManager::Init()
{
	//Initialise the RuntimeObjectSystem
	_runtimeObjectSystem = new RuntimeObjectSystem;
	_compilerLogger = new LogSystem();
	if( !_runtimeObjectSystem->Initialise(_compilerLogger, 0) )
    {
        _runtimeObjectSystem = 0;
        return false;
    }
	_runtimeObjectSystem->GetObjectFactorySystem()->AddListener(this);

  SetIncludePath();
  SetCompileOptions();
  SetLibraryPath();

	// construct first object
	IObjectConstructor* pCtor = _runtimeObjectSystem->GetObjectFactorySystem()->GetConstructor( "Sandbox" );
	if( pCtor )
	{
		IObject* pObj = pCtor->Construct();
		pObj->GetInterface( &_sceneProducer );
		if( 0 == _sceneProducer )
		{
			delete pObj;
			_compilerLogger->LogError("Error - no updateable interface found\n");
			return false;
		}
		_objectId = pObj->GetObjectId();

	}

	return true;
}

void RtcManager::SetCompileOptions()
{
#ifdef _MSC_VER
  _runtimeObjectSystem->SetAdditionalCompileOptions("/std:c++17 /DBABYLON_BUILD_SANDBOX");
#else
  _runtimeObjectSystem->SetAdditionalCompileOptions("-DBABYLON_BUILD_SANDBOX");
#endif // _MSC_VER
}

void RtcManager::SetLibraryPath()
{
  std::string exePath = BABYLON::System::getExecutablePath();
  std::string exeFolder = BABYLON::Filesystem::baseDir(exePath);

  std::string libPath = BABYLON::Filesystem::absolutePath(exeFolder + "/../lib");
  _runtimeObjectSystem->AddLibraryDir(libPath.c_str());
}

void RtcManager::SetIncludePath()
{
  FileSystemUtils::Path basePath = _runtimeObjectSystem->FindFile(__FILE__);
  FileSystemUtils::Path repoPath = basePath.ParentPath().ParentPath().ParentPath().ParentPath();
  FileSystemUtils::Path repoSrcPath = basePath.ParentPath().ParentPath().ParentPath().ParentPath() / "src";
  FileSystemUtils::Path repoExternalPath = basePath.ParentPath().ParentPath().ParentPath().ParentPath() / "external";
  _runtimeObjectSystem->AddIncludeDir(repoSrcPath.c_str());
  _runtimeObjectSystem->AddIncludeDir((repoExternalPath / "RuntimeCompiledCPlusPlus/Aurora").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoExternalPath / "imgui").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoExternalPath / "json.hpp").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoExternalPath / "glad/include").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoSrcPath / "BabylonCpp/include").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoSrcPath / "BabylonImGui/include").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoSrcPath / "MaterialsLibrary/include").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoSrcPath / "ProceduralTexturesLibrary/include").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoSrcPath / "Loaders/include").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoSrcPath / "imgui_utils").c_str());

  std::string exePath = BABYLON::System::getExecutablePath();
  std::string exeFolder = BABYLON::Filesystem::baseDir(exePath);
  std::string apiPath = BABYLON::Filesystem::absolutePath(exeFolder + "/../../src/BabylonCpp/include");
  _runtimeObjectSystem->AddIncludeDir(apiPath.c_str());
}

void RtcManager::OnConstructorsAdded()
{
	// This could have resulted in a change of object pointer, so release old and get new one.
	if( _sceneProducer )
	{
		IObject* pObj = _runtimeObjectSystem->GetObjectFactorySystem()->GetObject( _objectId );
		pObj->GetInterface( &_sceneProducer );
    _lastCompiledScene = _sceneProducer->MakeScene();
		if( 0 == _sceneProducer )
		{
			delete pObj;
			_compilerLogger->LogError( "Error - no updateable interface found\n");
		}
	}
}

BABYLON::SandboxCompilerStatus RtcManager::Heartbeat()
{
	//check status of any compile
	if( _runtimeObjectSystem->GetIsCompiledComplete() )
	{
		// load module when compile complete
		_runtimeObjectSystem->LoadCompiledModule();
	}

	if(_runtimeObjectSystem->GetIsCompiling() )
	{
    BABYLON::SandboxCompilerStatus r;
    r._isCompiling = true;
    return r;
	}
  else
  {
    const float deltaTime = 1.0f;
    _runtimeObjectSystem->GetFileChangeNotifier()->Update(deltaTime);
    _sceneProducer->Update(deltaTime);
  }

  if (_lastCompiledScene)
  {
    BABYLON::SandboxCompilerStatus r;
    r._renderableScene = _lastCompiledScene;
    _lastCompiledScene.reset();
    return r;
  }
  return BABYLON::SandboxCompilerStatus();
}

} // namespace BABYLON
} // namespace rtc

#endif // BABYLON_BUILD_SANDBOX
<commit_msg>rtc_mamager : std=c++17 on linux<commit_after>#ifdef BABYLON_BUILD_SANDBOX

// Adapted from RuntimeCompiledCPlusPlus/Aurora/Examples/ConsoleExample/ConsoleGame.cpp
#include <SamplesRunner/rtc/suppress_warnings.h>
#include <SamplesRunner/rtc/rtc_manager.h>
#include <SamplesRunner/rtc/log_system.h>

#include <RuntimeCompiler/AUArray.h>
#include <RuntimeCompiler/BuildTool.h>
#include <RuntimeCompiler/ICompilerLogger.h>
#include <RuntimeCompiler/FileChangeNotifier.h>
#include <RuntimeObjectSystem/IObjectFactorySystem.h>
#include <RuntimeObjectSystem/ObjectFactorySystem/ObjectFactorySystem.h>
#include <RuntimeObjectSystem/RuntimeObjectSystem.h>
#include <RuntimeObjectSystem/IObject.h>

#include <SamplesRunner/rtc/iscene_producer.h>
#include <SamplesRunner/rtc/interface_ids.h>
#include <babylon/core/system.h>
#include <babylon/core/filesystem.h>

#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <string>
#include <stdarg.h>

// Remove windows.h define of GetObject which conflicts with EntitySystem GetObject
#if defined _WINDOWS_ && defined GetObject
#undef GetObject
#endif
using FileSystemUtils::Path;

namespace BABYLON {
namespace rtc {

RtcManager::RtcManager()
	: _compilerLogger(0)
	, _runtimeObjectSystem(0)
	, _sceneProducer(0)
{
}

RtcManager::~RtcManager()
{
    if( _runtimeObjectSystem )
    {
        // clean temp object files
        _runtimeObjectSystem->CleanObjectFiles();
    }

    if( _runtimeObjectSystem && _runtimeObjectSystem->GetObjectFactorySystem() )
    {
        _runtimeObjectSystem->GetObjectFactorySystem()->RemoveListener(this);

        // delete object via correct interface
        IObject* pObj = _runtimeObjectSystem->GetObjectFactorySystem()->GetObject( _objectId );
        delete pObj;
    }

	delete _runtimeObjectSystem;
	delete _compilerLogger;
}

bool RtcManager::Init()
{
	//Initialise the RuntimeObjectSystem
	_runtimeObjectSystem = new RuntimeObjectSystem;
	_compilerLogger = new LogSystem();
	if( !_runtimeObjectSystem->Initialise(_compilerLogger, 0) )
    {
        _runtimeObjectSystem = 0;
        return false;
    }
	_runtimeObjectSystem->GetObjectFactorySystem()->AddListener(this);

  SetIncludePath();
  SetCompileOptions();
  SetLibraryPath();

	// construct first object
	IObjectConstructor* pCtor = _runtimeObjectSystem->GetObjectFactorySystem()->GetConstructor( "Sandbox" );
	if( pCtor )
	{
		IObject* pObj = pCtor->Construct();
		pObj->GetInterface( &_sceneProducer );
		if( 0 == _sceneProducer )
		{
			delete pObj;
			_compilerLogger->LogError("Error - no updateable interface found\n");
			return false;
		}
		_objectId = pObj->GetObjectId();

	}

	return true;
}

void RtcManager::SetCompileOptions()
{
#ifdef _MSC_VER
  _runtimeObjectSystem->SetAdditionalCompileOptions("/std:c++17 /DBABYLON_BUILD_SANDBOX");
#else
  _runtimeObjectSystem->SetAdditionalCompileOptions("-std=c++17 -DBABYLON_BUILD_SANDBOX");
#endif // _MSC_VER
}

void RtcManager::SetLibraryPath()
{
  std::string exePath = BABYLON::System::getExecutablePath();
  std::string exeFolder = BABYLON::Filesystem::baseDir(exePath);

  std::string libPath = BABYLON::Filesystem::absolutePath(exeFolder + "/../lib");
  _runtimeObjectSystem->AddLibraryDir(libPath.c_str());
}

void RtcManager::SetIncludePath()
{
  FileSystemUtils::Path basePath = _runtimeObjectSystem->FindFile(__FILE__);
  FileSystemUtils::Path repoPath = basePath.ParentPath().ParentPath().ParentPath().ParentPath();
  FileSystemUtils::Path repoSrcPath = basePath.ParentPath().ParentPath().ParentPath().ParentPath() / "src";
  FileSystemUtils::Path repoExternalPath = basePath.ParentPath().ParentPath().ParentPath().ParentPath() / "external";
  _runtimeObjectSystem->AddIncludeDir(repoSrcPath.c_str());
  _runtimeObjectSystem->AddIncludeDir((repoExternalPath / "RuntimeCompiledCPlusPlus/Aurora").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoExternalPath / "imgui").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoExternalPath / "json.hpp").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoExternalPath / "glad/include").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoSrcPath / "BabylonCpp/include").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoSrcPath / "BabylonImGui/include").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoSrcPath / "MaterialsLibrary/include").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoSrcPath / "ProceduralTexturesLibrary/include").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoSrcPath / "Loaders/include").c_str());
  _runtimeObjectSystem->AddIncludeDir((repoSrcPath / "imgui_utils").c_str());

  std::string exePath = BABYLON::System::getExecutablePath();
  std::string exeFolder = BABYLON::Filesystem::baseDir(exePath);
  std::string apiPath = BABYLON::Filesystem::absolutePath(exeFolder + "/../../src/BabylonCpp/include");
  _runtimeObjectSystem->AddIncludeDir(apiPath.c_str());
}

void RtcManager::OnConstructorsAdded()
{
	// This could have resulted in a change of object pointer, so release old and get new one.
	if( _sceneProducer )
	{
		IObject* pObj = _runtimeObjectSystem->GetObjectFactorySystem()->GetObject( _objectId );
		pObj->GetInterface( &_sceneProducer );
    _lastCompiledScene = _sceneProducer->MakeScene();
		if( 0 == _sceneProducer )
		{
			delete pObj;
			_compilerLogger->LogError( "Error - no updateable interface found\n");
		}
	}
}

BABYLON::SandboxCompilerStatus RtcManager::Heartbeat()
{
	//check status of any compile
	if( _runtimeObjectSystem->GetIsCompiledComplete() )
	{
		// load module when compile complete
		_runtimeObjectSystem->LoadCompiledModule();
	}

	if(_runtimeObjectSystem->GetIsCompiling() )
	{
    BABYLON::SandboxCompilerStatus r;
    r._isCompiling = true;
    return r;
	}
  else
  {
    const float deltaTime = 1.0f;
    _runtimeObjectSystem->GetFileChangeNotifier()->Update(deltaTime);
    _sceneProducer->Update(deltaTime);
  }

  if (_lastCompiledScene)
  {
    BABYLON::SandboxCompilerStatus r;
    r._renderableScene = _lastCompiledScene;
    _lastCompiledScene.reset();
    return r;
  }
  return BABYLON::SandboxCompilerStatus();
}

} // namespace BABYLON
} // namespace rtc

#endif // BABYLON_BUILD_SANDBOX
<|endoftext|>


<commit_before>// Time:  O(n * C(n - 1, c - 1)), n is length of str, c is unique count of pattern,
//                                there are H(n - c, c - 1) = C(n - 1, c - 1) possible splits of string,
//                                and each one costs O(n) to check if it matches the word pattern.
// Space: O(n + c)

class Solution {
public:
    bool wordPatternMatch(string pattern, string str) {
        unordered_map<string, char> w2p;
        unordered_map<char, string> p2w;
        return match(pattern, str, 0, 0, &w2p, &p2w);
    }

    bool match(const string &pattern, const string &str,
               const int i, const int j,
               unordered_map<string, char>* w2p,
               unordered_map<char, string>* p2w) {
        bool is_match = false;
        if (i == pattern.length() && j == str.length()) {
            is_match = true;
        } else if (i < pattern.length() && j < str.length()) {
            const char p = pattern[i];
            if (p2w->count(p)) {
                if ((*p2w)[p] == str.substr(j, (*p2w)[p].length())) {  // Match pattern.
                    is_match = match(pattern, str, i + 1, j + (*p2w)[p].length(), w2p, p2w);
                }  // Else return false.
            } else {
                for (int k = j; k < str.length() && !is_match; ++k) {
                    const string w = str.substr(j, k - j + 1);
                    if (!w2p->count(w)) {
                        // Build mapping. Space: O(n + c)
                        (*w2p)[w] = p, (*p2w)[p] = w;
                        is_match = match(pattern, str, i + 1, k + 1, w2p, p2w);
                        w2p->erase(w), p2w->erase(p);
                    }  // Else try longer word.
                }
            }
        }
        return is_match;
    }
};
<commit_msg>Update word-pattern-ii.cpp<commit_after>// Time:  O(n * C(n - 1, c - 1)), n is length of str, c is unique count of pattern,
//                                there are H(n - c, c - 1) = C(n - 1, c - 1) possible splits of string,
//                                and each one costs O(n) to check if it matches the word pattern.
// Space: O(n + c)

class Solution {
public:
    bool wordPatternMatch(string pattern, string str) {
        unordered_map<string, char> w2p;
        unordered_map<char, string> p2w;
        return match(pattern, str, 0, 0, &w2p, &p2w);
    }

    bool match(const string &pattern, const string &str,
               const int i, const int j,
               unordered_map<string, char>* w2p,
               unordered_map<char, string>* p2w) {

        bool is_match = false;
        if (i == pattern.length() && j == str.length()) {
            is_match = true;
        } else if (i < pattern.length() && j < str.length()) {
            const char p = pattern[i];
            if (p2w->count(p)) {
                const auto& w = (*p2w)[p];
                if (w == str.substr(j, w.length())) {  // Match pattern.
                    is_match = match(pattern, str, i + 1, j + w.length(), w2p, p2w);
                }  // Else return false.
            } else {
                for (int k = j; k < str.length() && !is_match; ++k) {
                    const string w = str.substr(j, k - j + 1);
                    if (!w2p->count(w)) {
                        // Build mapping. Space: O(n + c)
                        (*w2p)[w] = p, (*p2w)[p] = w;
                        is_match = match(pattern, str, i + 1, k + 1, w2p, p2w);
                        w2p->erase(w), p2w->erase(p);
                    }  // Else try longer word.
                }
            }
        }
        return is_match;
    }
};
<|endoftext|>


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

#include "dglproject_runapp.h"

#include <QFileInfo>
#include <QDir>

#include <QFileDialog>

#ifndef _WIN32
#include <wordexp.h>
#else
#include <wtypes.h>
#include <shellapi.h>
#endif

#include <stdexcept>
#include <sstream>

#include <DGLCommon/os.h>

DGLRunAppProject::DGLRunAppProject(const std::string& executable,
                                   const std::string& path, const std::wstring& args,
                                   bool eglMode)
        : m_process(nullptr),
          m_executable(executable),
          m_path(path),
          m_args(args),
          m_EglMode(eglMode) {}

DGLRunAppProject::DGLRunAppProject() : m_process(nullptr) {}

DGLRunAppProject::~DGLRunAppProject() { stopDebugging(); }

const std::string& DGLRunAppProject::getExecutable() const {
    return m_executable;
}

const std::string& DGLRunAppProject::getPath() const { return m_path; }

const std::wstring& DGLRunAppProject::getCommandLineArgs() const {
    return m_args;
}

bool DGLRunAppProject::isEglMode() {
    return m_EglMode;
}

void DGLRunAppProject::startDebugging() {
    // randomize connection port
    int port = rand() % (0xffff - 1024) + 1024;

    m_process = new DGLDebugeeQTProcess(port, m_EglMode);

    m_process->setParent(this);

    CONNASSERT(m_process, SIGNAL(processReady()), this,
               SLOT(processReadyHandler()));
    CONNASSERT(m_process, SIGNAL(processError(std::string)), this,
               SLOT(processErrorHandler(std::string)));
    CONNASSERT(m_process, SIGNAL(processFinished(int)), this,
               SLOT(processExitHandler(int)));
    CONNASSERT(m_process, SIGNAL(processCrashed()), this,
               SLOT(processCrashHandler()));

    m_process->run(getExecutable(), getPath(), getCommandLineArgVector());
}

void DGLRunAppProject::stopDebugging() {
    if (m_process) {
        m_process->exit(false);
        m_process->requestDelete();
        m_process = NULL;
    }
}

bool DGLRunAppProject::shouldTerminateOnStop() {
    return true;
}

void DGLRunAppProject::processReadyHandler() {

    std::ostringstream portStr;
    portStr << m_process->getPort();

    emit debugStarted("127.0.0.1", portStr.str());
}

void DGLRunAppProject::processCrashHandler() {
    emit debugError(tr("Process crashed"), tr("Loader process has crashed"));
}

void DGLRunAppProject::processErrorHandler(std::string err) {
    emit debugError(tr("Fatal Error"), QString::fromStdString(err));
}

void DGLRunAppProject::processExitHandler(int code) {
    emit debugExit(tr("Process has exited with code ") + QString::number(code) +
                   ".");
}

std::vector<std::string> DGLRunAppProject::getCommandLineArgVector() {
    std::vector<std::string> ret;

// some magic here. We have arguments from user, but we must pre-parse them and
// split into and array.
// due to laziness some weird system-specific functions are used here.
#ifdef _WIN32
    int numArgs;
    if (m_args.length()) {
        LPWSTR* strings =
                CommandLineToArgvW(m_args.c_str(), &numArgs);
        if (!strings) {
            if (int osError = Os::getLastosError()) {
                throw std::runtime_error("Program arguments: " +
                                         Os::translateOsError(osError));
            } else {
                throw std::runtime_error("Program arguments: unknown error");
            }
        }

        if (numArgs > 0) {
            ret.resize(static_cast<size_t>(numArgs));
            for (size_t i = 0; i < ret.size(); i++) {
                ret[i] = QString::fromWCharArray(strings[i]).toStdString();
            }
        }
        LocalFree(strings);
    }
#else
    wordexp_t wordExp;

    std::string argsUtf8 = "";

    if (m_args.size()) {
        std::vector<char> charBuffer(MB_CUR_MAX * m_args.size(), 0);
        wcstombs(&charBuffer[0], &m_args[0], charBuffer.size());
        argsUtf8 = &charBuffer[0];
    }

    int status = wordexp(argsUtf8.c_str(), &wordExp, 0);
    switch (status) {
        case WRDE_BADCHAR:
            throw std::runtime_error(
                    "Program arguments: Illegal occurrence of newline or one "
                    "of |, "
                    "&, ;, <, >, (, ), {, }.");
        case WRDE_BADVAL:
            DGL_ASSERT(!"no  WRDE_UNDEF was set, but got WRDE_BADVAL");
            throw std::runtime_error(
                    "Program arguments: An undefined shell variable was "
                    "referenced");
        case WRDE_CMDSUB:
            DGL_ASSERT(!" WRDE_NOCMD flag not set, but got WRDE_CMDSUB");
            throw std::runtime_error(
                    "Program arguments: Command substitution occurred");
        case WRDE_NOSPACE:
            DGL_ASSERT(&wordExp);
            throw std::runtime_error("Program arguments: Out of memory.");
        case WRDE_SYNTAX:
            throw std::runtime_error("Program arguments: syntax error");
        case 0:
            break;
        default:
            throw std::runtime_error("Program arguments: unknown error");
    }

    ret.resize(wordExp.we_wordc);
    for (size_t i = 0; i < ret.size(); i++) {
        ret[i] = wordExp.we_wordv[i];
    }

    wordfree(&wordExp);

#endif
    return ret;
}

DGLRunAppProjectFactory::DGLRunAppProjectFactory() {
    m_ui.setupUi(&m_gui);

#ifndef _WIN32
    m_ui.radioButton_ModeWGLGLX->setText("GLX");
#endif

    CONNASSERT(m_ui.lineEdit_Executable, SIGNAL(editingFinished()), this,
               SLOT(updatePath()));
    CONNASSERT(m_ui.toolButton_Exec, SIGNAL(clicked()), this,
               SLOT(browseExecutable()));
    CONNASSERT(m_ui.toolButton_Dir, SIGNAL(clicked()), this,
               SLOT(browseDirectory()));
    m_ui.lineEdit_Executable->setFocus();
}

void DGLRunAppProjectFactory::updatePath() {
    QFileInfo info(m_ui.lineEdit_Executable->text());
    m_ui.lineEdit_Path->setText(QDir::toNativeSeparators(info.dir().path()));
    ;
}

void DGLRunAppProjectFactory::browseExecutable() {
    QFileInfo info(m_ui.lineEdit_Executable->text());
    QString res = QFileDialog::getOpenFileName(
            &m_gui, tr("Choose a executable to run"), info.absoluteFilePath(),
            tr("Executables (*.exe)"));
    if (!res.isNull()) {
        m_ui.lineEdit_Executable->setText(QDir::toNativeSeparators(res));
    }
    updatePath();
}

void DGLRunAppProjectFactory::browseDirectory() {
    QString res = QFileDialog::getExistingDirectory(&m_gui, "Choose directory",
                                                    m_ui.lineEdit_Path->text());
    if (!res.isNull()) {
        m_ui.lineEdit_Path->setText(res);
    }
}

std::shared_ptr<DGLProject> DGLRunAppProjectFactory::createProject() {
    QString message;
    if (!valid(message)) {
        throw std::runtime_error(message.toStdString());
    } else {
        return std::make_shared<DGLRunAppProject>(
                m_ui.lineEdit_Executable->text().toStdString(),
                m_ui.lineEdit_Path->text().toStdString(),
                m_ui.lineEdit_CommandLineArgs->text().toStdWString(),
                m_ui.radioButton_ModeEGL->isChecked() &&
                        !m_ui.radioButton_ModeWGLGLX->isChecked());
    }
}

bool DGLRunAppProjectFactory::valid(QString& message) {
    if (!m_ui.lineEdit_Executable->text().length()) {
        message = tr("Executable not set.");
        return false;
    }
    return true;
}

bool DGLRunAppProjectFactory::loadPropertiesFromProject(
        const DGLProject* project) {
    const DGLRunAppProject* runProject =
            dynamic_cast<const DGLRunAppProject*>(project);
    if (!runProject) {
        return false;
    } else {
        m_ui.lineEdit_Executable->setText(
                QString::fromStdString(runProject->getExecutable()));
        m_ui.lineEdit_CommandLineArgs->setText(
                QString::fromStdWString(runProject->getCommandLineArgs()));
        m_ui.lineEdit_Path->setText(
                QString::fromStdString(runProject->getPath()));
    }
    return true;
}

QString DGLRunAppProjectFactory::getName() {
    return tr("Run local Application");
}

QWidget* DGLRunAppProjectFactory::getGUI() { return &m_gui; }
<commit_msg>Fixup RunApp open file to not expect *.exe files on non-Window<commit_after>/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "dglproject_runapp.h"

#include <QFileInfo>
#include <QDir>

#include <QFileDialog>

#ifndef _WIN32
#include <wordexp.h>
#else
#include <wtypes.h>
#include <shellapi.h>
#endif

#include <stdexcept>
#include <sstream>

#include <DGLCommon/os.h>

DGLRunAppProject::DGLRunAppProject(const std::string& executable,
                                   const std::string& path, const std::wstring& args,
                                   bool eglMode)
        : m_process(nullptr),
          m_executable(executable),
          m_path(path),
          m_args(args),
          m_EglMode(eglMode) {}

DGLRunAppProject::DGLRunAppProject() : m_process(nullptr) {}

DGLRunAppProject::~DGLRunAppProject() { stopDebugging(); }

const std::string& DGLRunAppProject::getExecutable() const {
    return m_executable;
}

const std::string& DGLRunAppProject::getPath() const { return m_path; }

const std::wstring& DGLRunAppProject::getCommandLineArgs() const {
    return m_args;
}

bool DGLRunAppProject::isEglMode() {
    return m_EglMode;
}

void DGLRunAppProject::startDebugging() {
    // randomize connection port
    int port = rand() % (0xffff - 1024) + 1024;

    m_process = new DGLDebugeeQTProcess(port, m_EglMode);

    m_process->setParent(this);

    CONNASSERT(m_process, SIGNAL(processReady()), this,
               SLOT(processReadyHandler()));
    CONNASSERT(m_process, SIGNAL(processError(std::string)), this,
               SLOT(processErrorHandler(std::string)));
    CONNASSERT(m_process, SIGNAL(processFinished(int)), this,
               SLOT(processExitHandler(int)));
    CONNASSERT(m_process, SIGNAL(processCrashed()), this,
               SLOT(processCrashHandler()));

    m_process->run(getExecutable(), getPath(), getCommandLineArgVector());
}

void DGLRunAppProject::stopDebugging() {
    if (m_process) {
        m_process->exit(false);
        m_process->requestDelete();
        m_process = NULL;
    }
}

bool DGLRunAppProject::shouldTerminateOnStop() {
    return true;
}

void DGLRunAppProject::processReadyHandler() {

    std::ostringstream portStr;
    portStr << m_process->getPort();

    emit debugStarted("127.0.0.1", portStr.str());
}

void DGLRunAppProject::processCrashHandler() {
    emit debugError(tr("Process crashed"), tr("Loader process has crashed"));
}

void DGLRunAppProject::processErrorHandler(std::string err) {
    emit debugError(tr("Fatal Error"), QString::fromStdString(err));
}

void DGLRunAppProject::processExitHandler(int code) {
    emit debugExit(tr("Process has exited with code ") + QString::number(code) +
                   ".");
}

std::vector<std::string> DGLRunAppProject::getCommandLineArgVector() {
    std::vector<std::string> ret;

// some magic here. We have arguments from user, but we must pre-parse them and
// split into and array.
// due to laziness some weird system-specific functions are used here.
#ifdef _WIN32
    int numArgs;
    if (m_args.length()) {
        LPWSTR* strings =
                CommandLineToArgvW(m_args.c_str(), &numArgs);
        if (!strings) {
            if (int osError = Os::getLastosError()) {
                throw std::runtime_error("Program arguments: " +
                                         Os::translateOsError(osError));
            } else {
                throw std::runtime_error("Program arguments: unknown error");
            }
        }

        if (numArgs > 0) {
            ret.resize(static_cast<size_t>(numArgs));
            for (size_t i = 0; i < ret.size(); i++) {
                ret[i] = QString::fromWCharArray(strings[i]).toStdString();
            }
        }
        LocalFree(strings);
    }
#else
    wordexp_t wordExp;

    std::string argsUtf8 = "";

    if (m_args.size()) {
        std::vector<char> charBuffer(MB_CUR_MAX * m_args.size(), 0);
        wcstombs(&charBuffer[0], &m_args[0], charBuffer.size());
        argsUtf8 = &charBuffer[0];
    }

    int status = wordexp(argsUtf8.c_str(), &wordExp, 0);
    switch (status) {
        case WRDE_BADCHAR:
            throw std::runtime_error(
                    "Program arguments: Illegal occurrence of newline or one "
                    "of |, "
                    "&, ;, <, >, (, ), {, }.");
        case WRDE_BADVAL:
            DGL_ASSERT(!"no  WRDE_UNDEF was set, but got WRDE_BADVAL");
            throw std::runtime_error(
                    "Program arguments: An undefined shell variable was "
                    "referenced");
        case WRDE_CMDSUB:
            DGL_ASSERT(!" WRDE_NOCMD flag not set, but got WRDE_CMDSUB");
            throw std::runtime_error(
                    "Program arguments: Command substitution occurred");
        case WRDE_NOSPACE:
            DGL_ASSERT(&wordExp);
            throw std::runtime_error("Program arguments: Out of memory.");
        case WRDE_SYNTAX:
            throw std::runtime_error("Program arguments: syntax error");
        case 0:
            break;
        default:
            throw std::runtime_error("Program arguments: unknown error");
    }

    ret.resize(wordExp.we_wordc);
    for (size_t i = 0; i < ret.size(); i++) {
        ret[i] = wordExp.we_wordv[i];
    }

    wordfree(&wordExp);

#endif
    return ret;
}

DGLRunAppProjectFactory::DGLRunAppProjectFactory() {
    m_ui.setupUi(&m_gui);

#ifndef _WIN32
    m_ui.radioButton_ModeWGLGLX->setText("GLX");
#endif

    CONNASSERT(m_ui.lineEdit_Executable, SIGNAL(editingFinished()), this,
               SLOT(updatePath()));
    CONNASSERT(m_ui.toolButton_Exec, SIGNAL(clicked()), this,
               SLOT(browseExecutable()));
    CONNASSERT(m_ui.toolButton_Dir, SIGNAL(clicked()), this,
               SLOT(browseDirectory()));
    m_ui.lineEdit_Executable->setFocus();
}

void DGLRunAppProjectFactory::updatePath() {
    QFileInfo info(m_ui.lineEdit_Executable->text());
    m_ui.lineEdit_Path->setText(QDir::toNativeSeparators(info.dir().path()));
    ;
}

void DGLRunAppProjectFactory::browseExecutable() {
    QFileInfo info(m_ui.lineEdit_Executable->text());

#ifdef _WIN32
    const char* filter = "Executables (*.exe)";
#else
    //executables on non-Windows does not have a suffix
    const char* filter = "Executables (*)";
#endif
    QString res = QFileDialog::getOpenFileName(
            &m_gui, tr("Choose a executable to run"), info.absoluteFilePath(),
            tr(filter));

    if (!res.isNull()) {
        m_ui.lineEdit_Executable->setText(QDir::toNativeSeparators(res));
    }
    updatePath();
}

void DGLRunAppProjectFactory::browseDirectory() {
    QString res = QFileDialog::getExistingDirectory(&m_gui, "Choose directory",
                                                    m_ui.lineEdit_Path->text());
    if (!res.isNull()) {
        m_ui.lineEdit_Path->setText(res);
    }
}

std::shared_ptr<DGLProject> DGLRunAppProjectFactory::createProject() {
    QString message;
    if (!valid(message)) {
        throw std::runtime_error(message.toStdString());
    } else {
        return std::make_shared<DGLRunAppProject>(
                m_ui.lineEdit_Executable->text().toStdString(),
                m_ui.lineEdit_Path->text().toStdString(),
                m_ui.lineEdit_CommandLineArgs->text().toStdWString(),
                m_ui.radioButton_ModeEGL->isChecked() &&
                        !m_ui.radioButton_ModeWGLGLX->isChecked());
    }
}

bool DGLRunAppProjectFactory::valid(QString& message) {
    if (!m_ui.lineEdit_Executable->text().length()) {
        message = tr("Executable not set.");
        return false;
    }
    return true;
}

bool DGLRunAppProjectFactory::loadPropertiesFromProject(
        const DGLProject* project) {
    const DGLRunAppProject* runProject =
            dynamic_cast<const DGLRunAppProject*>(project);
    if (!runProject) {
        return false;
    } else {
        m_ui.lineEdit_Executable->setText(
                QString::fromStdString(runProject->getExecutable()));
        m_ui.lineEdit_CommandLineArgs->setText(
                QString::fromStdWString(runProject->getCommandLineArgs()));
        m_ui.lineEdit_Path->setText(
                QString::fromStdString(runProject->getPath()));
    }
    return true;
}

QString DGLRunAppProjectFactory::getName() {
    return tr("Run local Application");
}

QWidget* DGLRunAppProjectFactory::getGUI() { return &m_gui; }
<|endoftext|>


<commit_before>/*
 * Copyright 2022 The CFU-Playground Authors
 * Copyright 2019 The TensorFlow 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.
 */

#include "tensorflow/lite/kernels/internal/reference/integer_ops/fully_connected_accel.h"

#include <cstdio>

#include "tensorflow/lite/kernels/internal/common.h"

namespace tflite {
namespace reference_integer_ops {

// Determine whether operation is suitable for acceleration
bool CanAccelerateFullyConnected(const FullyConnectedParams& params,
                                 const RuntimeShape& filter_shape,
                                 const int32_t* bias_data,
                                 const RuntimeShape& output_shape) {
  if (params.input_offset != 128) return false;
  if (params.weights_offset != 0) return false;
  if (bias_data == NULL) return false;
  if (filter_shape.Dims(1) % 16 != 0) return false;
  if (output_shape.Dims(0) != 1) return false;
  return true;
}

// Accelerated implementation
void AccelerateFullyConnected(
    const FullyConnectedParams& params, const RuntimeShape& input_shape,
    const int8_t* input_data, const RuntimeShape& filter_shape,
    const int8_t* filter_data, const RuntimeShape& bias_shape,
    const int32_t* bias_data, const RuntimeShape& output_shape,
    int8_t* output_data) {
  const int32_t input_offset = params.input_offset;
  const int32_t filter_offset = params.weights_offset;
  const int32_t output_offset = params.output_offset;
  const int32_t output_multiplier = params.output_multiplier;
  const int output_shift = params.output_shift;
  const int32_t output_activation_min = params.quantized_activation_min;
  const int32_t output_activation_max = params.quantized_activation_max;
  TFLITE_DCHECK_GE(filter_shape.DimensionsCount(), 2);
  TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 2);

  TFLITE_DCHECK_LE(output_activation_min, output_activation_max);
  const int filter_dim_count = filter_shape.DimensionsCount();
  const int batches = output_shape.Dims(0);
  const int output_depth = output_shape.Dims(1);
  TFLITE_DCHECK_LE(output_depth, filter_shape.Dims(filter_dim_count - 2));
  const int accum_depth = filter_shape.Dims(filter_dim_count - 1);
  for (int b = 0; b < batches; ++b) {
    for (int out_c = 0; out_c < output_depth; ++out_c) {
      int32_t acc = 0;
      for (int d = 0; d < accum_depth; ++d) {
        int32_t input_val = input_data[b * accum_depth + d];
        int32_t filter_val = filter_data[out_c * accum_depth + d];
        acc += (filter_val + filter_offset) * (input_val + input_offset);
      }
      if (bias_data) {
        acc += bias_data[out_c];
      }
      acc = MultiplyByQuantizedMultiplier(acc, output_multiplier, output_shift);
      acc += output_offset;
      acc = std::max(acc, output_activation_min);
      acc = std::min(acc, output_activation_max);
      output_data[out_c + output_depth * b] = static_cast<int8_t>(acc);
    }
  }
}

}  // namespace reference_integer_ops
}  // namespace tflite
<commit_msg>hps_accel/fully_connected: simple optimisations<commit_after>/*
 * Copyright 2022 The CFU-Playground Authors
 * Copyright 2019 The TensorFlow 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.
 */

#include "tensorflow/lite/kernels/internal/reference/integer_ops/fully_connected_accel.h"

#include <cstdio>

#include "tensorflow/lite/kernels/internal/common.h"

namespace tflite {
namespace reference_integer_ops {

// Determine whether operation is suitable for acceleration
bool CanAccelerateFullyConnected(const FullyConnectedParams& params,
                                 const RuntimeShape& filter_shape,
                                 const int32_t* bias_data,
                                 const RuntimeShape& output_shape) {
  if (params.input_offset != 128) return false;
  if (params.weights_offset != 0) return false;
  if (bias_data == NULL) return false;
  if (filter_shape.Dims(1) % 16 != 0) return false;
  if (output_shape.Dims(0) != 1) return false;
  return true;
}

// Accelerated implementation
void AccelerateFullyConnected(
    const FullyConnectedParams& params, const RuntimeShape& input_shape,
    const int8_t* input_data, const RuntimeShape& filter_shape,
    const int8_t* filter_data, const RuntimeShape& bias_shape,
    const int32_t* bias_data, const RuntimeShape& output_shape,
    int8_t* output_data) {
  const int32_t input_offset = 128;
  const int32_t output_offset = params.output_offset;
  const int32_t output_multiplier = params.output_multiplier;
  const int output_shift = params.output_shift;
  const int32_t output_activation_min = params.quantized_activation_min;
  const int32_t output_activation_max = params.quantized_activation_max;
  TFLITE_DCHECK_GE(filter_shape.DimensionsCount(), 2);
  TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 2);

  TFLITE_DCHECK_LE(output_activation_min, output_activation_max);
  const int filter_dim_count = filter_shape.DimensionsCount();
  const int output_depth = output_shape.Dims(1);
  TFLITE_DCHECK_LE(output_depth, filter_shape.Dims(filter_dim_count - 2));
  const int accum_depth = filter_shape.Dims(filter_dim_count - 1);
  for (int out_c = 0; out_c < output_depth; ++out_c) {
    int32_t acc = 0;
    for (int d = 0; d < accum_depth; ++d) {
      int32_t input_val = input_data[d];
      int32_t filter_val = filter_data[out_c * accum_depth + d];
      acc += filter_val * (input_val + input_offset);
    }
    acc += bias_data[out_c];
    acc = MultiplyByQuantizedMultiplier(acc, output_multiplier, output_shift);
    acc += output_offset;
    acc = std::max(acc, output_activation_min);
    acc = std::min(acc, output_activation_max);
    output_data[out_c] = static_cast<int8_t>(acc);
  }
}

}  // namespace reference_integer_ops
}  // namespace tflite
<|endoftext|>


<commit_before>#include "Arduino.h"

#include "BLEUtil.h"

void BLEUtil::addressToString(const unsigned char *in, char* out) {
  sprintf(out, "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
    in[5],
    in[4],
    in[3],
    in[2],
    in[1],
    in[0]);
}

void BLEUtil::printBuffer(const unsigned char* buffer, unsigned char length) {
  for (int i = 0; i < length; i++) {
    if ((buffer[i] & 0xf0) == 00) {
      Serial.print("0");
    }

    Serial.print(buffer[i], HEX);
    Serial.print(" ");
  }
  Serial.println();
}

<commit_msg>- swap printf out for String + loop<commit_after>#include "Arduino.h"

#include "BLEUtil.h"

void BLEUtil::addressToString(const unsigned char *in, char* out) {
  String address = "";

  for (int i = 5; i >= 0; i--) {
    if (in[i] < 0x10) {
      address += "0";
    }

    address += String(in[i], 16);

    if (i > 0) {
      address += ":";
    }
  }

  address.toCharArray(out, 18);
}

void BLEUtil::printBuffer(const unsigned char* buffer, unsigned char length) {
  for (int i = 0; i < length; i++) {
    if ((buffer[i] & 0xf0) == 00) {
      Serial.print("0");
    }

    Serial.print(buffer[i], HEX);
    Serial.print(" ");
  }
  Serial.println();
}

<|endoftext|>


<commit_before>//
//  Object.cpp
//  Test02
//
//  Created by Golden Compass on 9/17/14.
//  Copyright (c) 2014 Golden Compass. All rights reserved.
//

#include "Object.h"

Sphere::Sphere(vec3 _center, float _radius)
{
    center = _center;
    radius = _radius;
}
//bool Sphere::isIntersectByRay(const vec3& ray)
//{
//
//    return false;
//}

Plane::Plane(float _a, float _b, float _c, float _d)
{
    a = _a;
    b = _b;
    c = _c;
    d = _d;
}

// ax + by + cz + d = 0
Plane::Plane(vec3 point, vec3 normal)
{
    a = normal.x;
    b = normal.y;
    c = normal.z;
    d = -(a*point.x) - (b*point.y) - (c*point.z);
}<commit_msg>Working Copy<commit_after>//
//  Object.cpp
//  Test02
//
//  Created by Golden Compass on 9/17/14.
//  Copyright (c) 2014 Golden Compass. All rights reserved.
//

#include "Object.h"

Sphere::Sphere(vec3 _center, float _radius)
{
    center = _center;
    radius = _radius;
}
//bool Sphere::isIntersectByRay(const vec3& ray)
//{
//
//    return false;
//}

Plane::Plane(float _a, float _b, float _c, float _d)
{
    a = _a;
    b = _b;
    c = _c;
    d = _d;
}

// ax + by + cz + d = 0
Plane::Plane(vec3 point, vec3 normal)
{
    a = normal.x;
    b = normal.y;
    c = normal.z;
    d = -(a*point.x) - (b*point.y) - (c*point.z);
}<|endoftext|>


<commit_before>/* $Id$ */
/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
//--------------------------------------------------------------------//
//                                                                    //
// AliCFEffGrid Class                                              //
// Class to handle efficiency grids                                   //
//                                                                    //
// -- Author : S.Arcelli                                              //
//                                                                    //
//                                                                    //
//                                                                    //
//--------------------------------------------------------------------//
//
//
#include "TMath.h"
#include "AliLog.h"
#include "AliCFEffGrid.h"
#include "TH1D.h"
#include "TH2D.h"
#include "TH3D.h"

//____________________________________________________________________
ClassImp(AliCFEffGrid)

//____________________________________________________________________
AliCFEffGrid::AliCFEffGrid() :
  AliCFGridSparse(),
  fContainer(0x0),
  fSelNum(-1),
  fSelDen(-1)
{
  //
  // default constructor
  //
}

//____________________________________________________________________
AliCFEffGrid::AliCFEffGrid(const Char_t* name, const Char_t* title, const Int_t nVarIn, const Int_t * nBinIn, const Double_t *binLimitsIn) :
  AliCFGridSparse(name,title,nVarIn,nBinIn,binLimitsIn),
  fContainer(0x0),
  fSelNum(-1),
  fSelDen(-1)
{
  //
  // ctor
  //
  SumW2();
}
//____________________________________________________________________
AliCFEffGrid::AliCFEffGrid(const Char_t* name, const Char_t* title, const AliCFContainer &c) :
  AliCFGridSparse(name,title,c.GetNVar(),c.GetNBins(),c.GetBinLimits()),
  fContainer(NULL),
  fSelNum(-1),
  fSelDen(-1)
{
  //
  // main constructor
  //
  SumW2();
  //assign the container;
  fContainer=&c;
}
//____________________________________________________________________
AliCFEffGrid::AliCFEffGrid(const AliCFEffGrid& eff) : AliCFGridSparse(),
  fContainer(0x0),
  fSelNum(-1),
  fSelDen(-1)
{
  //
  // copy constructor
  //
  ((AliCFEffGrid &)eff).Copy(*this);
}

//____________________________________________________________________
AliCFEffGrid::~AliCFEffGrid()
{
  //
  // destructor
  //
}

//____________________________________________________________________
AliCFEffGrid &AliCFEffGrid::operator=(const AliCFEffGrid &eff)
{
  //
  // assigment operator
  //
  if (this != &eff)
    ((AliCFEffGrid &) eff).Copy(*this);
  return *this;
}
//____________________________________________________________________

void AliCFEffGrid::CalculateEfficiency(Int_t istep1,Int_t istep2, Option_t *option)
{
  //
  // Calculate the efficiency matrix and its error between selection
  // Steps istep1 and istep2
  //

  fSelNum=istep1;
  fSelDen=istep2;
  AliCFVGrid *num=fContainer->GetGrid(fSelNum);
  AliCFVGrid *den=fContainer->GetGrid(fSelDen);
  num->SumW2();
  den->SumW2();
  this->SumW2();
  this->Divide(num,den,1.,1.,option);

  Int_t nEmptyBinsNum=0;
  Int_t nEmptyBinsNumAndDen=0;
  for(Int_t iel=0;iel<fNDim;iel++){
    if(den->GetElement(iel)>0){
      if(num->GetElement(iel)==0)nEmptyBinsNum++; //num==0,den!=0
    }
    else{
      nEmptyBinsNumAndDen++;
    }
  }
  // Some monitoring printout:
  AliInfo(Form("Efficiency calculated for steps %i and %i: %i empty bins in the numerator && !denominator and %i empty bins in numerator && denominator were found.",fSelNum,fSelDen,nEmptyBinsNumAndDen,nEmptyBinsNum));
  AliInfo(Form("The correction map contains %i empty bins ",nEmptyBinsNum+nEmptyBinsNumAndDen));
}
//_____________________________________________________________________
Double_t AliCFEffGrid::GetAverage() const
{
  //
  // Get the average efficiency
  //

  Double_t val=0;
  Double_t valnum=0;
  Double_t valden=0;
  for(Int_t i=0;i<fNDim;i++){
    valnum+=fContainer->GetGrid(fSelNum)->GetElement(i);
    valden+=fContainer->GetGrid(fSelDen)->GetElement(i);
  }
  if(valden>0)val=valnum/valden;
  AliInfo(Form(" The Average Efficiency = %f ",val));

  return val;
}
//_____________________________________________________________________
Double_t AliCFEffGrid::GetAverage(Double_t *varMin, Double_t* varMax ) const
{
  //
  // Get ave efficiency in a range
  //

  Double_t val=0;
  Int_t *indexMin = new Int_t[fNVar];
  Int_t *indexMax = new Int_t[fNVar];
  Int_t *index    = new Int_t[fNVar];

  //Find out the min and max bins

  for(Int_t i=0;i<fNVar;i++){
    Double_t xmin=varMin[i]; // the min values
    Double_t xmax=varMax[i]; // the max values
    Int_t nbins=fNVarBins[i]+1;
    Double_t *bins=new Double_t[nbins];
    for(Int_t ibin =0;ibin<nbins;ibin++){
      bins[ibin] = fVarBinLimits[ibin+fOffset[i]];
    }
    indexMin[i] = TMath::BinarySearch(nbins,bins,xmin);
    indexMax[i] = TMath::BinarySearch(nbins,bins,xmax);
    if(xmax>=bins[nbins-1]){
      indexMax[i]=indexMax[i]-1;
    }
    delete [] bins;
  }

  Double_t valnum=0;
  Double_t valden=0;
  for(Int_t i=0;i<fNDim;i++){
    for (Int_t j=0;j<fNVar;j++)index[j]=GetBinIndex(j,i);
    Bool_t isIn=kTRUE;
    for (Int_t j=0;j<fNVar;j++){
      if(!(index[j]>=indexMin[j] && index[j]<=indexMax[j]))isIn=kFALSE;
    }
    if(isIn){
      valnum+=fContainer->GetGrid(fSelNum)->GetElement(i);
      valden+=fContainer->GetGrid(fSelDen)->GetElement(i);
    }
  }
  delete [] index;
  delete [] indexMin;
  delete [] indexMax;
  if(valden>0)val=valnum/valden;
  AliInfo(Form(" the Average Efficiency = %f ",val));
  return val;
}
//____________________________________________________________________
void AliCFEffGrid::Copy(TObject& eff) const
{
  //
  // copy function
  //
  Copy(eff);
  AliCFEffGrid& target = (AliCFEffGrid &) eff;

  target.fSelNum=fSelNum;
  target.fSelDen=fSelDen;
  if(fContainer)
    target.fContainer=fContainer;
}
//___________________________________________________________________
TH1D *AliCFEffGrid::Project(Int_t ivar) const
{
  //
  // Make a 1D projection along variable ivar
  //

  TH1D *proj1D=0;
  Int_t nbins =fNVarBins[ivar];
  Float_t *bins = new Float_t[nbins+1];
  for(Int_t ibin =0;ibin<nbins+1;ibin++){
    bins[ibin] = fVarBinLimits[ibin+fOffset[ivar]];
  }

  char pname[30];
  sprintf(pname,"%s%s%i%i%s%i",GetName(),"_SelStep",fSelNum,fSelDen,"_proj1D_var", ivar);
  char htitle[30];
  sprintf(htitle,"%s%s%i%i%s%i",GetName(),"_SelStep",fSelNum,fSelDen,"_proj1D_var", ivar);

  if(!proj1D){
    proj1D =new TH1D(pname,htitle, nbins, bins);
  }

  //unset the use of axis range to be able to divide the histos
  fContainer->GetGrid(fSelNum)->UseAxisRange(kFALSE);
  fContainer->GetGrid(fSelDen)->UseAxisRange(kFALSE);

  proj1D->Sumw2();
  proj1D->Divide(fContainer->GetGrid(fSelNum)->Project(ivar),fContainer->GetGrid(fSelDen)->Project(ivar),1.,1.,"B");

  fContainer->GetGrid(fSelNum)->UseAxisRange(kTRUE);
  fContainer->GetGrid(fSelDen)->UseAxisRange(kTRUE);
  proj1D->GetXaxis()->SetRange(
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar)->GetFirst(),
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar)->GetLast()
			       );

  delete [] bins;
  return proj1D;
}
//___________________________________________________________________
TH2D *AliCFEffGrid::Project(Int_t ivar1,Int_t ivar2) const
{
  //
  // Make a 2D projection along variable ivar1,ivar2
  //

  TH2D *proj2D=0;

  Int_t nbins1 =fNVarBins[ivar1];
  Float_t *bins1 = new Float_t[nbins1+1];
  Int_t nbins2 =fNVarBins[ivar2];
  Float_t *bins2 = new Float_t[nbins2+1];
  for(Int_t ibin1 =0;ibin1<nbins1+1;ibin1++){
    bins1[ibin1] = fVarBinLimits[ibin1+fOffset[ivar1]];
  }
  for(Int_t ibin2 =0;ibin2<nbins2+1;ibin2++){
    bins2[ibin2] = fVarBinLimits[ibin2+fOffset[ivar2]];
  }

  char pname[30];
  sprintf(pname,"%s%s%i%i%s%i%i",GetName(),"_SelStep",fSelNum,fSelDen,"_proj2D_var", ivar1,ivar2);
  char htitle[30];
  sprintf(htitle,"%s%s%i%i%s%i%i",GetName(),"_SelStep",fSelNum,fSelDen,"_proj2D_var",ivar1,ivar2);

  if(!proj2D){
    proj2D =new TH2D(pname,htitle, nbins1,bins1,nbins2,bins2);
  }

  //unset the use of axis range to be able to divide the histos
  fContainer->GetGrid(fSelNum)->UseAxisRange(kFALSE);
  fContainer->GetGrid(fSelDen)->UseAxisRange(kFALSE);

  proj2D->Sumw2();
  proj2D->Divide(fContainer->GetGrid(fSelNum)->Project(ivar1,ivar2),fContainer->GetGrid(fSelDen)->Project(ivar1,ivar2),1.,1.,"B");

  fContainer->GetGrid(fSelNum)->UseAxisRange(kTRUE);
  fContainer->GetGrid(fSelDen)->UseAxisRange(kTRUE);
  proj2D->GetXaxis()->SetRange(
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar1)->GetFirst(),
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar1)->GetLast()
			       );
  proj2D->GetYaxis()->SetRange(
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar2)->GetFirst(),
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar2)->GetLast()
			       );

  delete [] bins1;
  delete [] bins2;
  return proj2D;
}
//___________________________________________________________________
TH3D *AliCFEffGrid::Project(Int_t ivar1, Int_t ivar2, Int_t ivar3) const
{
  //
  // Make a 3D projection along variable ivar1,ivar2,ivar3
  //

  TH3D *proj3D=0;

  Int_t nbins1 =fNVarBins[ivar1];
  Int_t nbins2 =fNVarBins[ivar2];
  Int_t nbins3 =fNVarBins[ivar3];

  Float_t *bins1 = new Float_t[nbins1+1];
  Float_t *bins2 = new Float_t[nbins2+1];
  Float_t *bins3 = new Float_t[nbins3+1];

  for(Int_t ibin =0;ibin<nbins1+1;ibin++){
    bins1[ibin] = fVarBinLimits[ibin+fOffset[ivar1]];
  }
  for(Int_t ibin =0;ibin<nbins2+1;ibin++){
    bins2[ibin] = fVarBinLimits[ibin+fOffset[ivar2]];
  }
  for(Int_t ibin =0;ibin<nbins3+1;ibin++){
    bins3[ibin] = fVarBinLimits[ibin+fOffset[ivar3]];
  }

  char pname[30];
  sprintf(pname,"%s%s%i%i%s%i%i%i",GetName(),"_SelStep",fSelNum,fSelDen,"_proj3D_var",ivar1,ivar2,ivar3);
  char htitle[30];
  sprintf(htitle,"%s%s%i%i%s%i%i%i",GetName(),"_SelStep",fSelNum,fSelDen,"_proj3D_var",ivar1,ivar2,ivar3);

  if(!proj3D){
    proj3D =new TH3D(pname,htitle, nbins1, bins1,nbins2,bins2,nbins3,bins3);
  }

  //unset the use of axis range to be able to divide the histos
  fContainer->GetGrid(fSelNum)->UseAxisRange(kFALSE);
  fContainer->GetGrid(fSelDen)->UseAxisRange(kFALSE);

  proj3D->Sumw2();
  proj3D->Divide(fContainer->GetGrid(fSelNum)->Project(ivar1,ivar2,ivar3),fContainer->GetGrid(fSelDen)->Project(ivar1,ivar2,ivar3),1.,1.,"B");

  fContainer->GetGrid(fSelNum)->UseAxisRange(kTRUE);
  fContainer->GetGrid(fSelDen)->UseAxisRange(kTRUE);

  proj3D->GetXaxis()->SetRange(
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar1)->GetFirst(),
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar1)->GetLast()
			       );
  proj3D->GetYaxis()->SetRange(
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar2)->GetFirst(),
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar2)->GetLast()
			       );
  proj3D->GetZaxis()->SetRange(
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar3)->GetFirst(),
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar3)->GetLast()
			       );

  delete [] bins1;
  delete [] bins2;
  delete [] bins3;

  return proj3D;
}

<commit_msg>Float_t -> Double_t in projection for axis consistency (C. Zampolli)<commit_after>/* $Id$ */
/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
//--------------------------------------------------------------------//
//                                                                    //
// AliCFEffGrid Class                                              //
// Class to handle efficiency grids                                   //
//                                                                    //
// -- Author : S.Arcelli                                              //
//                                                                    //
//                                                                    //
//                                                                    //
//--------------------------------------------------------------------//
//
//
#include "TMath.h"
#include "AliLog.h"
#include "AliCFEffGrid.h"
#include "TH1D.h"
#include "TH2D.h"
#include "TH3D.h"

//____________________________________________________________________
ClassImp(AliCFEffGrid)

//____________________________________________________________________
AliCFEffGrid::AliCFEffGrid() :
  AliCFGridSparse(),
  fContainer(0x0),
  fSelNum(-1),
  fSelDen(-1)
{
  //
  // default constructor
  //
}

//____________________________________________________________________
AliCFEffGrid::AliCFEffGrid(const Char_t* name, const Char_t* title, const Int_t nVarIn, const Int_t * nBinIn, const Double_t *binLimitsIn) :
  AliCFGridSparse(name,title,nVarIn,nBinIn,binLimitsIn),
  fContainer(0x0),
  fSelNum(-1),
  fSelDen(-1)
{
  //
  // ctor
  //
  SumW2();
}
//____________________________________________________________________
AliCFEffGrid::AliCFEffGrid(const Char_t* name, const Char_t* title, const AliCFContainer &c) :
  AliCFGridSparse(name,title,c.GetNVar(),c.GetNBins(),c.GetBinLimits()),
  fContainer(NULL),
  fSelNum(-1),
  fSelDen(-1)
{
  //
  // main constructor
  //
  SumW2();
  //assign the container;
  fContainer=&c;
}
//____________________________________________________________________
AliCFEffGrid::AliCFEffGrid(const AliCFEffGrid& eff) : AliCFGridSparse(),
  fContainer(0x0),
  fSelNum(-1),
  fSelDen(-1)
{
  //
  // copy constructor
  //
  ((AliCFEffGrid &)eff).Copy(*this);
}

//____________________________________________________________________
AliCFEffGrid::~AliCFEffGrid()
{
  //
  // destructor
  //
}

//____________________________________________________________________
AliCFEffGrid &AliCFEffGrid::operator=(const AliCFEffGrid &eff)
{
  //
  // assigment operator
  //
  if (this != &eff)
    ((AliCFEffGrid &) eff).Copy(*this);
  return *this;
}
//____________________________________________________________________

void AliCFEffGrid::CalculateEfficiency(Int_t istep1,Int_t istep2, Option_t *option)
{
  //
  // Calculate the efficiency matrix and its error between selection
  // Steps istep1 and istep2
  //

  fSelNum=istep1;
  fSelDen=istep2;
  AliCFVGrid *num=fContainer->GetGrid(fSelNum);
  AliCFVGrid *den=fContainer->GetGrid(fSelDen);
  num->SumW2();
  den->SumW2();
  this->SumW2();
  this->Divide(num,den,1.,1.,option);

  Int_t nEmptyBinsNum=0;
  Int_t nEmptyBinsNumAndDen=0;
  for(Int_t iel=0;iel<fNDim;iel++){
    if(den->GetElement(iel)>0){
      if(num->GetElement(iel)==0)nEmptyBinsNum++; //num==0,den!=0
    }
    else{
      nEmptyBinsNumAndDen++;
    }
  }
  // Some monitoring printout:
  AliInfo(Form("Efficiency calculated for steps %i and %i: %i empty bins in the numerator && !denominator and %i empty bins in numerator && denominator were found.",fSelNum,fSelDen,nEmptyBinsNumAndDen,nEmptyBinsNum));
  AliInfo(Form("The correction map contains %i empty bins ",nEmptyBinsNum+nEmptyBinsNumAndDen));
}
//_____________________________________________________________________
Double_t AliCFEffGrid::GetAverage() const
{
  //
  // Get the average efficiency
  //

  Double_t val=0;
  Double_t valnum=0;
  Double_t valden=0;
  for(Int_t i=0;i<fNDim;i++){
    valnum+=fContainer->GetGrid(fSelNum)->GetElement(i);
    valden+=fContainer->GetGrid(fSelDen)->GetElement(i);
  }
  if(valden>0)val=valnum/valden;
  AliInfo(Form(" The Average Efficiency = %f ",val));

  return val;
}
//_____________________________________________________________________
Double_t AliCFEffGrid::GetAverage(Double_t *varMin, Double_t* varMax ) const
{
  //
  // Get ave efficiency in a range
  //

  Double_t val=0;
  Int_t *indexMin = new Int_t[fNVar];
  Int_t *indexMax = new Int_t[fNVar];
  Int_t *index    = new Int_t[fNVar];

  //Find out the min and max bins

  for(Int_t i=0;i<fNVar;i++){
    Double_t xmin=varMin[i]; // the min values
    Double_t xmax=varMax[i]; // the max values
    Int_t nbins=fNVarBins[i]+1;
    Double_t *bins=new Double_t[nbins];
    for(Int_t ibin =0;ibin<nbins;ibin++){
      bins[ibin] = fVarBinLimits[ibin+fOffset[i]];
    }
    indexMin[i] = TMath::BinarySearch(nbins,bins,xmin);
    indexMax[i] = TMath::BinarySearch(nbins,bins,xmax);
    if(xmax>=bins[nbins-1]){
      indexMax[i]=indexMax[i]-1;
    }
    delete [] bins;
  }

  Double_t valnum=0;
  Double_t valden=0;
  for(Int_t i=0;i<fNDim;i++){
    for (Int_t j=0;j<fNVar;j++)index[j]=GetBinIndex(j,i);
    Bool_t isIn=kTRUE;
    for (Int_t j=0;j<fNVar;j++){
      if(!(index[j]>=indexMin[j] && index[j]<=indexMax[j]))isIn=kFALSE;
    }
    if(isIn){
      valnum+=fContainer->GetGrid(fSelNum)->GetElement(i);
      valden+=fContainer->GetGrid(fSelDen)->GetElement(i);
    }
  }
  delete [] index;
  delete [] indexMin;
  delete [] indexMax;
  if(valden>0)val=valnum/valden;
  AliInfo(Form(" the Average Efficiency = %f ",val));
  return val;
}
//____________________________________________________________________
void AliCFEffGrid::Copy(TObject& eff) const
{
  //
  // copy function
  //
  Copy(eff);
  AliCFEffGrid& target = (AliCFEffGrid &) eff;

  target.fSelNum=fSelNum;
  target.fSelDen=fSelDen;
  if(fContainer)
    target.fContainer=fContainer;
}
//___________________________________________________________________
TH1D *AliCFEffGrid::Project(Int_t ivar) const
{
  //
  // Make a 1D projection along variable ivar
  //

  TH1D *proj1D=0;
  Int_t nbins =fNVarBins[ivar];
  Double_t *bins = new Double_t[nbins+1];
  for(Int_t ibin =0;ibin<nbins+1;ibin++){
    bins[ibin] = fVarBinLimits[ibin+fOffset[ivar]];
  }

  char pname[30];
  sprintf(pname,"%s%s%i%i%s%i",GetName(),"_SelStep",fSelNum,fSelDen,"_proj1D_var", ivar);
  char htitle[30];
  sprintf(htitle,"%s%s%i%i%s%i",GetName(),"_SelStep",fSelNum,fSelDen,"_proj1D_var", ivar);

  if(!proj1D){
    proj1D =new TH1D(pname,htitle, nbins, bins);
  }

  //unset the use of axis range to be able to divide the histos
  fContainer->GetGrid(fSelNum)->UseAxisRange(kFALSE);
  fContainer->GetGrid(fSelDen)->UseAxisRange(kFALSE);

  proj1D->Sumw2();
  proj1D->Divide(fContainer->GetGrid(fSelNum)->Project(ivar),fContainer->GetGrid(fSelDen)->Project(ivar),1.,1.,"B");

  fContainer->GetGrid(fSelNum)->UseAxisRange(kTRUE);
  fContainer->GetGrid(fSelDen)->UseAxisRange(kTRUE);
  proj1D->GetXaxis()->SetRange(
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar)->GetFirst(),
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar)->GetLast()
			       );

  delete [] bins;
  return proj1D;
}
//___________________________________________________________________
TH2D *AliCFEffGrid::Project(Int_t ivar1,Int_t ivar2) const
{
  //
  // Make a 2D projection along variable ivar1,ivar2
  //

  TH2D *proj2D=0;

  Int_t nbins1 =fNVarBins[ivar1];
  Double_t *bins1 = new Double_t[nbins1+1];
  Int_t nbins2 =fNVarBins[ivar2];
  Double_t *bins2 = new Double_t[nbins2+1];
  for(Int_t ibin1 =0;ibin1<nbins1+1;ibin1++){
    bins1[ibin1] = fVarBinLimits[ibin1+fOffset[ivar1]];
  }
  for(Int_t ibin2 =0;ibin2<nbins2+1;ibin2++){
    bins2[ibin2] = fVarBinLimits[ibin2+fOffset[ivar2]];
  }

  char pname[30];
  sprintf(pname,"%s%s%i%i%s%i%i",GetName(),"_SelStep",fSelNum,fSelDen,"_proj2D_var", ivar1,ivar2);
  char htitle[30];
  sprintf(htitle,"%s%s%i%i%s%i%i",GetName(),"_SelStep",fSelNum,fSelDen,"_proj2D_var",ivar1,ivar2);

  if(!proj2D){
    proj2D =new TH2D(pname,htitle, nbins1,bins1,nbins2,bins2);
  }

  //unset the use of axis range to be able to divide the histos
  fContainer->GetGrid(fSelNum)->UseAxisRange(kFALSE);
  fContainer->GetGrid(fSelDen)->UseAxisRange(kFALSE);

  proj2D->Sumw2();
  proj2D->Divide(fContainer->GetGrid(fSelNum)->Project(ivar1,ivar2),fContainer->GetGrid(fSelDen)->Project(ivar1,ivar2),1.,1.,"B");

  fContainer->GetGrid(fSelNum)->UseAxisRange(kTRUE);
  fContainer->GetGrid(fSelDen)->UseAxisRange(kTRUE);
  proj2D->GetXaxis()->SetRange(
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar1)->GetFirst(),
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar1)->GetLast()
			       );
  proj2D->GetYaxis()->SetRange(
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar2)->GetFirst(),
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar2)->GetLast()
			       );

  delete [] bins1;
  delete [] bins2;
  return proj2D;
}
//___________________________________________________________________
TH3D *AliCFEffGrid::Project(Int_t ivar1, Int_t ivar2, Int_t ivar3) const
{
  //
  // Make a 3D projection along variable ivar1,ivar2,ivar3
  //

  TH3D *proj3D=0;

  Int_t nbins1 =fNVarBins[ivar1];
  Int_t nbins2 =fNVarBins[ivar2];
  Int_t nbins3 =fNVarBins[ivar3];

  Double_t *bins1 = new Double_t[nbins1+1];
  Double_t *bins2 = new Double_t[nbins2+1];
  Double_t *bins3 = new Double_t[nbins3+1];

  for(Int_t ibin =0;ibin<nbins1+1;ibin++){
    bins1[ibin] = fVarBinLimits[ibin+fOffset[ivar1]];
  }
  for(Int_t ibin =0;ibin<nbins2+1;ibin++){
    bins2[ibin] = fVarBinLimits[ibin+fOffset[ivar2]];
  }
  for(Int_t ibin =0;ibin<nbins3+1;ibin++){
    bins3[ibin] = fVarBinLimits[ibin+fOffset[ivar3]];
  }

  char pname[30];
  sprintf(pname,"%s%s%i%i%s%i%i%i",GetName(),"_SelStep",fSelNum,fSelDen,"_proj3D_var",ivar1,ivar2,ivar3);
  char htitle[30];
  sprintf(htitle,"%s%s%i%i%s%i%i%i",GetName(),"_SelStep",fSelNum,fSelDen,"_proj3D_var",ivar1,ivar2,ivar3);

  if(!proj3D){
    proj3D =new TH3D(pname,htitle, nbins1, bins1,nbins2,bins2,nbins3,bins3);
  }

  //unset the use of axis range to be able to divide the histos
  fContainer->GetGrid(fSelNum)->UseAxisRange(kFALSE);
  fContainer->GetGrid(fSelDen)->UseAxisRange(kFALSE);

  proj3D->Sumw2();
  proj3D->Divide(fContainer->GetGrid(fSelNum)->Project(ivar1,ivar2,ivar3),fContainer->GetGrid(fSelDen)->Project(ivar1,ivar2,ivar3),1.,1.,"B");

  fContainer->GetGrid(fSelNum)->UseAxisRange(kTRUE);
  fContainer->GetGrid(fSelDen)->UseAxisRange(kTRUE);

  proj3D->GetXaxis()->SetRange(
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar1)->GetFirst(),
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar1)->GetLast()
			       );
  proj3D->GetYaxis()->SetRange(
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar2)->GetFirst(),
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar2)->GetLast()
			       );
  proj3D->GetZaxis()->SetRange(
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar3)->GetFirst(),
			       ((AliCFGridSparse*)GetNum())->GetGrid()->GetAxis(ivar3)->GetLast()
			       );

  delete [] bins1;
  delete [] bins2;
  delete [] bins3;

  return proj3D;
}

<|endoftext|>