<commit_before>/**
 * @file Cosa/Interrupt.h
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2013, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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
 *
 * @section Description
 * Interface for Interrupt Handlers.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#ifndef __COSA_INTERRUPT_H__
#define __COSA_INTERRUPT_H__

class Interrupt {
public:
  class Handler {
  public:
    virtual void on_interrupt() {}
    virtual void on_interrupt(uint8_t arg) {}
    virtual void on_interrupt(uint16_t arg) {}
  };
};

#endif

<commit_msg>Fixing naming convension.<commit_after>/**
 * @file Cosa/Interrupt.hh
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2013, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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
 *
 * @section Description
 * Interface for Interrupt Handlers.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#ifndef __COSA_INTERRUPT_HH__
#define __COSA_INTERRUPT_HH__

class Interrupt {
public:
  class Handler {
  public:
    virtual void on_interrupt() {}
    virtual void on_interrupt(uint8_t arg) {}
    virtual void on_interrupt(uint16_t arg) {}
  };
};

#endif

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkDataArraySelection.cxx

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

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

=========================================================================*/
#include "vtkDataArraySelection.h"
#include "vtkObjectFactory.h"

#include <vtkstd/vector>
#include <vtkstd/string>
#include <vtkstd/algorithm>

vtkCxxRevisionMacro(vtkDataArraySelection, "1.15");
vtkStandardNewMacro(vtkDataArraySelection);

class vtkDataArraySelectionArrayNamesType: public vtkstd::vector<vtkstd::string> {};
class vtkDataArraySelectionArraySettingsType: public vtkstd::vector<int> {};

//----------------------------------------------------------------------------
vtkDataArraySelection::vtkDataArraySelection()
{
  this->ArrayNames = new vtkDataArraySelectionArrayNamesType;
  this->ArraySettings = new vtkDataArraySelectionArraySettingsType;
}

