<commit_before>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CProgressBar.cpp,v $
//   $Revision: 1.41 $
//   $Name:  $
//   $Author: bergmann $
//   $Date: 2012/03/28 09:46:45 $
// End CVS Header

// Copyright (C) 2012 - 2010 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include <qapplication.h>
#include <qlayout.h>
#include <qwaitcondition.h>

#include <QCloseEvent>
#include <QMutex>
#include <QMutexLocker>
#include <QThread>

#include "copasi.h"
#include "qtUtilities.h"
#include "utilities/CVector.h"
#include "CProgressBar.h"
#include "DataModelGUI.h"
#include "CQProgressItemText.h"
#include "CQProgressItemBar.h"
#include "CQMessageBox.h"
#include "copasiui3window.h"

#undef min
#undef max

extern QApplication *pApp;

// static
CProgressBar * CProgressBar::create(QWidget* parent, const char* name,
                                    bool modal, Qt::WFlags fl)
{
  if (CopasiUI3Window::getMainWindow()->getMainThread() != QThread::currentThread())
    {
      return NULL;
    }
  else
    {
      return new CProgressBar(parent, name, modal, fl);
    }
}

CProgressBar::CProgressBar(QWidget* parent, const char* name,
                           bool modal, Qt::WFlags fl):
    CQProgressDialog(parent, name, modal, fl | Qt::WindowMinimizeButtonHint),
    CProcessReport(),
    mProgressItemList(1),
    mNextEventProcessing(QDateTime::currentDateTime()),
    mpMainWidget(NULL),
    mpMainThread(NULL)
{
  mProgressItemList[0] = NULL;

  // Whenever a progress bar is active we do not want any user
  // intervention.
  if ((mpMainWidget = CopasiUI3Window::getMainWindow()) != NULL)
    {
      mpMainThread = CopasiUI3Window::getMainWindow()->getMainThread();
      mpMainWidget->setEnabled(false);
      QCoreApplication::processEvents();
    }

  connect(this, SIGNAL(signalAddItem(const int)),
          this, SLOT(slotAddItem(const int)));

  connect(this, SIGNAL(signalSetName(QString)),
          this, SLOT(slotSetName(QString)));

  connect(this, SIGNAL(signalProgressAll()),
          this, SLOT(slotProgressAll()));

  connect(this, SIGNAL(signalFinishItem(const int)),
          this, SLOT(slotFinishItem(const int)));
}

CProgressBar::~CProgressBar()
{
  finish();

  size_t i, imax = mProgressItemList.size();

  for (i = 0; i < imax; i++)
    pdelete(mProgressItemList[i]);
}

size_t CProgressBar::addItem(const std::string & name,
                             const CCopasiParameter::Type & type,
                             const void * pValue,
                             const void * pEndValue)

{
  size_t hItem = CProcessReport::addItem(name, type, pValue, pEndValue);

  if (mpMainThread != NULL &&
      QThread::currentThread() != mpMainThread)
    {
      QMutexLocker Locker(&mMutex);
      mSlotFinished = false;

      emit signalAddItem((int) hItem);

      if (!mSlotFinished)
        {
          mWaitSlot.wait(&mMutex);
        }
    }
  else
    {
      slotAddItem((int) hItem);
      QCoreApplication::processEvents();
    }

  return hItem;
}

void CProgressBar::slotAddItem(const int handle)
{
  size_t Handle = (size_t) handle;

  if (Handle == C_INVALID_INDEX) return;

  QMutexLocker Locker(&mMutex);

  if (Handle >= mProgressItemList.size()) // we need to resize
    {
      size_t i, imax = mProgressItemList.size();

      mProgressItemList.resize(2 * imax, true); // Note, imax is never zero

      i = imax;
      imax *= 2;

      while (i < imax) mProgressItemList[i++] = NULL;
    }

  if (mProcessReportItemList[Handle]->hasEndValue())
    mProgressItemList[Handle] = new CQProgressItemBar(static_cast<CQProgressDialog *>(this));
  else
    mProgressItemList[Handle] = new CQProgressItemText(static_cast<CQProgressDialog *>(this));

  mProgressItemList[Handle]->initFromProcessReportItem(mProcessReportItemList[Handle]);
  insertProgressItem(mProgressItemList[Handle]);

  mSlotFinished = true;
  mWaitSlot.wakeAll();
}

bool CProgressBar::resetItem(const size_t & handle)
{
  if (!isValidHandle(handle) || mProgressItemList[handle] == NULL) return false;

  return (mProgressItemList[handle]->reset() && mProceed);
}

bool CProgressBar::progressItem(const size_t & handle)
{
  if (!isValidHandle(handle) || mProgressItemList[handle] == NULL) return false;

  QDateTime currDateTime = QDateTime::currentDateTime();

  if (mNextEventProcessing >= currDateTime)
    return mProceed;

  mNextEventProcessing = currDateTime.addSecs(1);

  if (mPause)
    {
      mWaitPause.wait(&mMutex);
    }

  if (mpMainThread != NULL &&
      QThread::currentThread() != mpMainThread)
    {
      if (mSlotFinished)
        {
          mSlotFinished = false;

          emit signalProgressAll();
        }
    }
  else
    {
      slotProgressAll();
      QCoreApplication::processEvents();
    }

  return mProceed;
}

void CProgressBar::slotProgressAll()
{
  size_t hItem, hmax = mProgressItemList.size();

  QMutexLocker Locker(&mMutex);

  for (hItem = 0; hItem < hmax; hItem++)
    {
      if (mProgressItemList[hItem])
        mProceed &= mProgressItemList[hItem]->process();
    }

  mSlotFinished = true;
}

bool CProgressBar::finish()
{
  // Assure that all signals have been properly handled before we delete
  // the progress items
  if (mpMainThread == NULL ||
      QThread::currentThread() == mpMainThread)
    QCoreApplication::processEvents();

  // The method must only be called from the main thread!
  CQProgressItem ** ppIt = mProgressItemList.array();
  CQProgressItem ** ppEnd = ppIt + mProgressItemList.size();
  CProcessReportItem **ppItem = mProcessReportItemList.array();

  for (; ppIt != ppEnd; ++ppIt, ++ppItem)
    {
      if (*ppIt != NULL)
        {
          removeProgressItem(*ppIt);

          // We must make sure the CProcessReportItem is not deleted prior to the actual delete.
          // The destructor of CQProgressItem will take care of the deletion.
          *ppItem = NULL;

          (*ppIt)->deleteLater();
          (*ppIt) = NULL;
        }
    }

  // We need to activate the user interface again.
  if (mpMainWidget != NULL)
    {
      mpMainWidget->setEnabled(true);

      if (mpMainThread == NULL ||
          QThread::currentThread() == mpMainThread)
        QCoreApplication::processEvents();
    }

  CProcessReport::finish();
  done(1);

  return mProceed;
}

bool CProgressBar::finishItem(const size_t & handle)
{
  if (!isValidHandle(handle) || mProgressItemList[handle] == NULL) return false;

  if (mpMainThread != NULL &&
      QThread::currentThread() != mpMainThread)
    {
      QMutexLocker Locker(&mMutex);
      mSlotFinished = false;

      emit signalFinishItem((int) handle);

      if (!mSlotFinished)
        {
          mWaitSlot.wait(&mMutex);
        }
    }
  else
    {
      slotFinishItem((int) handle);
      QCoreApplication::processEvents();
    }

  return mProceed;
}

void CProgressBar::slotFinishItem(const int handle)
{
  size_t Handle = (size_t) handle;

  if (isValidHandle(Handle) &&
      mProgressItemList[Handle] != NULL)
    {
      QMutexLocker Locker(&mMutex);

      removeProgressItem(mProgressItemList[Handle]);

      // We must make sure the CProcessReportItem is not deleted prior to the actual delete.
      // The destructor of CQProgressItem will take care of the deletion.
      mProcessReportItemList[Handle] = NULL;

      mProgressItemList[Handle]->deleteLater();
      mProgressItemList[Handle] = NULL;
    }

  mSlotFinished = true;
  mWaitSlot.wakeAll();
}

bool CProgressBar::proceed()
{
  return mProceed;
}

// virtual
bool CProgressBar::setName(const std::string & name)
{
  if (mpMainThread != NULL &&
      QThread::currentThread() != mpMainThread)
    {
      QMutexLocker Locker(&mMutex);
      mSlotFinished = false;

      emit signalSetName(FROM_UTF8(name));

      if (!mSlotFinished)
        {
          mWaitSlot.wait(&mMutex);
        }
    }
  else
    {
      slotSetName(FROM_UTF8(name));
      QCoreApplication::processEvents();
    }

  return true;
}
void CProgressBar::slotSetName(QString name)
{
  QMutexLocker Locker(&mMutex);

  setWindowTitle(name);
  CProcessReport::setName(TO_UTF8(name));

  mSlotFinished = true;
  mWaitSlot.wakeAll();
}

void CProgressBar::closeEvent(QCloseEvent *e)
{
  CQMessageBox::information(this, "COPASI", "COPASI is currently executing tasks.\n"
                            "Please stop them first before closing COPASI.");

  e->ignore();
}

// virtual
void CProgressBar::btnStopPressed()
{
  CQProgressDialog::btnStopPressed();
  mWaitPause.wakeAll();
}

// virtual
void CProgressBar::btnContinuePressed()
{
  CQProgressDialog::btnContinuePressed();
  mWaitPause.wakeAll();
}
<commit_msg>Added locking of mutex when waiting during pause to avoid assertion violation in Qt.<commit_after>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CProgressBar.cpp,v $
//   $Revision: 1.42 $
//   $Name:  $
//   $Author: shoops $
//   $Date: 2012/04/16 15:25:48 $
// End CVS Header

// Copyright (C) 2012 - 2010 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include <qapplication.h>
#include <qlayout.h>
#include <qwaitcondition.h>

#include <QCloseEvent>
#include <QMutex>
#include <QMutexLocker>
#include <QThread>

#include "copasi.h"
#include "qtUtilities.h"
#include "utilities/CVector.h"
#include "CProgressBar.h"
#include "DataModelGUI.h"
#include "CQProgressItemText.h"
#include "CQProgressItemBar.h"
#include "CQMessageBox.h"
#include "copasiui3window.h"

