<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: test_interactionhandler.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 15:41:38 $
 *
 *  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
 *
 ************************************************************************/

/**************************************************************************
                                TODO
 **************************************************************************

 *************************************************************************/
#ifndef _TEST_ACTIVEDATASINK_HXX_
#define _TEST_ACTIVEDATASINK_HXX_

#include <cppuhelper/weak.hxx>
#include <cppuhelper/queryinterface.hxx>
#include <com/sun/star/task/XInteractionHandler.hpp>

namespace test_ftp {

    class Test_InteractionHandler
        : public cppu::OWeakObject,
          public com::sun::star::task::XInteractionHandler
    {
    public:

        // 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( void ) throw();

        virtual void SAL_CALL release( void ) throw();

        // XInteractionHandler

        virtual void SAL_CALL
        handle( const ::com::sun::star::uno::Reference<
                ::com::sun::star::task::XInteractionRequest >& Request )
            throw (::com::sun::star::uno::RuntimeException);

    private:

    };

}

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

/**************************************************************************
                                TODO
 **************************************************************************

 *************************************************************************/
#ifndef _TEST_ACTIVEDATASINK_HXX_
#define _TEST_ACTIVEDATASINK_HXX_

#include <cppuhelper/weak.hxx>
#include <cppuhelper/queryinterface.hxx>
#include <com/sun/star/task/XInteractionHandler.hpp>

namespace test_ftp {

    class Test_InteractionHandler
        : public cppu::OWeakObject,
          public com::sun::star::task::XInteractionHandler
    {
    public:

        // 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( void ) throw();

        virtual void SAL_CALL release( void ) throw();

        // XInteractionHandler

        virtual void SAL_CALL
        handle( const ::com::sun::star::uno::Reference<
                ::com::sun::star::task::XInteractionRequest >& Request )
            throw (::com::sun::star::uno::RuntimeException);

    private:

    };

}

#endif
<|endoftext|>


<commit_before>#include "aboutwindow.h"
#include "ui_aboutwindow.h"

AboutWindow::AboutWindow(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AboutWindow)
{
    ui->setupUi(this);
    ui->lblAbout->setTextFormat(Qt::RichText);
    ui->lblAbout->setTextInteractionFlags(Qt::TextBrowserInteraction);
    ui->lblAbout->setOpenExternalLinks(true);

    ui->lblAbout->setText(QString("Team Shock:
Brian Mottola
Casey Conway\

Jesse Zhou\nShamus Cardon

\
                           GitHub"));
}

AboutWindow::~AboutWindow()
{
    delete ui;
}
<commit_msg>added github link<commit_after>#include "aboutwindow.h"
#include "ui_aboutwindow.h"

AboutWindow::AboutWindow(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AboutWindow)
{
    ui->setupUi(this);
    ui->lblAbout->setTextFormat(Qt::RichText);
    ui->lblAbout->setTextInteractionFlags(Qt::TextBrowserInteraction);
    ui->lblAbout->setOpenExternalLinks(true);

    ui->lblAbout->setText(QString("Team Shock:
Brian Mottola
Casey Conway\

Jesse Zhou\nShamus Cardon

\
                           GitHub"));
}

AboutWindow::~AboutWindow()
{
    delete ui;
}
<|endoftext|>


<commit_before>/// This file is part of the KDE libraries
/// Copyright (C) 2008 Paul Giannaros <paul@giannaros.org>
///
/// This library is free software; you can redistribute it and/or
/// modify it under the terms of the GNU Library General Public
/// License as published by the Free Software Foundation; either
/// version 2 of the License, or (at your option) version 3.
///
/// 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
/// Library General Public License for more details.
///
/// You should have received a copy of the GNU Library General Public License
/// along with this library; see the file COPYING.LIB.  If not, write to
/// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
/// Boston, MA 02110-1301, USA.

#include "katescriptdocument.h"

#include "katedocument.h"
#include "kateview.h"
#include "katerenderer.h"
#include "katehighlight.h"
#include "katescript.h"

KateScriptDocument::KateScriptDocument(QObject *parent)
  : QObject(parent), m_document(0)
{
}

void KateScriptDocument::setDocument(KateDocument *document)
{
  m_document = document;
}

KateDocument *KateScriptDocument::document()
{
  return m_document;
}

bool KateScriptDocument::isCode(int line, int column)
{
  KateDocCursor cursor(line, column, m_document);
  QList<KTextEditor::Attribute::Ptr> attributes = m_document->highlight()->attributes(((KateView*) m_document->activeView())->renderer()->config()->schema());
  KTextEditor::Attribute::Ptr a = attributes[cursor.currentAttrib()];
  const int defaultStyle = a->property(KateExtendedAttribute::AttributeDefaultStyleIndex).toInt();
  return _isCode(defaultStyle);
}

int KateScriptDocument::firstVirtualColumn(int line)
{
  const int tabWidth = m_document->config()->tabWidth();
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(line);
  const int firstPos = textLine ? textLine->firstChar() : -1;
  if(!textLine || firstPos == -1)
    return -1;
  return textLine->indentDepth(tabWidth);
}

int KateScriptDocument::lastVirtualColumn(int line)
{
  const int tabWidth = m_document->config()->tabWidth();
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(line);
  const int lastPos = textLine ? textLine->lastChar() : -1;
  if(!textLine || lastPos == -1)
    return -1;
  return textLine->toVirtualColumn(lastPos, tabWidth);
}

int KateScriptDocument::toVirtualColumn(int line, int column)
{
  const int tabWidth = m_document->config()->tabWidth();
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(line);
  if (!textLine || column < 0 || column > textLine->length()) return -1;
  return textLine->toVirtualColumn(column, tabWidth);
}

int KateScriptDocument::fromVirtualColumn(int line, int virtualColumn)
{
  const int tabWidth = m_document->config()->tabWidth();
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(line);
  if(!textLine || virtualColumn < 0 || virtualColumn > textLine->virtualLength(tabWidth))
    return -1;
  return textLine->fromVirtualColumn(virtualColumn, tabWidth);
}

KTextEditor::Cursor KateScriptDocument::anchor(int line, int column, QChar character)
{
  KateDocCursor cursor(line, column, m_document);
  QList<KTextEditor::Attribute::Ptr> attributes =
      m_document->highlight()->attributes(((KateView*) m_document->activeView())->renderer()->config()->schema());
  int count = 1;
  QChar lc = character;
  QChar rc;
  if (lc == '(') rc = ')';
  else if (lc == '{') rc = '}';
  else if (lc == '[') rc = ']';
  else return KTextEditor::Cursor::invalid ();

  // Move backwards char by char and find the opening character
  while (cursor.moveBackward(1)) {
    QChar ch = cursor.currentChar();
    if (ch == lc) {
      KTextEditor::Attribute::Ptr a = attributes[cursor.currentAttrib()];
      const int ds = a->property(KateExtendedAttribute::AttributeDefaultStyleIndex).toInt();
      if (_isCode(ds)) {
        --count;
      }
    }
    else if (ch == rc) {
      KTextEditor::Attribute::Ptr a = attributes[cursor.currentAttrib()];
      const int ds = a->property(KateExtendedAttribute::AttributeDefaultStyleIndex).toInt();
      if (_isCode(ds)) {
        ++count;
      }
    }

    if (count == 0) {
      return KTextEditor::Cursor (line, column);
    }
  }
  return KTextEditor::Cursor::invalid ();
}

bool KateScriptDocument::startsWith (int line, const QString &pattern, bool skipWhiteSpaces)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(line);

  if (!textLine)
    return false;

  if (skipWhiteSpaces)
    return textLine->matchesAt(textLine->firstChar(), pattern);

  return textLine->startsWith (pattern);
}

bool KateScriptDocument::endsWith (int line, const QString &pattern, bool skipWhiteSpaces)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(line);

  if (!textLine)
    return false;

  if (skipWhiteSpaces)
    return textLine->matchesAt(textLine->lastChar() - pattern.length() + 1, pattern);

  return textLine->endsWith (pattern);
}

//BEGIN Automatically generated

QString KateScriptDocument::fileName()
{
  return m_document->documentName();
}

QString KateScriptDocument::url()
{
  return m_document->url().prettyUrl();
}

QString KateScriptDocument::mimeType()
{
  return m_document->mimeType();
}

QString KateScriptDocument::encoding()
{
  return m_document->encoding();
}

bool KateScriptDocument::isModified()
{
  return m_document->isModified();
}

QString KateScriptDocument::text()
{
  return m_document->text();
}

QString KateScriptDocument::textRange(int i, int j, int k, int l)
{
  return m_document->text(KTextEditor::Range(i, j, k, l));
}

QString KateScriptDocument::line(int i)
{
  return m_document->line (i);
}

QString KateScriptDocument::wordAt(int i, int j)
{
  return m_document->getWord(KTextEditor::Cursor(i, j));
}

QString KateScriptDocument::charAt(int i, int j)
{
  const QChar c = m_document->character (KTextEditor::Cursor(i, j));
  return c.isNull() ? "" : QString(c);
}

QString KateScriptDocument::firstChar(int i)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  if(!textLine) return "";
  // check for isNull(), as the returned character then would be "\0"
  const QChar c = textLine->at(textLine->firstChar());
  return c.isNull() ? "" : QString(c);
}

QString KateScriptDocument::lastChar(int i)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  if(!textLine) return "";
  // check for isNull(), as the returned character then would be "\0"
  const QChar c = textLine->at(textLine->lastChar());
  return c.isNull() ? "" : QString(c);
}

