<commit_before>/* logWidget.cc                         KPilot
**
** Copyright (C) 2001 by Dan Pilone
**
** This file defines the log window widget, which logs
** sync-messages during a HotSync.
*/

/*
** This program 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 2 of the License, or
** (at your option) any later version.
**
** This program 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 this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
** MA 02139, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org.
*/
static const char *logw_id =
	"$Id$";

#include "options.h"

#include <qfile.h>
#include <qlayout.h>
#include <qtextview.h>
#include <qtooltip.h>
#include <qdatetime.h>
#include <qlabel.h>
#include <qpixmap.h>
#include <qtimer.h>
#include <qpushbutton.h>
#include <qhbox.h>
#include <qtextstream.h>

#include <kglobal.h>
#include <kstddirs.h>
#include <kprogress.h>
#include <kfiledialog.h>
#include <kmessagebox.h>

#include "logWidget.moc"

LogWidget::LogWidget(QWidget * parent) :
	PilotComponent(parent, "component_log", QString::null),
	DCOPObject("KPilotIface"),
	fLog(0L),
	fShowTime(false),
	fSplash(0L),
	fLabel(0L),
	fProgress(0L)
{
	FUNCTIONSETUP;
	QGridLayout *grid = new QGridLayout(this, 4, 4, SPACING);

	grid->addRowSpacing(0, SPACING);
	grid->addRowSpacing(1, 100);
	grid->addColSpacing(2, 100);
	grid->addRowSpacing(3, SPACING);
	grid->addColSpacing(0, SPACING);
	grid->addColSpacing(3, SPACING);
	grid->setRowStretch(1, 50);
	grid->setColStretch(2, 50);

	fLog = new QTextView(this);
	QToolTip::add(fLog, i18n("<qt>This lists all the messages received "
			"during the current HotSync</qt>"));
	grid->addMultiCellWidget(fLog, 1, 1,1,2);

	fLog->setText(i18n("<qt>HotSync Log</qt>"));

	QHBox *h = new QHBox(this);
	h->setSpacing(SPACING);
	QPushButton *b = new QPushButton(
		i18n("Clear the text of HotSync messages","Clear Log"),
		h);
	QToolTip::add(b,i18n("<qt>Clears the list of messages from the "
		"current HotSync.</qt>"));
	connect(b,SIGNAL(clicked()),this,SLOT(clearLog()));

	b = new QPushButton(i18n("Save Log"),h);
	QToolTip::add(b,i18n("<qt>You can save the list of messages received "
		"during this HotSync to a file (for example for use in a "
		"bug report) by clicking here.</qt>"));
	connect(b,SIGNAL(clicked()),this,SLOT(saveLog()));

	grid->addMultiCellWidget(h,2,2,1,2);

	fLabel = new QLabel(i18n("Sync Progress:"),this);
	grid->addWidget(fLabel,3,1);
	fProgress = new KProgress(0,100,0,KProgress::Horizontal,this);
	QToolTip::add(fProgress,i18n("<qt>The (estimated) percentage "
		"completed in the current HotSync.</qt>"));
	grid->addWidget(fProgress,3,2);

	QString splashPath =
		KGlobal::dirs()->findResource("data",
			"kpilot/kpilot-splash.png");

	if (!splashPath.isEmpty() && QFile::exists(splashPath))
	{
		fLog->hide();
		fLabel->hide();
		fProgress->hide();

		QPixmap splash(splashPath);
		QPainter painter(&splash);
		painter.setPen(QColor(255, 0, 0));

		int textWidth =fontMetrics().width(KPILOT_VERSION) ;
		int textHeight = fontMetrics().height();

#ifdef DEBUG
		DEBUGKPILOT << fname
			<< ": Using text size "
			<< textWidth << "x" << textHeight
			<< endl;
#endif

		painter.fillRect(splash.width() -  28 - textWidth,
			splash.height() - 6 - textHeight - textHeight ,
			textWidth + 6,
			textHeight + 4,
			black);
		painter.drawText(splash.width() -  25 - textWidth,
			splash.height() - 8 - textHeight,
			KPILOT_VERSION);
		fSplash = new QLabel(this);
		fSplash->setPixmap(splash);
		QTimer::singleShot(3000,this,SLOT(hideSplash()));
		grid->addMultiCellWidget(fSplash,1,3,1,2);
	}

	(void) logw_id;
}

void LogWidget::addMessage(const QString & s)
{
	FUNCTIONSETUP;

	if (fShowTime)
	{
		QString t;

		t = QTime::currentTime().toString();
		t.append("  ");
		t.append(s);
		fLog->append(t);
	}
	else
	{
		fLog->append(s);
	}
}

void LogWidget::addError(const QString & s)
{
	FUNCTIONSETUP;

	QString t("<qt>");

	if (fShowTime)
	{

		t = QTime::currentTime().toString();
		t.append("  ");
	}

	t.append(s);
	t.append("</qt>");

	fLog->append(s);
}

void LogWidget::addProgress(const QString &s,int i)
{
	FUNCTIONSETUP;

	logMessage(s);

	if ((i >= 0) && (i <= 100))
	{
		fProgress->setValue(i);
	}
}

void LogWidget::syncDone()
{
	FUNCTIONSETUP;

	addMessage(i18n("HotSync Finished!"));
}

void LogWidget::initialize()
{
	FUNCTIONSETUP;
}

void LogWidget::hideSplash()
{
	FUNCTIONSETUP;

	if (fSplash)
	{
		fSplash->hide();
		KPILOT_DELETE(fSplash);
	}

	fLog->show();
	fLabel->show();
	fProgress->show();
}

/* DCOP */ ASYNC LogWidget::logMessage(QString s)
{
	FUNCTIONSETUP;

	if (fLog)
	{
		QTime t = QTime::currentTime();
		QString s1 = t.toString();

		s1.append("  ");
		s1.append(s);
		fLog->append(s1);
	}
}

/* DCOP */ ASYNC LogWidget::logProgress(QString s, int i)
{
	FUNCTIONSETUP;

	addProgress(s,i);
}

/* slot */ void LogWidget::clearLog()
{
	FUNCTIONSETUP;

	if (fLog)
	{
		fLog->setText(QString::null);
	}
}

/* slot */ void LogWidget::saveLog()
{
	FUNCTIONSETUP;

	bool finished = false;

	while (!finished)
	{
		QString saveFileName = KFileDialog::getSaveFileName(
			QString::null,     /* default */
			"*.log",           /* show log files by default */
			this,
			i18n("Save Log"));

		if (saveFileName.isEmpty()) return;
		if (QFile::exists(saveFileName))
		{
			int r = KMessageBox::warningYesNoCancel(
				this,
				i18n("The file exists. Do you want to "
					"overwrite it?"),
				i18n("File Exists"));
			if (r==KMessageBox::Yes)
			{
				finished=saveFile(saveFileName);
			}

			if (r==KMessageBox::Cancel) return;
		}
		else
		{
			finished=saveFile(saveFileName);
		}
	}
}

bool LogWidget::saveFile(const QString &saveFileName)
{
	FUNCTIONSETUP;

	QFile f(saveFileName);
	if (!f.open(IO_WriteOnly))
	{
		int r = KMessageBox::questionYesNo(this,
			i18n("<qt>Can't open the file "%1" "
				"for writing. Try again?</qt>"),
			i18n("Can't Save"));

		if (r==KMessageBox::Yes) return false;
		return true;
	}
	else
	{
		QTextStream t(&f);
		t << fLog->text();
	}

	f.close();
}

// $Log$
// Revision 1.9  2001/12/29 15:44:16  adridg
// Missing progress slots
//
// Revision 1.8  2001/11/25 22:02:57  adridg
// Save/clear the sync log
//
// Revision 1.7  2001/11/18 16:59:55  adridg
// New icons, DCOP changes
//
<commit_msg>Make it compile<commit_after>/* logWidget.cc                         KPilot
**
** Copyright (C) 2001 by Dan Pilone
**
** This file defines the log window widget, which logs
** sync-messages during a HotSync.
*/

/*
** This program 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 2 of the License, or
** (at your option) any later version.
**
** This program 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 this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
** MA 02139, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org.
*/
static const char *logw_id =
	"$Id$";

#include "options.h"

#include <qfile.h>
#include <qlayout.h>
#include <qtextview.h>
#include <qtooltip.h>
#include <qdatetime.h>
#include <qlabel.h>
#include <qpixmap.h>
#include <qtimer.h>
#include <qpushbutton.h>
#include <qhbox.h>
#include <qtextstream.h>
#include <qpainter.h>

#include <kglobal.h>
#include <kstddirs.h>
#include <kprogress.h>
#include <kfiledialog.h>
#include <kmessagebox.h>

#include "logWidget.moc"

LogWidget::LogWidget(QWidget * parent) :
	PilotComponent(parent, "component_log", QString::null),
	DCOPObject("KPilotIface"),
	fLog(0L),
	fShowTime(false),
	fSplash(0L),
	fLabel(0L),
	fProgress(0L)
{
	FUNCTIONSETUP;
	QGridLayout *grid = new QGridLayout(this, 4, 4, SPACING);

	grid->addRowSpacing(0, SPACING);
	grid->addRowSpacing(1, 100);
	grid->addColSpacing(2, 100);
	grid->addRowSpacing(3, SPACING);
	grid->addColSpacing(0, SPACING);
	grid->addColSpacing(3, SPACING);
	grid->setRowStretch(1, 50);
	grid->setColStretch(2, 50);

	fLog = new QTextView(this);
	QToolTip::add(fLog, i18n("<qt>This lists all the messages received "
			"during the current HotSync</qt>"));
	grid->addMultiCellWidget(fLog, 1, 1,1,2);

	fLog->setText(i18n("<qt>HotSync Log</qt>"));

	QHBox *h = new QHBox(this);
	h->setSpacing(SPACING);
	QPushButton *b = new QPushButton(
		i18n("Clear the text of HotSync messages","Clear Log"),
		h);
	QToolTip::add(b,i18n("<qt>Clears the list of messages from the "
		"current HotSync.</qt>"));
	connect(b,SIGNAL(clicked()),this,SLOT(clearLog()));

	b = new QPushButton(i18n("Save Log"),h);
	QToolTip::add(b,i18n("<qt>You can save the list of messages received "
		"during this HotSync to a file (for example for use in a "
		"bug report) by clicking here.</qt>"));
	connect(b,SIGNAL(clicked()),this,SLOT(saveLog()));

	grid->addMultiCellWidget(h,2,2,1,2);

	fLabel = new QLabel(i18n("Sync Progress:"),this);
	grid->addWidget(fLabel,3,1);
	fProgress = new KProgress(0,100,0,KProgress::Horizontal,this);
	QToolTip::add(fProgress,i18n("<qt>The (estimated) percentage "
		"completed in the current HotSync.</qt>"));
	grid->addWidget(fProgress,3,2);

	QString splashPath =
		KGlobal::dirs()->findResource("data",
			"kpilot/kpilot-splash.png");

	if (!splashPath.isEmpty() && QFile::exists(splashPath))
	{
		fLog->hide();
		fLabel->hide();
		fProgress->hide();

		QPixmap splash(splashPath);
		QPainter painter(&splash);
		painter.setPen(QColor(255, 0, 0));

		int textWidth =fontMetrics().width(KPILOT_VERSION) ;
		int textHeight = fontMetrics().height();

#ifdef DEBUG
		DEBUGKPILOT << fname
			<< ": Using text size "
			<< textWidth << "x" << textHeight
			<< endl;
#endif

		painter.fillRect(splash.width() -  28 - textWidth,
			splash.height() - 6 - textHeight - textHeight ,
			textWidth + 6,
			textHeight + 4,
			black);
		painter.drawText(splash.width() -  25 - textWidth,
			splash.height() - 8 - textHeight,
			KPILOT_VERSION);
		fSplash = new QLabel(this);
		fSplash->setPixmap(splash);
		QTimer::singleShot(3000,this,SLOT(hideSplash()));
		grid->addMultiCellWidget(fSplash,1,3,1,2);
	}

	(void) logw_id;
}