#undef min
#undef max

extern QApplication *pApp;

// static
CProgressBar * CProgressBar::create(QWidget* parent, const char* name,
                                    bool modal, Qt::WFlags fl)
{
  if (CopasiUI3Window::getMainWindow()->getMainThread() != QThread::currentThread())
    {
      return NULL;
    }
  else
    {
      return new CProgressBar(parent, name, modal, fl);
    }
}

CProgressBar::CProgressBar(QWidget* parent, const char* name,
                           bool modal, Qt::WFlags fl):
    CQProgressDialog(parent, name, modal, fl | Qt::WindowMinimizeButtonHint),
    CProcessReport(),
    mProgressItemList(1),
    mNextEventProcessing(QDateTime::currentDateTime()),
    mpMainWidget(NULL),
    mpMainThread(NULL)
{
  mProgressItemList[0] = NULL;

  // Whenever a progress bar is active we do not want any user
  // intervention.
  if ((mpMainWidget = CopasiUI3Window::getMainWindow()) != NULL)
    {
      mpMainThread = CopasiUI3Window::getMainWindow()->getMainThread();
      mpMainWidget->setEnabled(false);
      QCoreApplication::processEvents();
    }

  connect(this, SIGNAL(signalAddItem(const int)),
          this, SLOT(slotAddItem(const int)));

  connect(this, SIGNAL(signalSetName(QString)),
          this, SLOT(slotSetName(QString)));

  connect(this, SIGNAL(signalProgressAll()),
          this, SLOT(slotProgressAll()));

  connect(this, SIGNAL(signalFinishItem(const int)),
          this, SLOT(slotFinishItem(const int)));
}

CProgressBar::~CProgressBar()
{
  finish();

  size_t i, imax = mProgressItemList.size();

  for (i = 0; i < imax; i++)
    pdelete(mProgressItemList[i]);
}

size_t CProgressBar::addItem(const std::string & name,
                             const CCopasiParameter::Type & type,
                             const void * pValue,
                             const void * pEndValue)

{
  size_t hItem = CProcessReport::addItem(name, type, pValue, pEndValue);

  if (mpMainThread != NULL &&
      QThread::currentThread() != mpMainThread)
    {
      QMutexLocker Locker(&mMutex);
      mSlotFinished = false;

      emit signalAddItem((int) hItem);

      if (!mSlotFinished)
        {
          mWaitSlot.wait(&mMutex);
        }
    }
  else
    {
      slotAddItem((int) hItem);
      QCoreApplication::processEvents();
    }

  return hItem;
}

void CProgressBar::slotAddItem(const int handle)
{
  size_t Handle = (size_t) handle;

  if (Handle == C_INVALID_INDEX) return;

  QMutexLocker Locker(&mMutex);

  if (Handle >= mProgressItemList.size()) // we need to resize
    {
      size_t i, imax = mProgressItemList.size();

      mProgressItemList.resize(2 * imax, true); // Note, imax is never zero

      i = imax;
      imax *= 2;

      while (i < imax) mProgressItemList[i++] = NULL;
    }

  if (mProcessReportItemList[Handle]->hasEndValue())
    mProgressItemList[Handle] = new CQProgressItemBar(static_cast<CQProgressDialog *>(this));
  else
    mProgressItemList[Handle] = new CQProgressItemText(static_cast<CQProgressDialog *>(this));

  mProgressItemList[Handle]->initFromProcessReportItem(mProcessReportItemList[Handle]);
  insertProgressItem(mProgressItemList[Handle]);

  mSlotFinished = true;
  mWaitSlot.wakeAll();
}

bool CProgressBar::resetItem(const size_t & handle)
{
  if (!isValidHandle(handle) || mProgressItemList[handle] == NULL) return false;

  return (mProgressItemList[handle]->reset() && mProceed);
}

bool CProgressBar::progressItem(const size_t & handle)
{
  if (!isValidHandle(handle) || mProgressItemList[handle] == NULL) return false;

  QDateTime currDateTime = QDateTime::currentDateTime();

  if (mNextEventProcessing >= currDateTime)
    return mProceed;

  mNextEventProcessing = currDateTime.addSecs(1);

  if (mPause)
    {
      QMutexLocker Locker(&mMutex);
      mWaitPause.wait(&mMutex);
    }

  if (mpMainThread != NULL &&
      QThread::currentThread() != mpMainThread)
    {
      if (mSlotFinished)
        {
          mSlotFinished = false;

          emit signalProgressAll();
        }
    }
  else
    {
      slotProgressAll();
      QCoreApplication::processEvents();
    }

  return mProceed;
}

void CProgressBar::slotProgressAll()
{
  size_t hItem, hmax = mProgressItemList.size();

  QMutexLocker Locker(&mMutex);

  for (hItem = 0; hItem < hmax; hItem++)
    {
      if (mProgressItemList[hItem])
        mProceed &= mProgressItemList[hItem]->process();
    }

  mSlotFinished = true;
}

bool CProgressBar::finish()
{
  // Assure that all signals have been properly handled before we delete
  // the progress items
  if (mpMainThread == NULL ||
      QThread::currentThread() == mpMainThread)
    QCoreApplication::processEvents();

  // The method must only be called from the main thread!
  CQProgressItem ** ppIt = mProgressItemList.array();
  CQProgressItem ** ppEnd = ppIt + mProgressItemList.size();
  CProcessReportItem **ppItem = mProcessReportItemList.array();

  for (; ppIt != ppEnd; ++ppIt, ++ppItem)
    {
      if (*ppIt != NULL)
        {
          removeProgressItem(*ppIt);

          // We must make sure the CProcessReportItem is not deleted prior to the actual delete.
          // The destructor of CQProgressItem will take care of the deletion.
          *ppItem = NULL;

          (*ppIt)->deleteLater();
          (*ppIt) = NULL;
        }
    }

  // We need to activate the user interface again.
  if (mpMainWidget != NULL)
    {
      mpMainWidget->setEnabled(true);

      if (mpMainThread == NULL ||
          QThread::currentThread() == mpMainThread)
        QCoreApplication::processEvents();
    }

  CProcessReport::finish();
  done(1);

  return mProceed;
}

bool CProgressBar::finishItem(const size_t & handle)
{
  if (!isValidHandle(handle) || mProgressItemList[handle] == NULL) return false;

  if (mpMainThread != NULL &&
      QThread::currentThread() != mpMainThread)
    {
      QMutexLocker Locker(&mMutex);
      mSlotFinished = false;

      emit signalFinishItem((int) handle);

      if (!mSlotFinished)
        {
          mWaitSlot.wait(&mMutex);
        }
    }
  else
    {
      slotFinishItem((int) handle);
      QCoreApplication::processEvents();
    }

  return mProceed;
}

void CProgressBar::slotFinishItem(const int handle)
{
  size_t Handle = (size_t) handle;

  if (isValidHandle(Handle) &&
      mProgressItemList[Handle] != NULL)
    {
      QMutexLocker Locker(&mMutex);

      removeProgressItem(mProgressItemList[Handle]);

      // We must make sure the CProcessReportItem is not deleted prior to the actual delete.
      // The destructor of CQProgressItem will take care of the deletion.
      mProcessReportItemList[Handle] = NULL;

      mProgressItemList[Handle]->deleteLater();
      mProgressItemList[Handle] = NULL;
    }

  mSlotFinished = true;
  mWaitSlot.wakeAll();
}

bool CProgressBar::proceed()
{
  return mProceed;
}

// virtual
bool CProgressBar::setName(const std::string & name)
{
  if (mpMainThread != NULL &&
      QThread::currentThread() != mpMainThread)
    {
      QMutexLocker Locker(&mMutex);
      mSlotFinished = false;

      emit signalSetName(FROM_UTF8(name));

      if (!mSlotFinished)
        {
          mWaitSlot.wait(&mMutex);
        }
    }
  else
    {
      slotSetName(FROM_UTF8(name));
      QCoreApplication::processEvents();
    }

  return true;
}
void CProgressBar::slotSetName(QString name)
{
  QMutexLocker Locker(&mMutex);

  setWindowTitle(name);
  CProcessReport::setName(TO_UTF8(name));

  mSlotFinished = true;
  mWaitSlot.wakeAll();
}

void CProgressBar::closeEvent(QCloseEvent *e)
{
  CQMessageBox::information(this, "COPASI", "COPASI is currently executing tasks.\n"
                            "Please stop them first before closing COPASI.");

  e->ignore();
}

// virtual
void CProgressBar::btnStopPressed()
{
  CQProgressDialog::btnStopPressed();
  mWaitPause.wakeAll();
}

// virtual
void CProgressBar::btnContinuePressed()
{
  CQProgressDialog::btnContinuePressed();
  mWaitPause.wakeAll();
}
<|endoftext|>


<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/lite/micro/micro_profiler.h"

#include "tensorflow/lite/kernels/internal/compatibility.h"
#include "tensorflow/lite/micro/micro_time.h"

namespace tflite {

MicroProfiler::MicroProfiler(tflite::ErrorReporter* reporter)
    : reporter_(reporter) {}

uint32_t MicroProfiler::BeginEvent(const char* tag, EventType event_type,
                                   int64_t event_metadata1,
                                   int64_t event_metadata2) {
  start_time_ = GetCurrentTimeTicks();
  TFLITE_DCHECK(tag != nullptr);
  event_tag_ = tag;
  return 0;
}

void MicroProfiler::EndEvent(uint32_t event_handle) {
#ifndef NPROFILE
  int32_t end_time = GetCurrentTimeTicks();
  TF_LITE_REPORT_ERROR(reporter_, "%s took %d cycles\n", event_tag_,
                       end_time - start_time_);
#endif
}
}  // namespace tflite
<commit_msg>micro_profiler.cc: Output profile data in CSV format<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/lite/micro/micro_profiler.h"

#include "tensorflow/lite/kernels/internal/compatibility.h"
#include "tensorflow/lite/micro/micro_time.h"