//----------------------------------------------------------------------------
vtkDataArraySelection::~vtkDataArraySelection()
{
  delete this->ArraySettings;
  delete this->ArrayNames;
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "Number of Arrays: " << this->GetNumberOfArrays() << "\n";
  vtkIndent nindent = indent.GetNextIndent();
  int cc;
  for ( cc = 0; cc < this->GetNumberOfArrays(); cc ++ )
    {
    os << nindent << "Array: " << this->GetArrayName(cc) << " is: "
      << (this->GetArraySetting(cc)?"enabled":"disabled")
      << " (" << this->ArrayIsEnabled(this->GetArrayName(cc)) << ")" <<  endl;
    }
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::EnableArray(const char* name)
{
  vtkDebugMacro("Enabling array \"" << name << "\".");
  vtkstd::vector<vtkstd::string>::iterator i =
    vtkstd::find(this->ArrayNames->begin(), this->ArrayNames->end(), vtkstd::string(name));
  if(i != this->ArrayNames->end())
    {
    int& setting = (*this->ArraySettings)[i-this->ArrayNames->begin()];
    if(!setting)
      {
      setting = 1;
      this->Modified();
      }
    }
  else
    {
    this->ArrayNames->push_back(name);
    this->ArraySettings->push_back(1);
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::DisableArray(const char* name)
{
  vtkDebugMacro("Disabling array \"" << name << "\".");
  vtkstd::vector<vtkstd::string>::iterator i =
    vtkstd::find(this->ArrayNames->begin(), this->ArrayNames->end(), vtkstd::string(name));
  if(i != this->ArrayNames->end())
    {
    int& setting = (*this->ArraySettings)[i - this->ArrayNames->begin()];
    if(setting)
      {
      setting = 0;
      this->Modified();
      }
    }
  else
    {
    this->ArrayNames->push_back(name);
    this->ArraySettings->push_back(0);
    this->Modified();
    }
}

//----------------------------------------------------------------------------
int vtkDataArraySelection::ArrayIsEnabled(const char* name)
{
  // Check if there is a specific entry for this array.
  vtkstd::vector<vtkstd::string>::iterator i =
    vtkstd::find(this->ArrayNames->begin(), this->ArrayNames->end(), vtkstd::string(name));
  if(i != this->ArrayNames->end())
    {
    return (*this->ArraySettings)[i - this->ArrayNames->begin()];
    }

  // The array does not have an entry.  Assume it is disabled.
  return 0;
}

//----------------------------------------------------------------------------
int vtkDataArraySelection::ArrayExists(const char* name)
{
  // Check if there is a specific entry for this array.
  vtkstd::vector<vtkstd::string>::iterator i =
    vtkstd::find(this->ArrayNames->begin(), this->ArrayNames->end(), vtkstd::string(name));
  return i != this->ArrayNames->end();
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::EnableAllArrays()
{
  vtkDebugMacro("Enabling all arrays.");
  int modified = 0;
  for(vtkstd::vector<int>::iterator i = this->ArraySettings->begin();
      i != this->ArraySettings->end(); ++i)
    {
    if(!*i)
      {
      *i = 1;
      modified = 1;
      }
    }
  if(modified)
    {
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::DisableAllArrays()
{
  vtkDebugMacro("Disabling all arrays.");
  int modified = 0;
  for(vtkstd::vector<int>::iterator i = this->ArraySettings->begin();
      i != this->ArraySettings->end(); ++i)
    {
    if(*i)
      {
      *i = 0;
      modified = 1;
      }
    }
  if(modified)
    {
    this->Modified();
    }
}

//----------------------------------------------------------------------------
int vtkDataArraySelection::GetNumberOfArrays()
{
  return static_cast<int>(this->ArrayNames->size());
}

//----------------------------------------------------------------------------
const char* vtkDataArraySelection::GetArrayName(int index)
{
  vtkstd::vector<vtkstd::string>::iterator i = this->ArrayNames->begin()+index;
  if(i >= this->ArrayNames->begin() && i < this->ArrayNames->end())
    {
    return i->c_str();
    }
  return 0;
}

//----------------------------------------------------------------------------
int vtkDataArraySelection::GetArraySetting(int index)
{
  vtkstd::vector<int>::iterator i = this->ArraySettings->begin()+index;
  if(i >= this->ArraySettings->begin() && i < this->ArraySettings->end())
    {
    return *i;
    }
  return 0;
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::RemoveAllArrays()
{
  vtkDebugMacro("Removing all arrays.");
  if(this->GetNumberOfArrays() > 0)
    {
    this->ArrayNames->erase(this->ArrayNames->begin(),
                            this->ArrayNames->end());
    this->ArraySettings->erase(this->ArraySettings->begin(),
                               this->ArraySettings->end());
    this->Modified();
    }
}

//----------------------------------------------------------------------------
int vtkDataArraySelection::AddArray(const char* name)
{
  vtkDebugMacro("Adding array \"" << name << "\".");

  // This function is called only by the filter owning the selection.
  // It should not call Modified() because array settings are not
  // changed.
  if(this->ArrayExists(name))
    {
    return 0;
    }
  this->ArrayNames->push_back(name);
  this->ArraySettings->push_back(1);
  return 1;
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::SetArrays(const char* const* names, int numArrays)
{
  this->SetArraysWithDefault(names, numArrays, 1);
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::SetArraysWithDefault(const char* const* names,
                                                 int numArrays,
                                                 int defaultStatus)
{
  // This function is called only by the filter owning the selection.
  // It should not call Modified() because array settings are not
  // changed.

  vtkDebugMacro("Settings arrays to given list of " << numArrays
                << " arrays.");

  // Create a new map for this set of arrays.
  vtkDataArraySelectionArrayNamesType* newNames =
    new vtkDataArraySelectionArrayNamesType;
  vtkDataArraySelectionArraySettingsType* newSettings =
    new vtkDataArraySelectionArraySettingsType;

  newNames->reserve(numArrays);
  newSettings->reserve(numArrays);

  // Fill with settings for all arrays.
  int i;
  for(i=0;i < numArrays; ++i)
    {
    // Add this array.
    newNames->push_back(names[i]);

    // Fill in the setting.  Use the old value if available.
    // Otherwise, default to on.
    vtkstd::vector<vtkstd::string>::iterator it =
      vtkstd::find(this->ArrayNames->begin(), this->ArrayNames->end(),
                   vtkstd::string(names[i]));
    int setting = defaultStatus?1:0;
    if(it != this->ArrayNames->end())
      {
      setting = (*this->ArraySettings)[it - this->ArrayNames->begin()];
      }
    newSettings->push_back(setting);
    }

  // Delete the old map and save the new one.
  delete this->ArrayNames;
  delete this->ArraySettings;
  this->ArrayNames = newNames;
  this->ArraySettings = newSettings;
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::CopySelections(vtkDataArraySelection* selections)
{
  if(this == selections)
    {
    return;
    }

  vtkDebugMacro("Copying arrays and settings from " << selections << ".");

  this->RemoveAllArrays();

  this->ArrayNames->insert(this->ArrayNames->begin(),
                           selections->ArrayNames->begin(),
                           selections->ArrayNames->end());
  this->ArraySettings->insert(this->ArraySettings->begin(),
                              selections->ArraySettings->begin(),
                              selections->ArraySettings->end());
  this->Modified();
}
<commit_msg>BUG: (bug #1508) In the CopySelections method, check whether the array names and settings of the input vtkDataArraySelection match this one before actually copying.  Without this change, the EnSight reader was being modified when nothing had actually changed, and so it was re-executing unnecessarily.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkDataArraySelection.cxx

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

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

=========================================================================*/
#include "vtkDataArraySelection.h"
#include "vtkObjectFactory.h"

#include <vtkstd/vector>
#include <vtkstd/string>
#include <vtkstd/algorithm>

vtkCxxRevisionMacro(vtkDataArraySelection, "1.16");
vtkStandardNewMacro(vtkDataArraySelection);

class vtkDataArraySelectionArrayNamesType: public vtkstd::vector<vtkstd::string> {};
class vtkDataArraySelectionArraySettingsType: public vtkstd::vector<int> {};

//----------------------------------------------------------------------------
vtkDataArraySelection::vtkDataArraySelection()
{
  this->ArrayNames = new vtkDataArraySelectionArrayNamesType;
  this->ArraySettings = new vtkDataArraySelectionArraySettingsType;
}

//----------------------------------------------------------------------------
vtkDataArraySelection::~vtkDataArraySelection()
{
  delete this->ArraySettings;
  delete this->ArrayNames;
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "Number of Arrays: " << this->GetNumberOfArrays() << "\n";
  vtkIndent nindent = indent.GetNextIndent();
  int cc;
  for ( cc = 0; cc < this->GetNumberOfArrays(); cc ++ )
    {
    os << nindent << "Array: " << this->GetArrayName(cc) << " is: "
      << (this->GetArraySetting(cc)?"enabled":"disabled")
      << " (" << this->ArrayIsEnabled(this->GetArrayName(cc)) << ")" <<  endl;
    }
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::EnableArray(const char* name)
{
  vtkDebugMacro("Enabling array \"" << name << "\".");
  vtkstd::vector<vtkstd::string>::iterator i =
    vtkstd::find(this->ArrayNames->begin(), this->ArrayNames->end(), vtkstd::string(name));
  if(i != this->ArrayNames->end())
    {
    int& setting = (*this->ArraySettings)[i-this->ArrayNames->begin()];
    if(!setting)
      {
      setting = 1;
      this->Modified();
      }
    }
  else
    {
    this->ArrayNames->push_back(name);
    this->ArraySettings->push_back(1);
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::DisableArray(const char* name)
{
  vtkDebugMacro("Disabling array \"" << name << "\".");
  vtkstd::vector<vtkstd::string>::iterator i =
    vtkstd::find(this->ArrayNames->begin(), this->ArrayNames->end(), vtkstd::string(name));
  if(i != this->ArrayNames->end())
    {
    int& setting = (*this->ArraySettings)[i - this->ArrayNames->begin()];
    if(setting)
      {
      setting = 0;
      this->Modified();
      }
    }
  else
    {
    this->ArrayNames->push_back(name);
    this->ArraySettings->push_back(0);
    this->Modified();
    }
}

//----------------------------------------------------------------------------
int vtkDataArraySelection::ArrayIsEnabled(const char* name)
{
  // Check if there is a specific entry for this array.
  vtkstd::vector<vtkstd::string>::iterator i =
    vtkstd::find(this->ArrayNames->begin(), this->ArrayNames->end(), vtkstd::string(name));
  if(i != this->ArrayNames->end())
    {
    return (*this->ArraySettings)[i - this->ArrayNames->begin()];
    }

  // The array does not have an entry.  Assume it is disabled.
  return 0;
}

//----------------------------------------------------------------------------
int vtkDataArraySelection::ArrayExists(const char* name)
{
  // Check if there is a specific entry for this array.
  vtkstd::vector<vtkstd::string>::iterator i =
    vtkstd::find(this->ArrayNames->begin(), this->ArrayNames->end(), vtkstd::string(name));
  return i != this->ArrayNames->end();
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::EnableAllArrays()
{
  vtkDebugMacro("Enabling all arrays.");
  int modified = 0;
  for(vtkstd::vector<int>::iterator i = this->ArraySettings->begin();
      i != this->ArraySettings->end(); ++i)
    {
    if(!*i)
      {
      *i = 1;
      modified = 1;
      }
    }
  if(modified)
    {
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::DisableAllArrays()
{
  vtkDebugMacro("Disabling all arrays.");
  int modified = 0;
  for(vtkstd::vector<int>::iterator i = this->ArraySettings->begin();
      i != this->ArraySettings->end(); ++i)
    {
    if(*i)
      {
      *i = 0;
      modified = 1;
      }
    }
  if(modified)
    {
    this->Modified();
    }
}

//----------------------------------------------------------------------------
int vtkDataArraySelection::GetNumberOfArrays()
{
  return static_cast<int>(this->ArrayNames->size());
}

//----------------------------------------------------------------------------
const char* vtkDataArraySelection::GetArrayName(int index)
{
  vtkstd::vector<vtkstd::string>::iterator i = this->ArrayNames->begin()+index;
  if(i >= this->ArrayNames->begin() && i < this->ArrayNames->end())
    {
    return i->c_str();
    }
  return 0;
}

//----------------------------------------------------------------------------
int vtkDataArraySelection::GetArraySetting(int index)
{
  vtkstd::vector<int>::iterator i = this->ArraySettings->begin()+index;
  if(i >= this->ArraySettings->begin() && i < this->ArraySettings->end())
    {
    return *i;
    }
  return 0;
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::RemoveAllArrays()
{
  vtkDebugMacro("Removing all arrays.");
  if(this->GetNumberOfArrays() > 0)
    {
    this->ArrayNames->erase(this->ArrayNames->begin(),
                            this->ArrayNames->end());
    this->ArraySettings->erase(this->ArraySettings->begin(),
                               this->ArraySettings->end());
    this->Modified();
    }
}

//----------------------------------------------------------------------------
int vtkDataArraySelection::AddArray(const char* name)
{
  vtkDebugMacro("Adding array \"" << name << "\".");

  // This function is called only by the filter owning the selection.
  // It should not call Modified() because array settings are not
  // changed.
  if(this->ArrayExists(name))
    {
    return 0;
    }
  this->ArrayNames->push_back(name);
  this->ArraySettings->push_back(1);
  return 1;
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::SetArrays(const char* const* names, int numArrays)
{
  this->SetArraysWithDefault(names, numArrays, 1);
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::SetArraysWithDefault(const char* const* names,
                                                 int numArrays,
                                                 int defaultStatus)
{
  // This function is called only by the filter owning the selection.
  // It should not call Modified() because array settings are not
  // changed.

  vtkDebugMacro("Settings arrays to given list of " << numArrays
                << " arrays.");

  // Create a new map for this set of arrays.
  vtkDataArraySelectionArrayNamesType* newNames =
    new vtkDataArraySelectionArrayNamesType;
  vtkDataArraySelectionArraySettingsType* newSettings =
    new vtkDataArraySelectionArraySettingsType;

  newNames->reserve(numArrays);
  newSettings->reserve(numArrays);

  // Fill with settings for all arrays.
  int i;
  for(i=0;i < numArrays; ++i)
    {
    // Add this array.
    newNames->push_back(names[i]);

    // Fill in the setting.  Use the old value if available.
    // Otherwise, default to on.
    vtkstd::vector<vtkstd::string>::iterator it =
      vtkstd::find(this->ArrayNames->begin(), this->ArrayNames->end(),
                   vtkstd::string(names[i]));
    int setting = defaultStatus?1:0;
    if(it != this->ArrayNames->end())
      {
      setting = (*this->ArraySettings)[it - this->ArrayNames->begin()];
      }
    newSettings->push_back(setting);
    }

  // Delete the old map and save the new one.
  delete this->ArrayNames;
  delete this->ArraySettings;
  this->ArrayNames = newNames;
  this->ArraySettings = newSettings;
}

//----------------------------------------------------------------------------
void vtkDataArraySelection::CopySelections(vtkDataArraySelection* selections)
{
  if(this == selections)
    {
    return;
    }

  int needUpdate = 0;
  int i;
  const char* arrayName;
  if (this->GetNumberOfArrays() != selections->GetNumberOfArrays())
    {
    needUpdate = 1;
    }
  else
    {
    for (i = 0; i < this->GetNumberOfArrays(); i++)
      {
      arrayName = this->GetArrayName(i);
      if (!selections->ArrayExists(arrayName))
        {
        needUpdate = 1;
        break;
        }
      if (selections->ArrayIsEnabled(arrayName) !=
          this->ArrayIsEnabled(arrayName))
        {
        needUpdate = 1;
        break;
        }
      }
    }

  if (!needUpdate)
    {
    return;
    }

  vtkDebugMacro("Copying arrays and settings from " << selections << ".");

  this->RemoveAllArrays();

  this->ArrayNames->insert(this->ArrayNames->begin(),
                           selections->ArrayNames->begin(),
                           selections->ArrayNames->end());
  this->ArraySettings->insert(this->ArraySettings->begin(),
                              selections->ArraySettings->begin(),
                              selections->ArraySettings->end());
  this->Modified();
}
<|endoftext|>


<commit_before><commit_msg>Trying a new way of freeing the memory for the CLN objects.<commit_after><|endoftext|>


<commit_before><commit_msg>RCORE: runtime_entropy: move arc4random seeding here<commit_after><|endoftext|>


<commit_before>/*
 * opencog/atomspace/TruthValue.cc
 *
 * Copyright (C) 2002-2007 Novamente LLC
 * All Rights Reserved
 *
 * Written by Welter Silva <welter@vettalabs.com>
 *            Guilherme Lamacie
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <typeinfo>

#include <stdio.h>
#include <stdlib.h>

#include <opencog/atomspace/ClassServer.h>
#include <opencog/truthvalue/CountTruthValue.h>
#include <opencog/truthvalue/IndefiniteTruthValue.h>
#include <opencog/truthvalue/NullTruthValue.h>
#include <opencog/truthvalue/SimpleTruthValue.h>
#include <opencog/truthvalue/TruthValue.h>
#include <opencog/util/platform.h>

//#define DPRINTF printf
#define DPRINTF(...)

using namespace opencog;

const strength_t MAX_TRUTH  = 1.0f;
count_t TruthValue::DEFAULT_K = 800.0;

TruthValuePtr TruthValue::NULL_TV()
{
    static TruthValuePtr instance(std::make_shared<NullTruthValue>());
    return instance;
}

TruthValuePtr TruthValue::DEFAULT_TV()
{
    // True, but no confidence.
    static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(MAX_TRUTH, 0.0));
    return instance;
}

TruthValuePtr TruthValue::TRUE_TV()
{
    // True, with maximum confidence.
    static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(MAX_TRUTH, 1.0e35));
    return instance;
}

TruthValuePtr TruthValue::FALSE_TV()
{
    // False, with maximum confidence.
    static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(0.0f, 1.0e35));
    return instance;
}

TruthValuePtr TruthValue::TRIVIAL_TV()
{
    // False, with no confidence.
    static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(0.0, 0.0));
    return instance;
}

bool TruthValue::isNullTv() const
{
    return false;
}

bool TruthValue::isDefaultTV() const
{
    TruthValuePtr dtv = DEFAULT_TV();
    if (dtv.get() == this) return true;
    if (getType() == dtv->getType() and
        getMean() == dtv->getMean() and
        getCount() == dtv->getCount())
    {
        return true;
    }
    return false;
}

/**
 * Return true if the TV value is one of the pre-defined TV values.
 */
bool TruthValue::isDefinedTV() const
{
    TruthValuePtr dtv = DEFAULT_TV();
    if (dtv.get() == this) return true;
    if (getType() == dtv->getType() and
        getMean() == dtv->getMean() and
        getCount() == dtv->getCount())
    {
        return true;
    }

    dtv = TRUE_TV();
    if (dtv.get() == this) return true;

    dtv = FALSE_TV();
    if (dtv.get() == this) return true;

    dtv = TRIVIAL_TV();
    if (dtv.get() == this) return true;

    dtv = TRUE_TV();
    if (getType() == dtv->getType() and
        getMean() == dtv->getMean() and
        getCount() == dtv->getCount())
    {
        return true;
    }

    dtv = FALSE_TV();
    if (getType() == dtv->getType() and
        getMean() == dtv->getMean() and
        getCount() == dtv->getCount())
    {
        return true;
    }

    dtv = TRIVIAL_TV();
    if (getType() == dtv->getType() and
        getMean() == dtv->getMean() and
        getCount() == dtv->getCount())
    {
        return true;
    }
    return false;
}

TruthValuePtr TruthValue::higher_confidence_merge(TruthValuePtr other) const
{
    if (other->getConfidence() > getConfidence()) {
        return other->clone();
    }
    return clone();
}
<commit_msg>Fix https://github.com/opencog/opencog/issues/1962<commit_after>/*
 * opencog/atomspace/TruthValue.cc
 *
 * Copyright (C) 2002-2007 Novamente LLC
 * All Rights Reserved
 *
 * Written by Welter Silva <welter@vettalabs.com>
 *            Guilherme Lamacie
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <typeinfo>

#include <stdio.h>
#include <stdlib.h>

#include <opencog/truthvalue/CountTruthValue.h>
#include <opencog/truthvalue/IndefiniteTruthValue.h>
#include <opencog/truthvalue/NullTruthValue.h>
#include <opencog/truthvalue/SimpleTruthValue.h>
#include <opencog/truthvalue/TruthValue.h>
#include <opencog/util/platform.h>

//#define DPRINTF printf
#define DPRINTF(...)

using namespace opencog;

const strength_t MAX_TRUTH  = 1.0f;
count_t TruthValue::DEFAULT_K = 800.0;

TruthValuePtr TruthValue::NULL_TV()
{
    static TruthValuePtr instance(std::make_shared<NullTruthValue>());
    return instance;
}

TruthValuePtr TruthValue::DEFAULT_TV()
{
    // True, but no confidence.
    static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(MAX_TRUTH, 0.0));
    return instance;
}

TruthValuePtr TruthValue::TRUE_TV()
{
    // True, with maximum confidence.
    static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(MAX_TRUTH, 1.0e35));
    return instance;
}

TruthValuePtr TruthValue::FALSE_TV()
{
    // False, with maximum confidence.
    static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(0.0f, 1.0e35));
    return instance;
}

TruthValuePtr TruthValue::TRIVIAL_TV()
{
    // False, with no confidence.
    static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(0.0, 0.0));
    return instance;
}

bool TruthValue::isNullTv() const
{
    return false;
}

bool TruthValue::isDefaultTV() const
{
    TruthValuePtr dtv = DEFAULT_TV();
    if (dtv.get() == this) return true;
    if (getType() == dtv->getType() and
        getMean() == dtv->getMean() and
        getCount() == dtv->getCount())
    {
        return true;
    }
    return false;
}

/**
 * Return true if the TV value is one of the pre-defined TV values.
 */
bool TruthValue::isDefinedTV() const
{
    TruthValuePtr dtv = DEFAULT_TV();
    if (dtv.get() == this) return true;
    if (getType() == dtv->getType() and
        getMean() == dtv->getMean() and
        getCount() == dtv->getCount())
    {
        return true;
    }

    dtv = TRUE_TV();
    if (dtv.get() == this) return true;

    dtv = FALSE_TV();
    if (dtv.get() == this) return true;

    dtv = TRIVIAL_TV();
    if (dtv.get() == this) return true;

    dtv = TRUE_TV();
    if (getType() == dtv->getType() and
        getMean() == dtv->getMean() and
        getCount() == dtv->getCount())
    {
        return true;
    }

    dtv = FALSE_TV();
    if (getType() == dtv->getType() and
        getMean() == dtv->getMean() and
        getCount() == dtv->getCount())
    {
        return true;
    }

    dtv = TRIVIAL_TV();
    if (getType() == dtv->getType() and
        getMean() == dtv->getMean() and
        getCount() == dtv->getCount())
    {
        return true;
    }
    return false;
}

TruthValuePtr TruthValue::higher_confidence_merge(TruthValuePtr other) const
{
    if (other->getConfidence() > getConfidence()) {
        return other->clone();
    }
    return clone();
}
<|endoftext|>


<commit_before>#include <iostream>
#include "Ising_simulator.hpp"
#include "spin.hpp"
#include "Ising_simulator_traits.hpp"

using numerical_type = Default_simulator_traits::numerical_type;
constexpr std::size_t system_row_num, system_column_num, total_step;
constexpr int random_seed;
constexpr numerical_type tempreture, magnetic_flux_density, spin_interaction;

row_Num			= 1000;
column_Num		= 1000;
total_step		= 10000;
random_seed		= 53;
tempreture		= 1;
magnetic_flux_density	= 1;
spin_interaction	= 1;

int main(){

    Ising_simulator<
	Neuman_flip_spin, system_row_num, system_column_num, Default_simulator_traits>
	simulator(random_seed);
    simulator.set_neuman_spin_system(
	tempreture, magnetic_flux_density, spin_interaction);

    for(std::size_t step = 0; step < total_step; ++step){
	simulator.step();
	    }

    return 0;

}
<commit_msg>edit constexpression variable.<commit_after>#include <iostream>
#include "Ising_simulator.hpp"
#include "spin.hpp"
#include "Ising_simulator_traits.hpp"

using numerical_type = Default_simulator_traits::numerical_type;
constexpr std::size_t system_row_num(1000);
constexpr std::size_t system_column_num(1000);
constexpr std::size_t total_step(10000);
constexpr int random_seed(53);
constexpr numerical_type tempreture(1);
constexpr numerical_type magnetic_flux_density(1);
constexpr numerical_type spin_interaction(1);

int main(){

    Ising_simulator<
	Neuman_flip_spin, system_row_num, system_column_num, Default_simulator_traits>
	simulator(random_seed, tempreture, magnetic_flux_density, spin_interaction);

    // for(std::size_t step = 0; step < total_step; ++step){
    // 	std::cout << step << std::endl;
    // 	simulator.step();
    // }
    return 0;
}
<|endoftext|>


<commit_before>// $Header$

// Functions to read data from HOMER.
//
// Setup: edit location of HLT configuration in first line of
// homer_display(). This is a temporary solution.
//
// Run as: alieve command_queue.C+ hlt_structs.C+ homer_display.C
//
// nextEvent() will get next event from HOMER.

#include "TTimer.h"
#include "TGLViewer.h"
#include "TTimer.h"
#include "TRandom.h"
#include "TVirtualPad.h"
//#include "AliEVEHOMERManager.h"

class AliRawReaderMemory;

namespace Reve {
class PointSet;
class TrackList;
class Track;
}

namespace Alieve {
class TPCLoader;
class TPCData;
class TPCSector2D;
class TPCSector3D;

class AliEVEHOMERManager;
class AliHLTHOMERBlockDesc;
}

using namespace Reve;
using namespace Alieve;

TPCLoader*  loader  = 0;
TPCData*    tpcdata = 0;
PointSet*   tpc_cls = 0;
TrackList*  tpc_trk = 0;

AliRawReaderMemory* memreader = 0;
AliEVEHOMERManager* homerM = 0;

Int_t    event  = -1;

TTimer   timer;
TTimer   event_timer;

TThread* ldthread = 0;

TRandom  rnd(0);

TGLViewer::ECameraType camera = TGLViewer::kCameraPerspXOZ;

//****************************************************************************
void nextEvent();

//****************************************************************************
void process_tpc_clusters(AliHLTHOMERBlockDesc* b);

//****************************************************************************
void homer_display()
{
  homerM = new AliEVEHOMERManager("/local/home/hlt/TPC-SCC1-Generate.xml");
  //  homerM = new AliEVEHOMERManager("/local/home/hlt/sampleConfig2.xml");

  gReve->AddToListTree(homerM, kTRUE);

  homerM->CreateHOMERSourcesList();
  //  homerM->SelectRawTPC();
  homerM->SelectClusterTPC();
  homerM->SelectESDTPC();
  homerM->ConnectHOMER();

  memreader = new AliRawReaderMemory(0, 0);
  gStyle->SetPalette(1, 0);

  loader = new TPCLoader;
  loader->SetDoubleSR(kTRUE);
  loader->SetInitParams(40, 900, 10, 100); // Sector params (mint, maxt, thr, maxval)
  //loader->SetInitParams(40, 1023, 10); // Sector params (mint, maxt, thr)
  tpcdata = loader->GetData();
  tpcdata->SetLoadPedestal(0);
  tpcdata->SetLoadThreshold(0);
  // tpcdata->SetAutoPedestal(kTRUE); // For non-zero suppressed data.
  tpcdata->SetAutoPedestal(kFALSE);
  gReve->AddRenderElement(loader);

  tpc_cls = new Reve::PointSet("TPC Clusters");
  tpc_cls->SetMainColor((Color_t)kRed);
  gReve->AddRenderElement(tpc_cls);

  tpc_trk = new TrackList("TPC Tracks");
  gReve->AddRenderElement(tpc_trk);
  tpc_trk->SetMainColor(Color_t(6));
  Reve::TrackRnrStyle* rnrStyle = tpc_trk->GetRnrStyle();
  rnrStyle->SetMagField( 5 );

  nextEvent();
}

//****************************************************************************
void nextEvent()
{
  tpcdata->DropAllSectors();
  tpc_cls->Reset();
  tpc_trk->DestroyElements();

  homerM->NextEvent();
  TIter next(homerM->GetBlockList());
  AliHLTHOMERBlockDesc* b = 0;
  while ((b = (AliHLTHOMERBlockDesc*)next())) {

    //    printf("Q - %s\n", b->GetDataType().Data());

    if (b->GetDataType().CompareTo("CLUSTERS") == 0) {
      process_tpc_clusters(b);
      tpc_cls->ElementChanged();
    }

    else if (b->GetDataType().CompareTo("DDL_RAW") == 0) {
      Int_t slice = b->GetSubDetector().Atoi();
      Int_t patch = b->GetSubSubDetector().Atoi();
      Int_t eqid = 768 + patch;
      if (patch >= 2)
	eqid += 4*slice + 70;
      else
	eqid += 2*slice;

      //printf("%d %d %d -- %p %d\n", slice, patch, eqid, b->GetData(), b->GetSize());

      memreader->SetMemory(b->GetData(), b->GetSize());
      memreader->SetEquipmentID(eqid);
      memreader->Reset();

      AliTPCRawStream input(memreader);
      input.SetOldRCUFormat(kTRUE);
      //input.SetOldRCUFormat(kFALSE);
      memreader->Select("TPC"); // ("TPC", firstRCU, lastRCU);
      tpcdata->LoadRaw(input, kTRUE, kTRUE);
    }
  }

  loader->UpdateSectors(kTRUE); // true -> delete non present
  tpc_cls->ResetBBox();
  tpc_trk->MakeTracks();

  gReve->Redraw3D(1, 1);
}

//****************************************************************************
void process_tpc_clusters(AliHLTHOMERBlockDesc* b)
{
  AliHLTTPCClusterData    *cd = (AliHLTTPCClusterData*) b->GetData();
  UChar_t *data = (UChar_t*) cd->fSpacePoints;

  //  printf("XXX %p %d; sizeof=%d, calcsize=%d\n", b->GetData(), cd->fSpacePointCnt,
  //	 sizeof(AliHLTTPCSpacePointData), (b->GetSize() - 4)/cd->fSpacePointCnt);

  Int_t   slice = b->GetSubDetector().Atoi();
  Float_t phi = (slice+0.5)*TMath::Pi()/9.0;
  Float_t cos = TMath::Cos(phi);
  Float_t sin = TMath::Sin(phi);

  for (Int_t i = 0; i < cd->fSpacePointCnt; ++i, data += sizeof(AliHLTTPCSpacePointData)) {
    AliHLTTPCSpacePointData *sp = (AliHLTTPCSpacePointData *) data;
    //if (i % 100 == 0)
    //printf("  %4d  %6.2f, %6.2f, %6.2f\n", i, sp->fX, sp->fY, sp->fZ);
    tpc_cls->SetNextPoint(cos*sp->fX - sin*sp->fY,
			  sin*sp->fX + cos*sp->fY,
			  sp->fZ);
  }
}

//****************************************************************************
Reve::Track* esd_make_track(Reve::TrackRnrStyle*   rnrStyle,
			    Int_t                  index,
			    AliESDtrack*           at,
			    AliExternalTrackParam* tp=0)
{
  // Helper function
  Double_t        pbuf[3], vbuf[3];
  Reve::RecTrack  rt;

  if(tp == 0) tp = at;

  rt.label  = at->GetLabel();
  rt.index  = index;
  rt.status = (Int_t) at->GetStatus();
  rt.sign   = tp->GetSign();
  tp->GetXYZ(vbuf);
  rt.V.Set(vbuf);
  tp->GetPxPyPz(pbuf);
  rt.P.Set(pbuf);
  Double_t ep = at->GetP(), mc = at->GetMass();
  rt.beta = ep/TMath::Sqrt(ep*ep + mc*mc);

  Reve::Track* track = new Reve::Track(&rt, rnrStyle);
  //PH The line below is replaced waiting for a fix in Root
  //PH which permits to use variable siza arguments in CINT
  //PH on some platforms (alphalinuxgcc, solariscc5, etc.)
  //PH  track->SetName(Form("ESDTrack %d", rt.label));
  //PH  track->SetTitle(Form("pT=%.3f, pZ=%.3f; V=(%.3f, %.3f, %.3f)",
  //PH		       rt.sign*TMath::Hypot(rt.P.x, rt.P.y), rt.P.z,
  //PH		       rt.V.x, rt.V.y, rt.V.z));
  char form[1000];
  sprintf(form,"Track %d", rt.index);
  track->SetName(form);
  track->SetStdTitle();
  return track;
}

//****************************************************************************
void process_tpc_tracks(AliHLTHOMERBlockDesc* b)
{
  AliESDEvent* esd = (AliESDEvent*) b->GetTObject();

  Reve::TrackRnrStyle* rnrStyle = tpc_trk->GetRnrStyle();

  for (Int_t n=0; n<esd->GetNumberOfTracks(); n++)
  {
    AliESDtrack           *at = esd->GetTrack(n);
    AliExternalTrackParam *tp = at;

    Reve::Track* track = esd_make_track(rnrStyle, n, at, tp);
    track->SetAttLineAttMarker(tpc_trk);
    gReve->AddRenderElement(track, tpc_trk);
  }

}

//****************************************************************************
void process_tpc_xxxx(AliESDEvent* esd)
{
  Reve::TrackRnrStyle* rnrStyle = tpc_trk->GetRnrStyle();

  for (Int_t n=0; n<esd->GetNumberOfTracks(); n++)
  {
    AliESDtrack           *at = esd->GetTrack(n);
    AliExternalTrackParam *tp = at;

    Reve::Track* track = esd_make_track(rnrStyle, n, at, tp);
    track->SetAttLineAttMarker(tpc_trk);
    gReve->AddRenderElement(track, tpc_trk);
  }

}

//****************************************************************************
/*
  // Getting esd

f=TFile::Open("AliESDs.root")
AliESDEvent * esd = new AliESDEvent
esd->ReadFromTree(esdTree)
esdTree->GetEntry(0)
esd->GetNumberOfTracks()
///////////////////

root [3] AliESDEvent * esd = new AliESDEvent
root [4] esd->ReadFromTree(esdTree)
W-TStreamerInfo::BuildOld: Cannot convert AliESDCaloCluster::fTracksMatched from type:TArrayS* to type:TArrayI, skip element
W-TStreamerInfo::BuildOld: Cannot convert AliESDCaloCluster::fLabels from type:TArrayS* to type:TArrayI, skip element
STEER/AliESDEvent.cxx 1040 AliESDEvent::ReadFromTree() TList contains less than the standard contents 21 < 22
root [5] esdTree->GetEntry(0)
(Int_t)(764314)
root [6] esd->GetNumberOfTracks()
(const Int_t)(275)
root [7] process_tpc_xxxx(esd)
root [8] gReve->Redraw3D(
void Redraw3D(Bool_t resetCameras = kFALSE, Bool_t dropLogicals = kFALSE)
root [8] gReve->Redraw3D(1,1)
root [9] trk_cnt->Elem
variable "trk_cnt" not defined.

variable "trk_cnt->Elem" not defined.
root [9] trk_cnt->Eleme
variable "trk_cnt" not defined.

variable "trk_cnt->Eleme" not defined.
root [9] tpc_trk->ElementChanged(
void ElementChanged(Bool_t update_scenes = kTRUE, Bool_t redraw = kFALSE)
root [9] tpc_trk->ElementChanged(1,1)
root [10] tpc_trk->SelectByP
SelectByPt
SelectByPt
SelectByP
SelectByP
root [10] tpc_trk->SelectByPt(
void SelectByPt(Float_t min_pt, Float_t max_pt)
void SelectByPt(Float_t min_pt, Float_t max_pt, Reve::RenderElement* el)
root [10] tpc_trk->SelectByPt(0,1000000000000)
root [11] tpc_trk->MakeTracks(
void MakeTracks(Bool_t recurse = kTRUE)
root [11] tpc_trk->MakeTracks()
root [12]

*/

//****************************************************************************
void loopEvent()
{
  event_timer.SetCommand("nextEvent()");
  event_timer.Start(60);
}

//****************************************************************************
void stopLoopEvent()
{
  event_timer.Stop();
}
<commit_msg>Move class fws decls to proper namespace.<commit_after>// $Header$

// Functions to read data from HOMER.
//
// Setup: edit location of HLT configuration in first line of
// homer_display(). This is a temporary solution.
//
// Run as: alieve command_queue.C+ hlt_structs.C+ homer_display.C
//
// nextEvent() will get next event from HOMER.

#include "TTimer.h"
#include "TGLViewer.h"
#include "TTimer.h"
#include "TRandom.h"
#include "TVirtualPad.h"
//#include "AliEVEHOMERManager.h"

class AliRawReaderMemory;

class AliEVEHOMERManager;
class AliHLTHOMERBlockDesc;

namespace Reve {
class PointSet;
class TrackList;
class Track;
}

namespace Alieve {
class TPCLoader;
class TPCData;
class TPCSector2D;
class TPCSector3D;
}

using namespace Reve;
using namespace Alieve;

TPCLoader*  loader  = 0;
TPCData*    tpcdata = 0;
PointSet*   tpc_cls = 0;
TrackList*  tpc_trk = 0;

AliRawReaderMemory* memreader = 0;
AliEVEHOMERManager* homerM = 0;

Int_t    event  = -1;

TTimer   timer;
TTimer   event_timer;

TThread* ldthread = 0;

TRandom  rnd(0);

TGLViewer::ECameraType camera = TGLViewer::kCameraPerspXOZ;

//****************************************************************************
void nextEvent();

//****************************************************************************
void process_tpc_clusters(AliHLTHOMERBlockDesc* b);

//****************************************************************************
void homer_display()
{
  homerM = new AliEVEHOMERManager("/local/home/hlt/TPC-SCC1-Generate.xml");
  //  homerM = new AliEVEHOMERManager("/local/home/hlt/sampleConfig2.xml");

  gReve->AddToListTree(homerM, kTRUE);

  homerM->CreateHOMERSourcesList();
  //  homerM->SelectRawTPC();
  homerM->SelectClusterTPC();
  homerM->SelectESDTPC();
  homerM->ConnectHOMER();

  memreader = new AliRawReaderMemory(0, 0);
  gStyle->SetPalette(1, 0);

  loader = new TPCLoader;
  loader->SetDoubleSR(kTRUE);
  loader->SetInitParams(40, 900, 10, 100); // Sector params (mint, maxt, thr, maxval)
  //loader->SetInitParams(40, 1023, 10); // Sector params (mint, maxt, thr)
  tpcdata = loader->GetData();
  tpcdata->SetLoadPedestal(0);
  tpcdata->SetLoadThreshold(0);
  // tpcdata->SetAutoPedestal(kTRUE); // For non-zero suppressed data.
  tpcdata->SetAutoPedestal(kFALSE);
  gReve->AddRenderElement(loader);

  tpc_cls = new Reve::PointSet("TPC Clusters");
  tpc_cls->SetMainColor((Color_t)kRed);
  gReve->AddRenderElement(tpc_cls);

  tpc_trk = new TrackList("TPC Tracks");
  gReve->AddRenderElement(tpc_trk);
  tpc_trk->SetMainColor(Color_t(6));
  Reve::TrackRnrStyle* rnrStyle = tpc_trk->GetRnrStyle();
  rnrStyle->SetMagField( 5 );

  nextEvent();
}

//****************************************************************************
void nextEvent()
{
  tpcdata->DropAllSectors();
  tpc_cls->Reset();
  tpc_trk->DestroyElements();

  homerM->NextEvent();
  TIter next(homerM->GetBlockList());
  AliHLTHOMERBlockDesc* b = 0;
  while ((b = (AliHLTHOMERBlockDesc*)next())) {

    //    printf("Q - %s\n", b->GetDataType().Data());

    if (b->GetDataType().CompareTo("CLUSTERS") == 0) {
      process_tpc_clusters(b);
      tpc_cls->ElementChanged();
    }

    else if (b->GetDataType().CompareTo("DDL_RAW") == 0) {
      Int_t slice = b->GetSubDetector().Atoi();
      Int_t patch = b->GetSubSubDetector().Atoi();
      Int_t eqid = 768 + patch;
      if (patch >= 2)
	eqid += 4*slice + 70;
      else
	eqid += 2*slice;

      //printf("%d %d %d -- %p %d\n", slice, patch, eqid, b->GetData(), b->GetSize());

      memreader->SetMemory(b->GetData(), b->GetSize());
      memreader->SetEquipmentID(eqid);
      memreader->Reset();

      AliTPCRawStream input(memreader);
      input.SetOldRCUFormat(kTRUE);
      //input.SetOldRCUFormat(kFALSE);
      memreader->Select("TPC"); // ("TPC", firstRCU, lastRCU);
      tpcdata->LoadRaw(input, kTRUE, kTRUE);
    }
  }

  loader->UpdateSectors(kTRUE); // true -> delete non present
  tpc_cls->ResetBBox();
  tpc_trk->MakeTracks();

  gReve->Redraw3D(1, 1);
}

//****************************************************************************
void process_tpc_clusters(AliHLTHOMERBlockDesc* b)
{
  AliHLTTPCClusterData    *cd = (AliHLTTPCClusterData*) b->GetData();
  UChar_t *data = (UChar_t*) cd->fSpacePoints;

  //  printf("XXX %p %d; sizeof=%d, calcsize=%d\n", b->GetData(), cd->fSpacePointCnt,
  //	 sizeof(AliHLTTPCSpacePointData), (b->GetSize() - 4)/cd->fSpacePointCnt);

  Int_t   slice = b->GetSubDetector().Atoi();
  Float_t phi = (slice+0.5)*TMath::Pi()/9.0;
  Float_t cos = TMath::Cos(phi);
  Float_t sin = TMath::Sin(phi);

  for (Int_t i = 0; i < cd->fSpacePointCnt; ++i, data += sizeof(AliHLTTPCSpacePointData)) {
    AliHLTTPCSpacePointData *sp = (AliHLTTPCSpacePointData *) data;
    //if (i % 100 == 0)
    //printf("  %4d  %6.2f, %6.2f, %6.2f\n", i, sp->fX, sp->fY, sp->fZ);
    tpc_cls->SetNextPoint(cos*sp->fX - sin*sp->fY,
			  sin*sp->fX + cos*sp->fY,
			  sp->fZ);
  }
}

//****************************************************************************
Reve::Track* esd_make_track(Reve::TrackRnrStyle*   rnrStyle,
			    Int_t                  index,
			    AliESDtrack*           at,
			    AliExternalTrackParam* tp=0)
{
  // Helper function
  Double_t        pbuf[3], vbuf[3];
  Reve::RecTrack  rt;

  if(tp == 0) tp = at;

  rt.label  = at->GetLabel();
  rt.index  = index;
  rt.status = (Int_t) at->GetStatus();
  rt.sign   = tp->GetSign();
  tp->GetXYZ(vbuf);
  rt.V.Set(vbuf);
  tp->GetPxPyPz(pbuf);
  rt.P.Set(pbuf);
  Double_t ep = at->GetP(), mc = at->GetMass();
  rt.beta = ep/TMath::Sqrt(ep*ep + mc*mc);

  Reve::Track* track = new Reve::Track(&rt, rnrStyle);
  //PH The line below is replaced waiting for a fix in Root
  //PH which permits to use variable siza arguments in CINT
  //PH on some platforms (alphalinuxgcc, solariscc5, etc.)
  //PH  track->SetName(Form("ESDTrack %d", rt.label));
  //PH  track->SetTitle(Form("pT=%.3f, pZ=%.3f; V=(%.3f, %.3f, %.3f)",
  //PH		       rt.sign*TMath::Hypot(rt.P.x, rt.P.y), rt.P.z,
  //PH		       rt.V.x, rt.V.y, rt.V.z));
  char form[1000];
  sprintf(form,"Track %d", rt.index);
  track->SetName(form);
  track->SetStdTitle();
  return track;
}

//****************************************************************************
void process_tpc_tracks(AliHLTHOMERBlockDesc* b)
{
  AliESDEvent* esd = (AliESDEvent*) b->GetTObject();

  Reve::TrackRnrStyle* rnrStyle = tpc_trk->GetRnrStyle();

  for (Int_t n=0; n<esd->GetNumberOfTracks(); n++)
  {
    AliESDtrack           *at = esd->GetTrack(n);
    AliExternalTrackParam *tp = at;

    Reve::Track* track = esd_make_track(rnrStyle, n, at, tp);
    track->SetAttLineAttMarker(tpc_trk);
    gReve->AddRenderElement(track, tpc_trk);
  }

}

//****************************************************************************
void process_tpc_xxxx(AliESDEvent* esd)
{
  Reve::TrackRnrStyle* rnrStyle = tpc_trk->GetRnrStyle();

  for (Int_t n=0; n<esd->GetNumberOfTracks(); n++)
  {
    AliESDtrack           *at = esd->GetTrack(n);
    AliExternalTrackParam *tp = at;

    Reve::Track* track = esd_make_track(rnrStyle, n, at, tp);
    track->SetAttLineAttMarker(tpc_trk);
    gReve->AddRenderElement(track, tpc_trk);
  }

}

//****************************************************************************
/*
  // Getting esd

f=TFile::Open("AliESDs.root")
AliESDEvent * esd = new AliESDEvent
esd->ReadFromTree(esdTree)
esdTree->GetEntry(0)
esd->GetNumberOfTracks()
///////////////////

root [3] AliESDEvent * esd = new AliESDEvent
root [4] esd->ReadFromTree(esdTree)
W-TStreamerInfo::BuildOld: Cannot convert AliESDCaloCluster::fTracksMatched from type:TArrayS* to type:TArrayI, skip element
W-TStreamerInfo::BuildOld: Cannot convert AliESDCaloCluster::fLabels from type:TArrayS* to type:TArrayI, skip element
STEER/AliESDEvent.cxx 1040 AliESDEvent::ReadFromTree() TList contains less than the standard contents 21 < 22
root [5] esdTree->GetEntry(0)
(Int_t)(764314)
root [6] esd->GetNumberOfTracks()
(const Int_t)(275)
root [7] process_tpc_xxxx(esd)
root [8] gReve->Redraw3D(
void Redraw3D(Bool_t resetCameras = kFALSE, Bool_t dropLogicals = kFALSE)
root [8] gReve->Redraw3D(1,1)
root [9] trk_cnt->Elem
variable "trk_cnt" not defined.

variable "trk_cnt->Elem" not defined.
root [9] trk_cnt->Eleme
variable "trk_cnt" not defined.

variable "trk_cnt->Eleme" not defined.
root [9] tpc_trk->ElementChanged(
void ElementChanged(Bool_t update_scenes = kTRUE, Bool_t redraw = kFALSE)
root [9] tpc_trk->ElementChanged(1,1)
root [10] tpc_trk->SelectByP
SelectByPt
SelectByPt
SelectByP
SelectByP
root [10] tpc_trk->SelectByPt(
void SelectByPt(Float_t min_pt, Float_t max_pt)
void SelectByPt(Float_t min_pt, Float_t max_pt, Reve::RenderElement* el)
root [10] tpc_trk->SelectByPt(0,1000000000000)
root [11] tpc_trk->MakeTracks(
void MakeTracks(Bool_t recurse = kTRUE)
root [11] tpc_trk->MakeTracks()
root [12]

*/

//****************************************************************************
void loopEvent()
{
  event_timer.SetCommand("nextEvent()");
  event_timer.Start(60);
}

//****************************************************************************
void stopLoopEvent()
{
  event_timer.Stop();
}
<|endoftext|>


<commit_before>//******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#include "ResourceClient.h"
#include "ResourceBroker.h"
#include "ResourceCacheManager.h"

#define CLIENT_W_TAG  PCF("ResourceClient")

using namespace OIC::Service;

namespace
{
    ResourceState getResourceStateFromBrokerState(BROKER_STATE state)
    {

        OC_LOG(DEBUG, CLIENT_W_TAG, "getResourceStateFromBrokerState entry");

        if (state == BROKER_STATE::ALIVE)
        {
            return ResourceState::ALIVE;
        }
        else if (state == BROKER_STATE::REQUESTED)
        {
            return ResourceState::REQUESTED;
        }
        else if (state == BROKER_STATE::LOST_SIGNAL)
        {
            return ResourceState::LOST_SIGNAL;
        }
        else if (state == BROKER_STATE::DESTROYED)
        {
            return ResourceState::DESTROYED;
        }
        else if (state == BROKER_STATE::NONE)
        {
            return ResourceState::NOT_MONITORING;
        }
        OC_LOG(ERROR, CLIENT_W_TAG, "getResourceStateFromBrokerState ERROR");

        //Default return value
        return ResourceState::NOT_MONITORING;
    }

    CacheState getCacheState(CACHE_STATE state)
    {

        OC_LOG(DEBUG, CLIENT_W_TAG, "getCacheState (from CACHE_STATE) entry");

        if (state == CACHE_STATE::READY)
        {
            return CacheState::READY;
        }
        else if (state == CACHE_STATE::READY_YET)
        {
            return CacheState::READY_YET;
        }
        else if (state == CACHE_STATE::LOST_SIGNAL)
        {
            return CacheState::LOST_SIGNAL;
        }
        else if (state == CACHE_STATE::DESTROYED)
        {
            return CacheState::DESTROYED;
        }
        else if (state == CACHE_STATE::UPDATING)
        {
            return CacheState::UPDATING;
        }
        else if (state == CACHE_STATE::NONE)
        {
            return CacheState::NONE;
        }
        OC_LOG(ERROR, CLIENT_W_TAG, "getCacheState (from CACHE_STATE) ERROR");

        //Default return value
        return CacheState::NONE;
    }

    OCStackResult hostingCallback(BROKER_STATE state,
                                  RemoteResourceObject::ResourceStateChangedCallback onResourceStateChanged)
    {
        OC_LOG(DEBUG, CLIENT_W_TAG, "hostingCallback entry");

        ResourceState resourceState = getResourceStateFromBrokerState(state);
        onResourceStateChanged(resourceState); //passing ResourceState to application

        OC_LOG(DEBUG, CLIENT_W_TAG, "hostingCallback exit");
        return OC_STACK_OK;
    }

    OCStackResult cachingCallback(std::shared_ptr<PrimitiveResource> resource,
                                  const ResourceAttributes &data,
                                  RemoteResourceObject::CacheUpdatedCallback onCacheUpdated)
    {
        OC_LOG(DEBUG, CLIENT_W_TAG, "cachingCallback entry");

        onCacheUpdated(data); //passing ResourceAttributes to application

        OC_LOG(DEBUG, CLIENT_W_TAG, "cachingCallback exit");
        return OC_STACK_OK;
    }

    void setCallback(const HeaderOptions &header, const ResponseStatement &response, int n,
                     RemoteResourceObject::RemoteAttributesSetCallback onRemoteAttributesSet)
    {
        OC_LOG(DEBUG, CLIENT_W_TAG, "setCallback entry");

        const ResourceAttributes &attributes = response.getAttributes();
        onRemoteAttributesSet(attributes); //passing ResourceAttributes to application

        OC_LOG(DEBUG, CLIENT_W_TAG, "setCallback exit");
    }

    void getCallback(const HeaderOptions &headerOption, const ResponseStatement &response, int n,
                     RemoteResourceObject::RemoteAttributesReceivedCallback onRemoteAttributesReceived)
    {
        OC_LOG(DEBUG, CLIENT_W_TAG, "getCallback entry");

        const ResourceAttributes &attributes = response.getAttributes();
        onRemoteAttributesReceived(attributes); //passing ResourceAttributes to application

        OC_LOG(DEBUG, CLIENT_W_TAG, "getCallback exit");
    }

    void findCallback(std::shared_ptr<PrimitiveResource> primitiveResource,
                      DiscoveryManager::OnResourceDiscoveredCallback OnResourceDiscovered )
    {
        OC_LOG(DEBUG, CLIENT_W_TAG, "findCallback entry");

        if (nullptr == primitiveResource)
        {
            OC_LOG(ERROR, CLIENT_W_TAG, "findCallback::primitiveResource NULL Parameter");
            return ;
        }

        std::shared_ptr< RemoteResourceObject>  primitiveClientResource =
            std::shared_ptr< RemoteResourceObject>(new RemoteResourceObject(primitiveResource));

        OnResourceDiscovered(primitiveClientResource); //passing PrimitiveClientResource to application

        OC_LOG(DEBUG, CLIENT_W_TAG, "findcb exit");
    }

}

//*******************************Primitive Client Resource*************************************

namespace OIC
{
    namespace Service
    {

        RemoteResourceObject:: RemoteResourceObject(std::shared_ptr<PrimitiveResource>  pResource) :
            m_monitoringFlag(false), m_cachingFlag(false),  m_observableFlag(pResource->isObservable()),
            m_primitiveResource(pResource), m_cacheId(0), m_brokerId(0) {}

        bool RemoteResourceObject::isMonitoring() const
        {
            return m_monitoringFlag;
        }

        bool RemoteResourceObject::isCaching() const
        {
            return m_cachingFlag;
        }

        void RemoteResourceObject::startMonitoring(ResourceStateChangedCallback cb)
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startMonitoring entry");
            if (true == m_monitoringFlag)
            {
                OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startMonitoring : Already started");
            }
            else
            {
                try
                {
                    BrokerID brokerId =  ResourceBroker::getInstance()->hostResource(m_primitiveResource,
                                         std::bind(hostingCallback, std::placeholders::_1,
                                                   cb));
                    m_monitoringFlag = true;
                    m_brokerId = brokerId;
                }
                catch (std::exception &exception)
                {
                    throw InvalidParameterException {exception.what()};
                }
            }
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startMonitoring exit");
        }

        void RemoteResourceObject::stopMonitoring()
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::stopMonitoring entry");
            if (true == m_monitoringFlag)
            {
                try
                {
                    ResourceBroker::getInstance()->cancelHostResource(m_brokerId);
                    m_monitoringFlag = false;
                }
                catch (std::exception &exception)
                {
                    OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::stopMonitoring InvalidParameterException");
                }
            }
            else
            {
                OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject:: stopMonitoring : already terminated");
            }

            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::stopMonitoring exit");
        }

        ResourceState RemoteResourceObject::getState() const
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, " RemoteResourceObject::getState entry");
            try
            {
                BROKER_STATE brokerState = ResourceBroker::getInstance()->getResourceState(m_primitiveResource);
                OC_LOG(DEBUG, CLIENT_W_TAG, " RemoteResourceObject::getState exit");
                return getResourceStateFromBrokerState(brokerState);
            }
            catch (std::exception &exception)
            {
                OC_LOG(DEBUG, CLIENT_W_TAG, " RemoteResourceObject::getState InvalidParameterException");
            }
        }

        void RemoteResourceObject::startCaching()
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching entry");
            if (true == m_cachingFlag)
            {
                OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching : already Started");
            }
            else
            {
                try
                {
                  CacheID cacheId = ResourceCacheManager::getInstance()->requestResourceCache(m_primitiveResource,
                                      NULL, REPORT_FREQUENCY::NONE,  0);

                    m_cacheId = cacheId;
                    m_cachingFlag = true;
                    OC_LOG_V(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching CACHE ID %d", cacheId);
                }
                catch (std::exception &exception)
                {
                    OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching InvalidParameterException");
                }
            }
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching exit");
        }

        void RemoteResourceObject::startCaching(CacheUpdatedCallback cb)
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching entry");
            if (true == m_cachingFlag)
            {
                OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching : already Started");
            }
            else
            {
                try
                {
                  CacheID cacheId = ResourceCacheManager::getInstance()->requestResourceCache(m_primitiveResource,
                                      std::bind(cachingCallback, std::placeholders::_1, std::placeholders::_2, cb),
                                      REPORT_FREQUENCY::UPTODATE,  0);

                    m_cacheId = cacheId;
                    m_cachingFlag = true;
                    OC_LOG_V(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching CACHE ID %d", cacheId);
                }
                catch (std::exception &exception)
                {
                    throw InvalidParameterException {"startCaching : Callback is NULL" };
                }
            }
        }

        void RemoteResourceObject::stopCaching()
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::stopCaching entry");

            if (true == m_cachingFlag)
            {
                try
                {
                    ResourceCacheManager::getInstance()->cancelResourceCache(m_cacheId);
                    m_cachingFlag = false;
                }
                catch (std::exception &exception)
                {
                    OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::stopCaching InvalidParameterException");
                }
            }
            else
            {
                OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject:: Caching already terminated");
            }

            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::stopCaching exit");
        }

        CacheState  RemoteResourceObject::getResourceCacheState()
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::getResourceCacheState entry");
            try
            {
                CACHE_STATE cacheState = ResourceCacheManager::getInstance()->getResourceCacheState(
                                             m_primitiveResource);
                OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::getResourceCacheState exit");
                return getCacheState(cacheState);
            }
            catch (std::exception &exception)
            {
                OC_LOG(DEBUG, CLIENT_W_TAG,
                       "RemoteResourceObject::getResourceCacheState InvalidParameterException");
            }
        }

        void RemoteResourceObject::refreshCache()
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::refreshCache entry");
            try
            {

                ResourceCacheManager::getInstance()->updateResourceCache(
                    m_primitiveResource);
            }
            catch (std::exception &exception)
            {
                OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::refreshCache InvalidParameterException");
            }
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::refreshCache exit");
        }

        ResourceAttributes RemoteResourceObject:: getCachedAttributes() const
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject :: getCachedAttributes ");
            try
            {
                return ResourceCacheManager::getInstance()->getCachedData(m_primitiveResource);
            }
            catch (std::exception &exception)
            {
                throw BadRequestException { "[getCachedAttributes]  Caching not started" };
            }
        }

        ResourceAttributes::Value  RemoteResourceObject:: getCachedAttribute( const std::string &key)
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject :: getCachedAttribute entry");
            try
            {
                ResourceAttributes  Cachedattributes = ResourceCacheManager::getInstance()->getCachedData(
                        m_primitiveResource);
                return Cachedattributes[key];
            }
            catch (std::exception &exception)
            {
                throw BadRequestException { "[getCachedAttribute]  Caching not started" };
            }
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject :: getCachedAttribute exit");
        }

        std::string RemoteResourceObject::getUri() const
        {
            return m_primitiveResource->getUri();
        }

        std::string RemoteResourceObject::getAddress() const
        {
            return m_primitiveResource->getHost();
        }

        std::vector < std::string > RemoteResourceObject::getTypes() const
        {
            return m_primitiveResource->getTypes();
        }

        std::vector < std::string > RemoteResourceObject::getInterfaces() const
        {
            return m_primitiveResource->getInterfaces();
        }

        void RemoteResourceObject::getRemoteAttributes(RemoteAttributesReceivedCallback cb)
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::getRemoteAttributes entry");

            m_primitiveResource->requestGet(std::bind(getCallback, std::placeholders::_1,
                                            std::placeholders::_2, std::placeholders::_3, cb));

            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::getRemoteAttributes exit");
        }

        void RemoteResourceObject::setRemoteAttributes(ResourceAttributes &attribute,
                RemoteAttributesSetCallback cb)
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::setRemoteAttributes entry");

            m_primitiveResource->requestSet(attribute, std::bind(setCallback, std::placeholders::_1,
                                            std::placeholders::_2, std::placeholders::_3, cb));

            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::setRemoteAttributes exit");
        }

        bool RemoteResourceObject::isObservable() const
        {
            return m_observableFlag;
        }

//*******************************Discovery Manager****************************************

        DiscoveryManager *DiscoveryManager:: getInstance()
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "DiscoveryManager:: getInstance entry");
            static DiscoveryManager *s_instance;
            static std::mutex s_mutex;
            if (!s_instance)
            {
                std::lock_guard<std::mutex> lock(s_mutex);
                if (!s_instance)
                {
                    s_instance = new DiscoveryManager();
                }
            }
            OC_LOG(DEBUG, CLIENT_W_TAG, "DiscoveryManager:: getInstance exit");
            return s_instance;
        }

        void DiscoveryManager::discoverResource(std::string host, std::string resourceURI,
                                                OCConnectivityType connectivityType,
                                                OnResourceDiscoveredCallback cb)
        {

            OC_LOG(DEBUG, CLIENT_W_TAG, "DiscoveryManager::discoverResource entry");

            if ( resourceURI.empty() )
            {
                OC_LOG(ERROR, CLIENT_W_TAG, "discoverResource NULL resourceURI");
                throw InvalidParameterException { "discoverResource NULL resourceURI'" };
            }
            else if ( !cb )
            {
                OC_LOG(ERROR, CLIENT_W_TAG, "discoverResource NULL Callback");
                throw InvalidParameterException { "discoverResource NULL Callback'" };
            }
            OIC::Service::discoverResource(host, resourceURI, connectivityType, std::bind(findCallback,
                                           std::placeholders::_1,
                                           cb));

            OC_LOG(DEBUG, CLIENT_W_TAG, "DiscoveryManager::discoverResource exit");
        }
    }
}
<commit_msg>Fix compiler warnings.<commit_after>//******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#include "ResourceClient.h"
#include "ResourceBroker.h"
#include "ResourceCacheManager.h"

#define CLIENT_W_TAG  PCF("ResourceClient")

using namespace OIC::Service;

namespace
{
    ResourceState getResourceStateFromBrokerState(BROKER_STATE state)
    {

        OC_LOG(DEBUG, CLIENT_W_TAG, "getResourceStateFromBrokerState entry");

        if (state == BROKER_STATE::ALIVE)
        {
            return ResourceState::ALIVE;
        }
        else if (state == BROKER_STATE::REQUESTED)
        {
            return ResourceState::REQUESTED;
        }
        else if (state == BROKER_STATE::LOST_SIGNAL)
        {
            return ResourceState::LOST_SIGNAL;
        }
        else if (state == BROKER_STATE::DESTROYED)
        {
            return ResourceState::DESTROYED;
        }
        else if (state == BROKER_STATE::NONE)
        {
            return ResourceState::NOT_MONITORING;
        }
        OC_LOG(ERROR, CLIENT_W_TAG, "getResourceStateFromBrokerState ERROR");

        //Default return value
        return ResourceState::NOT_MONITORING;
    }

    CacheState getCacheState(CACHE_STATE state)
    {

        OC_LOG(DEBUG, CLIENT_W_TAG, "getCacheState (from CACHE_STATE) entry");

        if (state == CACHE_STATE::READY)
        {
            return CacheState::READY;
        }
        else if (state == CACHE_STATE::READY_YET)
        {
            return CacheState::READY_YET;
        }
        else if (state == CACHE_STATE::LOST_SIGNAL)
        {
            return CacheState::LOST_SIGNAL;
        }
        else if (state == CACHE_STATE::DESTROYED)
        {
            return CacheState::DESTROYED;
        }
        else if (state == CACHE_STATE::UPDATING)
        {
            return CacheState::UPDATING;
        }
        else if (state == CACHE_STATE::NONE)
        {
            return CacheState::NONE;
        }
        OC_LOG(ERROR, CLIENT_W_TAG, "getCacheState (from CACHE_STATE) ERROR");

        //Default return value
        return CacheState::NONE;
    }

    OCStackResult hostingCallback(BROKER_STATE state,
                                  RemoteResourceObject::ResourceStateChangedCallback onResourceStateChanged)
    {
        OC_LOG(DEBUG, CLIENT_W_TAG, "hostingCallback entry");

        ResourceState resourceState = getResourceStateFromBrokerState(state);
        onResourceStateChanged(resourceState); //passing ResourceState to application

        OC_LOG(DEBUG, CLIENT_W_TAG, "hostingCallback exit");
        return OC_STACK_OK;
    }

    OCStackResult cachingCallback(std::shared_ptr<PrimitiveResource> resource,
                                  const ResourceAttributes &data,
                                  RemoteResourceObject::CacheUpdatedCallback onCacheUpdated)
    {
        OC_LOG(DEBUG, CLIENT_W_TAG, "cachingCallback entry");

        onCacheUpdated(data); //passing ResourceAttributes to application

        OC_LOG(DEBUG, CLIENT_W_TAG, "cachingCallback exit");
        return OC_STACK_OK;
    }

    void setCallback(const HeaderOptions &header, const ResponseStatement &response, int n,
                     RemoteResourceObject::RemoteAttributesSetCallback onRemoteAttributesSet)
    {
        OC_LOG(DEBUG, CLIENT_W_TAG, "setCallback entry");

        const ResourceAttributes &attributes = response.getAttributes();
        onRemoteAttributesSet(attributes); //passing ResourceAttributes to application

        OC_LOG(DEBUG, CLIENT_W_TAG, "setCallback exit");
    }

    void getCallback(const HeaderOptions &headerOption, const ResponseStatement &response, int n,
                     RemoteResourceObject::RemoteAttributesReceivedCallback onRemoteAttributesReceived)
    {
        OC_LOG(DEBUG, CLIENT_W_TAG, "getCallback entry");

        const ResourceAttributes &attributes = response.getAttributes();
        onRemoteAttributesReceived(attributes); //passing ResourceAttributes to application

        OC_LOG(DEBUG, CLIENT_W_TAG, "getCallback exit");
    }

    void findCallback(std::shared_ptr<PrimitiveResource> primitiveResource,
                      DiscoveryManager::OnResourceDiscoveredCallback OnResourceDiscovered )
    {
        OC_LOG(DEBUG, CLIENT_W_TAG, "findCallback entry");

        if (nullptr == primitiveResource)
        {
            OC_LOG(ERROR, CLIENT_W_TAG, "findCallback::primitiveResource NULL Parameter");
            return ;
        }

        std::shared_ptr< RemoteResourceObject>  primitiveClientResource =
            std::shared_ptr< RemoteResourceObject>(new RemoteResourceObject(primitiveResource));

        OnResourceDiscovered(primitiveClientResource); //passing PrimitiveClientResource to application

        OC_LOG(DEBUG, CLIENT_W_TAG, "findcb exit");
    }

}

//*******************************Primitive Client Resource*************************************

namespace OIC
{
    namespace Service
    {

        RemoteResourceObject:: RemoteResourceObject(std::shared_ptr<PrimitiveResource>  pResource) :
            m_monitoringFlag(false), m_cachingFlag(false),  m_observableFlag(pResource->isObservable()),
            m_primitiveResource(pResource), m_cacheId(0), m_brokerId(0) {}

        bool RemoteResourceObject::isMonitoring() const
        {
            return m_monitoringFlag;
        }

        bool RemoteResourceObject::isCaching() const
        {
            return m_cachingFlag;
        }

        void RemoteResourceObject::startMonitoring(ResourceStateChangedCallback cb)
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startMonitoring entry");
            if (true == m_monitoringFlag)
            {
                OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startMonitoring : Already started");
            }
            else
            {
                try
                {
                    BrokerID brokerId =  ResourceBroker::getInstance()->hostResource(m_primitiveResource,
                                         std::bind(hostingCallback, std::placeholders::_1,
                                                   cb));
                    m_monitoringFlag = true;
                    m_brokerId = brokerId;
                }
                catch (std::exception &exception)
                {
                    throw InvalidParameterException {exception.what()};
                }
            }
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startMonitoring exit");
        }

        void RemoteResourceObject::stopMonitoring()
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::stopMonitoring entry");
            if (true == m_monitoringFlag)
            {
                try
                {
                    ResourceBroker::getInstance()->cancelHostResource(m_brokerId);
                    m_monitoringFlag = false;
                }
                catch (std::exception &exception)
                {
                    OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::stopMonitoring InvalidParameterException");
                }
            }
            else
            {
                OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject:: stopMonitoring : already terminated");
            }

            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::stopMonitoring exit");
        }

        ResourceState RemoteResourceObject::getState() const
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, " RemoteResourceObject::getState entry");
            try
            {
                BROKER_STATE brokerState = ResourceBroker::getInstance()->getResourceState(m_primitiveResource);
                OC_LOG(DEBUG, CLIENT_W_TAG, " RemoteResourceObject::getState exit");
                return getResourceStateFromBrokerState(brokerState);
            }
            catch (std::exception &exception)
            {
                OC_LOG(DEBUG, CLIENT_W_TAG, " RemoteResourceObject::getState InvalidParameterException");
                throw BadRequestException { "[getState] Get Resource Source State from Broker Error " };
            }
        }

        void RemoteResourceObject::startCaching()
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching entry");
            if (true == m_cachingFlag)
            {
                OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching : already Started");
            }
            else
            {
                try
                {
                  CacheID cacheId = ResourceCacheManager::getInstance()->requestResourceCache(m_primitiveResource,
                                      NULL, REPORT_FREQUENCY::NONE,  0);

                    m_cacheId = cacheId;
                    m_cachingFlag = true;
                    OC_LOG_V(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching CACHE ID %d", cacheId);
                }
                catch (std::exception &exception)
                {
                    OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching InvalidParameterException");
                }
            }
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching exit");
        }

        void RemoteResourceObject::startCaching(CacheUpdatedCallback cb)
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching entry");
            if (true == m_cachingFlag)
            {
                OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching : already Started");
            }
            else
            {
                try
                {
                  CacheID cacheId = ResourceCacheManager::getInstance()->requestResourceCache(m_primitiveResource,
                                      std::bind(cachingCallback, std::placeholders::_1, std::placeholders::_2, cb),
                                      REPORT_FREQUENCY::UPTODATE,  0);

                    m_cacheId = cacheId;
                    m_cachingFlag = true;
                    OC_LOG_V(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::startCaching CACHE ID %d", cacheId);
                }
                catch (std::exception &exception)
                {
                    throw InvalidParameterException {"startCaching : Callback is NULL" };
                }
            }
        }

        void RemoteResourceObject::stopCaching()
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::stopCaching entry");

            if (true == m_cachingFlag)
            {
                try
                {
                    ResourceCacheManager::getInstance()->cancelResourceCache(m_cacheId);
                    m_cachingFlag = false;
                }
                catch (std::exception &exception)
                {
                    OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::stopCaching InvalidParameterException");
                }
            }
            else
            {
                OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject:: Caching already terminated");
            }

            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::stopCaching exit");
        }

        CacheState  RemoteResourceObject::getResourceCacheState()
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::getResourceCacheState entry");
            try
            {
                CACHE_STATE cacheState = ResourceCacheManager::getInstance()->getResourceCacheState(
                                             m_primitiveResource);
                OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::getResourceCacheState exit");
                return getCacheState(cacheState);
            }
            catch (std::exception &exception)
            {
                OC_LOG(DEBUG, CLIENT_W_TAG,
                       "RemoteResourceObject::getResourceCacheState InvalidParameterException");
                throw BadRequestException { "[getResourceCacheState] Caching not started" };
            }
        }

        void RemoteResourceObject::refreshCache()
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::refreshCache entry");
            try
            {

                ResourceCacheManager::getInstance()->updateResourceCache(
                    m_primitiveResource);
            }
            catch (std::exception &exception)
            {
                OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::refreshCache InvalidParameterException");
            }
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::refreshCache exit");
        }

        ResourceAttributes RemoteResourceObject:: getCachedAttributes() const
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject :: getCachedAttributes ");
            try
            {
                return ResourceCacheManager::getInstance()->getCachedData(m_primitiveResource);
            }
            catch (std::exception &exception)
            {
                throw BadRequestException { "[getCachedAttributes]  Caching not started" };
            }
        }

        ResourceAttributes::Value  RemoteResourceObject:: getCachedAttribute( const std::string &key)
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject :: getCachedAttribute entry");
            try
            {
                ResourceAttributes  Cachedattributes = ResourceCacheManager::getInstance()->getCachedData(
                        m_primitiveResource);
                return Cachedattributes[key];
            }
            catch (std::exception &exception)
            {
                throw BadRequestException { "[getCachedAttribute]  Caching not started" };
            }
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject :: getCachedAttribute exit");
        }

        std::string RemoteResourceObject::getUri() const
        {
            return m_primitiveResource->getUri();
        }

        std::string RemoteResourceObject::getAddress() const
        {
            return m_primitiveResource->getHost();
        }

        std::vector < std::string > RemoteResourceObject::getTypes() const
        {
            return m_primitiveResource->getTypes();
        }

        std::vector < std::string > RemoteResourceObject::getInterfaces() const
        {
            return m_primitiveResource->getInterfaces();
        }

        void RemoteResourceObject::getRemoteAttributes(RemoteAttributesReceivedCallback cb)
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::getRemoteAttributes entry");

            m_primitiveResource->requestGet(std::bind(getCallback, std::placeholders::_1,
                                            std::placeholders::_2, std::placeholders::_3, cb));

            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::getRemoteAttributes exit");
        }

        void RemoteResourceObject::setRemoteAttributes(ResourceAttributes &attribute,
                RemoteAttributesSetCallback cb)
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::setRemoteAttributes entry");

            m_primitiveResource->requestSet(attribute, std::bind(setCallback, std::placeholders::_1,
                                            std::placeholders::_2, std::placeholders::_3, cb));

            OC_LOG(DEBUG, CLIENT_W_TAG, "RemoteResourceObject::setRemoteAttributes exit");
        }

        bool RemoteResourceObject::isObservable() const
        {
            return m_observableFlag;
        }