void LogWidget::addMessage(const QString & s)
{
	FUNCTIONSETUP;

	if (fShowTime)
	{
		QString t;

		t = QTime::currentTime().toString();
		t.append("  ");
		t.append(s);
		fLog->append(t);
	}
	else
	{
		fLog->append(s);
	}
}

void LogWidget::addError(const QString & s)
{
	FUNCTIONSETUP;

	QString t("<qt>");

	if (fShowTime)
	{

		t = QTime::currentTime().toString();
		t.append("  ");
	}

	t.append(s);
	t.append("</qt>");

	fLog->append(s);
}

void LogWidget::addProgress(const QString &s,int i)
{
	FUNCTIONSETUP;

	logMessage(s);

	if ((i >= 0) && (i <= 100))
	{
		fProgress->setValue(i);
	}
}

void LogWidget::syncDone()
{
	FUNCTIONSETUP;

	addMessage(i18n("HotSync Finished!"));
}

void LogWidget::initialize()
{
	FUNCTIONSETUP;
}

void LogWidget::hideSplash()
{
	FUNCTIONSETUP;

	if (fSplash)
	{
		fSplash->hide();
		KPILOT_DELETE(fSplash);
	}

	fLog->show();
	fLabel->show();
	fProgress->show();
}

/* DCOP */ ASYNC LogWidget::logMessage(QString s)
{
	FUNCTIONSETUP;

	if (fLog)
	{
		QTime t = QTime::currentTime();
		QString s1 = t.toString();

		s1.append("  ");
		s1.append(s);
		fLog->append(s1);
	}
}

/* DCOP */ ASYNC LogWidget::logProgress(QString s, int i)
{
	FUNCTIONSETUP;

	addProgress(s,i);
}

/* slot */ void LogWidget::clearLog()
{
	FUNCTIONSETUP;

	if (fLog)
	{
		fLog->setText(QString::null);
	}
}

/* slot */ void LogWidget::saveLog()
{
	FUNCTIONSETUP;

	bool finished = false;

	while (!finished)
	{
		QString saveFileName = KFileDialog::getSaveFileName(
			QString::null,     /* default */
			"*.log",           /* show log files by default */
			this,
			i18n("Save Log"));

		if (saveFileName.isEmpty()) return;
		if (QFile::exists(saveFileName))
		{
			int r = KMessageBox::warningYesNoCancel(
				this,
				i18n("The file exists. Do you want to "
					"overwrite it?"),
				i18n("File Exists"));
			if (r==KMessageBox::Yes)
			{
				finished=saveFile(saveFileName);
			}

			if (r==KMessageBox::Cancel) return;
		}
		else
		{
			finished=saveFile(saveFileName);
		}
	}
}

bool LogWidget::saveFile(const QString &saveFileName)
{
	FUNCTIONSETUP;

	QFile f(saveFileName);
	if (!f.open(IO_WriteOnly))
	{
		int r = KMessageBox::questionYesNo(this,
			i18n("<qt>Can't open the file "%1" "
				"for writing. Try again?</qt>"),
			i18n("Can't Save"));

		if (r==KMessageBox::Yes) return false;
		return true;
	}
	else
	{
		QTextStream t(&f);
		t << fLog->text();
	}

	f.close();
}

// $Log$
// Revision 1.10  2001/12/31 09:38:09  adridg
// Splash patch by Aaron
//
// Revision 1.9  2001/12/29 15:44:16  adridg
// Missing progress slots
//
// Revision 1.8  2001/11/25 22:02:57  adridg
// Save/clear the sync log
//
// Revision 1.7  2001/11/18 16:59:55  adridg
// New icons, DCOP changes
//
<|endoftext|>


<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_WAIT_FOR_READINESS_HPP_
#define RDB_PROTOCOL_WAIT_FOR_READINESS_HPP_

#include "errors.hpp"
#include <boost/shared_ptr.hpp>

#include "concurrency/interruptor.hpp"

class namespace_interface_t;
class signal_t;

/* `test_for_rdb_table_readiness()` returns `true` if the given namespace is ready for
reading, and `false` otherwise. */
bool test_for_rdb_table_readiness(namespace_interface_t *namespace_if,
                                  signal_t *interruptor)
    THROWS_ONLY(interrupted_exc_t);

#endif /* RDB_PROTOCOL_WAIT_FOR_READINESS_HPP_ */
<commit_msg>Added a MUST_USE on test_for_rdb_table_readiness.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_WAIT_FOR_READINESS_HPP_
#define RDB_PROTOCOL_WAIT_FOR_READINESS_HPP_

#include "errors.hpp"
#include <boost/shared_ptr.hpp>

#include "concurrency/interruptor.hpp"

class namespace_interface_t;
class signal_t;

/* `test_for_rdb_table_readiness()` returns `true` if the given namespace is ready for
reading, and `false` otherwise. */
MUST_USE bool test_for_rdb_table_readiness(namespace_interface_t *namespace_if,
                                           signal_t *interruptor)
    THROWS_ONLY(interrupted_exc_t);

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


<commit_before>//===--------------------- ResourcePressureView.cpp -------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file implements methods in the ResourcePressureView interface.
///
//===----------------------------------------------------------------------===//

#include "ResourcePressureView.h"
#include "llvm/Support/raw_ostream.h"

namespace mca {

using namespace llvm;

void ResourcePressureView::initialize() {
  // Populate the map of resource descriptors.
  unsigned R2VIndex = 0;
  const MCSchedModel &SM = STI.getSchedModel();
  for (unsigned I = 0, E = SM.getNumProcResourceKinds(); I < E; ++I) {
    const MCProcResourceDesc &ProcResource = *SM.getProcResource(I);
    unsigned NumUnits = ProcResource.NumUnits;
    // Skip groups and invalid resources with zero units.
    if (ProcResource.SubUnitsIdxBegin || !NumUnits)
      continue;

    Resource2VecIndex.insert(std::pair<unsigned, unsigned>(I, R2VIndex));
    R2VIndex += ProcResource.NumUnits;
  }

  NumResourceUnits = R2VIndex;
  ResourceUsage.resize(NumResourceUnits * (Source.size() + 1));
  std::fill(ResourceUsage.begin(), ResourceUsage.end(), 0.0);
}

void ResourcePressureView::onInstructionEvent(const HWInstructionEvent &Event) {
  // We're only interested in Issue events.
  if (Event.Type != HWInstructionEvent::Issued)
    return;
  const auto &IssueEvent = static_cast<const HWInstructionIssuedEvent &>(Event);
  unsigned SourceIdx = Event.Index % Source.size();
  for (const std::pair<ResourceRef, double> &Use : IssueEvent.UsedResources) {
    const ResourceRef &RR = Use.first;
    assert(Resource2VecIndex.find(RR.first) != Resource2VecIndex.end());
    unsigned R2VIndex = Resource2VecIndex[RR.first];
    R2VIndex += countTrailingZeros(RR.second);
    ResourceUsage[R2VIndex + NumResourceUnits * SourceIdx] += Use.second;
    ResourceUsage[R2VIndex + NumResourceUnits * Source.size()] += Use.second;
  }
}

static void printColumnNames(raw_string_ostream &OS, const MCSchedModel &SM) {
  for (unsigned I = 1, ResourceIndex = 0, E = SM.getNumProcResourceKinds();
       I < E; ++I) {
    const MCProcResourceDesc &ProcResource = *SM.getProcResource(I);
    unsigned NumUnits = ProcResource.NumUnits;
    // Skip groups and invalid resources with zero units.
    if (ProcResource.SubUnitsIdxBegin || !NumUnits)
      continue;

    if (NumUnits == 1) {
      OS << '[' << ResourceIndex << ']';
      if (ResourceIndex < 10)
        OS << "    ";
      else
        OS << "   ";
    } else {
      for (unsigned J = 0; J < NumUnits; ++J) {
        OS << "[" << ResourceIndex << '.' << J << ']';
        if (ResourceIndex < 10)
          OS << "  ";
        else
          OS << ' ';
      }
    }
    ResourceIndex++;
  }
}

void ResourcePressureView::printResourcePressurePerIteration(
    raw_ostream &OS, unsigned Executions) const {
  std::string Buffer;
  raw_string_ostream TempStream(Buffer);

  TempStream << "\n\nResources:\n";
  const MCSchedModel &SM = STI.getSchedModel();
  for (unsigned I = 1, ResourceIndex = 0, E = SM.getNumProcResourceKinds();
       I < E; ++I) {
    const MCProcResourceDesc &ProcResource = *SM.getProcResource(I);
    unsigned NumUnits = ProcResource.NumUnits;
    // Skip groups and invalid resources with zero units.
    if (ProcResource.SubUnitsIdxBegin || !NumUnits)
      continue;

    for (unsigned J = 0; J < NumUnits; ++J) {
      TempStream << '[' << ResourceIndex;
      if (NumUnits > 1)
        TempStream << '.' << J;
      TempStream << "] - " << ProcResource.Name << '\n';
    }

    ResourceIndex++;
  }

  TempStream << "\n\nResource pressure per iteration:\n";
  printColumnNames(TempStream, SM);
  TempStream << '\n';

  for (unsigned I = 0, E = NumResourceUnits; I < E; ++I) {
    double Usage = ResourceUsage[I + Source.size() * E];
    if (!Usage) {
      TempStream << " -     ";
      continue;
    }

    double Pressure = Usage / Executions;
    // Round to the value to the nearest hundredth and then print it.
    TempStream << format("%.2f", floor((Pressure * 100) + 0.5)/100);
    if (Pressure < 10.0)
      TempStream << "   ";
    else if (Pressure < 100.0)
      TempStream << "  ";
    else
      TempStream << ' ';
  }

  TempStream.flush();
  OS << Buffer;
}

void ResourcePressureView::printResourcePressurePerInstruction(
    raw_ostream &OS, unsigned Executions) const {
  std::string Buffer;
  raw_string_ostream TempStream(Buffer);

  TempStream << "\n\nResource pressure by instruction:\n";
  printColumnNames(TempStream, STI.getSchedModel());
  TempStream << "\tInstructions:\n";

  for (unsigned I = 0, E = Source.size(); I < E; ++I) {
    for (unsigned J = 0; J < NumResourceUnits; ++J) {
      double Usage = ResourceUsage[J + I * NumResourceUnits];
      if (!Usage) {
        TempStream << " -     ";
      } else {
        double Pressure = Usage / Executions;
        if (Pressure < 0.005) {
          TempStream << " -     ";
        } else {
          TempStream << format("%.2f", Pressure);
          if (Pressure < 10.0)
            TempStream << "   ";
          else if (Pressure < 100.0)
            TempStream << "  ";
          else
            TempStream << ' ';
        }
      }
    }

    MCIP.printInst(&Source.getMCInstFromIndex(I), TempStream, "", STI);
    TempStream << '\n';
    TempStream.flush();
    OS << Buffer;
    Buffer = "";
  }
}
} // namespace mca
<commit_msg>[llvm-mca] Simplify code. NFC<commit_after>//===--------------------- ResourcePressureView.cpp -------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file implements methods in the ResourcePressureView interface.
///
//===----------------------------------------------------------------------===//