namespace tflite {

MicroProfiler::MicroProfiler(tflite::ErrorReporter* reporter)
    : reporter_(reporter) {}

uint32_t MicroProfiler::BeginEvent(const char* tag, EventType event_type,
                                   int64_t event_metadata1,
                                   int64_t event_metadata2) {
  start_time_ = GetCurrentTimeTicks();
  TFLITE_DCHECK(tag != nullptr);
  event_tag_ = tag;
  return 0;
}

void MicroProfiler::EndEvent(uint32_t event_handle) {
#ifndef NPROFILE
  int32_t end_time = GetCurrentTimeTicks();
  TF_LITE_REPORT_ERROR(reporter_, "\"PROFILER\", \"%s\", %d", event_tag_,
                       end_time - start_time_);
#endif
}
}  // namespace tflite
<|endoftext|>


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

#ifndef SC_TPHF_HXX
#define SC_TPHF_HXX

#ifndef _SVX_HDFT_HXX //autogen
#include <svx/hdft2.hxx>
#endif

class ScStyleDlg;

//========================================================================

class ScHFPage : public SvxHFPage
{
public:
    virtual         ~ScHFPage();

    virtual void    Reset( const SfxItemSet& rSet );
    virtual BOOL    FillItemSet( SfxItemSet& rOutSet );

    void            SetPageStyle( const String& rName )    { aStrPageStyle = rName; }
    void            SetStyleDlg ( const ScStyleDlg* pDlg ) { pStyleDlg = pDlg; }

protected:
                    ScHFPage( Window* pParent,
                              USHORT nResId,
                              const SfxItemSet& rSet,
                              USHORT nSetId );

    virtual void    ActivatePage( const SfxItemSet& rSet );
    virtual int     DeactivatePage( SfxItemSet* pSet = 0 );

private:
    PushButton          aBtnEdit;
    SfxItemSet          aDataSet;
    String              aStrPageStyle;
    USHORT              nPageUsage;
    const ScStyleDlg*   pStyleDlg;

#ifdef _TPHF_CXX
private:
    DECL_LINK( BtnHdl, PushButton* );
    DECL_LINK( HFEditHdl, void* );
    DECL_LINK( TurnOnHdl, CheckBox* );
#endif
};

//========================================================================

class ScHeaderPage : public ScHFPage
{
public:
    static SfxTabPage*  Create( Window* pParent, const SfxItemSet& rSet );
    static USHORT*      GetRanges();

private:
    ScHeaderPage( Window* pParent, const SfxItemSet& rSet );
};

//========================================================================

class ScFooterPage : public ScHFPage
{
public:
    static SfxTabPage*  Create( Window* pParent, const SfxItemSet& rSet );
    static USHORT*      GetRanges();

private:
    ScFooterPage( Window* pParent, const SfxItemSet& rSet );
};

#endif // SC_TPHF_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.798); FILE MERGED 2005/09/05 15:05:59 rt 1.2.798.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tphf.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:58: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
 *
 ************************************************************************/

#ifndef SC_TPHF_HXX
#define SC_TPHF_HXX

#ifndef _SVX_HDFT_HXX //autogen
#include <svx/hdft2.hxx>
#endif

class ScStyleDlg;

//========================================================================

class ScHFPage : public SvxHFPage
{
public:
    virtual         ~ScHFPage();

    virtual void    Reset( const SfxItemSet& rSet );
    virtual BOOL    FillItemSet( SfxItemSet& rOutSet );

    void            SetPageStyle( const String& rName )    { aStrPageStyle = rName; }
    void            SetStyleDlg ( const ScStyleDlg* pDlg ) { pStyleDlg = pDlg; }

protected:
                    ScHFPage( Window* pParent,
                              USHORT nResId,
                              const SfxItemSet& rSet,
                              USHORT nSetId );

    virtual void    ActivatePage( const SfxItemSet& rSet );
    virtual int     DeactivatePage( SfxItemSet* pSet = 0 );

private:
    PushButton          aBtnEdit;
    SfxItemSet          aDataSet;
    String              aStrPageStyle;
    USHORT              nPageUsage;
    const ScStyleDlg*   pStyleDlg;

#ifdef _TPHF_CXX
private:
    DECL_LINK( BtnHdl, PushButton* );
    DECL_LINK( HFEditHdl, void* );
    DECL_LINK( TurnOnHdl, CheckBox* );
#endif
};

//========================================================================

class ScHeaderPage : public ScHFPage
{
public:
    static SfxTabPage*  Create( Window* pParent, const SfxItemSet& rSet );
    static USHORT*      GetRanges();

private:
    ScHeaderPage( Window* pParent, const SfxItemSet& rSet );
};

//========================================================================

class ScFooterPage : public ScHFPage
{
public:
    static SfxTabPage*  Create( Window* pParent, const SfxItemSet& rSet );
    static USHORT*      GetRanges();

private:
    ScFooterPage( Window* pParent, const SfxItemSet& rSet );
};

#endif // SC_TPHF_HXX

<|endoftext|>


<commit_before>// Copyright (C) 2014 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

#include <math.h>

#include "copasi/utilities/CUnit.h"
#include "copasi/report/CKeyFactory.h"
#include "copasi/report/CCopasiRootContainer.h"
#include "copasi/model/CModel.h"

#include <algorithm>

// static
C_FLOAT64 CUnit::Avogadro(6.02214129e23); // http://physics.nist.gov/cgi-bin/cuu/Value?na (Wed Jan 29 18:33:36 EST 2014)

const char * CUnit::VolumeUnitNames[] =
{"dimensionless", "m\xc2\xb3", "l", "ml", "\xc2\xb5l", "nl", "pl", "fl", NULL};

const char * CUnit::AreaUnitNames[] =
{"dimensionless", "m\xc2\xb2", "dm\xc2\xb2", "cm\xc2\xb2", "mm\xc2\xb2", "\xc2\xb5m\xc2\xb2", "nm\xc2\xb2", "pm\xc2\xb2", "fm\xc2\xb2", NULL};

const char * CUnit::LengthUnitNames[] =
{"dimensionless", "m", "dm", "cm", "mm", "\xc2\xb5m", "nm", "pm", "fm", NULL};

const char * CUnit::TimeUnitNames[] =
{"dimensionless", "d", "h", "min", "s", "ms", "\xc2\xb5s", "ns", "ps", "fs", NULL};

// "mol" is the correct name, however in the COPASI XML files "Mol" is used
// up to build 18

const char * CUnit::QuantityUnitOldXMLNames[] =
{"dimensionless", "Mol", "mMol", "\xc2\xb5Mol", "nMol", "pMol", "fMol", "#", NULL};

const char * CUnit::QuantityUnitNames[] =
{"dimensionless", "mol", "mmol", "\xc2\xb5mol", "nmol", "pmol", "fmol", "#", NULL};

// constructors
CUnit::CUnit(const std::string & name,
             const CCopasiContainer * pParent):
  CCopasiContainer(name, pParent, "Unit"),
  mSymbol(),
  mKey(),
  mComponents()
{
  setup();
}

// copy constructor
CUnit::CUnit(const CUnit & src,
             const CCopasiContainer * pParent):
  CCopasiContainer(src, pParent),
  mSymbol(src.mSymbol),
  mKey(),
  mComponents(src.mComponents)
{
  setup();
}

CUnit::~CUnit()
{
  CCopasiRootContainer::getKeyFactory()->remove(mKey);
}

void CUnit::fromEnum(VolumeUnit volEnum)
{
  mComponents.clear();

  mSymbol = VolumeUnitNames[volEnum];
  // setup();

  if( volEnum == CUnit::dimensionlessVolume )
    return; // no need to add component

  CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter);
  tmpComponent.setExponent(3);

  switch (volEnum)
  {
    case CUnit::m3:  //default scale = 0
      break;

    case CUnit::l:
      tmpComponent.setScale(-3);
      break;

    case CUnit::ml:
      tmpComponent.setScale(-6);
      break;

    case CUnit::microl:
      tmpComponent.setScale(-9);
      break;

    case CUnit::nl:
      tmpComponent.setScale(-12);
      break;

    case CUnit::pl:
      tmpComponent.setScale(-15);
      break;

    case CUnit::fl:
      tmpComponent.setScale(-18);
      break;
  }

  addComponent(tmpComponent);

}

void CUnit::fromEnum(AreaUnit areaEnum)
{
  mComponents.clear();

  mSymbol = AreaUnitNames[areaEnum];
  setup();

  if( areaEnum == CUnit::dimensionlessArea )
    return; // no need to add component

  CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter);
  tmpComponent.setExponent(2);

  switch (areaEnum)
  {
    case CUnit::m2:  //default scale = 0
      break;

    case CUnit::dm2:
      tmpComponent.setScale(-2);
      break;

    case CUnit::cm2:
      tmpComponent.setScale(-4);
      break;

    case CUnit::mm2:
      tmpComponent.setScale(-6);
      break;

    case CUnit::microm2:
      tmpComponent.setScale(-12);
      break;

    case CUnit::nm2:
      tmpComponent.setScale(-18);
      break;

    case CUnit::pm2:
      tmpComponent.setScale(-24);
      break;

    case CUnit::fm2:
      tmpComponent.setScale(-30);
      break;
  }

  addComponent(tmpComponent);

}

void CUnit::fromEnum(LengthUnit lengthEnum)
{
  mComponents.clear();

  mSymbol = LengthUnitNames[lengthEnum];
  setup();

  if( lengthEnum == CUnit::dimensionlessLength )
    return; // no need to add component

  CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter);

  switch (lengthEnum)
  {
    case CUnit::m:  //default scale = 0
      break;

    case CUnit::dm:
      tmpComponent.setScale(-1);
      break;

    case CUnit::cm:
      tmpComponent.setScale(-2);
      break;

    case CUnit::mm:
      tmpComponent.setScale(-3);
      break;

    case CUnit::microm:
      tmpComponent.setScale(-6);
      break;

    case CUnit::nm:
      tmpComponent.setScale(-9);
      break;

    case CUnit::pm:
      tmpComponent.setScale(-12);
      break;

    case CUnit::fm:
      tmpComponent.setScale(-15);
      break;
  }

  addComponent(tmpComponent);

}

