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

  Program:   Visualization Toolkit
  Module:    vtkInstantiator.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 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 "vtkInstantiator.h"
#include "vtkObjectFactory.h"
#include "vtkDebugLeaks.h"

vtkCxxRevisionMacro(vtkInstantiator, "1.4");
vtkStandardNewMacro(vtkInstantiator);

// Node in hash table.
class vtkInstantiatorHashNode
{
public:
  typedef vtkInstantiator::CreateFunction CreateFunction;

  vtkInstantiatorHashNode() { this->ClassName = 0; this->Function = 0; }

  void SetClassName(const char* className) { this->ClassName = className; }
  const char* GetClassName() { return this->ClassName; }

  void SetFunction(CreateFunction function) { this->Function = function; }
  CreateFunction GetFunction() { return this->Function; }

private:
  const char* ClassName;
  CreateFunction Function;
};

// Hash table used by vtkInstantiator.
class vtkInstantiatorHashTable : public vtkObject
{
public:
  vtkTypeRevisionMacro(vtkInstantiatorHashTable,vtkObject);
  void PrintSelf(ostream& os, vtkIndent indent);

  static vtkInstantiatorHashTable* New();

  typedef vtkInstantiator::CreateFunction CreateFunction;
  void Insert(const char* className, CreateFunction function);
  void Erase(const char* className, CreateFunction function);
  CreateFunction Find(const char* className);

protected:
  vtkInstantiatorHashTable();
  ~vtkInstantiatorHashTable();

  unsigned long Hash(const char* s);
  void ExtendBucket(unsigned long bucket);
  const char* AddClassName(const char* className);

  vtkInstantiatorHashNode** Buckets;
  unsigned int* BucketCounts;
  unsigned int* BucketSizes;
  unsigned long NumberOfBuckets;
  char** ClassNames;
  unsigned long NumberOfClassNames;
  unsigned long ClassNamesSize;

private:
  vtkInstantiatorHashTable(const vtkInstantiatorHashTable&);  // Not implemented.
  void operator=(const vtkInstantiatorHashTable&);  // Not implemented.
};

vtkCxxRevisionMacro(vtkInstantiatorHashTable, "1.4");

//----------------------------------------------------------------------------
vtkInstantiatorHashTable* vtkInstantiatorHashTable::New()
{
#ifdef VTK_DEBUG_LEAKS
  vtkDebugLeaks::ConstructClass("vtkInstantiatorHashTable");
#endif
  // Don't use the object factory because it may not have been
  // initialized when this table is allocated.
  return new vtkInstantiatorHashTable;
}

//----------------------------------------------------------------------------
vtkInstantiatorHashTable::vtkInstantiatorHashTable()
{
  this->NumberOfBuckets = 101;
  this->Buckets = new vtkInstantiatorHashNode*[this->NumberOfBuckets];
  this->BucketCounts = new unsigned int[this->NumberOfBuckets];
  this->BucketSizes = new unsigned int[this->NumberOfBuckets];

  unsigned int i;
  for(i=0;i < this->NumberOfBuckets;++i)
    {
    this->BucketCounts[i] = 0;
    this->BucketSizes[i] = 16;
    this->Buckets[i] = new vtkInstantiatorHashNode[this->BucketSizes[i]];
    }

  this->NumberOfClassNames = 0;
  this->ClassNamesSize = 256;
  this->ClassNames = new char*[this->ClassNamesSize];
}

//----------------------------------------------------------------------------
vtkInstantiatorHashTable::~vtkInstantiatorHashTable()
{
  unsigned long i;
  for(i=0; i < this->NumberOfBuckets;++i)
    {
    delete [] this->Buckets[i];
    }
  delete [] this->BucketSizes;
  delete [] this->BucketCounts;
  delete [] this->Buckets;

  for(i=0;i < this->NumberOfClassNames;++i)
    {
    delete [] this->ClassNames[i];
    }
  delete [] this->ClassNames;
}

//----------------------------------------------------------------------------
void vtkInstantiatorHashTable::PrintSelf(ostream& os, vtkIndent indent)
{
  this->vtkObject::PrintSelf(os, indent);
  os << indent << "NumberOfBuckets: " << this->NumberOfBuckets << "\n";
  unsigned int i;
  float avgBucketSize = 0;
  unsigned int maxBucketSize = 0;
  unsigned int minBucketSize = this->NumberOfClassNames;
  for(i=0;i < this->NumberOfBuckets;++i)
    {
    avgBucketSize += this->BucketCounts[i];
    if(this->BucketCounts[i] > maxBucketSize)
      { maxBucketSize = this->BucketCounts[i]; }
    if(this->BucketCounts[i] < minBucketSize)
      { minBucketSize = this->BucketCounts[i]; }
    }
  avgBucketSize /= float(this->NumberOfBuckets);
  os << indent << "Average Bucket Size: " << avgBucketSize << "\n";
  os << indent << "Minimum Bucket Size: " << minBucketSize << "\n";
  os << indent << "Maximum Bucket Size: " << maxBucketSize << "\n";
}

//----------------------------------------------------------------------------
void vtkInstantiatorHashTable::Insert(const char* className,
                                      CreateFunction function)
{
  unsigned long bucket = this->Hash(className);

  if(this->BucketCounts[bucket] == this->BucketSizes[bucket])
    { this->ExtendBucket(bucket); }

  // Do not check if the class is already registered.  It is possible
  // that more than one create function will be registered for the
  // same class, and even that the same function is registered more
  // than once.  Each register should have a corresponding unregister.
  // As long as any register has not had its corresponding unregister,
  // we want to allow the class to be created.
  unsigned int pos = this->BucketCounts[bucket]++;
  this->Buckets[bucket][pos].SetClassName(this->AddClassName(className));
  this->Buckets[bucket][pos].SetFunction(function);
}

//----------------------------------------------------------------------------
void vtkInstantiatorHashTable::Erase(const char* className,
                                     CreateFunction function)
{
  unsigned long bucket = this->Hash(className);

  // Find the exact registration function we have been given, and
  // remove it only once.  If more than one funcion has been
  // registered for this class, or the same function more than once,
  // each register should have its corresponding unregister.
  unsigned int i;
  for(i=0; i < this->BucketCounts[bucket];++i)
    {
    if(((this->Buckets[bucket][i].GetFunction() == function)
        && (strcmp(this->Buckets[bucket][i].GetClassName(), className) == 0)))
      {
      unsigned int j;
      --this->BucketCounts[bucket];
      for(j=i;j < this->BucketCounts[bucket];++j)
        {
        this->Buckets[bucket][j] = this->Buckets[bucket][j+1];
        }
      return;
      }
    }
}

//----------------------------------------------------------------------------
vtkInstantiatorHashTable::CreateFunction
vtkInstantiatorHashTable::Find(const char* className)
{
  unsigned long bucket = this->Hash(className);

  unsigned int i;
  for(i=0; i < this->BucketCounts[bucket];++i)
    {
    if(strcmp(this->Buckets[bucket][i].GetClassName(), className) == 0)
      { return this->Buckets[bucket][i].GetFunction(); }
    }
  return 0;
}

//----------------------------------------------------------------------------
unsigned long vtkInstantiatorHashTable::Hash(const char* s)
{
  unsigned long h = 0;
  for(;*s;++s) { h = 5*h + *s; }
  return h % this->NumberOfBuckets;
}

//----------------------------------------------------------------------------
void vtkInstantiatorHashTable::ExtendBucket(unsigned long bucket)
{
  unsigned int newSize = this->BucketSizes[bucket] * 2;

  vtkInstantiatorHashNode* newBucket =
    new vtkInstantiatorHashNode[newSize];

  unsigned int i;
  for(i=0; i < this->BucketCounts[bucket];++i)
    { newBucket[i] = this->Buckets[bucket][i]; }

  delete [] this->Buckets[bucket];
  this->Buckets[bucket] = newBucket;
  this->BucketSizes[bucket] = newSize;
}

//----------------------------------------------------------------------------
const char* vtkInstantiatorHashTable::AddClassName(const char* className)
{
  if(this->NumberOfClassNames == this->ClassNamesSize)
    {
    unsigned long newSize = this->ClassNamesSize * 2;
    char** newNames = new char*[newSize];

    unsigned long i;
    for(i=0;i < this->NumberOfClassNames;++i)
      { newNames[i] = this->ClassNames[i]; }

    delete [] this->ClassNames;
    this->ClassNames = newNames;
    this->ClassNamesSize = newSize;
    }

  char* newName = new char[strlen(className)+1];
  strcpy(newName, className);
  this->ClassNames[this->NumberOfClassNames++] = newName;

  return newName;
}

//----------------------------------------------------------------------------
// Implementation of actual vtkInstantiator class.
//----------------------------------------------------------------------------
vtkInstantiator::vtkInstantiator()
{
}

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

//----------------------------------------------------------------------------
void vtkInstantiator::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  vtkInstantiator::CreatorTable->PrintSelf(os, indent);
}

//----------------------------------------------------------------------------
vtkObject* vtkInstantiator::CreateInstance(const char* className)
{
  CreateFunction function = vtkInstantiator::CreatorTable->Find(className);
  if(function) { return function(); }
  return 0;
}

//----------------------------------------------------------------------------
void vtkInstantiator::RegisterInstantiator(const char* className,
                                           CreateFunction createFunction)
{
  vtkInstantiator::CreatorTable->Insert(className, createFunction);
}

//----------------------------------------------------------------------------
void vtkInstantiator::UnRegisterInstantiator(const char* className,
                                             CreateFunction createFunction)
{
  vtkInstantiator::CreatorTable->Erase(className, createFunction);
}

//----------------------------------------------------------------------------
void vtkInstantiator::ClassInitialize()
{
  vtkInstantiator::CreatorTable = vtkInstantiatorHashTable::New();
}

//----------------------------------------------------------------------------
void vtkInstantiator::ClassFinalize()
{
  vtkInstantiator::CreatorTable->Delete();
}

//----------------------------------------------------------------------------
vtkInstantiatorInitialize::vtkInstantiatorInitialize()
{
  if(++vtkInstantiatorInitialize::Count == 1)
    { vtkInstantiator::ClassInitialize(); }
}

//----------------------------------------------------------------------------
vtkInstantiatorInitialize::~vtkInstantiatorInitialize()
{
  if(--vtkInstantiatorInitialize::Count == 0)
    { vtkInstantiator::ClassFinalize(); }
}

//----------------------------------------------------------------------------
unsigned int vtkInstantiatorInitialize::Count;
vtkInstantiatorHashTable* vtkInstantiator::CreatorTable;
<commit_msg>BUG: vtkInstantiatorHashTable must not be a subclass of vtkObject because vtkObject's constructor touches vtkTimeStamp's global, which may not yet be initialized by the time vtkInstantiatorHashTable is constructed (on certain platforms).<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkInstantiator.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 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 "vtkInstantiator.h"
#include "vtkObjectFactory.h"

vtkCxxRevisionMacro(vtkInstantiator, "1.5");
vtkStandardNewMacro(vtkInstantiator);

// Node in hash table.
class vtkInstantiatorHashNode
{
public:
  typedef vtkInstantiator::CreateFunction CreateFunction;

  vtkInstantiatorHashNode() { this->ClassName = 0; this->Function = 0; }

  void SetClassName(const char* className) { this->ClassName = className; }
  const char* GetClassName() { return this->ClassName; }

  void SetFunction(CreateFunction function) { this->Function = function; }
  CreateFunction GetFunction() { return this->Function; }

private:
  const char* ClassName;
  CreateFunction Function;
};

// Hash table used by vtkInstantiator.  Must not be a vtkObject.
class vtkInstantiatorHashTable
{
public:
  vtkInstantiatorHashTable();
  ~vtkInstantiatorHashTable();

  void PrintSelf(ostream& os, vtkIndent indent);

  typedef vtkInstantiator::CreateFunction CreateFunction;
  void Insert(const char* className, CreateFunction function);
  void Erase(const char* className, CreateFunction function);
  CreateFunction Find(const char* className);

protected:
  unsigned long Hash(const char* s);
  void ExtendBucket(unsigned long bucket);
  const char* AddClassName(const char* className);

