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

  Program:   Visualization Toolkit
  Module:    vtkUnstructuredGridCellIterator.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkUnstructuredGridCellIterator.h"

#include "vtkCellArray.h"
#include "vtkIdList.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnstructuredGrid.h"

vtkStandardNewMacro(vtkUnstructuredGridCellIterator)

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "CellTypeBegin: " << this->CellTypeBegin << endl;
  os << indent << "CellTypePtr: " << this->CellTypePtr << endl;
  os << indent << "CellTypeEnd: " << this->CellTypeEnd << endl;
  os << indent << "ConnectivityBegin: " << this->ConnectivityBegin << endl;
  os << indent << "ConnectivityPtr: " << this->ConnectivityPtr << endl;
  os << indent << "FacesBegin: " << this->FacesBegin<< endl;
  os << indent << "FacesLocsBegin: " << this->FacesLocsBegin << endl;
  os << indent << "FacesLocsPtr: " << this->FacesLocsPtr << endl;
  os << indent << "SkippedCells: " << this->SkippedCells << endl;
  os << indent << "UnstructuredGridPoints: " <<
        this->UnstructuredGridPoints.GetPointer() << endl;
}

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::SetUnstructuredGrid(
    vtkUnstructuredGrid *ug)
{
  // If the unstructured grid has not been initialized yet, these may not exist:
  vtkUnsignedCharArray *cellTypeArray = ug ? ug->GetCellTypesArray() : NULL;
  vtkCellArray *cellArray = ug ? ug->GetCells() : NULL;
  vtkPoints *points = ug ? ug->GetPoints() : NULL;

  if (ug && cellTypeArray && cellArray && points)
    {
    // Cell types
    this->CellTypeBegin = this->CellTypeEnd = this->CellTypePtr
        = cellTypeArray ? cellTypeArray->GetPointer(0) : NULL;
    this->CellTypeEnd += cellTypeArray ? cellTypeArray->GetNumberOfTuples() : 0;

    // CellArray
    this->ConnectivityBegin = this->ConnectivityPtr = cellArray->GetPointer();

    // Point
    this->UnstructuredGridPoints = points;

    // Faces
    vtkIdTypeArray *faces = ug->GetFaces();
    vtkIdTypeArray *facesLocs = ug->GetFaceLocations();
    if (faces && facesLocs)
      {
      this->FacesBegin = faces->GetPointer(0);
      this->FacesLocsBegin = this->FacesLocsPtr = facesLocs->GetPointer(0);
      }
    else
      {
      this->FacesBegin = NULL;
      this->FacesLocsBegin = NULL;
      this->FacesLocsPtr = NULL;
      }
    }
  else
    {
    this->CellTypeBegin = NULL;
    this->CellTypePtr = NULL;
    this->CellTypeEnd = NULL;
    this->FacesBegin = NULL;
    this->FacesLocsBegin = NULL;
    this->FacesLocsPtr = NULL;
    this->ConnectivityBegin= NULL;
    this->ConnectivityPtr = NULL;
    this->UnstructuredGridPoints = NULL;
    }

  this->SkippedCells = 0;
}

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::CatchUpSkippedCells()
{
  // catch up on skipped cells -- cache misses make incrementing Connectivity
  // in IncrementToNextCell() too expensive, so we delay it until here. Special
  // cases are used for 0 or 1 skipped cells to reduce the number of jumps.
  switch (this->SkippedCells)
    {
    default:
      while (this->SkippedCells-- > 1)
        {
        this->ConnectivityPtr += *this->ConnectivityPtr + 1;
        }
      // Fall through to first case
    case 1:
      this->ConnectivityPtr += *this->ConnectivityPtr + 1;
      --this->SkippedCells;
      // fall through to 0 case
    case 0:
      // do nothing.
      break;
  }
}

//------------------------------------------------------------------------------
bool vtkUnstructuredGridCellIterator::IsDoneWithTraversal()
{
  return this->CellTypePtr >= this->CellTypeEnd;
}

//------------------------------------------------------------------------------
vtkIdType vtkUnstructuredGridCellIterator::GetCellId()
{
  return static_cast<vtkIdType>(this->CellTypePtr - this->CellTypeBegin);
}

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::IncrementToNextCell()
{
  ++this->CellTypePtr;

  // Bookkeeping for ConnectivityPtr
  ++this->SkippedCells;

  // Note that we may be incrementing an invalid pointer here...check
  // if FacesLocsBegin is NULL before dereferencing this!
  ++this->FacesLocsPtr;
}

//------------------------------------------------------------------------------
vtkUnstructuredGridCellIterator::vtkUnstructuredGridCellIterator()
  : vtkCellIterator(),
    CellTypeBegin(NULL),
    CellTypePtr(NULL),
    CellTypeEnd(NULL),
    ConnectivityBegin(NULL),
    ConnectivityPtr(NULL),
    FacesBegin(NULL),
    FacesLocsBegin(NULL),
    FacesLocsPtr(NULL),
    SkippedCells(0),
    UnstructuredGridPoints(NULL)
{
}

//------------------------------------------------------------------------------
vtkUnstructuredGridCellIterator::~vtkUnstructuredGridCellIterator()
{
}

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::ResetToFirstCell()
{
  this->CellTypePtr = this->CellTypeBegin;
  this->FacesLocsPtr = this->FacesLocsBegin;
  this->ConnectivityPtr = this->ConnectivityBegin;
  this->SkippedCells = 0;
}

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::FetchCellType()
{
  this->CellType = *this->CellTypePtr;
}

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::FetchPointIds()
{
  CatchUpSkippedCells();
  const vtkIdType *connPtr = this->ConnectivityPtr;
  vtkIdType numCellPoints = *(connPtr++);
  this->PointIds->SetNumberOfIds(numCellPoints);
  vtkIdType *cellPtr = this->PointIds->GetPointer(0);
  std::copy(connPtr, connPtr + numCellPoints, cellPtr);
}

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::FetchPoints()
{
  this->UnstructuredGridPoints->GetPoints(this->GetPointIds(), this->Points);
}

//------------------------------------------------------------------------------
// Given a pointer into a set of faces, traverse the faces and return the total
// number of ids (including size hints) in the face set.
namespace {
inline vtkIdType FaceSetSize(vtkIdType *begin)
{
  vtkIdType *result = begin;
  vtkIdType numFaces = *(result++);
  while (numFaces-- > 0)
    {
    result += *result + 1;
    }
  return result - begin;
}
} // end anon namespace

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::FetchFaces()
{
  // FacesLocsPtr may be non-null and invalid (this is done to prevent branching
  // in IncrementToNextCell()). Check FacesLocsBegin to determine validity of
  // the pointer.
  if (this->FacesLocsBegin && *this->FacesLocsPtr >= 0)
    {
    vtkIdType *faceSet = this->FacesBegin + *this->FacesLocsPtr;
    vtkIdType facesSize = FaceSetSize(faceSet);
    this->Faces->SetNumberOfIds(facesSize);
    vtkIdType *tmpPtr = this->Faces->GetPointer(0);
    std::copy(faceSet, faceSet + facesSize, tmpPtr);
    }
  else
    {
    this->Faces->SetNumberOfIds(0);
    }
}
<commit_msg>Fix failing printOther test.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkUnstructuredGridCellIterator.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkUnstructuredGridCellIterator.h"

#include "vtkCellArray.h"
#include "vtkIdList.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnstructuredGrid.h"

vtkStandardNewMacro(vtkUnstructuredGridCellIterator)

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  // Cast the 'unsigned char*' members to void* to prevent the compiler from
  // interpreting them as strings.
  os << indent << "CellTypeBegin: "
     << static_cast<void*>(this->CellTypeBegin) << endl;
  os << indent << "CellTypePtr: "
     << static_cast<void*>(this->CellTypePtr) << endl;
  os << indent << "CellTypeEnd: "
     << static_cast<void*>(this->CellTypeEnd) << endl;
  os << indent << "ConnectivityBegin: " << this->ConnectivityBegin << endl;
  os << indent << "ConnectivityPtr: " << this->ConnectivityPtr << endl;
  os << indent << "FacesBegin: " << this->FacesBegin<< endl;
  os << indent << "FacesLocsBegin: " << this->FacesLocsBegin << endl;
  os << indent << "FacesLocsPtr: " << this->FacesLocsPtr << endl;
  os << indent << "SkippedCells: " << this->SkippedCells << endl;
  os << indent << "UnstructuredGridPoints: " <<
        this->UnstructuredGridPoints.GetPointer() << endl;
}

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::SetUnstructuredGrid(
    vtkUnstructuredGrid *ug)
{
  // If the unstructured grid has not been initialized yet, these may not exist:
  vtkUnsignedCharArray *cellTypeArray = ug ? ug->GetCellTypesArray() : NULL;
  vtkCellArray *cellArray = ug ? ug->GetCells() : NULL;
  vtkPoints *points = ug ? ug->GetPoints() : NULL;

  if (ug && cellTypeArray && cellArray && points)
    {
    // Cell types
    this->CellTypeBegin = this->CellTypeEnd = this->CellTypePtr
        = cellTypeArray ? cellTypeArray->GetPointer(0) : NULL;
    this->CellTypeEnd += cellTypeArray ? cellTypeArray->GetNumberOfTuples() : 0;

    // CellArray
    this->ConnectivityBegin = this->ConnectivityPtr = cellArray->GetPointer();

    // Point
    this->UnstructuredGridPoints = points;

    // Faces
    vtkIdTypeArray *faces = ug->GetFaces();
    vtkIdTypeArray *facesLocs = ug->GetFaceLocations();
    if (faces && facesLocs)
      {
      this->FacesBegin = faces->GetPointer(0);
      this->FacesLocsBegin = this->FacesLocsPtr = facesLocs->GetPointer(0);
      }
    else
      {
      this->FacesBegin = NULL;
      this->FacesLocsBegin = NULL;
      this->FacesLocsPtr = NULL;
      }
    }
  else
    {
    this->CellTypeBegin = NULL;
    this->CellTypePtr = NULL;
    this->CellTypeEnd = NULL;
    this->FacesBegin = NULL;
    this->FacesLocsBegin = NULL;
    this->FacesLocsPtr = NULL;
    this->ConnectivityBegin= NULL;
    this->ConnectivityPtr = NULL;
    this->UnstructuredGridPoints = NULL;
    }

  this->SkippedCells = 0;
}

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::CatchUpSkippedCells()
{
  // catch up on skipped cells -- cache misses make incrementing Connectivity
  // in IncrementToNextCell() too expensive, so we delay it until here. Special
  // cases are used for 0 or 1 skipped cells to reduce the number of jumps.
  switch (this->SkippedCells)
    {
    default:
      while (this->SkippedCells-- > 1)
        {
        this->ConnectivityPtr += *this->ConnectivityPtr + 1;
        }
      // Fall through to first case
    case 1:
      this->ConnectivityPtr += *this->ConnectivityPtr + 1;
      --this->SkippedCells;
      // fall through to 0 case
    case 0:
      // do nothing.
      break;
  }
}