void CUnit::fromEnum(TimeUnit timeEnum)
{
  mComponents.clear();

  mSymbol = TimeUnitNames[timeEnum];
  setup();

  if( timeEnum == CUnit::dimensionlessTime )
    return; // no need to add component

  CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::second);

  switch (timeEnum)
  {
    case CUnit::d:
      tmpComponent.setMultiplier(60*60*24);
      break;

    case CUnit::h:
      tmpComponent.setMultiplier(60*60);
      break;

    case CUnit::min:
    case CUnit::OldMinute:
      tmpComponent.setMultiplier(60);
      break;

    case CUnit::s:  // defaults are appropriate
      break;

    case CUnit::micros:
      tmpComponent.setScale(-6);
      break;

    case CUnit::ns:
      tmpComponent.setScale(-9);
      break;

    case CUnit::ps:
      tmpComponent.setScale(-12);
      break;

    case CUnit::fs:
      tmpComponent.setScale(-15);
      break;
  }

  addComponent(tmpComponent);
}

void CUnit::fromEnum(QuantityUnit quantityEnum)
{
  mComponents.clear();

  mSymbol = QuantityUnitNames[quantityEnum];
  setup();

  if( quantityEnum == CUnit::dimensionlessQuantity )
    return; // no need to add component

  CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::item);

  const CModel * pModel = dynamic_cast<const CModel *>(getObjectAncestor("Model"));

  C_FLOAT64 usedAvogadro;

  if(pModel != NULL)
    usedAvogadro = pModel->getAvogadro();
  else
    usedAvogadro = Avogadro;

  tmpComponent.setMultiplier(usedAvogadro);

  //   enum QuantityUnit {dimensionlessQuantity = 0, Mol, mMol, microMol, nMol, pMol, fMol, number, OldXML};

  switch (quantityEnum)
  {
    case CUnit::Mol:
      break;

    case CUnit::mMol:
      tmpComponent.setScale(-3);
      break;

    case CUnit::microMol:
      tmpComponent.setScale(-6);
      break;

    case CUnit::nMol:
      tmpComponent.setScale(-9);
      break;

    case CUnit::pMol:
      tmpComponent.setScale(-12);
      break;

    case CUnit::fMol:
      tmpComponent.setScale(-15);
      break;

    case CUnit::number:
    case CUnit::OldXML:
      tmpComponent.setMultiplier(1);
      break;
  }

  addComponent(tmpComponent);
}

void CUnit::setup()
{
  mKey = CCopasiRootContainer::getKeyFactory()->add("Unit", this);
  setSymbol("tmp");
}

void CUnit::setSymbol(std::string symbol)
{
  mSymbol = symbol;
}

std::string CUnit::getSymbol() const
{
  return mSymbol;
}

// See if the component units cancel (divide to 1).
// The CUnitComponent::Kind enumerator uses only prime numbers.
// Multiplying all the components should give 1, if numerators and
// denominators have the same combination of units.
bool CUnit::isDimensionless() const
{
  // If the symbol string has been set to other than "dimensionless",
  // assume it has dimension, regardless of the components
  if(mSymbol != "dimensionless" || mSymbol != "")
    return false;

  std::vector< CUnitComponent >::const_iterator it = mComponents.begin();

  double reduction = 1;

  for (; it != mComponents.end(); it++)
    {
      reduction *= pow((double)(*it).getKind(), (*it).getExponent());
    }

  // If the vector is empy, it will loop 0 times, and the reduction
  // will remain ==1 (i.e. dimensionless if no components)
  return reduction == 1;
}

void CUnit::addComponent(const CUnitComponent & component)
{
  mComponents.push_back(component);
}

bool CUnit::simplifyComponents()
{
  if (mComponents.size() < 2)
    return false;

  std::vector< CUnitComponent > replacementVector;
  std::vector< CUnitComponent >::const_iterator it = mComponents.begin();
  CUnitComponent tempComponent;
  bool didSimplify = false;

  std::sort(mComponents.begin(), mComponents.end()); // make same Kinds adjacent

  for (; it != mComponents.end(); it++)
    {
      tempComponent = (*it);

      while (it != mComponents.end() && tempComponent.getKind() == (*(it + 1)).getKind())
        {
          tempComponent.setExponent((tempComponent.getExponent()) + (*(it + 1)).getExponent());
          tempComponent.setScale(tempComponent.getScale() + (*(it + 1)).getScale());
          tempComponent.setMultiplier(tempComponent.getMultiplier() * (*(it + 1)).getMultiplier());
          didSimplify = true;
          it++;
        }

      replacementVector.push_back(tempComponent);
    }

  if (didSimplify)
    {
      mComponents = replacementVector;
    }

  return didSimplify;
}
<commit_msg>Unit name assignment should work again.<commit_after>// Copyright (C) 2014 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

#include <math.h>

#include "copasi/utilities/CUnit.h"
#include "copasi/report/CKeyFactory.h"
#include "copasi/report/CCopasiRootContainer.h"
#include "copasi/model/CModel.h"

#include <algorithm>

// static
C_FLOAT64 CUnit::Avogadro(6.02214129e23); // http://physics.nist.gov/cgi-bin/cuu/Value?na (Wed Jan 29 18:33:36 EST 2014)

const char * CUnit::VolumeUnitNames[] =
{"dimensionless", "m\xc2\xb3", "l", "ml", "\xc2\xb5l", "nl", "pl", "fl", NULL};

const char * CUnit::AreaUnitNames[] =
{"dimensionless", "m\xc2\xb2", "dm\xc2\xb2", "cm\xc2\xb2", "mm\xc2\xb2", "\xc2\xb5m\xc2\xb2", "nm\xc2\xb2", "pm\xc2\xb2", "fm\xc2\xb2", NULL};

const char * CUnit::LengthUnitNames[] =
{"dimensionless", "m", "dm", "cm", "mm", "\xc2\xb5m", "nm", "pm", "fm", NULL};

const char * CUnit::TimeUnitNames[] =
{"dimensionless", "d", "h", "min", "s", "ms", "\xc2\xb5s", "ns", "ps", "fs", NULL};

// "mol" is the correct name, however in the COPASI XML files "Mol" is used
// up to build 18

const char * CUnit::QuantityUnitOldXMLNames[] =
{"dimensionless", "Mol", "mMol", "\xc2\xb5Mol", "nMol", "pMol", "fMol", "#", NULL};

const char * CUnit::QuantityUnitNames[] =
{"dimensionless", "mol", "mmol", "\xc2\xb5mol", "nmol", "pmol", "fmol", "#", NULL};

// constructors
CUnit::CUnit(const std::string & name,
             const CCopasiContainer * pParent):
  CCopasiContainer(name, pParent, "Unit"),
  mSymbol("none"),
  mKey(),
  mComponents()
{
  setup();
}

// copy constructor
CUnit::CUnit(const CUnit & src,
             const CCopasiContainer * pParent):
  CCopasiContainer(src, pParent),
  mSymbol(src.mSymbol),
  mKey(),
  mComponents(src.mComponents)
{
  setup();
}

CUnit::~CUnit()
{
  CCopasiRootContainer::getKeyFactory()->remove(mKey);
}

void CUnit::setup()
{
  mKey = CCopasiRootContainer::getKeyFactory()->add("Unit", this);
}

void CUnit::fromEnum(VolumeUnit volEnum)
{
  mComponents.clear();

  mSymbol = VolumeUnitNames[volEnum];

  if( volEnum == CUnit::dimensionlessVolume )
    return; // no need to add component

  CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter);
  tmpComponent.setExponent(3);

  switch (volEnum)
  {
    case CUnit::m3:  //default scale = 0
      break;

    case CUnit::l:
      tmpComponent.setScale(-3);
      break;

    case CUnit::ml:
      tmpComponent.setScale(-6);
      break;

    case CUnit::microl:
      tmpComponent.setScale(-9);
      break;

    case CUnit::nl:
      tmpComponent.setScale(-12);
      break;

    case CUnit::pl:
      tmpComponent.setScale(-15);
      break;

    case CUnit::fl:
      tmpComponent.setScale(-18);
      break;
  }

  addComponent(tmpComponent);

}

void CUnit::fromEnum(AreaUnit areaEnum)
{
  mComponents.clear();

  mSymbol = AreaUnitNames[areaEnum];

  if( areaEnum == CUnit::dimensionlessArea )
    return; // no need to add component

  CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter);
  tmpComponent.setExponent(2);

  switch (areaEnum)
  {
    case CUnit::m2:  //default scale = 0
      break;

    case CUnit::dm2:
      tmpComponent.setScale(-2);
      break;

    case CUnit::cm2:
      tmpComponent.setScale(-4);
      break;

    case CUnit::mm2:
      tmpComponent.setScale(-6);
      break;

    case CUnit::microm2:
      tmpComponent.setScale(-12);
      break;

    case CUnit::nm2:
      tmpComponent.setScale(-18);
      break;

    case CUnit::pm2:
      tmpComponent.setScale(-24);
      break;

    case CUnit::fm2:
      tmpComponent.setScale(-30);
      break;
  }

  addComponent(tmpComponent);

}

void CUnit::fromEnum(LengthUnit lengthEnum)
{
  mComponents.clear();

  mSymbol = LengthUnitNames[lengthEnum];

  if( lengthEnum == CUnit::dimensionlessLength )
    return; // no need to add component

  CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter);

  switch (lengthEnum)
  {
    case CUnit::m:  //default scale = 0
      break;

    case CUnit::dm:
      tmpComponent.setScale(-1);
      break;

    case CUnit::cm:
      tmpComponent.setScale(-2);
      break;

    case CUnit::mm:
      tmpComponent.setScale(-3);
      break;

    case CUnit::microm:
      tmpComponent.setScale(-6);
      break;

    case CUnit::nm:
      tmpComponent.setScale(-9);
      break;

    case CUnit::pm:
      tmpComponent.setScale(-12);
      break;

    case CUnit::fm:
      tmpComponent.setScale(-15);
      break;
  }

  addComponent(tmpComponent);

}

void CUnit::fromEnum(TimeUnit timeEnum)
{
  mComponents.clear();

  mSymbol = TimeUnitNames[timeEnum];

  if( timeEnum == CUnit::dimensionlessTime )
    return; // no need to add component

  CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::second);

  switch (timeEnum)
  {
    case CUnit::d:
      tmpComponent.setMultiplier(60*60*24);
      break;

    case CUnit::h:
      tmpComponent.setMultiplier(60*60);
      break;

    case CUnit::min:
    case CUnit::OldMinute:
      tmpComponent.setMultiplier(60);
      break;

    case CUnit::s:  // defaults are appropriate
      break;

    case CUnit::micros:
      tmpComponent.setScale(-6);
      break;

    case CUnit::ns:
      tmpComponent.setScale(-9);
      break;

    case CUnit::ps:
      tmpComponent.setScale(-12);
      break;

    case CUnit::fs:
      tmpComponent.setScale(-15);
      break;
  }

  addComponent(tmpComponent);
}