#include "ResourcePressureView.h"
#include "llvm/Support/raw_ostream.h"

namespace mca {

using namespace llvm;

void ResourcePressureView::initialize() {
  // Populate the map of resource descriptors.
  unsigned R2VIndex = 0;
  const MCSchedModel &SM = STI.getSchedModel();
  for (unsigned I = 0, E = SM.getNumProcResourceKinds(); I < E; ++I) {
    const MCProcResourceDesc &ProcResource = *SM.getProcResource(I);
    unsigned NumUnits = ProcResource.NumUnits;
    // Skip groups and invalid resources with zero units.
    if (ProcResource.SubUnitsIdxBegin || !NumUnits)
      continue;

    Resource2VecIndex.insert(std::pair<unsigned, unsigned>(I, R2VIndex));
    R2VIndex += ProcResource.NumUnits;
  }

  NumResourceUnits = R2VIndex;
  ResourceUsage.resize(NumResourceUnits * (Source.size() + 1));
  std::fill(ResourceUsage.begin(), ResourceUsage.end(), 0.0);
}

void ResourcePressureView::onInstructionEvent(const HWInstructionEvent &Event) {
  // We're only interested in Issue events.
  if (Event.Type != HWInstructionEvent::Issued)
    return;
  const auto &IssueEvent = static_cast<const HWInstructionIssuedEvent &>(Event);
  unsigned SourceIdx = Event.Index % Source.size();
  for (const std::pair<ResourceRef, double> &Use : IssueEvent.UsedResources) {
    const ResourceRef &RR = Use.first;
    assert(Resource2VecIndex.find(RR.first) != Resource2VecIndex.end());
    unsigned R2VIndex = Resource2VecIndex[RR.first];
    R2VIndex += countTrailingZeros(RR.second);
    ResourceUsage[R2VIndex + NumResourceUnits * SourceIdx] += Use.second;
    ResourceUsage[R2VIndex + NumResourceUnits * Source.size()] += Use.second;
  }
}

static void printColumnNames(raw_string_ostream &OS, const MCSchedModel &SM) {
  for (unsigned I = 1, ResourceIndex = 0, E = SM.getNumProcResourceKinds();
       I < E; ++I) {
    const MCProcResourceDesc &ProcResource = *SM.getProcResource(I);
    unsigned NumUnits = ProcResource.NumUnits;
    // Skip groups and invalid resources with zero units.
    if (ProcResource.SubUnitsIdxBegin || !NumUnits)
      continue;

    if (NumUnits == 1) {
      OS << '[' << ResourceIndex << ']';
      if (ResourceIndex < 10)
        OS << "    ";
      else
        OS << "   ";
    } else {
      for (unsigned J = 0; J < NumUnits; ++J) {
        OS << "[" << ResourceIndex << '.' << J << ']';
        if (ResourceIndex < 10)
          OS << "  ";
        else
          OS << ' ';
      }
    }
    ResourceIndex++;
  }
}

static void printResourcePressure(raw_string_ostream &OS, double Pressure) {
  if (!Pressure) {
    OS << " -     ";
    return;
  }

  // Round to the value to the nearest hundredth and then print it.
  OS << format("%.2f", floor((Pressure * 100) + 0.5)/100);
  if (Pressure < 10.0)
    OS << "   ";
  else if (Pressure < 100.0)
    OS << "  ";
  else
    OS << ' ';
}

void ResourcePressureView::printResourcePressurePerIteration(
    raw_ostream &OS, unsigned Executions) const {
  std::string Buffer;
  raw_string_ostream TempStream(Buffer);

  TempStream << "\n\nResources:\n";
  const MCSchedModel &SM = STI.getSchedModel();
  for (unsigned I = 1, ResourceIndex = 0, E = SM.getNumProcResourceKinds();
       I < E; ++I) {
    const MCProcResourceDesc &ProcResource = *SM.getProcResource(I);
    unsigned NumUnits = ProcResource.NumUnits;
    // Skip groups and invalid resources with zero units.
    if (ProcResource.SubUnitsIdxBegin || !NumUnits)
      continue;

    for (unsigned J = 0; J < NumUnits; ++J) {
      TempStream << '[' << ResourceIndex;
      if (NumUnits > 1)
        TempStream << '.' << J;
      TempStream << "] - " << ProcResource.Name << '\n';
    }

    ResourceIndex++;
  }

  TempStream << "\n\nResource pressure per iteration:\n";
  printColumnNames(TempStream, SM);
  TempStream << '\n';

  for (unsigned I = 0, E = NumResourceUnits; I < E; ++I) {
    double Usage = ResourceUsage[I + Source.size() * E];
    printResourcePressure(TempStream, Usage / Executions);
  }

  TempStream.flush();
  OS << Buffer;
}

void ResourcePressureView::printResourcePressurePerInstruction(
    raw_ostream &OS, unsigned Executions) const {
  std::string Buffer;
  raw_string_ostream TempStream(Buffer);

  TempStream << "\n\nResource pressure by instruction:\n";
  printColumnNames(TempStream, STI.getSchedModel());
  TempStream << "\tInstructions:\n";

  for (unsigned I = 0, E = Source.size(); I < E; ++I) {
    for (unsigned J = 0; J < NumResourceUnits; ++J) {
      double Usage = ResourceUsage[J + I * NumResourceUnits];
      printResourcePressure(TempStream, Usage / Executions);
    }

    MCIP.printInst(&Source.getMCInstFromIndex(I), TempStream, "", STI);
    TempStream << '\n';
    TempStream.flush();
    OS << Buffer;
    Buffer = "";
  }
}
} // namespace mca
<|endoftext|>


<commit_before>// $Id: assignShiftProcessor.C,v 1.20 2000/10/02 18:58:21 amoll Exp $

#include<BALL/NMR/assignShiftProcessor.h>
#include<BALL/KERNEL/atom.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/STRUCTURE/fragmentDB.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/SYSTEM/path.h>

using namespace std;

namespace BALL
{

	bool AssignShiftProcessor::start()
	{
		if (!valid_)
		{
			Log.error() << "AssignShiftProcessor: shift data were not assigned" << endl;
			return false;
		}

		// ----------transforming the names from STAR-FILE-STANDARD to PDB------
		FragmentDB frag_db;
		if (!frag_db.getNamingStandards().has("Star-PDB"))
		{
			 Log.error() << "AssignShiftProcessor::start: "
									 << "no appropriate map found for name conversion" << endl;
			return false;
		}

		StringHashMap<String>* map = frag_db.getNamingStandards()["Star-PDB"];

		// ---------------------read translate table ------------------------
		Path path;
		ifstream tableFile(path.find("NMR/translate.dat").c_str(), ios::in);
		if (!tableFile)
		{
			Log.error() << "AssignShiftProcessor: translate.dat not found:" << endl;
			return false;
		}

		StringHashMap<String> transform_table;
		String name;

		do
		{
			String entry;
			tableFile >> name;
			tableFile >> entry;
			transform_table[name] = entry;
		}
		while (name != "END");

		tableFile.close();

		// ----------------------read the shiftdata ------------------------
		for (Position atom_pos = 0; atom_pos < atom_data_.size() ; atom_pos++)
		{
			// normalize the atom name to reflect the PDB standard
			String residue_name = atom_data_[atom_pos]->residueLabel;
			String atom_name    = atom_data_[atom_pos]->atomName;
			bool normalized = false;
			if (map != 0)
			{
				normalized = frag_db.normalize_names.matchName(residue_name, atom_name, map);
			}

			const String entry(residue_name + ":" + atom_name);

			if (!normalized && !transform_table.has(entry))
			{
				Log.warn() << "AssignShiftProcessor::start: could not convert atom name " << entry << endl;
			}

			String prefix(atom_data_[atom_pos]->residueSeqCode);
			prefix += residue_name;
			prefix += ":";

			if (!transform_table.has(entry))
			{
				String full_name(prefix);
				full_name += atom_name;
				shift_table_[full_name] = atom_data_[atom_pos]->shiftValue;
				//cout << full_name << " " << atom_data_[atom_pos]->shiftValue << endl;
				continue;
			}

			// from now on getting the transformed names for atoms
			if (!transform_table[entry].has('/'))
			{
				String full_name(residue_name);
				full_name += transform_table[entry];
				shift_table_[full_name] = atom_data_[atom_pos]->shiftValue;
				//cout << full_name << " " << atom_data_[atom_pos]->shiftValue << endl;
				continue;
			}

			// adding multiple atoms for one entry
			std::vector<String> tokens;
			Size size = transform_table[entry].split(tokens, "/");
			for (Position wordpos = 0; wordpos < size ; wordpos++)
			{
				String full_name(atom_data_[atom_pos]->residueSeqCode);
				full_name += tokens[wordpos];
				shift_table_[full_name] = atom_data_[atom_pos]->shiftValue;
				//cout << full_name << " " << atom_data_[atom_pos]->shiftValue << endl;
			}
		}

		molecule_ = 0;
		return true;
	}

