<commit_before>/*************************************************************************
 *
 *  $RCSfile: MABResultSet.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2001-10-17 18:18:52 $
 *
 *  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 EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_MAB_RESULTSET_HXX_
#define _CONNECTIVITY_MAB_RESULTSET_HXX_

#ifndef _CONNECTIVITY_FILE_FRESULTSET_HXX_
#include "file/FResultSet.hxx"
#endif
#ifndef _CONNECTIVITY_MAB_TABLE_HXX_
#include "mozaddressbook/MABTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBCX_XROWLOCATE_HPP_
#include <com/sun/star/sdbcx/XRowLocate.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XDELETEROWS_HPP_
#include <com/sun/star/sdbcx/XDeleteRows.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

namespace connectivity
{
    namespace mozaddressbook
    {
        class OMozabResultSet;
        // these typedef's are only necessary for the compiler
        typedef ::cppu::ImplHelper2<  ::com::sun::star::sdbcx::XRowLocate,
                                      ::com::sun::star::sdbcx::XDeleteRows> OMozabResultSet_BASE;
        typedef file::OResultSet                                            OMozabResultSet_BASE2;
        typedef ::comphelper::OPropertyArrayUsageHelper<OMozabResultSet>    OMozabResultSet_BASE3;

        class OMozabResultSet : public OMozabResultSet_BASE2,
                                public OMozabResultSet_BASE,
                                public OMozabResultSet_BASE3
        {
            sal_Bool m_bBookmarkable;
        protected:
            OMozabTable         *m_pMozTable;

            // OPropertyArrayUsageHelper
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const;
            // OPropertySetHelper
            virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
            virtual sal_Bool fillIndexValues(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier> &_xIndex);

        public:
            DECLARE_SERVICE_INFO();

            OMozabResultSet( file::OStatement_Base* pStmt,connectivity::OSQLParseTreeIterator&  _aSQLIterator);

            // XInterface
            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL acquire() throw();
            virtual void SAL_CALL release() throw();
            //XTypeProvider
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException);
            // XPropertySet
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);

            // XRowLocate
            virtual ::com::sun::star::uno::Any SAL_CALL getBookmark(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL moveToBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL moveRelativeToBookmark( const ::com::sun::star::uno::Any& bookmark, sal_Int32 rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL compareBookmarks( const ::com::sun::star::uno::Any& first, const ::com::sun::star::uno::Any& second ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL hasOrderedBookmarks(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL hashBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XDeleteRows
            virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL deleteRows( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // special methods
            //  virtual BOOL OpenImpl();
            virtual void doTableSpecials(const OSQLTable& _xTable);
        };
    }
}

#endif //_CONNECTIVITY_MAB_RESULTSET_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.8.342); FILE MERGED 2005/09/05 17:25:41 rt 1.8.342.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MABResultSet.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 07:31:07 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_MAB_RESULTSET_HXX_
#define _CONNECTIVITY_MAB_RESULTSET_HXX_

#ifndef _CONNECTIVITY_FILE_FRESULTSET_HXX_
#include "file/FResultSet.hxx"
#endif
#ifndef _CONNECTIVITY_MAB_TABLE_HXX_
#include "mozaddressbook/MABTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBCX_XROWLOCATE_HPP_
#include <com/sun/star/sdbcx/XRowLocate.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XDELETEROWS_HPP_
#include <com/sun/star/sdbcx/XDeleteRows.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

namespace connectivity
{
    namespace mozaddressbook
    {
        class OMozabResultSet;
        // these typedef's are only necessary for the compiler
        typedef ::cppu::ImplHelper2<  ::com::sun::star::sdbcx::XRowLocate,
                                      ::com::sun::star::sdbcx::XDeleteRows> OMozabResultSet_BASE;
        typedef file::OResultSet                                            OMozabResultSet_BASE2;
        typedef ::comphelper::OPropertyArrayUsageHelper<OMozabResultSet>    OMozabResultSet_BASE3;

        class OMozabResultSet : public OMozabResultSet_BASE2,
                                public OMozabResultSet_BASE,
                                public OMozabResultSet_BASE3
        {
            sal_Bool m_bBookmarkable;
        protected:
            OMozabTable         *m_pMozTable;

            // OPropertyArrayUsageHelper
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper() const;
            // OPropertySetHelper
            virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
            virtual sal_Bool fillIndexValues(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier> &_xIndex);

        public:
            DECLARE_SERVICE_INFO();

            OMozabResultSet( file::OStatement_Base* pStmt,connectivity::OSQLParseTreeIterator&  _aSQLIterator);

            // XInterface
            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL acquire() throw();
            virtual void SAL_CALL release() throw();
            //XTypeProvider
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException);
            // XPropertySet
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);

            // XRowLocate
            virtual ::com::sun::star::uno::Any SAL_CALL getBookmark(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL moveToBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL moveRelativeToBookmark( const ::com::sun::star::uno::Any& bookmark, sal_Int32 rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL compareBookmarks( const ::com::sun::star::uno::Any& first, const ::com::sun::star::uno::Any& second ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL hasOrderedBookmarks(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL hashBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XDeleteRows
            virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL deleteRows( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // special methods
            //  virtual BOOL OpenImpl();
            virtual void doTableSpecials(const OSQLTable& _xTable);
        };
    }
}

#endif //_CONNECTIVITY_MAB_RESULTSET_HXX_

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkTextMapper.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to Matt Turek who developed this class.

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkTextMapper.h"

#ifdef _WIN32
  #include "vtkWin32OpenGLTextMapper.h"
  #include "vtkWin32TextMapper.h"
#else
#ifdef VTK_USE_OGLR
  #include "vtkXOpenGLTextMapper.h"
#endif
  #include "vtkXTextMapper.h"
#endif

// Creates a new text mapper with Font size 12, bold off, italic off,
// and Arial font
vtkTextMapper::vtkTextMapper()
{
  this->Input = (char*) NULL;
  this->FontSize = 12;
  this->Bold = 0;
  this->Italic = 0;
  this->Shadow = 0;
  this->FontFamily = VTK_ARIAL;
  this->Justification = VTK_TEXT_LEFT;
  this->VerticalJustification = VTK_TEXT_BOTTOM;

  this->TextLines = NULL;
  this->NumberOfLines = 0;
  this->NumberOfLinesAllocated = 0;
  this->LineOffset = 0.0;
  this->LineSpacing = 1.0;
}

vtkTextMapper *vtkTextMapper::New()
{
#ifdef _WIN32
#ifndef VTK_USE_NATIVE_IMAGING
  return vtkWin32OpenGLTextMapper::New();
#else
  return vtkWin32TextMapper::New();
#endif
#else
#ifdef VTK_USE_OGLR
#ifndef VTK_USE_NATIVE_IMAGING
  return vtkXOpenGLTextMapper::New();
#else
  return vtkXTextMapper::New();
#endif
#else
  return vtkXTextMapper::New();
#endif
#endif

}

vtkTextMapper::~vtkTextMapper()
{
  if (this->Input)
    {
    delete [] this->Input;
    this->Input = NULL;
    }

  if ( this->TextLines != NULL )
    {
    for (int i=0; i < this->NumberOfLinesAllocated; i++)
      {
      this->TextLines[i]->Delete();
      }
    delete [] this->TextLines;
    }

}

//----------------------------------------------------------------------------
void vtkTextMapper::PrintSelf(ostream& os, vtkIndent indent)
{
  os << indent << "Line Offset: " << this->LineOffset;
  os << indent << "Line Spacing: " << this->LineSpacing;
  os << indent << "Bold: " << (this->Bold ? "On\n" : "Off\n");
  os << indent << "Italic: " << (this->Italic ? "On\n" : "Off\n");
  os << indent << "Shadow: " << (this->Shadow ? "On\n" : "Off\n");
  os << indent << "FontFamily: " << this->FontFamily << "\n";
  os << indent << "FontSize: " << this->FontSize << "\n";
  os << indent << "Input: " << (this->Input ? this->Input : "(none)") << "\n";
  os << indent << "Justification: ";
  switch (this->Justification)
    {
    case 0: os << "Left  (0)" << endl; break;
    case 1: os << "Centered  (1)" << endl; break;
    case 2: os << "Right  (2)" << endl; break;
    }
  os << indent << "VerticalJustification: ";
  switch (this->VerticalJustification)
    {
    case VTK_TEXT_TOP: os << "Top" << endl; break;
    case VTK_TEXT_CENTERED: os << "Centered" << endl; break;
    case VTK_TEXT_BOTTOM: os << "Bottom" << endl; break;
    }

  vtkMapper2D::PrintSelf(os,indent);
}

int vtkTextMapper::GetWidth(vtkViewport* viewport)
{
  int size[2];
  this->GetSize(viewport, size);
  return size[0];
}

int vtkTextMapper::GetHeight(vtkViewport* viewport)
{
  int size[2];
  this->GetSize(viewport, size);
  return size[1];
}

// Parse the input and create multiple text mappers if multiple lines
// (delimited by \n) are specified.
void vtkTextMapper::SetInput(char *input)
{
  if ( this->Input && input && (!strcmp(this->Input,input)))
    {
    return;
    }
  if (this->Input)
    {
    delete [] this->Input;
    }
  if (input)
    {
    this->Input = new char[strlen(input)+1];
    strcpy(this->Input,input);
    }
  else
    {
    this->Input = NULL;
    }
  this->Modified();

  int numLines = this->GetNumberOfLines(input);

  if ( numLines <= 1) // a line with no "\n"
    {
    this->NumberOfLines = numLines;
    this->LineOffset = 0.0;
    }

  else //multiple lines
    {
    char *line;
    int i;

    if ( numLines > this->NumberOfLinesAllocated )
      {
      // delete old stuff
      if ( this->TextLines )
        {
        for (i=0; i < this->NumberOfLinesAllocated; i++)
          {
          this->TextLines[i]->Delete();
          }
        delete [] this->TextLines;
        }

      // allocate new text mappers
      this->NumberOfLinesAllocated = numLines;
      this->TextLines = new vtkTextMapper *[numLines];
      for (i=0; i < numLines; i++)
        {
        this->TextLines[i] = vtkTextMapper::New();
        }
      } //if we need to reallocate

    // set the input strings
    this->NumberOfLines = numLines;
    for (i=0; i < this->NumberOfLines; i++)
      {
      line = this->NextLine(input, i);
      this->TextLines[i]->SetInput( line );
      delete [] line;
      }
    }
}

// Determine the number of lines in the Input string (delimited by "\n").
int vtkTextMapper::GetNumberOfLines(char *input)
{
  if ( input == NULL )
    {
    return 0;
    }

  int numLines=1;
  char *ptr = input;

  while ( ptr != NULL )
    {
    if ( (ptr=strstr(ptr,"\n")) != NULL )
      {
      numLines++;
      ptr++; //skip over \n
      }
    }

  return numLines;
}

// Get the next \n delimited line. Returns a string that
// must be freed by the calling function.
char *vtkTextMapper::NextLine(char *input, int lineNum)
{
  char *line, *ptr, *ptrEnd;
  int strLen;

  ptr = input;
  for (int i=0; i != lineNum; i++)
    {
    ptr = strstr(ptr,"\n");
    ptr++;
    }
  ptrEnd = strstr(ptr,"\n");
  if ( ptrEnd == NULL )
    {
    ptrEnd = strchr(ptr, '\0');
    }

  strLen = ptrEnd - ptr;
  line = new char[strLen+1];
  strncpy(line, ptr, strLen);
  line[strLen] = '\0';

  return line;
}

// Get the size of a multi-line text string
void vtkTextMapper::GetMultiLineSize(vtkViewport* viewport, int size[2])
{
  int i;
  int lineSize[2];

  lineSize[0] = lineSize[1] = size[0] = size[1] = 0;
  for ( i=0; i < this->NumberOfLines; i++ )
    {
    this->TextLines[i]->SetItalic(this->Italic);
    this->TextLines[i]->SetBold(this->Bold);
    this->TextLines[i]->SetShadow(this->Shadow);
    this->TextLines[i]->SetFontSize(this->FontSize);
    this->TextLines[i]->SetFontFamily(this->FontFamily);
    this->TextLines[i]->GetSize(viewport, lineSize);
    size[0] = (lineSize[0] > size[0] ? lineSize[0] : size[0]);
    size[1] = (lineSize[1] > size[1] ? lineSize[1] : size[1]);
    }

  // add in the line spacing
  this->LineSize = size[1];
  size[1] = this->NumberOfLines* this->LineSpacing * size[1];
}

void vtkTextMapper::RenderOverlayMultipleLines(vtkViewport *viewport,
                                               vtkActor2D *actor)
{
  float offset;
  int size[2];
  // make sure LineSize is up to date
  this->GetMultiLineSize(viewport,size);

  switch (this->VerticalJustification)
    {
    case VTK_TEXT_TOP:
      offset = 1.0;
      break;
    case VTK_TEXT_CENTERED:
      offset = -this->NumberOfLines/2.0 + 1;
      break;
    case VTK_TEXT_BOTTOM:
      offset = -(this->NumberOfLines - 1.0);
      break;
    }

  for (int lineNum=0; lineNum < this->NumberOfLines; lineNum++)
    {
    this->TextLines[lineNum]->SetItalic(this->Italic);
    this->TextLines[lineNum]->SetBold(this->Bold);
    this->TextLines[lineNum]->SetShadow(this->Shadow);
    this->TextLines[lineNum]->SetFontSize(this->FontSize);
    this->TextLines[lineNum]->SetFontFamily(this->FontFamily);
    this->TextLines[lineNum]->SetJustification(this->Justification);
    this->TextLines[lineNum]->SetLineOffset(this->LineSize*(lineNum+offset));
    this->TextLines[lineNum]->SetLineSpacing(this->LineSpacing);
    this->TextLines[lineNum]->RenderOverlay(viewport,actor);
    }
}

void vtkTextMapper::RenderOpaqueGeometryMultipleLines(vtkViewport *viewport,
                                                      vtkActor2D *actor)
{
  float offset;
  int size[2];
  // make sure LineSize is up to date
  this->GetMultiLineSize(viewport,size);

  switch (this->VerticalJustification)
    {
    case VTK_TEXT_TOP:
      offset = 1.0;
      break;
    case VTK_TEXT_CENTERED:
      offset = -this->NumberOfLines/2.0 + 1;
      break;
    case VTK_TEXT_BOTTOM:
      offset = -(this->NumberOfLines - 1.0);
      break;
    }

  for (int lineNum=0; lineNum < this->NumberOfLines; lineNum++)
    {
    this->TextLines[lineNum]->SetItalic(this->Italic);
    this->TextLines[lineNum]->SetBold(this->Bold);
    this->TextLines[lineNum]->SetShadow(this->Shadow);
    this->TextLines[lineNum]->SetFontSize(this->FontSize);
    this->TextLines[lineNum]->SetFontFamily(this->FontFamily);
    this->TextLines[lineNum]->SetJustification(this->Justification);
    this->TextLines[lineNum]->SetLineOffset(this->LineSize*(lineNum+offset));
    this->TextLines[lineNum]->SetLineSpacing(this->LineSpacing);
    this->TextLines[lineNum]->RenderOpaqueGeometry(viewport,actor);
    }
}
<commit_msg>fixed print self<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkTextMapper.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to Matt Turek who developed this class.

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkTextMapper.h"

#ifdef _WIN32
  #include "vtkWin32OpenGLTextMapper.h"
  #include "vtkWin32TextMapper.h"
#else
#ifdef VTK_USE_OGLR
  #include "vtkXOpenGLTextMapper.h"
#endif
  #include "vtkXTextMapper.h"
#endif

// Creates a new text mapper with Font size 12, bold off, italic off,
// and Arial font
vtkTextMapper::vtkTextMapper()
{
  this->Input = (char*) NULL;
  this->FontSize = 12;
  this->Bold = 0;
  this->Italic = 0;
  this->Shadow = 0;
  this->FontFamily = VTK_ARIAL;
  this->Justification = VTK_TEXT_LEFT;
  this->VerticalJustification = VTK_TEXT_BOTTOM;

  this->TextLines = NULL;
  this->NumberOfLines = 0;
  this->NumberOfLinesAllocated = 0;
  this->LineOffset = 0.0;
  this->LineSpacing = 1.0;
}

vtkTextMapper *vtkTextMapper::New()
{
#ifdef _WIN32
#ifndef VTK_USE_NATIVE_IMAGING
  return vtkWin32OpenGLTextMapper::New();
#else
  return vtkWin32TextMapper::New();
#endif
#else
#ifdef VTK_USE_OGLR
#ifndef VTK_USE_NATIVE_IMAGING
  return vtkXOpenGLTextMapper::New();
#else
  return vtkXTextMapper::New();
#endif
#else
  return vtkXTextMapper::New();
#endif
#endif

}

vtkTextMapper::~vtkTextMapper()
{
  if (this->Input)
    {
    delete [] this->Input;
    this->Input = NULL;
    }

  if ( this->TextLines != NULL )
    {
    for (int i=0; i < this->NumberOfLinesAllocated; i++)
      {
      this->TextLines[i]->Delete();
      }
    delete [] this->TextLines;
    }

}

//----------------------------------------------------------------------------
void vtkTextMapper::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkMapper2D::PrintSelf(os,indent);

  os << indent << "Line Offset: " << this->LineOffset;
  os << indent << "Line Spacing: " << this->LineSpacing;
  os << indent << "Bold: " << (this->Bold ? "On\n" : "Off\n");
  os << indent << "Italic: " << (this->Italic ? "On\n" : "Off\n");
  os << indent << "Shadow: " << (this->Shadow ? "On\n" : "Off\n");
  os << indent << "FontFamily: " << this->FontFamily << "\n";
  os << indent << "FontSize: " << this->FontSize << "\n";
  os << indent << "Input: " << (this->Input ? this->Input : "(none)") << "\n";
  os << indent << "Justification: ";
  switch (this->Justification)
    {
    case 0: os << "Left  (0)" << endl; break;
    case 1: os << "Centered  (1)" << endl; break;
    case 2: os << "Right  (2)" << endl; break;
    }
  os << indent << "VerticalJustification: ";
  switch (this->VerticalJustification)
    {
    case VTK_TEXT_TOP: os << "Top" << endl; break;
    case VTK_TEXT_CENTERED: os << "Centered" << endl; break;
    case VTK_TEXT_BOTTOM: os << "Bottom" << endl; break;
    }

  os << indent << "NumberOfLines: " << this->NumberOfLines << "\n";
}

int vtkTextMapper::GetWidth(vtkViewport* viewport)
{
  int size[2];
  this->GetSize(viewport, size);
  return size[0];
}

int vtkTextMapper::GetHeight(vtkViewport* viewport)
{
  int size[2];
  this->GetSize(viewport, size);
  return size[1];
}

// Parse the input and create multiple text mappers if multiple lines
// (delimited by \n) are specified.
void vtkTextMapper::SetInput(char *input)
{
  if ( this->Input && input && (!strcmp(this->Input,input)))
    {
    return;
    }
  if (this->Input)
    {
    delete [] this->Input;
    }
  if (input)
    {
    this->Input = new char[strlen(input)+1];
    strcpy(this->Input,input);
    }
  else
    {
    this->Input = NULL;
    }
  this->Modified();

  int numLines = this->GetNumberOfLines(input);

  if ( numLines <= 1) // a line with no "\n"
    {
    this->NumberOfLines = numLines;
    this->LineOffset = 0.0;
    }

  else //multiple lines
    {
    char *line;
    int i;

    if ( numLines > this->NumberOfLinesAllocated )
      {
      // delete old stuff
      if ( this->TextLines )
        {
        for (i=0; i < this->NumberOfLinesAllocated; i++)
          {
          this->TextLines[i]->Delete();
          }
        delete [] this->TextLines;
        }

      // allocate new text mappers
      this->NumberOfLinesAllocated = numLines;
      this->TextLines = new vtkTextMapper *[numLines];
      for (i=0; i < numLines; i++)
        {
        this->TextLines[i] = vtkTextMapper::New();
        }
      } //if we need to reallocate

    // set the input strings
    this->NumberOfLines = numLines;
    for (i=0; i < this->NumberOfLines; i++)
      {
      line = this->NextLine(input, i);
      this->TextLines[i]->SetInput( line );
      delete [] line;
      }
    }
}

// Determine the number of lines in the Input string (delimited by "\n").
int vtkTextMapper::GetNumberOfLines(char *input)
{
  if ( input == NULL )
    {
    return 0;
    }

  int numLines=1;
  char *ptr = input;

  while ( ptr != NULL )
    {
    if ( (ptr=strstr(ptr,"\n")) != NULL )
      {
      numLines++;
      ptr++; //skip over \n
      }
    }

  return numLines;
}

// Get the next \n delimited line. Returns a string that
// must be freed by the calling function.
char *vtkTextMapper::NextLine(char *input, int lineNum)
{
  char *line, *ptr, *ptrEnd;
  int strLen;

  ptr = input;
  for (int i=0; i != lineNum; i++)
    {
    ptr = strstr(ptr,"\n");
    ptr++;
    }
  ptrEnd = strstr(ptr,"\n");
  if ( ptrEnd == NULL )
    {
    ptrEnd = strchr(ptr, '\0');
    }

  strLen = ptrEnd - ptr;
  line = new char[strLen+1];
  strncpy(line, ptr, strLen);
  line[strLen] = '\0';

  return line;
}

// Get the size of a multi-line text string
void vtkTextMapper::GetMultiLineSize(vtkViewport* viewport, int size[2])
{
  int i;
  int lineSize[2];

  lineSize[0] = lineSize[1] = size[0] = size[1] = 0;
  for ( i=0; i < this->NumberOfLines; i++ )
    {
    this->TextLines[i]->SetItalic(this->Italic);
    this->TextLines[i]->SetBold(this->Bold);
    this->TextLines[i]->SetShadow(this->Shadow);
    this->TextLines[i]->SetFontSize(this->FontSize);
    this->TextLines[i]->SetFontFamily(this->FontFamily);
    this->TextLines[i]->GetSize(viewport, lineSize);
    size[0] = (lineSize[0] > size[0] ? lineSize[0] : size[0]);
    size[1] = (lineSize[1] > size[1] ? lineSize[1] : size[1]);
    }

  // add in the line spacing
  this->LineSize = size[1];
  size[1] = this->NumberOfLines* this->LineSpacing * size[1];
}

void vtkTextMapper::RenderOverlayMultipleLines(vtkViewport *viewport,
                                               vtkActor2D *actor)
{
  float offset;
  int size[2];
  // make sure LineSize is up to date
  this->GetMultiLineSize(viewport,size);

  switch (this->VerticalJustification)
    {
    case VTK_TEXT_TOP:
      offset = 1.0;
      break;
    case VTK_TEXT_CENTERED:
      offset = -this->NumberOfLines/2.0 + 1;
      break;
    case VTK_TEXT_BOTTOM:
      offset = -(this->NumberOfLines - 1.0);
      break;
    }

  for (int lineNum=0; lineNum < this->NumberOfLines; lineNum++)
    {
    this->TextLines[lineNum]->SetItalic(this->Italic);
    this->TextLines[lineNum]->SetBold(this->Bold);
    this->TextLines[lineNum]->SetShadow(this->Shadow);
    this->TextLines[lineNum]->SetFontSize(this->FontSize);
    this->TextLines[lineNum]->SetFontFamily(this->FontFamily);
    this->TextLines[lineNum]->SetJustification(this->Justification);
    this->TextLines[lineNum]->SetLineOffset(this->LineSize*(lineNum+offset));
    this->TextLines[lineNum]->SetLineSpacing(this->LineSpacing);
    this->TextLines[lineNum]->RenderOverlay(viewport,actor);
    }
}

void vtkTextMapper::RenderOpaqueGeometryMultipleLines(vtkViewport *viewport,
                                                      vtkActor2D *actor)
{
  float offset;
  int size[2];
  // make sure LineSize is up to date
  this->GetMultiLineSize(viewport,size);

  switch (this->VerticalJustification)
    {
    case VTK_TEXT_TOP:
      offset = 1.0;
      break;
    case VTK_TEXT_CENTERED:
      offset = -this->NumberOfLines/2.0 + 1;
      break;
    case VTK_TEXT_BOTTOM:
      offset = -(this->NumberOfLines - 1.0);
      break;
    }

  for (int lineNum=0; lineNum < this->NumberOfLines; lineNum++)
    {
    this->TextLines[lineNum]->SetItalic(this->Italic);
    this->TextLines[lineNum]->SetBold(this->Bold);
    this->TextLines[lineNum]->SetShadow(this->Shadow);
    this->TextLines[lineNum]->SetFontSize(this->FontSize);
    this->TextLines[lineNum]->SetFontFamily(this->FontFamily);
    this->TextLines[lineNum]->SetJustification(this->Justification);
    this->TextLines[lineNum]->SetLineOffset(this->LineSize*(lineNum+offset));
    this->TextLines[lineNum]->SetLineSpacing(this->LineSpacing);
    this->TextLines[lineNum]->RenderOpaqueGeometry(viewport,actor);
    }
}
<|endoftext|>


<commit_before>/* Copyright (c) 2008-2019 the MRtrix3 contributors.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Covered Software is provided under this License on an "as is"
 * basis, without warranty of any kind, either expressed, implied, or
 * statutory, including, without limitation, warranties that the
 * Covered Software is free of defects, merchantable, fit for a
 * particular purpose or non-infringing.
 * See the Mozilla Public License v. 2.0 for more details.
 *
 * For more details, see http://www.mrtrix.org/.
 */

