<commit_before>/*************************************************************************
 *
 *  $RCSfile: ZipPackageFolder.hxx,v $
 *
 *  $Revision: 1.33 $
 *
 *  last change: $Author: kz $ $Date: 2005-07-12 12:28:10 $
 *
 *  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): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/
#ifndef _ZIP_PACKAGE_FOLDER_HXX
#define _ZIP_PACKAGE_FOLDER_HXX

#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_
#include <com/sun/star/container/XEnumerationAccess.hpp>
#endif
#ifndef _HASHMAPS_HXX
#include <HashMaps.hxx>
#endif
#ifndef _ZIP_PACKAGE_ENTRY_HXX
#include <ZipPackageEntry.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

namespace com { namespace sun { namespace star {
namespace beans
{
    struct PropertyValue;
}
} } };
class ZipFile;
class ZipPackage;
class ZipOutputStream;
struct ZipEntry;
typedef void* rtlRandomPool;

class ZipPackageFolder : public cppu::ImplInheritanceHelper2
<
    ZipPackageEntry,
    ::com::sun::star::container::XNameContainer,
    ::com::sun::star::container::XEnumerationAccess
>
{
    static com::sun::star::uno::Sequence < sal_Int8 > aImplementationId;

protected:
    ContentHash maContents;
    const ::com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > m_xFactory;
    sal_Bool m_bPackageFormat;

public:

    ZipPackageFolder( const ::com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory >& xFactory,
                      sal_Bool bPackageFormat,
                      sal_Bool bAllowRemoveOnInsert );
    virtual ~ZipPackageFolder();

    void doInsertByName ( ZipPackageEntry *pEntry, sal_Bool bSetParent )
        throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    com::sun::star::packages::ContentInfo & doGetByName( const ::rtl::OUString& aName )
        throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    static void copyZipEntry( ZipEntry &rDest, const ZipEntry &rSource);
    static ::com::sun::star::uno::Sequence < sal_Int8 > static_getImplementationId()
    {
        return aImplementationId;
    }

    void setPackageFormat_Impl( sal_Bool bPackageFormat ) { m_bPackageFormat = bPackageFormat; }
    void setRemoveOnInsertMode_Impl( sal_Bool bRemove ) { ZipPackageEntry::mbAllowRemoveOnInsert = bRemove; }

    // Recursive functions
    void  saveContents(rtl::OUString &rPath, std::vector < com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue > > &rManList, ZipOutputStream & rZipOut, com::sun::star::uno::Sequence < sal_Int8 > &rEncryptionKey, rtlRandomPool & rRandomPool)
        throw(::com::sun::star::uno::RuntimeException);
    void  releaseUpwardRef();

    // XNameContainer
    virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement )
        throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeByName( const ::rtl::OUString& Name )
        throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XEnumerationAccess
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XEnumeration > SAL_CALL createEnumeration(  )
        throw(::com::sun::star::uno::RuntimeException);

    // XElementAccess
    virtual ::com::sun::star::uno::Type SAL_CALL getElementType(  )
        throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasElements(  )
        throw(::com::sun::star::uno::RuntimeException);

    // XNameAccess
    virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName )
        throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames(  )
        throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName )
        throw(::com::sun::star::uno::RuntimeException);

    // XNameReplace
    virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement )
        throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XPropertySet
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XUnoTunnel
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier )
        throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  )
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  )
        throw (::com::sun::star::uno::RuntimeException);
};
#endif
<commit_msg>INTEGRATION: CWS gslpatches4 (1.33.2); FILE MERGED 2005/07/19 13:48:39 mav 1.33.2.1: #i51940# apply the patch<commit_after>/*************************************************************************
 *
 *  $RCSfile: ZipPackageFolder.hxx,v $
 *
 *  $Revision: 1.34 $
 *
 *  last change: $Author: kz $ $Date: 2005-08-25 16:16:29 $
 *
 *  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): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/
#ifndef _ZIP_PACKAGE_FOLDER_HXX
#define _ZIP_PACKAGE_FOLDER_HXX

#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_
#include <com/sun/star/container/XEnumerationAccess.hpp>
#endif
#ifndef _HASHMAPS_HXX
#include <HashMaps.hxx>
#endif
#ifndef _ZIP_PACKAGE_ENTRY_HXX
#include <ZipPackageEntry.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

namespace com { namespace sun { namespace star {
namespace beans
{
    struct PropertyValue;
}
} } };
class ZipFile;
class ZipPackage;
class ZipOutputStream;
struct ZipEntry;
typedef void* rtlRandomPool;

class ZipPackageFolder : public cppu::ImplInheritanceHelper2
<
    ZipPackageEntry,
    ::com::sun::star::container::XNameContainer,
    ::com::sun::star::container::XEnumerationAccess
>
{
    static com::sun::star::uno::Sequence < sal_Int8 > aImplementationId;

protected:
    ContentHash maContents;
    const ::com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > m_xFactory;
    sal_Bool m_bPackageFormat;

public:

    ZipPackageFolder( const ::com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory >& xFactory,
                      sal_Bool bPackageFormat,
                      sal_Bool bAllowRemoveOnInsert );
    virtual ~ZipPackageFolder();

    void doInsertByName ( ZipPackageEntry *pEntry, sal_Bool bSetParent )
        throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    com::sun::star::packages::ContentInfo & doGetByName( const ::rtl::OUString& aName )
        throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    static void copyZipEntry( ZipEntry &rDest, const ZipEntry &rSource);
    static ::com::sun::star::uno::Sequence < sal_Int8 > static_getImplementationId()
    {
        return aImplementationId;
    }

    void setPackageFormat_Impl( sal_Bool bPackageFormat ) { m_bPackageFormat = bPackageFormat; }
    void setRemoveOnInsertMode_Impl( sal_Bool bRemove ) { this->mbAllowRemoveOnInsert = bRemove; }

    // Recursive functions
    void  saveContents(rtl::OUString &rPath, std::vector < com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue > > &rManList, ZipOutputStream & rZipOut, com::sun::star::uno::Sequence < sal_Int8 > &rEncryptionKey, rtlRandomPool & rRandomPool)
        throw(::com::sun::star::uno::RuntimeException);
    void  releaseUpwardRef();

    // XNameContainer
    virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement )
        throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeByName( const ::rtl::OUString& Name )
        throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XEnumerationAccess
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XEnumeration > SAL_CALL createEnumeration(  )
        throw(::com::sun::star::uno::RuntimeException);

    // XElementAccess
    virtual ::com::sun::star::uno::Type SAL_CALL getElementType(  )
        throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasElements(  )
        throw(::com::sun::star::uno::RuntimeException);

    // XNameAccess
    virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName )
        throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames(  )
        throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName )
        throw(::com::sun::star::uno::RuntimeException);

    // XNameReplace
    virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement )
        throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XPropertySet
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XUnoTunnel
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier )
        throw(::com::sun::star::uno::RuntimeException);

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


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"

#define VERIFY_TRSM(TRI,XB) { \
    (XB).setRandom(); ref = (XB); \
    (TRI).solveInPlace(XB); \
    VERIFY_IS_APPROX((TRI).toDenseMatrix() * (XB), ref); \
  }

#define VERIFY_TRSM_ONTHERIGHT(TRI,XB) { \
    (XB).setRandom(); ref = (XB); \
    (TRI).transpose().template solveInPlace<OnTheRight>(XB.transpose()); \
    VERIFY_IS_APPROX((XB).transpose() * (TRI).transpose().toDenseMatrix(), ref.transpose()); \
  }

template<typename Scalar,int Size, int Cols> void trsolve(int size=Size,int cols=Cols)
{
  typedef typename NumTraits<Scalar>::Real RealScalar;

  Matrix<Scalar,Size,Size,ColMajor> cmLhs(size,size);
  Matrix<Scalar,Size,Size,RowMajor> rmLhs(size,size);

  enum {  colmajor = Size==1 ? RowMajor : ColMajor,
          rowmajor = Cols==1 ? ColMajor : RowMajor };
  Matrix<Scalar,Size,Cols,colmajor> cmRhs(size,cols), ref(size,cols);
  Matrix<Scalar,Size,Cols,rowmajor> rmRhs(size,cols);

  cmLhs.setRandom(); cmLhs *= static_cast<RealScalar>(0.1); cmLhs.diagonal().array() += static_cast<RealScalar>(1);
  rmLhs.setRandom(); rmLhs *= static_cast<RealScalar>(0.1); rmLhs.diagonal().array() += static_cast<RealScalar>(1);

  VERIFY_TRSM(cmLhs.conjugate().template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM(cmLhs.adjoint()  .template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM(cmLhs            .template triangularView<Upper>(), cmRhs);
  VERIFY_TRSM(cmLhs            .template triangularView<Lower>(), rmRhs);
  VERIFY_TRSM(cmLhs.conjugate().template triangularView<Upper>(), rmRhs);
  VERIFY_TRSM(cmLhs.adjoint()  .template triangularView<Upper>(), rmRhs);

  VERIFY_TRSM(cmLhs.conjugate().template triangularView<UnitLower>(), cmRhs);
  VERIFY_TRSM(cmLhs            .template triangularView<UnitUpper>(), rmRhs);

  VERIFY_TRSM(rmLhs            .template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM(rmLhs.conjugate().template triangularView<UnitUpper>(), rmRhs);

  VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs            .template triangularView<Upper>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs            .template triangularView<Lower>(), rmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<Upper>(), rmRhs);

  VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<UnitLower>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs            .template triangularView<UnitUpper>(), rmRhs);

  VERIFY_TRSM_ONTHERIGHT(rmLhs            .template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(rmLhs.conjugate().template triangularView<UnitUpper>(), rmRhs);

  int c = internal::random<int>(0,cols-1);
  VERIFY_TRSM(rmLhs.template triangularView<Lower>(), rmRhs.col(c));
  VERIFY_TRSM(cmLhs.template triangularView<Lower>(), rmRhs.col(c));
}

void test_product_trsolve()
{
  for(int i = 0; i < g_repeat ; i++)
  {
    // matrices
    CALL_SUBTEST_1((trsolve<float,Dynamic,Dynamic>(internal::random<int>(1,320),internal::random<int>(1,320))));
    CALL_SUBTEST_2((trsolve<double,Dynamic,Dynamic>(internal::random<int>(1,320),internal::random<int>(1,320))));
    CALL_SUBTEST_3((trsolve<std::complex<float>,Dynamic,Dynamic>(internal::random<int>(1,200),internal::random<int>(1,200))));
    CALL_SUBTEST_4((trsolve<std::complex<double>,Dynamic,Dynamic>(internal::random<int>(1,200),internal::random<int>(1,200))));

    // vectors
    CALL_SUBTEST_1((trsolve<float,Dynamic,1>(internal::random<int>(1,320))));
    CALL_SUBTEST_5((trsolve<std::complex<double>,Dynamic,1>(internal::random<int>(1,320))));
    CALL_SUBTEST_6((trsolve<float,1,1>()));
    CALL_SUBTEST_7((trsolve<float,1,2>()));
    CALL_SUBTEST_8((trsolve<std::complex<float>,4,1>()));
  }
}
<commit_msg>fix bug 120 : compilation issue of trsolve unit test<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"

#define VERIFY_TRSM(TRI,XB) { \
    (XB).setRandom(); ref = (XB); \
    (TRI).solveInPlace(XB); \
    VERIFY_IS_APPROX((TRI).toDenseMatrix() * (XB), ref); \
  }

#define VERIFY_TRSM_ONTHERIGHT(TRI,XB) { \
    (XB).setRandom(); ref = (XB); \
    (TRI).transpose().template solveInPlace<OnTheRight>(XB.transpose()); \
    VERIFY_IS_APPROX((XB).transpose() * (TRI).transpose().toDenseMatrix(), ref.transpose()); \
  }

template<typename Scalar,int Size, int Cols> void trsolve(int size=Size,int cols=Cols)
{
  typedef typename NumTraits<Scalar>::Real RealScalar;

  Matrix<Scalar,Size,Size,ColMajor> cmLhs(size,size);
  Matrix<Scalar,Size,Size,RowMajor> rmLhs(size,size);

  enum {  colmajor = Size==1 ? RowMajor : ColMajor,
          rowmajor = Cols==1 ? ColMajor : RowMajor };
  Matrix<Scalar,Size,Cols,colmajor> cmRhs(size,cols);
  Matrix<Scalar,Size,Cols,rowmajor> rmRhs(size,cols);
  Matrix<Scalar,Dynamic,Dynamic,colmajor> ref(size,cols);

  cmLhs.setRandom(); cmLhs *= static_cast<RealScalar>(0.1); cmLhs.diagonal().array() += static_cast<RealScalar>(1);
  rmLhs.setRandom(); rmLhs *= static_cast<RealScalar>(0.1); rmLhs.diagonal().array() += static_cast<RealScalar>(1);

  VERIFY_TRSM(cmLhs.conjugate().template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM(cmLhs.adjoint()  .template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM(cmLhs            .template triangularView<Upper>(), cmRhs);
  VERIFY_TRSM(cmLhs            .template triangularView<Lower>(), rmRhs);
  VERIFY_TRSM(cmLhs.conjugate().template triangularView<Upper>(), rmRhs);
  VERIFY_TRSM(cmLhs.adjoint()  .template triangularView<Upper>(), rmRhs);

  VERIFY_TRSM(cmLhs.conjugate().template triangularView<UnitLower>(), cmRhs);
  VERIFY_TRSM(cmLhs            .template triangularView<UnitUpper>(), rmRhs);

  VERIFY_TRSM(rmLhs            .template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM(rmLhs.conjugate().template triangularView<UnitUpper>(), rmRhs);

  VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs            .template triangularView<Upper>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs            .template triangularView<Lower>(), rmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<Upper>(), rmRhs);

  VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<UnitLower>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs            .template triangularView<UnitUpper>(), rmRhs);

  VERIFY_TRSM_ONTHERIGHT(rmLhs            .template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(rmLhs.conjugate().template triangularView<UnitUpper>(), rmRhs);

  int c = internal::random<int>(0,cols-1);
  VERIFY_TRSM(rmLhs.template triangularView<Lower>(), rmRhs.col(c));
  VERIFY_TRSM(cmLhs.template triangularView<Lower>(), rmRhs.col(c));
}

void test_product_trsolve()
{
  for(int i = 0; i < g_repeat ; i++)
  {
    // matrices
    CALL_SUBTEST_1((trsolve<float,Dynamic,Dynamic>(internal::random<int>(1,320),internal::random<int>(1,320))));
    CALL_SUBTEST_2((trsolve<double,Dynamic,Dynamic>(internal::random<int>(1,320),internal::random<int>(1,320))));
    CALL_SUBTEST_3((trsolve<std::complex<float>,Dynamic,Dynamic>(internal::random<int>(1,200),internal::random<int>(1,200))));
    CALL_SUBTEST_4((trsolve<std::complex<double>,Dynamic,Dynamic>(internal::random<int>(1,200),internal::random<int>(1,200))));

    // vectors
    CALL_SUBTEST_1((trsolve<float,Dynamic,1>(internal::random<int>(1,320))));
    CALL_SUBTEST_5((trsolve<std::complex<double>,Dynamic,1>(internal::random<int>(1,320))));
    CALL_SUBTEST_6((trsolve<float,1,1>()));
    CALL_SUBTEST_7((trsolve<float,1,2>()));
    CALL_SUBTEST_8((trsolve<std::complex<float>,4,1>()));
  }
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#define DUNE_GDT_TEST_SPACES_RT_CHECK 1

// This one has to come first (includes the config.h)!
#include <dune/stuff/test/main.hxx>

#include "spaces_rt.hh"
#include "spaces_rt_pdelab.hh"

typedef testing::Types<SPACES_RT_PDELAB
#if HAVE_ALUGRID
                       ,
                       SPACES_RT_PDELAB_ALUGRID
#endif
                       > RT_Spaces;

TYPED_TEST_CASE(RT_Space, RT_Spaces);
TYPED_TEST(RT_Space, fulfills_interface)
{
  this->fulfills_interface();
}
TYPED_TEST(RT_Space, mapper_fulfills_interface)
{
  this->mapper_fulfills_interface();
}
TYPED_TEST(RT_Space, basefunctionset_fulfills_interface)
{
  this->basefunctionset_fulfills_interface();
}
TYPED_TEST(RT_Space, check_for_correct_copy)
{
  this->check_for_correct_copy();
}
<commit_msg>[test.spaces_rt_pdelab] add tests<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#define DUNE_GDT_TEST_SPACES_RT_CHECK 1

// This one has to come first (includes the config.h)!
#include <dune/stuff/test/main.hxx>

#include "spaces_rt.hh"
#include "spaces_rt_pdelab.hh"

typedef testing::Types<SPACES_RT_PDELAB
#if HAVE_ALUGRID
                       ,
                       SPACES_RT_PDELAB_ALUGRID
#endif
                       > RT_Spaces;

TYPED_TEST_CASE(RT_Space, RT_Spaces);
TYPED_TEST(RT_Space, fulfills_interface)
{
  this->fulfills_interface();
}
TYPED_TEST(RT_Space, mapper_fulfills_interface)
{
  this->mapper_fulfills_interface();
}
TYPED_TEST(RT_Space, basefunctionset_fulfills_interface)
{
  this->basefunctionset_fulfills_interface();
}
TYPED_TEST(RT_Space, check_for_correct_copy)
{
  this->check_for_correct_copy();
}
TYPED_TEST(RT_Space, matches_raviart_thomas_signature)
{
  this->matches_raviart_thomas_signature();
}

#if HAVE_ALUGRID

typedef testing::Types<SPACE_RT_PDELAB_ALUCONFORMGRID(2)> RT_2d_Spaces;

TYPED_TEST_CASE(RT_2d_simplicial_Space, RT_2d_Spaces);
TYPED_TEST(RT_2d_simplicial_Space, fulfills_raviart_thomas_2d_simplicial_interface)
{
  this->fulfills_raviart_thomas_2d_simplicial_interface();
}

#else // HAVE_ALUGRID

TYPED_TEST(DISABLED_RT_2d_simplicial_Space, fulfills_raviart_thomas_2d_simplicial_interface)
{
}

#endif // HAVE_ALUGRID
<|endoftext|>


<commit_before>#include "test-drafter.h"

#include <string>

#include "snowcrash.h"

#include "sosJSON.h"
#include "SerializeAST.h"

bool HandleFixtureTest(const std::string& basepath)
{
    ITFixtureFiles fixture = ITFixtureFiles(basepath);

    snowcrash::ParseResult<snowcrash::Blueprint> blueprint;
    int result = snowcrash::parse(fixture.get(".apib"), 0, blueprint);

    REQUIRE(result == snowcrash::Error::OK);

    std::stringstream outStream;
    sos::SerializeJSON serializer;

    serializer.process(drafter::WrapBlueprint(blueprint.node), outStream);
    outStream << "\n";

    return (outStream.str() == fixture.get(".json"));
}

TEST_CASE("Testing refract serialization for primitive types","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-primitives"));
}

TEST_CASE("Testing refract serialization for named types with inheritance","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-inheritance"));
}

TEST_CASE("Testing refract serialization for array[type]","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-typed-array"));
}

TEST_CASE("Testing refract serialization for typed object","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-typed-object"));
}

TEST_CASE("Testing refract serialization for nontypped object","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-nontyped-object"));
}

TEST_CASE("Testing refract serialization for enums","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-enum"));
}

TEST_CASE("Testing refract serialization for oneof","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-enum"));
}

TEST_CASE("Testing refract serialization for mixin","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-mixin"));
}

TEST_CASE("Testing refract serialization for primitive with samples","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-string-sample"));
}

TEST_CASE("Testing refract serialization for typed array samples","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-typed-array-sample"));
}

TEST_CASE("Testing refract serialization for 'One Of' with grouped elements","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-group"));
}

TEST_CASE("Testing refract serialization array with empty sample","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-empty-sample"));
}

TEST_CASE("Testing refract serialization with inner inheritance","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-inheritance"));
}

TEST_CASE("Testing refract serialization oneof w/ sample","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-oneof-sample"));
}

TEST_CASE("Testing refract serialization with multiline comments","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-multiline-description"));
}

TEST_CASE("Testing refract serialization for primitive variables","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-primitive-variables"));
}

TEST_CASE("Testing refract serialization for NamedTypes w/ type specification","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-named-with-types"));
}

TEST_CASE("Testing refract serialization for nontypes array","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-nontyped-array"));
}

TEST_CASE("Testing refract serialization for wrong number value","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-number-wrong-value"));
}

TEST_CASE("Testing refract serialization for enum samples","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-enum-sample"));
}

TEST_CASE("Testing refract serialization primitive elements w/ members","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-primitive-with-members"));
}

TEST_CASE("Testing refract serialization of nontyped array w/ samples","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-nontyped-array-sample"));
}
<commit_msg>Refract fixtures testing - allow optional skip test for parser result<commit_after>#include "test-drafter.h"

#include <string>

#include "snowcrash.h"

#include "sosJSON.h"
#include "SerializeAST.h"

bool HandleFixtureTest(const std::string& basepath, bool mustBeOk = true)
{
    ITFixtureFiles fixture = ITFixtureFiles(basepath);

    snowcrash::ParseResult<snowcrash::Blueprint> blueprint;
    int result = snowcrash::parse(fixture.get(".apib"), 0, blueprint);

    if (mustBeOk) {
        REQUIRE(result == snowcrash::Error::OK);
    }

    std::stringstream outStream;
    sos::SerializeJSON serializer;

    serializer.process(drafter::WrapBlueprint(blueprint.node), outStream);
    outStream << "\n";

    return (outStream.str() == fixture.get(".json"));
}

TEST_CASE("Testing refract serialization for primitive types","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-primitives"));
}

TEST_CASE("Testing refract serialization for named types with inheritance","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-inheritance"));
}

TEST_CASE("Testing refract serialization for array[type]","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-typed-array"));
}

TEST_CASE("Testing refract serialization for typed object","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-typed-object"));
}

TEST_CASE("Testing refract serialization for nontypped object","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-nontyped-object"));
}

TEST_CASE("Testing refract serialization for enums","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-enum"));
}

TEST_CASE("Testing refract serialization for oneof","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-enum"));
}

TEST_CASE("Testing refract serialization for mixin","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-mixin"));
}

TEST_CASE("Testing refract serialization for primitive with samples","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-string-sample"));
}

TEST_CASE("Testing refract serialization for typed array samples","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-typed-array-sample"));
}

TEST_CASE("Testing refract serialization for 'One Of' with grouped elements","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-group"));
}

TEST_CASE("Testing refract serialization array with empty sample","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-empty-sample"));
}

TEST_CASE("Testing refract serialization with inner inheritance","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-inheritance"));
}

TEST_CASE("Testing refract serialization oneof w/ sample","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-oneof-sample"));
}

TEST_CASE("Testing refract serialization with multiline comments","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-multiline-description"));
}

TEST_CASE("Testing refract serialization for primitive variables","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-primitive-variables"));
}

TEST_CASE("Testing refract serialization for NamedTypes w/ type specification","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-named-with-types"));
}

TEST_CASE("Testing refract serialization for nontypes array","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-nontyped-array"));
}

TEST_CASE("Testing refract serialization for wrong number value","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-number-wrong-value"));
}

TEST_CASE("Testing refract serialization for enum samples","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-enum-sample"));
}

TEST_CASE("Testing refract serialization primitive elements w/ members","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-primitive-with-members", false));
}

TEST_CASE("Testing refract serialization of nontyped array w/ samples","[refract]")
{
    REQUIRE(HandleFixtureTest("test/fixtures/mson-nontyped-array-sample"));
}
<|endoftext|>


<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "test_optimizers"

#include <boost/test/unit_test.hpp>
#include "libnanocv/optimize.h"
#include "libnanocv/util/abs.hpp"
#include "libnanocv/util/math.hpp"
#include "libnanocv/util/logger.h"
#include "libnanocv/util/epsilon.hpp"
#include <iostream>

namespace test
{
        using namespace ncv;

        void check_solution(const opt_state_t& state, const std::vector<std::pair<vector_t, scalar_t>>& solutions)
        {
                // Find the closest solution
                size_t best_index = std::string::npos;
                scalar_t best_distance = std::numeric_limits<scalar_t>::max();

                for (size_t index = 0; index < solutions.size(); index ++)
                {
                        const scalar_t distance = (state.x - solutions[index].first).lpNorm<Eigen::Infinity>();
                        if (distance < best_distance)
                        {
                                best_distance = distance;
                                best_index = index;
                        }
                }

//                // Check accuracy
//                BOOST_CHECK_LE(best_index, solutions.size());
//                if (best_index < solutions.size())
//                {
//                        const scalar_t epsilon = math::epsilon1<scalar_t>();

//                        const scalar_t dfx = math::abs(state.f - solutions[best_index].second);
//                        const scalar_t dx = (state.x - solutions[best_index].first).lpNorm<Eigen::Infinity>();

//                        BOOST_CHECK_LE(dfx, epsilon);
//                        BOOST_CHECK_LE(dx, epsilon);
//                }
        }

        void check_problem(
                const string_t& name,
                const opt_opsize_t& fn_size, const opt_opfval_t& fn_fval, const opt_opgrad_t& fn_grad,
                const std::vector<std::pair<vector_t, scalar_t>>& solutions)
        {
                const size_t iterations = 8 * 1024;
                const scalar_t epsilon = math::epsilon1<scalar_t>();
                const size_t history = 6;

                const auto optimizers =
                {
                        batch_optimizer::GD,
                        batch_optimizer::CGD,
                        batch_optimizer::LBFGS
                };

                const size_t dims = fn_size();

                vector_t x0(dims);
                x0.setRandom();

                for (batch_optimizer optimizer : optimizers)
                {
                        const opt_state_t state = ncv::minimize(fn_size, fn_fval, fn_grad, nullptr, nullptr, nullptr,
                                                                x0, optimizer, iterations, epsilon, history);

                        log_info() << "[" << name << "], dims = " << fn_size()
                                   << ", optimizer = " << text::to_string(optimizer)
                                   << ", x = " << state.x.transpose()
                                   << ", fx = " << state.f
                                   << ", gx = " << state.g.lpNorm<Eigen::Infinity>()
                                   << ", evals = " << state.m_n_fvals << "/" << state.m_n_grads;

                        check_solution(state, solutions);
                }

                log_info();
        }
}

BOOST_AUTO_TEST_CASE(test_optimizers)
{
        using namespace ncv;

//        https://en.wikipedia.org/wiki/Test_functions_for_optimization

        // Sphere function
        for (size_t dims = 1; dims <= 8; dims ++)
        {
                const opt_opsize_t fn_size = [=] ()
                {
                        return dims;
                };

                const opt_opfval_t fn_fval = [=] (const vector_t& x)
                {
                        scalar_t fx = 0;
                        for (size_t i = 0; i < dims; i ++)
                        {
                                fx += x(i) * x(i);
                        }

                        return fx;
                };

                const opt_opgrad_t fn_grad = [=] (const vector_t& x, vector_t& gx)
                {
                        gx.resize(dims);
                        for (size_t i = 0; i < dims; i ++)
                        {
                                gx(i) = 2 * x(i);
                        }

                        return fn_fval(x);
                };

                std::vector<std::pair<vector_t, scalar_t>> solutions;
                {
                        solutions.emplace_back(vector_t::Zero(dims), 0);
                }

                test::check_problem("sphere", fn_size, fn_fval, fn_grad, solutions);
        }

        // Rosenbrock function
        for (size_t dims = 2; dims <= 8; dims ++)
        {
                const opt_opsize_t fn_size = [=] ()
                {
                        return dims;
                };

                const opt_opfval_t fn_fval = [=] (const vector_t& x)
                {
                        scalar_t fx = 0;
                        for (size_t i = 0; i + 1 < dims; i ++)
                        {
                                fx += 100.0 * math::square(x(i + 1) - x(i) * x(i)) + math::square(x(i) - 1);
                        }

                        return fx;
                };

                const opt_opgrad_t fn_grad = [=] (const vector_t& x, vector_t& gx)
                {
                        gx.resize(dims);
                        gx.setZero();
                        for (size_t i = 0; i + 1 < dims; i ++)
                        {
                                gx(i) += 2.0 * (x(i) - 1);
                                gx(i) += 100.0 * 2.0 * (x(i + 1) - x(i) * x(i)) * (- 2.0 * x(i));
                                gx(i + 1) += 100.0 * 2.0 * (x(i + 1) - x(i) * x(i));
                        }

                        return fn_fval(x);
                };

                std::vector<std::pair<vector_t, scalar_t>> solutions;
                {
                        solutions.emplace_back(vector_t::Ones(dims), 0);
                }

                test::check_problem("Rosenbrock", fn_size, fn_fval, fn_grad, solutions);
        }

        // Beale function
        {
                const opt_opsize_t fn_size = [=] ()
                {
                        return 2;
                };

                const opt_opfval_t fn_fval = [=] (const vector_t& x)
                {
                        const scalar_t a = x(0), b = x(1);

                        const scalar_t z0 = 1.5 - a + a * b;
                        const scalar_t z1 = 2.25 - a + a * b * b;
                        const scalar_t z2 = 2.625 - a + a * b * b * b;

                        return z0 * z0 + z1 * z1 + z2 * z2;
                };

                const opt_opgrad_t fn_grad = [=] (const vector_t& x, vector_t& gx)
                {
                        const scalar_t a = x(0), b = x(1);

                        const scalar_t z0 = 1.5 - a + a * b;
                        const scalar_t z1 = 2.25 - a + a * b * b;
                        const scalar_t z2 = 2.625 - a + a * b * b * b;

                        gx.resize(2);
                        gx(0) = 2.0 * (- z0 + z0 * b - z1 + z1 * b * b - z2 + z2 * b * b * b);
                        gx(1) = 2.0 * (z0 * a + z1 * a * 2.0 * b + z2 * a * 3.0 * b * b);

                        return fn_fval(x);
                };

                std::vector<std::pair<vector_t, scalar_t>> solutions;
                {
                        vector_t x(2);
                        x(0) = 3.0;
                        x(1) = 0.5;
                        solutions.emplace_back(x, 0);
                }

                test::check_problem("Beale", fn_size, fn_fval, fn_grad, solutions);
        }

        // Goldstein-Price function
        {
                const opt_opsize_t fn_size = [=] ()
                {
                        return 2;
                };

                const opt_opfval_t fn_fval = [=] (const vector_t& x)
                {
                        const scalar_t a = x(0), b = x(1);

                        const scalar_t z0 = 1.0 + a + b;
                        const scalar_t z1 = 19 - 14 * a + 3 * a * a - 14 * b + 6 * a * b + 3 * b * b;
                        const scalar_t z2 = 2 * a - 3 * b;
                        const scalar_t z3 = 18 - 32 * a + 12 * a * a + 48 * b - 36 * a * b + 27 * b * b;

                        return (1 + z0 * z0 * z1) * (30 + z2 * z2 * z3);
                };

                const opt_opgrad_t fn_grad = [=] (const vector_t& x, vector_t& gx)
                {
                        const scalar_t a = x(0), b = x(1);

                        const scalar_t z0 = 1.0 + a + b;
                        const scalar_t z1 = 19 - 14 * a + 3 * a * a - 14 * b + 6 * a * b + 3 * b * b;
                        const scalar_t z2 = 2 * a - 3 * b;
                        const scalar_t z3 = 18 - 32 * a + 12 * a * a + 48 * b - 36 * a * b + 27 * b * b;

                        const scalar_t u = 1 + z0 * z0 * z1;
                        const scalar_t v = 30 + z2 * z2 * z3;

                        gx.resize(2);
                        gx(0) = u * (2 * z2 * (+2) * z3 + z2 * z2 * (-32 + 24 * a - 36 * b)) +
                                v * (2 * z0 * (+1) * z1 + z0 * z0 * (-14 + 6 * a + 6 * b));
                        gx(1) = u * (2 * z2 * (-3) * z3 + z2 * z2 * (+48 - 36 * a + 54 * b)) +
                                v * (2 * z0 * (+1) * z1 + z0 * z0 * (-14 + 6 * a + 6 * b));

                        return fn_fval(x);
                };

                std::vector<std::pair<vector_t, scalar_t>> solutions;
                {
                        vector_t x(2);
                        x(0) = 0.0;
                        x(1) = -1.0;
                        solutions.emplace_back(x, 3.0);
                }

                test::check_problem("Goldstein-Price", fn_size, fn_fval, fn_grad, solutions);
        }
}

<commit_msg>more test functions to optimize<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "test_optimizers"

#include <boost/test/unit_test.hpp>
#include "libnanocv/optimize.h"
#include "libnanocv/util/abs.hpp"
#include "libnanocv/util/math.hpp"
#include "libnanocv/util/logger.h"
#include "libnanocv/util/epsilon.hpp"
#include <iostream>

namespace test
{
        using namespace ncv;

        void check_solution(const string_t& problem_name, const string_t& optimizer_name,
                const opt_state_t& state, const std::vector<std::pair<vector_t, scalar_t>>& solutions)
        {
                // Find the closest solution
                size_t best_index = std::string::npos;
                scalar_t best_distance = std::numeric_limits<scalar_t>::max();

                for (size_t index = 0; index < solutions.size(); index ++)
                {
                        const scalar_t distance = (state.x - solutions[index].first).lpNorm<Eigen::Infinity>();
                        if (distance < best_distance)
                        {
                                best_distance = distance;
                                best_index = index;
                        }
                }

                // Check accuracy
                BOOST_CHECK_LE(best_index, solutions.size());
                if (best_index < solutions.size())
                {
                        const scalar_t dfx = math::abs(state.f - solutions[best_index].second);
                        const scalar_t dx = (state.x - solutions[best_index].first).lpNorm<Eigen::Infinity>();

                        BOOST_CHECK_LE(dfx, math::epsilon3<scalar_t>());
                        BOOST_CHECK_LE(dx, math::epsilon3<scalar_t>());

                        if (dfx > math::epsilon3<scalar_t>())
                        {
                                log_error() << "fx = " << state.f << ", x = " << state.x.transpose()
                                            << "@" << problem_name << "/" << optimizer_name;
                        }
                        if (dx > math::epsilon3<scalar_t>())
                        {
                                log_error() << "fx = " << state.f << ", x = " << state.x.transpose()
                                            << "@" << problem_name << "/" << optimizer_name;
                        }
                }
        }

        void check_problem(
                const string_t& problem_name,
                const opt_opsize_t& fn_size, const opt_opfval_t& fn_fval, const opt_opgrad_t& fn_grad,
                const std::vector<std::pair<vector_t, scalar_t>>& solutions)
        {
                const size_t iterations = 8 * 1024;
                const scalar_t epsilon = math::epsilon1<scalar_t>();
                const size_t history = 6;

                const size_t trials = 16;

                const auto optimizers =
                {
                        batch_optimizer::GD,
                        batch_optimizer::CGD,
                        batch_optimizer::LBFGS
                };

                const size_t dims = fn_size();

                for (size_t t = 0; t < trials; t ++)
                {
                        vector_t x0(dims);
                        x0.setRandom();

                        // check gradient
                        const opt_problem_t fval_problem(fn_size, fn_fval);
                        const opt_problem_t grad_problem(fn_size, fn_fval, fn_grad);

                        vector_t fval_gx0, grad_gx0;
                        fval_problem(x0, fval_gx0);
                        grad_problem(x0, grad_gx0);

                        BOOST_CHECK_LE((fval_gx0 - grad_gx0).lpNorm<Eigen::Infinity>(), math::epsilon3<scalar_t>());

//                        log_info() << "[" << problem_name << ", " << (t + 1) << "/" << trials << ", dims = " << dims << "]"
//                                   << ", dgx = " << (fval_gx0 - grad_gx0).lpNorm<Eigen::Infinity>();

                        // optimize & check solutions
                        for (batch_optimizer optimizer : optimizers)
                        {
                                const opt_state_t state = ncv::minimize(
                                        fn_size, fn_fval, fn_grad, nullptr, nullptr, nullptr,
                                        x0, optimizer, iterations, epsilon, history);

                                log_info() << "[" << problem_name << ", " << (t + 1) << "/" << trials << ", dims = " << dims << "]"
                                           << ", optimizer = " << text::to_string(optimizer)
                                           << ", x = " << state.x.transpose()
                                           << ", fx = " << state.f
                                           << ", gx = " << state.g.lpNorm<Eigen::Infinity>()
                                           << ", evals = " << state.m_n_fvals << "/" << state.m_n_grads;

                                check_solution(problem_name, text::to_string(optimizer), state, solutions);
                        }

//                        log_info();
                }
        }
}

BOOST_AUTO_TEST_CASE(test_optimizers)
{
        using namespace ncv;

//        https://en.wikipedia.org/wiki/Test_functions_for_optimization

        // Sphere function
        for (size_t dims = 1; dims <= 8; dims ++)
        {
                const opt_opsize_t fn_size = [=] ()
                {
                        return dims;
                };

                const opt_opfval_t fn_fval = [=] (const vector_t& x)
                {
                        scalar_t fx = 0;
                        for (size_t i = 0; i < dims; i ++)
                        {
                                fx += x(i) * x(i);
                        }

                        return fx;
                };

                const opt_opgrad_t fn_grad = [=] (const vector_t& x, vector_t& gx)
                {
                        gx.resize(dims);
                        for (size_t i = 0; i < dims; i ++)
                        {
                                gx(i) = 2 * x(i);
                        }

                        return fn_fval(x);
                };

                std::vector<std::pair<vector_t, scalar_t>> solutions;
                {
                        solutions.emplace_back(vector_t::Zero(dims), 0);
                }

                test::check_problem("sphere", fn_size, fn_fval, fn_grad, solutions);
        }

//        // Rosenbrock function
//        for (size_t dims = 2; dims <= 7; dims ++)
//        {
//                const opt_opsize_t fn_size = [=] ()
//                {
//                        return dims;
//                };

//                const opt_opfval_t fn_fval = [=] (const vector_t& x)
//                {
//                        scalar_t fx = 0;
//                        for (size_t i = 0; i + 1 < dims; i ++)
//                        {
//                                fx += 100.0 * math::square(x(i + 1) - x(i) * x(i)) + math::square(x(i) - 1);
//                        }

//                        return fx;
//                };

//                const opt_opgrad_t fn_grad = [=] (const vector_t& x, vector_t& gx)
//                {
//                        gx.resize(dims);
//                        gx.setZero();
//                        for (size_t i = 0; i + 1 < dims; i ++)
//                        {
//                                gx(i) += 2.0 * (x(i) - 1);
//                                gx(i) += 100.0 * 2.0 * (x(i + 1) - x(i) * x(i)) * (- 2.0 * x(i));
//                                gx(i + 1) += 100.0 * 2.0 * (x(i + 1) - x(i) * x(i));
//                        }

//                        return fn_fval(x);
//                };

//                std::vector<std::pair<vector_t, scalar_t>> solutions;
//                {
//                        solutions.emplace_back(vector_t::Ones(dims), 0);
//                        if (dims >= 4 && dims <= 7)
//                        {
//                                vector_t x = vector_t::Ones(dims);
//                                x(0) = -1;
//                                solutions.emplace_back(x, 0);
//                        }
//                }

//                test::check_problem("Rosenbrock", fn_size, fn_fval, fn_grad, solutions);
//        }

        // Beale function
        {
                const opt_opsize_t fn_size = [=] ()
                {
                        return 2;
                };

                const opt_opfval_t fn_fval = [=] (const vector_t& x)
                {
                        const scalar_t a = x(0), b = x(1);

                        const scalar_t z0 = 1.5 - a + a * b;
                        const scalar_t z1 = 2.25 - a + a * b * b;
                        const scalar_t z2 = 2.625 - a + a * b * b * b;

                        return z0 * z0 + z1 * z1 + z2 * z2;
                };

                const opt_opgrad_t fn_grad = [=] (const vector_t& x, vector_t& gx)
                {
                        const scalar_t a = x(0), b = x(1);

                        const scalar_t z0 = 1.5 - a + a * b;
                        const scalar_t z1 = 2.25 - a + a * b * b;
                        const scalar_t z2 = 2.625 - a + a * b * b * b;

                        gx.resize(2);
                        gx(0) = 2.0 * (z0 * (-1 + b) + z1 * (-1 + b * b) + z2 * (-1 + b * b * b));
                        gx(1) = 2.0 * (z0 * (a) + z1 * (2 * a * b) + z2 * (3 * a * b * b));

                        return fn_fval(x);
                };

                std::vector<std::pair<vector_t, scalar_t>> solutions;
                {
                        vector_t x(2);
                        x(0) = 3.0;
                        x(1) = 0.5;
                        solutions.emplace_back(x, 0);
                }

                test::check_problem("Beale", fn_size, fn_fval, fn_grad, solutions);
        }

//        // Goldstein-Price function
//        {
//                const opt_opsize_t fn_size = [=] ()
//                {
//                        return 2;
//                };

//                const opt_opfval_t fn_fval = [=] (const vector_t& x)
//                {
//                        const scalar_t a = x(0), b = x(1);

//                        const scalar_t z0 = 1.0 + a + b;
//                        const scalar_t z1 = 19 - 14 * a + 3 * a * a - 14 * b + 6 * a * b + 3 * b * b;
//                        const scalar_t z2 = 2 * a - 3 * b;
//                        const scalar_t z3 = 18 - 32 * a + 12 * a * a + 48 * b - 36 * a * b + 27 * b * b;

//                        return (1 + z0 * z0 * z1) * (30 + z2 * z2 * z3);
//                };

//                const opt_opgrad_t fn_grad = [=] (const vector_t& x, vector_t& gx)
//                {
//                        const scalar_t a = x(0), b = x(1);

//                        const scalar_t z0 = 1.0 + a + b;
//                        const scalar_t z1 = 19 - 14 * a + 3 * a * a - 14 * b + 6 * a * b + 3 * b * b;
//                        const scalar_t z2 = 2 * a - 3 * b;
//                        const scalar_t z3 = 18 - 32 * a + 12 * a * a + 48 * b - 36 * a * b + 27 * b * b;

//                        const scalar_t u = 1 + z0 * z0 * z1;
//                        const scalar_t v = 30 + z2 * z2 * z3;

//                        gx.resize(2);
//                        gx(0) = u * (2 * z2 * (+2) * z3 + z2 * z2 * (-32 + 24 * a - 36 * b)) +
//                                v * (2 * z0 * (+1) * z1 + z0 * z0 * (-14 + 6 * a + 6 * b));
//                        gx(1) = u * (2 * z2 * (-3) * z3 + z2 * z2 * (+48 - 36 * a + 54 * b)) +
//                                v * (2 * z0 * (+1) * z1 + z0 * z0 * (-14 + 6 * a + 6 * b));

//                        return fn_fval(x);
//                };

//                std::vector<std::pair<vector_t, scalar_t>> solutions;
//                {
//                        vector_t x(2);
//                        x(0) = 0.0;
//                        x(1) = -1.0;
//                        solutions.emplace_back(x, 3.0);
//                }

//                test::check_problem("Goldstein-Price", fn_size, fn_fval, fn_grad, solutions);
//        }

//        // Booth function
//        {
//                const opt_opsize_t fn_size = [=] ()
//                {
//                        return 2;
//                };

//                const opt_opfval_t fn_fval = [=] (const vector_t& x)
//                {
//                        const scalar_t a = x(0), b = x(1);

//                        const scalar_t u = a + 2 * b - 7;
//                        const scalar_t v = 2 * a + b - 5;

//                        return u * u + v * v;
//                };

//                const opt_opgrad_t fn_grad = [=] (const vector_t& x, vector_t& gx)
//                {
//                        const scalar_t a = x(0), b = x(1);

//                        const scalar_t u = a + 2 * b - 7;
//                        const scalar_t v = 2 * a + b - 5;

//                        gx.resize(2);
//                        gx(0) = 2 * u + 2 * v * 2;
//                        gx(1) = 2 * u * 2 + 2 * v;

//                        return fn_fval(x);
//                };

//                std::vector<std::pair<vector_t, scalar_t>> solutions;
//                {
//                        vector_t x(2);
//                        x(0) = 1.0;
//                        x(1) = 3.0;
//                        solutions.emplace_back(x, 0.0);
//                }

//                test::check_problem("Booth", fn_size, fn_fval, fn_grad, solutions);
//        }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: brkpnts.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 21:14:16 $
 *
 *  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 _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#ifndef _SBXCLASS_HXX //autogen
#include <sbx.hxx>
#endif
#ifndef _SB_SBMOD_HXX //autogen
#include <sbmod.hxx>
#endif
#ifndef _SB_SBSTAR_HXX //autogen
#include <sbstar.hxx>
#endif
#ifndef _SB_SBMETH_HXX //autogen
#include <sbmeth.hxx>
#endif
#ifndef _SV_IMAGE_HXX //autogen
#include <vcl/image.hxx>
#endif
#ifndef _TEXTDATA_HXX //autogen
#include <svtools/textdata.hxx>
#endif
#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef _SV_GRADIENT_HXX
#include <vcl/gradient.hxx>
#endif

#ifndef _BASIC_TTRESHLP_HXX
#include "ttstrhlp.hxx"
#endif

#include <brkpnts.hxx>
#include "basic.hrc"
#include "resids.hrc"

struct Breakpoint
{
    USHORT nLine;

    Breakpoint( USHORT nL ) { nLine = nL; }
};

ImageList* BreakpointWindow::pImages = NULL;

BreakpointWindow::BreakpointWindow( Window *pParent )
: Window( pParent )
, nCurYOffset( 0 )
, pModule( NULL )
, nMarkerPos( MARKER_NOMARKER )
{
    if ( !pImages )
        pImages = new ImageList( ResId( RID_IMGLST_LAYOUT ) );

    Gradient aGradient( GRADIENT_AXIAL, Color( 185, 182, 215 ), Color( 250, 245, 255 ) );
    aGradient.SetAngle(900);
    SetBackground( aGradient );
    Show();
}

void BreakpointWindow::Reset()
{
    Breakpoint* pBrk = First();
    while ( pBrk )
    {
        delete pBrk;
        pBrk = Next();
    }
    Clear();

    pModule->ClearAllBP();
}

void BreakpointWindow::SetModule( SbModule *pMod )
{
    pModule = pMod;
    USHORT i;
    for ( i=0 ; i < pModule->GetBPCount() ; i++ )
    {
        InsertBreakpoint( pModule->GetBP( i ) );
    }
    SetBPsInModule();
}

void BreakpointWindow::SetBPsInModule()
{
    pModule->ClearAllBP();

    Breakpoint* pBrk = First();
    while ( pBrk )
    {
        pModule->SetBP( (USHORT)pBrk->nLine );
#if OSL_DEBUG_LEVEL > 1
        DBG_ASSERT( !pModule->IsCompiled() || pModule->IsBP( (USHORT)pBrk->nLine ), "Brechpunkt wurde nicht gesetzt" )
#endif
        pBrk = Next();
    }
    for ( USHORT nMethod = 0; nMethod < pModule->GetMethods()->Count(); nMethod++ )
    {
        SbMethod* pMethod = (SbMethod*)pModule->GetMethods()->Get( nMethod );
        DBG_ASSERT( pMethod, "Methode nicht gefunden! (NULL)" );
        pMethod->SetDebugFlags( pMethod->GetDebugFlags() | SbDEBUG_BREAK );
    }
}

void BreakpointWindow::InsertBreakpoint( USHORT nLine )
{
    Breakpoint* pNewBrk = new Breakpoint( nLine );
    Breakpoint* pBrk = First();
    while ( pBrk )
    {
        if ( nLine <= pBrk->nLine )
        {
            if ( pBrk->nLine != nLine )
                Insert( pNewBrk );
            else
                delete pNewBrk;
            pNewBrk = NULL;
            pBrk = NULL;
        }
        else
            pBrk = Next();
    }
    // Keine Einfuegeposition gefunden => LIST_APPEND
    if ( pNewBrk )
        Insert( pNewBrk, LIST_APPEND );

    // vielleicht mal etwas genauer...
    Invalidate();

    if ( pModule->SetBP( nLine ) )
    {
#if OSL_DEBUG_LEVEL > 1
        DBG_ASSERT( !pModule->IsCompiled() || pModule->IsBP( nLine ), "Brechpunkt wurde nicht gesetzt" )
#endif
        if ( StarBASIC::IsRunning() )
        {
            for ( USHORT nMethod = 0; nMethod < pModule->GetMethods()->Count(); nMethod++ )
            {
                SbMethod* pMethod = (SbMethod*)pModule->GetMethods()->Get( nMethod );
                DBG_ASSERT( pMethod, "Methode nicht gefunden! (NULL)" );
                pMethod->SetDebugFlags( pMethod->GetDebugFlags() | SbDEBUG_BREAK );
            }
        }
    }
#if OSL_DEBUG_LEVEL > 1
    DBG_ASSERT( !pModule->IsCompiled() || pModule->IsBP( nLine ), "Brechpunkt wurde nicht gesetzt" )
#endif
}

Breakpoint* BreakpointWindow::FindBreakpoint( ULONG nLine )
{
    Breakpoint* pBrk = First();
    while ( pBrk )
    {
        if ( pBrk->nLine == nLine )
            return pBrk;

        pBrk = Next();
    }

    return (Breakpoint*)0;
}

void BreakpointWindow::AdjustBreakpoints( ULONG nLine, BOOL bInserted )
{
    if ( nLine == TEXT_PARA_ALL+1 )
        return;
    Breakpoint* pBrk = First();
    while ( pBrk )
    {
        BOOL bDelBrk = FALSE;
        if ( pBrk->nLine == nLine )
        {
            if ( bInserted )
                pBrk->nLine++;
            else
                bDelBrk = TRUE;
        }
        else if ( pBrk->nLine > nLine )
        {
            if ( bInserted )
                pBrk->nLine++;
            else
                pBrk->nLine--;
        }

        if ( bDelBrk )
        {
            ULONG n = GetCurPos();
            delete Remove( pBrk );
            pBrk = Seek( n );
        }
        else
        {
            pBrk = Next();
        }
    }
    Invalidate();
}

void BreakpointWindow::LoadBreakpoints( String aFilename )
{
    Config aConfig(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));

    aConfig.SetGroup("Breakpoints");

    ByteString aBreakpoints;
    aBreakpoints = aConfig.ReadKey( ByteString( aFilename, RTL_TEXTENCODING_UTF8 ) );

    xub_StrLen i;

    for ( i = 0 ; i < aBreakpoints.GetTokenCount( ';' ) ; i++ )
    {
        InsertBreakpoint( (USHORT)aBreakpoints.GetToken( i, ';' ).ToInt32() );
    }
}

void BreakpointWindow::SaveBreakpoints( String aFilename )
{
    ByteString aBreakpoints;

    Breakpoint* pBrk = First();
    while ( pBrk )
    {
        if ( aBreakpoints.Len() )
            aBreakpoints += ';';

        aBreakpoints += ByteString::CreateFromInt32( pBrk->nLine );
        pBrk = Next();
    }

    Config aConfig(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));

    aConfig.SetGroup("Breakpoints");

    if ( aBreakpoints.Len() )
        aConfig.WriteKey( ByteString( aFilename, RTL_TEXTENCODING_UTF8 ), aBreakpoints );
    else
        aConfig.DeleteKey( ByteString( aFilename, RTL_TEXTENCODING_UTF8 ) );
}

void BreakpointWindow::Paint( const Rectangle& )
{
    Size aOutSz( GetOutputSize() );
    long nLineHeight = GetTextHeight();

    Image aBrk( pImages->GetImage( IMGID_BRKENABLED ) );
    Size aBmpSz( aBrk.GetSizePixel() );
    aBmpSz = PixelToLogic( aBmpSz );
    Point aBmpOff( 0, 0 );
    aBmpOff.X() = ( aOutSz.Width() - aBmpSz.Width() ) / 2;
    aBmpOff.Y() = ( nLineHeight - aBmpSz.Height() ) / 2;

    Breakpoint* pBrk = First();
    while ( pBrk )
    {
#if OSL_DEBUG_LEVEL > 1
        DBG_ASSERT( !pModule->IsCompiled() || pModule->IsBP( pBrk->nLine ), "Brechpunkt wurde nicht gesetzt" )
#endif
        ULONG nLine = pBrk->nLine-1;
        ULONG nY = nLine*nLineHeight - nCurYOffset;
        DrawImage( Point( 0, nY ) + aBmpOff, aBrk );
        pBrk = Next();
    }
    ShowMarker( TRUE );
}

Breakpoint* BreakpointWindow::FindBreakpoint( const Point& rMousePos )
{
    long nLineHeight = GetTextHeight();
    long nYPos = rMousePos.Y() + nCurYOffset;

    Breakpoint* pBrk = First();
    while ( pBrk )
    {
        ULONG nLine = pBrk->nLine-1;
        long nY = nLine*nLineHeight;
        if ( ( nYPos > nY ) && ( nYPos < ( nY + nLineHeight ) ) )
            return pBrk;
        pBrk = Next();
    }
    return 0;
}

void BreakpointWindow::ToggleBreakpoint( USHORT nLine )
{
    BOOL bNewBreakPoint = FALSE;
    Breakpoint* pBrk = FindBreakpoint( nLine );
    if ( pBrk ) // entfernen
    {
        pModule->ClearBP( nLine );
        delete Remove( pBrk );
    }
    else // einen erzeugen
    {
        InsertBreakpoint( nLine );
    }
    // vielleicht mal etwas genauer...
    Invalidate();
}

void BreakpointWindow::ShowMarker( BOOL bShow )
{
    if ( nMarkerPos == MARKER_NOMARKER )
        return;

    Size aOutSz( GetOutputSize() );
    long nLineHeight = GetTextHeight();

    Image aMarker;
    if ( bErrorMarker )
        aMarker = pImages->GetImage( IMGID_ERRORMARKER );
    else
        aMarker = pImages->GetImage( IMGID_STEPMARKER );

    Size aMarkerSz( aMarker.GetSizePixel() );
    aMarkerSz = PixelToLogic( aMarkerSz );
    Point aMarkerOff( 0, 0 );
    aMarkerOff.X() = ( aOutSz.Width() - aMarkerSz.Width() ) / 2;
    aMarkerOff.Y() = ( nLineHeight - aMarkerSz.Height() ) / 2;

    ULONG nY = nMarkerPos*nLineHeight - nCurYOffset;
    Point aPos( 0, nY );
    aPos += aMarkerOff;
    if ( bShow )
        DrawImage( aPos, aMarker );
    else
        Invalidate( Rectangle( aPos, aMarkerSz ) );
}

void BreakpointWindow::MouseButtonDown( const MouseEvent& rMEvt )
{
    if ( rMEvt.GetClicks() == 2 )
    {
        Point aMousePos( PixelToLogic( rMEvt.GetPosPixel() ) );
        long nLineHeight = GetTextHeight();
        long nYPos = aMousePos.Y() + nCurYOffset;
        long nLine = nYPos / nLineHeight + 1;
        ToggleBreakpoint( nLine );
        // vielleicht mal etwas genauer...
        Invalidate();
    }
}

void BreakpointWindow::SetMarkerPos( USHORT nLine, BOOL bError )
{
    ShowMarker( FALSE );    // Alten wegzeichen...
    nMarkerPos = nLine;
    bErrorMarker = bError;
    ShowMarker( TRUE );     // Neuen zeichnen...
    Update();
}

void BreakpointWindow::Scroll( long nHorzScroll, long nVertScroll )
{
    nCurYOffset -= nVertScroll;
    Window::Scroll( nHorzScroll, nVertScroll );
}

<commit_msg>INTEGRATION: CWS warnings01 (1.7.30); FILE MERGED 2005/11/18 14:29:38 gh 1.7.30.2: solaris warnings (some more) 2005/10/28 12:36:16 gh 1.7.30.1: remove warnings for linux<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: brkpnts.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 17:34:43 $
 *
 *  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 _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#ifndef _SBXCLASS_HXX //autogen
#include <sbx.hxx>
#endif
#ifndef _SB_SBMOD_HXX //autogen
#include <sbmod.hxx>
#endif
#ifndef _SB_SBSTAR_HXX //autogen
#include <sbstar.hxx>
#endif
#ifndef _SB_SBMETH_HXX //autogen
#include <sbmeth.hxx>
#endif
#ifndef _SV_IMAGE_HXX //autogen
#include <vcl/image.hxx>
#endif
#ifndef _TEXTDATA_HXX //autogen
#include <svtools/textdata.hxx>
#endif
#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef _SV_GRADIENT_HXX
#include <vcl/gradient.hxx>
#endif

#ifndef _BASIC_TTRESHLP_HXX
#include "ttstrhlp.hxx"
#endif

#include "brkpnts.hxx"
#include "basic.hrc"
#include "resids.hrc"

struct Breakpoint
{
    USHORT nLine;

    Breakpoint( USHORT nL ) { nLine = nL; }
};

ImageList* BreakpointWindow::pImages = NULL;

BreakpointWindow::BreakpointWindow( Window *pParent )
: Window( pParent )
, nCurYOffset( 0 )
, nMarkerPos( MARKER_NOMARKER )
, pModule( NULL )
, bErrorMarker( FALSE )
{
    if ( !pImages )
        pImages = new ImageList( ResId( RID_IMGLST_LAYOUT ) );

    Gradient aGradient( GRADIENT_AXIAL, Color( 185, 182, 215 ), Color( 250, 245, 255 ) );
    aGradient.SetAngle(900);
    SetBackground( aGradient );
    Show();
}

void BreakpointWindow::Reset()
{
    Breakpoint* pBrk = First();
    while ( pBrk )
    {
        delete pBrk;
        pBrk = Next();
    }
    Clear();

    pModule->ClearAllBP();
}

void BreakpointWindow::SetModule( SbModule *pMod )
{
    pModule = pMod;
    USHORT i;
    for ( i=0 ; i < pModule->GetBPCount() ; i++ )
    {
        InsertBreakpoint( pModule->GetBP( i ) );
    }
    SetBPsInModule();
}

void BreakpointWindow::SetBPsInModule()
{
    pModule->ClearAllBP();

    Breakpoint* pBrk = First();
    while ( pBrk )
    {
        pModule->SetBP( (USHORT)pBrk->nLine );
#if OSL_DEBUG_LEVEL > 1
        DBG_ASSERT( !pModule->IsCompiled() || pModule->IsBP( (USHORT)pBrk->nLine ), "Brechpunkt wurde nicht gesetzt" )
#endif
        pBrk = Next();
    }
    for ( USHORT nMethod = 0; nMethod < pModule->GetMethods()->Count(); nMethod++ )
    {
        SbMethod* pMethod = (SbMethod*)pModule->GetMethods()->Get( nMethod );
        DBG_ASSERT( pMethod, "Methode nicht gefunden! (NULL)" );
        pMethod->SetDebugFlags( pMethod->GetDebugFlags() | SbDEBUG_BREAK );
    }
}

void BreakpointWindow::InsertBreakpoint( USHORT nLine )
{
    Breakpoint* pNewBrk = new Breakpoint( nLine );
    Breakpoint* pBrk = First();
    while ( pBrk )
    {
        if ( nLine <= pBrk->nLine )
        {
            if ( pBrk->nLine != nLine )
                Insert( pNewBrk );
            else
                delete pNewBrk;
            pNewBrk = NULL;
            pBrk = NULL;
        }
        else
            pBrk = Next();
    }
    // Keine Einfuegeposition gefunden => LIST_APPEND
    if ( pNewBrk )
        Insert( pNewBrk, LIST_APPEND );

    // vielleicht mal etwas genauer...
    Invalidate();

    if ( pModule->SetBP( nLine ) )
    {
#if OSL_DEBUG_LEVEL > 1
        DBG_ASSERT( !pModule->IsCompiled() || pModule->IsBP( nLine ), "Brechpunkt wurde nicht gesetzt" )
#endif
        if ( StarBASIC::IsRunning() )
        {
            for ( USHORT nMethod = 0; nMethod < pModule->GetMethods()->Count(); nMethod++ )
            {
                SbMethod* pMethod = (SbMethod*)pModule->GetMethods()->Get( nMethod );
                DBG_ASSERT( pMethod, "Methode nicht gefunden! (NULL)" );
                pMethod->SetDebugFlags( pMethod->GetDebugFlags() | SbDEBUG_BREAK );
            }
        }
    }
#if OSL_DEBUG_LEVEL > 1
    DBG_ASSERT( !pModule->IsCompiled() || pModule->IsBP( nLine ), "Brechpunkt wurde nicht gesetzt" )
#endif
}

Breakpoint* BreakpointWindow::FindBreakpoint( ULONG nLine )
{
    Breakpoint* pBrk = First();
    while ( pBrk )
    {
        if ( pBrk->nLine == nLine )
            return pBrk;

        pBrk = Next();
    }

    return (Breakpoint*)0;
}

void BreakpointWindow::AdjustBreakpoints( ULONG nLine, BOOL bInserted )
{
    if ( nLine == TEXT_PARA_ALL+1 )
        return;
    Breakpoint* pBrk = First();
    while ( pBrk )
    {
        BOOL bDelBrk = FALSE;
        if ( pBrk->nLine == nLine )
        {
            if ( bInserted )
                pBrk->nLine++;
            else
                bDelBrk = TRUE;
        }
        else if ( pBrk->nLine > nLine )
        {
            if ( bInserted )
                pBrk->nLine++;
            else
                pBrk->nLine--;
        }

        if ( bDelBrk )
        {
            ULONG n = GetCurPos();
            delete Remove( pBrk );
            pBrk = Seek( n );
        }
        else
        {
            pBrk = Next();
        }
    }
    Invalidate();
}

void BreakpointWindow::LoadBreakpoints( String aFilename )
{
    Config aConfig(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));

    aConfig.SetGroup("Breakpoints");

    ByteString aBreakpoints;
    aBreakpoints = aConfig.ReadKey( ByteString( aFilename, RTL_TEXTENCODING_UTF8 ) );

    xub_StrLen i;

    for ( i = 0 ; i < aBreakpoints.GetTokenCount( ';' ) ; i++ )
    {
        InsertBreakpoint( (USHORT)aBreakpoints.GetToken( i, ';' ).ToInt32() );
    }
}

void BreakpointWindow::SaveBreakpoints( String aFilename )
{
    ByteString aBreakpoints;

    Breakpoint* pBrk = First();
    while ( pBrk )
    {
        if ( aBreakpoints.Len() )
            aBreakpoints += ';';

        aBreakpoints += ByteString::CreateFromInt32( pBrk->nLine );
        pBrk = Next();
    }

    Config aConfig(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") ));

    aConfig.SetGroup("Breakpoints");

    if ( aBreakpoints.Len() )
        aConfig.WriteKey( ByteString( aFilename, RTL_TEXTENCODING_UTF8 ), aBreakpoints );
    else
        aConfig.DeleteKey( ByteString( aFilename, RTL_TEXTENCODING_UTF8 ) );
}

void BreakpointWindow::Paint( const Rectangle& )
{
    Size aOutSz( GetOutputSize() );
    long nLineHeight = GetTextHeight();

    Image aBrk( pImages->GetImage( IMGID_BRKENABLED ) );
    Size aBmpSz( aBrk.GetSizePixel() );
    aBmpSz = PixelToLogic( aBmpSz );
    Point aBmpOff( 0, 0 );
    aBmpOff.X() = ( aOutSz.Width() - aBmpSz.Width() ) / 2;
    aBmpOff.Y() = ( nLineHeight - aBmpSz.Height() ) / 2;

    Breakpoint* pBrk = First();
    while ( pBrk )
    {
#if OSL_DEBUG_LEVEL > 1
        DBG_ASSERT( !pModule->IsCompiled() || pModule->IsBP( pBrk->nLine ), "Brechpunkt wurde nicht gesetzt" )
#endif
        ULONG nLine = pBrk->nLine-1;
        ULONG nY = nLine*nLineHeight - nCurYOffset;
        DrawImage( Point( 0, nY ) + aBmpOff, aBrk );
        pBrk = Next();
    }
    ShowMarker( TRUE );
}

Breakpoint* BreakpointWindow::FindBreakpoint( const Point& rMousePos )
{
    long nLineHeight = GetTextHeight();
    long nYPos = rMousePos.Y() + nCurYOffset;

    Breakpoint* pBrk = First();
    while ( pBrk )
    {
        ULONG nLine = pBrk->nLine-1;
        long nY = nLine*nLineHeight;
        if ( ( nYPos > nY ) && ( nYPos < ( nY + nLineHeight ) ) )
            return pBrk;
        pBrk = Next();
    }
    return 0;
}

void BreakpointWindow::ToggleBreakpoint( USHORT nLine )
{
    Breakpoint* pBrk = FindBreakpoint( nLine );
    if ( pBrk ) // entfernen
    {
        pModule->ClearBP( nLine );
        delete Remove( pBrk );
    }
    else // einen erzeugen
    {
        InsertBreakpoint( nLine );
    }
    // vielleicht mal etwas genauer...
    Invalidate();
}

void BreakpointWindow::ShowMarker( BOOL bShow )
{
    if ( nMarkerPos == MARKER_NOMARKER )
        return;

    Size aOutSz( GetOutputSize() );
    long nLineHeight = GetTextHeight();

    Image aMarker;
    if ( bErrorMarker )
        aMarker = pImages->GetImage( IMGID_ERRORMARKER );
    else
        aMarker = pImages->GetImage( IMGID_STEPMARKER );

    Size aMarkerSz( aMarker.GetSizePixel() );
    aMarkerSz = PixelToLogic( aMarkerSz );
    Point aMarkerOff( 0, 0 );
    aMarkerOff.X() = ( aOutSz.Width() - aMarkerSz.Width() ) / 2;
    aMarkerOff.Y() = ( nLineHeight - aMarkerSz.Height() ) / 2;

    ULONG nY = nMarkerPos*nLineHeight - nCurYOffset;
    Point aPos( 0, nY );
    aPos += aMarkerOff;
    if ( bShow )
        DrawImage( aPos, aMarker );
    else
        Invalidate( Rectangle( aPos, aMarkerSz ) );
}

void BreakpointWindow::MouseButtonDown( const MouseEvent& rMEvt )
{
    if ( rMEvt.GetClicks() == 2 )
    {
        Point aMousePos( PixelToLogic( rMEvt.GetPosPixel() ) );
        long nLineHeight = GetTextHeight();
        long nYPos = aMousePos.Y() + nCurYOffset;
        long nLine = nYPos / nLineHeight + 1;
        ToggleBreakpoint( nLine );
        // vielleicht mal etwas genauer...
        Invalidate();
    }
}

void BreakpointWindow::SetMarkerPos( USHORT nLine, BOOL bError )
{
    ShowMarker( FALSE );    // Alten wegzeichen...
    nMarkerPos = nLine;
    bErrorMarker = bError;
    ShowMarker( TRUE );     // Neuen zeichnen...
    Update();
}

void BreakpointWindow::Scroll( long nHorzScroll, long nVertScroll, USHORT nFlags )
{
    (void) nFlags; /* avoid warning about unused parameter */
    nCurYOffset -= nVertScroll;
    Window::Scroll( nHorzScroll, nVertScroll );
}