void CUnit::fromEnum(QuantityUnit quantityEnum)
{
  mComponents.clear();

  mSymbol = QuantityUnitNames[quantityEnum];

  if( quantityEnum == CUnit::dimensionlessQuantity )
    return; // no need to add component

  CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::item);

  const CModel * pModel = dynamic_cast<const CModel *>(getObjectAncestor("Model"));

  C_FLOAT64 usedAvogadro;

  if(pModel != NULL)
    usedAvogadro = pModel->getAvogadro();
  else
    usedAvogadro = Avogadro;

  tmpComponent.setMultiplier(usedAvogadro);

  //   enum QuantityUnit {dimensionlessQuantity = 0, Mol, mMol, microMol, nMol, pMol, fMol, number, OldXML};

  switch (quantityEnum)
  {
    case CUnit::Mol:
      break;

    case CUnit::mMol:
      tmpComponent.setScale(-3);
      break;

    case CUnit::microMol:
      tmpComponent.setScale(-6);
      break;

    case CUnit::nMol:
      tmpComponent.setScale(-9);
      break;

    case CUnit::pMol:
      tmpComponent.setScale(-12);
      break;

    case CUnit::fMol:
      tmpComponent.setScale(-15);
      break;

    case CUnit::number:
    case CUnit::OldXML:
      tmpComponent.setMultiplier(1);
      break;
  }

  addComponent(tmpComponent);
}

void CUnit::setSymbol(std::string symbol)
{
  mSymbol = symbol;
}

std::string CUnit::getSymbol() const
{
  return mSymbol;
}

// See if the component units cancel (divide to 1).
// The CUnitComponent::Kind enumerator uses only prime numbers.
// Multiplying all the components should give 1, if numerators and
// denominators have the same combination of units.
bool CUnit::isDimensionless() const
{
  // If the symbol string has been set to other than "dimensionless",
  // assume it has dimension, regardless of the components
  if(mSymbol != "dimensionless" || mSymbol != "")
    return false;

  std::vector< CUnitComponent >::const_iterator it = mComponents.begin();

  double reduction = 1;

  for (; it != mComponents.end(); it++)
    {
      reduction *= pow((double)(*it).getKind(), (*it).getExponent());
    }

  // If the vector is empy, it will loop 0 times, and the reduction
  // will remain ==1 (i.e. dimensionless if no components)
  return reduction == 1;
}

void CUnit::addComponent(const CUnitComponent & component)
{
  mComponents.push_back(component);
}

bool CUnit::simplifyComponents()
{
  if (mComponents.size() < 2)
    return false;

  std::vector< CUnitComponent > replacementVector;
  std::vector< CUnitComponent >::const_iterator it = mComponents.begin();
  CUnitComponent tempComponent;
  bool didSimplify = false;

  std::sort(mComponents.begin(), mComponents.end()); // make same Kinds adjacent

  for (; it != mComponents.end(); it++)
    {
      tempComponent = (*it);

      while (it != mComponents.end() && tempComponent.getKind() == (*(it + 1)).getKind())
        {
          tempComponent.setExponent((tempComponent.getExponent()) + (*(it + 1)).getExponent());
          tempComponent.setScale(tempComponent.getScale() + (*(it + 1)).getScale());
          tempComponent.setMultiplier(tempComponent.getMultiplier() * (*(it + 1)).getMultiplier());
          didSimplify = true;
          it++;
        }

      replacementVector.push_back(tempComponent);
    }

  if (didSimplify)
    {
      mComponents = replacementVector;
    }

  return didSimplify;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <stdexcept>

#include "matrix.h"

#include "Python.h"

#define ERROR_SUCCESS                               0
#define ERROR_FAILURE                              -1

void _assert(bool a)
{
    if (!a) throw std::runtime_error("Assertion failed.");
}

void test_matrix1()
{
    CooMatrix m(5);
    m.add(1, 3, 3.5);
    m.add(2, 3, 4.5);
    m.add(3, 4, 1.5);
    m.add(4, 2, 1.5);
    m.add(2, 3, 1);
    m.print();

    printf("----\n");
    CSRMatrix n(&m);
    n.print();
}

int main(int argc, char* argv[])
{
    try {
        // This is a hack, this should be set somewhere else:
        putenv((char *)"PYTHONPATH=../..");
        Py_Initialize();
        PySys_SetArgv(argc, argv);

        test_matrix1();

        return ERROR_SUCCESS;
    } catch(std::exception const &ex) {
        std::cout << "Exception raised: " << ex.what() << "\n";
        return ERROR_FAILURE;
    } catch(...) {
        std::cout << "Exception raised." << "\n";
        return ERROR_FAILURE;
    }
}
<commit_msg>Test the lin solver<commit_after>#include <iostream>
#include <stdexcept>

#include "matrix.h"

#include "Python.h"

#define EPS 1e-12

#define ERROR_SUCCESS                               0
#define ERROR_FAILURE                              -1

void _assert(bool a)
{
    if (!a) throw std::runtime_error("Assertion failed.");
}

void test_solver1()
{
    CooMatrix A(4);
    A.add(0, 0, -1);
    A.add(1, 1, -1);
    A.add(2, 2, -1);
    A.add(3, 3, -1);
    A.add(0, 1, 2);
    A.add(1, 0, 2);
    A.add(1, 2, 2);
    A.add(2, 1, 2);
    A.add(2, 3, 2);
    A.add(3, 2, 2);

    double res[4] = {1., 1., 1., 1.};

    solve_linear_system(&A, res);
    _assert(fabs(res[0] - 0.2) < EPS);
    _assert(fabs(res[1] - 0.6) < EPS);
    _assert(fabs(res[2] - 0.6) < EPS);
    _assert(fabs(res[3] - 0.2) < EPS);
}

int main(int argc, char* argv[])
{
    try {
        // This is a hack, this should be set somewhere else:
        putenv((char *)"PYTHONPATH=../..");
        Py_Initialize();
        PySys_SetArgv(argc, argv);

        test_solver1();

        return ERROR_SUCCESS;
    } catch(std::exception const &ex) {
        std::cout << "Exception raised: " << ex.what() << "\n";
        return ERROR_FAILURE;
    } catch(...) {
        std::cout << "Exception raised." << "\n";
        return ERROR_FAILURE;
    }
}
<|endoftext|>


<commit_before>/* -*- indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- */

/* This code is PUBLIC DOMAIN, and is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND. See the accompanying
 * LICENSE file.
 */

#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <curl/curl.h>
#include <string>
#include <string.h>
#include <vector>
#include <stdint.h>
#include <iostream>

using namespace node;
using namespace v8;

#define THROW_BAD_ARGS \
  ThrowException(Exception::TypeError(String::New("Bad argument")))

typedef std::vector<char> buff_t;

class CurlLib : ObjectWrap {
private:
  static std::string buffer;
  static std::vector<std::string> headers;
  static Persistent<String> sym_body_length;
  static Persistent<String> sym_headers;
  static Persistent<String> sym_timedout;
  static Persistent<String> sym_error;

public:
  static Persistent<FunctionTemplate> s_ct;
  static void Init(Handle<Object> target) {
    Local<FunctionTemplate> t = FunctionTemplate::New(New);

    s_ct = Persistent<FunctionTemplate>::New(t);
    s_ct->InstanceTemplate()->SetInternalFieldCount(1);
    s_ct->SetClassName(String::NewSymbol("CurlLib"));

    NODE_SET_PROTOTYPE_METHOD(s_ct, "run", Run);
    NODE_SET_PROTOTYPE_METHOD(s_ct, "body", Body);

    target->Set(String::NewSymbol("CurlLib"),
                s_ct->GetFunction());

    sym_body_length = NODE_PSYMBOL("body_length");
    sym_headers = NODE_PSYMBOL("headers");
    sym_timedout = NODE_PSYMBOL("timedout");
    sym_error = NODE_PSYMBOL("error");
  }

  CurlLib() { }
  ~CurlLib() { }

  static Handle<Value> New(const Arguments& args) {
    CurlLib* curllib = new CurlLib();
    curllib->Wrap(args.This());
    return args.This();
  }

  static size_t write_data(void *ptr, size_t size,
			   size_t nmemb, void *userdata) {
    buffer.append(static_cast<char*>(ptr), size * nmemb);
    // std::cerr<<"Wrote: "<<size*nmemb<<" bytes"<<std::endl;
    // std::cerr<<"Buffer size: "<<buffer.size()<<" bytes"<<std::endl;
    return size * nmemb;
  }

  static size_t write_headers(void *ptr, size_t size, size_t nmemb, void *userdata)
  {
    std::string header(static_cast<char*>(ptr), size * nmemb);
    headers.push_back(header);
    return size * nmemb;
  }

  /**
   * Copy src->Length() bytes from src to dest. Resize dest before
   * copying the data.
   */
  static void copy_to_buffer(buff_t &dest, Local<String> &src) {
    // std::cerr<<"copy_to_buffer::Length::"<<src->Length()<<std::endl;
    if (src->Length() > 0) {
      dest.resize(src->Length());
      src->WriteAscii(&dest[0], 0, src->Length());
    }
  }

  static Handle<Value> Body(const Arguments& args) {
    if (args.Length() < 1 || !Buffer::HasInstance(args[0])) {
      return THROW_BAD_ARGS;
    }

    HandleScope scope;
    Local<Object> buffer_obj = args[0]->ToObject();
    char *buffer_data        = Buffer::Data(buffer_obj);
    size_t buffer_length     = Buffer::Length(buffer_obj);

    if (buffer_length < buffer.size()) {
      return ThrowException(Exception::TypeError(
        String::New("Insufficient Buffer Length")));
    }

    if (!buffer.empty()) {
      memcpy(buffer_data, buffer.data(), buffer.size());
    }
    buffer.clear();
    return scope.Close(buffer_obj);
  }

  static Handle<Value> Run(const Arguments& args) {
    if (args.Length() < 1) {
      return THROW_BAD_ARGS;
    }

    Local<String> key_method = String::New("method");
    Local<String> key_url = String::New("url");
    Local<String> key_headers = String::New("headers");
    Local<String> key_body = String::New("body");
    Local<String> key_connect_timeout_ms = String::New("connect_timeout_ms");
    Local<String> key_timeout_ms = String::New("timeout_ms");
    Local<String> key_rejectUnauthorized = String::New("rejectUnauthorized");

    Local<Array> opt = Local<Array>::Cast(args[0]);

    if (!opt->Has(key_method) ||
        !opt->Has(key_url) ||
        !opt->Has(key_headers)) {
      return THROW_BAD_ARGS;
    }

    if (!opt->Get(key_method)->IsString() ||
        !opt->Get(key_url)->IsString()) {
      return THROW_BAD_ARGS;
    }

    Local<String> method = Local<String>::Cast(opt->Get(key_method));
    Local<String> url    = Local<String>::Cast(opt->Get(key_url));
    Local<Array>  reqh   = Local<Array>::Cast(opt->Get(key_headers));
    Local<String> body   = String::New((const char*)"", 0);
    long connect_timeout_ms = 1 * 60 * 60 * 1000; /* 1 hr in msec */
    long timeout_ms = 1 * 60 * 60 * 1000; /* 1 hr in msec */
    bool rejectUnauthorized = false;

    if (opt->Has(key_body) && opt->Get(key_body)->IsString()) {
      body = opt->Get(key_body)->ToString();
    }

    if (opt->Has(key_connect_timeout_ms) && opt->Get(key_connect_timeout_ms)->IsNumber()) {
      connect_timeout_ms = opt->Get(key_connect_timeout_ms)->IntegerValue();
    }

    if (opt->Has(key_timeout_ms) && opt->Get(key_timeout_ms)->IsNumber()) {
      timeout_ms = opt->Get(key_timeout_ms)->IntegerValue();
    }

    if (opt->Has(key_rejectUnauthorized)) {
      // std::cerr<<"has reject unauth"<<std::endl;
      if (opt->Get(key_rejectUnauthorized)->IsBoolean()) {
        rejectUnauthorized = opt->Get(key_rejectUnauthorized)->BooleanValue();
      } else if (opt->Get(key_rejectUnauthorized)->IsBooleanObject()) {
        rejectUnauthorized = opt->Get(key_rejectUnauthorized)
          ->ToBoolean()
          ->BooleanValue();
      }
    }

    // std::cerr<<"rejectUnauthorized: " << rejectUnauthorized << std::endl;

    buff_t _body, _method, _url;
    std::vector<buff_t> _reqh;

    copy_to_buffer(_body, body);
    copy_to_buffer(_method, method);
    _method.push_back('\0');
    copy_to_buffer(_url, url);
    _url.push_back('\0');

    for (size_t i = 0; i < reqh->Length(); ++i) {
      buff_t _tmp;
      Local<String> _src = reqh->Get(i)->ToString();
      copy_to_buffer(_tmp, _src);
      _tmp.push_back('\0');
      _reqh.push_back(_tmp);
    }

    HandleScope scope;
    // CurlLib* curllib = ObjectWrap::Unwrap<CurlLib>(args.This());

    buffer.clear();
    headers.clear();

    CURL *curl;
    CURLcode res = CURLE_FAILED_INIT;

    // char error_buffer[CURL_ERROR_SIZE];
    // error_buffer[0] = '\0';

    curl = curl_easy_init();
    if (curl) {
      // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
      // curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buffer);

      curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, &_method[0]);
      if (!_body.empty()) {
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
                         reinterpret_cast<char*> (&_body[0]));
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
                         (curl_off_t)_body.size());
      }
      curl_easy_setopt(curl, CURLOPT_URL, &_url[0]);
      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
      curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, write_headers);

      curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, connect_timeout_ms);
      curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, timeout_ms);

      if (rejectUnauthorized) {
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
      } else {
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
      }

      struct curl_slist *slist = NULL;

      for (size_t i = 0; i < _reqh.size(); ++i) {
        slist = curl_slist_append(slist, &(_reqh[i][0]));
      }

      curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);

      res = curl_easy_perform(curl);

      curl_slist_free_all(slist);

      /* always cleanup */
      curl_easy_cleanup(curl);
    }

    // std::cerr<<"error_buffer: "<<error_buffer<<std::endl;

    Local<Object> result = Object::New();

    if (!res) {
      result->Set(sym_body_length, Integer::New(buffer.size()));
      Local<Array> _h = Array::New();
      for (size_t i = 0; i < headers.size(); ++i) {
        _h->Set(i, String::New(headers[i].c_str()));
      }
      result->Set(sym_headers, _h);
    }
    else if (res == CURLE_OPERATION_TIMEDOUT) {
      result->Set(sym_timedout, Integer::New(1));
    } else {
      result->Set(sym_error, String::New(curl_easy_strerror(res)));
    }

    headers.clear();
    return scope.Close(result);
  }
};