  vtkInstantiatorHashNode** Buckets;
  unsigned int* BucketCounts;
  unsigned int* BucketSizes;
  unsigned long NumberOfBuckets;
  char** ClassNames;
  unsigned long NumberOfClassNames;
  unsigned long ClassNamesSize;

private:
  vtkInstantiatorHashTable(const vtkInstantiatorHashTable&);  // Not implemented.
  void operator=(const vtkInstantiatorHashTable&);  // Not implemented.
};

//----------------------------------------------------------------------------
vtkInstantiatorHashTable::vtkInstantiatorHashTable()
{
  this->NumberOfBuckets = 101;
  this->Buckets = new vtkInstantiatorHashNode*[this->NumberOfBuckets];
  this->BucketCounts = new unsigned int[this->NumberOfBuckets];
  this->BucketSizes = new unsigned int[this->NumberOfBuckets];

  unsigned int i;
  for(i=0;i < this->NumberOfBuckets;++i)
    {
    this->BucketCounts[i] = 0;
    this->BucketSizes[i] = 16;
    this->Buckets[i] = new vtkInstantiatorHashNode[this->BucketSizes[i]];
    }

  this->NumberOfClassNames = 0;
  this->ClassNamesSize = 256;
  this->ClassNames = new char*[this->ClassNamesSize];
}

//----------------------------------------------------------------------------
vtkInstantiatorHashTable::~vtkInstantiatorHashTable()
{
  unsigned long i;
  for(i=0; i < this->NumberOfBuckets;++i)
    {
    delete [] this->Buckets[i];
    }
  delete [] this->BucketSizes;
  delete [] this->BucketCounts;
  delete [] this->Buckets;

  for(i=0;i < this->NumberOfClassNames;++i)
    {
    delete [] this->ClassNames[i];
    }
  delete [] this->ClassNames;
}

//----------------------------------------------------------------------------
void vtkInstantiatorHashTable::PrintSelf(ostream& os, vtkIndent indent)
{
  os << indent << "NumberOfBuckets: " << this->NumberOfBuckets << "\n";
  unsigned int i;
  float avgBucketSize = 0;
  unsigned int maxBucketSize = 0;
  unsigned int minBucketSize = this->NumberOfClassNames;
  for(i=0;i < this->NumberOfBuckets;++i)
    {
    avgBucketSize += this->BucketCounts[i];
    if(this->BucketCounts[i] > maxBucketSize)
      { maxBucketSize = this->BucketCounts[i]; }
    if(this->BucketCounts[i] < minBucketSize)
      { minBucketSize = this->BucketCounts[i]; }
    }
  avgBucketSize /= float(this->NumberOfBuckets);
  os << indent << "Average Bucket Size: " << avgBucketSize << "\n";
  os << indent << "Minimum Bucket Size: " << minBucketSize << "\n";
  os << indent << "Maximum Bucket Size: " << maxBucketSize << "\n";
}

//----------------------------------------------------------------------------
void vtkInstantiatorHashTable::Insert(const char* className,
                                      CreateFunction function)
{
  unsigned long bucket = this->Hash(className);

  if(this->BucketCounts[bucket] == this->BucketSizes[bucket])
    { this->ExtendBucket(bucket); }

  // Do not check if the class is already registered.  It is possible
  // that more than one create function will be registered for the
  // same class, and even that the same function is registered more
  // than once.  Each register should have a corresponding unregister.
  // As long as any register has not had its corresponding unregister,
  // we want to allow the class to be created.
  unsigned int pos = this->BucketCounts[bucket]++;
  this->Buckets[bucket][pos].SetClassName(this->AddClassName(className));
  this->Buckets[bucket][pos].SetFunction(function);
}

//----------------------------------------------------------------------------
void vtkInstantiatorHashTable::Erase(const char* className,
                                     CreateFunction function)
{
  unsigned long bucket = this->Hash(className);

  // Find the exact registration function we have been given, and
  // remove it only once.  If more than one funcion has been
  // registered for this class, or the same function more than once,
  // each register should have its corresponding unregister.
  unsigned int i;
  for(i=0; i < this->BucketCounts[bucket];++i)
    {
    if(((this->Buckets[bucket][i].GetFunction() == function)
        && (strcmp(this->Buckets[bucket][i].GetClassName(), className) == 0)))
      {
      unsigned int j;
      --this->BucketCounts[bucket];
      for(j=i;j < this->BucketCounts[bucket];++j)
        {
        this->Buckets[bucket][j] = this->Buckets[bucket][j+1];
        }
      return;
      }
    }
}

//----------------------------------------------------------------------------
vtkInstantiatorHashTable::CreateFunction
vtkInstantiatorHashTable::Find(const char* className)
{
  unsigned long bucket = this->Hash(className);

  unsigned int i;
  for(i=0; i < this->BucketCounts[bucket];++i)
    {
    if(strcmp(this->Buckets[bucket][i].GetClassName(), className) == 0)
      { return this->Buckets[bucket][i].GetFunction(); }
    }
  return 0;
}

//----------------------------------------------------------------------------
unsigned long vtkInstantiatorHashTable::Hash(const char* s)
{
  unsigned long h = 0;
  for(;*s;++s) { h = 5*h + *s; }
  return h % this->NumberOfBuckets;
}

//----------------------------------------------------------------------------
void vtkInstantiatorHashTable::ExtendBucket(unsigned long bucket)
{
  unsigned int newSize = this->BucketSizes[bucket] * 2;

  vtkInstantiatorHashNode* newBucket =
    new vtkInstantiatorHashNode[newSize];

  unsigned int i;
  for(i=0; i < this->BucketCounts[bucket];++i)
    { newBucket[i] = this->Buckets[bucket][i]; }

  delete [] this->Buckets[bucket];
  this->Buckets[bucket] = newBucket;
  this->BucketSizes[bucket] = newSize;
}

//----------------------------------------------------------------------------
const char* vtkInstantiatorHashTable::AddClassName(const char* className)
{
  if(this->NumberOfClassNames == this->ClassNamesSize)
    {
    unsigned long newSize = this->ClassNamesSize * 2;
    char** newNames = new char*[newSize];

    unsigned long i;
    for(i=0;i < this->NumberOfClassNames;++i)
      { newNames[i] = this->ClassNames[i]; }

    delete [] this->ClassNames;
    this->ClassNames = newNames;
    this->ClassNamesSize = newSize;
    }

  char* newName = new char[strlen(className)+1];
  strcpy(newName, className);
  this->ClassNames[this->NumberOfClassNames++] = newName;

  return newName;
}

//----------------------------------------------------------------------------
// Implementation of actual vtkInstantiator class.
//----------------------------------------------------------------------------
vtkInstantiator::vtkInstantiator()
{
}

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

//----------------------------------------------------------------------------
void vtkInstantiator::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  vtkInstantiator::CreatorTable->PrintSelf(os, indent);
}

//----------------------------------------------------------------------------
vtkObject* vtkInstantiator::CreateInstance(const char* className)
{
  CreateFunction function = vtkInstantiator::CreatorTable->Find(className);
  if(function) { return function(); }
  return 0;
}

//----------------------------------------------------------------------------
void vtkInstantiator::RegisterInstantiator(const char* className,
                                           CreateFunction createFunction)
{
  vtkInstantiator::CreatorTable->Insert(className, createFunction);
}

//----------------------------------------------------------------------------
void vtkInstantiator::UnRegisterInstantiator(const char* className,
                                             CreateFunction createFunction)
{
  vtkInstantiator::CreatorTable->Erase(className, createFunction);
}

//----------------------------------------------------------------------------
void vtkInstantiator::ClassInitialize()
{
  vtkInstantiator::CreatorTable = new vtkInstantiatorHashTable;
}

//----------------------------------------------------------------------------
void vtkInstantiator::ClassFinalize()
{
  delete vtkInstantiator::CreatorTable;
}

//----------------------------------------------------------------------------
vtkInstantiatorInitialize::vtkInstantiatorInitialize()
{
  if(++vtkInstantiatorInitialize::Count == 1)
    { vtkInstantiator::ClassInitialize(); }
}

//----------------------------------------------------------------------------
vtkInstantiatorInitialize::~vtkInstantiatorInitialize()
{
  if(--vtkInstantiatorInitialize::Count == 0)
    { vtkInstantiator::ClassFinalize(); }
}

//----------------------------------------------------------------------------
unsigned int vtkInstantiatorInitialize::Count;
vtkInstantiatorHashTable* vtkInstantiator::CreatorTable;
<|endoftext|>


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

#ifndef GLOBAL_HXX_INCLUDED
#define GLOBAL_HXX_INCLUDED

#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#ifndef OS2
#include <windows.h>
#endif
#if defined _MSC_VER
#pragma warning(pop)
#endif

#ifndef DBGMACROS_HXX_INCLUDED
#include "internal/dbgmacros.hxx"
#endif

extern long g_DllRefCnt;

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

#ifndef GLOBAL_HXX_INCLUDED
#define GLOBAL_HXX_INCLUDED

#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#ifndef OS2
#include <windows.h>
#endif
#if defined _MSC_VER
#pragma warning(pop)
#endif
#include "internal/dbgmacros.hxx"

extern long g_DllRefCnt;

#endif
<|endoftext|>


<commit_before>/**
 * @file dt_main.cpp
 * @ Parikshit Ram (pram@cc.gatech.edu)
 *
 * This file provides an example use of the DET
 */

#include <mlpack/core.hpp>
#include "dt_utils.hpp"

using namespace mlpack;
using namespace mlpack::det;
using namespace std;

PROGRAM_INFO("Density estimation with DET", "This program "
             "provides an example use of the Density Estimation "
	     "Tree for density estimation. For more details, "
	     "please look at the paper titled "
	     "'Density Estimation Trees'.");

// input data files
PARAM_STRING_REQ("input/training_set", "The data set on which to "
		 "perform density estimation.", "S");
PARAM_STRING("input/test_set", "An extra set of test points on "
	     "which to estimate the density given the estimator.",
	     "T", "");
PARAM_STRING("input/labels", "The labels for the given training data to "
	     "generate the class membership of each leaf (as an "
	     "extra statistic)", "L", "");

// output data files
PARAM_STRING("output/unpruned_tree_estimates", "The file "
	     "in which to output the estimates on the "
	     "training set from the large unpruned tree.", "u", "");
PARAM_STRING("output/training_set_estimates", "The file "
	     "in which to output the estimates on the "
	     "training set from the final optimally pruned"
	     " tree.", "s", "");
PARAM_STRING("output/test_set_estimates", "The file "
	     "in which to output the estimates on the "
	     "test set from the final optimally pruned"
	     " tree.", "t", "");
PARAM_STRING("output/leaf_class_table", "The file "
	     "in which to output the leaf class membership "
	     "table.", "l", "leaf_class_membership.txt");
PARAM_STRING("output/tree", "The file in which to print "
	     "the final optimally pruned tree.", "p", "");
PARAM_STRING("output/vi", "The file to output the "
	     "variable importance values for each feature.",
	     "i", "");

// parameters for the algorithm
PARAM_INT("param/number_of_classes", "The number of classes present "
	  "in the 'labels' set provided", "C", 0);
PARAM_INT("param/folds", "The number of folds of cross-validation"
	  " to performed for the estimation (enter 0 for LOOCV)",
	  "F", 10);
PARAM_INT("DET/min_leaf_size", "The minimum size of a leaf"
	  " in the unpruned fully grown DET.", "N", 5);
PARAM_INT("DET/max_leaf_size", "The maximum size of a leaf"
	  " in the unpruned fully grown DET.", "M", 10);
PARAM_FLAG("DET/use_volume_reg", "This flag gives the used the "
	   "option to use a form of regularization similar to "
	   "the usual alpha-pruning in decision tree. But "
	   "instead of regularizing on the number of leaves, "
	   "you regularize on the sum of the inverse of the volume "
	   "of the leaves (meaning you penalize  "
	   "low volume leaves.", "R");

// some flags for output of some information about the tree
PARAM_FLAG("flag/print_tree", "If you just wish to print the tree "
	   "out on the command line.", "P");
PARAM_FLAG("flag/print_vi", "If you just wish to print the "
	   "variable importance of each feature "
	   "out on the command line.", "I");