<|endoftext|>


<commit_before>// Copyright (c) 2011 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 "chrome/browser/component_updater/component_updater_service.h"

#include <algorithm>
#include <string>
#include <vector>

#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/metrics/histogram.h"
#include "base/string_util.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "net/url_request/url_request_context_getter.h"

namespace {
// Default time constants.
const int kDelayOneMinute = 60;
const int kDelayOneHour = kDelayOneMinute * 60;

// Debug values you can pass to --component-updater-debug=<value>.
const char kDebugFastUpdate[] = "fast-update";
const char kDebugOutOfProcess[] = "out-of-process";

bool HasDebugValue(const std::vector<std::string>& vec, const char* test) {
  if (vec.empty())
    return 0;
  return (std::find(vec.begin(), vec.end(), test) != vec.end());
}

// The request extra information is the OS and architecture, this helps
// the server select the right package to be delivered.
const char kExtraInfo[] =
#if defined(OS_MACOSX)
  #if defined(__amd64__)
    "os=mac&arch=x64";
  #elif defined(__i386__)
     "os=mac&arch=x86";
  #else
     #error "unknown mac architecture"
  #endif
#elif defined(OS_WIN)
  #if defined(_WIN64)
    "os=win&arch=x64";
  #elif defined(_WIN32)
    "os=win&arch=x86";
  #else
    #error "unknown windows architecture"
  #endif
#elif defined(OS_LINUX)
  #if defined(__amd64__)
    "os=linux&arch=x64";
  #elif defined(__i386__)
    "os=linux&arch=x86";
  #else
    #error "unknown linux architecture"
  #endif
#elif defined(OS_CHROMEOS)
  #if defined(__i386__)
    "os=cros&arch=x86";
  #else
    // TODO(cpu): Fix this for ARM.
    "os=none&arch=none";
  #endif
#else
    #error "unknown os or architecture"
#endif

}  // namespace