#include "command.h"
#include "debug.h"
#include "file/path.h"
#include "file/dicom/element.h"
#include "file/dicom/quick_scan.h"
#include "file/dicom/definitions.h"

using namespace MR;
using namespace App;

void usage ()
{
  AUTHOR = "J-Donald Tournier (jdtournier@gmail.com)";

  SYNOPSIS = "Edit DICOM file in-place";

  DESCRIPTION
  + "Note that this command simply replaces the existing "
    "values without modifying the DICOM structure in any way. Replacement text "
    "will be truncated if it is too long to fit inside the existing tag."

  + "WARNING: this command will modify existing data! It is recommended to run "
    "this command on a copy of the original data set to avoid loss of data.";

  ARGUMENTS
  + Argument ("file", "the DICOM file to be edited.").type_file_in();

  OPTIONS
  + Option ("anonymise", "remove any identifiable information, by replacing the following tags:\n"
      "- any tag with Value Representation PN will be replaced with 'anonymous'\n"
      "- tag (0010,0030) PatientBirthDate will be replaced with an empty string\n\n"
      "WARNING: there is no guarantee that this command will remove all identiable "
      "information, since such information may be contained in any number "
      "of private vendor-specific tags. You will need to double-check the "
      "results independently if you " "need to ensure anonymity.")

  + Option ("id", "replace all ID tags with string supplied. This consists of tags "
      "(0010, 0020) PatientID and (0010, 1000) OtherPatientIDs")
  +   Argument ("text").type_text()

  + Option ("tag", "replace specific tag.").allow_multiple()
  +   Argument ("group")
  +   Argument ("element")
  +   Argument ("newvalue");
}