bool KateScriptDocument::isSpace(int i, int j)
{
  return m_document->character (KTextEditor::Cursor(i, j)).isSpace();
}

bool KateScriptDocument::matchesAt(int i, int j, const QString &s)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  return textLine ? textLine->matchesAt(j, s) : false;
}

bool KateScriptDocument::setText(const QString &s)
{
  return m_document->setText(s);
}

bool KateScriptDocument::clear()
{
  return m_document->clear();
}

bool KateScriptDocument::truncate(int i, int j)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  if(textLine) textLine->truncate(j);
  return static_cast<bool>(textLine);
}

bool KateScriptDocument::insertText(int i, int j, const QString &s)
{
  return m_document->insertText (KTextEditor::Cursor(i, j), s);
}

bool KateScriptDocument::removeText(int i, int j, int k, int l)
{
  return m_document->removeText(KTextEditor::Range(i, j, k, l));
}

bool KateScriptDocument::insertLine(int i, const QString &s)
{
  return m_document->insertLine (i, s);
}

bool KateScriptDocument::removeLine(int i)
{
  return m_document->removeLine (i);
}

void KateScriptDocument::joinLines(int i, int j)
{
  m_document->joinLines (i, j);
  return;
}

int KateScriptDocument::lines()
{
  return m_document->lines();
}

int KateScriptDocument::length()
{
  return m_document->totalCharacters();
}

int KateScriptDocument::lineLength(int i)
{
  return m_document->lineLength(i);
}

void KateScriptDocument::editBegin()
{
  m_document->editBegin();
  return;
}

void KateScriptDocument::editEnd()
{
  m_document->editEnd ();
  return;
}

int KateScriptDocument::firstColumn(int i)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  return textLine ? textLine->firstChar() : -1;
}

int KateScriptDocument::lastColumn(int i)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  return textLine ? textLine->lastChar() : -1;
}

int KateScriptDocument::prevNonSpaceColumn(int i, int j)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  if(!textLine) return -1;
  return textLine->previousNonSpaceChar(j);
}

int KateScriptDocument::nextNonSpaceColumn(int i, int j)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  if(!textLine) return -1;
  return textLine->nextNonSpaceChar(j);
}

int KateScriptDocument::prevNonEmptyLine(int i)
{
  const int startLine = i;
  for (int currentLine = startLine; currentLine >= 0; --currentLine) {
    KateTextLine::Ptr textLine = m_document->plainKateTextLine(currentLine);
    if(!textLine)
      return -1;
    if(textLine->firstChar() != -1)
      return currentLine;
  }
  return -1;
}

int KateScriptDocument::nextNonEmptyLine(int i)
{
  const int startLine = i;
  for (int currentLine = startLine; currentLine < m_document->lines(); ++currentLine) {
    KateTextLine::Ptr textLine = m_document->plainKateTextLine(currentLine);
    if(!textLine)
      return -1;
    if(textLine->firstChar() != -1)
      return currentLine;
  }
  return -1;
}

bool KateScriptDocument::isInWord(const QString &s, int i)
{
  return m_document->highlight()->isInWord(s.at(0), i);
}

bool KateScriptDocument::canBreakAt(const QString &s, int i)
{
  return m_document->highlight()->canBreakAt(s.at(0), i);
}

bool KateScriptDocument::canComment(int i, int j)
{
  return m_document->highlight()->canComment(i, j);
}

QString KateScriptDocument::commentMarker(int i)
{
  return m_document->highlight()->getCommentSingleLineStart(i);
}

QString KateScriptDocument::commentStart(int i)
{
  return m_document->highlight()->getCommentStart(i);
}

QString KateScriptDocument::commentEnd(int i)
{
  return m_document->highlight()->getCommentEnd(i);
}

int KateScriptDocument::attribute(int i, int j)
{
  KateTextLine::Ptr textLine = m_document->kateTextLine(i);
  if(!textLine) return 0;
  return textLine->attribute(j);
}

QString KateScriptDocument::variable(const QString &s)
{
  return m_document->variable(s);
}

//END

bool KateScriptDocument::_isCode(int defaultStyle)
{
  return (defaultStyle != KateExtendedAttribute::dsComment
       && defaultStyle != KateExtendedAttribute::dsString
       && defaultStyle != KateExtendedAttribute::dsRegionMarker
       && defaultStyle != KateExtendedAttribute::dsChar
       && defaultStyle != KateExtendedAttribute::dsOthers);
}

// kate: space-indent on; indent-width 2; replace-tabs on;

<commit_msg>Return proper cursor from KateScriptDocument::anchor.<commit_after>/// This file is part of the KDE libraries
/// Copyright (C) 2008 Paul Giannaros <paul@giannaros.org>
///
/// This library is free software; you can redistribute it and/or
/// modify it under the terms of the GNU Library General Public
/// License as published by the Free Software Foundation; either
/// version 2 of the License, or (at your option) version 3.
///
/// 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
/// Library General Public License for more details.
///
/// You should have received a copy of the GNU Library General Public License
/// along with this library; see the file COPYING.LIB.  If not, write to
/// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
/// Boston, MA 02110-1301, USA.

#include "katescriptdocument.h"

#include "katedocument.h"
#include "kateview.h"
#include "katerenderer.h"
#include "katehighlight.h"
#include "katescript.h"

KateScriptDocument::KateScriptDocument(QObject *parent)
  : QObject(parent), m_document(0)
{
}

void KateScriptDocument::setDocument(KateDocument *document)
{
  m_document = document;
}

KateDocument *KateScriptDocument::document()
{
  return m_document;
}

bool KateScriptDocument::isCode(int line, int column)
{
  KateDocCursor cursor(line, column, m_document);
  QList<KTextEditor::Attribute::Ptr> attributes = m_document->highlight()->attributes(((KateView*) m_document->activeView())->renderer()->config()->schema());
  KTextEditor::Attribute::Ptr a = attributes[cursor.currentAttrib()];
  const int defaultStyle = a->property(KateExtendedAttribute::AttributeDefaultStyleIndex).toInt();
  return _isCode(defaultStyle);
}

int KateScriptDocument::firstVirtualColumn(int line)
{
  const int tabWidth = m_document->config()->tabWidth();
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(line);
  const int firstPos = textLine ? textLine->firstChar() : -1;
  if(!textLine || firstPos == -1)
    return -1;
  return textLine->indentDepth(tabWidth);
}

int KateScriptDocument::lastVirtualColumn(int line)
{
  const int tabWidth = m_document->config()->tabWidth();
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(line);
  const int lastPos = textLine ? textLine->lastChar() : -1;
  if(!textLine || lastPos == -1)
    return -1;
  return textLine->toVirtualColumn(lastPos, tabWidth);
}

int KateScriptDocument::toVirtualColumn(int line, int column)
{
  const int tabWidth = m_document->config()->tabWidth();
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(line);
  if (!textLine || column < 0 || column > textLine->length()) return -1;
  return textLine->toVirtualColumn(column, tabWidth);
}

int KateScriptDocument::fromVirtualColumn(int line, int virtualColumn)
{
  const int tabWidth = m_document->config()->tabWidth();
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(line);
  if(!textLine || virtualColumn < 0 || virtualColumn > textLine->virtualLength(tabWidth))
    return -1;
  return textLine->fromVirtualColumn(virtualColumn, tabWidth);
}

KTextEditor::Cursor KateScriptDocument::anchor(int line, int column, QChar character)
{
  KateDocCursor cursor(line, column, m_document);
  QList<KTextEditor::Attribute::Ptr> attributes =
      m_document->highlight()->attributes(((KateView*) m_document->activeView())->renderer()->config()->schema());
  int count = 1;
  QChar lc = character;
  QChar rc;
  if (lc == '(') rc = ')';
  else if (lc == '{') rc = '}';
  else if (lc == '[') rc = ']';
  else return KTextEditor::Cursor::invalid ();

  // Move backwards char by char and find the opening character
  while (cursor.moveBackward(1)) {
    QChar ch = cursor.currentChar();
    if (ch == lc) {
      KTextEditor::Attribute::Ptr a = attributes[cursor.currentAttrib()];
      const int ds = a->property(KateExtendedAttribute::AttributeDefaultStyleIndex).toInt();
      if (_isCode(ds)) {
        --count;
      }
    }
    else if (ch == rc) {
      KTextEditor::Attribute::Ptr a = attributes[cursor.currentAttrib()];
      const int ds = a->property(KateExtendedAttribute::AttributeDefaultStyleIndex).toInt();
      if (_isCode(ds)) {
        ++count;
      }
    }

    if (count == 0) {
      return cursor;
    }
  }
  return KTextEditor::Cursor::invalid ();
}

bool KateScriptDocument::startsWith (int line, const QString &pattern, bool skipWhiteSpaces)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(line);

  if (!textLine)
    return false;

  if (skipWhiteSpaces)
    return textLine->matchesAt(textLine->firstChar(), pattern);

  return textLine->startsWith (pattern);
}

bool KateScriptDocument::endsWith (int line, const QString &pattern, bool skipWhiteSpaces)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(line);

  if (!textLine)
    return false;

  if (skipWhiteSpaces)
    return textLine->matchesAt(textLine->lastChar() - pattern.length() + 1, pattern);

  return textLine->endsWith (pattern);
}

//BEGIN Automatically generated

QString KateScriptDocument::fileName()
{
  return m_document->documentName();
}

QString KateScriptDocument::url()
{
  return m_document->url().prettyUrl();
}

QString KateScriptDocument::mimeType()
{
  return m_document->mimeType();
}