//*******************************Discovery Manager****************************************

        DiscoveryManager *DiscoveryManager:: getInstance()
        {
            OC_LOG(DEBUG, CLIENT_W_TAG, "DiscoveryManager:: getInstance entry");
            static DiscoveryManager *s_instance;
            static std::mutex s_mutex;
            if (!s_instance)
            {
                std::lock_guard<std::mutex> lock(s_mutex);
                if (!s_instance)
                {
                    s_instance = new DiscoveryManager();
                }
            }
            OC_LOG(DEBUG, CLIENT_W_TAG, "DiscoveryManager:: getInstance exit");
            return s_instance;
        }

        void DiscoveryManager::discoverResource(std::string host, std::string resourceURI,
                                                OCConnectivityType connectivityType,
                                                OnResourceDiscoveredCallback cb)
        {

            OC_LOG(DEBUG, CLIENT_W_TAG, "DiscoveryManager::discoverResource entry");

            if ( resourceURI.empty() )
            {
                OC_LOG(ERROR, CLIENT_W_TAG, "discoverResource NULL resourceURI");
                throw InvalidParameterException { "discoverResource NULL resourceURI'" };
            }
            else if ( !cb )
            {
                OC_LOG(ERROR, CLIENT_W_TAG, "discoverResource NULL Callback");
                throw InvalidParameterException { "discoverResource NULL Callback'" };
            }
            OIC::Service::discoverResource(host, resourceURI, connectivityType, std::bind(findCallback,
                                           std::placeholders::_1,
                                           cb));

            OC_LOG(DEBUG, CLIENT_W_TAG, "DiscoveryManager::discoverResource exit");
        }
    }
}
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2018 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