int main(int argc, char *argv[])
{
  CLI::ParseCommandLine(argc, argv);

  string train_set_file = CLI::GetParam<string>("S");
  arma::Mat<float> training_data;

  Log::Info << "Loading training set..." << endl;
  if (!data::Load(train_set_file, training_data))
    Log::Fatal << "Training set file "<< train_set_file
	       << " can't be loaded." << endl;

  Log::Info << "Training set (" << training_data.n_rows
	    << ", " << training_data.n_cols
	    << ")" << endl;

  // cross-validation here
  size_t folds = CLI::GetParam<int>("F");
  if (folds == 0) {
    folds = training_data.n_cols;
    Log::Info << "Starting Leave-One-Out Cross validation" << endl;
  } else
    Log::Info << "Starting " << folds
	      << "-fold Cross validation" << endl;

  // obtaining the optimal tree
  string unpruned_tree_estimate_file
    = CLI::GetParam<string>("u");

  Timer::Start("DET/Training");
  DTree<float> *dtree_opt = Trainer<float>
    (&training_data, folds, CLI::HasParam("R"), CLI::GetParam<int>("M"),
     CLI::GetParam<int>("N"), unpruned_tree_estimate_file);
  Timer::Stop("DET/Training");

  // computing densities for the train points in the
  // optimal tree
  FILE *fp = NULL;

  if (CLI::GetParam<string>("s") != "") {
    string optimal_estimates_file = CLI::GetParam<string>("s");
    fp = fopen(optimal_estimates_file.c_str(), "w");
  }

  // Computation timing is more accurate when you do not
  // perform the printing.
  Timer::Start("DET/EstimationTime");
  for (size_t i = 0; i < training_data.n_cols; i++) {
    arma::Col<float> test_p = training_data.unsafe_col(i);
    long double f = dtree_opt->ComputeValue(&test_p);
    if (fp != NULL)
      fprintf(fp, "%Lg\n", f);
  } // end for
  Timer::Stop("DET/EstimationTime");

  if (fp != NULL)
    fclose(fp);

  // computing the density at the provided test points
  // and outputting the density in the given file.
  if (CLI::GetParam<string>("T") != "") {
    string test_file = CLI::GetParam<string>("T");
    arma::Mat<float> test_data;
    Log::Info << "Loading test set..." << endl;
    if (!data::Load(test_file, test_data))
      Log::Fatal << "Test set file "<< test_file
		 << " can't be loaded." << endl;

    Log::Info << "Test set (" << test_data.n_rows
	      << ", " << test_data.n_cols
	      << ")" << endl;

    fp = NULL;

    if (CLI::GetParam<string>("t") != "") {
      string test_density_file
	= CLI::GetParam<string>("t");
      fp = fopen(test_density_file.c_str(), "w");
    }

    Timer::Start("DET/TestSetEstimation");
    for (size_t i = 0; i < test_data.n_cols; i++) {
      arma::Col<float> test_p = test_data.unsafe_col(i);
      long double f = dtree_opt->ComputeValue(&test_p);
      if (fp != NULL)
	fprintf(fp, "%Lg\n", f);
    } // end for
    Timer::Stop("DET/TestSetEstimation");

    if (fp != NULL)
      fclose(fp);
  } // Test set estimation

  // printing the final tree
  if (CLI::HasParam("P")) {

    fp = NULL;
    if (CLI::GetParam<string>("p") != "") {
      string print_tree_file = CLI::GetParam<string>("p");
      fp = fopen(print_tree_file.c_str(), "w");

      if (fp != NULL) {
	dtree_opt->WriteTree(0, fp);
	fclose(fp);
      }
    } else {
      dtree_opt->WriteTree(0, stdout);
      printf("\n");
    }
  } // Printing the tree

  // print the leaf memberships for the optimal tree
  if (CLI::GetParam<string>("L") != "") {
    std::string labels_file = CLI::GetParam<string>("L");
    arma::Mat<int> labels;

    Log::Info << "Loading label file..." << endl;
    if (!data::Load(labels_file, labels))
      Log::Fatal << "Label file "<< labels_file
		 << " can't be loaded." << endl;

    Log::Info << "Labels (" << labels.n_rows
	      << ", " << labels.n_cols
	      << ")" << endl;

    size_t num_classes = CLI::GetParam<int>("C");
    if (num_classes == 0)
      Log::Fatal << "Please provide the number of classes"
		 << " present in the label file" << endl;

    assert(training_data.n_cols == labels.n_cols);
    assert(labels.n_rows == 1);

    PrintLeafMembership<float>
      (dtree_opt, training_data, labels, num_classes,
       (string) CLI::GetParam<string>("l"));
  } // leaf class membership

  if(CLI::HasParam("I")) {
    PrintVariableImportance<float>
      (dtree_opt, training_data.n_rows,
       (string) CLI::GetParam<string>("i"));
  } // print variable importance

  delete dtree_opt;
  return 0;
} // end main
<commit_msg>Switch to doubles not floats in main executable so it compiles.<commit_after>/**
 * @file dt_main.cpp
 * @ Parikshit Ram (pram@cc.gatech.edu)
 *
 * This file provides an example use of the DET
 */

#include <mlpack/core.hpp>
#include "dt_utils.hpp"

using namespace mlpack;
using namespace mlpack::det;
using namespace std;

PROGRAM_INFO("Density estimation with DET", "This program provides an example "
    "use of the Density Estimation "
	     "Tree for density estimation. For more details, "
	     "please look at the paper titled "
	     "'Density Estimation Trees'.");

// input data files
PARAM_STRING_REQ("input/training_set", "The data set on which to "
		 "perform density estimation.", "S");
PARAM_STRING("input/test_set", "An extra set of test points on "
	     "which to estimate the density given the estimator.",
	     "T", "");
PARAM_STRING("input/labels", "The labels for the given training data to "
	     "generate the class membership of each leaf (as an "
	     "extra statistic)", "L", "");

// output data files
PARAM_STRING("output/unpruned_tree_estimates", "The file "
	     "in which to output the estimates on the "
	     "training set from the large unpruned tree.", "u", "");
PARAM_STRING("output/training_set_estimates", "The file "
	     "in which to output the estimates on the "
	     "training set from the final optimally pruned"
	     " tree.", "s", "");
PARAM_STRING("output/test_set_estimates", "The file "
	     "in which to output the estimates on the "
	     "test set from the final optimally pruned"
	     " tree.", "t", "");
PARAM_STRING("output/leaf_class_table", "The file "
	     "in which to output the leaf class membership "
	     "table.", "l", "leaf_class_membership.txt");
PARAM_STRING("output/tree", "The file in which to print "
	     "the final optimally pruned tree.", "p", "");
PARAM_STRING("output/vi", "The file to output the "
	     "variable importance values for each feature.",
	     "i", "");

// parameters for the algorithm
PARAM_INT("param/number_of_classes", "The number of classes present "
	  "in the 'labels' set provided", "C", 0);
PARAM_INT("param/folds", "The number of folds of cross-validation"
	  " to performed for the estimation (enter 0 for LOOCV)",
	  "F", 10);
PARAM_INT("DET/min_leaf_size", "The minimum size of a leaf"
	  " in the unpruned fully grown DET.", "N", 5);
PARAM_INT("DET/max_leaf_size", "The maximum size of a leaf"
	  " in the unpruned fully grown DET.", "M", 10);
PARAM_FLAG("DET/use_volume_reg", "This flag gives the used the "
	   "option to use a form of regularization similar to "
	   "the usual alpha-pruning in decision tree. But "
	   "instead of regularizing on the number of leaves, "
	   "you regularize on the sum of the inverse of the volume "
	   "of the leaves (meaning you penalize  "
	   "low volume leaves.", "R");

// some flags for output of some information about the tree
PARAM_FLAG("flag/print_tree", "If you just wish to print the tree "
	   "out on the command line.", "P");
PARAM_FLAG("flag/print_vi", "If you just wish to print the "
	   "variable importance of each feature "
	   "out on the command line.", "I");

int main(int argc, char *argv[])
{
  CLI::ParseCommandLine(argc, argv);

  string train_set_file = CLI::GetParam<string>("S");
  arma::Mat<double> training_data;

  Log::Info << "Loading training set..." << endl;
  if (!data::Load(train_set_file, training_data))
    Log::Fatal << "Training set file "<< train_set_file
	       << " can't be loaded." << endl;

  Log::Info << "Training set (" << training_data.n_rows
	    << ", " << training_data.n_cols
	    << ")" << endl;

  // cross-validation here
  size_t folds = CLI::GetParam<int>("F");
  if (folds == 0) {
    folds = training_data.n_cols;
    Log::Info << "Starting Leave-One-Out Cross validation" << endl;
  } else
    Log::Info << "Starting " << folds
	      << "-fold Cross validation" << endl;

  // obtaining the optimal tree
  string unpruned_tree_estimate_file
    = CLI::GetParam<string>("u");

  Timer::Start("DET/Training");
  DTree<double> *dtree_opt = Trainer<double>
    (&training_data, folds, CLI::HasParam("R"), CLI::GetParam<int>("M"),
     CLI::GetParam<int>("N"), unpruned_tree_estimate_file);
  Timer::Stop("DET/Training");

  // computing densities for the train points in the
  // optimal tree
  FILE *fp = NULL;

  if (CLI::GetParam<string>("s") != "") {
    string optimal_estimates_file = CLI::GetParam<string>("s");
    fp = fopen(optimal_estimates_file.c_str(), "w");
  }

  // Computation timing is more accurate when you do not
  // perform the printing.
  Timer::Start("DET/EstimationTime");
  for (size_t i = 0; i < training_data.n_cols; i++) {
    arma::Col<double> test_p = training_data.unsafe_col(i);
    long double f = dtree_opt->ComputeValue(&test_p);
    if (fp != NULL)
      fprintf(fp, "%Lg\n", f);
  } // end for
  Timer::Stop("DET/EstimationTime");

  if (fp != NULL)
    fclose(fp);

  // computing the density at the provided test points
  // and outputting the density in the given file.
  if (CLI::GetParam<string>("T") != "") {
    string test_file = CLI::GetParam<string>("T");
    arma::Mat<double> test_data;
    Log::Info << "Loading test set..." << endl;
    if (!data::Load(test_file, test_data))
      Log::Fatal << "Test set file "<< test_file
		 << " can't be loaded." << endl;

    Log::Info << "Test set (" << test_data.n_rows
	      << ", " << test_data.n_cols
	      << ")" << endl;

    fp = NULL;

    if (CLI::GetParam<string>("t") != "") {
      string test_density_file
	= CLI::GetParam<string>("t");
      fp = fopen(test_density_file.c_str(), "w");
    }

    Timer::Start("DET/TestSetEstimation");
    for (size_t i = 0; i < test_data.n_cols; i++) {
      arma::Col<double> test_p = test_data.unsafe_col(i);
      long double f = dtree_opt->ComputeValue(&test_p);
      if (fp != NULL)
	fprintf(fp, "%Lg\n", f);
    } // end for
    Timer::Stop("DET/TestSetEstimation");

    if (fp != NULL)
      fclose(fp);
  } // Test set estimation

  // printing the final tree
  if (CLI::HasParam("P")) {

    fp = NULL;
    if (CLI::GetParam<string>("p") != "") {
      string print_tree_file = CLI::GetParam<string>("p");
      fp = fopen(print_tree_file.c_str(), "w");

      if (fp != NULL) {
	dtree_opt->WriteTree(0, fp);
	fclose(fp);
      }
    } else {
      dtree_opt->WriteTree(0, stdout);
      printf("\n");
    }
  } // Printing the tree

  // print the leaf memberships for the optimal tree
  if (CLI::GetParam<string>("L") != "") {
    std::string labels_file = CLI::GetParam<string>("L");
    arma::Mat<int> labels;

    Log::Info << "Loading label file..." << endl;
    if (!data::Load(labels_file, labels))
      Log::Fatal << "Label file "<< labels_file
		 << " can't be loaded." << endl;

    Log::Info << "Labels (" << labels.n_rows
	      << ", " << labels.n_cols
	      << ")" << endl;

    size_t num_classes = CLI::GetParam<int>("C");
    if (num_classes == 0)
      Log::Fatal << "Please provide the number of classes"
		 << " present in the label file" << endl;

    assert(training_data.n_cols == labels.n_cols);
    assert(labels.n_rows == 1);

    PrintLeafMembership<double>
      (dtree_opt, training_data, labels, num_classes,
       (string) CLI::GetParam<string>("l"));
  } // leaf class membership

  if(CLI::HasParam("I")) {
    PrintVariableImportance<double>
      (dtree_opt, training_data.n_rows,
       (string) CLI::GetParam<string>("i"));
  } // print variable importance

  delete dtree_opt;
  return 0;
} // end main
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX24T/RX66T グループ・CMPC 定義
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2016, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/device.hpp"