class Tag { NOMEMALIGN
  public:
    Tag (uint16_t group, uint16_t element, const std::string& newvalue) :
      group (group), element (element), newvalue (newvalue) { }
    uint16_t group, element;
    std::string newvalue;
};

inline std::string hex (uint16_t value)
{
  std::ostringstream hex;
  hex << std::hex << value;
  return hex.str();
}

inline uint16_t read_hex (const std::string& m)
{
  uint16_t value;
  std::istringstream hex (m);
  hex >> std::hex >> value;
  return value;
}

void run ()
{
  vector<Tag> tags;
  vector<uint16_t> VRs;

  auto opt = get_options ("anonymise");
  if (opt.size()) {
    tags.push_back (Tag (0x0010U, 0x0030U, "")); // PatientBirthDate
    VRs.push_back (VR_PN);
  }

  opt = get_options ("tag");
  if (opt.size())
    for (size_t n = 0; n < opt.size(); ++n)
      tags.push_back (Tag (read_hex (opt[n][0]), read_hex (opt[n][1]), opt[n][2]));

  opt = get_options ("id");
  if (opt.size()) {
    std::string newid = opt[0][0];
    tags.push_back (Tag (0x0010U, 0x0020U, newid)); // PatientID
    tags.push_back (Tag (0x0010U, 0x1000U, newid)); // OtherPatientIDs
  }

  for (size_t n = 0; n < VRs.size(); ++n) {
    union __VR { uint16_t i; char c[2]; } VR;
    VR.i = VRs[n];
    INFO (std::string ("clearing entries with VR \"") + VR.c[1] + VR.c[0] + "\"");
  }
  for (size_t n = 0; n < tags.size(); ++n)
    INFO ("replacing tag (" + hex(tags[n].group) + "," + hex(tags[n].element) + ") with value \"" + tags[n].newvalue + "\"");

  File::Dicom::Element item;
  item.set (argument[0], true, true);
  while (item.read()) {
    for (size_t n = 0; n < VRs.size(); ++n) {
      if (item.VR == VRs[n]) {
        memset (item.data, 32, item.size);
        memcpy (item.data, "anonymous", std::min<int> (item.size, 9));
      }
    }
    for (size_t n = 0; n < tags.size(); ++n) {
      if (item.is (tags[n].group, tags[n].element)) {
        memset (item.data, 32, item.size);
        memcpy (item.data, tags[n].newvalue.c_str(), std::min<int> (item.size, tags[n].newvalue.size()));
      }
    }
  }
}