// ospcommon
#include "ospcommon/utility/StringManip.h"
// sg
#include "../common/Data.h"
#include "Generator.h"

namespace ospray {
  namespace sg {

    void generateGridOfSpheres(const std::shared_ptr<Node> &world,
                               const std::vector<string_pair> &params)
    {
      auto spheres_node = createNode("grid_of_spheres", "Spheres");

      // get generator parameters

      vec3i dims(100, 100, 100);

      for (auto &p : params) {
        if (p.first == "dimensions" || p.first == "dims") {
          auto string_dims = ospcommon::utility::split(p.second, 'x');
          if (string_dims.size() != 3) {
            std::cout << "WARNING: ignoring incorrect 'dimensions' parameter,"
                      << " it must be of the form 'dimensions=XxYxZ'"
                      << std::endl;
            continue;
          }

          dims = vec3i(std::atoi(string_dims[0].c_str()),
                       std::atoi(string_dims[1].c_str()),
                       std::atoi(string_dims[2].c_str()));
        } else {
          std::cout << "WARNING: unknown spheres generator parameter '"
                    << p.first << "' with value '" << p.second << "'"
                    << std::endl;
        }
      }

      // generate sphere data

      const auto numSpheres = dims.product();
      const auto inv_dims = 1.f / dims;

      auto sphere_centers = std::make_shared<DataVector3f>();
      sphere_centers->setName("spheres");

      sphere_centers->v.resize(numSpheres);

      vec3f current(0.f);

      for (int i = 0; i < numSpheres; ++i) {
        auto &c = sphere_centers->v[i];

        c = current;

        current.x += inv_dims.x;
        if (current.x > 1.f) {
          current.x = 0.f;
          current.y += inv_dims.x;
          if (current.y > 1.f) {
            current.y = 0.f;
            current.z += inv_dims.x;
            if (current.z > 1.f)
              current.z = 0.f;
          }
        }
      }

      spheres_node->add(sphere_centers);

      // spheres attribute nodes

      spheres_node->createChild("radius", "float", inv_dims.x / 5.f);
      spheres_node->createChild("bytes_per_sphere", "int", int(sizeof(vec3f)));

      // finally add to world

      world->add(spheres_node);
    }