class ChromeConfigurator : public ComponentUpdateService::Configurator {
 public:
  ChromeConfigurator(const CommandLine* cmdline,
                     net::URLRequestContextGetter* url_request_getter);

  virtual ~ChromeConfigurator() {}

  virtual int InitialDelay() OVERRIDE;
  virtual int NextCheckDelay() OVERRIDE;
  virtual int StepDelay() OVERRIDE;
  virtual int MinimumReCheckWait() OVERRIDE;
  virtual GURL UpdateUrl() OVERRIDE;
  virtual const char* ExtraRequestParams() OVERRIDE;
  virtual size_t UrlSizeLimit() OVERRIDE;
  virtual net::URLRequestContextGetter* RequestContext() OVERRIDE;
  virtual bool InProcess() OVERRIDE;
  virtual void OnEvent(Events event, int val) OVERRIDE;

 private:
  net::URLRequestContextGetter* url_request_getter_;
  bool fast_update_;
  bool out_of_process_;
  std::string extra_info_;
};

ChromeConfigurator::ChromeConfigurator(const CommandLine* cmdline,
    net::URLRequestContextGetter* url_request_getter)
      : url_request_getter_(url_request_getter) {
  // Parse comma-delimited debug flags.
  std::vector<std::string> debug_values;
  Tokenize(cmdline->GetSwitchValueASCII(switches::kComponentUpdaterDebug),
      ",", &debug_values);
  fast_update_ = HasDebugValue(debug_values, kDebugFastUpdate);
  out_of_process_ = HasDebugValue(debug_values, kDebugOutOfProcess);
}