QString KateScriptDocument::encoding()
{
  return m_document->encoding();
}

bool KateScriptDocument::isModified()
{
  return m_document->isModified();
}

QString KateScriptDocument::text()
{
  return m_document->text();
}

QString KateScriptDocument::textRange(int i, int j, int k, int l)
{
  return m_document->text(KTextEditor::Range(i, j, k, l));
}

QString KateScriptDocument::line(int i)
{
  return m_document->line (i);
}

QString KateScriptDocument::wordAt(int i, int j)
{
  return m_document->getWord(KTextEditor::Cursor(i, j));
}

QString KateScriptDocument::charAt(int i, int j)
{
  const QChar c = m_document->character (KTextEditor::Cursor(i, j));
  return c.isNull() ? "" : QString(c);
}

QString KateScriptDocument::firstChar(int i)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  if(!textLine) return "";
  // check for isNull(), as the returned character then would be "\0"
  const QChar c = textLine->at(textLine->firstChar());
  return c.isNull() ? "" : QString(c);
}

QString KateScriptDocument::lastChar(int i)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  if(!textLine) return "";
  // check for isNull(), as the returned character then would be "\0"
  const QChar c = textLine->at(textLine->lastChar());
  return c.isNull() ? "" : QString(c);
}

bool KateScriptDocument::isSpace(int i, int j)
{
  return m_document->character (KTextEditor::Cursor(i, j)).isSpace();
}

bool KateScriptDocument::matchesAt(int i, int j, const QString &s)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  return textLine ? textLine->matchesAt(j, s) : false;
}

bool KateScriptDocument::setText(const QString &s)
{
  return m_document->setText(s);
}

bool KateScriptDocument::clear()
{
  return m_document->clear();
}

bool KateScriptDocument::truncate(int i, int j)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  if(textLine) textLine->truncate(j);
  return static_cast<bool>(textLine);
}

bool KateScriptDocument::insertText(int i, int j, const QString &s)
{
  return m_document->insertText (KTextEditor::Cursor(i, j), s);
}

bool KateScriptDocument::removeText(int i, int j, int k, int l)
{
  return m_document->removeText(KTextEditor::Range(i, j, k, l));
}

bool KateScriptDocument::insertLine(int i, const QString &s)
{
  return m_document->insertLine (i, s);
}

bool KateScriptDocument::removeLine(int i)
{
  return m_document->removeLine (i);
}

void KateScriptDocument::joinLines(int i, int j)
{
  m_document->joinLines (i, j);
  return;
}

int KateScriptDocument::lines()
{
  return m_document->lines();
}

int KateScriptDocument::length()
{
  return m_document->totalCharacters();
}

int KateScriptDocument::lineLength(int i)
{
  return m_document->lineLength(i);
}

void KateScriptDocument::editBegin()
{
  m_document->editBegin();
  return;
}

void KateScriptDocument::editEnd()
{
  m_document->editEnd ();
  return;
}

int KateScriptDocument::firstColumn(int i)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  return textLine ? textLine->firstChar() : -1;
}

int KateScriptDocument::lastColumn(int i)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  return textLine ? textLine->lastChar() : -1;
}

int KateScriptDocument::prevNonSpaceColumn(int i, int j)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  if(!textLine) return -1;
  return textLine->previousNonSpaceChar(j);
}

int KateScriptDocument::nextNonSpaceColumn(int i, int j)
{
  KateTextLine::Ptr textLine = m_document->plainKateTextLine(i);
  if(!textLine) return -1;
  return textLine->nextNonSpaceChar(j);
}

int KateScriptDocument::prevNonEmptyLine(int i)
{
  const int startLine = i;
  for (int currentLine = startLine; currentLine >= 0; --currentLine) {
    KateTextLine::Ptr textLine = m_document->plainKateTextLine(currentLine);
    if(!textLine)
      return -1;
    if(textLine->firstChar() != -1)
      return currentLine;
  }
  return -1;
}

int KateScriptDocument::nextNonEmptyLine(int i)
{
  const int startLine = i;
  for (int currentLine = startLine; currentLine < m_document->lines(); ++currentLine) {
    KateTextLine::Ptr textLine = m_document->plainKateTextLine(currentLine);
    if(!textLine)
      return -1;
    if(textLine->firstChar() != -1)
      return currentLine;
  }
  return -1;
}

bool KateScriptDocument::isInWord(const QString &s, int i)
{
  return m_document->highlight()->isInWord(s.at(0), i);
}

bool KateScriptDocument::canBreakAt(const QString &s, int i)
{
  return m_document->highlight()->canBreakAt(s.at(0), i);
}

bool KateScriptDocument::canComment(int i, int j)
{
  return m_document->highlight()->canComment(i, j);
}

QString KateScriptDocument::commentMarker(int i)
{
  return m_document->highlight()->getCommentSingleLineStart(i);
}

QString KateScriptDocument::commentStart(int i)
{
  return m_document->highlight()->getCommentStart(i);
}

QString KateScriptDocument::commentEnd(int i)
{
  return m_document->highlight()->getCommentEnd(i);
}

int KateScriptDocument::attribute(int i, int j)
{
  KateTextLine::Ptr textLine = m_document->kateTextLine(i);
  if(!textLine) return 0;
  return textLine->attribute(j);
}

QString KateScriptDocument::variable(const QString &s)
{
  return m_document->variable(s);
}

//END

bool KateScriptDocument::_isCode(int defaultStyle)
{
  return (defaultStyle != KateExtendedAttribute::dsComment
       && defaultStyle != KateExtendedAttribute::dsString
       && defaultStyle != KateExtendedAttribute::dsRegionMarker
       && defaultStyle != KateExtendedAttribute::dsChar
       && defaultStyle != KateExtendedAttribute::dsOthers);
}

// kate: space-indent on; indent-width 2; replace-tabs on;

<|endoftext|>


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

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

#include "SchXMLImport.hxx"
#include "SchXMLParagraphContext.hxx"

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif

using namespace rtl;
using namespace com::sun::star;

SchXMLParagraphContext::SchXMLParagraphContext( SvXMLImport& rImport,
                                                const OUString& rLocalName,
                                                OUString& rText ) :
        SvXMLImportContext( rImport, XML_NAMESPACE_TEXT, rLocalName ),
        mrText( rText )
{
}

SchXMLParagraphContext::~SchXMLParagraphContext()
{}

void SchXMLParagraphContext::EndElement()
{
    mrText = maBuffer.makeStringAndClear();
}

SvXMLImportContext* SchXMLParagraphContext::CreateChildContext(
    USHORT nPrefix,
    const OUString& rLocalName,
    const uno::Reference< xml::sax::XAttributeList >& )
{
    if( nPrefix == XML_NAMESPACE_TEXT )
    {
        if( rLocalName.equals( ::xmloff::token::GetXMLToken( ::xmloff::token::XML_TAB_STOP )))
        {
            maBuffer.append( sal_Unicode( 0x0009 ));  // tabulator
        }
        else if( rLocalName.equals( ::xmloff::token::GetXMLToken( ::xmloff::token::XML_LINE_BREAK )))
        {
            maBuffer.append( sal_Unicode( 0x000A ));  // linefeed
        }
    }

    return new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
}

void SchXMLParagraphContext::Characters( const OUString& rChars )
{
    maBuffer.append( rChars );
}
<commit_msg>INTEGRATION: CWS chart20_DEV300 (1.6.142); FILE MERGED 2008/02/21 15:59:48 bm 1.6.142.1: #i366# error bars from cell ranges<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SchXMLParagraphContext.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-06 15:48:03 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include "SchXMLImport.hxx"
#include "SchXMLParagraphContext.hxx"

#include "xmlnmspe.hxx"
#include <xmloff/xmltoken.hxx>
#include <xmloff/nmspmap.hxx>

using namespace rtl;
using namespace com::sun::star;
using namespace ::xmloff::token;

SchXMLParagraphContext::SchXMLParagraphContext( SvXMLImport& rImport,
                                                const OUString& rLocalName,
                                                OUString& rText,
                                                OUString * pOutId /* = 0 */ ) :
        SvXMLImportContext( rImport, XML_NAMESPACE_TEXT, rLocalName ),
        mrText( rText ),
        mpId( pOutId )
{
}

SchXMLParagraphContext::~SchXMLParagraphContext()
{}

void SchXMLParagraphContext::StartElement( const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
    // remember the id. It is used for storing the original cell range string in
    // a local table (cached data)
    if( mpId )
    {
        sal_Int16 nAttrCount = xAttrList.is()? xAttrList->getLength(): 0;
        rtl::OUString aValue;

        for( sal_Int16 i = 0; i < nAttrCount; i++ )
        {
            rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
            rtl::OUString aLocalName;
            USHORT nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( sAttrName, &aLocalName );

            if( nPrefix == XML_NAMESPACE_TEXT &&
                IsXMLToken( aLocalName, XML_ID ) )
            {
                (*mpId) = xAttrList->getValueByIndex( i );
                break;   // we only need this attribute
            }
        }
    }
}

void SchXMLParagraphContext::EndElement()
{
    mrText = maBuffer.makeStringAndClear();
}

SvXMLImportContext* SchXMLParagraphContext::CreateChildContext(
    USHORT nPrefix,
    const OUString& rLocalName,
    const uno::Reference< xml::sax::XAttributeList >& )
{
    if( nPrefix == XML_NAMESPACE_TEXT )
    {
        if( rLocalName.equals( ::xmloff::token::GetXMLToken( ::xmloff::token::XML_TAB_STOP )))
        {
            maBuffer.append( sal_Unicode( 0x0009 ));  // tabulator
        }
        else if( rLocalName.equals( ::xmloff::token::GetXMLToken( ::xmloff::token::XML_LINE_BREAK )))
        {
            maBuffer.append( sal_Unicode( 0x000A ));  // linefeed
        }
    }

    return new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
}