//------------------------------------------------------------------------------
bool vtkUnstructuredGridCellIterator::IsDoneWithTraversal()
{
  return this->CellTypePtr >= this->CellTypeEnd;
}

//------------------------------------------------------------------------------
vtkIdType vtkUnstructuredGridCellIterator::GetCellId()
{
  return static_cast<vtkIdType>(this->CellTypePtr - this->CellTypeBegin);
}

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::IncrementToNextCell()
{
  ++this->CellTypePtr;

  // Bookkeeping for ConnectivityPtr
  ++this->SkippedCells;

  // Note that we may be incrementing an invalid pointer here...check
  // if FacesLocsBegin is NULL before dereferencing this!
  ++this->FacesLocsPtr;
}

//------------------------------------------------------------------------------
vtkUnstructuredGridCellIterator::vtkUnstructuredGridCellIterator()
  : vtkCellIterator(),
    CellTypeBegin(NULL),
    CellTypePtr(NULL),
    CellTypeEnd(NULL),
    ConnectivityBegin(NULL),
    ConnectivityPtr(NULL),
    FacesBegin(NULL),
    FacesLocsBegin(NULL),
    FacesLocsPtr(NULL),
    SkippedCells(0),
    UnstructuredGridPoints(NULL)
{
}

//------------------------------------------------------------------------------
vtkUnstructuredGridCellIterator::~vtkUnstructuredGridCellIterator()
{
}

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::ResetToFirstCell()
{
  this->CellTypePtr = this->CellTypeBegin;
  this->FacesLocsPtr = this->FacesLocsBegin;
  this->ConnectivityPtr = this->ConnectivityBegin;
  this->SkippedCells = 0;
}

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::FetchCellType()
{
  this->CellType = *this->CellTypePtr;
}

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::FetchPointIds()
{
  CatchUpSkippedCells();
  const vtkIdType *connPtr = this->ConnectivityPtr;
  vtkIdType numCellPoints = *(connPtr++);
  this->PointIds->SetNumberOfIds(numCellPoints);
  vtkIdType *cellPtr = this->PointIds->GetPointer(0);
  std::copy(connPtr, connPtr + numCellPoints, cellPtr);
}

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::FetchPoints()
{
  this->UnstructuredGridPoints->GetPoints(this->GetPointIds(), this->Points);
}

//------------------------------------------------------------------------------
// Given a pointer into a set of faces, traverse the faces and return the total
// number of ids (including size hints) in the face set.
namespace {
inline vtkIdType FaceSetSize(vtkIdType *begin)
{
  vtkIdType *result = begin;
  vtkIdType numFaces = *(result++);
  while (numFaces-- > 0)
    {
    result += *result + 1;
    }
  return result - begin;
}
} // end anon namespace

//------------------------------------------------------------------------------
void vtkUnstructuredGridCellIterator::FetchFaces()
{
  // FacesLocsPtr may be non-null and invalid (this is done to prevent branching
  // in IncrementToNextCell()). Check FacesLocsBegin to determine validity of
  // the pointer.
  if (this->FacesLocsBegin && *this->FacesLocsPtr >= 0)
    {
    vtkIdType *faceSet = this->FacesBegin + *this->FacesLocsPtr;
    vtkIdType facesSize = FaceSetSize(faceSet);
    this->Faces->SetNumberOfIds(facesSize);
    vtkIdType *tmpPtr = this->Faces->GetPointer(0);
    std::copy(faceSet, faceSet + facesSize, tmpPtr);
    }
  else
    {
    this->Faces->SetNumberOfIds(0);
    }
}
<|endoftext|>


<commit_before>#include <stdint.h>

#if defined(_WIN32)
  #include <time.h>
#else
  #include <sys/time.h>
#endif

extern "C" {

WEAK bool halide_reference_clock_inited = false;
WEAK timeval halide_reference_clock;

WEAK int halide_start_clock() {
    // Guard against multiple calls
    if (!halide_reference_clock_inited) {
      gettimeofday(&halide_reference_clock, NULL);
      halide_reference_clock_inited = true;
    }
    return 0;
}

WEAK int halide_current_time() {
    timeval now;
    gettimeofday(&now, NULL);
    int delta = (now.tv_sec - halide_reference_clock.tv_sec)*1000;
    delta += (now.tv_usec - halide_reference_clock.tv_usec)/1000;
    return delta;
}

// TODO(srj): gettimeofday isn't a good way to get a time for
// profiling-ish purposes, since that can change the whim of
// a remote time server; clock_gettime() is now recommended
WEAK int64_t halide_current_time_usec() {
    timeval now;
    gettimeofday(&now, NULL);
    int64_t delta = (now.tv_sec - halide_reference_clock.tv_sec)*1000000;
    delta += (now.tv_usec - halide_reference_clock.tv_usec);
    return delta;
}

}
<commit_msg>Don't include time.h in posix_clock.cpp<commit_after>#include <stdint.h>

#ifndef _STRUCT_TIMEVAL
#define _STRUCT_TIMEVAL

#ifdef _LP64
typedef int64_t sec_t;
#else
typedef int32_t sec_t;
#endif

// OSX always uses an int32 for the usec field
#if defined(_LP64) && !defined(__APPLE__)
typedef int64_t usec_t;
#else
typedef int32_t usec_t;
#endif

struct timeval {
    sec_t tv_sec;
    usec_t tv_usec;
};

#endif

extern "C" {

extern int gettimeofday(timeval *tv, void *);

WEAK bool halide_reference_clock_inited = false;
WEAK timeval halide_reference_clock;

WEAK int halide_start_clock() {
    // Guard against multiple calls
    if (!halide_reference_clock_inited) {
      gettimeofday(&halide_reference_clock, NULL);
      halide_reference_clock_inited = true;
    }
    return 0;
}

// TODO(srj): gettimeofday isn't a good way to get a time for
// profiling-ish purposes, since that can change the whim of
// a remote time server; clock_gettime() is now recommended, but it doesn't
// exist on OSX.
WEAK int64_t halide_current_time_usec() {
    timeval now = {0,0};
    gettimeofday(&now, NULL);
    int64_t delta = (now.tv_sec - halide_reference_clock.tv_sec)*1000000;
    delta += (now.tv_usec - halide_reference_clock.tv_usec);
    return delta;
}

WEAK int halide_current_time() {
  return int(halide_current_time_usec() / 1000);
}

}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkTestingMacros.h"
#include <mitkTestingConfig.h>
#include <mitkTestFixture.h>

#include <mitkIOUtil.h>
#include <mitkInteractionTestHelper.h>
#include <mitkPointSet.h>
#include <mitkPointSetDataInteractor.h>

class mitkPointSetDataInteractorTestSuite : public mitk::TestFixture
{

  CPPUNIT_TEST_SUITE(mitkPointSetDataInteractorTestSuite);
  MITK_TEST(AddPointInteraction);
  CPPUNIT_TEST_SUITE_END();

private:
  mitk::DataNode::Pointer testPointSetNode;
  mitk::PointSetDataInteractor::Pointer dataInteractor;
  mitk::PointSet::Pointer testPointSet;
  mitk::InteractionTestHelper interactionTestHelper;

public:

  void setUp()
  {
    //Create DataNode as a container for our PointSet to be tested
    testPointSetNode = mitk::DataNode::New();

    // Create PointSetData Interactor
    dataInteractor = mitk::PointSetDataInteractor::New();
    // Load the according state machine for regular point set interaction
    dataInteractor->LoadStateMachine("PointSet.xml");
    // Set the configuration file that defines the triggers for the transitions
    dataInteractor->SetEventConfig("PointSetConfig.xml");
    // set the DataNode (which already is added to the DataStorage)
    dataInteractor->SetDataNode(testPointSetNode);

    //Create test helper to initialize all necessary objects for interaction
    interactionTestHelper = mitk::InteractionTestHelper();
    //Add our test node to the DataStorage of our test helper
    interactionTestHelper.AddNodeToStorage(testPointSetNode);

    //Create new PointSet which will receive the interaction input
    testPointSet = mitk::PointSet::New();
    testPointSetNode->SetData(testPointSet);
  }

  void tearDown()
  {
    testPointSetNode = NULL;
    testPointSet = NULL;
    dataInteractor = NULL;
  }

  void AddPointInteraction()
  {
    //Path to the reference PointSet
    std::string referencePointSetPath = "/Users/schroedt/Desktop/pointsetTestRef.mps";

    //Path to the interaction xml file
    std::string interactionXmlPath = "/Users/schroedt/Desktop/pointsetTest.xml";

    //load interaction events
    interactionTestHelper.LoadInteraction(interactionXmlPath);
    //Start Interaction
    interactionTestHelper.PlaybackInteraction();

    //Load the reference PointSet
    mitk::PointSet::Pointer referencePointSet = mitk::IOUtil::LoadPointSet(referencePointSetPath);

    //Compare reference with the result of the interaction
    MITK_ASSERT_EQUAL(testPointSet.GetPointer(), referencePointSet.GetPointer(), "");
  }

};

MITK_TEST_SUITE_REGISTRATION(mitkPointSetDataInteractor)
<commit_msg>Changed test to take care of destruction.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkTestingMacros.h"
#include <mitkTestingConfig.h>
#include <mitkTestFixture.h>

#include <mitkIOUtil.h>
#include <mitkInteractionTestHelper.h>
#include <mitkPointSet.h>
#include <mitkPointSetDataInteractor.h>

class mitkPointSetDataInteractorTestSuite : public mitk::TestFixture
{

  CPPUNIT_TEST_SUITE(mitkPointSetDataInteractorTestSuite);
  MITK_TEST(AddPointInteraction);
  CPPUNIT_TEST_SUITE_END();

private:
  mitk::DataNode::Pointer testPointSetNode;
  mitk::PointSetDataInteractor::Pointer dataInteractor;
  mitk::PointSet::Pointer testPointSet;
  mitk::InteractionTestHelper* interactionTestHelper;

public:

  void setUp()
  {
    //Create DataNode as a container for our PointSet to be tested
    testPointSetNode = mitk::DataNode::New();

    // Create PointSetData Interactor
    dataInteractor = mitk::PointSetDataInteractor::New();
    // Load the according state machine for regular point set interaction
    dataInteractor->LoadStateMachine("PointSet.xml");
    // Set the configuration file that defines the triggers for the transitions
    dataInteractor->SetEventConfig("PointSetConfig.xml");
    // set the DataNode (which already is added to the DataStorage)
    dataInteractor->SetDataNode(testPointSetNode);

    //Create new PointSet which will receive the interaction input
    testPointSet = mitk::PointSet::New();
    testPointSetNode->SetData(testPointSet);

    //Create test helper to initialize all necessary objects for interaction
    interactionTestHelper = new mitk::InteractionTestHelper();
    //Add our test node to the DataStorage of our test helper
    interactionTestHelper->AddNodeToStorage(testPointSetNode);
  }

  void tearDown()
  {
    testPointSetNode = NULL;
    testPointSet = NULL;
    dataInteractor = NULL;
    delete interactionTestHelper;
  }