	Processor::Result AssignShiftProcessor::operator()(Composite& object)
	{
		//-----------------switching by the type of given object--------------------------
		if (RTTI::isKindOf<Molecule>(object))
		{
			if (molecule_ == 0)
			{
				molecule_ = RTTI::castTo<Molecule>(object);
				number_of_fragment_ = 0;
				return Processor::CONTINUE;
			}
			else
			{
				Log.error() << "AssignShiftProcessor: a second molecule was given" << endl;
				return Processor::BREAK;
			}
		}

		if (RTTI::isKindOf<Fragment>(object))
		{
			number_of_fragment_++;
			return Processor::CONTINUE;
		}

		if (!RTTI::isKindOf<Atom>(object))
		{
			return Processor::CONTINUE;
		}

		// --------------------set the shift value--------------------------------------------
		Atom* patom = RTTI::castTo<Atom>(object);

		String full_name;
		if (patom->getResidue() != 0)
		{
			full_name = patom->getResidue()->getID();
		}
		else
		{
			full_name = String(number_of_fragment_);
		}
		full_name += patom->getFragment()->getName();
		full_name += ":";
		full_name += patom->getName();

		if (patom->hasProperty(ShiftModule::PROPERTY__SHIFT))
		{
			Log.error() << "AssignShiftProcessor: atom contains already shift data: " << full_name << endl;
			patom->clearProperty(ShiftModule::PROPERTY__SHIFT);
		}

		if (shift_table_.has(full_name))
		{
			patom->setProperty(ShiftModule::PROPERTY__SHIFT, shift_table_[full_name]);
			Log.info() << "atom found " << full_name << endl;
		}
		else
		{
			Log.info() << "AssignShiftProcessor: entry not found: " << full_name << endl;
		}

		return Processor::CONTINUE;
	}

#	ifdef BALL_NO_INLINE_FUNCTIONS
#		include <BALL/NMR/assignShiftProcessor.iC>
#	endif

}//namespace BALL
<commit_msg>fixed: variable names now according to coding style<commit_after>// $Id: assignShiftProcessor.C,v 1.21 2000/10/03 02:04:12 amoll Exp $

#include <BALL/NMR/assignShiftProcessor.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/STRUCTURE/fragmentDB.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/SYSTEM/path.h>

using namespace std;

namespace BALL
{

	bool AssignShiftProcessor::start()
	{
		if (!valid_)
		{
			Log.error() << "AssignShiftProcessor: shift data were not assigned" << endl;
			return false;
		}

		// ----------transforming the names from STAR-FILE-STANDARD to PDB------
		FragmentDB frag_db;
		if (!frag_db.getNamingStandards().has("Star-PDB"))
		{
			 Log.error() << "AssignShiftProcessor::start: "
									 << "no appropriate map found for name conversion" << endl;
			return false;
		}

		StringHashMap<String>* map = frag_db.getNamingStandards()["Star-PDB"];

		// ---------------------read translate table ------------------------
		Path path;
		ifstream tableFile(path.find("NMR/translate.dat").c_str(), ios::in);
		if (!tableFile)
		{
			Log.error() << "AssignShiftProcessor: translate.dat not found:" << endl;
			return false;
		}

		StringHashMap<String> transform_table;
		String name;

		do
		{
			String entry;
			tableFile >> name;
			tableFile >> entry;
			transform_table[name] = entry;
		}
		while (name != "END");

		tableFile.close();

		// ----------------------read the shiftdata ------------------------
		for (Position atom_pos = 0; atom_pos < atom_data_.size() ; atom_pos++)
		{
			// normalize the atom name to reflect the PDB standard
			String residue_name = atom_data_[atom_pos]->residue_label;
			String atom_name    = atom_data_[atom_pos]->atom_name;
			bool normalized = false;
			if (map != 0)
			{
				normalized = frag_db.normalize_names.matchName(residue_name, atom_name, map);
			}

			const String entry(residue_name + ":" + atom_name);

			if (!normalized && !transform_table.has(entry))
			{
				Log.warn() << "AssignShiftProcessor::start: could not convert atom name " << entry << endl;
			}

			String prefix(atom_data_[atom_pos]->residue_seq_code);
			prefix += residue_name;
			prefix += ":";

			if (!transform_table.has(entry))
			{
				String full_name(prefix);
				full_name += atom_name;
				shift_table_[full_name] = atom_data_[atom_pos]->shift_value;
				//cout << full_name << " " << atom_data_[atom_pos]->shift_value << endl;
				continue;
			}

			// from now on getting the transformed names for atoms
			if (!transform_table[entry].has('/'))
			{
				String full_name(residue_name);
				full_name += transform_table[entry];
				shift_table_[full_name] = atom_data_[atom_pos]->shift_value;
				//cout << full_name << " " << atom_data_[atom_pos]->shift_value << endl;
				continue;
			}

			// adding multiple atoms for one entry
			std::vector<String> tokens;
			Size size = transform_table[entry].split(tokens, "/");
			for (Position wordpos = 0; wordpos < size ; wordpos++)
			{
				String full_name(atom_data_[atom_pos]->residue_seq_code);
				full_name += tokens[wordpos];
				shift_table_[full_name] = atom_data_[atom_pos]->shift_value;
				//cout << full_name << " " << atom_data_[atom_pos]->shift_value << endl;
			}
		}

		molecule_ = 0;
		return true;
	}

	Processor::Result AssignShiftProcessor::operator()(Composite& object)
	{
		//-----------------switching by the type of given object--------------------------
		if (RTTI::isKindOf<Molecule>(object))
		{
			if (molecule_ == 0)
			{
				molecule_ = RTTI::castTo<Molecule>(object);
				number_of_fragment_ = 0;
				return Processor::CONTINUE;
			}
			else
			{
				Log.error() << "AssignShiftProcessor: a second molecule was given" << endl;
				return Processor::BREAK;
			}
		}

		if (RTTI::isKindOf<Fragment>(object))
		{
			number_of_fragment_++;
			return Processor::CONTINUE;
		}

		if (!RTTI::isKindOf<Atom>(object))
		{
			return Processor::CONTINUE;
		}

		// --------------------set the shift value--------------------------------------------
		Atom* patom = RTTI::castTo<Atom>(object);

		String full_name;
		if (patom->getResidue() != 0)
		{
			full_name = patom->getResidue()->getID();
		}
		else
		{
			full_name = String(number_of_fragment_);
		}
		full_name += patom->getFragment()->getName();
		full_name += ":";
		full_name += patom->getName();

		if (patom->hasProperty(ShiftModule::PROPERTY__SHIFT))
		{
			Log.error() << "AssignShiftProcessor: atom contains already shift data: " << full_name << endl;
			patom->clearProperty(ShiftModule::PROPERTY__SHIFT);
		}

		if (shift_table_.has(full_name))
		{
			patom->setProperty(ShiftModule::PROPERTY__SHIFT, shift_table_[full_name]);
			Log.info() << "atom found " << full_name << endl;
		}
		else
		{
			Log.info() << "AssignShiftProcessor: entry not found: " << full_name << endl;
		}

		return Processor::CONTINUE;
	}

#	ifdef BALL_NO_INLINE_FUNCTIONS
#		include <BALL/NMR/assignShiftProcessor.iC>
#	endif

}//namespace BALL
<|endoftext|>


<commit_before>#include "triprism.h"
#include <iostream>
#include <math.h>

TriPrism::TriPrism(int state, double *pt1, double *pt2, double *pt3, double l) : Shape(state)
{

  this->l   = l;
  this->pt1 = new double[3];
  this->pt2 =new double[3];
  this->pt3 = new double[3];
  this->pt1[0] = pt1[0]; this->pt1[1] = pt1[1]; this->pt1[2] = pt1[2];
  this->pt2[0] = pt2[0]; this->pt2[1] = pt2[1]; this->pt2[2] = pt2[2];
  this->pt3[0] = pt3[0]; this->pt3[1] = pt3[1]; this->pt3[2] = pt3[2];

  double *p1 = new double[3];
  double *p2 = new double[3];

  p1[0] = pt3[0]; p1[1]=pt3[1]; p1[2]=pt3[2];
  p2[0] = pt2[0]; p2[1]=pt1[1]; p2[2]=pt2[2]+l;

  this->boundingBox = new BoundingBox(p1,p2);
}

TriPrism::~TriPrism(){
 delete [] pt1;
 delete [] pt2;
 delete [] pt3;
}

bool TriPrism::IsInside(double *pt)
{
  // Different to the "same side" methof from the c# code, should be faster this way
  bool isInside = false;
  // Create vectors
  double *v0= new double[3];
  double *v1= new double[3];
  double *v2= new double[3];

  v0[0] = pt2[0] - pt3[0];
  v0[1] = pt2[1] - pt3[1];
  v0[2] = pt2[2] - pt3[2];

  v1[0] = pt1[0] - pt3[0];
  v1[1] = pt1[1] - pt3[1];
  v1[2] = pt1[2] - pt3[2];

  v2[0] = pt[0] - pt3[0];
  v2[1] = pt[1] - pt3[1];
  v2[2] = pt[2] - pt3[2];

  // Compute dot products
  double dot00;
  dot00 = (v0[0]*v0[0]) + (v0[1]*v0[1]) + (v0[2]*v0[2]);
  double dot01;
  dot01 = (v0[0]*v1[0]) + (v0[1]*v1[1]) + (v0[2]*v1[2]);
  double dot02;
  dot02 = (v0[0]*v2[0]) + (v0[1]*v2[1]) + (v0[2]*v2[2]);
  double dot11;
  dot11 = (v1[0]*v1[0]) + (v1[1]*v1[1]) + (v1[2]*v1[2]);
  double dot12;
  dot12 = (v1[0]*v2[0]) + (v1[1]*v2[1]) + (v1[2]*v2[2]);
  double u;
  double v;
 // if(((dot00*dot11)-(dot01*dot01))==0)
  //  {
  //    u=-1;
  //    v=-1;
  //  }
  //else{
  double invDenom = 1 / ( (dot00*dot11)-(dot01*dot01) );
  //std::cout << invDenom << std::endl;
  u = ((dot11*dot02)-(dot01*dot12))*invDenom;
 // std::cout << u << std::endl;
  v = ((dot00*dot12)-(dot01*dot02))*invDenom;
 // std::cout << v << std::endl;
 //}
 if( (u>=0) && (v>=0) && ((u+v)<1) && (pt[2]<=(pt1[2]+l)))
  {
    isInside = true;
  }

 delete [] v0;
 delete [] v1;
 delete [] v2;
//delete v0,v1,v2,dot00,dot01,dot01,dot11,dot12,invDenom,u,v;

  return isInside;
}
<commit_msg>+ updated incorrect bounding box in TriPrism.cpp<commit_after>#include "triprism.h"
#include <iostream>
#include <math.h>

TriPrism::TriPrism(int state, double *pt1, double *pt2, double *pt3, double l) : Shape(state)
{

  this->l   = l;
  this->pt1 = new double[3];
  this->pt2 =new double[3];
  this->pt3 = new double[3];
  this->pt1[0] = pt1[0]; this->pt1[1] = pt1[1]; this->pt1[2] = pt1[2];
  this->pt2[0] = pt2[0]; this->pt2[1] = pt2[1]; this->pt2[2] = pt2[2];
  this->pt3[0] = pt3[0]; this->pt3[1] = pt3[1]; this->pt3[2] = pt3[2];

  double *p1 = new double[3];
  double *p2 = new double[3];

  p1[0] = std::min(pt1[0],std::min(pt2[0],pt3[0])); p1[1]=std::min(pt1[1],std::min(pt2[1],pt3[1])); p1[2]=std::min(pt1[2],std::min(pt2[2],pt3[2]));
  p2[0] = std::max(pt1[0],std::max(pt2[0],pt3[0])); p2[1]=std::max(pt1[1],std::max(pt2[1],pt3[1])); p2[2]=p1[2]+l;

  this->boundingBox = new BoundingBox(p1,p2);
}