void SchXMLParagraphContext::Characters( const OUString& rChars )
{
    maBuffer.append( rChars );
}
<|endoftext|>


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

#include "absl/strings/str_cat.h"
#include "astronomy/frames.hpp"
#include "geometry/interval.hpp"
#include "geometry/named_quantities.hpp"
#include "glog/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "integrators/methods.hpp"
#include "integrators/symmetric_linear_multistep_integrator.hpp"
#include "mathematica/mathematica.hpp"
#include "numerics/apodization.hpp"
#include "numerics/fast_fourier_transform.hpp"
#include "numerics/frequency_analysis.hpp"
#include "numerics/poisson_series.hpp"
#include "numerics/polynomial_evaluators.hpp"
#include "physics/ephemeris.hpp"
#include "physics/solar_system.hpp"
#include "quantities/astronomy.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "testing_utilities/approximate_quantity.hpp"

namespace principia {
namespace physics {

using astronomy::ICRS;
using geometry::Displacement;
using geometry::Instant;
using geometry::Interval;
using geometry::Position;
using integrators::SymmetricLinearMultistepIntegrator;
using integrators::methods::QuinlanTremaine1990Order12;
using numerics::EstrinEvaluator;
using numerics::FastFourierTransform;
using numerics::PoissonSeries;
using quantities::Angle;
using quantities::AngularFrequency;
using quantities::Length;
using quantities::Time;
using quantities::astronomy::JulianYear;
using quantities::si::Metre;
using quantities::si::Milli;
using quantities::si::Minute;
using quantities::si::Radian;
using quantities::si::Second;

namespace apodization = numerics::apodization;
namespace frequency_analysis = numerics::frequency_analysis;

static constexpr int aperiodic_approximation_degree = 5;
static constexpr int periodic_approximation_degree = 3;
static constexpr int log2_number_of_samples = 14;
static constexpr int number_of_frequencies = 10;
static constexpr Length acceptable_residual = 1 * Metre;

class AnalyticalSeriesTest : public ::testing::Test {
 protected:
  AnalyticalSeriesTest()
      : logger_(TEMP_DIR / "analytical_series.wl",
               /*make_unique=*/false) {
    google::LogToStderr();
  }

  template<int degree>
  PoissonSeries<Displacement<ICRS>,
                std::max(aperiodic_approximation_degree,
                         periodic_approximation_degree),
                EstrinEvaluator>
  ComputeCompactRepresentation(ContinuousTrajectory<ICRS> const& trajectory) {
    Instant const t_min = trajectory.t_min();
    Instant const t_max = trajectory.t_max();
    auto const piecewise_poisson_series =
        trajectory.ToPiecewisePoissonSeries<degree>(t_min, t_max);

    logger_.Set("tMin", t_min, mathematica::ExpressIn(Second));
    logger_.Set("tMax", t_max, mathematica::ExpressIn(Second));

    int step = 0;

    auto angular_frequency_calculator =
        [this, &step, t_min, t_max](
            auto const& residual) -> std::optional<AngularFrequency> {
      Time const Δt = (t_max - t_min) / (1 << log2_number_of_samples);
      LOG(INFO) << "step=" << step;
      if (step == 0) {
        ++step;
        return AngularFrequency();
      } else if (step <= number_of_frequencies) {
        ++step;
        Length max_residual;
        std::vector<Displacement<ICRS>> residuals;
        for (int i = 0; i < 1 << log2_number_of_samples; ++i) {
          residuals.push_back(residual(t_min + i * Δt));
          max_residual = std::max(max_residual, residuals.back().Norm());
        }
        LOG(INFO) << "max_residual=" << max_residual;
        if (max_residual < acceptable_residual) {
          return std::nullopt;
        }
        auto fft =
            std::make_unique<FastFourierTransform<Displacement<ICRS>,
                                                  Instant,
                                                  1 << log2_number_of_samples>>(
                residuals, Δt);
        auto const mode = fft->Mode();
        Interval<Time> const period{2 * π * Radian / mode.max,
                                    2 * π * Radian / mode.min};
        LOG(INFO) << "period=" << period;
        auto const precise_mode = frequency_analysis::PreciseMode(
            mode, residual, apodization::Hann<EstrinEvaluator>(t_min, t_max));
        auto const precise_period = 2 * π * Radian / precise_mode;
        LOG(INFO) << "precise_period=" << precise_period;
        logger_.Append(
            "precisePeriods", precise_period, mathematica::ExpressIn(Second));
        return precise_mode;
      } else {
        Length max_residual;
        for (int i = 0; i < 1 << log2_number_of_samples; ++i) {
          max_residual =
              std::max(max_residual, residual(t_min + i * Δt).Norm());
        }
        LOG(INFO) << "max_residual=" << max_residual
                  << (max_residual > acceptable_residual ? " ***" : "");
        return std::nullopt;
      }
    };

    return frequency_analysis::IncrementalProjection<
        aperiodic_approximation_degree, periodic_approximation_degree>(
        piecewise_poisson_series,
        angular_frequency_calculator,
        apodization::Dirichlet<EstrinEvaluator>(t_min, t_max),
        t_min, t_max);
  }

  mathematica::Logger logger_;
};

#define PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(         \
    degree, approximation, trajectory)                         \
  case degree: {                                               \
    approximation = std::make_unique<                          \
        PoissonSeries<Displacement<ICRS>,                      \
                      std::max(aperiodic_approximation_degree, \
                               periodic_approximation_degree), \
                      EstrinEvaluator>>(                       \
        ComputeCompactRepresentation<(degree)>(trajectory));   \
    break;                                                     \
  }

#if !_DEBUG
TEST_F(AnalyticalSeriesTest, CompactRepresentation) {
  SolarSystem<ICRS> solar_system_at_j2000(
      SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt",
      SOLUTION_DIR / "astronomy" /
          "sol_initial_state_jd_2451545_000000000.proto.txt");

  // NOTE(phl): Keep these parameters aligned with
  // sol_numerics_blueprint.proto.txt.
  auto const ephemeris = solar_system_at_j2000.MakeEphemeris(
      /*accuracy_parameters=*/{/*fitting_tolerance=*/1 * Milli(Metre),
                               /*geopotential_tolerance=*/0x1p-24},
      Ephemeris<ICRS>::FixedStepParameters(
          SymmetricLinearMultistepIntegrator<QuinlanTremaine1990Order12,
                                             Position<ICRS>>(),
          /*step=*/10 * Minute));
  ephemeris->Prolong(solar_system_at_j2000.epoch() + 0.25 * JulianYear);

  for (auto const& celestial : {"Io", "Moon", "Phobos"}/*solar_system_at_j2000.names()*/) {
    LOG(INFO) << "---------- " << celestial;
    auto const& celestial_trajectory =
        solar_system_at_j2000.trajectory(*ephemeris, celestial);
    int const celestial_piecewise_poisson_series_degree =
        celestial_trajectory.PiecewisePoissonSeriesDegree(
            celestial_trajectory.t_min(), celestial_trajectory.t_max());
    std::unique_ptr<PoissonSeries<Displacement<ICRS>,
                                  std::max(aperiodic_approximation_degree,
                                           periodic_approximation_degree),
                                  EstrinEvaluator>>
        celestial_approximation;

    switch (celestial_piecewise_poisson_series_degree) {
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          3, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          4, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          5, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          6, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          7, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          8, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          9, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          10, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          11, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          12, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          13, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          14, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          15, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          16, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          17, celestial_approximation, celestial_trajectory);
      default:
        LOG(FATAL) << "Unexpected degree "
                   << celestial_piecewise_poisson_series_degree;
    };

    logger_.Set(absl::StrCat("approximation", celestial),
                *celestial_approximation,
                mathematica::ExpressIn(Metre, Second, Radian));
  }
}
#endif

#undef PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE

}  // namespace physics
}  // namespace principia
<commit_msg>Test cleanup.<commit_after>
#include <algorithm>
#include <vector>

#include "absl/strings/str_cat.h"
#include "astronomy/frames.hpp"
#include "geometry/interval.hpp"
#include "geometry/named_quantities.hpp"
#include "glog/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "integrators/methods.hpp"
#include "integrators/symmetric_linear_multistep_integrator.hpp"
#include "mathematica/mathematica.hpp"
#include "numerics/apodization.hpp"
#include "numerics/fast_fourier_transform.hpp"
#include "numerics/frequency_analysis.hpp"
#include "numerics/poisson_series.hpp"
#include "numerics/polynomial_evaluators.hpp"
#include "physics/ephemeris.hpp"
#include "physics/solar_system.hpp"
#include "quantities/astronomy.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "testing_utilities/approximate_quantity.hpp"