<commit_msg>dcmedit: minor tweaks to docs<commit_after>/* Copyright (c) 2008-2019 the MRtrix3 contributors.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Covered Software is provided under this License on an "as is"
 * basis, without warranty of any kind, either expressed, implied, or
 * statutory, including, without limitation, warranties that the
 * Covered Software is free of defects, merchantable, fit for a
 * particular purpose or non-infringing.
 * See the Mozilla Public License v. 2.0 for more details.
 *
 * For more details, see http://www.mrtrix.org/.
 */

#include "command.h"
#include "debug.h"
#include "file/path.h"
#include "file/dicom/element.h"
#include "file/dicom/quick_scan.h"
#include "file/dicom/definitions.h"

using namespace MR;
using namespace App;

void usage ()
{
  AUTHOR = "J-Donald Tournier (jdtournier@gmail.com)";

  SYNOPSIS = "Edit DICOM file in-place";

  DESCRIPTION
  + "Note that this command simply replaces the existing "
    "values without modifying the DICOM structure in any way. Replacement text "
    "will be truncated if it is too long to fit inside the existing tag."

  + "WARNING: this command will modify existing data! It is recommended to run "
    "this command on a copy of the original data set to avoid loss of data.";

  ARGUMENTS
  + Argument ("file", "the DICOM file to be edited.").type_file_in();

  OPTIONS
  + Option ("anonymise", "remove any identifiable information, by replacing the following tags:\n"
      "- any tag with Value Representation PN will be replaced with 'anonymous'\n"
      "- tag (0010,0030) PatientBirthDate will be replaced with an empty string\n"
      "WARNING: there is no guarantee that this command will remove all identiable "
      "information, since such information may be contained in any number "
      "of private vendor-specific tags. You will need to double-check the "
      "results independently if you " "need to ensure anonymity.")

  + Option ("id", "replace all ID tags with string supplied. This consists of tags "
      "(0010, 0020) PatientID and (0010, 1000) OtherPatientIDs")
  +   Argument ("text").type_text()

  + Option ("tag", "replace specific tag.").allow_multiple()
  +   Argument ("group")
  +   Argument ("element")
  +   Argument ("newvalue");
}

class Tag { NOMEMALIGN
  public:
    Tag (uint16_t group, uint16_t element, const std::string& newvalue) :
      group (group), element (element), newvalue (newvalue) { }
    uint16_t group, element;
    std::string newvalue;
};

inline std::string hex (uint16_t value)
{
  std::ostringstream hex;
  hex << std::hex << value;
  return hex.str();
}

inline uint16_t read_hex (const std::string& m)
{
  uint16_t value;
  std::istringstream hex (m);
  hex >> std::hex >> value;
  return value;
}

void run ()
{
  vector<Tag> tags;
  vector<uint16_t> VRs;

  auto opt = get_options ("anonymise");
  if (opt.size()) {
    tags.push_back (Tag (0x0010U, 0x0030U, "")); // PatientBirthDate
    VRs.push_back (VR_PN);
  }

  opt = get_options ("tag");
  if (opt.size())
    for (size_t n = 0; n < opt.size(); ++n)
      tags.push_back (Tag (read_hex (opt[n][0]), read_hex (opt[n][1]), opt[n][2]));

  opt = get_options ("id");
  if (opt.size()) {
    std::string newid = opt[0][0];
    tags.push_back (Tag (0x0010U, 0x0020U, newid)); // PatientID
    tags.push_back (Tag (0x0010U, 0x1000U, newid)); // OtherPatientIDs
  }

  for (size_t n = 0; n < VRs.size(); ++n) {
    union __VR { uint16_t i; char c[2]; } VR;
    VR.i = VRs[n];
    INFO (std::string ("clearing entries with VR \"") + VR.c[1] + VR.c[0] + "\"");
  }
  for (size_t n = 0; n < tags.size(); ++n)
    INFO ("replacing tag (" + hex(tags[n].group) + "," + hex(tags[n].element) + ") with value \"" + tags[n].newvalue + "\"");

  File::Dicom::Element item;
  item.set (argument[0], true, true);
  while (item.read()) {
    for (size_t n = 0; n < VRs.size(); ++n) {
      if (item.VR == VRs[n]) {
        memset (item.data, 32, item.size);
        memcpy (item.data, "anonymous", std::min<int> (item.size, 9));
      }
    }
    for (size_t n = 0; n < tags.size(); ++n) {
      if (item.is (tags[n].group, tags[n].element)) {
        memset (item.data, 32, item.size);
        memcpy (item.data, tags[n].newvalue.c_str(), std::min<int> (item.size, tags[n].newvalue.size()));
      }
    }
  }
}

<|endoftext|>


<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/browser.h"

#include <stdlib.h>

#include "atom/browser/native_window.h"
#include "atom/browser/window_list.h"
#include "atom/common/atom_version.h"
#include "brightray/common/application_info.h"
#include "chrome/browser/ui/libgtk2ui/unity_service.h"

namespace atom {

void Browser::Focus() {
  // Focus on the first visible window.
  WindowList* list = WindowList::GetInstance();
  for (WindowList::iterator iter = list->begin(); iter != list->end(); ++iter) {
    NativeWindow* window = *iter;
    if (window->IsVisible()) {
      window->Focus(true);
      break;
    }
  }
}

void Browser::AddRecentDocument(const base::FilePath& path) {
}

void Browser::ClearRecentDocuments() {
}

void Browser::SetAppUserModelID(const base::string16& name) {
}

bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol) {
  return false;
}

bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) {
  return false;
}

bool Browser::IsDefaultProtocolClient(const std::string& protocol) {
  return false;
}

bool Browser::SetBadgeCount(int count) {
  if (IsUnityRunning()) {
    unity::SetDownloadCount(count);
    badge_count_ = count;
    return true;
  } else {
    return false;
  }
}

void Browser::SetLoginItemSettings(LoginItemSettings settings) {
}