  void AddPointInteraction()
  {
    //Path to the reference PointSet
    std::string referencePointSetPath = "/Users/schroedt/Desktop/pointsetTestRef.mps";

    //Path to the interaction xml file
    std::string interactionXmlPath = "/Users/schroedt/Desktop/pointsetTest.xml";

    //load interaction events
    interactionTestHelper->LoadInteraction(interactionXmlPath);
    //Start Interaction
    interactionTestHelper->PlaybackInteraction();

    //Load the reference PointSet
    mitk::PointSet::Pointer referencePointSet = mitk::IOUtil::LoadPointSet(referencePointSetPath);

    //Compare reference with the result of the interaction
    MITK_ASSERT_EQUAL(testPointSet.GetPointer(), referencePointSet.GetPointer(), "");
  }

};

MITK_TEST_SUITE_REGISTRATION(mitkPointSetDataInteractor)
<|endoftext|>


<commit_before>/*
 * Radio device I/O interface
 * Written by Thomas Tsou <ttsou@vt.edu>
 *
 * Copyright 2011 Free Software Foundation, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * See the COPYING file in the main directory for details.
 */

#include <radioInterface.h>
#include <Logger.h>

/* Device side buffers */
static short rx_buf[OUTCHUNK * 2 * 2];
static short tx_buf[INCHUNK * 2 * 2];

/* Complex float to short conversion */
static int float_to_short(short *shrt_out, float *flt_in, int num)
{
	int i;

	for (i = 0; i < num; i++) {
		shrt_out[2 * i + 0] = flt_in[2 * i + 0];
		shrt_out[2 * i + 1] = flt_in[2 * i + 1];
	}

	return i;
}

/* Comlpex short to float conversion */
static int short_to_float(float *flt_out, short *shrt_in, int num)
{
	int i;

	for (i = 0; i < num; i++) {
		flt_out[2 * i + 0] = shrt_in[2 * i + 0];
		flt_out[2 * i + 1] = shrt_in[2 * i + 1];
	}

	return i;
}

/* Receive a timestamped chunk from the device */
void RadioInterface::pullBuffer()
{
	bool local_underrun;

	/* Read samples. Fail if we don't get what we want. */
	int num_rd = mRadio->readSamples(rx_buf, OUTCHUNK, &overrun,
					    readTimestamp, &local_underrun);

	LOG(DEBUG) << "Rx read " << num_rd << " samples from device";
	assert(num_rd == OUTCHUNK);

	underrun |= local_underrun;
	readTimestamp += (TIMESTAMP) num_rd;

	short_to_float(rcvBuffer + 2 * rcvCursor, rx_buf, num_rd);
	rcvCursor += num_rd;
}

/* Send timestamped chunk to the device with arbitrary size */
void RadioInterface::pushBuffer()
{
	if (sendCursor < INCHUNK)
		return;

	float_to_short(tx_buf, sendBuffer, sendCursor);

	/* Write samples. Fail if we don't get what we want. */
	int num_smpls = mRadio->writeSamples(tx_buf,
					     sendCursor,
					     &underrun,
					     writeTimestamp);
	assert(num_smpls == sendCursor);

	writeTimestamp += (TIMESTAMP) num_smpls;
	sendCursor = 0;
}
<commit_msg>multi-arfcn, trx: remove float conversion from single channel case<commit_after>/*
 * Radio device I/O interface
 * Written by Thomas Tsou <ttsou@vt.edu>
 *
 * Copyright 2011,2012 Free Software Foundation, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * See the COPYING file in the main directory for details.
 */

#include <radioInterface.h>
#include <Logger.h>

/* Receive a timestamped chunk from the device */
void RadioInterface::pullBuffer()
{
	bool local_underrun;

	/* Read samples. Fail if we don't get what we want. */
	int num_rd = mRadio->readSamples(&rcvBuffer[0][2 * rcvCursor],
					 OUTCHUNK, &overrun,
					 readTimestamp, &local_underrun);

	LOG(DEBUG) << "Rx read " << num_rd << " samples from device";
	assert(num_rd == OUTCHUNK);

	underrun |= local_underrun;
	readTimestamp += (TIMESTAMP) num_rd;

	rcvCursor += num_rd;
}

/* Send timestamped chunk to the device with arbitrary size */
void RadioInterface::pushBuffer()
{
	if (sendCursor < INCHUNK)
		return;

	/* Write samples. Fail if we don't get what we want. */
	int num_smpls = mRadio->writeSamples(sendBuffer[0],
					     sendCursor,
					     &underrun,
					     writeTimestamp);
	assert(num_smpls == sendCursor);

	writeTimestamp += (TIMESTAMP) num_smpls;
	sendCursor = 0;
}

bool RadioInterface::activateChan(int num)
{
	if (num != 0) {
		LOG(ERR) << "Invalid channel selection";
		return false;
	}

	if (chanActive[num]) {
		LOG(ERR) << "Channel already activated";
		return false;
	}

	chanActive[num] = true;

	return true;
}

bool RadioInterface::deactivateChan(int num)
{
	if (num != 0) {
		LOG(ERR) << "Invalid channel selection";
		return false;
	}

	if (chanActive[num]) {
		LOG(ERR) << "Channel not active";
		return false;
	}

	chanActive[num] = false;

	return true;
}

bool RadioInterface::init()
{
}

void RadioInterface::close()
{
}
<|endoftext|>


<commit_before>/*!
	@file
	@author		Albert Semenov
	@date		07/2012
*/

#include "Data.h"
#include "MyGUI.h"

namespace tools
{
	Data::Data() :
		mType(nullptr),
		mParent(nullptr)
	{
	}

	Data::~Data()
	{
		clear();
	}

	void Data::setType(DataInfo* _value)
	{
		mType = _value;

		mProperties.clear();

		if (mType != nullptr)
		{
			const DataInfo::VectorProperty& properties = mType->getProperties();
			for (DataInfo::VectorProperty::const_iterator property = properties.begin(); property != properties.end(); property++)
				mProperties[(*property)->getName()] = "";
		}
	}

	DataInfo* Data::getType()
	{
		return mType;
	}

	Data* Data::getParent()
	{
		return mParent;
	}

	const Data::VectorData& Data::getChilds() const
	{
		return mChilds;
	}

	void Data::clear()
	{
		while (!mChilds.empty())
		{
			Data* child = mChilds.back();
			removeChild(child);
			delete child;
		}
	}

	const Data::MapString Data::getProperties() const
	{
		return mProperties;
	}

	void Data::addChild(Data* _child)
	{
		MYGUI_ASSERT(_child != nullptr, "Child is nullptr");
		MYGUI_ASSERT(_child->getParent() == nullptr, "Child already attached");

		mChilds.push_back(_child);
		_child->mParent = this;
	}

	void Data::removeChild(Data* _child)
	{
		MYGUI_ASSERT(_child->getParent() == this, "Child not found");

		mChilds.erase(std::remove(mChilds.begin(), mChilds.end(), _child), mChilds.end());
		_child->mParent = nullptr;
	}

	const std::string& Data::getPropertyValue(const std::string& _name) const
	{
		MapString::const_iterator property = mProperties.find(_name);
		MYGUI_ASSERT(property != mProperties.end(), "Property " << _name << " not found");

		return (*property).second;
	}

	void Data::setPropertyValue(const std::string& _name, const std::string& _value)
	{
		MapString::iterator property = mProperties.find(_name);
		MYGUI_ASSERT(property != mProperties.end(), "Property " << _name << " not found");

		mProperties[_name] = _value;
	}
}
<commit_msg>fix TestApp broken build<commit_after>/*!
	@file
	@author		Albert Semenov
	@date		07/2012
*/

#include "Data.h"
#include "MyGUI.h"

namespace tools
{
	Data::Data() :
		mType(nullptr),
		mParent(nullptr)
	{
	}

	Data::~Data()
	{
		clear();
	}

	void Data::setType(DataInfo* _value)
	{
		mType = _value;

		mProperties.clear();

		if (mType != nullptr)
		{
			const DataInfo::VectorProperty& properties = mType->getProperties();
			for (DataInfo::VectorProperty::const_iterator property = properties.begin(); property != properties.end(); property++)
				mProperties[(*property)->getName()] = "";
		}
	}

	DataInfo* Data::getType()
	{
		return mType;
	}

	Data* Data::getParent()
	{
		return mParent;
	}

	const Data::VectorData& Data::getChilds() const
	{
		return mChilds;
	}

	void Data::clear()
	{
		while (!mChilds.empty())
		{
			Data* child = mChilds.back();
			removeChild(child);
			delete child;
		}
	}

	const MyGUI::MapString Data::getProperties() const
	{
		return mProperties;
	}

	void Data::addChild(Data* _child)
	{
		MYGUI_ASSERT(_child != nullptr, "Child is nullptr");
		MYGUI_ASSERT(_child->getParent() == nullptr, "Child already attached");

		mChilds.push_back(_child);
		_child->mParent = this;
	}

	void Data::removeChild(Data* _child)
	{
		MYGUI_ASSERT(_child->getParent() == this, "Child not found");

		mChilds.erase(std::remove(mChilds.begin(), mChilds.end(), _child), mChilds.end());
		_child->mParent = nullptr;
	}

	const std::string& Data::getPropertyValue(const std::string& _name) const
	{
		MyGUI::MapString::const_iterator property = mProperties.find(_name);
		MYGUI_ASSERT(property != mProperties.end(), "Property " << _name << " not found");

		return (*property).second;
	}

	void Data::setPropertyValue(const std::string& _name, const std::string& _value)
	{
		MyGUI::MapString::iterator property = mProperties.find(_name);
		MYGUI_ASSERT(property != mProperties.end(), "Property " << _name << " not found");

		mProperties[_name] = _value;
	}
}
<|endoftext|>


<commit_before>#ifndef slic3r_Print_hpp_
#define slic3r_Print_hpp_

#include "libslic3r.h"
#include <set>
#include <string>
#include <vector>
#include <boost/thread.hpp>
#include "BoundingBox.hpp"
#include "Flow.hpp"
#include "PrintConfig.hpp"
#include "Point.hpp"
#include "Layer.hpp"
#include "Model.hpp"
#include "PlaceholderParser.hpp"
#include "SlicingAdaptive.hpp"
#include "LayerHeightSpline.hpp"

namespace Slic3r {

class Print;
class PrintObject;
class ModelObject;

// Print step IDs for keeping track of the print state.
enum PrintStep {
    psSkirt, psBrim,
};
enum PrintObjectStep {
    posLayers, posSlice, posPerimeters, posDetectSurfaces,
    posPrepareInfill, posInfill, posSupportMaterial,
};

// To be instantiated over PrintStep or PrintObjectStep enums.
template <class StepType>
class PrintState
{
    public:
    std::set<StepType> started, done;

    bool is_started(StepType step) const;
    bool is_done(StepType step) const;
    void set_started(StepType step);
    void set_done(StepType step);
    bool invalidate(StepType step);
};

// A PrintRegion object represents a group of volumes to print
// sharing the same config (including the same assigned extruder(s))
class PrintRegion
{
    friend class Print;