namespace principia {
namespace physics {

using astronomy::ICRS;
using geometry::Displacement;
using geometry::Instant;
using geometry::Interval;
using geometry::Position;
using integrators::SymmetricLinearMultistepIntegrator;
using integrators::methods::QuinlanTremaine1990Order12;
using numerics::EstrinEvaluator;
using numerics::FastFourierTransform;
using numerics::PoissonSeries;
using quantities::Angle;
using quantities::AngularFrequency;
using quantities::Length;
using quantities::Time;
using quantities::astronomy::JulianYear;
using quantities::si::Metre;
using quantities::si::Milli;
using quantities::si::Minute;
using quantities::si::Radian;
using quantities::si::Second;

namespace apodization = numerics::apodization;
namespace frequency_analysis = numerics::frequency_analysis;

static constexpr int aperiodic_approximation_degree = 5;
static constexpr int periodic_approximation_degree = 3;
static constexpr int log2_number_of_samples = 14;
static constexpr int number_of_frequencies = 10;
static constexpr Length acceptable_residual = 1 * Metre;

class AnalyticalSeriesTest : public ::testing::Test {
 protected:
  AnalyticalSeriesTest()
      : logger_(TEMP_DIR / "analytical_series.wl",
               /*make_unique=*/false) {
    google::LogToStderr();
  }

  template<int degree>
  PoissonSeries<Displacement<ICRS>,
                std::max(aperiodic_approximation_degree,
                         periodic_approximation_degree),
                EstrinEvaluator>
  ComputeCompactRepresentation(ContinuousTrajectory<ICRS> const& trajectory) {
    Instant const t_min = trajectory.t_min();
    Instant const t_max = trajectory.t_max();
    auto const piecewise_poisson_series =
        trajectory.ToPiecewisePoissonSeries<degree>(t_min, t_max);

    logger_.Set("tMin", t_min, mathematica::ExpressIn(Second));
    logger_.Set("tMax", t_max, mathematica::ExpressIn(Second));

    int step = 0;

    auto angular_frequency_calculator =
        [this, &step, t_min, t_max](
            auto const& residual) -> std::optional<AngularFrequency> {
      Time const Δt = (t_max - t_min) / (1 << log2_number_of_samples);
      LOG(INFO) << "step=" << step;
      if (step == 0) {
        ++step;
        return AngularFrequency();
      } else if (step <= number_of_frequencies) {
        ++step;
        Length max_residual;
        std::vector<Displacement<ICRS>> residuals;
        for (int i = 0; i < 1 << log2_number_of_samples; ++i) {
          residuals.push_back(residual(t_min + i * Δt));
          max_residual = std::max(max_residual, residuals.back().Norm());
        }
        LOG(INFO) << "max_residual=" << max_residual;
        if (max_residual < acceptable_residual) {
          return std::nullopt;
        }
        auto fft =
            std::make_unique<FastFourierTransform<Displacement<ICRS>,
                                                  Instant,
                                                  1 << log2_number_of_samples>>(
                residuals, Δt);
        auto const mode = fft->Mode();
        Interval<Time> const period{2 * π * Radian / mode.max,
                                    2 * π * Radian / mode.min};
        LOG(INFO) << "period=" << period;
        auto const precise_mode = frequency_analysis::PreciseMode(
            mode, residual, apodization::Hann<EstrinEvaluator>(t_min, t_max));
        auto const precise_period = 2 * π * Radian / precise_mode;
        LOG(INFO) << "precise_period=" << precise_period;
        logger_.Append(
            "precisePeriods", precise_period, mathematica::ExpressIn(Second));
        return precise_mode;
      } else {
        Length max_residual;
        for (int i = 0; i < 1 << log2_number_of_samples; ++i) {
          max_residual =
              std::max(max_residual, residual(t_min + i * Δt).Norm());
        }
        LOG(INFO) << "max_residual=" << max_residual
                  << (max_residual > acceptable_residual ? " ***" : "");
        return std::nullopt;
      }
    };

    return frequency_analysis::IncrementalProjection<
        aperiodic_approximation_degree, periodic_approximation_degree>(
        piecewise_poisson_series,
        angular_frequency_calculator,
        apodization::Dirichlet<EstrinEvaluator>(t_min, t_max),
        t_min, t_max);
  }

  mathematica::Logger logger_;
};

#define PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(         \
    degree, approximation, trajectory)                         \
  case degree: {                                               \
    approximation = std::make_unique<                          \
        PoissonSeries<Displacement<ICRS>,                      \
                      std::max(aperiodic_approximation_degree, \
                               periodic_approximation_degree), \
                      EstrinEvaluator>>(                       \
        ComputeCompactRepresentation<(degree)>(trajectory));   \
    break;                                                     \
  }

#if !_DEBUG
TEST_F(AnalyticalSeriesTest, CompactRepresentation) {
  SolarSystem<ICRS> solar_system_at_j2000(
      SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt",
      SOLUTION_DIR / "astronomy" /
          "sol_initial_state_jd_2451545_000000000.proto.txt");

  // NOTE(phl): Keep these parameters aligned with
  // sol_numerics_blueprint.proto.txt.
  auto const ephemeris = solar_system_at_j2000.MakeEphemeris(
      /*accuracy_parameters=*/{/*fitting_tolerance=*/1 * Milli(Metre),
                               /*geopotential_tolerance=*/0x1p-24},
      Ephemeris<ICRS>::FixedStepParameters(
          SymmetricLinearMultistepIntegrator<QuinlanTremaine1990Order12,
                                             Position<ICRS>>(),
          /*step=*/10 * Minute));
  ephemeris->Prolong(solar_system_at_j2000.epoch() + 0.25 * JulianYear);

  for (auto const& celestial : {"Io", "Moon", "Phobos"}) {
    LOG(INFO) << "---------- " << celestial;
    auto const& celestial_trajectory =
        solar_system_at_j2000.trajectory(*ephemeris, celestial);
    int const celestial_piecewise_poisson_series_degree =
        celestial_trajectory.PiecewisePoissonSeriesDegree(
            celestial_trajectory.t_min(), celestial_trajectory.t_max());
    std::unique_ptr<PoissonSeries<Displacement<ICRS>,
                                  std::max(aperiodic_approximation_degree,
                                           periodic_approximation_degree),
                                  EstrinEvaluator>>
        celestial_approximation;

    switch (celestial_piecewise_poisson_series_degree) {
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          3, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          4, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          5, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          6, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          7, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          8, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          9, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          10, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          11, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          12, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          13, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          14, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          15, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          16, celestial_approximation, celestial_trajectory);
      PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE(
          17, celestial_approximation, celestial_trajectory);
      default:
        LOG(FATAL) << "Unexpected degree "
                   << celestial_piecewise_poisson_series_degree;
    };

    logger_.Set(absl::StrCat("approximation", celestial),
                *celestial_approximation,
                mathematica::ExpressIn(Metre, Second, Radian));
  }
}
#endif

#undef PRINCIPIA_COMPUTE_COMPACT_REPRESENTATION_CASE

}  // namespace physics
}  // namespace principia
<|endoftext|>


<commit_before>// Convert folder with binary data to cpp data

#include <stdio.h>
#include <string>
#include <algorithm>
#include <direct.h>
#include <vector>
#include <limits.h>
#include <stdlib.h>

#include <assert.h>

#include "tinydir.h"

void ReplaceAll(std::string& str, const std::string& from, const std::string& to)
{
	if (from.empty())
		return;
	size_t start_pos = 0;
	while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
		str.replace(start_pos, from.length(), to);
		start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
	}
}

std::vector<std::string> split(const std::string& s, char seperator)
{
	std::vector<std::string> output;
	std::string::size_type prev_pos = 0, pos = 0;

	while ((pos = s.find(seperator, pos)) != std::string::npos)
	{
		std::string substring(s.substr(prev_pos, pos - prev_pos));
		output.push_back(substring);
		prev_pos = ++pos;
	}

	output.push_back(s.substr(prev_pos, pos - prev_pos)); // Last word
	return output;
}

void PrintRow(FILE* dst, const unsigned char* buf, unsigned count)
{
	fprintf(dst, "\n    ");
	while (count > 1)
	{
		fprintf(dst, "0x%02X,", *buf);
		++buf;
		--count;
	}
	if (count > 0)
		fprintf(dst, "0x%02X", *buf);
}