/// CMPC モジュールが無いデバイスでエラーとする
#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N)
#  error "cmpc.hpp: This module does not exist"
#endif

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  コンパレータ C（CMPC）
		@param[in]	base	ベース・アドレス
		@param[in]	per		ペリフェラル型
		@param[in]	ivec	割り込みベクタ型
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t base, peripheral per, ICU::VECTOR ivec>
	struct cmpc_t {

		static const auto PERIPHERAL = per;		///< ペリフェラル型
		static const auto IVEC = ivec;			///< 割り込みベクター

		//-----------------------------------------------------------------//
		/*!
			@brief  コンパレータ制御レジスタ（CMPCTL）
			@param[in]	ofs	オフセット
		*/
		//-----------------------------------------------------------------//
		template <uint32_t ofs>
		struct cmpctl_t : public rw8_t<ofs> {
			typedef rw8_t<ofs> io_;
			using io_::operator =;
			using io_::operator ();
			using io_::operator |=;
			using io_::operator &=;

			bit_rw_t <io_, bitpos::B0>     CINV;
			bit_rw_t <io_, bitpos::B1>     COE;
			bits_rw_t<io_, bitpos::B3, 2>  CEG;
			bits_rw_t<io_, bitpos::B5, 2>  CDFS;
			bit_rw_t <io_, bitpos::B7>     HCMPON;
		};
		static cmpctl_t<base + 0x00> CMPCTL;

		//-----------------------------------------------------------------//
		/*!
			@brief  コンパレータ入力切り替えレジスタ（CMPSEL0）
			@param[in]	ofs	オフセット
		*/
		//-----------------------------------------------------------------//
		template <uint32_t ofs>
		struct cmpsel0_t : public rw8_t<ofs> {
			typedef rw8_t<ofs> io_;
			using io_::operator =;
			using io_::operator ();
			using io_::operator |=;
			using io_::operator &=;

			bits_rw_t<io_, bitpos::B0, 4>  CMPSEL;
		};
		static cmpsel0_t<base + 0x04> CMPSEL0;

		//-----------------------------------------------------------------//
		/*!
			@brief  コンパレータ入力切り替えレジスタ（CMPSEL1）
			@param[in]	ofs	オフセット
		*/
		//-----------------------------------------------------------------//
		template <uint32_t ofs>
		struct cmpsel1_t : public rw8_t<ofs> {
			typedef rw8_t<ofs> io_;
			using io_::operator =;
			using io_::operator ();
			using io_::operator |=;
			using io_::operator &=;

			bits_rw_t<io_, bitpos::B0, 2>  CVRS;
		};
		static cmpsel1_t<base + 0x08> CMPSEL1;

		//-----------------------------------------------------------------//
		/*!
			@brief  コンパレータ出力モニタレジスタ（CMPMON）
			@param[in]	ofs	オフセット
		*/
		//-----------------------------------------------------------------//
		template <uint32_t ofs>
		struct cmpmon_t : public rw8_t<ofs> {
			typedef rw8_t<ofs> io_;
			using io_::operator =;
			using io_::operator ();
			using io_::operator |=;
			using io_::operator &=;

			bit_rw_t<io_, bitpos::B0>  CMPMON0;
		};
		static cmpmon_t<base + 0x0C> CMPMON;

		//-----------------------------------------------------------------//
		/*!
			@brief  コンパレータ外部出力許可レジスタ（CMPIOC）
			@param[in]	ofs	オフセット
		*/
		//-----------------------------------------------------------------//
		template <uint32_t ofs>
		struct cmpioc_t : public rw8_t<ofs> {
			typedef rw8_t<ofs> io_;
			using io_::operator =;
			using io_::operator ();
			using io_::operator |=;
			using io_::operator &=;

			bit_rw_t<io_, bitpos::B0>  CPOE;
		};
		static cmpioc_t<base + 0x10> CMPIOC;
	};

#if defined(SIG_RX24T)
	typedef cmpc_t<0x000A0C80, peripheral::CMPC0, ICU::VECTOR::CMPC0> CMPC0;
	typedef cmpc_t<0x000A0CA0, peripheral::CMPC1, ICU::VECTOR::CMPC1> CMPC1;
	typedef cmpc_t<0x000A0CC0, peripheral::CMPC2, ICU::VECTOR::CMPC2> CMPC2;
	typedef cmpc_t<0x000A0CE0, peripheral::CMPC3, ICU::VECTOR::CMPC3> CMPC3;
#elif defined(SIG_RX66T)
	typedef cmpc_t<0x000A0C80, peripheral::CMPC0, ICU::VECTOR::CMPC0> CMPC0;
	typedef cmpc_t<0x000A0CA0, peripheral::CMPC1, ICU::VECTOR::CMPC1> CMPC1;
	typedef cmpc_t<0x000A0CC0, peripheral::CMPC2, ICU::VECTOR::CMPC2> CMPC2;
	typedef cmpc_t<0x000A0CE0, peripheral::CMPC3, ICU::VECTOR::CMPC3> CMPC3;
	typedef cmpc_t<0x000A0D00, peripheral::CMPC4, ICU::VECTOR::CMPC4> CMPC4;
	typedef cmpc_t<0x000A0D20, peripheral::CMPC5, ICU::VECTOR::CMPC5> CMPC5;
#endif
}
<commit_msg>Update: The reality of the template when it is not optimized<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX24T/RX66T グループ・CMPC 定義
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2016, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/device.hpp"

/// CMPC モジュールが無いデバイスでエラーとする
#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N)
#  error "cmpc.hpp: This module does not exist"
#endif

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  コンパレータ C（CMPC）
		@param[in]	base	ベース・アドレス
		@param[in]	per		ペリフェラル型
		@param[in]	ivec	割り込みベクタ型
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t base, peripheral per, ICU::VECTOR ivec>
	struct cmpc_t {

		static const auto PERIPHERAL = per;		///< ペリフェラル型
		static const auto IVEC = ivec;			///< 割り込みベクター

		//-----------------------------------------------------------------//
		/*!
			@brief  コンパレータ制御レジスタ（CMPCTL）
			@param[in]	ofs	オフセット
		*/
		//-----------------------------------------------------------------//
		template <uint32_t ofs>
		struct cmpctl_t : public rw8_t<ofs> {
			typedef rw8_t<ofs> io_;
			using io_::operator =;
			using io_::operator ();
			using io_::operator |=;
			using io_::operator &=;

			bit_rw_t <io_, bitpos::B0>     CINV;
			bit_rw_t <io_, bitpos::B1>     COE;
			bits_rw_t<io_, bitpos::B3, 2>  CEG;
			bits_rw_t<io_, bitpos::B5, 2>  CDFS;
			bit_rw_t <io_, bitpos::B7>     HCMPON;
		};
		typedef cmpctl_t<base + 0x00> CMPCTL_;
		static  CMPCTL_ CMPCTL;

		//-----------------------------------------------------------------//
		/*!
			@brief  コンパレータ入力切り替えレジスタ（CMPSEL0）
			@param[in]	ofs	オフセット
		*/
		//-----------------------------------------------------------------//
		template <uint32_t ofs>
		struct cmpsel0_t : public rw8_t<ofs> {
			typedef rw8_t<ofs> io_;
			using io_::operator =;
			using io_::operator ();
			using io_::operator |=;
			using io_::operator &=;

			bits_rw_t<io_, bitpos::B0, 4>  CMPSEL;
		};
		typedef cmpsel0_t<base + 0x04> CMPSEL0_;
		static  CMPSEL0_ CMPSEL0;

		//-----------------------------------------------------------------//
		/*!
			@brief  コンパレータ入力切り替えレジスタ（CMPSEL1）
			@param[in]	ofs	オフセット
		*/
		//-----------------------------------------------------------------//
		template <uint32_t ofs>
		struct cmpsel1_t : public rw8_t<ofs> {
			typedef rw8_t<ofs> io_;
			using io_::operator =;
			using io_::operator ();
			using io_::operator |=;
			using io_::operator &=;

			bits_rw_t<io_, bitpos::B0, 2>  CVRS;
		};
		typedef cmpsel1_t<base + 0x08> CMPSEL1_;
		static  CMPSEL1_ CMPSEL1;

		//-----------------------------------------------------------------//
		/*!
			@brief  コンパレータ出力モニタレジスタ（CMPMON）
			@param[in]	ofs	オフセット
		*/
		//-----------------------------------------------------------------//
		template <uint32_t ofs>
		struct cmpmon_t : public rw8_t<ofs> {
			typedef rw8_t<ofs> io_;
			using io_::operator =;
			using io_::operator ();
			using io_::operator |=;
			using io_::operator &=;

			bit_rw_t<io_, bitpos::B0>  CMPMON0;
		};
		typedef cmpmon_t<base + 0x0C> CMPMON_;
		static  CMPMON_ CMPMON;

		//-----------------------------------------------------------------//
		/*!
			@brief  コンパレータ外部出力許可レジスタ（CMPIOC）
			@param[in]	ofs	オフセット
		*/
		//-----------------------------------------------------------------//
		template <uint32_t ofs>
		struct cmpioc_t : public rw8_t<ofs> {
			typedef rw8_t<ofs> io_;
			using io_::operator =;
			using io_::operator ();
			using io_::operator |=;
			using io_::operator &=;

			bit_rw_t<io_, bitpos::B0>  CPOE;
		};
		typedef cmpioc_t<base + 0x10> CMPIOC_;
		static  CMPIOC_ CMPIOC;
	};
	template <uint32_t base, peripheral per, ICU::VECTOR ivec>
		typename cmpc_t<base, per, ivec>::CMPCTL_  cmpc_t<base, per, ivec>::CMPCTL;
	template <uint32_t base, peripheral per, ICU::VECTOR ivec>
		typename cmpc_t<base, per, ivec>::CMPSEL0_ cmpc_t<base, per, ivec>::CMPSEL0;
	template <uint32_t base, peripheral per, ICU::VECTOR ivec>
		typename cmpc_t<base, per, ivec>::CMPSEL1_ cmpc_t<base, per, ivec>::CMPSEL1;
	template <uint32_t base, peripheral per, ICU::VECTOR ivec>
		typename cmpc_t<base, per, ivec>::CMPMON_  cmpc_t<base, per, ivec>::CMPMON;
	template <uint32_t base, peripheral per, ICU::VECTOR ivec>
		typename cmpc_t<base, per, ivec>::CMPIOC_  cmpc_t<base, per, ivec>::CMPIOC;

#if defined(SIG_RX24T)
	typedef cmpc_t<0x000A0C80, peripheral::CMPC0, ICU::VECTOR::CMPC0> CMPC0;
	typedef cmpc_t<0x000A0CA0, peripheral::CMPC1, ICU::VECTOR::CMPC1> CMPC1;
	typedef cmpc_t<0x000A0CC0, peripheral::CMPC2, ICU::VECTOR::CMPC2> CMPC2;
	typedef cmpc_t<0x000A0CE0, peripheral::CMPC3, ICU::VECTOR::CMPC3> CMPC3;
#elif defined(SIG_RX66T)
	typedef cmpc_t<0x000A0C80, peripheral::CMPC0, ICU::VECTOR::CMPC0> CMPC0;
	typedef cmpc_t<0x000A0CA0, peripheral::CMPC1, ICU::VECTOR::CMPC1> CMPC1;
	typedef cmpc_t<0x000A0CC0, peripheral::CMPC2, ICU::VECTOR::CMPC2> CMPC2;
	typedef cmpc_t<0x000A0CE0, peripheral::CMPC3, ICU::VECTOR::CMPC3> CMPC3;
	typedef cmpc_t<0x000A0D00, peripheral::CMPC4, ICU::VECTOR::CMPC4> CMPC4;
	typedef cmpc_t<0x000A0D20, peripheral::CMPC5, ICU::VECTOR::CMPC5> CMPC5;