    public:
    PrintRegionConfig config;

    Print* print();
    Flow flow(FlowRole role, double layer_height, bool bridge, bool first_layer, double width, const PrintObject &object) const;
    bool invalidate_state_by_config(const PrintConfigBase &config);

    private:
    Print* _print;

    PrintRegion(Print* print);
    ~PrintRegion();
};

typedef std::vector<Layer*> LayerPtrs;
typedef std::vector<SupportLayer*> SupportLayerPtrs;
class BoundingBoxf3;        // TODO: for temporary constructor parameter

class PrintObject
{
    friend class Print;

    public:
    // map of (vectors of volume ids), indexed by region_id
    /* (we use map instead of vector so that we don't have to worry about
       resizing it and the [] operator adds new items automagically) */
    std::map< size_t,std::vector<int> > region_volumes;
    PrintObjectConfig config;
    t_layer_height_ranges layer_height_ranges;

    LayerHeightSpline layer_height_spline;

    // this is set to true when LayerRegion->slices is split in top/internal/bottom
    // so that next call to make_perimeters() performs a union() before computing loops
    bool typed_slices;

    Point3 size;           // XYZ in scaled coordinates

    // scaled coordinates to add to copies (to compensate for the alignment
    // operated when creating the object but still preserving a coherent API
    // for external callers)
    Point _copies_shift;

    // Slic3r::Point objects in scaled G-code coordinates in our coordinates
    Points _shifted_copies;

    LayerPtrs layers;
    SupportLayerPtrs support_layers;
    // TODO: Fill* fill_maker        => (is => 'lazy');
    PrintState<PrintObjectStep> state;

    Print* print();
    ModelObject* model_object() { return this->_model_object; };

    Points copies() const;
    bool add_copy(const Pointf &point);
    bool delete_last_copy();
    bool delete_all_copies();
    bool set_copies(const Points &points);
    bool reload_model_instances();
    BoundingBox bounding_box() const;
    std::set<size_t> extruders() const;
    std::set<size_t> support_material_extruders() const;

    // adds region_id, too, if necessary
    void add_region_volume(int region_id, int volume_id);

    size_t total_layer_count() const;
    size_t layer_count() const;
    void clear_layers();
    Layer* get_layer(int idx) { return this->layers.at(idx); };
    const Layer* get_layer(int idx) const { return this->layers.at(idx); };
    // print_z: top of the layer; slice_z: center of the layer.
    Layer* add_layer(int id, coordf_t height, coordf_t print_z, coordf_t slice_z);
    void delete_layer(int idx);

    size_t support_layer_count() const;
    void clear_support_layers();
    SupportLayer* get_support_layer(int idx) { return this->support_layers.at(idx); };
    const SupportLayer* get_support_layer(int idx) const { return this->support_layers.at(idx); };
    SupportLayer* add_support_layer(int id, coordf_t height, coordf_t print_z);
    void delete_support_layer(int idx);

    // methods for handling state
    bool invalidate_state_by_config(const PrintConfigBase &config);
    bool invalidate_step(PrintObjectStep step);
    bool invalidate_all_steps();

    bool has_support_material() const;
    void detect_surfaces_type();
    void process_external_surfaces();
    void bridge_over_infill();
    coordf_t adjust_layer_height(coordf_t layer_height) const;
    std::vector<coordf_t> generate_object_layers(coordf_t first_layer_height);
    void _slice();
    std::vector<ExPolygons> _slice_region(size_t region_id, std::vector<float> z, bool modifier);
    void _make_perimeters();
    void _infill();

    private:
    Print* _print;
    ModelObject* _model_object;
    Points _copies;      // Slic3r::Point objects in scaled G-code coordinates

    // TODO: call model_object->get_bounding_box() instead of accepting
        // parameter
    PrintObject(Print* print, ModelObject* model_object, const BoundingBoxf3 &modobj_bbox);
    ~PrintObject();
};

typedef std::vector<PrintObject*> PrintObjectPtrs;
typedef std::vector<PrintRegion*> PrintRegionPtrs;

// The complete print tray with possibly multiple objects.
class Print
{
    public:
    PrintConfig config;
    PrintObjectConfig default_object_config;
    PrintRegionConfig default_region_config;
    PrintObjectPtrs objects;
    PrintRegionPtrs regions;
    PlaceholderParser placeholder_parser;
    // TODO: status_cb
    double total_used_filament, total_extruded_volume, total_cost, total_weight;
    std::map<size_t,float> filament_stats;
    PrintState<PrintStep> state;

    // ordered collections of extrusion paths to build skirt loops and brim
    ExtrusionEntityCollection skirt, brim;

    Print();
    ~Print();

    // methods for handling objects
    void clear_objects();
    PrintObject* get_object(size_t idx) { return this->objects.at(idx); };
    const PrintObject* get_object(size_t idx) const { return this->objects.at(idx); };
    void delete_object(size_t idx);
    void reload_object(size_t idx);
    bool reload_model_instances();

    // methods for handling regions
    PrintRegion* get_region(size_t idx) { return this->regions.at(idx); };
    const PrintRegion* get_region(size_t idx) const { return this->regions.at(idx); };
    PrintRegion* add_region();

    // methods for handling state
    bool invalidate_state_by_config(const PrintConfigBase &config);
    bool invalidate_step(PrintStep step);
    bool invalidate_all_steps();
    bool step_done(PrintObjectStep step) const;

    void add_model_object(ModelObject* model_object, int idx = -1);
    bool apply_config(DynamicPrintConfig config);
    bool has_infinite_skirt() const;
    bool has_skirt() const;
    // Returns an empty string if valid, otherwise returns an error message.
    std::string validate() const;
    BoundingBox bounding_box() const;
    BoundingBox total_bounding_box() const;
    double skirt_first_layer_height() const;
    Flow brim_flow() const;
    Flow skirt_flow() const;
    void _make_brim();

    std::set<size_t> object_extruders() const;
    std::set<size_t> support_material_extruders() const;
    std::set<size_t> extruders() const;
    size_t brim_extruder() const;
    void _simplify_slices(double distance);
    double max_allowed_layer_height() const;
    bool has_support_material() const;
    void auto_assign_extruders(ModelObject* model_object) const;
    std::string output_filename();
    std::string output_filepath(const std::string &path);

    private:
    void clear_regions();
    void delete_region(size_t idx);
    PrintRegionConfig _region_config_from_model_volume(const ModelVolume &volume);
};

#define FOREACH_BASE(type, container, iterator) for (type::const_iterator iterator = (container).begin(); iterator != (container).end(); ++iterator)
#define FOREACH_REGION(print, region)       FOREACH_BASE(PrintRegionPtrs, (print)->regions, region)
#define FOREACH_OBJECT(print, object)       FOREACH_BASE(PrintObjectPtrs, (print)->objects, object)
#define FOREACH_LAYER(object, layer)        FOREACH_BASE(LayerPtrs, (object)->layers, layer)
#define FOREACH_LAYERREGION(layer, layerm)  FOREACH_BASE(LayerRegionPtrs, (layer)->regions, layerm)

}

#endif
<commit_msg>Changed a few comments to doxygen format.<commit_after>#ifndef slic3r_Print_hpp_
#define slic3r_Print_hpp_

#include "libslic3r.h"
#include <set>
#include <string>
#include <vector>
#include <boost/thread.hpp>
#include "BoundingBox.hpp"
#include "Flow.hpp"
#include "PrintConfig.hpp"
#include "Point.hpp"
#include "Layer.hpp"
#include "Model.hpp"
#include "PlaceholderParser.hpp"
#include "SlicingAdaptive.hpp"
#include "LayerHeightSpline.hpp"

namespace Slic3r {

class Print;
class PrintObject;
class ModelObject;

// Print step IDs for keeping track of the print state.
enum PrintStep {
    psSkirt, psBrim,
};
enum PrintObjectStep {
    posLayers, posSlice, posPerimeters, posDetectSurfaces,
    posPrepareInfill, posInfill, posSupportMaterial,
};

// To be instantiated over PrintStep or PrintObjectStep enums.
template <class StepType>
class PrintState
{
    public:
    std::set<StepType> started, done;

    bool is_started(StepType step) const;
    bool is_done(StepType step) const;
    void set_started(StepType step);
    void set_done(StepType step);
    bool invalidate(StepType step);
};

// A PrintRegion object represents a group of volumes to print
// sharing the same config (including the same assigned extruder(s))
class PrintRegion
{
    friend class Print;

    public:
    PrintRegionConfig config;

    Print* print();
    Flow flow(FlowRole role, double layer_height, bool bridge, bool first_layer, double width, const PrintObject &object) const;
    bool invalidate_state_by_config(const PrintConfigBase &config);

    private:
    Print* _print;

    PrintRegion(Print* print);
    ~PrintRegion();
};

typedef std::vector<Layer*> LayerPtrs;
typedef std::vector<SupportLayer*> SupportLayerPtrs;
class BoundingBoxf3;        // TODO: for temporary constructor parameter

class PrintObject
{
    friend class Print;

    public:
    /// map of (vectors of volume ids), indexed by region_id
    /// (we use map instead of vector so that we don't have to worry about
    /// resizing it and the [] operator adds new items automagically)
    std::map< size_t,std::vector<int> > region_volumes;
    PrintObjectConfig config; //< Configuration
    t_layer_height_ranges layer_height_ranges;

    LayerHeightSpline layer_height_spline;

    /// this is set to true when LayerRegion->slices is split in top/internal/bottom
    /// so that next call to make_perimeters() performs a union() before computing loops
    bool typed_slices;

    Point3 size;           //< XYZ in scaled coordinates

    // scaled coordinates to add to copies (to compensate for the alignment
    // operated when creating the object but still preserving a coherent API
    // for external callers)
    Point _copies_shift;

    // Slic3r::Point objects in scaled G-code coordinates in our coordinates
    Points _shifted_copies;

    LayerPtrs layers;
    SupportLayerPtrs support_layers;
    // TODO: Fill* fill_maker        => (is => 'lazy');
    PrintState<PrintObjectStep> state;

    Print* print();
    ModelObject* model_object() { return this->_model_object; };

    Points copies() const;
    bool add_copy(const Pointf &point);
    bool delete_last_copy();
    bool delete_all_copies();
    bool set_copies(const Points &points);
    bool reload_model_instances();
    BoundingBox bounding_box() const;
    std::set<size_t> extruders() const;
    std::set<size_t> support_material_extruders() const;

    // adds region_id, too, if necessary
    void add_region_volume(int region_id, int volume_id);

    size_t total_layer_count() const;
    size_t layer_count() const;
    void clear_layers();
    Layer* get_layer(int idx) { return this->layers.at(idx); };
    const Layer* get_layer(int idx) const { return this->layers.at(idx); };
    // print_z: top of the layer; slice_z: center of the layer.
    Layer* add_layer(int id, coordf_t height, coordf_t print_z, coordf_t slice_z);
    void delete_layer(int idx);