void ExportFile(const char* pName, const char* pInputFilename, const char* pOutputFilename, const char* pRelativePath)
{
	FILE* pOriginFile = fopen(pInputFilename, "rb");

	assert(NULL != pOriginFile);

	//TODO read all pOriginFile and compress it
	unsigned int iOriginSize;
	fseek(pOriginFile, 0, SEEK_END);
	iOriginSize = (unsigned int)ftell(pOriginFile);
	fseek(pOriginFile, 0, SEEK_SET);
	char* pData = (char*)malloc(iOriginSize);
	fread(pData, 1, iOriginSize, pOriginFile);

	fclose(pOriginFile);

	if (iOriginSize == 0)
	{
		free(pData);
		return;
	}

	std::string sHeaderFilename = pOutputFilename + std::string(".h");
	std::string sSourceFilename = pOutputFilename + std::string(".cpp");
	ReplaceAll(sHeaderFilename, "/", "\\");
	ReplaceAll(sSourceFilename, "/", "\\");
	FILE* pHeaderFile = fopen(sHeaderFilename.c_str(), "w+");
	FILE* pSourceFile = fopen(sSourceFilename.c_str(), "w+");

	assert(NULL != pHeaderFile);
	assert(NULL != pSourceFile);

	std::string sRelativePath = "Resources";
	if (NULL != pRelativePath)
	{
		sRelativePath += "/";
		sRelativePath += pRelativePath;
	}
	std::vector<std::string> oNamespaces = split(sRelativePath, '/');

	int iIndent = oNamespaces.size();
	std::string sIndent(iIndent, '\t');
	std::string sIndentP(iIndent + 1, '\t');
	std::string sIndentPP(iIndent + 2, '\t');

	std::string sName = pName;
	ReplaceAll(sName, ".", "_");
	ReplaceAll(sName, " ", "_");

	std::string sDefine = "__RESOURCES_";
	if (NULL != pRelativePath)
	{
		sDefine += pRelativePath;
		sDefine += "_";
	}
	sDefine += sName;
	sDefine += "_H__";
	std::transform(sDefine.begin(), sDefine.end(), sDefine.begin(), ::toupper);
	ReplaceAll(sDefine, ".", "_");
	ReplaceAll(sDefine, " ", "_");
	ReplaceAll(sDefine, "/", "_");

	fprintf(pHeaderFile, "#ifndef %s\n", sDefine.c_str());
	fprintf(pHeaderFile, "#define %s\n\n", sDefine.c_str());

	fprintf(pSourceFile, "#include \"%s.h\"\n", sName.c_str());

	for (int iNamespace = 0; iNamespace < oNamespaces.size(); ++iNamespace)
	{
		std::string sNamespace = oNamespaces[iNamespace];
		ReplaceAll(sDefine, ".", "_");
		ReplaceAll(sDefine, " ", "_");
		std::string sNamespaceIndent(iNamespace, '\t');
		fprintf(pHeaderFile, "%snamespace %s \n%s{\n", sNamespaceIndent.c_str(), sNamespace.c_str(), sNamespaceIndent.c_str());
		fprintf(pSourceFile, "%snamespace %s \n%s{\n", sNamespaceIndent.c_str(), sNamespace.c_str(), sNamespaceIndent.c_str());
	}

	fprintf(pHeaderFile, "%snamespace %s \n%s{\n", sIndent.c_str(), sName.c_str(), sIndent.c_str());
	fprintf(pSourceFile, "%snamespace %s \n%s{\n", sIndent.c_str(), sName.c_str(), sIndent.c_str());

	fprintf(pHeaderFile, "%s extern const unsigned int Size;\n", sIndentP.c_str());
	fprintf(pHeaderFile, "%s extern const char Data[];\n", sIndentP.c_str());

	fprintf(pSourceFile, "%sconst unsigned int Size = %d;\n", sIndentP.c_str(), iOriginSize);
	fprintf(pSourceFile, "%sconst char Data[] = {", sIndentP.c_str());

	for (int iPos = 0; iPos < iOriginSize; ++iPos)
	{
		if (iPos % 16 == 0)
		{
			fprintf(pSourceFile, "\n%s", sIndentPP.c_str());
		}
		fprintf(pSourceFile, "0x%02X,", *(pData+iPos));
	}

	fprintf(pSourceFile, "\n%s};\n", sIndentP.c_str());

	//Closing namespaces
	fprintf(pHeaderFile, "%s}\n", sIndent.c_str());
	fprintf(pSourceFile, "%s}\n", sIndent.c_str());

	for (int iNamespace = oNamespaces.size()-1; iNamespace >= 0; --iNamespace)
	{
		std::string sNamespaceIndent(iNamespace, '\t');
		fprintf(pHeaderFile, "%s}\n", sNamespaceIndent.c_str());
		fprintf(pSourceFile, "%s}\n", sNamespaceIndent.c_str());
	}

	fprintf(pHeaderFile, "#endif // %s", sDefine.c_str());

	fclose(pHeaderFile);
	fclose(pSourceFile);

	free(pData);
}

void ScanFolder(const char* pInputFolder, const char* pOutputFolderBase, const char* pOutputRelative)
{
	std::string sFolder = pOutputFolderBase;
	if (NULL != pOutputRelative)
	{
		sFolder += "/";
		sFolder += pOutputRelative;
	}

	mkdir(sFolder.c_str());
	tinydir_dir dir;
	tinydir_open(&dir, pInputFolder);

	while (dir.has_next)
	{
		tinydir_file file;
		tinydir_readfile(&dir, &file);

		if (file.is_dir)
		{
			if (file.name != std::string(".") && file.name != std::string(".."))
			{
				std::string sOutRelative = "";
				if (NULL != pOutputRelative)
				{
					sOutRelative += pOutputRelative;
					sOutRelative += "/";
				}
				sOutRelative += file.name;
				ScanFolder(file.path, pOutputFolderBase, sOutRelative.c_str());
			}
		}
		else
		{
			std::string sOutPath = pOutputFolderBase;
			if (NULL != pOutputRelative)
			{
				sOutPath += "/";
				sOutPath += pOutputRelative;
			}
			sOutPath += "/";
			std::string sName = file.name;
			ReplaceAll(sName, ".", "_");
			ReplaceAll(sName, " ", "_");
			sOutPath += sName;

			ExportFile(file.name, file.path, sOutPath.c_str(), pOutputRelative);
		}

		tinydir_next(&dir);
	}

	tinydir_close(&dir);
}

void main(int argn, char** argv)
{
	if (argn == 3)
	{
		ScanFolder(argv[1], argv[2], NULL);
	}
	else
	{
		printf("Usage: ResourceEmbedder <input resource folder> <output cpp folder>\n");
	}
}<commit_msg>Fix bad hexa<commit_after>// Convert folder with binary data to cpp data

#include <stdio.h>
#include <string>
#include <algorithm>
#include <direct.h>
#include <vector>
#include <limits.h>
#include <stdlib.h>

#include <assert.h>

#include "tinydir.h"

void ReplaceAll(std::string& str, const std::string& from, const std::string& to)
{
	if (from.empty())
		return;
	size_t start_pos = 0;
	while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
		str.replace(start_pos, from.length(), to);
		start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
	}
}

std::vector<std::string> split(const std::string& s, char seperator)
{
	std::vector<std::string> output;
	std::string::size_type prev_pos = 0, pos = 0;

	while ((pos = s.find(seperator, pos)) != std::string::npos)
	{
		std::string substring(s.substr(prev_pos, pos - prev_pos));
		output.push_back(substring);
		prev_pos = ++pos;
	}

	output.push_back(s.substr(prev_pos, pos - prev_pos)); // Last word
	return output;
}

void PrintRow(FILE* dst, const unsigned char* buf, unsigned count)
{
	fprintf(dst, "\n    ");
	while (count > 1)
	{
		fprintf(dst, "0x%02X,", *buf);
		++buf;
		--count;
	}
	if (count > 0)
		fprintf(dst, "0x%02X", *buf);
}

void ExportFile(const char* pName, const char* pInputFilename, const char* pOutputFilename, const char* pRelativePath)
{
	FILE* pOriginFile = fopen(pInputFilename, "rb");

	assert(NULL != pOriginFile);

	//TODO read all pOriginFile and compress it
	unsigned int iOriginSize;
	fseek(pOriginFile, 0, SEEK_END);
	iOriginSize = (unsigned int)ftell(pOriginFile);
	fseek(pOriginFile, 0, SEEK_SET);
	char* pData = (char*)malloc(iOriginSize);
	fread(pData, 1, iOriginSize, pOriginFile);

	fclose(pOriginFile);

	if (iOriginSize == 0)
	{
		free(pData);
		return;
	}

	std::string sHeaderFilename = pOutputFilename + std::string(".h");
	std::string sSourceFilename = pOutputFilename + std::string(".cpp");
	ReplaceAll(sHeaderFilename, "/", "\\");
	ReplaceAll(sSourceFilename, "/", "\\");
	FILE* pHeaderFile = fopen(sHeaderFilename.c_str(), "w+");
	FILE* pSourceFile = fopen(sSourceFilename.c_str(), "w+");

	assert(NULL != pHeaderFile);
	assert(NULL != pSourceFile);

	std::string sRelativePath = "Resources";
	if (NULL != pRelativePath)
	{
		sRelativePath += "/";
		sRelativePath += pRelativePath;
	}
	std::vector<std::string> oNamespaces = split(sRelativePath, '/');

	int iIndent = oNamespaces.size();
	std::string sIndent(iIndent, '\t');
	std::string sIndentP(iIndent + 1, '\t');
	std::string sIndentPP(iIndent + 2, '\t');

	std::string sName = pName;
	ReplaceAll(sName, ".", "_");
	ReplaceAll(sName, " ", "_");

	std::string sDefine = "__RESOURCES_";
	if (NULL != pRelativePath)
	{
		sDefine += pRelativePath;
		sDefine += "_";
	}
	sDefine += sName;
	sDefine += "_H__";
	std::transform(sDefine.begin(), sDefine.end(), sDefine.begin(), ::toupper);
	ReplaceAll(sDefine, ".", "_");
	ReplaceAll(sDefine, " ", "_");
	ReplaceAll(sDefine, "/", "_");

	fprintf(pHeaderFile, "#ifndef %s\n", sDefine.c_str());
	fprintf(pHeaderFile, "#define %s\n\n", sDefine.c_str());

	fprintf(pSourceFile, "#include \"%s.h\"\n", sName.c_str());

	for (int iNamespace = 0; iNamespace < oNamespaces.size(); ++iNamespace)
	{
		std::string sNamespace = oNamespaces[iNamespace];
		ReplaceAll(sDefine, ".", "_");
		ReplaceAll(sDefine, " ", "_");
		std::string sNamespaceIndent(iNamespace, '\t');
		fprintf(pHeaderFile, "%snamespace %s \n%s{\n", sNamespaceIndent.c_str(), sNamespace.c_str(), sNamespaceIndent.c_str());
		fprintf(pSourceFile, "%snamespace %s \n%s{\n", sNamespaceIndent.c_str(), sNamespace.c_str(), sNamespaceIndent.c_str());
	}

	fprintf(pHeaderFile, "%snamespace %s \n%s{\n", sIndent.c_str(), sName.c_str(), sIndent.c_str());
	fprintf(pSourceFile, "%snamespace %s \n%s{\n", sIndent.c_str(), sName.c_str(), sIndent.c_str());

	fprintf(pHeaderFile, "%s extern const unsigned int Size;\n", sIndentP.c_str());
	fprintf(pHeaderFile, "%s extern const char Data[];\n", sIndentP.c_str());

	fprintf(pSourceFile, "%sconst unsigned int Size = %d;\n", sIndentP.c_str(), iOriginSize);
	fprintf(pSourceFile, "%sconst char Data[] = {", sIndentP.c_str());

	for (int iPos = 0; iPos < iOriginSize; ++iPos)
	{
		if (iPos % 16 == 0)
		{
			fprintf(pSourceFile, "\n%s", sIndentPP.c_str());
		}
		fprintf(pSourceFile, "0x%02X,", (unsigned char)*(pData + iPos));
	}

	fprintf(pSourceFile, "\n%s};\n", sIndentP.c_str());

	//Closing namespaces
	fprintf(pHeaderFile, "%s}\n", sIndent.c_str());
	fprintf(pSourceFile, "%s}\n", sIndent.c_str());

	for (int iNamespace = oNamespaces.size()-1; iNamespace >= 0; --iNamespace)
	{
		std::string sNamespaceIndent(iNamespace, '\t');
		fprintf(pHeaderFile, "%s}\n", sNamespaceIndent.c_str());
		fprintf(pSourceFile, "%s}\n", sNamespaceIndent.c_str());
	}

	fprintf(pHeaderFile, "#endif // %s", sDefine.c_str());

	fclose(pHeaderFile);
	fclose(pSourceFile);

	free(pData);
}