TriPrism::~TriPrism(){
 delete [] pt1;
 delete [] pt2;
 delete [] pt3;
}

bool TriPrism::IsInside(double *pt)
{
  // barycentric method http://www.blackpawn.com/texts/pointinpoly/
  // Create vectors
  double v0[3];
  double v1[3];
  double v2[3];

  v0[0] = pt2[0] - pt3[0];
  v0[1] = pt2[1] - pt3[1];
  v0[2] = pt2[2] - pt3[2];

  v1[0] = pt1[0] - pt3[0];
  v1[1] = pt1[1] - pt3[1];
  v1[2] = pt1[2] - pt3[2];

  v2[0] = pt[0] - pt3[0];
  v2[1] = pt[1] - pt3[1];
  v2[2] = pt[2] - pt3[2];

  // Compute dot products
  double dot00;
  dot00 = (v0[0]*v0[0]) + (v0[1]*v0[1]) + (v0[2]*v0[2]);
  double dot01;
  dot01 = (v0[0]*v1[0]) + (v0[1]*v1[1]) + (v0[2]*v1[2]);
  double dot02;
  dot02 = (v0[0]*v2[0]) + (v0[1]*v2[1]) + (v0[2]*v2[2]);
  double dot11;
  dot11 = (v1[0]*v1[0]) + (v1[1]*v1[1]) + (v1[2]*v1[2]);
  double dot12;
  dot12 = (v1[0]*v2[0]) + (v1[1]*v2[1]) + (v1[2]*v2[2]);
  double u;
  double v;
  double invDenom = 1 / ( (dot00*dot11)-(dot01*dot01) );
  u = ((dot11*dot02)-(dot01*dot12))*invDenom;
  v = ((dot00*dot12)-(dot01*dot02))*invDenom;

  return ( (u>=0) && (v>=0) && ((u+v)<1) && (pt[2]<=(pt1[2]+l)));
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright 2011-2013 The University of North Carolina at Chapel Hill
 *  All rights reserved.
 *
 *  Licensed under the MADAI Software License. You may obtain a copy of
 *  this license at
 *
 *         https://madai-public.cs.unc.edu/visualization/software-license/
 *
 *  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.
 *
 *=========================================================================*/

/**
ACKNOWLEDGMENTS:
  This software was written in 2012-2013 by Hal Canary
  <cs.unc.edu/~hal>, based off of the MADAIEmulator program (Copyright
  2009-2012 Duke University) by C.Coleman-Smith <cec24@phy.duke.edu>
  in 2010-2012 while working for the MADAI project <http://madai.us/>.
*/

#include <iostream> // cout, cin
#include <fstream> // ifstream, ofstream
#include <cstring> // strcmp, strlen

#include "ApplicationUtilities.h"
#include "GaussianProcessEmulator.h"
#include "GaussianProcessEmulatorDirectoryReader.h"
#include "GaussianProcessEmulatorSingleFileReader.h"
#include "GaussianProcessEmulatorSingleFileWriter.h"
#include "RuntimeParameterFileReader.h"
#include "Paths.h"
#include "Defaults.h"

using madai::Paths;

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

  if ( argc < 2 ) {
    std::cerr
      << "Usage:\n"
      << "    " << argv[0] << " <StatisticsDirectory>\n"
      << "\n"
      << "This loads the model data and PCA information computed with\n"
      << "madai_pca_decompose and performs a refined training of the emulator.\n"
      << "It stores the results in <StatisticsDirectory>" << Paths::SEPARATOR
      << Paths::EMULATOR_STATE_FILE << "\n"
      << "\n"
      << "<StatisticsDirectory> is the directory in which all \n"
      << "statistics data are stored. It contains the parameter file "
      << Paths::RUNTIME_PARAMETER_FILE << "\n"
      << "\n"
      << "Format of entries in " << Paths::RUNTIME_PARAMETER_FILE
      << ":\n\n"
      << "MODEL_OUTPUT_DIRECTORY <value> (default: "
      << madai::Defaults::MODEL_OUTPUT_DIRECTORY << ")\n"
      << "EXPERIMENTAL_RESULTS_FILE <value> (default: "
      << madai::Defaults::EXPERIMENTAL_RESULTS_FILE << ")\n"
      << "PCA_FRACTION_RESOLVING_POWER <value> (default: 0.95)\n"
      << "EMULATOR_COVARIANCE_FUNCTION <value> (default: "
      << madai::Defaults::EMULATOR_COVARIANCE_FUNCTION << ")\n"
      << "EMULATOR_REGRESSION_ORDER <value> (default: "
      << madai::Defaults::EMULATOR_REGRESSION_ORDER << ")\n"
      << "READER_VERBOSE <value> (default: false)\n"
      << "VERBOSE <value> (default: false)\n";

    return EXIT_FAILURE;
  }
  std::string statisticsDirectory( argv[1] );
  madai::EnsurePathSeparatorAtEnd( statisticsDirectory );

  madai::RuntimeParameterFileReader settings;
  std::string settingsFile = statisticsDirectory + madai::Paths::RUNTIME_PARAMETER_FILE;
  if ( !settings.ParseFile( settingsFile ) ) {
    std::cerr << "Could not open runtime parameter file '" << settingsFile << "'\n";
    return EXIT_FAILURE;
  }

  std::string modelOutputDirectory =
    madai::GetModelOutputDirectory( statisticsDirectory, settings );
  std::string experimentalResultsFile =
    madai::GetExperimentalResultsFile( statisticsDirectory, settings );

  std::string covarianceFunctionString = settings.GetOption(
      "EMULATOR_COVARIANCE_FUNCTION",
      madai::Defaults::EMULATOR_COVARIANCE_FUNCTION);

  madai::GaussianProcessEmulator::CovarianceFunctionType emulatorCovarianceFunction;
  if ( covarianceFunctionString == "POWER_EXPONENTIAL_FUNCTION" ) {
    emulatorCovarianceFunction = madai::GaussianProcessEmulator::POWER_EXPONENTIAL_FUNCTION;
  } else if ( covarianceFunctionString == "SQUARE_EXPONENTIAL_FUNCTION" ) {
    emulatorCovarianceFunction = madai::GaussianProcessEmulator::SQUARE_EXPONENTIAL_FUNCTION;
  } else if ( covarianceFunctionString == "MATERN_32_FUNCTION" ) {
    emulatorCovarianceFunction = madai::GaussianProcessEmulator::MATERN_32_FUNCTION;
  } else if ( covarianceFunctionString == "MATERN_52_FUNCTION" ) {
    emulatorCovarianceFunction = madai::GaussianProcessEmulator::MATERN_52_FUNCTION;
  } else {
    std::cerr << "Unrecognized covariance function '" << covarianceFunctionString << "'\n";
    return EXIT_FAILURE;
  }

  int emulatorRegressionOrder = settings.GetOptionAsInt(
    "EMULATOR_REGRESSION_ORDER", madai::Defaults::EMULATOR_REGRESSION_ORDER);

  double emulatorNugget = settings.GetOptionAsDouble(
    "EMULATOR_NUGGET", madai::Defaults::EMULATOR_NUGGET);

  double emulatorAmplitude = settings.GetOptionAsDouble(
    "EMULATOR_AMPLITUDE", madai::Defaults::EMULATOR_AMPLITUDE);

  double emulatorScale = settings.GetOptionAsDouble(
    "EMULATOR_SCALE", madai::Defaults::EMULATOR_SCALE);

  std::string emulatorTrainingRigor = settings.GetOption(
    "EMULATOR_TRAINING_RIGOR",  madai::Defaults::EMULATOR_TRAINING_RIGOR );
  std::transform( emulatorTrainingRigor.begin(), emulatorTrainingRigor.end(),
                  emulatorTrainingRigor.begin(), ::tolower );

  bool readerVerbose = settings.GetOptionAsBool(
      "READER_VERBOSE", madai::Defaults::READER_VERBOSE );

  madai::GaussianProcessEmulator gpe;
  madai::GaussianProcessEmulatorDirectoryReader directoryReader;
  directoryReader.SetVerbose( readerVerbose );

  if ( !directoryReader.LoadTrainingData( &gpe,
                                          modelOutputDirectory,
                                          statisticsDirectory,
                                          experimentalResultsFile ) ) {
    std::cerr << "Error loading training data.\n";
    return EXIT_FAILURE;
  }

  if ( !directoryReader.LoadPCA( &gpe, statisticsDirectory ) ) {
    std::cerr << "Error loading PCA data.\n";
    return EXIT_FAILURE;
  }
  std::string outputFileName = statisticsDirectory + madai::Paths::EMULATOR_STATE_FILE;

  // Switch between full and basic training
  if ( emulatorTrainingRigor == "full" ) {
    if (! gpe.Train( emulatorCovarianceFunction,
                     emulatorRegressionOrder ) ) {
      std::cerr << "Error while performing full emulator training.\n";
      return EXIT_FAILURE;
    }
  } else { /* Basic training */
    if (! gpe.BasicTraining( emulatorCovarianceFunction,
                             emulatorRegressionOrder,
                             emulatorNugget,
                             emulatorAmplitude,
                             emulatorScale ) ) {
      std::cerr << "Error while performing basic emulator training\n";
      return EXIT_FAILURE;
    }
  }

  std::ofstream os( outputFileName.c_str() );

  if ( !os.good() ) {
    std::cerr << "Could not open emulator state file '" << outputFileName
              << "' for writing.\n";
    return EXIT_FAILURE;
  }

  madai::GaussianProcessEmulatorSingleFileWriter singleFileWriter;
  singleFileWriter.Write( &gpe, os );

  if ( settings.GetOptionAsBool( "VERBOSE", madai::Defaults::VERBOSE ) ) {
    std::cout << "Emulator training succeeded.\n";
    std::cout << "Wrote emulator state file '" << outputFileName << "'.\n";
  }

  return EXIT_SUCCESS;
}
<commit_msg>Added settings to usage message<commit_after>/*=========================================================================
 *
 *  Copyright 2011-2013 The University of North Carolina at Chapel Hill
 *  All rights reserved.
 *
 *  Licensed under the MADAI Software License. You may obtain a copy of
 *  this license at
 *
 *         https://madai-public.cs.unc.edu/visualization/software-license/
 *
 *  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.
 *
 *=========================================================================*/

/**
ACKNOWLEDGMENTS:
  This software was written in 2012-2013 by Hal Canary
  <cs.unc.edu/~hal>, based off of the MADAIEmulator program (Copyright
  2009-2012 Duke University) by C.Coleman-Smith <cec24@phy.duke.edu>
  in 2010-2012 while working for the MADAI project <http://madai.us/>.
*/

#include <iostream> // cout, cin
#include <fstream> // ifstream, ofstream
#include <cstring> // strcmp, strlen