    size_t support_layer_count() const;
    void clear_support_layers();
    SupportLayer* get_support_layer(int idx) { return this->support_layers.at(idx); };
    const SupportLayer* get_support_layer(int idx) const { return this->support_layers.at(idx); };
    SupportLayer* add_support_layer(int id, coordf_t height, coordf_t print_z);
    void delete_support_layer(int idx);

    // methods for handling state
    bool invalidate_state_by_config(const PrintConfigBase &config);
    bool invalidate_step(PrintObjectStep step);
    bool invalidate_all_steps();

    bool has_support_material() const;
    void detect_surfaces_type();
    void process_external_surfaces();
    void bridge_over_infill();
    coordf_t adjust_layer_height(coordf_t layer_height) const;
    std::vector<coordf_t> generate_object_layers(coordf_t first_layer_height);
    void _slice();
    std::vector<ExPolygons> _slice_region(size_t region_id, std::vector<float> z, bool modifier);
    void _make_perimeters();
    void _infill();

    private:
    Print* _print;
    ModelObject* _model_object;
    Points _copies;      // Slic3r::Point objects in scaled G-code coordinates

    // TODO: call model_object->get_bounding_box() instead of accepting
        // parameter
    PrintObject(Print* print, ModelObject* model_object, const BoundingBoxf3 &modobj_bbox);
    ~PrintObject();
};

typedef std::vector<PrintObject*> PrintObjectPtrs;
typedef std::vector<PrintRegion*> PrintRegionPtrs;

// The complete print tray with possibly multiple objects.
class Print
{
    public:
    PrintConfig config;
    PrintObjectConfig default_object_config;
    PrintRegionConfig default_region_config;
    PrintObjectPtrs objects;
    PrintRegionPtrs regions;
    PlaceholderParser placeholder_parser;
    // TODO: status_cb
    double total_used_filament, total_extruded_volume, total_cost, total_weight;
    std::map<size_t,float> filament_stats;
    PrintState<PrintStep> state;

    // ordered collections of extrusion paths to build skirt loops and brim
    ExtrusionEntityCollection skirt, brim;

    Print();
    ~Print();

    // methods for handling objects
    void clear_objects();
    PrintObject* get_object(size_t idx) { return this->objects.at(idx); };
    const PrintObject* get_object(size_t idx) const { return this->objects.at(idx); };
    void delete_object(size_t idx);
    void reload_object(size_t idx);
    bool reload_model_instances();

    // methods for handling regions
    PrintRegion* get_region(size_t idx) { return this->regions.at(idx); };
    const PrintRegion* get_region(size_t idx) const { return this->regions.at(idx); };
    PrintRegion* add_region();

    // methods for handling state
    bool invalidate_state_by_config(const PrintConfigBase &config);
    bool invalidate_step(PrintStep step);
    bool invalidate_all_steps();
    bool step_done(PrintObjectStep step) const;

    void add_model_object(ModelObject* model_object, int idx = -1);
    bool apply_config(DynamicPrintConfig config);
    bool has_infinite_skirt() const;
    bool has_skirt() const;
    // Returns an empty string if valid, otherwise returns an error message.
    std::string validate() const;
    BoundingBox bounding_box() const;
    BoundingBox total_bounding_box() const;
    double skirt_first_layer_height() const;
    Flow brim_flow() const;
    Flow skirt_flow() const;
    void _make_brim();

    std::set<size_t> object_extruders() const;
    std::set<size_t> support_material_extruders() const;
    std::set<size_t> extruders() const;
    size_t brim_extruder() const;
    void _simplify_slices(double distance);
    double max_allowed_layer_height() const;
    bool has_support_material() const;
    void auto_assign_extruders(ModelObject* model_object) const;
    std::string output_filename();
    std::string output_filepath(const std::string &path);

    private:
    void clear_regions();
    void delete_region(size_t idx);
    PrintRegionConfig _region_config_from_model_volume(const ModelVolume &volume);
};

#define FOREACH_BASE(type, container, iterator) for (type::const_iterator iterator = (container).begin(); iterator != (container).end(); ++iterator)
#define FOREACH_REGION(print, region)       FOREACH_BASE(PrintRegionPtrs, (print)->regions, region)
#define FOREACH_OBJECT(print, object)       FOREACH_BASE(PrintObjectPtrs, (print)->objects, object)
#define FOREACH_LAYER(object, layer)        FOREACH_BASE(LayerPtrs, (object)->layers, layer)
#define FOREACH_LAYERREGION(layer, layerm)  FOREACH_BASE(LayerRegionPtrs, (layer)->regions, layerm)

}

#endif
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <cppuhelper/implbase3.hxx>
#include <comphelper/servicedecl.hxx>

#include <com/sun/star/deployment/UpdateInformationProvider.hpp>
#include <com/sun/star/deployment/XPackage.hpp>
#include <com/sun/star/deployment/XPackageInformationProvider.hpp>
#include <com/sun/star/deployment/ExtensionManager.hpp>
#include <com/sun/star/deployment/XUpdateInformationProvider.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/task/XAbortChannel.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/xml/dom/XElement.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>

#include <com/sun/star/uno/Reference.hxx>
#include <rtl/ustring.hxx>
#include <ucbhelper/content.hxx>

#include "dp_dependencies.hxx"
#include "dp_descriptioninfoset.hxx"
#include "dp_identifier.hxx"
#include "dp_version.hxx"
#include "dp_misc.h"
#include "dp_update.hxx"

namespace beans      = com::sun::star::beans ;
namespace deployment = com::sun::star::deployment ;
namespace lang       = com::sun::star::lang ;
namespace registry   = com::sun::star::registry ;
namespace task       = com::sun::star::task ;
namespace css_ucb    = com::sun::star::ucb ;
namespace uno        = com::sun::star::uno ;
namespace xml = com::sun::star::xml ;

namespace dp_info {

class PackageInformationProvider :
        public ::cppu::WeakImplHelper1< deployment::XPackageInformationProvider >

{
    public:
                 PackageInformationProvider( uno::Reference< uno::XComponentContext >const& xContext);
    virtual     ~PackageInformationProvider();

    // XPackageInformationProvider
    virtual OUString SAL_CALL getPackageLocation( const OUString& extensionId )
        throw ( uno::RuntimeException, std::exception ) SAL_OVERRIDE;
    virtual uno::Sequence< uno::Sequence< OUString > > SAL_CALL isUpdateAvailable( const OUString& extensionId )
        throw ( uno::RuntimeException, std::exception ) SAL_OVERRIDE;
    virtual uno::Sequence< uno::Sequence< OUString > > SAL_CALL getExtensionList()
        throw ( uno::RuntimeException, std::exception ) SAL_OVERRIDE;

private:

    uno::Reference< uno::XComponentContext> mxContext;

    OUString getPackageLocation( const OUString& repository,
                                      const OUString& _sExtensionId );

    uno::Reference< deployment::XUpdateInformationProvider > mxUpdateInformation;
};

PackageInformationProvider::PackageInformationProvider( uno::Reference< uno::XComponentContext > const& xContext) :
    mxContext( xContext ),
    mxUpdateInformation( deployment::UpdateInformationProvider::create( xContext ) )
{
}

PackageInformationProvider::~PackageInformationProvider()
{
}

OUString PackageInformationProvider::getPackageLocation(
    const OUString & repository,
    const OUString& _rExtensionId )
{
    OUString aLocationURL;
    uno::Reference<deployment::XExtensionManager> xManager =
        deployment::ExtensionManager::get(mxContext);

    if ( xManager.is() )
    {
        const uno::Sequence< uno::Reference< deployment::XPackage > > packages(
                xManager->getDeployedExtensions(
                    repository,
                    uno::Reference< task::XAbortChannel >(),
                    uno::Reference< css_ucb::XCommandEnvironment > () ) );

        for ( int pos = packages.getLength(); pos--; )
        {
            try
            {
                const beans::Optional< OUString > aID = packages[ pos ]->getIdentifier();
                if ( aID.IsPresent && (aID.Value == _rExtensionId ) )
                {
                    aLocationURL = packages[ pos ]->getURL();
                    break;
                }
            }
            catch ( uno::RuntimeException & ) {}
        }
    }

    return aLocationURL;
}

OUString SAL_CALL
PackageInformationProvider::getPackageLocation( const OUString& _sExtensionId )
    throw ( uno::RuntimeException, std::exception )
{
    OUString aLocationURL = getPackageLocation( OUString("user"), _sExtensionId );

    if ( aLocationURL.isEmpty() )
    {
        aLocationURL = getPackageLocation( OUString("shared"), _sExtensionId );
    }
    if ( aLocationURL.isEmpty() )
    {
        aLocationURL = getPackageLocation( OUString("bundled"), _sExtensionId );
    }
    if ( !aLocationURL.isEmpty() )
    {
        ::ucbhelper::Content aContent( aLocationURL, NULL, mxContext );
        aLocationURL = aContent.getURL();
    }
    return aLocationURL;
}

uno::Sequence< uno::Sequence< OUString > > SAL_CALL
PackageInformationProvider::isUpdateAvailable( const OUString& _sExtensionId )
    throw ( uno::RuntimeException, std::exception )
{
    uno::Sequence< uno::Sequence< OUString > > aList;

    uno::Reference<deployment::XExtensionManager> extMgr =
        deployment::ExtensionManager::get(mxContext);

    if (!extMgr.is())
    {
        OSL_ASSERT(false);
        return aList;
    }
    std::vector<std::pair<uno::Reference<deployment::XPackage>, uno::Any > > errors;
    dp_misc::UpdateInfoMap updateInfoMap;
    if (!_sExtensionId.isEmpty())
    {
        std::vector<uno::Reference<deployment::XPackage> > vecExtensions;
        uno::Reference<deployment::XPackage> extension;
        try
        {
            extension = dp_misc::getExtensionWithHighestVersion(
                extMgr->getExtensionsWithSameIdentifier(
                    _sExtensionId, _sExtensionId, uno::Reference<css_ucb::XCommandEnvironment>()));
            vecExtensions.push_back(extension);
        }
        catch (lang::IllegalArgumentException &)
        {
            OSL_ASSERT(false);
        }
        updateInfoMap = dp_misc::getOnlineUpdateInfos(
            mxContext, extMgr, mxUpdateInformation, &vecExtensions, errors);
    }
    else
    {
        updateInfoMap = dp_misc::getOnlineUpdateInfos(
            mxContext, extMgr, mxUpdateInformation, NULL, errors);
    }

    int nCount = 0;
    for (dp_misc::UpdateInfoMap::iterator i(updateInfoMap.begin()); i != updateInfoMap.end(); ++i)
    {
        dp_misc::UpdateInfo const & info = i->second;

        OUString sOnlineVersion;
        if (info.info.is())
        {
            // check, if there are unsatisfied dependencies and ignore this online update
            dp_misc::DescriptionInfoset infoset(mxContext, info.info);
            uno::Sequence< uno::Reference< xml::dom::XElement > >
                ds( dp_misc::Dependencies::check( infoset ) );
            if ( ! ds.getLength() )
                sOnlineVersion = info.version;
        }

        OUString sVersionUser;
        OUString sVersionShared;
        OUString sVersionBundled;
        uno::Sequence< uno::Reference< deployment::XPackage> > extensions;
        try {
            extensions = extMgr->getExtensionsWithSameIdentifier(
                dp_misc::getIdentifier(info.extension), info.extension->getName(),
                uno::Reference<css_ucb::XCommandEnvironment>());
        } catch (lang::IllegalArgumentException& e) {
            SAL_WARN(
                "desktop.deployment",
                "ignoring IllegalArgumentException \"" << e.Message << "\"");
            continue;
        }
        OSL_ASSERT(extensions.getLength() == 3);
        if (extensions[0].is() )
            sVersionUser = extensions[0]->getVersion();
        if (extensions[1].is() )
            sVersionShared = extensions[1]->getVersion();
        if (extensions[2].is() )
            sVersionBundled = extensions[2]->getVersion();

        bool bSharedReadOnly = extMgr->isReadOnlyRepository("shared");

        dp_misc::UPDATE_SOURCE sourceUser = dp_misc::isUpdateUserExtension(
            bSharedReadOnly, sVersionUser, sVersionShared, sVersionBundled, sOnlineVersion);
        dp_misc::UPDATE_SOURCE sourceShared = dp_misc::isUpdateSharedExtension(
            bSharedReadOnly, sVersionShared, sVersionBundled, sOnlineVersion);

        OUString updateVersionUser;
        OUString updateVersionShared;
        if (sourceUser != dp_misc::UPDATE_SOURCE_NONE)
            updateVersionUser = dp_misc::getHighestVersion(
                OUString(), sVersionShared, sVersionBundled, sOnlineVersion);
        if (sourceShared  != dp_misc::UPDATE_SOURCE_NONE)
            updateVersionShared = dp_misc::getHighestVersion(
                OUString(), OUString(), sVersionBundled, sOnlineVersion);
        OUString updateVersion;
        if (dp_misc::compareVersions(updateVersionUser, updateVersionShared) == dp_misc::GREATER)
            updateVersion = updateVersionUser;
        else
            updateVersion = updateVersionShared;
        if (!updateVersion.isEmpty())
        {

            OUString aNewEntry[2];
            aNewEntry[0] = i->first;
            aNewEntry[1] = updateVersion;
            aList.realloc( ++nCount );
            aList[ nCount-1 ] = ::uno::Sequence< OUString >( aNewEntry, 2 );
        }
    }
    return aList;
}

uno::Sequence< uno::Sequence< OUString > > SAL_CALL PackageInformationProvider::getExtensionList()
    throw ( uno::RuntimeException, std::exception )
{
    const uno::Reference<deployment::XExtensionManager> mgr =
        deployment::ExtensionManager::get(mxContext);

    if (!mgr.is())
        return uno::Sequence< uno::Sequence< OUString > >();

    const uno::Sequence< uno::Sequence< uno::Reference<deployment::XPackage > > >
        allExt =  mgr->getAllExtensions(
            uno::Reference< task::XAbortChannel >(),
            uno::Reference< css_ucb::XCommandEnvironment > () );

    uno::Sequence< uno::Sequence< OUString > > retList;

    sal_Int32 cAllIds = allExt.getLength();
    retList.realloc(cAllIds);

    for (sal_Int32 i = 0; i < cAllIds; i++)
    {
        //The inner sequence contains extensions with the same identifier from
        //all the different repositories, that is user, share, bundled.
        const uno::Sequence< uno::Reference< deployment::XPackage > > &
            seqExtension = allExt[i];
        sal_Int32 cExt = seqExtension.getLength();
        OSL_ASSERT(cExt == 3);
        for (sal_Int32 j = 0; j < cExt; j++)
        {
            //ToDo according to the old code the first found extenions is used
            //even if another one with the same id has a better version.
            uno::Reference< deployment::XPackage > const & xExtension( seqExtension[j] );
            if (xExtension.is())
            {
                OUString aNewEntry[2];
                aNewEntry[0] = dp_misc::getIdentifier(xExtension);
                aNewEntry[1] = xExtension->getVersion();
                retList[i] = ::uno::Sequence< OUString >( aNewEntry, 2 );
                break;
            }
        }
    }
    return retList;
}

namespace sdecl = comphelper::service_decl;
sdecl::class_<PackageInformationProvider> servicePIP;
extern sdecl::ServiceDecl const serviceDecl(
    servicePIP,
    // a private one:
    "com.sun.star.comp.deployment.PackageInformationProvider",
    "com.sun.star.comp.deployment.PackageInformationProvider" );

} // namespace dp_info

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#706495 Uncaught exception<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <cppuhelper/implbase3.hxx>
#include <comphelper/servicedecl.hxx>