    OSPSG_REGISTER_GENERATE_FUNCTION(generateGridOfSpheres, gridOfSpheres);
    OSPSG_REGISTER_GENERATE_FUNCTION(generateGridOfSpheres, grid_of_spheres);

  }  // ::ospray::sg
}  // ::ospray
<commit_msg>better implementation for gridOfSpheres generator<commit_after>// ======================================================================== //
// Copyright 2009-2018 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

// ospcommon
#include "ospcommon/utility/StringManip.h"
// sg
#include "../common/Data.h"
#include "Generator.h"

namespace ospray {
  namespace sg {

    // Helper type ////////////////////////////////////////////////////////////

    // TODO: generalize to more than just 3D (2D + 4D)
    struct multidim_index_sequence
    {
      multidim_index_sequence(const vec3i &_dims) : dims(_dims) {}

      size_t flatten(const vec3i &coords)
      {
        return coords.x + dims.x * (coords.y + dims.y * coords.z);
      }

      vec3i reshape(size_t i)
      {
        size_t z = i / (dims.x * dims.y);
        i -= (z * dims.x * dims.y);
        size_t y = i / dims.x;
        size_t x = i % dims.x;
        return vec3i(x, y, z);
      }

      size_t total_indices()
      {
        return dims.product();
      }

      // TODO: iterators...