void ScanFolder(const char* pInputFolder, const char* pOutputFolderBase, const char* pOutputRelative)
{
	std::string sFolder = pOutputFolderBase;
	if (NULL != pOutputRelative)
	{
		sFolder += "/";
		sFolder += pOutputRelative;
	}

	mkdir(sFolder.c_str());
	tinydir_dir dir;
	tinydir_open(&dir, pInputFolder);

	while (dir.has_next)
	{
		tinydir_file file;
		tinydir_readfile(&dir, &file);

		if (file.is_dir)
		{
			if (file.name != std::string(".") && file.name != std::string(".."))
			{
				std::string sOutRelative = "";
				if (NULL != pOutputRelative)
				{
					sOutRelative += pOutputRelative;
					sOutRelative += "/";
				}
				sOutRelative += file.name;
				ScanFolder(file.path, pOutputFolderBase, sOutRelative.c_str());
			}
		}
		else
		{
			std::string sOutPath = pOutputFolderBase;
			if (NULL != pOutputRelative)
			{
				sOutPath += "/";
				sOutPath += pOutputRelative;
			}
			sOutPath += "/";
			std::string sName = file.name;
			ReplaceAll(sName, ".", "_");
			ReplaceAll(sName, " ", "_");
			sOutPath += sName;

			ExportFile(file.name, file.path, sOutPath.c_str(), pOutputRelative);
		}

		tinydir_next(&dir);
	}

	tinydir_close(&dir);
}

void main(int argn, char** argv)
{
	if (argn == 3)
	{
		ScanFolder(argv[1], argv[2], NULL);
	}
	else
	{
		printf("Usage: ResourceEmbedder <input resource folder> <output cpp folder>\n");
	}
}<|endoftext|>


<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.

#ifndef MFEM_VTK
#define MFEM_VTK

#include "../fem/geom.hpp"

namespace mfem
{

// Helpers for writing to the VTK format

enum class VTKFormat
{
   ASCII,
   BINARY,
   BINARY32
};

/// Create the VTK element connectivity array for a given element geometry and
/// refinement level. Converts node numbers from MFEM to VTK ordering.
void CreateVTKElementConnectivity(Array<int> &con, Geometry::Type geom, int ref);

/// Outputs encoded binary data in the format needed by VTK. The binary data
/// will be base 64 encoded, and compressed if @a compression_level is not
/// zero. The proper header will be prepended to the data.
void WriteVTKEncodedCompressed(std::ostream &out, const void *bytes,
                               uint32_t nbytes, int compression_level);

} // namespace mfem

#endif<commit_msg>Formatting<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.

#ifndef MFEM_VTK
#define MFEM_VTK

#include "../fem/geom.hpp"

namespace mfem
{

// Helpers for writing to the VTK format

enum class VTKFormat
{
   ASCII,
   BINARY,
   BINARY32
};

/// Create the VTK element connectivity array for a given element geometry and
/// refinement level. Converts node numbers from MFEM to VTK ordering.
void CreateVTKElementConnectivity(Array<int> &con, Geometry::Type geom,
                                  int ref);

/// Outputs encoded binary data in the format needed by VTK. The binary data
/// will be base 64 encoded, and compressed if @a compression_level is not
/// zero. The proper header will be prepended to the data.
void WriteVTKEncodedCompressed(std::ostream &out, const void *bytes,
                               uint32_t nbytes, int compression_level);

} // namespace mfem

#endif<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: 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 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file main.cpp
 * @author Yann yann@ethdev.com
 * @date 2014
 * Ethereum IDE client.
 */

#include <iostream>
#include <stdlib.h>
#include "MixApplication.h"
#include "Exceptions.h"
using namespace dev::mix;

int main(int _argc, char* _argv[])
{
#ifdef ETH_HAVE_WEBENGINE
	Q_INIT_RESOURCE(js);
#endif
#if __linux
	//work around ubuntu appmenu-qt5 bug
	//https://bugs.launchpad.net/ubuntu/+source/appmenu-qt5/+bug/1323853
	putenv((char*)"QT_QPA_PLATFORMTHEME=");
	putenv((char*)"QSG_RENDER_LOOP=threaded");
#endif
#ifdef _WIN32
	putenv((char*)"OPENSSL_CONF=c:\\");
#endif
#ifdef _WIN64
	putenv((char*)"OPENSSL_CONF=c:\\");
#endif
	try
	{
		MixApplication app(_argc, _argv);
		return app.exec();
	}
	catch (boost::exception const& _e)
	{
		std::cerr << boost::diagnostic_information(_e);
	}
	catch (std::exception const& _e)
	{
		std::cerr << _e.what();
	}
}
<commit_msg>Change WIN32 (WIN64) test.<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: 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 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file main.cpp
 * @author Yann yann@ethdev.com
 * @date 2014
 * Ethereum IDE client.
 */

#include <iostream>
#include <stdlib.h>
#include "MixApplication.h"
#include "Exceptions.h"
using namespace dev::mix;

int main(int _argc, char* _argv[])
{
#ifdef ETH_HAVE_WEBENGINE
	Q_INIT_RESOURCE(js);
#endif
#if __linux
	//work around ubuntu appmenu-qt5 bug
	//https://bugs.launchpad.net/ubuntu/+source/appmenu-qt5/+bug/1323853
	putenv((char*)"QT_QPA_PLATFORMTHEME=");
	putenv((char*)"QSG_RENDER_LOOP=threaded");
#endif
#if (defined(_WIN32) || defined(_WIN64))
	if (!getenv("OPENSSL_CONF"))
		putenv((char*)"OPENSSL_CONF=c:\\");
#endif
	try
	{
		MixApplication app(_argc, _argv);
		return app.exec();
	}
	catch (boost::exception const& _e)
	{
		std::cerr << boost::diagnostic_information(_e);
	}
	catch (std::exception const& _e)
	{
		std::cerr << _e.what();
	}
}
<|endoftext|>


<commit_before>/*
 -----------------------------------------------------------------------------
 This source file is part of OGRE
 (Object-oriented Graphics Rendering Engine)
 For the latest info, see http://www.ogre3d.org/

 Copyright (c) 2000-2009 Torus Knot Software Ltd

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 -----------------------------------------------------------------------------
 */
#include "OgrePlatform.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_SYMBIAN
#include <coecntrl.h>
#endif

#include "SampleBrowser.h"

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_IPHONE
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

// To use CADisplayLink for smoother animation on iPhone comment out
// the following line or define it to 1.  Use with caution, it can
// sometimes cause input lag.
#define USE_CADISPLAYLINK 1
#endif

#if OGRE_PLATFORM != OGRE_PLATFORM_SYMBIAN

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT)
#else
int main(int argc, char *argv[])
#endif
{
#if OGRE_PLATFORM == OGRE_PLATFORM_IPHONE
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	int retVal = UIApplicationMain(argc, argv, @"UIApplication", @"AppDelegate");
	[pool release];
	return retVal;
#else

	try
	{
		OgreBites::SampleBrowser sb;
		sb.go();
	}
	catch (Ogre::Exception& e)
	{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
		MessageBoxA(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_ICONERROR | MB_TASKMODAL);
#else
		std::cerr << "An exception has occurred: " << e.getFullDescription().c_str() << std::endl;
#endif
	}

#endif
	return 0;
}

#endif // OGRE_PLATFORM != OGRE_PLATFORM_SYMBIAN

#if OGRE_PLATFORM == OGRE_PLATFORM_IPHONE
#   ifdef __OBJC__
@interface AppDelegate : NSObject <UIApplicationDelegate>
{
    NSTimer *mTimer;
    OgreBites::SampleBrowser sb;

    // Use of the CADisplayLink class is the preferred method for controlling your animation timing.
    // CADisplayLink will link to the main display and fire every vsync when added to a given run-loop.
    // The NSTimer class is used only as fallback when running on a pre 3.1 device where CADisplayLink
    // isn't available.
    id mDisplayLink;
    NSDate* mDate;
    NSTimeInterval mLastFrameTime;
    BOOL mDisplayLinkSupported;
}