#include "ApplicationUtilities.h"
#include "GaussianProcessEmulator.h"
#include "GaussianProcessEmulatorDirectoryReader.h"
#include "GaussianProcessEmulatorSingleFileReader.h"
#include "GaussianProcessEmulatorSingleFileWriter.h"
#include "RuntimeParameterFileReader.h"
#include "Paths.h"
#include "Defaults.h"

using madai::Paths;

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

  if ( argc < 2 ) {
    std::cerr
      << "Usage:\n"
      << "    " << argv[0] << " <StatisticsDirectory>\n"
      << "\n"
      << "This loads the model data and PCA information computed with\n"
      << "madai_pca_decompose and performs a refined training of the emulator.\n"
      << "It stores the results in <StatisticsDirectory>" << Paths::SEPARATOR
      << Paths::EMULATOR_STATE_FILE << "\n"
      << "\n"
      << "<StatisticsDirectory> is the directory in which all \n"
      << "statistics data are stored. It contains the parameter file "
      << Paths::RUNTIME_PARAMETER_FILE << "\n"
      << "\n"
      << "Format of entries in " << Paths::RUNTIME_PARAMETER_FILE
      << ":\n\n"
      << "MODEL_OUTPUT_DIRECTORY <value> (default: "
      << madai::Defaults::MODEL_OUTPUT_DIRECTORY << ")\n"
      << "EXPERIMENTAL_RESULTS_FILE <value> (default: "
      << madai::Defaults::EXPERIMENTAL_RESULTS_FILE << ")\n"
      << "PCA_FRACTION_RESOLVING_POWER <value> (default: 0.95)\n"
      << "EMULATOR_COVARIANCE_FUNCTION <value> (default: "
      << madai::Defaults::EMULATOR_COVARIANCE_FUNCTION << ")\n"
      << "EMULATOR_REGRESSION_ORDER <value> (default: "
      << madai::Defaults::EMULATOR_REGRESSION_ORDER << ")\n"
      << "EMULATOR_NUGGET <value> (default: "
      << madai::Defaults::EMULATOR_NUGGET << ")\n"
      << "EMULATOR_AMPLITUDE <value> (default: "
      << madai::Defaults::EMULATOR_AMPLITUDE << ")\n"
      << "EMULATOR_SCALE <value> (default: "
      << madai::Defaults::EMULATOR_SCALE << ")\n"
      << "READER_VERBOSE <value> (default: "
      << madai::Defaults::READER_VERBOSE << ")\n"
      << "VERBOSE <value> (default: "
      << madai::Defaults::VERBOSE << ")\n";

    return EXIT_FAILURE;
  }
  std::string statisticsDirectory( argv[1] );
  madai::EnsurePathSeparatorAtEnd( statisticsDirectory );

  madai::RuntimeParameterFileReader settings;
  std::string settingsFile = statisticsDirectory + madai::Paths::RUNTIME_PARAMETER_FILE;
  if ( !settings.ParseFile( settingsFile ) ) {
    std::cerr << "Could not open runtime parameter file '" << settingsFile << "'\n";
    return EXIT_FAILURE;
  }

  std::string modelOutputDirectory =
    madai::GetModelOutputDirectory( statisticsDirectory, settings );
  std::string experimentalResultsFile =
    madai::GetExperimentalResultsFile( statisticsDirectory, settings );

  std::string covarianceFunctionString = settings.GetOption(
      "EMULATOR_COVARIANCE_FUNCTION",
      madai::Defaults::EMULATOR_COVARIANCE_FUNCTION);

  madai::GaussianProcessEmulator::CovarianceFunctionType emulatorCovarianceFunction;
  if ( covarianceFunctionString == "POWER_EXPONENTIAL_FUNCTION" ) {
    emulatorCovarianceFunction = madai::GaussianProcessEmulator::POWER_EXPONENTIAL_FUNCTION;
  } else if ( covarianceFunctionString == "SQUARE_EXPONENTIAL_FUNCTION" ) {
    emulatorCovarianceFunction = madai::GaussianProcessEmulator::SQUARE_EXPONENTIAL_FUNCTION;
  } else if ( covarianceFunctionString == "MATERN_32_FUNCTION" ) {
    emulatorCovarianceFunction = madai::GaussianProcessEmulator::MATERN_32_FUNCTION;
  } else if ( covarianceFunctionString == "MATERN_52_FUNCTION" ) {
    emulatorCovarianceFunction = madai::GaussianProcessEmulator::MATERN_52_FUNCTION;
  } else {
    std::cerr << "Unrecognized covariance function '" << covarianceFunctionString << "'\n";
    return EXIT_FAILURE;
  }

  int emulatorRegressionOrder = settings.GetOptionAsInt(
    "EMULATOR_REGRESSION_ORDER", madai::Defaults::EMULATOR_REGRESSION_ORDER);

  double emulatorNugget = settings.GetOptionAsDouble(
    "EMULATOR_NUGGET", madai::Defaults::EMULATOR_NUGGET);

  double emulatorAmplitude = settings.GetOptionAsDouble(
    "EMULATOR_AMPLITUDE", madai::Defaults::EMULATOR_AMPLITUDE);

  double emulatorScale = settings.GetOptionAsDouble(
    "EMULATOR_SCALE", madai::Defaults::EMULATOR_SCALE);

  std::string emulatorTrainingRigor = settings.GetOption(
    "EMULATOR_TRAINING_RIGOR",  madai::Defaults::EMULATOR_TRAINING_RIGOR );
  std::transform( emulatorTrainingRigor.begin(), emulatorTrainingRigor.end(),
                  emulatorTrainingRigor.begin(), ::tolower );

  bool readerVerbose = settings.GetOptionAsBool(
      "READER_VERBOSE", madai::Defaults::READER_VERBOSE );

  madai::GaussianProcessEmulator gpe;
  madai::GaussianProcessEmulatorDirectoryReader directoryReader;
  directoryReader.SetVerbose( readerVerbose );

  if ( !directoryReader.LoadTrainingData( &gpe,
                                          modelOutputDirectory,
                                          statisticsDirectory,
                                          experimentalResultsFile ) ) {
    std::cerr << "Error loading training data.\n";
    return EXIT_FAILURE;
  }

  if ( !directoryReader.LoadPCA( &gpe, statisticsDirectory ) ) {
    std::cerr << "Error loading PCA data.\n";
    return EXIT_FAILURE;
  }
  std::string outputFileName = statisticsDirectory + madai::Paths::EMULATOR_STATE_FILE;

  // Switch between full and basic training
  if ( emulatorTrainingRigor == "full" ) {
    if (! gpe.Train( emulatorCovarianceFunction,
                     emulatorRegressionOrder ) ) {
      std::cerr << "Error while performing full emulator training.\n";
      return EXIT_FAILURE;
    }
  } else { /* Basic training */
    if (! gpe.BasicTraining( emulatorCovarianceFunction,
                             emulatorRegressionOrder,
                             emulatorNugget,
                             emulatorAmplitude,
                             emulatorScale ) ) {
      std::cerr << "Error while performing basic emulator training\n";
      return EXIT_FAILURE;
    }
  }

  std::ofstream os( outputFileName.c_str() );

  if ( !os.good() ) {
    std::cerr << "Could not open emulator state file '" << outputFileName
              << "' for writing.\n";
    return EXIT_FAILURE;
  }

  madai::GaussianProcessEmulatorSingleFileWriter singleFileWriter;
  singleFileWriter.Write( &gpe, os );

  if ( settings.GetOptionAsBool( "VERBOSE", madai::Defaults::VERBOSE ) ) {
    std::cout << "Emulator training succeeded.\n";
    std::cout << "Wrote emulator state file '" << outputFileName << "'.\n";
  }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before><commit_msg>Brake internal, authenticated cluster foxx requests again so we don't break the normal usecases<commit_after><|endoftext|>


<commit_before>/*
 * Simple implementation of shared_ptr.
 * Below code is non thread safe.
 *
 * (c) 2015 Raghavendra Nayak, All Rights Reserved.
 * http://www.openguru.com/
 */

#include <iostream>

namespace my {
    template <class T>
    class shared_ptr {
        T* ptr;
        int* ref_count;

        /**
         * Initializes the ref count used for tracking the usage.
         */
        void initialize_ref_count() {
            if (ref_count != nullptr)
                return;
            try {
                ref_count = new int;
                *ref_count = 1;
            }
            catch (std::bad_alloc e) {
                std::cerr << "Memory allocation error: " << e.what();
            }
        }

    public:
        // Constructors
        shared_ptr()
            : ptr(nullptr), ref_count(nullptr) {}

        shared_ptr(nullptr_t ptr)
            : ptr(ptr), ref_count(nullptr) {
        }

        shared_ptr(T* ptr)
            : ptr(ptr), ref_count(nullptr) {
            initialize_ref_count();
        }

        // Destructor
        ~shared_ptr() {
            --(*ref_count);
            if (*ref_count == 0) {
                delete ref_count;
                ref_count = nullptr;
                delete ptr;
                ptr = nullptr;
            }
        }

        // Copy constructor
        shared_ptr(const shared_ptr& copy) {
            ptr = copy.ptr;
            ref_count = copy.ref_count;
            if (ref_count != nullptr) {
                ++(*ref_count);
            }
        }

        // Assignment operator
        shared_ptr& operator=(const shared_ptr& copy) {
            ptr = copy.ptr;
            ref_count = copy.ref_count;
            if (ref_count != nullptr) {
                ++(*ref_count);
            }
            return *this;
        }

        // Returns stored object reference
        T& operator*() const {
            return *ptr;
        }

        // Returns stored object pointer
        T* operator->() const {
            return ptr;
        }
    };
}

class Base
{
    int data;
public:
    Base() : data(0) { std::cout << "  Base::Base()\n"; }
    virtual ~Base() { std::cout << "  Base::~Base()\n"; }

    void set_data(int data) {
        this->data = data;
    }
    int get_data() const {
        return this->data;
    }
};

class Derived : public Base
{
public:
    Derived() { std::cout << "  Derived::Derived()\n"; }
    ~Derived() { std::cout << "  Derived::~Derived()\n"; }
};

my::shared_ptr<Base> function()
{
    my::shared_ptr<Base> ptr = new Derived();
    return ptr;
}

int main()
{
    my::shared_ptr<Base> ptr1;

    {
        my::shared_ptr<Base> ptr2 = function();
        ptr2->set_data(100);
        my::shared_ptr<Base> ptr3 = ptr2;
        ptr1 = ptr3;
    }
    std::cout << "  data set to: " << (*ptr1).get_data() << std::endl;

    return 0;
}<commit_msg>Added comments<commit_after>/*
 * Simple implementation of shared_ptr.
 * Below code is non thread safe.
 *
 * (c) 2015 Raghavendra Nayak, All Rights Reserved.
 * http://www.openguru.com/
 */

#include <iostream>

namespace my {
    template <class T>
    class shared_ptr {
        T* ptr;
        int* ref_count;

        /**
         * Initializes the ref count used for tracking the usage.
         */
        void initialize_ref_count() {
            if (ref_count != nullptr)
                return;
            try {
                ref_count = new int;
                *ref_count = 1;
            }
            catch (std::bad_alloc& e) {
                std::cerr << "Memory allocation error: " << e.what();
            }
        }