int ChromeConfigurator::InitialDelay() {
  return  fast_update_ ? 1 : (6 * kDelayOneMinute);
}

int ChromeConfigurator::NextCheckDelay() {
  return fast_update_ ? 3 : (4 * kDelayOneHour);
}

int ChromeConfigurator::StepDelay() {
  return fast_update_ ? 1 : 4;
}

int ChromeConfigurator::MinimumReCheckWait() {
  return fast_update_ ? 30 : (6 * kDelayOneHour);
}

GURL ChromeConfigurator::UpdateUrl() {
  return GURL("http://clients2.google.com/service/update2/crx");
}

const char* ChromeConfigurator::ExtraRequestParams() {
  return kExtraInfo;
}

size_t ChromeConfigurator::UrlSizeLimit() {
  return 1024ul;
}

net::URLRequestContextGetter* ChromeConfigurator::RequestContext() {
  return url_request_getter_;
}

bool ChromeConfigurator::InProcess() {
  return !out_of_process_;
}

void ChromeConfigurator::OnEvent(Events event, int val) {
  switch (event) {
    case kManifestCheck:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ManifestCheck", val, 100);
      break;
    case kComponentUpdated:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ComponentUpdated", val, 100);
      break;
    case kManifestError:
      UMA_HISTOGRAM_COUNTS_100("ComponentUpdater.ManifestError", val);
      break;
    case kNetworkError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.NetworkError", val, 100);
      break;
    case kUnpackError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.UnpackError", val, 100);
      break;
    case kInstallerError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.InstallError", val, 100);
      break;
    default:
      NOTREACHED();
      break;
  }
}