LoginItemSettings Browser::GetLoginItemSettings() {
  return LoginItemSettings();
}

std::string Browser::GetExecutableFileVersion() const {
  return brightray::GetApplicationVersion();
}

std::string Browser::GetExecutableFileProductName() const {
  return brightray::GetApplicationName();
}

bool Browser::IsUnityRunning() {
  return unity::IsRunning();
}

}  // namespace atom
<commit_msg>Add Browser namespace<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/browser.h"

#include <stdlib.h>

#include "atom/browser/native_window.h"
#include "atom/browser/window_list.h"
#include "atom/common/atom_version.h"
#include "brightray/common/application_info.h"
#include "chrome/browser/ui/libgtk2ui/unity_service.h"

namespace atom {

void Browser::Focus() {
  // Focus on the first visible window.
  WindowList* list = WindowList::GetInstance();
  for (WindowList::iterator iter = list->begin(); iter != list->end(); ++iter) {
    NativeWindow* window = *iter;
    if (window->IsVisible()) {
      window->Focus(true);
      break;
    }
  }
}

void Browser::AddRecentDocument(const base::FilePath& path) {
}

void Browser::ClearRecentDocuments() {
}

void Browser::SetAppUserModelID(const base::string16& name) {
}

bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol) {
  return false;
}

bool Browser::SetAsDefaultProtocolClient(const std::string& protocol) {
  return false;
}

bool Browser::IsDefaultProtocolClient(const std::string& protocol) {
  return false;
}

bool Browser::SetBadgeCount(int count) {
  if (IsUnityRunning()) {
    unity::SetDownloadCount(count);
    badge_count_ = count;
    return true;
  } else {
    return false;
  }
}

void Browser::SetLoginItemSettings(LoginItemSettings settings) {
}

Browser::LoginItemSettings Browser::GetLoginItemSettings() {
  return LoginItemSettings();
}

std::string Browser::GetExecutableFileVersion() const {
  return brightray::GetApplicationVersion();
}

std::string Browser::GetExecutableFileProductName() const {
  return brightray::GetApplicationName();
}

bool Browser::IsUnityRunning() {
  return unity::IsRunning();
}

}  // namespace atom
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2021.  All rights reserved
 */

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

#ifndef _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_
#define _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_

#include "../Concrete/KeyedCollection_LinkedList.h"

namespace Stroika::Foundation::Containers::Factory {

    /*
     ********************************************************************************
     ****** KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EQUALS_COMPARER> *******
     ********************************************************************************
     */
#if qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy
    template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER>
    atomic<KeyedCollection<T, KEY_TYPE, TRAITS> (*) (KEY_EXTRACTOR&& keyExtractor, KEY_EQUALS_COMPARER&& keyComparer)> KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::sFactory_ (nullptr);
#endif
    template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER>
    inline KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::KeyedCollection_Factory (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer)
        : fKeyExtractorType_{keyExtractor}
        , fKeyEqualsComparer_{keyComparer}
    {
    }
    template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER>
    inline KeyedCollection<T, KEY_TYPE, TRAITS> KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::operator() () const
    {
        /*
         *  Would have been more performant to just and assure always properly set, but to initialize
         *  sFactory_ with a value other than nullptr requires waiting until after main() - so causes problems
         *  with containers constructed before main.
         *
         *  This works more generally (and with hopefully modest enough performance impact).
         */
        if (auto f = sFactory_.load ()) {
            return f (fKeyExtractorType_, fKeyEqualsComparer_);
        }
        else {
            return Default_ (fKeyExtractorType_, fKeyEqualsComparer_);
        }
    }
    template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER>
    void KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::Register (KeyedCollection<T, KEY_TYPE, TRAITS> (*factory) (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer))
    {
        sFactory_ = factory;
    }
    template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER>
    inline KeyedCollection<T, KEY_TYPE, TRAITS> KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::Default_ (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer)
    {
        /*
         *  Note - though this is not an efficient implementation of KeyedCollection<> for large sizes, its probably the most
         *  efficeint representation which adds no requirements to KEY_TYPE, such as operator< (or a traits less) or
         *  a hash function. And its quite reasonable for small KeyedCollection's - which are often the case.
         *
         *  Calls may use an explicit initializer of KeyedCollection_xxx<> to get better performance for large sized
         *  maps.
         */
        return Concrete::KeyedCollection_LinkedList<T, KEY_TYPE, TRAITS>{keyExtractor, keyComparer};
    }

}

#endif /* _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_ */
<commit_msg>fix typo in vs2k17 BWA<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2021.  All rights reserved
 */

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

#ifndef _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_
#define _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_

#include "../Concrete/KeyedCollection_LinkedList.h"

namespace Stroika::Foundation::Containers::Factory {

    /*
     ********************************************************************************
     ****** KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EQUALS_COMPARER> *******
     ********************************************************************************
     */
#if qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy
    template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER>
    atomic<KeyedCollection<T, KEY_TYPE, TRAITS> (*) (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer)> KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::sFactory_ (nullptr);
#endif
    template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER>
    inline KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::KeyedCollection_Factory (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer)
        : fKeyExtractorType_{keyExtractor}
        , fKeyEqualsComparer_{keyComparer}
    {
    }
    template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER>
    inline KeyedCollection<T, KEY_TYPE, TRAITS> KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::operator() () const
    {
        /*
         *  Would have been more performant to just and assure always properly set, but to initialize
         *  sFactory_ with a value other than nullptr requires waiting until after main() - so causes problems
         *  with containers constructed before main.
         *
         *  This works more generally (and with hopefully modest enough performance impact).
         */
        if (auto f = sFactory_.load ()) {
            return f (fKeyExtractorType_, fKeyEqualsComparer_);
        }
        else {
            return Default_ (fKeyExtractorType_, fKeyEqualsComparer_);
        }
    }
    template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER>
    void KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::Register (KeyedCollection<T, KEY_TYPE, TRAITS> (*factory) (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer))
    {
        sFactory_ = factory;
    }
    template <typename T, typename KEY_TYPE, typename TRAITS, typename KEY_EXTRACTOR, typename KEY_EQUALS_COMPARER>
    inline KeyedCollection<T, KEY_TYPE, TRAITS> KeyedCollection_Factory<T, KEY_TYPE, TRAITS, KEY_EXTRACTOR, KEY_EQUALS_COMPARER>::Default_ (const KEY_EXTRACTOR& keyExtractor, const KEY_EQUALS_COMPARER& keyComparer)
    {
        /*
         *  Note - though this is not an efficient implementation of KeyedCollection<> for large sizes, its probably the most
         *  efficeint representation which adds no requirements to KEY_TYPE, such as operator< (or a traits less) or
         *  a hash function. And its quite reasonable for small KeyedCollection's - which are often the case.
         *
         *  Calls may use an explicit initializer of KeyedCollection_xxx<> to get better performance for large sized
         *  maps.
         */
        return Concrete::KeyedCollection_LinkedList<T, KEY_TYPE, TRAITS>{keyExtractor, keyComparer};
    }

}

#endif /* _Stroika_Foundation_Containers_Concrete_KeyedCollection_Factory_inl_ */
<|endoftext|>


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

#include "itkGradientDescentLineSearchOptimizerv4.h"