    private:

      vec3ul dims{0};
    };

    // Generator function /////////////////////////////////////////////////////

    void generateGridOfSpheres(const std::shared_ptr<Node> &world,
                               const std::vector<string_pair> &params)
    {
      auto spheres_node = createNode("grid_of_spheres", "Spheres");

      // get generator parameters

      vec3i dims(100, 100, 100);

      for (auto &p : params) {
        if (p.first == "dimensions" || p.first == "dims") {
          auto string_dims = ospcommon::utility::split(p.second, 'x');
          if (string_dims.size() != 3) {
            std::cout << "WARNING: ignoring incorrect 'dimensions' parameter,"
                      << " it must be of the form 'dimensions=XxYxZ'"
                      << std::endl;
            continue;
          }

          dims = vec3i(std::atoi(string_dims[0].c_str()),
                       std::atoi(string_dims[1].c_str()),
                       std::atoi(string_dims[2].c_str()));
        } else {
          std::cout << "WARNING: unknown spheres generator parameter '"
                    << p.first << "' with value '" << p.second << "'"
                    << std::endl;
        }
      }

      // generate sphere data

      const auto numSpheres  = dims.product();
      const auto inv_dims    = 1.f / dims;
      const auto min_inv_dim = reduce_min(inv_dims);

      auto sphere_centers = std::make_shared<DataVector3f>();
      sphere_centers->setName("spheres");

      sphere_centers->v.resize(numSpheres);

      multidim_index_sequence dims_converter(dims);

      for (size_t i = 0; i < dims_converter.total_indices(); ++i) {
        auto &c = sphere_centers->v[i];
        c = dims_converter.reshape(i) * min_inv_dim;
      }

      spheres_node->add(sphere_centers);

      // spheres attribute nodes

      spheres_node->createChild("radius", "float", min_inv_dim / 5.f);
      spheres_node->createChild("bytes_per_sphere", "int", int(sizeof(vec3f)));

      // finally add to world

      world->add(spheres_node);
    }

    OSPSG_REGISTER_GENERATE_FUNCTION(generateGridOfSpheres, gridOfSpheres);
    OSPSG_REGISTER_GENERATE_FUNCTION(generateGridOfSpheres, grid_of_spheres);

  }  // ::ospray::sg
}  // ::ospray
<|endoftext|>


<commit_before><commit_msg>More clean-up<commit_after><|endoftext|>