ComponentUpdateService::Configurator* MakeChromeComponentUpdaterConfigurator(
    const CommandLine* cmdline, net::URLRequestContextGetter* context_getter) {
  return new ChromeConfigurator(cmdline, context_getter);
}
<commit_msg>Fix for broken arm bots BUG=none TEST=bots green<commit_after>// Copyright (c) 2011 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 "chrome/browser/component_updater/component_updater_service.h"

#include <algorithm>
#include <string>
#include <vector>

#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/metrics/histogram.h"
#include "base/string_util.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "net/url_request/url_request_context_getter.h"

namespace {
// Default time constants.
const int kDelayOneMinute = 60;
const int kDelayOneHour = kDelayOneMinute * 60;

// Debug values you can pass to --component-updater-debug=<value>.
const char kDebugFastUpdate[] = "fast-update";
const char kDebugOutOfProcess[] = "out-of-process";

bool HasDebugValue(const std::vector<std::string>& vec, const char* test) {
  if (vec.empty())
    return 0;
  return (std::find(vec.begin(), vec.end(), test) != vec.end());
}

// The request extra information is the OS and architecture, this helps
// the server select the right package to be delivered.
const char kExtraInfo[] =
#if defined(OS_MACOSX)
  #if defined(__amd64__)
    "os=mac&arch=x64";
  #elif defined(__i386__)
     "os=mac&arch=x86";
  #else
     #error "unknown mac architecture"
  #endif
#elif defined(OS_WIN)
  #if defined(_WIN64)
    "os=win&arch=x64";
  #elif defined(_WIN32)
    "os=win&arch=x86";
  #else
    #error "unknown windows architecture"
  #endif
#elif defined(OS_LINUX)
  #if defined(__amd64__)
    "os=linux&arch=x64";
  #elif defined(__i386__)
    "os=linux&arch=x86";
  #else
    "os=linux&arch=unknown";
  #endif
#elif defined(OS_CHROMEOS)
  #if defined(__i386__)
    "os=cros&arch=x86";
  #else
    // TODO(cpu): Fix this for ARM.
    "os=cros&arch=unknown";
  #endif
#else
    #error "unknown os or architecture"
#endif

}  // namespace