    public:
        // Constructors
        shared_ptr()
            : ptr(nullptr), ref_count(nullptr) {}

        shared_ptr(nullptr_t ptr)
            : ptr(ptr), ref_count(nullptr) {
        }

        shared_ptr(T* ptr)
            : ptr(ptr), ref_count(nullptr) {
            initialize_ref_count();
        }

        // Destructor
        ~shared_ptr() {
            --(*ref_count);
            if (*ref_count == 0) {
                delete ref_count;
                ref_count = nullptr;
                delete ptr;
                ptr = nullptr;
            }
        }

        // Copy constructor
        shared_ptr(const shared_ptr& copy) {
            ptr = copy.ptr;
            ref_count = copy.ref_count;
            if (ref_count != nullptr) {
                ++(*ref_count);
            }
        }

        // Assignment operator
        shared_ptr& operator=(const shared_ptr& copy) {
            ptr = copy.ptr;
            ref_count = copy.ref_count;
            if (ref_count != nullptr) {
                ++(*ref_count);
            }
            return *this;
        }

        // Returns stored object reference
        T& operator*() const {
            return *ptr;
        }

        // Returns stored object pointer
        T* operator->() const {
            return ptr;
        }
    };
}

class Base
{
    int data;
public:
    Base() : data(0) { std::cout << "  Base::Base()\n"; }
    virtual ~Base() { std::cout << "  Base::~Base()\n"; }

    void set_data(int data) {
        this->data = data;
    }
    int get_data() const {
        return this->data;
    }
};

class Derived : public Base
{
public:
    Derived() { std::cout << "  Derived::Derived()\n"; }
    ~Derived() { std::cout << "  Derived::~Derived()\n"; }
};

my::shared_ptr<Base> function()
{
    my::shared_ptr<Base> ptr = new Derived();
    return ptr;
}