Persistent<FunctionTemplate> CurlLib::s_ct;
std::string CurlLib::buffer;
std::vector<std::string> CurlLib::headers;
Persistent<String> CurlLib::sym_body_length;
Persistent<String> CurlLib::sym_headers;
Persistent<String> CurlLib::sym_timedout;
Persistent<String> CurlLib::sym_error;

extern "C" {
  static void init (Handle<Object> target) {
    CurlLib::Init(target);
  }
  NODE_MODULE(curllib, init);
}
<commit_msg>Follow HTTP redirects, maximum 5 hops<commit_after>/* -*- indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- */

/* This code is PUBLIC DOMAIN, and is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND. See the accompanying
 * LICENSE file.
 */

#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <curl/curl.h>
#include <string>
#include <string.h>
#include <vector>
#include <stdint.h>
#include <iostream>

using namespace node;
using namespace v8;

#define THROW_BAD_ARGS \
  ThrowException(Exception::TypeError(String::New("Bad argument")))

typedef std::vector<char> buff_t;

class CurlLib : ObjectWrap {
private:
  static std::string buffer;
  static std::vector<std::string> headers;
  static Persistent<String> sym_body_length;
  static Persistent<String> sym_headers;
  static Persistent<String> sym_timedout;
  static Persistent<String> sym_error;

public:
  static Persistent<FunctionTemplate> s_ct;
  static void Init(Handle<Object> target) {
    Local<FunctionTemplate> t = FunctionTemplate::New(New);

    s_ct = Persistent<FunctionTemplate>::New(t);
    s_ct->InstanceTemplate()->SetInternalFieldCount(1);
    s_ct->SetClassName(String::NewSymbol("CurlLib"));

    NODE_SET_PROTOTYPE_METHOD(s_ct, "run", Run);
    NODE_SET_PROTOTYPE_METHOD(s_ct, "body", Body);

    target->Set(String::NewSymbol("CurlLib"),
                s_ct->GetFunction());

    sym_body_length = NODE_PSYMBOL("body_length");
    sym_headers = NODE_PSYMBOL("headers");
    sym_timedout = NODE_PSYMBOL("timedout");
    sym_error = NODE_PSYMBOL("error");
  }

  CurlLib() { }
  ~CurlLib() { }

  static Handle<Value> New(const Arguments& args) {
    CurlLib* curllib = new CurlLib();
    curllib->Wrap(args.This());
    return args.This();
  }

  static size_t write_data(void *ptr, size_t size,
			   size_t nmemb, void *userdata) {
    buffer.append(static_cast<char*>(ptr), size * nmemb);
    // std::cerr<<"Wrote: "<<size*nmemb<<" bytes"<<std::endl;
    // std::cerr<<"Buffer size: "<<buffer.size()<<" bytes"<<std::endl;
    return size * nmemb;
  }

  static size_t write_headers(void *ptr, size_t size, size_t nmemb, void *userdata)
  {
    std::string header(static_cast<char*>(ptr), size * nmemb);
    headers.push_back(header);
    return size * nmemb;
  }

  /**
   * Copy src->Length() bytes from src to dest. Resize dest before
   * copying the data.
   */
  static void copy_to_buffer(buff_t &dest, Local<String> &src) {
    // std::cerr<<"copy_to_buffer::Length::"<<src->Length()<<std::endl;
    if (src->Length() > 0) {
      dest.resize(src->Length());
      src->WriteAscii(&dest[0], 0, src->Length());
    }
  }

  static Handle<Value> Body(const Arguments& args) {
    if (args.Length() < 1 || !Buffer::HasInstance(args[0])) {
      return THROW_BAD_ARGS;
    }

    HandleScope scope;
    Local<Object> buffer_obj = args[0]->ToObject();
    char *buffer_data        = Buffer::Data(buffer_obj);
    size_t buffer_length     = Buffer::Length(buffer_obj);

    if (buffer_length < buffer.size()) {
      return ThrowException(Exception::TypeError(
        String::New("Insufficient Buffer Length")));
    }

    if (!buffer.empty()) {
      memcpy(buffer_data, buffer.data(), buffer.size());
    }
    buffer.clear();
    return scope.Close(buffer_obj);
  }