class ChromeConfigurator : public ComponentUpdateService::Configurator {
 public:
  ChromeConfigurator(const CommandLine* cmdline,
                     net::URLRequestContextGetter* url_request_getter);

  virtual ~ChromeConfigurator() {}

  virtual int InitialDelay() OVERRIDE;
  virtual int NextCheckDelay() OVERRIDE;
  virtual int StepDelay() OVERRIDE;
  virtual int MinimumReCheckWait() OVERRIDE;
  virtual GURL UpdateUrl() OVERRIDE;
  virtual const char* ExtraRequestParams() OVERRIDE;
  virtual size_t UrlSizeLimit() OVERRIDE;
  virtual net::URLRequestContextGetter* RequestContext() OVERRIDE;
  virtual bool InProcess() OVERRIDE;
  virtual void OnEvent(Events event, int val) OVERRIDE;

 private:
  net::URLRequestContextGetter* url_request_getter_;
  bool fast_update_;
  bool out_of_process_;
  std::string extra_info_;
};

ChromeConfigurator::ChromeConfigurator(const CommandLine* cmdline,
    net::URLRequestContextGetter* url_request_getter)
      : url_request_getter_(url_request_getter) {
  // Parse comma-delimited debug flags.
  std::vector<std::string> debug_values;
  Tokenize(cmdline->GetSwitchValueASCII(switches::kComponentUpdaterDebug),
      ",", &debug_values);
  fast_update_ = HasDebugValue(debug_values, kDebugFastUpdate);
  out_of_process_ = HasDebugValue(debug_values, kDebugOutOfProcess);
}