- (void)go;
- (void)renderOneFrame:(id)sender;

@property (retain) NSTimer *mTimer;
@property (nonatomic) NSTimeInterval mLastFrameTime;

@end

@implementation AppDelegate

@synthesize mTimer;
@dynamic mLastFrameTime;

- (NSTimeInterval)mLastFrameTime
{
    return mLastFrameTime;
}

- (void)setLastFrameTime:(NSTimeInterval)frameInterval
{
    // Frame interval defines how many display frames must pass between each time the
    // display link fires. The display link will only fire 30 times a second when the
    // frame internal is two on a display that refreshes 60 times a second. The default
    // frame interval setting of one will fire 60 times a second when the display refreshes
    // at 60 times a second. A frame interval setting of less than one results in undefined
    // behavior.
    if (frameInterval >= 1)
    {
        mLastFrameTime = frameInterval;
    }
}

- (void)go {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    try {
        sb.initApp();

        mTimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)(1.0f / 60.0f)
                                                  target:self
                                                selector:@selector(renderOneFrame:)
                                                userInfo:nil
                                                 repeats:YES];
    } catch( Ogre::Exception& e ) {
        std::cerr << "An exception has occurred: " <<
        e.getFullDescription().c_str() << std::endl;
    }

    if (mDisplayLinkSupported)
    {
        // CADisplayLink is API new to iPhone SDK 3.1. Compiling against earlier versions will result in a warning, but can be dismissed
        // if the system version runtime check for CADisplayLink exists in -initWithCoder:. The runtime check ensures this code will
        // not be called in system versions earlier than 3.1.
        mDate = [[NSDate alloc] init];
        mLastFrameTime = -[mDate timeIntervalSinceNow];

        mDisplayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(renderOneFrame:)];
        [mDisplayLink setFrameInterval:mLastFrameTime];
        [mDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    }
    else
    {
        mTimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)(1.0f / 60.0f) * mLastFrameTime
                                                  target:self
                                                selector:@selector(renderOneFrame:)
                                                userInfo:nil
                                                 repeats:YES];
    }

    [pool release];
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    // Hide the status bar
    [[UIApplication sharedApplication] setStatusBarHidden:YES];

    mDisplayLinkSupported = FALSE;
    mLastFrameTime = 1;
    mDisplayLink = nil;
    mTimer = nil;

    // A system version of 3.1 or greater is required to use CADisplayLink. The NSTimer
    // class is used as fallback when it isn't available.
#if USE_CADISPLAYLINK
    NSString *reqSysVer = @"3.1";
    NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
    if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
        mDisplayLinkSupported = TRUE;
#endif

    [self go];
}

- (void)renderOneFrame:(id)sender
{
    [sb.mGestureView becomeFirstResponder];

    if (mDisplayLinkSupported)
    {
        // NSTimerInterval is a simple typedef for double
        NSTimeInterval currentFrameTime = -[mDate timeIntervalSinceNow];
        NSTimeInterval differenceInSeconds = currentFrameTime - mLastFrameTime;
        mLastFrameTime = currentFrameTime;

        Root::getSingleton().renderOneFrame((Real)differenceInSeconds);
    }
    else
    {
        Root::getSingleton().renderOneFrame((Real)[mTimer timeInterval]);
    }
}

- (void)applicationWillTerminate:(UIApplication *)application {
    sb.closeApp();
}

- (void)dealloc {
    if (mDisplayLinkSupported)
    {
        [mDate release];
        mDate = nil;

        [mDisplayLink invalidate];
        mDisplayLink = nil;
    }
    else
    {
        [mTimer invalidate];
        mTimer = nil;
    }

    [super dealloc];
}

@end
#   endif

#endif
<commit_msg>iOS: Remove an extra timer init in the sample browser<commit_after>/*
 -----------------------------------------------------------------------------
 This source file is part of OGRE
 (Object-oriented Graphics Rendering Engine)
 For the latest info, see http://www.ogre3d.org/

 Copyright (c) 2000-2009 Torus Knot Software Ltd

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 -----------------------------------------------------------------------------
 */
#include "OgrePlatform.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_SYMBIAN
#include <coecntrl.h>
#endif

#include "SampleBrowser.h"

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_IPHONE
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

// To use CADisplayLink for smoother animation on iPhone comment out
// the following line or define it to 1.  Use with caution, it can
// sometimes cause input lag.
#define USE_CADISPLAYLINK 1
#endif

#if OGRE_PLATFORM != OGRE_PLATFORM_SYMBIAN

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT)
#else
int main(int argc, char *argv[])
#endif
{
#if OGRE_PLATFORM == OGRE_PLATFORM_IPHONE
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	int retVal = UIApplicationMain(argc, argv, @"UIApplication", @"AppDelegate");
	[pool release];
	return retVal;
#else

	try
	{
		OgreBites::SampleBrowser sb;
		sb.go();
	}
	catch (Ogre::Exception& e)
	{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
		MessageBoxA(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_ICONERROR | MB_TASKMODAL);
#else
		std::cerr << "An exception has occurred: " << e.getFullDescription().c_str() << std::endl;
#endif
	}

#endif
	return 0;
}

#endif // OGRE_PLATFORM != OGRE_PLATFORM_SYMBIAN

#if OGRE_PLATFORM == OGRE_PLATFORM_IPHONE
#   ifdef __OBJC__
@interface AppDelegate : NSObject <UIApplicationDelegate>
{
    NSTimer *mTimer;
    OgreBites::SampleBrowser sb;

    // Use of the CADisplayLink class is the preferred method for controlling your animation timing.
    // CADisplayLink will link to the main display and fire every vsync when added to a given run-loop.
    // The NSTimer class is used only as fallback when running on a pre 3.1 device where CADisplayLink
    // isn't available.
    id mDisplayLink;
    NSDate* mDate;
    NSTimeInterval mLastFrameTime;
    BOOL mDisplayLinkSupported;
}

- (void)go;
- (void)renderOneFrame:(id)sender;

@property (retain) NSTimer *mTimer;
@property (nonatomic) NSTimeInterval mLastFrameTime;

@end

@implementation AppDelegate

@synthesize mTimer;
@dynamic mLastFrameTime;

- (NSTimeInterval)mLastFrameTime
{
    return mLastFrameTime;
}

- (void)setLastFrameTime:(NSTimeInterval)frameInterval
{
    // Frame interval defines how many display frames must pass between each time the
    // display link fires. The display link will only fire 30 times a second when the
    // frame internal is two on a display that refreshes 60 times a second. The default
    // frame interval setting of one will fire 60 times a second when the display refreshes
    // at 60 times a second. A frame interval setting of less than one results in undefined
    // behavior.
    if (frameInterval >= 1)
    {
        mLastFrameTime = frameInterval;
    }
}

- (void)go {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    try {
        sb.initApp();
    } catch( Ogre::Exception& e ) {
        std::cerr << "An exception has occurred: " <<
        e.getFullDescription().c_str() << std::endl;
    }

    if (mDisplayLinkSupported)
    {
        // CADisplayLink is API new to iPhone SDK 3.1. Compiling against earlier versions will result in a warning, but can be dismissed
        // if the system version runtime check for CADisplayLink exists in -initWithCoder:. The runtime check ensures this code will
        // not be called in system versions earlier than 3.1.
        mDate = [[NSDate alloc] init];
        mLastFrameTime = -[mDate timeIntervalSinceNow];

        mDisplayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(renderOneFrame:)];
        [mDisplayLink setFrameInterval:(1.0f/60.0f)];
        [mDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    }
    else
    {
        mTimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)(1.0f / 60.0f) * mLastFrameTime
                                                  target:self
                                                selector:@selector(renderOneFrame:)
                                                userInfo:nil
                                                 repeats:YES];
    }

    [pool release];
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    // Hide the status bar
    [[UIApplication sharedApplication] setStatusBarHidden:YES];

    mDisplayLinkSupported = NO;
    mLastFrameTime = 1;
    mDisplayLink = nil;
    mTimer = nil;

    // A system version of 3.1 or greater is required to use CADisplayLink. The NSTimer
    // class is used as fallback when it isn't available.
#if USE_CADISPLAYLINK
    NSString *reqSysVer = @"3.1";
    NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
    if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
        mDisplayLinkSupported = YES;
#endif

    [self go];
}

- (void)renderOneFrame:(id)sender
{
    [sb.mGestureView becomeFirstResponder];

    if (mDisplayLinkSupported)
    {
        // NSTimerInterval is a simple typedef for double
        NSTimeInterval currentFrameTime = -[mDate timeIntervalSinceNow];
        NSTimeInterval differenceInSeconds = currentFrameTime - mLastFrameTime;
        mLastFrameTime = currentFrameTime;

        Root::getSingleton().renderOneFrame((Real)differenceInSeconds);
    }
    else
    {
        Root::getSingleton().renderOneFrame((Real)[mTimer timeInterval]);
    }
}

- (void)applicationWillTerminate:(UIApplication *)application {
    sb.closeApp();
}

- (void)dealloc {
    if (mDisplayLinkSupported)
    {
        [mDate release];
        mDate = nil;

        [mDisplayLink invalidate];
        mDisplayLink = nil;
    }
    else
    {
        [mTimer invalidate];
        mTimer = nil;
    }

    [super dealloc];
}

@end
#   endif

#endif
<|endoftext|>