#endif
}
<|endoftext|>


<commit_before>#include "shadow/util/boxes.hpp"
#include "shadow/util/log.hpp"

namespace Boxes {

template <typename Dtype>
void Clip(const Box<Dtype> &box, Box<Dtype> *clip_box, Dtype min, Dtype max) {
  clip_box->xmin = std::max(std::min(box.xmin, max), min);
  clip_box->ymin = std::max(std::min(box.ymin, max), min);
  clip_box->xmax = std::max(std::min(box.xmax, max), min);
  clip_box->ymax = std::max(std::min(box.ymax, max), min);
}

template <typename Dtype>
Dtype Size(const Box<Dtype> &box) {
  return (box.xmax - box.xmin) * (box.ymax - box.ymin);
}

template <typename Dtype>
inline Dtype BorderOverlap(Dtype a1, Dtype a2, Dtype b1, Dtype b2) {
  Dtype left = a1 > b1 ? a1 : b1;
  Dtype right = a2 < b2 ? a2 : b2;
  return right - left;
}

template <typename Dtype>
float Intersection(const Box<Dtype> &box_a, const Box<Dtype> &box_b) {
  Dtype width = BorderOverlap(box_a.xmin, box_a.xmax, box_b.xmin, box_b.xmax);
  Dtype height = BorderOverlap(box_a.ymin, box_a.ymax, box_b.ymin, box_b.ymax);
  if (width < 0 || height < 0) return 0;
  return width * height;
}

template <typename Dtype>
float Union(const Box<Dtype> &box_a, const Box<Dtype> &box_b) {
  return Size(box_a) + Size(box_b) - Intersection(box_a, box_b);
}

template <typename Dtype>
float IoU(const Box<Dtype> &box_a, const Box<Dtype> &box_b) {
  return Intersection(box_a, box_b) / Union(box_a, box_b);
}

template <typename Dtype>
std::vector<Box<Dtype>> NMS(const std::vector<std::vector<Box<Dtype>>> &Bboxes,
                            float iou_threshold) {
  std::vector<Box<Dtype>> all_boxes;
  for (const auto &boxes : Bboxes) {
    for (const auto &box : boxes) {
      if (box.label != -1) all_boxes.push_back(box);
    }
  }
  for (int i = 0; i < all_boxes.size(); ++i) {
    Box<Dtype> &box_i = all_boxes[i];
    if (box_i.label == -1) continue;
    for (int j = i + 1; j < all_boxes.size(); ++j) {
      Box<Dtype> &box_j = all_boxes[j];
      if (box_j.label == -1 || box_i.label != box_j.label) continue;
      if (IoU(box_i, box_j) > iou_threshold) {
        float smooth = box_i.score / (box_i.score + box_j.score);
        Smooth(box_j, &box_i, smooth);
        box_j.label = -1;
        continue;
      }
      float in = Intersection(box_i, box_j);
      float cover_i = in / Size(box_i);
      float cover_j = in / Size(box_j);
      if (cover_i > cover_j && cover_i > 0.7) box_i.label = -1;
      if (cover_i < cover_j && cover_j > 0.7) box_j.label = -1;
    }
  }
  std::vector<Box<Dtype>> out_boxes;
  for (const auto &box : all_boxes) {
    if (box.label != -1) out_boxes.push_back(box);
  }
  all_boxes.clear();
  return out_boxes;
}

template <typename Dtype>
void Smooth(const Box<Dtype> &old_box, Box<Dtype> *new_box, float smooth) {
  new_box->xmin = old_box.xmin + (new_box->xmin - old_box.xmin) * smooth;
  new_box->ymin = old_box.ymin + (new_box->ymin - old_box.ymin) * smooth;
  new_box->xmax = old_box.xmax + (new_box->xmax - old_box.xmax) * smooth;
  new_box->ymax = old_box.ymax + (new_box->ymax - old_box.ymax) * smooth;
}

template <typename Dtype>
void Smooth(const std::vector<Box<Dtype>> &old_boxes,
            std::vector<Box<Dtype>> *new_boxes, float smooth) {
  for (auto &new_box : *new_boxes) {
    for (auto &old_box : old_boxes) {
      if (IoU(old_box, new_box) > 0.7) {
        Smooth(old_box, &new_box, smooth);
        break;
      }
    }
  }
}

template <typename Dtype>
void Amend(std::vector<std::vector<Box<Dtype>>> *Bboxes, const VecRectF &crops,
           int height, int width) {
  CHECK_EQ(Bboxes->size(), crops.size());
  for (int i = 0; i < crops.size(); ++i) {
    std::vector<Box<Dtype>> &boxes = Bboxes->at(i);
    const RectF &crop = crops[i];
    float x_off = crop.x <= 1 ? crop.x * width : crop.x;
    float y_off = crop.y <= 1 ? crop.y * height : crop.y;
    for (auto &box : boxes) {
      box.xmin += x_off;
      box.xmax += x_off;
      box.ymin += y_off;
      box.ymax += y_off;
    }
  }
}

// Explicit instantiation
template void Clip(const BoxI &box, BoxI *clip_box, int min, int max);
template void Clip(const BoxF &box, BoxF *clip_box, float min, float max);

template int Size(const BoxI &box);
template float Size(const BoxF &box);

template float Intersection(const BoxI &box_a, const BoxI &box_b);
template float Intersection(const BoxF &box_a, const BoxF &box_b);

template float Union(const BoxI &box_a, const BoxI &box_b);
template float Union(const BoxF &box_a, const BoxF &box_b);

template float IoU(const BoxI &box_a, const BoxI &box_b);
template float IoU(const BoxF &box_a, const BoxF &box_b);

template VecBoxI NMS(const std::vector<VecBoxI> &Bboxes, float iou_threshold);
template VecBoxF NMS(const std::vector<VecBoxF> &Bboxes, float iou_threshold);

template void Smooth(const BoxI &old_boxes, BoxI *new_boxes, float smooth);
template void Smooth(const BoxF &old_boxes, BoxF *new_boxes, float smooth);

template void Smooth(const VecBoxI &old_boxes, VecBoxI *new_boxes,
                     float smooth);
template void Smooth(const VecBoxF &old_boxes, VecBoxF *new_boxes,
                     float smooth);

template void Amend(std::vector<VecBoxI> *Bboxes, const VecRectF &crops,
                    int height, int width);
template void Amend(std::vector<VecBoxF> *Bboxes, const VecRectF &crops,
                    int height, int width);

}  // namespace Boxes
<commit_msg>fix bug: fix crop region normalize or none normalize error in amend function<commit_after>#include "shadow/util/boxes.hpp"
#include "shadow/util/log.hpp"

namespace Boxes {

template <typename Dtype>
void Clip(const Box<Dtype> &box, Box<Dtype> *clip_box, Dtype min, Dtype max) {
  clip_box->xmin = std::max(std::min(box.xmin, max), min);
  clip_box->ymin = std::max(std::min(box.ymin, max), min);
  clip_box->xmax = std::max(std::min(box.xmax, max), min);
  clip_box->ymax = std::max(std::min(box.ymax, max), min);
}

template <typename Dtype>
Dtype Size(const Box<Dtype> &box) {
  return (box.xmax - box.xmin) * (box.ymax - box.ymin);
}

template <typename Dtype>
inline Dtype BorderOverlap(Dtype a1, Dtype a2, Dtype b1, Dtype b2) {
  Dtype left = a1 > b1 ? a1 : b1;
  Dtype right = a2 < b2 ? a2 : b2;
  return right - left;
}

template <typename Dtype>
float Intersection(const Box<Dtype> &box_a, const Box<Dtype> &box_b) {
  Dtype width = BorderOverlap(box_a.xmin, box_a.xmax, box_b.xmin, box_b.xmax);
  Dtype height = BorderOverlap(box_a.ymin, box_a.ymax, box_b.ymin, box_b.ymax);
  if (width < 0 || height < 0) return 0;
  return width * height;
}

template <typename Dtype>
float Union(const Box<Dtype> &box_a, const Box<Dtype> &box_b) {
  return Size(box_a) + Size(box_b) - Intersection(box_a, box_b);
}

template <typename Dtype>
float IoU(const Box<Dtype> &box_a, const Box<Dtype> &box_b) {
  return Intersection(box_a, box_b) / Union(box_a, box_b);
}

template <typename Dtype>
std::vector<Box<Dtype>> NMS(const std::vector<std::vector<Box<Dtype>>> &Bboxes,
                            float iou_threshold) {
  std::vector<Box<Dtype>> all_boxes;
  for (const auto &boxes : Bboxes) {
    for (const auto &box : boxes) {
      if (box.label != -1) all_boxes.push_back(box);
    }
  }
  for (int i = 0; i < all_boxes.size(); ++i) {
    Box<Dtype> &box_i = all_boxes[i];
    if (box_i.label == -1) continue;
    for (int j = i + 1; j < all_boxes.size(); ++j) {
      Box<Dtype> &box_j = all_boxes[j];
      if (box_j.label == -1 || box_i.label != box_j.label) continue;
      if (IoU(box_i, box_j) > iou_threshold) {
        float smooth = box_i.score / (box_i.score + box_j.score);
        Smooth(box_j, &box_i, smooth);
        box_j.label = -1;
        continue;
      }
      float in = Intersection(box_i, box_j);
      float cover_i = in / Size(box_i);
      float cover_j = in / Size(box_j);
      if (cover_i > cover_j && cover_i > 0.7) box_i.label = -1;
      if (cover_i < cover_j && cover_j > 0.7) box_j.label = -1;
    }
  }
  std::vector<Box<Dtype>> out_boxes;
  for (const auto &box : all_boxes) {
    if (box.label != -1) out_boxes.push_back(box);
  }
  all_boxes.clear();
  return out_boxes;
}

template <typename Dtype>
void Smooth(const Box<Dtype> &old_box, Box<Dtype> *new_box, float smooth) {
  new_box->xmin = old_box.xmin + (new_box->xmin - old_box.xmin) * smooth;
  new_box->ymin = old_box.ymin + (new_box->ymin - old_box.ymin) * smooth;
  new_box->xmax = old_box.xmax + (new_box->xmax - old_box.xmax) * smooth;
  new_box->ymax = old_box.ymax + (new_box->ymax - old_box.ymax) * smooth;
}

template <typename Dtype>
void Smooth(const std::vector<Box<Dtype>> &old_boxes,
            std::vector<Box<Dtype>> *new_boxes, float smooth) {
  for (auto &new_box : *new_boxes) {
    for (auto &old_box : old_boxes) {
      if (IoU(old_box, new_box) > 0.7) {
        Smooth(old_box, &new_box, smooth);
        break;
      }
    }
  }
}

template <typename Dtype>
void Amend(std::vector<std::vector<Box<Dtype>>> *Bboxes, const VecRectF &crops,
           int height, int width) {
  CHECK_EQ(Bboxes->size(), crops.size());
  for (int i = 0; i < crops.size(); ++i) {
    std::vector<Box<Dtype>> &boxes = Bboxes->at(i);
    const RectF &crop = crops[i];
    bool normalize = crop.h <= 1 || crop.w <= 1;
    if (normalize) {
      CHECK_GT(height, 1);
      CHECK_GT(width, 1);
    }
    float x_off = normalize ? crop.x * width : crop.x;
    float y_off = normalize ? crop.y * height : crop.y;
    for (auto &box : boxes) {
      box.xmin += x_off;
      box.xmax += x_off;
      box.ymin += y_off;
      box.ymax += y_off;
    }
  }
}

// Explicit instantiation
template void Clip(const BoxI &box, BoxI *clip_box, int min, int max);
template void Clip(const BoxF &box, BoxF *clip_box, float min, float max);

template int Size(const BoxI &box);
template float Size(const BoxF &box);

template float Intersection(const BoxI &box_a, const BoxI &box_b);
template float Intersection(const BoxF &box_a, const BoxF &box_b);

template float Union(const BoxI &box_a, const BoxI &box_b);
template float Union(const BoxF &box_a, const BoxF &box_b);

template float IoU(const BoxI &box_a, const BoxI &box_b);
template float IoU(const BoxF &box_a, const BoxF &box_b);

template VecBoxI NMS(const std::vector<VecBoxI> &Bboxes, float iou_threshold);
template VecBoxF NMS(const std::vector<VecBoxF> &Bboxes, float iou_threshold);

template void Smooth(const BoxI &old_boxes, BoxI *new_boxes, float smooth);
template void Smooth(const BoxF &old_boxes, BoxF *new_boxes, float smooth);

template void Smooth(const VecBoxI &old_boxes, VecBoxI *new_boxes,
                     float smooth);
template void Smooth(const VecBoxF &old_boxes, VecBoxF *new_boxes,
                     float smooth);

template void Amend(std::vector<VecBoxI> *Bboxes, const VecRectF &crops,
                    int height, int width);
template void Amend(std::vector<VecBoxF> *Bboxes, const VecRectF &crops,
                    int height, int width);

}  // namespace Boxes
<|endoftext|>