int ChromeConfigurator::InitialDelay() {
  return  fast_update_ ? 1 : (6 * kDelayOneMinute);
}

int ChromeConfigurator::NextCheckDelay() {
  return fast_update_ ? 3 : (4 * kDelayOneHour);
}

int ChromeConfigurator::StepDelay() {
  return fast_update_ ? 1 : 4;
}

int ChromeConfigurator::MinimumReCheckWait() {
  return fast_update_ ? 30 : (6 * kDelayOneHour);
}

GURL ChromeConfigurator::UpdateUrl() {
  return GURL("http://clients2.google.com/service/update2/crx");
}

const char* ChromeConfigurator::ExtraRequestParams() {
  return kExtraInfo;
}

size_t ChromeConfigurator::UrlSizeLimit() {
  return 1024ul;
}

net::URLRequestContextGetter* ChromeConfigurator::RequestContext() {
  return url_request_getter_;
}

bool ChromeConfigurator::InProcess() {
  return !out_of_process_;
}

void ChromeConfigurator::OnEvent(Events event, int val) {
  switch (event) {
    case kManifestCheck:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ManifestCheck", val, 100);
      break;
    case kComponentUpdated:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ComponentUpdated", val, 100);
      break;
    case kManifestError:
      UMA_HISTOGRAM_COUNTS_100("ComponentUpdater.ManifestError", val);
      break;
    case kNetworkError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.NetworkError", val, 100);
      break;
    case kUnpackError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.UnpackError", val, 100);
      break;
    case kInstallerError:
      UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.InstallError", val, 100);
      break;
    default:
      NOTREACHED();
      break;
  }
}