  static Handle<Value> Run(const Arguments& args) {
    if (args.Length() < 1) {
      return THROW_BAD_ARGS;
    }

    Local<String> key_method = String::New("method");
    Local<String> key_url = String::New("url");
    Local<String> key_headers = String::New("headers");
    Local<String> key_body = String::New("body");
    Local<String> key_connect_timeout_ms = String::New("connect_timeout_ms");
    Local<String> key_timeout_ms = String::New("timeout_ms");
    Local<String> key_rejectUnauthorized = String::New("rejectUnauthorized");

    Local<Array> opt = Local<Array>::Cast(args[0]);

    if (!opt->Has(key_method) ||
        !opt->Has(key_url) ||
        !opt->Has(key_headers)) {
      return THROW_BAD_ARGS;
    }

    if (!opt->Get(key_method)->IsString() ||
        !opt->Get(key_url)->IsString()) {
      return THROW_BAD_ARGS;
    }

    Local<String> method = Local<String>::Cast(opt->Get(key_method));
    Local<String> url    = Local<String>::Cast(opt->Get(key_url));
    Local<Array>  reqh   = Local<Array>::Cast(opt->Get(key_headers));
    Local<String> body   = String::New((const char*)"", 0);
    long connect_timeout_ms = 1 * 60 * 60 * 1000; /* 1 hr in msec */
    long timeout_ms = 1 * 60 * 60 * 1000; /* 1 hr in msec */
    bool rejectUnauthorized = false;

    if (opt->Has(key_body) && opt->Get(key_body)->IsString()) {
      body = opt->Get(key_body)->ToString();
    }

    if (opt->Has(key_connect_timeout_ms) && opt->Get(key_connect_timeout_ms)->IsNumber()) {
      connect_timeout_ms = opt->Get(key_connect_timeout_ms)->IntegerValue();
    }

    if (opt->Has(key_timeout_ms) && opt->Get(key_timeout_ms)->IsNumber()) {
      timeout_ms = opt->Get(key_timeout_ms)->IntegerValue();
    }

    if (opt->Has(key_rejectUnauthorized)) {
      // std::cerr<<"has reject unauth"<<std::endl;
      if (opt->Get(key_rejectUnauthorized)->IsBoolean()) {
        rejectUnauthorized = opt->Get(key_rejectUnauthorized)->BooleanValue();
      } else if (opt->Get(key_rejectUnauthorized)->IsBooleanObject()) {
        rejectUnauthorized = opt->Get(key_rejectUnauthorized)
          ->ToBoolean()
          ->BooleanValue();
      }
    }

    // std::cerr<<"rejectUnauthorized: " << rejectUnauthorized << std::endl;

    buff_t _body, _method, _url;
    std::vector<buff_t> _reqh;

    copy_to_buffer(_body, body);
    copy_to_buffer(_method, method);
    _method.push_back('\0');
    copy_to_buffer(_url, url);
    _url.push_back('\0');

    for (size_t i = 0; i < reqh->Length(); ++i) {
      buff_t _tmp;
      Local<String> _src = reqh->Get(i)->ToString();
      copy_to_buffer(_tmp, _src);
      _tmp.push_back('\0');
      _reqh.push_back(_tmp);
    }

    HandleScope scope;
    // CurlLib* curllib = ObjectWrap::Unwrap<CurlLib>(args.This());

    buffer.clear();
    headers.clear();

    CURL *curl;
    CURLcode res = CURLE_FAILED_INIT;

    // char error_buffer[CURL_ERROR_SIZE];
    // error_buffer[0] = '\0';

    curl = curl_easy_init();
    if (curl) {
      // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
      // curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buffer);

      curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, &_method[0]);
      if (!_body.empty()) {
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS,
                         reinterpret_cast<char*> (&_body[0]));
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,
                         (curl_off_t)_body.size());
      }
      curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
      curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 5);
      curl_easy_setopt(curl, CURLOPT_URL, &_url[0]);
      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
      curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, write_headers);

      curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, connect_timeout_ms);
      curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, timeout_ms);

      if (rejectUnauthorized) {
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
      } else {
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
      }

      struct curl_slist *slist = NULL;

      for (size_t i = 0; i < _reqh.size(); ++i) {
        slist = curl_slist_append(slist, &(_reqh[i][0]));
      }

      curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);

      res = curl_easy_perform(curl);

      curl_slist_free_all(slist);

      /* always cleanup */
      curl_easy_cleanup(curl);
    }

    // std::cerr<<"error_buffer: "<<error_buffer<<std::endl;

    Local<Object> result = Object::New();

    if (!res) {
      result->Set(sym_body_length, Integer::New(buffer.size()));
      Local<Array> _h = Array::New();
      for (size_t i = 0; i < headers.size(); ++i) {
        _h->Set(i, String::New(headers[i].c_str()));
      }
      result->Set(sym_headers, _h);
    }
    else if (res == CURLE_OPERATION_TIMEDOUT) {
      result->Set(sym_timedout, Integer::New(1));
    } else {
      result->Set(sym_error, String::New(curl_easy_strerror(res)));
    }

    headers.clear();
    return scope.Close(result);
  }
};

Persistent<FunctionTemplate> CurlLib::s_ct;
std::string CurlLib::buffer;
std::vector<std::string> CurlLib::headers;
Persistent<String> CurlLib::sym_body_length;
Persistent<String> CurlLib::sym_headers;
Persistent<String> CurlLib::sym_timedout;
Persistent<String> CurlLib::sym_error;

extern "C" {
  static void init (Handle<Object> target) {
    CurlLib::Init(target);
  }
  NODE_MODULE(curllib, init);
}
<|endoftext|>


<commit_before>/**
 * @file demo_sir_reach.cpp
 * Reachability analysis on SIR epidemic model
 *
 * @author Tommaso Dreossi <tommasodreossi@berkeley.edu>
 * @version 0.1
 */

#include <stdio.h>
#include <iostream>

#include "Common.h"
#include "Bundle.h"
#include "Sapo.h"

using namespace std;

int main(int argc,char** argv){

	//The model
	int dim_sys = 3;

	// List of state variables and parameters
	symbol s("s"), i("i"), r("r"), beta("beta"), gamma("gamma");
	lst vars, dyns, params;
	vars = s, i, r;
	params = beta, gamma;

	// System's dynamics
	ex ds = s - (0.34*s*i)*0.1;				// susceptible
	ex di = i + (0.34*s*i - 0.05*i)*0.1;	// infected
	ex dr = r + 0.05*i*0.1;					// removed
	dyns = ds,di,dr;
	Model *sir = new Model(vars,params,dyns);

	// The initial set
	int num_dirs = 5;		// number of bundle directions
	int num_temps = 3;		// number of bundle templates

	// Directions matrix
	vector< double > Li (dim_sys,0);
	vector< vector< double > > L (num_dirs,Li);
	L[0][0] = 1;
	L[1][1] = 1;
	L[2][2] = 1;
	L[3][0] = 1; L[3][1] = 0.5;
	L[4][0] = 0.5; L[4][2] = 0.5;
//	L[5][0] = 1; L[5][1] = 0.5; L[5][2] = 0.5;
//	L[6][0] = 0; L[6][1] = 0.75; L[6][2] = 0.75;
//	L[7][0] = 1; L[7][1] = 0.2; L[7][2] = 0;

	// Offsets
	vector< double > offp (num_dirs,0);
	vector< double > offm (num_dirs,0);
	offp[0] = 0.8; offm[0] = -0.79;
	offp[1] = 0.2; offm[1] = -0.19;
	offp[2] = 0.0001; offm[2] = -0.000099;
	offp[3] = 1; offm[3] = 0;
	offp[4] = 1; offm[4] = 0;
//	offp[5] = 1; offm[5] = 0;
//	offp[6] = 1; offm[6] = 0;
//	offp[7] = 1; offm[7] = 0;

	// Template matrix
	vector< int > Ti (dim_sys,0);
	vector< vector< int > > T (num_temps,Ti);

	T[0][0] = 0; T[0][1] = 1; T[0][2] = 2;
	T[1][0] = 1; T[1][1] = 2; T[1][2] = 3;
	T[2][0] = 2; T[2][1] = 3; T[2][2] = 4;
//	T[3][0] = 5; T[3][1] = 2; T[3][2] = 1;

//	// Declare the initial parameter set as a linear system
//	vector<double> pAi (2,0);
//	vector< vector<double> > pA (4,pAi);
//	vector<double> pb (4,0);
//	pA[0][0] = 1; pA[0][1] = 0; pb[0] = 0.36;
//	pA[1][0] = -1; pA[1][1] = 0; pb[1] = -0.35;
//	pA[2][0] = 0; pA[2][1] = 1; pb[2] = 0.06;
//	pA[3][0] = 0; pA[3][1] = -1; pb[3] = -0.05;

	Bundle *B = new Bundle(L,offp,offm,T);

	// Options for Sapo
	sapo_opt options;
	options.trans = 1;
	options.alpha = 0.5;
	options.decomp = 0;
	options.verbose = false;

	Sapo *sapo = new Sapo(sir,options);
	Flowpipe* flowpipe = sapo->reach(B,300);

	// Store the constructed flowpipe in file sir.m
	char file_name[] = "sir.m";
	flowpipe->plotRegionToFile(file_name,'b');

}

<commit_msg>Demo: reachability SIR model<commit_after>/**
 * @file demo_sir_reach.cpp
 * Demo: Reachability analysis of SIR epidemic model
 *
 * @author Tommaso Dreossi <tommasodreossi@berkeley.edu>
 * @version 0.1
 */

#include <stdio.h>
#include <iostream>

#include "Common.h"
#include "Bundle.h"
#include "Sapo.h"

using namespace std;

/**
 * Main function
 *
 */
int main(int argc,char** argv){

	///// The dynamical system /////

	// System dimension (number of variables)
	int dim_sys = 3;
	// List of state variables
	symbol s("s"), i("i"), r("r");
	lst vars;
	vars = s, i, r;

	// System's dynamics
	ex ds = s - (0.34*s*i)*0.1;				// susceptible
	ex di = i + (0.34*s*i - 0.05*i)*0.1;	// infected
	ex dr = r + 0.05*i*0.1;					// removed
	lst dyns;
	dyns = ds,di,dr;

	Model *sir = new Model(vars,dyns);

	///// Parallelotope bundle for reachability analysis /////

	int num_dirs = 5;		// number of bundle directions
	int num_temps = 3;		// number of bundle templates

	// Directions matrix
	vector< double > Li (dim_sys,0);
	vector< vector< double > > L (num_dirs,Li);
	L[0][0] = 1;
	L[1][1] = 1;
	L[2][2] = 1;
	L[3][0] = 1; L[3][1] = 0.5;
	L[4][0] = 0.5; L[4][2] = 0.5;

	// Template matrix
	vector< int > Ti (dim_sys,0);
	vector< vector< int > > T (num_temps,Ti);
	T[0][0] = 0; T[0][1] = 1; T[0][2] = 2;
	T[1][0] = 1; T[1][1] = 2; T[1][2] = 3;
	T[2][0] = 2; T[2][1] = 3; T[2][2] = 4;

	// Offsets for the set of initial conditions
	vector< double > offp (num_dirs,0);
	vector< double > offm (num_dirs,0);
	offp[0] = 0.8; offm[0] = -0.79;
	offp[1] = 0.2; offm[1] = -0.19;
	offp[2] = 0.0001; offm[2] = -0.000099;
	offp[3] = 1; offm[3] = 0;
	offp[4] = 1; offm[4] = 0;

	Bundle *B = new Bundle(L,offp,offm,T);

	///// SAPO core /////

	// Sapo's options
	sapo_opt options;
	options.trans = 1;			// Set transformation (0=OFO, 1=AFO)
	options.decomp = 0;			// Template decomposition (0=no, 1=yes)
	//options.alpha = 0.5;		// Weight for bundle size/orthgonal proximity
	options.verbose = false;

	Sapo *sapo = new Sapo(sir,options);
	int reach_steps = 300;
	Flowpipe* flowpipe = sapo->reach(B,reach_steps);	// reachability analysis

	// Store the constructed flowpipe in file sir.m (in Matlab format)
	char file_name[] = "sir_flowpipe.m";
	flowpipe->plotRegionToFile(file_name,'b');

}