<commit_before>#include <cudaarithm.hpp>
#include <opencv2/highgui.hpp>

extern "C"
struct TensorWrapper minCuda(
        struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst)
{
    GpuMatT dstMat = dst.toGpuMatT();
    cuda::GpuMat & mat = dstMat.mat;
    cuda::min(src1.toGpuMat(), src2.toGpuMat(), dstMat, prepareStream(info));
    return TensorWrapper(dstMat, info.state);
}

extern "C"
struct TensorWrapper maxCuda(
        struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst)
{
    if (dst.isNull()) {
        cuda::GpuMat result;
        cuda::max(src1.toGpuMat(), src2.toGpuMat(), result, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::max(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), prepareStream(info));
        return dst;
    }
}

extern "C"
struct TensorPlusDouble thresholdCuda(
        struct cutorchInfo info, struct TensorWrapper src,
        struct TensorWrapper dst, double thresh, double maxval, int type)
{
    TensorPlusDouble retval;

    if (dst.isNull()) {
        cuda::GpuMat result;
        retval.val = cuda::threshold(src.toGpuMat(), result, thresh, maxval, type, prepareStream(info));
        new (&retval.tensor) TensorWrapper(result, info.state);
    } else {
        retval.val = cuda::threshold(src.toGpuMat(), dst.toGpuMat(), thresh, maxval, type, prepareStream(info));
        retval.tensor = dst;
    }
    return retval;
}