int main(int argc, char **argv)
{
    // Default constructor
    my::shared_ptr<Base> ptr1;

    {
        // Parameterized constructor
        my::shared_ptr<Base> ptr2 = function();

        // operator function call
        ptr2->set_data(100);

        // copy constructor call
        my::shared_ptr<Base> ptr3 = ptr2;

        // assignment operator call
        ptr1 = ptr3;
    }
    // operator function call
    std::cout << "  data set to: " << (*ptr1).get_data() << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: prof_usl.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:24:09 $
 *
 *  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
 *
 ************************************************************************/

#include <procfs.h>
#include <tools/stream.hxx>
#include "profiler.hxx"

struct SysdepProfileSnapshot
{
    pstatus mpstatus;
    psinfo mpsinfo;
    prusage mprusage;
};

struct SysdepStaticData
{
    // Hier steht alles, was whrend des Profiles stndig gebraucht wird
};

void TTProfiler::InitSysdepProfiler()
{
    if ( !pSysDepStatic )   // Sollte immer so sein!!
        pSysDepStatic = new SysdepStaticData;
    // Hier initialisieren

};

void TTProfiler::DeinitSysdepProfiler()
{
    if ( pSysDepStatic )    // Sollte immer so sein!!
    {
        // Hier aufrumen und eventuell Speicher freigeben

        delete pSysDepStatic;
    }
};

SysdepProfileSnapshot *TTProfiler::NewSysdepSnapshotData()
{
    return new SysdepProfileSnapshot;
};

void TTProfiler::DeleteSysdepSnapshotData( SysdepProfileSnapshot *pSysdepProfileSnapshot )
{
    delete pSysdepProfileSnapshot;
};

// Titelzeile fr Logdatei
String TTProfiler::GetSysdepProfileHeader()
{
    return String::CreateFromAscii(" Size(Kb) ResidentSZ  rtime  ktime  utime  total");
};

// Zustand merken
void TTProfiler::GetSysdepProfileSnapshot( SysdepProfileSnapshot *pSysdepProfileSnapshot, USHORT nMode )
{
    SvFileStream aStream( String::CreateFromAscii("/proc/self/psinfo"), STREAM_READ );      // Das ist ein expliziter Pfad fr UNXSOL!
    if ( aStream.IsOpen() )
    {
        aStream.Read( &(pSysdepProfileSnapshot->mpsinfo), sizeof( psinfo ) );
        aStream.Close();
    }
    SvFileStream anotherStream( String::CreateFromAscii("/proc/self/status"), STREAM_READ );        // Das ist ein expliziter Pfad fr UNXSOL!
    if ( anotherStream.IsOpen() )
    {
        anotherStream.Read( &(pSysdepProfileSnapshot->mpstatus), sizeof( pstatus ) );
        anotherStream.Close();
    }
    SvFileStream YetAnotherStream( String::CreateFromAscii("/proc/self/usage"), STREAM_READ );      // Das ist ein expliziter Pfad fr UNXSOL!
    if ( YetAnotherStream.IsOpen() )
    {
        YetAnotherStream.Read( &(pSysdepProfileSnapshot->mprusage), sizeof( prusage ) );
        YetAnotherStream.Close();
    }
};

#define DIFF2( aFirst, aSecond, Membername ) ( aSecond.Membername - aFirst.Membername )
#define CALC_MS( nSec, nNSec ) ( nSec * 1000 + (nNSec+500000) / 1000000 )
#define DIFF_MS( pStart, pEnd, Member ) ( CALC_MS( pEnd->Member.tv_sec, pEnd->Member.tv_nsec ) - CALC_MS( pStart->Member.tv_sec, pStart->Member.tv_nsec ) )
// Informationszeile zusammenbauen
String TTProfiler::GetSysdepProfileLine( SysdepProfileSnapshot *pStart, SysdepProfileSnapshot *pStop )
{
    String aProfile;

    aProfile += Pad( String::CreateFromInt64(pStop->mpsinfo.pr_size), 9);
    aProfile += Pad( String::CreateFromInt64(pStop->mpsinfo.pr_rssize), 11);

    aProfile += Pad( String::CreateFromInt64(DIFF_MS( pStart, pStop, mprusage.pr_rtime ) / AVER( pStart, pStop, mprusage.pr_count )), 7 );

    ULONG d_utime = DIFF_MS( pStart, pStop, mpstatus.pr_utime ) + DIFF_MS( pStart, pStop, mpstatus.pr_cutime );
    ULONG d_stime = DIFF_MS( pStart, pStop, mpstatus.pr_stime ) + DIFF_MS( pStart, pStop, mpstatus.pr_cstime );

    aProfile += Pad( String::CreateFromInt64(d_utime), 7 );
    aProfile += Pad( String::CreateFromInt64(d_stime), 7 );
    aProfile += Pad( String::CreateFromInt64(d_utime + d_stime), 7 );

    return aProfile;
};

<commit_msg>INTEGRATION: CWS warnings01 (1.4.12); FILE MERGED 2006/02/02 09:19:58 gh 1.4.12.1: removed compiler warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: prof_usl.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 00:23:12 $
 *
 *  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
 *
 ************************************************************************/

#include <procfs.h>
#include <tools/stream.hxx>
#include "profiler.hxx"

struct SysdepProfileSnapshot
{
    pstatus mpstatus;
    psinfo mpsinfo;
    prusage mprusage;
};

struct SysdepStaticData
{
    // Hier steht alles, was whrend des Profiles stndig gebraucht wird
};

void TTProfiler::InitSysdepProfiler()
{
    if ( !pSysDepStatic )   // Sollte immer so sein!!
        pSysDepStatic = new SysdepStaticData;
    // Hier initialisieren

};

void TTProfiler::DeinitSysdepProfiler()
{
    if ( pSysDepStatic )    // Sollte immer so sein!!
    {
        // Hier aufrumen und eventuell Speicher freigeben

        delete pSysDepStatic;
    }
};

SysdepProfileSnapshot *TTProfiler::NewSysdepSnapshotData()
{
    return new SysdepProfileSnapshot;
};

void TTProfiler::DeleteSysdepSnapshotData( SysdepProfileSnapshot *pSysdepProfileSnapshot )
{
    delete pSysdepProfileSnapshot;
};

// Titelzeile fr Logdatei
String TTProfiler::GetSysdepProfileHeader()
{
    return String::CreateFromAscii(" Size(Kb) ResidentSZ  rtime  ktime  utime  total");
};

// Zustand merken
void TTProfiler::GetSysdepProfileSnapshot( SysdepProfileSnapshot *pSysdepProfileSnapshot, USHORT )
{
    SvFileStream aStream( String::CreateFromAscii("/proc/self/psinfo"), STREAM_READ );      // Das ist ein expliziter Pfad fr UNXSOL!
    if ( aStream.IsOpen() )
    {
        aStream.Read( &(pSysdepProfileSnapshot->mpsinfo), sizeof( psinfo ) );
        aStream.Close();
    }
    SvFileStream anotherStream( String::CreateFromAscii("/proc/self/status"), STREAM_READ );        // Das ist ein expliziter Pfad fr UNXSOL!
    if ( anotherStream.IsOpen() )
    {
        anotherStream.Read( &(pSysdepProfileSnapshot->mpstatus), sizeof( pstatus ) );
        anotherStream.Close();
    }
    SvFileStream YetAnotherStream( String::CreateFromAscii("/proc/self/usage"), STREAM_READ );      // Das ist ein expliziter Pfad fr UNXSOL!
    if ( YetAnotherStream.IsOpen() )
    {
        YetAnotherStream.Read( &(pSysdepProfileSnapshot->mprusage), sizeof( prusage ) );
        YetAnotherStream.Close();
    }
};

#define DIFF2( aFirst, aSecond, Membername ) ( aSecond.Membername - aFirst.Membername )
#define CALC_MS( nSec, nNSec ) ( nSec * 1000 + (nNSec+500000) / 1000000 )
#define DIFF_MS( pStart, pEnd, Member ) ( CALC_MS( pEnd->Member.tv_sec, pEnd->Member.tv_nsec ) - CALC_MS( pStart->Member.tv_sec, pStart->Member.tv_nsec ) )
// Informationszeile zusammenbauen
String TTProfiler::GetSysdepProfileLine( SysdepProfileSnapshot *pStart, SysdepProfileSnapshot *pStop )
{
    String aProfile;

    aProfile += Pad( String::CreateFromInt64(pStop->mpsinfo.pr_size), 9);
    aProfile += Pad( String::CreateFromInt64(pStop->mpsinfo.pr_rssize), 11);

    aProfile += Pad( String::CreateFromInt64(DIFF_MS( pStart, pStop, mprusage.pr_rtime ) / AVER( pStart, pStop, mprusage.pr_count )), 7 );

    ULONG d_utime = DIFF_MS( pStart, pStop, mpstatus.pr_utime ) + DIFF_MS( pStart, pStop, mpstatus.pr_cutime );
    ULONG d_stime = DIFF_MS( pStart, pStop, mpstatus.pr_stime ) + DIFF_MS( pStart, pStop, mpstatus.pr_cstime );

    aProfile += Pad( String::CreateFromInt64(d_utime), 7 );
    aProfile += Pad( String::CreateFromInt64(d_stime), 7 );
    aProfile += Pad( String::CreateFromInt64(d_utime + d_stime), 7 );

    return aProfile;
};

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: prof_usl.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 00:35:33 $
 *
 *  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_automation.hxx"

#include <procfs.h>
#include <tools/stream.hxx>
#include "profiler.hxx"

struct SysdepProfileSnapshot
{
    pstatus mpstatus;
    psinfo mpsinfo;
    prusage mprusage;
};

struct SysdepStaticData
{
    // Hier steht alles, was whrend des Profiles stndig gebraucht wird
};

void TTProfiler::InitSysdepProfiler()
{
    if ( !pSysDepStatic )   // Sollte immer so sein!!
        pSysDepStatic = new SysdepStaticData;
    // Hier initialisieren

};

void TTProfiler::DeinitSysdepProfiler()
{
    if ( pSysDepStatic )    // Sollte immer so sein!!
    {
        // Hier aufrumen und eventuell Speicher freigeben

        delete pSysDepStatic;
    }
};

SysdepProfileSnapshot *TTProfiler::NewSysdepSnapshotData()
{
    return new SysdepProfileSnapshot;
};

void TTProfiler::DeleteSysdepSnapshotData( SysdepProfileSnapshot *pSysdepProfileSnapshot )
{
    delete pSysdepProfileSnapshot;
};

// Titelzeile fr Logdatei
String TTProfiler::GetSysdepProfileHeader()
{
    return String::CreateFromAscii(" Size(Kb) ResidentSZ  rtime  ktime  utime  total");
};

// Zustand merken
void TTProfiler::GetSysdepProfileSnapshot( SysdepProfileSnapshot *pSysdepProfileSnapshot, USHORT )
{
    SvFileStream aStream( String::CreateFromAscii("/proc/self/psinfo"), STREAM_READ );      // Das ist ein expliziter Pfad fr UNXSOL!
    if ( aStream.IsOpen() )
    {
        aStream.Read( &(pSysdepProfileSnapshot->mpsinfo), sizeof( psinfo ) );
        aStream.Close();
    }
    SvFileStream anotherStream( String::CreateFromAscii("/proc/self/status"), STREAM_READ );        // Das ist ein expliziter Pfad fr UNXSOL!
    if ( anotherStream.IsOpen() )
    {
        anotherStream.Read( &(pSysdepProfileSnapshot->mpstatus), sizeof( pstatus ) );
        anotherStream.Close();
    }
    SvFileStream YetAnotherStream( String::CreateFromAscii("/proc/self/usage"), STREAM_READ );      // Das ist ein expliziter Pfad fr UNXSOL!
    if ( YetAnotherStream.IsOpen() )
    {
        YetAnotherStream.Read( &(pSysdepProfileSnapshot->mprusage), sizeof( prusage ) );
        YetAnotherStream.Close();
    }
};

#define DIFF2( aFirst, aSecond, Membername ) ( aSecond.Membername - aFirst.Membername )
#define CALC_MS( nSec, nNSec ) ( nSec * 1000 + (nNSec+500000) / 1000000 )
#define DIFF_MS( pStart, pEnd, Member ) ( CALC_MS( pEnd->Member.tv_sec, pEnd->Member.tv_nsec ) - CALC_MS( pStart->Member.tv_sec, pStart->Member.tv_nsec ) )
// Informationszeile zusammenbauen
String TTProfiler::GetSysdepProfileLine( SysdepProfileSnapshot *pStart, SysdepProfileSnapshot *pStop )
{
    String aProfile;

    aProfile += Pad( String::CreateFromInt64(pStop->mpsinfo.pr_size), 9);
    aProfile += Pad( String::CreateFromInt64(pStop->mpsinfo.pr_rssize), 11);

    aProfile += Pad( String::CreateFromInt64(DIFF_MS( pStart, pStop, mprusage.pr_rtime ) / AVER( pStart, pStop, mprusage.pr_count )), 7 );

    ULONG d_utime = DIFF_MS( pStart, pStop, mpstatus.pr_utime ) + DIFF_MS( pStart, pStop, mpstatus.pr_cutime );
    ULONG d_stime = DIFF_MS( pStart, pStop, mpstatus.pr_stime ) + DIFF_MS( pStart, pStop, mpstatus.pr_cstime );

    aProfile += Pad( String::CreateFromInt64(d_utime), 7 );
    aProfile += Pad( String::CreateFromInt64(d_stime), 7 );
    aProfile += Pad( String::CreateFromInt64(d_utime + d_stime), 7 );

    return aProfile;
};

<commit_msg>INTEGRATION: CWS changefileheader (1.6.86); FILE MERGED 2008/03/28 16:03:38 rt 1.6.86.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: prof_usl.cxx,v $
 * $Revision: 1.7 $
 *
 * 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.
 *
 ************************************************************************/

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

#include <procfs.h>
#include <tools/stream.hxx>
#include "profiler.hxx"

struct SysdepProfileSnapshot
{
    pstatus mpstatus;
    psinfo mpsinfo;
    prusage mprusage;
};

struct SysdepStaticData
{
    // Hier steht alles, was whrend des Profiles stndig gebraucht wird
};

void TTProfiler::InitSysdepProfiler()
{
    if ( !pSysDepStatic )   // Sollte immer so sein!!
        pSysDepStatic = new SysdepStaticData;
    // Hier initialisieren

};

void TTProfiler::DeinitSysdepProfiler()
{
    if ( pSysDepStatic )    // Sollte immer so sein!!
    {
        // Hier aufrumen und eventuell Speicher freigeben

        delete pSysDepStatic;
    }
};

SysdepProfileSnapshot *TTProfiler::NewSysdepSnapshotData()
{
    return new SysdepProfileSnapshot;
};

void TTProfiler::DeleteSysdepSnapshotData( SysdepProfileSnapshot *pSysdepProfileSnapshot )
{
    delete pSysdepProfileSnapshot;
};

// Titelzeile fr Logdatei
String TTProfiler::GetSysdepProfileHeader()
{
    return String::CreateFromAscii(" Size(Kb) ResidentSZ  rtime  ktime  utime  total");
};

// Zustand merken
void TTProfiler::GetSysdepProfileSnapshot( SysdepProfileSnapshot *pSysdepProfileSnapshot, USHORT )
{
    SvFileStream aStream( String::CreateFromAscii("/proc/self/psinfo"), STREAM_READ );      // Das ist ein expliziter Pfad fr UNXSOL!
    if ( aStream.IsOpen() )
    {
        aStream.Read( &(pSysdepProfileSnapshot->mpsinfo), sizeof( psinfo ) );
        aStream.Close();
    }
    SvFileStream anotherStream( String::CreateFromAscii("/proc/self/status"), STREAM_READ );        // Das ist ein expliziter Pfad fr UNXSOL!
    if ( anotherStream.IsOpen() )
    {
        anotherStream.Read( &(pSysdepProfileSnapshot->mpstatus), sizeof( pstatus ) );
        anotherStream.Close();
    }
    SvFileStream YetAnotherStream( String::CreateFromAscii("/proc/self/usage"), STREAM_READ );      // Das ist ein expliziter Pfad fr UNXSOL!
    if ( YetAnotherStream.IsOpen() )
    {
        YetAnotherStream.Read( &(pSysdepProfileSnapshot->mprusage), sizeof( prusage ) );
        YetAnotherStream.Close();
    }
};

#define DIFF2( aFirst, aSecond, Membername ) ( aSecond.Membername - aFirst.Membername )
#define CALC_MS( nSec, nNSec ) ( nSec * 1000 + (nNSec+500000) / 1000000 )
#define DIFF_MS( pStart, pEnd, Member ) ( CALC_MS( pEnd->Member.tv_sec, pEnd->Member.tv_nsec ) - CALC_MS( pStart->Member.tv_sec, pStart->Member.tv_nsec ) )
// Informationszeile zusammenbauen
String TTProfiler::GetSysdepProfileLine( SysdepProfileSnapshot *pStart, SysdepProfileSnapshot *pStop )
{
    String aProfile;

    aProfile += Pad( String::CreateFromInt64(pStop->mpsinfo.pr_size), 9);
    aProfile += Pad( String::CreateFromInt64(pStop->mpsinfo.pr_rssize), 11);

    aProfile += Pad( String::CreateFromInt64(DIFF_MS( pStart, pStop, mprusage.pr_rtime ) / AVER( pStart, pStop, mprusage.pr_count )), 7 );

    ULONG d_utime = DIFF_MS( pStart, pStop, mpstatus.pr_utime ) + DIFF_MS( pStart, pStop, mpstatus.pr_cutime );
    ULONG d_stime = DIFF_MS( pStart, pStop, mpstatus.pr_stime ) + DIFF_MS( pStart, pStop, mpstatus.pr_cstime );

    aProfile += Pad( String::CreateFromInt64(d_utime), 7 );
    aProfile += Pad( String::CreateFromInt64(d_stime), 7 );
    aProfile += Pad( String::CreateFromInt64(d_utime + d_stime), 7 );

    return aProfile;
};

<|endoftext|>


<commit_before>#include <3ds.h>

extern "C" int (*backdoor_callback)(void);
extern "C" int backdoor_ret;

int (*backdoor_callback)(void) = nullptr;
int backdoor_ret = 0;

static s32 __attribute__((naked))
KernelBackdoorTargetWrapper()
{
    __asm__ __volatile__ (
        "push {r4, lr}              \t\n"

        "ldr r0, =backdoor_callback \t\n"
        "ldr r0, [r0]               \t\n"
        "blx r0                     \t\n"

        "ldr r4, =backdoor_ret      \t\n"
        "str r0, [r4]               \t\n"
        "pop {r4, pc}               \t\n"
        );
}

int KernelBackdoor(int (*callback)(void))
{
    backdoor_callback = callback;
    svcBackdoor(KernelBackdoorTargetWrapper);
    return backdoor_ret;
}
<commit_msg>Actually disable interrupts in the code that was meant to disable interrupts :/<commit_after>#include <3ds.h>

extern "C" int (*backdoor_callback)(void);
extern "C" int backdoor_ret;

int (*backdoor_callback)(void) = nullptr;
int backdoor_ret = 0;

static s32 __attribute__((naked))
KernelBackdoorTargetWrapper()
{
    __asm__ __volatile__ (
        "cpsid aif                  \t\n"
        "push {r4, lr}              \t\n"

        "ldr r0, =backdoor_callback \t\n"
        "ldr r0, [r0]               \t\n"
        "blx r0                     \t\n"

        "ldr r4, =backdoor_ret      \t\n"
        "str r0, [r4]               \t\n"
        "pop {r4, pc}               \t\n"
        );
}

int KernelBackdoor(int (*callback)(void))
{
    backdoor_callback = callback;
    svcBackdoor(KernelBackdoorTargetWrapper);
    return backdoor_ret;
}
<|endoftext|>