namespace itk
{

/**
 * Default constructor
 */
template<typename TInternalComputationValueType>
GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType>
::GradientDescentLineSearchOptimizerv4Template()
{
  this->m_MaximumLineSearchIterations = 20;
  this->m_LineSearchIterations = NumericTraits<unsigned int>::ZeroValue();
  this->m_LowerLimit = itk::NumericTraits< TInternalComputationValueType >::ZeroValue();
  this->m_UpperLimit = 5.0;
  this->m_Phi = 1.618034;
  this->m_Resphi = 2 - this->m_Phi;
  this->m_Epsilon = 0.01;
  this->m_ReturnBestParametersAndValue = true;
}

/**
* Destructor
*/
template<typename TInternalComputationValueType>
GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType>
::~GradientDescentLineSearchOptimizerv4Template() = default;

/**
*PrintSelf
*/
template<typename TInternalComputationValueType>
void
GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType>
::PrintSelf(std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
  }

/**
* Advance one Step following the gradient direction
*/
template<typename TInternalComputationValueType>
void
GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType>
::AdvanceOneStep()
{
  itkDebugMacro("AdvanceOneStep");

  /* Modify the gradient by scales once at the begin */
  this->ModifyGradientByScales();

  /* This will estimate the learning rate (m_LearningRate)
   * if the options are set to do so. We only ever want to
   * estimate at the first step for this class. */
  if ( this->m_CurrentIteration == 0 )
    {
    this->EstimateLearningRate();
    }

  this->m_LineSearchIterations = 0;
  this->m_LearningRate = this->GoldenSectionSearch( this->m_LearningRate * this->m_LowerLimit ,
                                                   this->m_LearningRate , this->m_LearningRate * this->m_UpperLimit );

  /* Begin threaded gradient modification of m_Gradient variable. */
  this->ModifyGradientByLearningRate();

  try
    {
    /* Pass gradient to transform and let it do its own updating */
    this->m_Metric->UpdateTransformParameters( this->m_Gradient );
    }
  catch ( ExceptionObject & err )
    {
    this->m_StopCondition = Superclass::UPDATE_PARAMETERS_ERROR;
    this->m_StopConditionDescription << "UpdateTransformParameters error";
    this->StopOptimization();
      // Pass exception to caller
    throw err;
    }

  this->InvokeEvent( IterationEvent() );
  }

// a and c are the current bounds; the minimum is between them.
// b is a center point
// f(x) is some mathematical function elsewhere defined
// a corresponds to x1; b corresponds to x2; c corresponds to x3
// x corresponds to x4
template<typename TInternalComputationValueType>
TInternalComputationValueType
GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType>
::GoldenSectionSearch( TInternalComputationValueType a, TInternalComputationValueType b, TInternalComputationValueType c )
{
  if ( this->m_LineSearchIterations > this->m_MaximumLineSearchIterations )
    {
    return ( c + a ) / 2;
    }
  this->m_LineSearchIterations++;

  TInternalComputationValueType x;
  if ( c - b > b - a )
    {
    x = b + this->m_Resphi * ( c - b );
    }
  else
    {
    x = b - this->m_Resphi * ( b - a );
    }
  if ( std::abs( c - a ) < this->m_Epsilon * ( std::abs( b ) + std::abs( x ) ) )
    {
    return ( c + a ) / 2;
    }

  TInternalComputationValueType metricx, metricb;

    {
      // Cache the learning rate , parameters , gradient
      // Contain this in a block so these variables go out of
      // scope before we call recursively below. With dense transforms
      // we would otherwise eat up a lot of memory unnecessarily.
    TInternalComputationValueType baseLearningRate = this->m_LearningRate;
    DerivativeType baseGradient( this->m_Gradient );
    ParametersType baseParameters( this->GetCurrentPosition() );

    this->m_LearningRate = x;
    this->ModifyGradientByLearningRate();
    this->m_Metric->UpdateTransformParameters( this->m_Gradient );
    metricx = this->GetMetric()->GetValue( );

    /** reset position of transform and gradient */
    this->m_Metric->SetParameters( baseParameters );
    this->m_Gradient = baseGradient;

    this->m_LearningRate = b;
    this->ModifyGradientByLearningRate();

    this->m_Metric->UpdateTransformParameters( this->m_Gradient );
    metricb = this->GetMetric()->GetValue( );

    /** reset position of transform and learning rate */
    this->m_Metric->SetParameters( baseParameters );
    this->m_Gradient = baseGradient;
    this->m_LearningRate = baseLearningRate;
    }

  /** golden section */
  if (  metricx < metricb )
    {
    if (c - b > b - a)
      {
      return this->GoldenSectionSearch( b, x, c );
      }
    else
      {
      return this->GoldenSectionSearch( a, x, b );
      }
    }
  else
    {
    if ( c - b > b - a )
      {
      return this->GoldenSectionSearch( a, b, x );
      }
    else
      {
      return this->GoldenSectionSearch( x, b, c  );
      }
    }
  }

}//namespace itk

#endif
<commit_msg>BUG: Handle boundary case with max metric<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#ifndef itkGradientDescentLineSearchOptimizerv4_hxx
#define itkGradientDescentLineSearchOptimizerv4_hxx

#include "itkGradientDescentLineSearchOptimizerv4.h"

namespace itk
{

/**
 * Default constructor
 */
template<typename TInternalComputationValueType>
GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType>
::GradientDescentLineSearchOptimizerv4Template()
{
  this->m_MaximumLineSearchIterations = 20;
  this->m_LineSearchIterations = NumericTraits<unsigned int>::ZeroValue();
  this->m_LowerLimit = itk::NumericTraits< TInternalComputationValueType >::ZeroValue();
  this->m_UpperLimit = 5.0;
  this->m_Phi = 1.618034;
  this->m_Resphi = 2 - this->m_Phi;
  this->m_Epsilon = 0.01;
  this->m_ReturnBestParametersAndValue = true;
}

/**
* Destructor
*/
template<typename TInternalComputationValueType>
GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType>
::~GradientDescentLineSearchOptimizerv4Template() = default;

/**
*PrintSelf
*/
template<typename TInternalComputationValueType>
void
GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType>
::PrintSelf(std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
  }

/**
* Advance one Step following the gradient direction
*/
template<typename TInternalComputationValueType>
void
GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType>
::AdvanceOneStep()
{
  itkDebugMacro("AdvanceOneStep");

  /* Modify the gradient by scales once at the begin */
  this->ModifyGradientByScales();

  /* This will estimate the learning rate (m_LearningRate)
   * if the options are set to do so. We only ever want to
   * estimate at the first step for this class. */
  if ( this->m_CurrentIteration == 0 )
    {
    this->EstimateLearningRate();
    }

  this->m_LineSearchIterations = 0;
  this->m_LearningRate = this->GoldenSectionSearch( this->m_LearningRate * this->m_LowerLimit ,
                                                   this->m_LearningRate , this->m_LearningRate * this->m_UpperLimit );

  /* Begin threaded gradient modification of m_Gradient variable. */
  this->ModifyGradientByLearningRate();

  try
    {
    /* Pass gradient to transform and let it do its own updating */
    this->m_Metric->UpdateTransformParameters( this->m_Gradient );
    }
  catch ( ExceptionObject & err )
    {
    this->m_StopCondition = Superclass::UPDATE_PARAMETERS_ERROR;
    this->m_StopConditionDescription << "UpdateTransformParameters error";
    this->StopOptimization();
      // Pass exception to caller
    throw err;
    }

  this->InvokeEvent( IterationEvent() );
  }

// a and c are the current bounds; the minimum is between them.
// b is a center point
// f(x) is some mathematical function elsewhere defined
// a corresponds to x1; b corresponds to x2; c corresponds to x3
// x corresponds to x4
template<typename TInternalComputationValueType>
TInternalComputationValueType
GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType>
::GoldenSectionSearch( TInternalComputationValueType a, TInternalComputationValueType b, TInternalComputationValueType c )
{
  if ( this->m_LineSearchIterations > this->m_MaximumLineSearchIterations )
    {
    return ( c + a ) / 2;
    }
  this->m_LineSearchIterations++;

  TInternalComputationValueType x;
  if ( c - b > b - a )
    {
    x = b + this->m_Resphi * ( c - b );
    }
  else
    {
    x = b - this->m_Resphi * ( b - a );
    }
  if ( std::abs( c - a ) < this->m_Epsilon * ( std::abs( b ) + std::abs( x ) ) )
    {
    return ( c + a ) / 2;
    }

  TInternalComputationValueType metricx, metricb;

    {
      // Cache the learning rate , parameters , gradient
      // Contain this in a block so these variables go out of
      // scope before we call recursively below. With dense transforms
      // we would otherwise eat up a lot of memory unnecessarily.
    TInternalComputationValueType baseLearningRate = this->m_LearningRate;
    DerivativeType baseGradient( this->m_Gradient );
    ParametersType baseParameters( this->GetCurrentPosition() );

    this->m_LearningRate = x;
    this->ModifyGradientByLearningRate();
    this->m_Metric->UpdateTransformParameters( this->m_Gradient );
    metricx = this->GetMetric()->GetValue( );

    /** reset position of transform and gradient */
    this->m_Metric->SetParameters( baseParameters );
    this->m_Gradient = baseGradient;

    this->m_LearningRate = b;
    this->ModifyGradientByLearningRate();

    this->m_Metric->UpdateTransformParameters( this->m_Gradient );
    metricb = this->GetMetric()->GetValue( );

    /** reset position of transform and learning rate */
    this->m_Metric->SetParameters( baseParameters );
    this->m_Gradient = baseGradient;
    this->m_LearningRate = baseLearningRate;
    }

  /** golden section */
  if (  metricx < metricb )
    {
    if (c - b > b - a)
      {
      return this->GoldenSectionSearch( b, x, c );
      }
    else
      {
      return this->GoldenSectionSearch( a, x, b );
      }
    }
  else
    {
    if ( c - b > b - a )
      {
      return this->GoldenSectionSearch( a, b, x );
      }
    else if ( metricx == NumericTraits<TInternalComputationValueType>::max() )
      {
      // Keep the lower bounds when metricx and metricb are both max,
      // likely due to no valid sample points, from too large of a
      // learning rate.
      return this->GoldenSectionSearch( a, x, b );
      }
    else
      {
      return this->GoldenSectionSearch( x, b, c  );
      }
    }
  }

}//namespace itk

#endif
<|endoftext|>


<commit_before><commit_msg>Answer to question 5.5 is complete and close issue #46<commit_after><|endoftext|>


<commit_before>//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// fpcmp is a tool that basically works like the 'cmp' tool, except that it can
// tolerate errors due to floating point noise, with the -r option.
//
//===----------------------------------------------------------------------===//