extern "C"
struct TensorWrapper magnitudeCuda(
        struct cutorchInfo info, struct TensorWrapper xy, struct TensorWrapper magnitude)
{
    if (magnitude.isNull()) {
        cuda::GpuMat result;
        cuda::magnitude(xy.toGpuMat(), result, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::magnitude(xy.toGpuMat(), magnitude.toGpuMat(), prepareStream(info));
        return magnitude;
    }
}

extern "C"
struct TensorWrapper magnitudeSqrCuda(
        struct cutorchInfo info, struct TensorWrapper xy, struct TensorWrapper magnitude)
{
    if (magnitude.isNull()) {
        cuda::GpuMat result;
        cuda::magnitudeSqr(xy.toGpuMat(), result, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::magnitudeSqr(xy.toGpuMat(), magnitude.toGpuMat(), prepareStream(info));
        return magnitude;
    }
}

extern "C"
struct TensorWrapper magnitude2Cuda(
        struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitude)
{
    if (magnitude.isNull()) {
        cuda::GpuMat result;
        cuda::magnitude(x.toGpuMat(), y.toGpuMat(), result, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::magnitude(x.toGpuMat(), y.toGpuMat(), magnitude.toGpuMat(), prepareStream(info));
        return magnitude;
    }
}

extern "C"
struct TensorWrapper magnitudeSqr2Cuda(
        struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitudeSqr)
{
    if (magnitudeSqr.isNull()) {
        cuda::GpuMat result;
        cuda::magnitudeSqr(x.toGpuMat(), y.toGpuMat(), result, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::magnitudeSqr(x.toGpuMat(), y.toGpuMat(), magnitudeSqr.toGpuMat(), prepareStream(info));
        return magnitudeSqr;
    }
}

extern "C"
struct TensorWrapper phaseCuda(
        struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y,
        struct TensorWrapper angle, bool angleInDegrees)
{
    if (angle.isNull()) {
        cuda::GpuMat result;
        cuda::phase(x.toGpuMat(), y.toGpuMat(), result, angleInDegrees, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::phase(x.toGpuMat(), y.toGpuMat(), angle.toGpuMat(), angleInDegrees, prepareStream(info));
        return angle;
    }
}

extern "C"
struct TensorArray cartToPolarCuda(
        struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y,
        struct TensorWrapper magnitude, struct TensorWrapper angle, bool angleInDegrees)
{
    std::vector<cuda::GpuMat> result(2);
    result[0] = magnitude.toGpuMat();
    result[1] = angle.toGpuMat();

    cuda::cartToPolar(x.toGpuMat(), y.toGpuMat(), result[0], result[1], angleInDegrees, prepareStream(info));

    return TensorArray(result, info.state);
}

extern "C"
struct TensorArray polarToCartCuda(
        struct cutorchInfo info, struct TensorWrapper magnitude, struct TensorWrapper angle,
        struct TensorWrapper x, struct TensorWrapper y, bool angleInDegrees)
{
    std::vector<cuda::GpuMat> result;
    result[0] = x.toGpuMat();
    result[1] = y.toGpuMat();

    cuda::polarToCart(magnitude.toGpuMat(), angle.toGpuMat(), result[0], result[1], angleInDegrees, prepareStream(info));

    return TensorArray(result, info.state);
}

extern "C"
struct LookUpTablePtr LookUpTable_ctorCuda(
        struct cutorchInfo info, struct TensorWrapper lut)
{
    return rescueObjectFromPtr(cuda::createLookUpTable(lut.toGpuMat()));
}

extern "C"
struct TensorWrapper LookUpTable_transformCuda(
        struct cutorchInfo info, struct LookUpTablePtr ptr,
        struct TensorWrapper src, struct TensorWrapper dst)
{
    if (dst.isNull()) {
        cuda::GpuMat result;
        ptr->transform(src.toGpuMat(), result);
        return TensorWrapper(result, info.state);
    } else {
        ptr->transform(src.toGpuMat(), dst.toGpuMat(), prepareStream(info));
        return dst;
    }
}

extern "C"
struct TensorWrapper rectStdDevCuda(
        struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sqr,
        struct TensorWrapper dst, struct RectWrapper rect)
{
    if (dst.isNull()) {
        cv::Mat result;
        cuda::rectStdDev(src.toGpuMat(), sqr.toGpuMat(), result, rect, prepareStream(info));
        return TensorWrapper(result);
    } else {
        cuda::rectStdDev(src.toGpuMat(), sqr.toGpuMat(), dst.toGpuMat(), rect, prepareStream(info));
        return dst;
    }
}

extern "C"
struct TensorWrapper normalizeCuda(
        struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper dst,
        double alpha, double beta, int norm_type, int dtype, struct TensorWrapper mask)
{
    if (dst.isNull()) {
        cv::Mat result;
        cuda::normalize(src.toGpuMat(), result, alpha, beta, norm_type,
                        dtype, TO_MAT_OR_NOARRAY(mask), prepareStream(info));
        return TensorWrapper(result);
    } else {
        cuda::normalize(src.toGpuMat(), dst.toGpuMat(), alpha, beta, norm_type,
                        dtype, TO_MAT_OR_NOARRAY(mask), prepareStream(info));
        return dst;
    }
}

extern "C"
struct TensorWrapper integralCuda(
        struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sum)
{
    if (sum.isNull()) {
        cv::Mat result;
        cuda::integral(src.toGpuMat(), result, prepareStream(info));
        return TensorWrapper(result);
    } else {
        cuda::integral(src.toGpuMat(), sum.toGpuMat(), prepareStream(info));
        return sum;
    }
}

extern "C"
struct TensorWrapper sqrIntegralCuda(
        struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sum)
{
    if (sum.isNull()) {
        cv::Mat result;
        cuda::sqrIntegral(src.toGpuMat(), result, prepareStream(info));
        return TensorWrapper(result);
    } else {
        cuda::sqrIntegral(src.toGpuMat(), sum.toGpuMat(), prepareStream(info));
        return sum;
    }
}

extern "C"
struct TensorWrapper mulSpectrumsCuda(
        struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2,
        struct TensorWrapper dst, int flags, bool conjB)
{
    if (dst.isNull()) {
        cuda::GpuMat result;
        cuda::mulSpectrums(src1.toGpuMat(), src2.toGpuMat(), result, flags, conjB, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::mulSpectrums(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), flags, conjB, prepareStream(info));
        return dst;
    }
}

extern "C"
struct TensorWrapper mulAndScaleSpectrumsCuda(
        struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2,
        struct TensorWrapper dst, int flags, float scale, bool conjB)
{
    if (dst.isNull()) {
        cuda::GpuMat result;
        cuda::mulAndScaleSpectrums(src1.toGpuMat(), src2.toGpuMat(), result, flags, scale, conjB, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::mulAndScaleSpectrums(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), flags, scale, conjB, prepareStream(info));
        return dst;
    }
}

extern "C"
struct TensorWrapper dftCuda(
        struct cutorchInfo info, struct TensorWrapper src,
        struct TensorWrapper dst, struct SizeWrapper dft_size, int flags)
{
    if (dst.isNull()) {
        cv::Mat result;
        cuda::dft(src.toGpuMat(), result, dft_size, flags, prepareStream(info));
        return TensorWrapper(result);
    } else {
        cuda::dft(src.toGpuMat(), dst.toGpuMat(), dft_size, flags, prepareStream(info));
        return dst;
    }
}

extern "C"
struct ConvolutionPtr Convolution_ctorCuda(
        struct cutorchInfo info, struct SizeWrapper user_block_size)
{
    return rescueObjectFromPtr(cuda::createConvolution(user_block_size));
}

extern "C"
struct TensorWrapper Convolution_convolveCuda(
        struct cutorchInfo info, struct ConvolutionPtr ptr, struct TensorWrapper image,
        struct TensorWrapper templ, struct TensorWrapper result, bool ccor)
{
    if (result.isNull()) {
        cuda::GpuMat resultMat;
        ptr->convolve(image.toGpuMat(), templ.toGpuMat(), resultMat, ccor, prepareStream(info));
        return TensorWrapper(resultMat, info.state);
    } else {
        ptr->convolve(image.toGpuMat(), templ.toGpuMat(), result.toGpuMat(), ccor);
        return result;
    }
}
<commit_msg>Fix #193<commit_after>#include <cudaarithm.hpp>
#include <opencv2/highgui.hpp>

extern "C"
struct TensorWrapper minCuda(
        struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst)
{
    GpuMatT dstMat = dst.toGpuMatT();
    cuda::GpuMat & mat = dstMat.mat;
    cuda::min(src1.toGpuMat(), src2.toGpuMat(), dstMat, prepareStream(info));
    return TensorWrapper(dstMat, info.state);
}

extern "C"
struct TensorWrapper maxCuda(
        struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst)
{
    if (dst.isNull()) {
        cuda::GpuMat result;
        cuda::max(src1.toGpuMat(), src2.toGpuMat(), result, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::max(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), prepareStream(info));
        return dst;
    }
}

extern "C"
struct TensorPlusDouble thresholdCuda(
        struct cutorchInfo info, struct TensorWrapper src,
        struct TensorWrapper dst, double thresh, double maxval, int type)
{
    TensorPlusDouble retval;

    if (dst.isNull()) {
        cuda::GpuMat result;
        retval.val = cuda::threshold(src.toGpuMat(), result, thresh, maxval, type, prepareStream(info));
        new (&retval.tensor) TensorWrapper(result, info.state);
    } else {
        retval.val = cuda::threshold(src.toGpuMat(), dst.toGpuMat(), thresh, maxval, type, prepareStream(info));
        retval.tensor = dst;
    }
    return retval;
}

extern "C"
struct TensorWrapper magnitudeCuda(
        struct cutorchInfo info, struct TensorWrapper xy, struct TensorWrapper magnitude)
{
    if (magnitude.isNull()) {
        cuda::GpuMat result;
        cuda::magnitude(xy.toGpuMat(), result, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::magnitude(xy.toGpuMat(), magnitude.toGpuMat(), prepareStream(info));
        return magnitude;
    }
}

extern "C"
struct TensorWrapper magnitudeSqrCuda(
        struct cutorchInfo info, struct TensorWrapper xy, struct TensorWrapper magnitude)
{
    if (magnitude.isNull()) {
        cuda::GpuMat result;
        cuda::magnitudeSqr(xy.toGpuMat(), result, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::magnitudeSqr(xy.toGpuMat(), magnitude.toGpuMat(), prepareStream(info));
        return magnitude;
    }
}

extern "C"
struct TensorWrapper magnitude2Cuda(
        struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitude)
{
    if (magnitude.isNull()) {
        cuda::GpuMat result;
        cuda::magnitude(x.toGpuMat(), y.toGpuMat(), result, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::magnitude(x.toGpuMat(), y.toGpuMat(), magnitude.toGpuMat(), prepareStream(info));
        return magnitude;
    }
}

extern "C"
struct TensorWrapper magnitudeSqr2Cuda(
        struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitudeSqr)
{
    if (magnitudeSqr.isNull()) {
        cuda::GpuMat result;
        cuda::magnitudeSqr(x.toGpuMat(), y.toGpuMat(), result, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::magnitudeSqr(x.toGpuMat(), y.toGpuMat(), magnitudeSqr.toGpuMat(), prepareStream(info));
        return magnitudeSqr;
    }
}

extern "C"
struct TensorWrapper phaseCuda(
        struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y,
        struct TensorWrapper angle, bool angleInDegrees)
{
    if (angle.isNull()) {
        cuda::GpuMat result;
        cuda::phase(x.toGpuMat(), y.toGpuMat(), result, angleInDegrees, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::phase(x.toGpuMat(), y.toGpuMat(), angle.toGpuMat(), angleInDegrees, prepareStream(info));
        return angle;
    }
}

extern "C"
struct TensorArray cartToPolarCuda(
        struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y,
        struct TensorWrapper magnitude, struct TensorWrapper angle, bool angleInDegrees)
{
    std::vector<cuda::GpuMat> result(2);
    result[0] = magnitude.toGpuMat();
    result[1] = angle.toGpuMat();

    cuda::cartToPolar(x.toGpuMat(), y.toGpuMat(), result[0], result[1], angleInDegrees, prepareStream(info));

    return TensorArray(result, info.state);
}

extern "C"
struct TensorArray polarToCartCuda(
        struct cutorchInfo info, struct TensorWrapper magnitude, struct TensorWrapper angle,
        struct TensorWrapper x, struct TensorWrapper y, bool angleInDegrees)
{
    std::vector<cuda::GpuMat> result;
    result[0] = x.toGpuMat();
    result[1] = y.toGpuMat();

    cuda::polarToCart(magnitude.toGpuMat(), angle.toGpuMat(), result[0], result[1], angleInDegrees, prepareStream(info));

    return TensorArray(result, info.state);
}

extern "C"
struct LookUpTablePtr LookUpTable_ctorCuda(
        struct cutorchInfo info, struct TensorWrapper lut)
{
    return rescueObjectFromPtr(cuda::createLookUpTable(lut.toGpuMat()));
}

extern "C"
struct TensorWrapper LookUpTable_transformCuda(
        struct cutorchInfo info, struct LookUpTablePtr ptr,
        struct TensorWrapper src, struct TensorWrapper dst)
{
    if (dst.isNull()) {
        cuda::GpuMat result;
        ptr->transform(src.toGpuMat(), result);
        return TensorWrapper(result, info.state);
    } else {
        ptr->transform(src.toGpuMat(), dst.toGpuMat(), prepareStream(info));
        return dst;
    }
}

extern "C"
struct TensorWrapper rectStdDevCuda(
        struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sqr,
        struct TensorWrapper dst, struct RectWrapper rect)
{
    if (dst.isNull()) {
        cuda::GpuMat result;
        cuda::rectStdDev(src.toGpuMat(), sqr.toGpuMat(), result, rect, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::rectStdDev(src.toGpuMat(), sqr.toGpuMat(), dst.toGpuMat(), rect, prepareStream(info));
        return dst;
    }
}

extern "C"
struct TensorWrapper normalizeCuda(
        struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper dst,
        double alpha, double beta, int norm_type, int dtype, struct TensorWrapper mask)
{
    if (dst.isNull()) {
        cuda::GpuMat result;
        cuda::normalize(src.toGpuMat(), result, alpha, beta, norm_type,
                        dtype, TO_MAT_OR_NOARRAY(mask), prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::normalize(src.toGpuMat(), dst.toGpuMat(), alpha, beta, norm_type,
                        dtype, TO_MAT_OR_NOARRAY(mask), prepareStream(info));
        return dst;
    }
}

extern "C"
struct TensorWrapper integralCuda(
        struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sum)
{
    if (sum.isNull()) {
        cuda::GpuMat result;
        cuda::integral(src.toGpuMat(), result, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::integral(src.toGpuMat(), sum.toGpuMat(), prepareStream(info));
        return sum;
    }
}

extern "C"
struct TensorWrapper sqrIntegralCuda(
        struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sum)
{
    if (sum.isNull()) {
        cuda::GpuMat result;
        cuda::sqrIntegral(src.toGpuMat(), result, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::sqrIntegral(src.toGpuMat(), sum.toGpuMat(), prepareStream(info));
        return sum;
    }
}

extern "C"
struct TensorWrapper mulSpectrumsCuda(
        struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2,
        struct TensorWrapper dst, int flags, bool conjB)
{
    if (dst.isNull()) {
        cuda::GpuMat result;
        cuda::mulSpectrums(src1.toGpuMat(), src2.toGpuMat(), result, flags, conjB, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::mulSpectrums(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), flags, conjB, prepareStream(info));
        return dst;
    }
}

extern "C"
struct TensorWrapper mulAndScaleSpectrumsCuda(
        struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2,
        struct TensorWrapper dst, int flags, float scale, bool conjB)
{
    if (dst.isNull()) {
        cuda::GpuMat result;
        cuda::mulAndScaleSpectrums(src1.toGpuMat(), src2.toGpuMat(), result, flags, scale, conjB, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::mulAndScaleSpectrums(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), flags, scale, conjB, prepareStream(info));
        return dst;
    }
}

extern "C"
struct TensorWrapper dftCuda(
        struct cutorchInfo info, struct TensorWrapper src,
        struct TensorWrapper dst, struct SizeWrapper dft_size, int flags)
{
    if (dst.isNull()) {
        cuda::GpuMat result;
        cuda::dft(src.toGpuMat(), result, dft_size, flags, prepareStream(info));
        return TensorWrapper(result, info.state);
    } else {
        cuda::dft(src.toGpuMat(), dst.toGpuMat(), dft_size, flags, prepareStream(info));
        return dst;
    }
}

extern "C"
struct ConvolutionPtr Convolution_ctorCuda(
        struct cutorchInfo info, struct SizeWrapper user_block_size)
{
    return rescueObjectFromPtr(cuda::createConvolution(user_block_size));
}

extern "C"
struct TensorWrapper Convolution_convolveCuda(
        struct cutorchInfo info, struct ConvolutionPtr ptr, struct TensorWrapper image,
        struct TensorWrapper templ, struct TensorWrapper result, bool ccor)
{
    if (result.isNull()) {
        cuda::GpuMat resultMat;
        ptr->convolve(image.toGpuMat(), templ.toGpuMat(), resultMat, ccor, prepareStream(info));
        return TensorWrapper(resultMat, info.state);
    } else {
        ptr->convolve(image.toGpuMat(), templ.toGpuMat(), result.toGpuMat(), ccor);
        return result;
    }
}
<|endoftext|>


<commit_before>#pragma once

#include <dispatch/dispatch.h>
#include <sstream>
#include <string>

class gcd_utility final {
public:
  class scoped_queue final {
  public:
    scoped_queue(void) {
      auto label = get_next_queue_label();
      queue_ = dispatch_queue_create(label.c_str(), nullptr);
    }

    ~scoped_queue(void) {
      dispatch_release(queue_);
    }

    dispatch_queue_t _Nonnull get(void) { return queue_; }

  private:
    dispatch_queue_t _Nonnull queue_;
  };

private:
  static std::string get_next_queue_label(void) {
    static std::mutex mutex;
    static int id = 0;

    std::lock_guard<std::mutex> guard(mutex);

    std::stringstream stream;
    stream << "org.pqrs.gcd_utility." << id++;
    return stream.str();
  }
};
<commit_msg>add gcd_utility::scoped_queue::get_label<commit_after>#pragma once

#include <dispatch/dispatch.h>
#include <sstream>
#include <string>

class gcd_utility final {
public:
  class scoped_queue final {
  public:
    scoped_queue(void) {
      auto label = get_next_queue_label();
      queue_ = dispatch_queue_create(label.c_str(), nullptr);
    }

    ~scoped_queue(void) {
      dispatch_release(queue_);
    }

    dispatch_queue_t _Nonnull get(void) { return queue_; }

    std::string get_label(void) {
      auto p = dispatch_queue_get_label(queue_);
      return p ? p : "";
    }

  private:
    dispatch_queue_t _Nonnull queue_;
  };

private:
  static std::string get_next_queue_label(void) {
    static std::mutex mutex;
    static int id = 0;

    std::lock_guard<std::mutex> guard(mutex);

    std::stringstream stream;
    stream << "org.pqrs.gcd_utility." << id++;
    return stream.str();
  }
};
<|endoftext|>


<commit_before>#include "SysConfig.h"
#if(HAS_PCA9539)

#include <CI2C.h>
#include "CPCA9539.h"
#include "CTimer.h"
#include "NDataManager.h"

namespace
{
    CTimer pcaSampleTimer;

    namespace knight_rider
    {
        //Knight rider stuff

        //Bit counter
        uint8_t counter;

        //Value that stores the mutated counter
        uint8_t value;

        //Bit mask for the PCA
        uint8_t bitmask = 0x1F;

        bool firstPass;
    }
}

CPCA9539::CPCA9539( CI2C *i2cInterfaceIn )
    : m_pca( i2cInterfaceIn )
{

}

void CPCA9539::Initialize()
{
    Serial.println( "CPCA9539.Status:INIT;" );

    //Timer resets
    pcaSampleTimer.Reset();

    //Knight rider stuff
    knight_rider::counter = 0;
    knight_rider::firstPass = true;

    //Expander init
    m_pca.Initialize();
    m_pca.PinMode( OUTPUT );

    Serial.println( "CPCA9539.Status:POST_INIT;");
}

void CPCA9539::Update( CCommand &commandIn )
{
    if( pcaSampleTimer.HasElapsed( 100 ) )
    {
        KnightRider();
    }
}

void CPCA9539::KnightRider()
{
    if( knight_rider::firstPass )
    {
        if( knight_rider::counter = 0 )
        {
            knight_rider::counter = 2;
        }

        //For the PCA, 1 is low and 0 is high
        //So we need to not and then mask the counter to get the desired pattern
        knight_rider::value = ~(knight_rider::counter);
        knight_rider::value &= knight_rider::bitmask;

        //Write the desired pattern
        auto ret = m_pca.DigitalWriteDecimal( knight_rider::value );
        if( ret != pca9539::ERetCode::SUCCESS )
        {
            Serial.println(ret);
        }

        //Increase the counter
        knight_rider::counter <<= 1;

        if( knight_rider::counter == 16 )
        {
            //Start the second half of the pattern
            knight_rider::firstPass = false;
        }
    }
    else
    {
        //For the PCA, 1 is low and 0 is high
        //So we need to not and then mask the counter to get the desired pattern
        knight_rider::value = ~(knight_rider::counter);
        knight_rider::value &= knight_rider::bitmask;

        //Write the desired pattern
        auto ret = m_pca.DigitalWriteDecimal( knight_rider::value );
        if( ret != pca9539::ERetCode::SUCCESS )
        {
            Serial.println(ret);
        }

        //Increase the counter
        knight_rider::counter >>= 1;

        if( knight_rider::counter == 0 )
        {
            //Reset the counter to the first section of the pattern
            knight_rider::firstPass = true;
        }
    }
}

#endif<commit_msg>typo Honestly I don't know how this compiles w/o warns<commit_after>#include "SysConfig.h"
#if(HAS_PCA9539)

#include <CI2C.h>
#include "CPCA9539.h"
#include "CTimer.h"
#include "NDataManager.h"

namespace
{
    CTimer pcaSampleTimer;

    namespace knight_rider
    {
        //Knight rider stuff

        //Bit counter
        uint8_t counter;

        //Value that stores the mutated counter
        uint8_t value;

        //Bit mask for the PCA
        uint8_t bitmask = 0x1F;

        bool firstPass;
    }
}

CPCA9539::CPCA9539( CI2C *i2cInterfaceIn )
    : m_pca( i2cInterfaceIn )
{

}

void CPCA9539::Initialize()
{
    Serial.println( "CPCA9539.Status:INIT;" );

    //Timer resets
    pcaSampleTimer.Reset();

    //Knight rider stuff
    knight_rider::counter = 0;
    knight_rider::firstPass = true;

    //Expander init
    m_pca.Initialize();
    m_pca.PinMode( OUTPUT );

    Serial.println( "CPCA9539.Status:POST_INIT;");
}

void CPCA9539::Update( CCommand &commandIn )
{
    if( pcaSampleTimer.HasElapsed( 100 ) )
    {
        KnightRider();
    }
}

void CPCA9539::KnightRider()
{
    if( knight_rider::firstPass )
    {
        if( knight_rider::counter == 0 )
        {
            knight_rider::counter = 2;
        }

        //For the PCA, 1 is low and 0 is high
        //So we need to not and then mask the counter to get the desired pattern
        knight_rider::value = ~(knight_rider::counter);
        knight_rider::value &= knight_rider::bitmask;

        //Write the desired pattern
        auto ret = m_pca.DigitalWriteDecimal( knight_rider::value );
        if( ret != pca9539::ERetCode::SUCCESS )
        {
            Serial.println(ret);
        }

        //Increase the counter
        knight_rider::counter <<= 1;

        if( knight_rider::counter == 16 )
        {
            //Start the second half of the pattern
            knight_rider::firstPass = false;
        }
    }
    else
    {
        //For the PCA, 1 is low and 0 is high
        //So we need to not and then mask the counter to get the desired pattern
        knight_rider::value = ~(knight_rider::counter);
        knight_rider::value &= knight_rider::bitmask;

        //Write the desired pattern
        auto ret = m_pca.DigitalWriteDecimal( knight_rider::value );
        if( ret != pca9539::ERetCode::SUCCESS )
        {
            Serial.println(ret);
        }

        //Increase the counter
        knight_rider::counter >>= 1;

        if( knight_rider::counter == 0 )
        {
            //Reset the counter to the first section of the pattern
            knight_rider::firstPass = true;
        }
    }
}

#endif<|endoftext|>


<commit_before>/*
 * AddSimMessage.cpp
 *
 *  Created on: 18.04.2016
 *      Author: Marc Hartung
 */

#include "../../include/messages/AddSimMessage.hpp"
#include "../../include/messages/AbstractMessage.hpp"
#include "../../include/AdditionalTypes.hpp"
#include "../../include/network_impl/SimNetworkFunctions.hpp"

#include <iostream>

namespace NetOff
{
    //////////////////////////////////////////////
    /////////////AddSimRequestMessage/////////////
    //////////////////////////////////////////////

    AddSimRequestMessage::AddSimRequestMessage(const int & id, const std::string & path)
            : AbstractMessage<InitialClientMessageSpecifyer>(InitialClientMessageSpecifyer::ADD_SIM)
    {
        _dataSize = sizeof(InitialClientMessageSpecifyer) + sizeof(int) + getStringDataSize(path);
        _data = std::shared_ptr<char>(new char[_dataSize]);
        char * p = _data.get();
        p = saveShiftIntegralInData(InitialClientMessageSpecifyer::ADD_SIM, p);
        p = saveShiftIntegralInData(id, p);
        saveStringInData(path, p);
    }

    AddSimRequestMessage::AddSimRequestMessage(std::shared_ptr<char> & data)
            : AbstractMessage<InitialClientMessageSpecifyer>(*reinterpret_cast<InitialClientMessageSpecifyer *>(data.get())),
              _data(data),
              _dataSize(0)
    {
    }

    char * AddSimRequestMessage::data()
    {
        return _data.get();
    }

    const char * AddSimRequestMessage::data() const
    {
        return _data.get();
    }

    size_t AddSimRequestMessage::dataSize() const
    {
        return _dataSize;
    }

    int AddSimRequestMessage::getSimId()
    {
        return *reinterpret_cast<int*>(shift<InitialClientMessageSpecifyer>(_data.get()));
    }

    std::string AddSimRequestMessage::getPath()
    {
        return createStringFromData(shift<int>(shift<InitialClientMessageSpecifyer>(_data.get())));
    }

    //////////////////////////////////////////////
    /////////AddSimRequestSuccessMessage//////////
    //////////////////////////////////////////////

    AddSimSuccessMessage::AddSimSuccessMessage(const int & id, const VariableList & inputs, const VariableList & outputs)
            : AbstractMessage<InitialServerMessageSpecifyer>(InitialServerMessageSpecifyer::SUCCESS_ADD_SIM),
              _dataSize(0)

    {
        _dataSize = sizeof(InitialServerMessageSpecifyer) + sizeof(int) + inputs.dataSize() + outputs.dataSize();
        _data = std::shared_ptr<char>(new char[_dataSize]);
        char * p = _data.get();
        p = saveShiftIntegralInData(InitialServerMessageSpecifyer::SUCCESS_ADD_SIM, p);
        p = saveShiftIntegralInData(id, p);
        inputs.saveVariablesTo(p);
        p = shiftDataAccessable<VariableList>(inputs,p);
        outputs.saveVariablesTo(p);
    }

    AddSimSuccessMessage::AddSimSuccessMessage(std::shared_ptr<char> & data)
            : AbstractMessage<InitialServerMessageSpecifyer>(getIntegralFromData<InitialServerMessageSpecifyer>(data.get())),
              _data(data),
              _dataSize(0)
    {
    }

    char * AddSimSuccessMessage::data()
    {
        return _data.get();
    }

    const char * AddSimSuccessMessage::data() const
    {
        return _data.get();
    }

    size_t AddSimSuccessMessage::dataSize() const
    {
        return _dataSize;
    }

    const int & AddSimSuccessMessage::getSimId() const
    {
        return *reinterpret_cast<int*>(shift<InitialServerMessageSpecifyer>(_data.get()));
    }

    VariableList AddSimSuccessMessage::getInputVariableList() const
    {
        return VariableList::getVariableListFromData(shift<const int>(shift<const InitialServerMessageSpecifyer>(_data.get())));
    }

    VariableList AddSimSuccessMessage::getOutputVariableList() const
    {
        return VariableList::getVariableListFromData(shift<const int>(shiftDataAccessable<VariableList>(getInputVariableList(),shift<const InitialServerMessageSpecifyer>(_data.get()))));
    }

    std::string AddSimSuccessMessage::getPath()
    {
        return createStringFromData(shift<int>(shift<InitialServerMessageSpecifyer>(_data.get())));
    }
}

<commit_msg>Add default initialization of members to constructor<commit_after>/*
 * AddSimMessage.cpp
 *
 *  Created on: 18.04.2016
 *      Author: Marc Hartung
 */

#include "../../include/messages/AddSimMessage.hpp"
#include "../../include/messages/AbstractMessage.hpp"
#include "../../include/AdditionalTypes.hpp"
#include "../../include/network_impl/SimNetworkFunctions.hpp"

#include <iostream>

namespace NetOff
{
    //////////////////////////////////////////////
    /////////////AddSimRequestMessage/////////////
    //////////////////////////////////////////////

    AddSimRequestMessage::AddSimRequestMessage(const int & id, const std::string & path)
            : AbstractMessage<InitialClientMessageSpecifyer>(InitialClientMessageSpecifyer::ADD_SIM),
              _data(nullptr),
              _dataSize(0)
    {
        _dataSize = sizeof(InitialClientMessageSpecifyer) + sizeof(int) + getStringDataSize(path);
        _data = std::shared_ptr<char>(new char[_dataSize]);
        char * p = _data.get();
        p = saveShiftIntegralInData(InitialClientMessageSpecifyer::ADD_SIM, p);
        p = saveShiftIntegralInData(id, p);
        saveStringInData(path, p);
    }

    AddSimRequestMessage::AddSimRequestMessage(std::shared_ptr<char> & data)
            : AbstractMessage<InitialClientMessageSpecifyer>(*reinterpret_cast<InitialClientMessageSpecifyer *>(data.get())),
              _data(data),
              _dataSize(0)
    {
    }

    char * AddSimRequestMessage::data()
    {
        return _data.get();
    }

    const char * AddSimRequestMessage::data() const
    {
        return _data.get();
    }

    size_t AddSimRequestMessage::dataSize() const
    {
        return _dataSize;
    }

    int AddSimRequestMessage::getSimId()
    {
        return *reinterpret_cast<int*>(shift<InitialClientMessageSpecifyer>(_data.get()));
    }

    std::string AddSimRequestMessage::getPath()
    {
        return createStringFromData(shift<int>(shift<InitialClientMessageSpecifyer>(_data.get())));
    }

    //////////////////////////////////////////////
    /////////AddSimRequestSuccessMessage//////////
    //////////////////////////////////////////////

    AddSimSuccessMessage::AddSimSuccessMessage(const int & id, const VariableList & inputs, const VariableList & outputs)
            : AbstractMessage<InitialServerMessageSpecifyer>(InitialServerMessageSpecifyer::SUCCESS_ADD_SIM),
              _data(nullptr),
              _dataSize(0)
    {
        _dataSize = sizeof(InitialServerMessageSpecifyer) + sizeof(int) + inputs.dataSize() + outputs.dataSize();
        _data = std::shared_ptr<char>(new char[_dataSize]);
        char * p = _data.get();
        p = saveShiftIntegralInData(InitialServerMessageSpecifyer::SUCCESS_ADD_SIM, p);
        p = saveShiftIntegralInData(id, p);
        inputs.saveVariablesTo(p);
        p = shiftDataAccessable<VariableList>(inputs, p);
        outputs.saveVariablesTo(p);
    }

    AddSimSuccessMessage::AddSimSuccessMessage(std::shared_ptr<char> & data)
            : AbstractMessage<InitialServerMessageSpecifyer>(getIntegralFromData<InitialServerMessageSpecifyer>(data.get())),
              _data(data),
              _dataSize(0)
    {
    }

    char * AddSimSuccessMessage::data()
    {
        return _data.get();
    }

    const char * AddSimSuccessMessage::data() const
    {
        return _data.get();
    }

    size_t AddSimSuccessMessage::dataSize() const
    {
        return _dataSize;
    }

    const int & AddSimSuccessMessage::getSimId() const
    {
        return *reinterpret_cast<int*>(shift<InitialServerMessageSpecifyer>(_data.get()));
    }

    VariableList AddSimSuccessMessage::getInputVariableList() const
    {
        return VariableList::getVariableListFromData(shift<const int>(shift<const InitialServerMessageSpecifyer>(_data.get())));
    }

    VariableList AddSimSuccessMessage::getOutputVariableList() const
    {
        return VariableList::getVariableListFromData(shift<const int>(shiftDataAccessable<VariableList>(getInputVariableList(), shift<const InitialServerMessageSpecifyer>(_data.get()))));
    }

    std::string AddSimSuccessMessage::getPath()
    {
        return createStringFromData(shift<int>(shift<InitialServerMessageSpecifyer>(_data.get())));
    }
}
<|endoftext|>