<|endoftext|>


<commit_before>#pragma once

#include "cog_token_type.hpp"
#include "text/tokenizer.hpp"

namespace gorc {
    namespace cog {

        class cog_tokenizer_state_machine : public tokenizer_state_machine {
            using tok_result = tokenizer_state_machine_result;

        private:
            enum class tokenizer_state {
                accept,
                reject,
                initial,
                skip_line_comment,
                identifier,
                string,
                escape_sequence,
                seen_slash,
                seen_equal,
                seen_exclamation_mark,
                seen_greater,
                seen_less,
                seen_ampersand,
                seen_pipe,
                hex_prefix,
                hex_required_digit,
                hex_digit_sequence,
                digit_sequence,
                decimal_required_digit,
                decimal_digit_sequence,
                decimal_exponent_sign,
                decimal_exponent_required_digit,
                decimal_exponent_sequence,
                string_fragment
            };

            tokenizer_state current_state = tokenizer_state::initial;
            cog_token_type current_type = cog_token_type::error;
            std::string reason;
            std::string append_buffer;
            bool should_return_newlines = false;

            inline tok_result append_directive(tokenizer_state new_state,
                                               char ch)
            {
                append_buffer.clear();
                append_buffer.push_back(ch);

                current_state = new_state;

                return tok_result(tokenizer_state_machine_result_type::append, append_buffer);
            }

            inline tok_result skip_directive(tokenizer_state new_state)
            {
                append_buffer.clear();
                current_state = new_state;
                return tok_result(tokenizer_state_machine_result_type::append, append_buffer);
            }

            inline tok_result discard_directive(tokenizer_state new_state)
            {
                current_state = new_state;
                return tok_result(tokenizer_state_machine_result_type::discard, append_buffer);
            }

            inline tok_result accept_immediately(cog_token_type type, maybe<char> ch = nothing)
            {
                current_type = type;
                current_state = tokenizer_state::initial;
                append_buffer.clear();
                if(ch.has_value()) {
                    append_buffer.push_back(ch.get_value());
                }
                return tok_result(tokenizer_state_machine_result_type::halt, append_buffer);
            }

            inline tok_result reject_immediately(std::string const &reason_msg)
            {
                current_type = cog_token_type::error;
                current_state = tokenizer_state::initial;
                reason = reason_msg;
                append_buffer.clear();
                return tok_result(tokenizer_state_machine_result_type::halt, append_buffer);
            }

            inline tok_result append_then_reject(char ch,
                                                 std::string const &reason_msg)
            {
                reason = reason_msg;
                return append_directive(tokenizer_state::reject, ch);
            }

            inline tok_result append_then_accept(char ch, cog_token_type type)
            {
                current_type = type;
                return append_directive(tokenizer_state::accept, ch);
            }

            inline tok_result skip_then_accept(cog_token_type type)
            {
                current_type = type;
                return skip_directive(tokenizer_state::accept);
            }

            tok_result handle_initial_state(char ch);
            tok_result handle_skip_line_comment_state(char ch);
            tok_result handle_identifier_state(char ch);
            tok_result handle_string_state(char ch);
            tok_result handle_escape_sequence_state(char ch);
            tok_result handle_seen_slash_state(char ch);
            tok_result handle_seen_equal_state(char ch);
            tok_result handle_seen_exclamation_mark_state(char ch);
            tok_result handle_seen_greater_state(char ch);
            tok_result handle_seen_less_state(char ch);
            tok_result handle_seen_ampersand_state(char ch);
            tok_result handle_seen_pipe_state(char ch);
            tok_result handle_single_punctuator_state(char ch);
            tok_result handle_hex_prefix_state(char ch);
            tok_result handle_hex_required_digit_state(char ch);
            tok_result handle_hex_digit_sequence_state(char ch);
            tok_result handle_digit_sequence_state(char ch);
            tok_result handle_decimal_required_digit_state(char ch);
            tok_result handle_decimal_digit_sequence_state(char ch);
            tok_result handle_decimal_exponent_sign_state(char ch);
            tok_result handle_decimal_exponent_required_digit_state(char ch);
            tok_result handle_decimal_exponent_sequence_state(char ch);
            tok_result handle_string_fragment_state(char ch);

        public:
            virtual tokenizer_state_machine_result handle(char ch) override;
            virtual std::string const & get_reason() const override;

            cog_token_type get_type() const;
            void set_string_fragment_state();
            void return_newlines(bool state);
        };

        class cog_tokenizer : public tokenizer<cog_tokenizer_state_machine> {
        public:
            cog_tokenizer(input_stream &);
            void extract_string_fragment();
            void return_newlines(bool state);
        };

    }
}
<commit_msg>Added signed numbers<commit_after>#pragma once

#include "cog_token_type.hpp"
#include "text/tokenizer.hpp"

namespace gorc {
    namespace cog {

        class cog_tokenizer_state_machine : public tokenizer_state_machine {
            using tok_result = tokenizer_state_machine_result;

        private:
            enum class tokenizer_state {
                accept,
                reject,
                initial,
                skip_line_comment,
                identifier,
                string,
                escape_sequence,
                seen_plus,
                seen_minus,
                seen_slash,
                seen_equal,
                seen_exclamation_mark,
                seen_greater,
                seen_less,
                seen_ampersand,
                seen_pipe,
                hex_prefix,
                hex_required_digit,
                hex_digit_sequence,
                digit_sequence,
                decimal_required_digit,
                decimal_digit_sequence,
                decimal_exponent_sign,
                decimal_exponent_required_digit,
                decimal_exponent_sequence,
                string_fragment
            };

            tokenizer_state current_state = tokenizer_state::initial;
            cog_token_type current_type = cog_token_type::error;
            std::string reason;
            std::string append_buffer;
            bool should_return_newlines = false;

            inline tok_result append_directive(tokenizer_state new_state,
                                               char ch)
            {
                append_buffer.clear();
                append_buffer.push_back(ch);

                current_state = new_state;

                return tok_result(tokenizer_state_machine_result_type::append, append_buffer);
            }

            inline tok_result skip_directive(tokenizer_state new_state)
            {
                append_buffer.clear();
                current_state = new_state;
                return tok_result(tokenizer_state_machine_result_type::append, append_buffer);
            }

            inline tok_result discard_directive(tokenizer_state new_state)
            {
                current_state = new_state;
                return tok_result(tokenizer_state_machine_result_type::discard, append_buffer);
            }

            inline tok_result accept_immediately(cog_token_type type, maybe<char> ch = nothing)
            {
                current_type = type;
                current_state = tokenizer_state::initial;
                append_buffer.clear();
                if(ch.has_value()) {
                    append_buffer.push_back(ch.get_value());
                }
                return tok_result(tokenizer_state_machine_result_type::halt, append_buffer);
            }

            inline tok_result reject_immediately(std::string const &reason_msg)
            {
                current_type = cog_token_type::error;
                current_state = tokenizer_state::initial;
                reason = reason_msg;
                append_buffer.clear();
                return tok_result(tokenizer_state_machine_result_type::halt, append_buffer);
            }

            inline tok_result append_then_reject(char ch,
                                                 std::string const &reason_msg)
            {
                reason = reason_msg;
                return append_directive(tokenizer_state::reject, ch);
            }

            inline tok_result append_then_accept(char ch, cog_token_type type)
            {
                current_type = type;
                return append_directive(tokenizer_state::accept, ch);
            }

            inline tok_result skip_then_accept(cog_token_type type)
            {
                current_type = type;
                return skip_directive(tokenizer_state::accept);
            }

            tok_result handle_initial_state(char ch);
            tok_result handle_skip_line_comment_state(char ch);
            tok_result handle_identifier_state(char ch);
            tok_result handle_string_state(char ch);
            tok_result handle_escape_sequence_state(char ch);
            tok_result handle_seen_plus_state(char ch);
            tok_result handle_seen_minus_state(char ch);
            tok_result handle_seen_slash_state(char ch);
            tok_result handle_seen_equal_state(char ch);
            tok_result handle_seen_exclamation_mark_state(char ch);
            tok_result handle_seen_greater_state(char ch);
            tok_result handle_seen_less_state(char ch);
            tok_result handle_seen_ampersand_state(char ch);
            tok_result handle_seen_pipe_state(char ch);
            tok_result handle_single_punctuator_state(char ch);
            tok_result handle_hex_prefix_state(char ch);
            tok_result handle_hex_required_digit_state(char ch);
            tok_result handle_hex_digit_sequence_state(char ch);
            tok_result handle_digit_sequence_state(char ch);
            tok_result handle_decimal_required_digit_state(char ch);
            tok_result handle_decimal_digit_sequence_state(char ch);
            tok_result handle_decimal_exponent_sign_state(char ch);
            tok_result handle_decimal_exponent_required_digit_state(char ch);
            tok_result handle_decimal_exponent_sequence_state(char ch);
            tok_result handle_string_fragment_state(char ch);

        public:
            virtual tokenizer_state_machine_result handle(char ch) override;
            virtual std::string const & get_reason() const override;

            cog_token_type get_type() const;
            void set_string_fragment_state();
            void return_newlines(bool state);
        };

        class cog_tokenizer : public tokenizer<cog_tokenizer_state_machine> {
        public:
            cog_tokenizer(input_stream &);
            void extract_string_fragment();
            void return_newlines(bool state);
        };

    }
}
<|endoftext|>