ComponentUpdateService::Configurator* MakeChromeComponentUpdaterConfigurator(
    const CommandLine* cmdline, net::URLRequestContextGetter* context_getter) {
  return new ChromeConfigurator(cmdline, context_getter);
}
<|endoftext|>


<commit_before><commit_msg>Rollback rev 24947 since it seems to have broken other tests.<commit_after><|endoftext|>


<commit_before>// -*- Mode:C++ -*-

/**************************************************************************************************/
/*                                                                                */
/* Copyright (C) 2016 University of Hull                                                          */
/*                                                                                */
/**************************************************************************************************/
/*                                                                                */
/*  module     :  hugh/render/stage/null.hpp                                                      */
/*  project    :                                                                                */
/*  description:                                                                                */
/*                                                                                */
/**************************************************************************************************/

#if !defined(HUGH_RENDER_STAGE_NULL_HPP)

#define HUGH_RENDER_STAGE_NULL_HPP

// includes, system

//#include <>

// includes, project

#include <hugh/render/stage/base.hpp>

namespace hugh {

  namespace render {

    namespace stage {

      // types, exported (class, enum, struct, union, typedef)

      class HUGH_RENDER_EXPORT null : public base {

      public:

        explicit null(context::device&);
        virtual ~null();

        virtual void invalidate()                             =0;
        virtual void resize    (glm::uvec2 const& /* size */) =0;

      protected:

        virtual void do_execute(context::swap&);

      };

      // variables, exported (extern)

      // functions, inlined (inline)

      // functions, exported (extern)

    } // namespace stage {

  } // namespace render {

} // namespace hugh {

#endif // #if !defined(HUGH_RENDER_STAGE_NULL_HPP)
<commit_msg>fixed: unintended abstract method specification<commit_after>// -*- Mode:C++ -*-

/**************************************************************************************************/
/*                                                                                */
/* Copyright (C) 2016 University of Hull                                                          */
/*                                                                                */
/**************************************************************************************************/
/*                                                                                */
/*  module     :  hugh/render/stage/null.hpp                                                      */
/*  project    :                                                                                */
/*  description:                                                                                */
/*                                                                                */
/**************************************************************************************************/

#if !defined(HUGH_RENDER_STAGE_NULL_HPP)

#define HUGH_RENDER_STAGE_NULL_HPP

// includes, system

//#include <>

// includes, project

#include <hugh/render/stage/base.hpp>

namespace hugh {

  namespace render {

    namespace stage {

      // types, exported (class, enum, struct, union, typedef)

      class HUGH_RENDER_EXPORT null : public base {

      public:

        explicit null(context::device&);
        virtual ~null();

        virtual void invalidate();
        virtual void resize    (glm::uvec2 const& /* size */);

      protected:

        virtual void do_execute(context::swap&);

      };

      // variables, exported (extern)

      // functions, inlined (inline)

      // functions, exported (extern)

    } // namespace stage {

  } // namespace render {

} // namespace hugh {

#endif // #if !defined(HUGH_RENDER_STAGE_NULL_HPP)
<|endoftext|>


<commit_before>/* ************************************************************************** */
/*                                                                            */
/*                                                                            */
/*    ShaderProgram.hpp                              oooooo       oooooo      */
/*                                                 oooooooooo   oooooooooo    */
/*                                                         o%%%%%o            */
/*                                                         %:::::%            */
/*                                                        %:::::::%           */
/*    This file is part of the                             %:::::%            */
/*    Lums library.                                         %%%%%             */
/*                                                                            */
/* ************************************************************************** */

#ifndef LUMS_SHADER_PROGRAM_HPP
#define LUMS_SHADER_PROGRAM_HPP

#include <vector>
#include <Lums/GL.hpp>

namespace lm
{
	class Shader;

	class ShaderProgram
	{
	public:
		ShaderProgram();
		void	attach(const Shader& shader);
		void	link();
		void	use() const;
		static const ShaderProgram& defaultProgram();
		~ShaderProgram();

	private:
		GLuint				_program;
		std::vector<GLuint>	_shaders;

	};
}

#endif
<commit_msg>Added program getter in ShaderProgram<commit_after>/* ************************************************************************** */
/*                                                                            */
/*                                                                            */
/*    ShaderProgram.hpp                              oooooo       oooooo      */
/*                                                 oooooooooo   oooooooooo    */
/*                                                         o%%%%%o            */
/*                                                         %:::::%            */
/*                                                        %:::::::%           */
/*    This file is part of the                             %:::::%            */
/*    Lums library.                                         %%%%%             */
/*                                                                            */
/* ************************************************************************** */

#ifndef LUMS_SHADER_PROGRAM_HPP
#define LUMS_SHADER_PROGRAM_HPP

#include <vector>
#include <Lums/GL.hpp>

namespace lm
{
	class Shader;

	class ShaderProgram
	{
	public:
		ShaderProgram();

		GLuint
		program() const
		{
			return _program;
		}

		void	attach(const Shader& shader);
		void	link();
		void	use() const;
		static const ShaderProgram& defaultProgram();
		~ShaderProgram();

	private:
		GLuint				_program;
		std::vector<GLuint>	_shaders;

	};
}

#endif
<|endoftext|>