#include "Support/CommandLine.h"
#include "Support/FileUtilities.h"
#include "Config/fcntl.h"
#include "Config/sys/mman.h"
#include <iostream>
#include <cmath>

using namespace llvm;

namespace {
  cl::opt<std::string>
  File1(cl::Positional, cl::desc("<input file #1>"), cl::Required);
  cl::opt<std::string>
  File2(cl::Positional, cl::desc("<input file #2>"), cl::Required);

  cl::opt<double>
  RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0));
  cl::opt<double>
  AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0));
}

/// OpenFile - mmap the specified file into the address space for reading, and
/// return the length and address of the buffer.
static void OpenFile(const std::string &Filename, unsigned &Len, char* &BufPtr){
  int FD = open(Filename.c_str(), O_RDONLY);
  if (FD == -1 || (Len = getFileSize(Filename)) == ~0U) {
    std::cerr << "Error: cannot open file '" << Filename << "'\n";
    exit(2);
  }

  // mmap in the file all at once...
  BufPtr = (char*)mmap(0, Len, PROT_READ, MAP_PRIVATE, FD, 0);

  if (BufPtr == (char*)MAP_FAILED) {
    std::cerr << "Error: cannot open file '" << Filename << "'\n";
    exit(2);
  }
}

static bool isNumberChar(char C) {
  switch (C) {
  case '0': case '1': case '2': case '3': case '4':
  case '5': case '6': case '7': case '8': case '9':
  case '.': case '+': case '-':
  case 'e':
  case 'E': return true;
  default: return false;
  }
}

static char *BackupNumber(char *Pos, char *FirstChar) {
  while (Pos > FirstChar && isNumberChar(Pos[-1]))
    --Pos;
  return Pos;
}

static void CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End) {
  char *F1NumEnd, *F2NumEnd;
  double V1 = strtod(F1P, &F1NumEnd);
  double V2 = strtod(F2P, &F2NumEnd);

  if (F1NumEnd == F1P || F2NumEnd == F2P) {
    std::cerr << "Comparison failed, not a numeric difference.\n";
    exit(1);
  }

  // Check to see if these are inside the absolute tolerance
  if (AbsTolerance < std::abs(V1-V2)) {
    // Nope, check the relative tolerance...
    double Diff;
    if (V2)
      Diff = std::abs(V1/V2 - 1.0);
    else if (V1)
      Diff = std::abs(V2/V1 - 1.0);
    else
      Diff = 0;  // Both zero.
    if (Diff > RelTolerance) {
      std::cerr << "Compared: " << V1 << " and " << V2 << ": diff = "
                << Diff << "\n";
      std::cerr << "Out of tolerance: rel/abs: " << RelTolerance
                << "/" << AbsTolerance << "\n";
      exit(1);
    }
  }

  // Otherwise, advance our read pointers to the end of the numbers.
  F1P = F1NumEnd;  F2P = F2NumEnd;
}

int main(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv);

  // mmap in the files.
  unsigned File1Len, File2Len;
  char *File1Start, *File2Start;
  OpenFile(File1, File1Len, File1Start);
  OpenFile(File2, File2Len, File2Start);

  // Okay, now that we opened the files, scan them for the first difference.
  char *File1End = File1Start+File1Len;
  char *File2End = File2Start+File2Len;
  char *F1P = File1Start;
  char *F2P = File2Start;

  while (1) {
    // Scan for the end of file or first difference.
    while (F1P < File1End && F2P < File2End && *F1P == *F2P)
      ++F1P, ++F2P;

    if (F1P >= File1End || F2P >= File2End) break;

    // Okay, we must have found a difference.  Backup to the start of the
    // current number each stream is at so that we can compare from the
    // beginning.
    F1P = BackupNumber(F1P, File1Start);
    F2P = BackupNumber(F2P, File2Start);

    // Now that we are at the start of the numbers, compare them, exiting if
    // they don't match.
    CompareNumbers(F1P, F2P, File1End, File2End);
  }

  // Okay, we reached the end of file.  If both files are at the end, we
  // succeeded.
  if (F1P >= File1End && F2P >= File2End) return 0;

  // Otherwise, we might have run off the end due to a number, backup and retry.
  F1P = BackupNumber(F1P, File1Start);
  F2P = BackupNumber(F2P, File2Start);

  // Now that we are at the start of the numbers, compare them, exiting if
  // they don't match.
  CompareNumbers(F1P, F2P, File1End, File2End);

  // If we found the end, we succeeded.
  if (F1P >= File1End && F2P >= File2End) return 0;

  return 1;
}

<commit_msg>mmap of a zero length file returns null on some platforms, so hack around it.<commit_after>//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// fpcmp is a tool that basically works like the 'cmp' tool, except that it can
// tolerate errors due to floating point noise, with the -r option.
//
//===----------------------------------------------------------------------===//

#include "Support/CommandLine.h"
#include "Support/FileUtilities.h"
#include "Config/fcntl.h"
#include "Config/sys/mman.h"
#include <iostream>
#include <cmath>

using namespace llvm;

namespace {
  cl::opt<std::string>
  File1(cl::Positional, cl::desc("<input file #1>"), cl::Required);
  cl::opt<std::string>
  File2(cl::Positional, cl::desc("<input file #2>"), cl::Required);

  cl::opt<double>
  RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0));
  cl::opt<double>
  AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0));
}

/// OpenFile - mmap the specified file into the address space for reading, and
/// return the length and address of the buffer.
static void OpenFile(const std::string &Filename, unsigned &Len, char* &BufPtr){
  int FD = open(Filename.c_str(), O_RDONLY);
  if (FD == -1 || (Len = getFileSize(Filename)) == ~0U) {
    std::cerr << "Error: cannot open file '" << Filename << "'\n";
    exit(2);
  }

  // mmap in the file all at once...
  BufPtr = (char*)mmap(0, Len, PROT_READ, MAP_PRIVATE, FD, 0);

  if (BufPtr == (char*)MAP_FAILED) {
    std::cerr << "Error: cannot open file '" << Filename << "'\n";
    exit(2);
  }

  // If mmap decided that the files were empty, it might have returned a
  // null pointer. If so, make a new, fake pointer -- it shouldn't matter
  // what it contains, because Len is 0, and it should never be read.
  if (BufPtr == 0 && Len == 0)
    BufPtr = new char[1];
}

static bool isNumberChar(char C) {
  switch (C) {
  case '0': case '1': case '2': case '3': case '4':
  case '5': case '6': case '7': case '8': case '9':
  case '.': case '+': case '-':
  case 'e':
  case 'E': return true;
  default: return false;
  }
}

static char *BackupNumber(char *Pos, char *FirstChar) {
  while (Pos > FirstChar && isNumberChar(Pos[-1]))
    --Pos;
  return Pos;
}

static void CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End) {
  char *F1NumEnd, *F2NumEnd;
  double V1 = strtod(F1P, &F1NumEnd);
  double V2 = strtod(F2P, &F2NumEnd);

  if (F1NumEnd == F1P || F2NumEnd == F2P) {
    std::cerr << "Comparison failed, not a numeric difference.\n";
    exit(1);
  }

  // Check to see if these are inside the absolute tolerance
  if (AbsTolerance < std::abs(V1-V2)) {
    // Nope, check the relative tolerance...
    double Diff;
    if (V2)
      Diff = std::abs(V1/V2 - 1.0);
    else if (V1)
      Diff = std::abs(V2/V1 - 1.0);
    else
      Diff = 0;  // Both zero.
    if (Diff > RelTolerance) {
      std::cerr << "Compared: " << V1 << " and " << V2 << ": diff = "
                << Diff << "\n";
      std::cerr << "Out of tolerance: rel/abs: " << RelTolerance
                << "/" << AbsTolerance << "\n";
      exit(1);
    }
  }

  // Otherwise, advance our read pointers to the end of the numbers.
  F1P = F1NumEnd;  F2P = F2NumEnd;
}

int main(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv);

  // mmap in the files.
  unsigned File1Len, File2Len;
  char *File1Start, *File2Start;
  OpenFile(File1, File1Len, File1Start);
  OpenFile(File2, File2Len, File2Start);

  // Okay, now that we opened the files, scan them for the first difference.
  char *File1End = File1Start+File1Len;
  char *File2End = File2Start+File2Len;
  char *F1P = File1Start;
  char *F2P = File2Start;

  while (1) {
    // Scan for the end of file or first difference.
    while (F1P < File1End && F2P < File2End && *F1P == *F2P)
      ++F1P, ++F2P;

    if (F1P >= File1End || F2P >= File2End) break;

    // Okay, we must have found a difference.  Backup to the start of the
    // current number each stream is at so that we can compare from the
    // beginning.
    F1P = BackupNumber(F1P, File1Start);
    F2P = BackupNumber(F2P, File2Start);

    // Now that we are at the start of the numbers, compare them, exiting if
    // they don't match.
    CompareNumbers(F1P, F2P, File1End, File2End);
  }

  // Okay, we reached the end of file.  If both files are at the end, we
  // succeeded.
  if (F1P >= File1End && F2P >= File2End) return 0;

  // Otherwise, we might have run off the end due to a number, backup and retry.
  F1P = BackupNumber(F1P, File1Start);
  F2P = BackupNumber(F2P, File2Start);

  // Now that we are at the start of the numbers, compare them, exiting if
  // they don't match.
  CompareNumbers(F1P, F2P, File1End, File2End);

  // If we found the end, we succeeded.
  if (F1P >= File1End && F2P >= File2End) return 0;

  return 1;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ik_ce.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 11:48:55 $
 *
 *  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 ARY_IDL_IK_CE_HXX