#include <com/sun/star/deployment/UpdateInformationProvider.hpp>
#include <com/sun/star/deployment/XPackage.hpp>
#include <com/sun/star/deployment/XPackageInformationProvider.hpp>
#include <com/sun/star/deployment/ExtensionManager.hpp>
#include <com/sun/star/deployment/XUpdateInformationProvider.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/task/XAbortChannel.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/xml/dom/XElement.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>

#include <com/sun/star/uno/Reference.hxx>
#include <rtl/ustring.hxx>
#include <ucbhelper/content.hxx>

#include "dp_dependencies.hxx"
#include "dp_descriptioninfoset.hxx"
#include "dp_identifier.hxx"
#include "dp_version.hxx"
#include "dp_misc.h"
#include "dp_update.hxx"

namespace beans      = com::sun::star::beans ;
namespace deployment = com::sun::star::deployment ;
namespace lang       = com::sun::star::lang ;
namespace registry   = com::sun::star::registry ;
namespace task       = com::sun::star::task ;
namespace css_ucb    = com::sun::star::ucb ;
namespace uno        = com::sun::star::uno ;
namespace xml = com::sun::star::xml ;

namespace dp_info {

class PackageInformationProvider :
        public ::cppu::WeakImplHelper1< deployment::XPackageInformationProvider >

{
    public:
                 PackageInformationProvider( uno::Reference< uno::XComponentContext >const& xContext);
    virtual     ~PackageInformationProvider();

    // XPackageInformationProvider
    virtual OUString SAL_CALL getPackageLocation( const OUString& extensionId )
        throw ( uno::RuntimeException, std::exception ) SAL_OVERRIDE;
    virtual uno::Sequence< uno::Sequence< OUString > > SAL_CALL isUpdateAvailable( const OUString& extensionId )
        throw ( uno::RuntimeException, std::exception ) SAL_OVERRIDE;
    virtual uno::Sequence< uno::Sequence< OUString > > SAL_CALL getExtensionList()
        throw ( uno::RuntimeException, std::exception ) SAL_OVERRIDE;

private:

    uno::Reference< uno::XComponentContext> mxContext;

    OUString getPackageLocation( const OUString& repository,
                                      const OUString& _sExtensionId );

    uno::Reference< deployment::XUpdateInformationProvider > mxUpdateInformation;
};

PackageInformationProvider::PackageInformationProvider( uno::Reference< uno::XComponentContext > const& xContext) :
    mxContext( xContext ),
    mxUpdateInformation( deployment::UpdateInformationProvider::create( xContext ) )
{
}

PackageInformationProvider::~PackageInformationProvider()
{
}

OUString PackageInformationProvider::getPackageLocation(
    const OUString & repository,
    const OUString& _rExtensionId )
{
    OUString aLocationURL;
    uno::Reference<deployment::XExtensionManager> xManager =
        deployment::ExtensionManager::get(mxContext);

    if ( xManager.is() )
    {
        const uno::Sequence< uno::Reference< deployment::XPackage > > packages(
                xManager->getDeployedExtensions(
                    repository,
                    uno::Reference< task::XAbortChannel >(),
                    uno::Reference< css_ucb::XCommandEnvironment > () ) );

        for ( int pos = packages.getLength(); pos--; )
        {
            try
            {
                const beans::Optional< OUString > aID = packages[ pos ]->getIdentifier();
                if ( aID.IsPresent && (aID.Value == _rExtensionId ) )
                {
                    aLocationURL = packages[ pos ]->getURL();
                    break;
                }
            }
            catch ( uno::RuntimeException & ) {}
        }
    }

    return aLocationURL;
}

OUString SAL_CALL
PackageInformationProvider::getPackageLocation( const OUString& _sExtensionId )
    throw ( uno::RuntimeException, std::exception )
{
    OUString aLocationURL = getPackageLocation( OUString("user"), _sExtensionId );

    if ( aLocationURL.isEmpty() )
    {
        aLocationURL = getPackageLocation( OUString("shared"), _sExtensionId );
    }
    if ( aLocationURL.isEmpty() )
    {
        aLocationURL = getPackageLocation( OUString("bundled"), _sExtensionId );
    }
    if ( !aLocationURL.isEmpty() )
    {
        try
        {
            ::ucbhelper::Content aContent( aLocationURL, NULL, mxContext );
            aLocationURL = aContent.getURL();
        }
        catch (const css::ucb::ContentCreationException& e)
        {
           SAL_WARN(
            "desktop.deployment",
            "ignoring ContentCreationException \"" << e.Message << "\"");
        }
    }
    return aLocationURL;
}

uno::Sequence< uno::Sequence< OUString > > SAL_CALL
PackageInformationProvider::isUpdateAvailable( const OUString& _sExtensionId )
    throw ( uno::RuntimeException, std::exception )
{
    uno::Sequence< uno::Sequence< OUString > > aList;

    uno::Reference<deployment::XExtensionManager> extMgr =
        deployment::ExtensionManager::get(mxContext);

    if (!extMgr.is())
    {
        OSL_ASSERT(false);
        return aList;
    }
    std::vector<std::pair<uno::Reference<deployment::XPackage>, uno::Any > > errors;
    dp_misc::UpdateInfoMap updateInfoMap;
    if (!_sExtensionId.isEmpty())
    {
        std::vector<uno::Reference<deployment::XPackage> > vecExtensions;
        uno::Reference<deployment::XPackage> extension;
        try
        {
            extension = dp_misc::getExtensionWithHighestVersion(
                extMgr->getExtensionsWithSameIdentifier(
                    _sExtensionId, _sExtensionId, uno::Reference<css_ucb::XCommandEnvironment>()));
            vecExtensions.push_back(extension);
        }
        catch (lang::IllegalArgumentException &)
        {
            OSL_ASSERT(false);
        }
        updateInfoMap = dp_misc::getOnlineUpdateInfos(
            mxContext, extMgr, mxUpdateInformation, &vecExtensions, errors);
    }
    else
    {
        updateInfoMap = dp_misc::getOnlineUpdateInfos(
            mxContext, extMgr, mxUpdateInformation, NULL, errors);
    }

    int nCount = 0;
    for (dp_misc::UpdateInfoMap::iterator i(updateInfoMap.begin()); i != updateInfoMap.end(); ++i)
    {
        dp_misc::UpdateInfo const & info = i->second;

        OUString sOnlineVersion;
        if (info.info.is())
        {
            // check, if there are unsatisfied dependencies and ignore this online update
            dp_misc::DescriptionInfoset infoset(mxContext, info.info);
            uno::Sequence< uno::Reference< xml::dom::XElement > >
                ds( dp_misc::Dependencies::check( infoset ) );
            if ( ! ds.getLength() )
                sOnlineVersion = info.version;
        }

        OUString sVersionUser;
        OUString sVersionShared;
        OUString sVersionBundled;
        uno::Sequence< uno::Reference< deployment::XPackage> > extensions;
        try {
            extensions = extMgr->getExtensionsWithSameIdentifier(
                dp_misc::getIdentifier(info.extension), info.extension->getName(),
                uno::Reference<css_ucb::XCommandEnvironment>());
        } catch (const lang::IllegalArgumentException& e) {
            SAL_WARN(
                "desktop.deployment",
                "ignoring IllegalArgumentException \"" << e.Message << "\"");
            continue;
        }
        OSL_ASSERT(extensions.getLength() == 3);
        if (extensions[0].is() )
            sVersionUser = extensions[0]->getVersion();
        if (extensions[1].is() )
            sVersionShared = extensions[1]->getVersion();
        if (extensions[2].is() )
            sVersionBundled = extensions[2]->getVersion();

        bool bSharedReadOnly = extMgr->isReadOnlyRepository("shared");

        dp_misc::UPDATE_SOURCE sourceUser = dp_misc::isUpdateUserExtension(
            bSharedReadOnly, sVersionUser, sVersionShared, sVersionBundled, sOnlineVersion);
        dp_misc::UPDATE_SOURCE sourceShared = dp_misc::isUpdateSharedExtension(
            bSharedReadOnly, sVersionShared, sVersionBundled, sOnlineVersion);

        OUString updateVersionUser;
        OUString updateVersionShared;
        if (sourceUser != dp_misc::UPDATE_SOURCE_NONE)
            updateVersionUser = dp_misc::getHighestVersion(
                OUString(), sVersionShared, sVersionBundled, sOnlineVersion);
        if (sourceShared  != dp_misc::UPDATE_SOURCE_NONE)
            updateVersionShared = dp_misc::getHighestVersion(
                OUString(), OUString(), sVersionBundled, sOnlineVersion);
        OUString updateVersion;
        if (dp_misc::compareVersions(updateVersionUser, updateVersionShared) == dp_misc::GREATER)
            updateVersion = updateVersionUser;
        else
            updateVersion = updateVersionShared;
        if (!updateVersion.isEmpty())
        {

            OUString aNewEntry[2];
            aNewEntry[0] = i->first;
            aNewEntry[1] = updateVersion;
            aList.realloc( ++nCount );
            aList[ nCount-1 ] = ::uno::Sequence< OUString >( aNewEntry, 2 );
        }
    }
    return aList;
}

uno::Sequence< uno::Sequence< OUString > > SAL_CALL PackageInformationProvider::getExtensionList()
    throw ( uno::RuntimeException, std::exception )
{
    const uno::Reference<deployment::XExtensionManager> mgr =
        deployment::ExtensionManager::get(mxContext);

    if (!mgr.is())
        return uno::Sequence< uno::Sequence< OUString > >();

    const uno::Sequence< uno::Sequence< uno::Reference<deployment::XPackage > > >
        allExt =  mgr->getAllExtensions(
            uno::Reference< task::XAbortChannel >(),
            uno::Reference< css_ucb::XCommandEnvironment > () );

    uno::Sequence< uno::Sequence< OUString > > retList;

    sal_Int32 cAllIds = allExt.getLength();
    retList.realloc(cAllIds);

    for (sal_Int32 i = 0; i < cAllIds; i++)
    {
        //The inner sequence contains extensions with the same identifier from
        //all the different repositories, that is user, share, bundled.
        const uno::Sequence< uno::Reference< deployment::XPackage > > &
            seqExtension = allExt[i];
        sal_Int32 cExt = seqExtension.getLength();
        OSL_ASSERT(cExt == 3);
        for (sal_Int32 j = 0; j < cExt; j++)
        {
            //ToDo according to the old code the first found extenions is used
            //even if another one with the same id has a better version.
            uno::Reference< deployment::XPackage > const & xExtension( seqExtension[j] );
            if (xExtension.is())
            {
                OUString aNewEntry[2];
                aNewEntry[0] = dp_misc::getIdentifier(xExtension);
                aNewEntry[1] = xExtension->getVersion();
                retList[i] = ::uno::Sequence< OUString >( aNewEntry, 2 );
                break;
            }
        }
    }
    return retList;
}

namespace sdecl = comphelper::service_decl;
sdecl::class_<PackageInformationProvider> servicePIP;
extern sdecl::ServiceDecl const serviceDecl(
    servicePIP,
    // a private one:
    "com.sun.star.comp.deployment.PackageInformationProvider",
    "com.sun.star.comp.deployment.PackageInformationProvider" );

} // namespace dp_info

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>//Author: John Xu. 6/23/2019
//Initial code drafted on 6/21/2019 on a flight back from Plantation, FL
//
//The initial problem was an Amazon phone screen problem: print out the top K number from a given array of integers
//
//Initally the answer should be simple: take each integer from the array and insert into a priority queue and then
//do a loop to pop from this prioroty queue to print out each of the integer
//
//Then later on, it is asked, what if the array is so big, such as comming from a stream, and does not fit into the memory ?
//My immediate response was: once we reached size K for the priority queue, we remove the last element before insert the
//new element into the priority queue, if the new element is larger than the last element of the priority queue.
//
// Above immediate response has following defects:
//
// 1) priority queue does not have a method to access or remove the last element
//    regular queue has push, pop, front, back, size, empty.
//    dequeue has push_back, push_front, pop_back, pop_front, size, empty
//    priority_queue has push, pop, top, size, empty
//
// 2) over use of priority queue may be too slow. Priority queue better used for cases where the data is really used as
//    a queue structure, where processed elements are gone from the storage, where no need to keep the historical top K
//    element.
//
// 3) If we want to keep the historical top K element from a unlimited stream inout, it is more efficient to maintain a
//    dynamic array of size K. Maintain the array sorted from large to small. When new element comes in, if it is smaller
//    than the last one, ignore it. Otherwise, remove the last one, and shift every element one position to next one if that
//    element is smaller than the new one, then insert the new one at the end of the shift.
//