#define ARY_IDL_IK_CE_HXX

// USED SERVICES
    // BASE CLASSES
    // COMPONENTS
    // PARAMETERS
#include <ary/idl/i_language.hxx>
#include <ary/stdconstiter.hxx>

namespace ary
{
namespace info
{
     class Text;
}
namespace idl
{

namespace ifc_ce
{

typedef ::ary::Dyn_StdConstIterator<Ce_id>      Dyn_CeIterator;
typedef ::ary::Dyn_StdConstIterator<Type_id>    Dyn_TypeIterator;
typedef ::ary::info::Text                       DocText;

struct attr
{
    static Ce_id        CeId(
                            const CodeEntity &  i_ce );
    static const String &
                        LocalName(
                            const CodeEntity &  i_ce );
    static Ce_id        NameRoom(
                            const CodeEntity &  i_ce );
    static Rid          Owner(
                            const CodeEntity &  i_ce );
    static E_SightLevel SightLevel(
                            const CodeEntity &  i_ce );
    static bool         Search_Member(
                            const CodeEntity &  ,
                            const String &      )
                            { return true; }    // KORR_FUTURE
};

struct xref
{
};

struct doc
{
    static const DocText &
                        ShortInfo(          /// @return a short description of the CodeEntity
                            const CodeEntity &  i_ce );

    static const DocText &
                        TagAuthor(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagExample(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagDescr(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagGuarantees(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagKey(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagMissing(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagSee(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagShort(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagVersion(
                            const CodeEntity &  i_ce );

    void                Get_UnkownTags(
                            Dyn_CeIterator &    o_result,
                            const CodeEntity &  i_ce );

    bool                IsDeprecated(
                            const CodeEntity &  i_ce );
    bool                IsIncomplete(
                            const CodeEntity &  i_ce );
    bool                IsInternal(
                            const CodeEntity &  i_ce );
    bool                IsNodoc(
                            const CodeEntity &  i_ce );
    bool                IsOptional(
                            const CodeEntity &  i_ce );
    bool                IsSuspicious(
                            const CodeEntity &  i_ce );

};

}   // namespace ifc_ce

}   // namspace idl
}   // namspace ary

#endif

<commit_msg>INTEGRATION: CWS adc18 (1.3.32); FILE MERGED 2007/10/18 13:06:37 np 1.3.32.1: #i81775#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ik_ce.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 15:13:20 $
 *
 *  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 ARY_IDL_IK_CE_HXX
#define ARY_IDL_IK_CE_HXX
//  KORR_DEPRECATED_3.0

// USED SERVICES
    // BASE CLASSES
    // COMPONENTS
    // PARAMETERS
#include <ary/idl/i_types4idl.hxx>
#include <ary/stdconstiter.hxx>

namespace ary
{
namespace info
{
     class Text;
}
namespace idl
{

namespace ifc_ce
{

typedef ::ary::Dyn_StdConstIterator<Ce_id>      Dyn_CeIterator;
typedef ::ary::Dyn_StdConstIterator<Type_id>    Dyn_TypeIterator;
typedef ::ary::info::Text                       DocText;

struct attr
{
    static Ce_id        CeId(
                            const CodeEntity &  i_ce );
    static const String &
                        LocalName(
                            const CodeEntity &  i_ce );
    static Ce_id        NameRoom(
                            const CodeEntity &  i_ce );
    static Rid          Owner(
                            const CodeEntity &  i_ce );
    static E_SightLevel SightLevel(
                            const CodeEntity &  i_ce );
    static bool         Search_Member(
                            const CodeEntity &  ,
                            const String &      )
                            { return true; }    // KORR_FUTURE
};

struct xref
{
};

struct doc
{
    static const DocText &
                        ShortInfo(          /// @return a short description of the CodeEntity
                            const CodeEntity &  i_ce );

    static const DocText &
                        TagAuthor(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagExample(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagDescr(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagGuarantees(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagKey(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagMissing(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagSee(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagShort(
                            const CodeEntity &  i_ce );
    static const DocText &
                        TagVersion(
                            const CodeEntity &  i_ce );

    void                Get_UnkownTags(
                            Dyn_CeIterator &    o_result,
                            const CodeEntity &  i_ce );

    bool                IsDeprecated(
                            const CodeEntity &  i_ce );
    bool                IsIncomplete(
                            const CodeEntity &  i_ce );
    bool                IsInternal(
                            const CodeEntity &  i_ce );
    bool                IsNodoc(
                            const CodeEntity &  i_ce );
    bool                IsOptional(
                            const CodeEntity &  i_ce );
    bool                IsSuspicious(
                            const CodeEntity &  i_ce );

};

}   // namespace ifc_ce

}   // namspace idl
}   // namspace ary

#endif

<|endoftext|>


<commit_before>//----------------------------  vertex_as_face_05.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2010 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  vertex_as_face_05.cc  ---------------------------

// verify that we can do things like cell->face() in 1d as well. here:
// test DoFHandler accessors for the same thing as the _01 test

#include "../tests.h"
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <grid/tria_accessor.h>
#include <grid/grid_generator.h>

#include <fe/fe_system.h>
#include <fe/fe_q.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_accessor.h>

#include <fstream>

template <int spacedim>
void test ()
{
  Triangulation<1,spacedim> tria;
  GridGenerator::hyper_cube (tria);

  FESystem<1,spacedim> fe(FE_Q<1,spacedim>(2),2,
			  FE_Q<1,spacedim>(1),1);
  DoFHandler<1,spacedim> dof_handler (tria);
  dof_handler.distribute_dofs (fe);

  deallog << "Coarse mesh:" << std::endl;
  deallog << "Left vertex=" << dof_handler.begin_active()->face(0)->vertex(0) << std::endl;
  deallog << "Right vertex=" << dof_handler.begin_active()->face(1)->vertex(0) << std::endl;

  tria.refine_global (2);
  dof_handler.distribute_dofs (fe);

  for (typename Triangulation<1,spacedim>::active_cell_iterator
	 cell = dof_handler.begin_active();
       cell != dof_handler.end(); ++cell)
    {
      deallog << "Cell: " << cell << std::endl;
      deallog << "Left vertex=" << cell->face(0)->vertex(0) << std::endl;
      deallog << "Right vertex=" << cell->face(1)->vertex(0) << std::endl;
    }
}

int main ()
{
  std::ofstream logfile("vertex_as_face_05/output");
  deallog.attach(logfile);
  deallog.depth_console(0);

  test<1> ();
  test<2> ();

  return 0;
}
<commit_msg>Fix type of iterator.<commit_after>//----------------------------  vertex_as_face_05.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2010 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  vertex_as_face_05.cc  ---------------------------

// verify that we can do things like cell->face() in 1d as well. here:
// test DoFHandler accessors for the same thing as the _01 test

#include "../tests.h"
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <grid/tria_accessor.h>
#include <grid/grid_generator.h>

#include <fe/fe_system.h>
#include <fe/fe_q.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_accessor.h>

#include <fstream>

template <int spacedim>
void test ()
{
  Triangulation<1,spacedim> tria;
  GridGenerator::hyper_cube (tria);

  FESystem<1,spacedim> fe(FE_Q<1,spacedim>(2),2,
			  FE_Q<1,spacedim>(1),1);
  DoFHandler<1,spacedim> dof_handler (tria);
  dof_handler.distribute_dofs (fe);

  deallog << "Coarse mesh:" << std::endl;
  deallog << "Left vertex=" << dof_handler.begin_active()->face(0)->vertex(0) << std::endl;
  deallog << "Right vertex=" << dof_handler.begin_active()->face(1)->vertex(0) << std::endl;

  tria.refine_global (2);
  dof_handler.distribute_dofs (fe);

  for (typename DoFHandler<1,spacedim>::active_cell_iterator
	 cell = dof_handler.begin_active();
       cell != dof_handler.end(); ++cell)
    {
      deallog << "Cell: " << cell << std::endl;
      deallog << "Left vertex=" << cell->face(0)->vertex(0) << std::endl;
      deallog << "Right vertex=" << cell->face(1)->vertex(0) << std::endl;
    }
}

int main ()
{
  std::ofstream logfile("vertex_as_face_05/output");
  deallog.attach(logfile);
  deallog.depth_console(0);

  test<1> ();
  test<2> ();

  return 0;
}
<|endoftext|>