//example of keep top 3 element from a unlimited stream of integers: top3
// generic cases: topk
//
// compiling instruction: g++ --std=c++17 topk.cpp -o topk

#include <fstream>
#include <iostream>
#include <filesystem>

#define MIN_INT -65535

void top3(char* filename)
{
    using namespace std;
    namespace fs = std::filesystem;
    fs::path fp {filename};
    if (!fs::exists(fp)) {
        cout << "file " << filename << " not exist" << endl;
        return;
    }

    ifstream fstrm(filename);

    int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;
    int number;
    while (! fstrm.eof()) {
        fstrm >> number;
        if (number > top1) {
            top2 = top1;
            top1 = number;
        }
        else if (number > top2){
            top3 = top2;
            top2 = number;
        }
        else if (number > top3)
            top3 = number;

    }
    cout << top1 << endl << top2 << endl << top3 << endl;
}

void topk(char* filename, int K)
{
    using namespace std;
    namespace fs = std::filesystem;
    fs::path fp {filename};
    if (!fs::exists(fp)) {
        cout << "file " << filename << " not exist" << endl;
        return;
    }

    ifstream fstrm(filename);

//    int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;
    int number;
    int arr[K];

    for (int i=0; i<K; i++)
      arr[i] = MIN_INT;

    while (! fstrm.eof()) {

        fstrm >> number;
        int i = K-1;

        if (number < arr[K-1])
            break;

        for (i = K-1; i >= 0; i--) {
            cout << " number = " << number << " i = " << i << endl;     //debug
            if (number < arr[i] )           // arr[i] > number > arr[i+1]
                break;
        }

        if (i < 0)
            i = 0;

        int j = K-1;
        for (j=K-1; j>i; j--) {
            arr[j] = arr[j-1];
        }

        arr[i] = number;

        cout << " i = " << i << " number = " << number << endl;
    }

    fstrm.close();

    for (int i=0; i<K; i++)
     cout << arr[i] << endl;

}

void topk2(char* filename, int K)
{
    using namespace std;
    namespace fs = std::filesystem;
    fs::path fp {filename};
    if (!fs::exists(fp)) {
        cout << "file " << filename << " not exist" << endl;
        return;
    }

    ifstream fstrm(filename);

//    int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;
    int number;
    int arr[K];

    for (int i=0; i<K; i++)
      arr[i] = MIN_INT;

    while (! fstrm.eof()) {

        fstrm >> number;
        int i = K-1;

        if (number < arr[K-1])
            break;

        int l =0;
        for (i = 0; i < K; i++) {
            if ( number > arr[i]) {
               l = i;                   //this will fix the uncertainty of value i
               break;
            }
        }

        int j = K-1;
        for (j=K-1; j>l; j--) {
            arr[j] = arr[j-1];
        }

        arr[l] = number;

        cout << " l = " << l << " number = " << number << endl;
    }

    fstrm.close();

    for (int i=0; i<K; i++)
     cout << arr[i] << endl;

}

int main(int argc, char* argv[])
{
    int K = atoi(argv[2]);
    topk2(argv[1], K);
    return 0;
}

//above version still have some bugs. an input of 1, 2, 3, 4, 5, 6 with command top example.txt 9
// will output 6, 6, 5, 4, 3, 2, 1, -65535, -65535.  When we expect 6, 5, 4, 3, 2, 1, -65535, -65535
// an input of 5,4,3,2,1,0 with top example2.txt 9 will output 4,3,2,1,0,0,5, -65535, -65535

// Future modified versions will need to be worked on and put in topk2, topk3, ..., etc
//
// topk2 has less bug than topk, but testing data still shows 6,6,5,4,3,2 for example.txt and 0,5,4,3,2,1 for
// example2.txt.  This is due to the last number get read twice in the stream.
/*
 l = 0 number = 1
 l = 0 number = 2
 l = 0 number = 3
 l = 0 number = 4
 l = 0 number = 5
 l = 0 number = 6
 l = 1 number = 6

 l = 0 number = 5
 l = 1 number = 4
 l = 2 number = 3
 l = 3 number = 2
 l = 4 number = 1
 l = 5 number = 0
 l = 0 number = 0

*/
<commit_msg>finally fixed all bugs in topk in topk3.<commit_after>//Author: John Xu. 6/23/2019
//Initial code drafted on 6/21/2019 on a flight back from Plantation, FL
//
//The initial problem was an Amazon phone screen problem: print out the top K number from a given array of integers
//
//Initally the answer should be simple: take each integer from the array and insert into a priority queue and then
//do a loop to pop from this prioroty queue to print out each of the integer
//
//Then later on, it is asked, what if the array is so big, such as comming from a stream, and does not fit into the memory ?
//My immediate response was: once we reached size K for the priority queue, we remove the last element before insert the
//new element into the priority queue, if the new element is larger than the last element of the priority queue.
//
// Above immediate response has following defects:
//
// 1) priority queue does not have a method to access or remove the last element
//    regular queue has push, pop, front, back, size, empty.
//    dequeue has push_back, push_front, pop_back, pop_front, size, empty
//    priority_queue has push, pop, top, size, empty
//
// 2) over use of priority queue may be too slow. Priority queue better used for cases where the data is really used as
//    a queue structure, where processed elements are gone from the storage, where no need to keep the historical top K
//    element.
//
// 3) If we want to keep the historical top K element from a unlimited stream inout, it is more efficient to maintain a
//    dynamic array of size K. Maintain the array sorted from large to small. When new element comes in, if it is smaller
//    than the last one, ignore it. Otherwise, remove the last one, and shift every element one position to next one if that
//    element is smaller than the new one, then insert the new one at the end of the shift.
//

//example of keep top 3 element from a unlimited stream of integers: top3
// generic cases: topk
//
// compiling instruction: g++ --std=c++17 topk.cpp -o topk

#include <fstream>
#include <iostream>
#include <filesystem>

#define MIN_INT -65535

void top3(char* filename)
{
    using namespace std;
    namespace fs = std::filesystem;
    fs::path fp {filename};
    if (!fs::exists(fp)) {
        cout << "file " << filename << " not exist" << endl;
        return;
    }

    ifstream fstrm(filename);

    int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;
    int number;
    while (! fstrm.eof()) {
        fstrm >> number;
        if (number > top1) {
            top2 = top1;
            top1 = number;
        }
        else if (number > top2){
            top3 = top2;
            top2 = number;
        }
        else if (number > top3)
            top3 = number;

    }
    cout << top1 << endl << top2 << endl << top3 << endl;
}

void topk(char* filename, int K)
{
    using namespace std;
    namespace fs = std::filesystem;
    fs::path fp {filename};
    if (!fs::exists(fp)) {
        cout << "file " << filename << " not exist" << endl;
        return;
    }

    ifstream fstrm(filename);

//    int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;
    int number;
    int arr[K];

    for (int i=0; i<K; i++)
      arr[i] = MIN_INT;

    while (! fstrm.eof()) {

        fstrm >> number;
        int i = K-1;

        if (number < arr[K-1])
            break;

        for (i = K-1; i >= 0; i--) {
            cout << " number = " << number << " i = " << i << endl;     //debug
            if (number < arr[i] )           // arr[i] > number > arr[i+1]
                break;
        }

        if (i < 0)
            i = 0;

        int j = K-1;
        for (j=K-1; j>i; j--) {
            arr[j] = arr[j-1];
        }

        arr[i] = number;

        cout << " i = " << i << " number = " << number << endl;
    }

    fstrm.close();

    for (int i=0; i<K; i++)
     cout << arr[i] << endl;

}

void topk2(char* filename, int K)
{
    using namespace std;
    namespace fs = std::filesystem;
    fs::path fp {filename};
    if (!fs::exists(fp)) {
        cout << "file " << filename << " not exist" << endl;
        return;
    }

    ifstream fstrm(filename);

//    int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;
    int number;
    int arr[K];

    for (int i=0; i<K; i++)
      arr[i] = MIN_INT;

    while (! fstrm.eof()) {

        fstrm >> number;
        int i = K-1;

        if (number < arr[K-1])
            break;

        int l =0;
        for (i = 0; i < K; i++) {
            if ( number > arr[i]) {
               l = i;                   //this will fix the uncertainty of value i
               break;
            }
        }

        int j = K-1;
        for (j=K-1; j>l; j--) {
            arr[j] = arr[j-1];
        }

        arr[l] = number;

        cout << " l = " << l << " number = " << number << endl;
    }

    fstrm.close();

    for (int i=0; i<K; i++)
     cout << arr[i] << endl;

}

void topk3(char* filename, int K)
{
    using namespace std;
    namespace fs = std::filesystem;
    fs::path fp {filename};
    if (!fs::exists(fp)) {
        cout << "file " << filename << " not exist" << endl;
        return;
    }

    ifstream fstrm(filename);

//    int top1 = MIN_INT, top2=MIN_INT, top3=MIN_INT;
    int number;
    int arr[K];

    for (int i=0; i<K; i++)
      arr[i] = MIN_INT;

    while (! fstrm.eof()) {

        fstrm >> number;
        if (!fstrm)
          break;

        int i = K-1;

        if (number < arr[K-1])
            break;

        int l =0;
        for (i = 0; i < K; i++) {
            if ( number > arr[i]) {
               l = i;                   //this will fix the uncertainty of value i
               break;
            }
        }

        int j = K-1;
        for (j=K-1; j>l; j--) {
            arr[j] = arr[j-1];
        }

        arr[l] = number;

        cout << " l = " << l << " number = " << number << endl;
    }

    fstrm.close();

    for (int i=0; i<K; i++)
     cout << arr[i] << endl;

}

int main(int argc, char* argv[])
{
    int K = atoi(argv[2]);
    topk3(argv[1], K);
    return 0;
}

//above version still have some bugs. an input of 1, 2, 3, 4, 5, 6 with command top example.txt 9
// will output 6, 6, 5, 4, 3, 2, 1, -65535, -65535.  When we expect 6, 5, 4, 3, 2, 1, -65535, -65535
// an input of 5,4,3,2,1,0 with top example2.txt 9 will output 4,3,2,1,0,0,5, -65535, -65535

// Future modified versions will need to be worked on and put in topk2, topk3, ..., etc
//
// topk2 has less bug than topk, but testing data still shows 6,6,5,4,3,2 for example.txt and 0,5,4,3,2,1 for
// example2.txt.  This is due to the last number get read twice in the stream.
/*
 l = 0 number = 1
 l = 0 number = 2
 l = 0 number = 3
 l = 0 number = 4
 l = 0 number = 5
 l = 0 number = 6
 l = 1 number = 6

 l = 0 number = 5
 l = 1 number = 4
 l = 2 number = 3
 l = 3 number = 2
 l = 4 number = 1
 l = 5 number = 0
 l = 0 number = 0

*/

//
// topk3 fixed above bug. We check if last read is successful or not before using the data we thought we got from the read.
// if it failed, the fstrm  >> number will be invalid but the data in number is still good at its last value;<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <memory>
#include <ctime>
#include "schema/GeneratedSchema.hpp"
#include "schema/Types.hpp"
#include "queries/neworderrandom.hpp"

using namespace std;

int main() {
  auto tables = std::make_unique<table_data>();
  //load all the tables from disk
  std::cout << "loading data tables" << std::endl;
  try {
    auto data_folder = std::string{"data/"};
    tables->warehouse.loadFromTbl(std::ifstream((data_folder + "tpcc_warehouse.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->district.loadFromTbl(std::ifstream((data_folder + "tpcc_district.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->customer.loadFromTbl(std::ifstream((data_folder + "tpcc_customer.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->history.loadFromTbl(std::ifstream((data_folder + "tpcc_history.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->neworder.loadFromTbl(std::ifstream((data_folder + "tpcc_neworder.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->order.loadFromTbl(std::ifstream((data_folder + "tpcc_order.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->orderline.loadFromTbl(std::ifstream((data_folder + "tpcc_orderline.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->item.loadFromTbl(std::ifstream((data_folder + "tpcc_item.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->stock.loadFromTbl(std::ifstream((data_folder + "tpcc_stock.tbl").c_str()));
    std::cout << "." << std::flush;
  } catch(const char* e) {
    std::cout << e << std::endl;
    return -1;
  }
  std::cout << std::endl
            << "order table size " << tables->order.col_o_id.size() << "\n"
            << "neworder table size " << tables->neworder.col_no_o_id.size() << "\n"
            << "orderline table size " << tables->orderline.col_ol_o_id.size() << "\n";
  std::cout << "tpcc benchmark" << std::endl;
  clock_t begin_time = clock();
  auto iterations = 1'000'000;
  for(int i = 0; i < iterations; i++) {
    newOrderRandom(tables.get(), Timestamp(), 1);
    if((i & 0xfff) == 0) std::cout << "." << std::flush;
  }
  std::cout << std::endl
            << "order table size " << tables->order.col_o_id.size() << "\n"
            << "neworder table size " << tables->neworder.col_no_o_id.size() << "\n"
            << "orderline table size " << tables->orderline.col_ol_o_id.size() << "\n";
  clock_t end_time = clock();
  double elapsed_secs = double(end_time - begin_time) / CLOCKS_PER_SEC;
  std::cout << (iterations / elapsed_secs) << " transactions per seconds" << std::endl;
}
<commit_msg>tpcc: remove progress indicator in release build<commit_after>#include <iostream>
#include <fstream>
#include <memory>
#include <ctime>
#include "schema/GeneratedSchema.hpp"
#include "schema/Types.hpp"
#include "queries/neworderrandom.hpp"

using namespace std;

int main() {
  auto tables = std::make_unique<table_data>();
  //load all the tables from disk
  std::cout << "loading data tables" << std::endl;
  try {
    auto data_folder = std::string{"data/"};
    tables->warehouse.loadFromTbl(std::ifstream((data_folder + "tpcc_warehouse.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->district.loadFromTbl(std::ifstream((data_folder + "tpcc_district.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->customer.loadFromTbl(std::ifstream((data_folder + "tpcc_customer.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->history.loadFromTbl(std::ifstream((data_folder + "tpcc_history.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->neworder.loadFromTbl(std::ifstream((data_folder + "tpcc_neworder.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->order.loadFromTbl(std::ifstream((data_folder + "tpcc_order.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->orderline.loadFromTbl(std::ifstream((data_folder + "tpcc_orderline.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->item.loadFromTbl(std::ifstream((data_folder + "tpcc_item.tbl").c_str()));
    std::cout << "." << std::flush;
    tables->stock.loadFromTbl(std::ifstream((data_folder + "tpcc_stock.tbl").c_str()));
    std::cout << "." << std::flush;
  } catch(const char* e) {
    std::cout << e << std::endl;
    return -1;
  }
  std::cout << std::endl
            << "order table size " << tables->order.col_o_id.size() << "\n"
            << "neworder table size " << tables->neworder.col_no_o_id.size() << "\n"
            << "orderline table size " << tables->orderline.col_ol_o_id.size() << "\n";
  std::cout << "tpcc benchmark" << std::endl;
  clock_t begin_time = clock();
  auto iterations = 1'000'000;
  for(int i = 0; i < iterations; i++) {
    newOrderRandom(tables.get(), Timestamp(), 1);
    #ifdef DEBUG
    if((i & 0xfff) == 0) std::cout << "." << std::flush;
    #endif
  }
  std::cout << std::endl
            << "order table size " << tables->order.col_o_id.size() << "\n"
            << "neworder table size " << tables->neworder.col_no_o_id.size() << "\n"
            << "orderline table size " << tables->orderline.col_ol_o_id.size() << "\n";
  clock_t end_time = clock();
  double elapsed_secs = double(end_time - begin_time) / CLOCKS_PER_SEC;
  std::cout << (iterations / elapsed_secs) << " transactions per seconds" << std::endl;
}
<|endoftext|>