<commit_before>// CompMap.cpp
#include "CompMap.h"

#include "MassTable.h"
#include "CycArithmetic.h"
#include "CycException.h"
#include "CycLimits.h"

#include <sstream>
#include <cmath> // std::abs

using namespace std;

LogLevel CompMap::log_level_ = LEV_INFO3;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMap::CompMap(Basis b) {
  init(b);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMap::CompMap(const CompMap& other) {
  init(other.basis());
  map_ = other.map();
}

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

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMap::iterator CompMap::begin() {
  return map_.begin();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMap::iterator CompMap::end() {
  return map_.end();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double& CompMap::operator[](const int& tope) {
  normalized_ = false;
  return map_.operator[](tope);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int CompMap::count(Iso tope) const {
  return map_.count(tope);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::erase(Iso tope) {
  normalized_ = false;
  map_.erase(tope);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::erase(CompMap::iterator position) {
  normalized_ = false;
  map_.erase(position);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CompMap::empty() const {
  return map_.empty();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int CompMap::size() const {
  return map_.size();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CompMap::operator==(const CompMap& rhs) const {
  return almostEqual(rhs, 0);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CompMap::operator<(const CompMap& rhs) const {
  return (ID_ < rhs.ID());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CompMap::almostEqual(const CompMap& rhs, double threshold) const{
  // I learned at
  // http://www.ualberta.ca/~kbeach/comp_phys/fp_err.html#testing-for-equality
  // that the following is less naive than the intuitive way of doing this...
  // almost equal if :
  // (abs(x-y) < abs(x)*eps) && (abs(x-y) < abs(y)*epsilon)

  if ( threshold < 0 ) {
      stringstream ss;
      ss << "The threshold cannot be negative. The value provided was "
         << threshold
         << " .";
      throw CycNegativeValueException(ss.str());
  }
  if ( size() != rhs.size() ) {
    return false;
  }
  for (const_iterator it = map_.begin(); it != map_.end(); it++) {
    if (rhs.count(it->first) == 0) {
      return false;
    }
    double minuend = rhs.massFraction(it->first);
    double subtrahend = massFraction(it->first);
    double diff = minuend - subtrahend;
    if (abs(minuend) == 0 || abs(subtrahend) == 0){
      if (abs(diff) > abs(diff)*threshold){
        return false;
      }
    } else if (abs(diff) > abs(minuend)*threshold || abs(diff) > abs(subtrahend)*threshold) {
      return false;
    }
  }
  return true;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CompMap::recorded() const {
  return (ID_ > 0);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Basis CompMap::basis() const {
  return basis_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Map CompMap::map() const {
  return map_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int CompMap::ID() const {
  return ID_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double CompMap::massFraction(const Iso& tope) const {
  if (count(tope) == 0 || mass_to_atom_ratio_ == 0) {
    return 0.0;
  }
  double factor = 1.0;
  if (basis_ != MASS) {
    factor = MT->gramsPerMol(tope) / mass_to_atom_ratio_;
  }
  return factor * map_.find(tope)->second;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double CompMap::atomFraction(const Iso& tope) const {
  if (count(tope) == 0 || mass_to_atom_ratio_ == 0) {
    return 0.0;
  }
  double factor = 1.0;
  if (basis_ != ATOM) {
    factor = 1 / (MT->gramsPerMol(tope) / mass_to_atom_ratio_);
  }
  return factor * map_.find(tope)->second;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMapPtr CompMap::parent() const {
  return parent_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int CompMap::decay_time() const {
  return decay_time_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CompMap::normalized() const {
  return normalized_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double CompMap::mass_to_atom_ratio() const {
  return mass_to_atom_ratio_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMapPtr CompMap::me() {
  return shared_from_this();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMapPtr CompMap::root_comp() {
  CompMapPtr child = me();
  while (child->parent()) {
    child = child->parent();
  }
  return child;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int CompMap::root_decay_time() {
  CompMapPtr child = me();
  int time = decay_time();
  while (child->parent()) {
    child = child->parent();
    time += child->decay_time();
  }
  return time;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::massify() {
  change_basis(MASS);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::atomify() {
  change_basis(ATOM);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::normalize() {
  double sum;
  double other_sum;
  vector<double> vec;
  vector<double> other_vec;
  bool atom = (basis_ == ATOM);
  for (iterator it = map_.begin(); it != map_.end(); ++it) {
    validateEntry(it->first,it->second);
    vec.push_back(it->second);
    if (atom) {
      other_vec.push_back(it->second * MT->gramsPerMol(it->first));
    }
    else {
      other_vec.push_back(it->second / MT->gramsPerMol(it->first));
    }
  }
  sum = CycArithmetic::KahanSum(vec);
  other_sum = CycArithmetic::KahanSum(other_vec);
  if (sum == 0) {
    mass_to_atom_ratio_ = 0;
  } else if (atom){
    mass_to_atom_ratio_ = other_sum / sum;
  } else {
    mass_to_atom_ratio_ = sum / other_sum;
  }
  normalize(sum);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::init(Basis b) {
  basis_ = b;
  map_ = Map();
  normalized_ = false;
  mass_to_atom_ratio_ = 1;
  ID_ = 0;
  decay_time_ = 0;
  parent_.reset();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::change_basis(Basis b) {
  if (!normalized()) {
    normalize();
  }
  if (basis_ != b) { // only change if we have to
    for (iterator it = map_.begin(); it != map_.end(); it++) {
      switch (b) {
      case ATOM:
        map_[it->first] = atomFraction(it->first);
        break;
      case MASS:
        map_[it->first] = massFraction(it->first);
        break;
      default:
        throw CycRangeException("Basis not atom or mass.");
        break;
      }
    }
    basis_ = b;
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::normalize(double sum) {
  if (sum != 1 && sum != 0) { // only normalize if needed
    for (iterator it = map_.begin(); it != map_.end(); it++) {
      it->second /= sum;
    }
  }
  normalized_ = true;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int CompMap::getAtomicNum(Iso tope) {
  validateIsotopeNumber(tope);
  return tope / 1000; // integer division;
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int CompMap::getMassNum(Iso tope) {
  validateIsotopeNumber(tope);
  return tope % 1000;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::validate() {
  for (Map::iterator it = map_.begin(); it != map_.end(); it ++) {
    validateEntry(it->first,it->second);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::validateEntry(const Iso& tope, const double& value) {
  validateIsotopeNumber(tope);
  validateValue(value);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::validateIsotopeNumber(const Iso& tope) {
  int lower_limit = 1001;
  int upper_limit = 1182949;
  if (tope < lower_limit || tope > upper_limit) {
    stringstream ss("");
    ss << tope;
    throw CycRangeException("Isotope identifier '" + ss.str() + "' is not valid.");
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::validateValue(const double& value) {
  if (value < 0.0) {
    string err_msg = "CompMap has negative quantity for an isotope.";
    throw CycRangeException(err_msg);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::print() {
  CLOG(log_level_) << detail();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string CompMap::detail() {
  stringstream ss;
  vector<string> entries = compStrings();
  for (vector<string>::iterator entry = entries.begin();
       entry != entries.end(); entry++) {
    CLOG(log_level_) << *entry;
  }
  return "";
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::vector<std::string> CompMap::compStrings() {
  stringstream ss;
  vector<string> comp_strings;
  for (const_iterator entry = map_.begin(); entry != map_.end(); entry++) {
    ss.str("");
    ss << entry->first << ": " << entry->second << " % / kg";
    comp_strings.push_back(ss.str());
  }
  return comp_strings;
}
<commit_msg>prefer prepended iterator<commit_after>// CompMap.cpp
#include "CompMap.h"

#include "MassTable.h"
#include "CycArithmetic.h"
#include "CycException.h"
#include "CycLimits.h"

#include <sstream>
#include <cmath> // std::abs

using namespace std;

LogLevel CompMap::log_level_ = LEV_INFO3;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMap::CompMap(Basis b) {
  init(b);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMap::CompMap(const CompMap& other) {
  init(other.basis());
  map_ = other.map();
}

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

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMap::iterator CompMap::begin() {
  return map_.begin();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMap::iterator CompMap::end() {
  return map_.end();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double& CompMap::operator[](const int& tope) {
  normalized_ = false;
  return map_.operator[](tope);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int CompMap::count(Iso tope) const {
  return map_.count(tope);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::erase(Iso tope) {
  normalized_ = false;
  map_.erase(tope);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::erase(CompMap::iterator position) {
  normalized_ = false;
  map_.erase(position);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CompMap::empty() const {
  return map_.empty();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int CompMap::size() const {
  return map_.size();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CompMap::operator==(const CompMap& rhs) const {
  return almostEqual(rhs, 0);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CompMap::operator<(const CompMap& rhs) const {
  return (ID_ < rhs.ID());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CompMap::almostEqual(const CompMap& rhs, double threshold) const{
  // I learned at
  // http://www.ualberta.ca/~kbeach/comp_phys/fp_err.html#testing-for-equality
  // that the following is less naive than the intuitive way of doing this...
  // almost equal if :
  // (abs(x-y) < abs(x)*eps) && (abs(x-y) < abs(y)*epsilon)

  if ( threshold < 0 ) {
      stringstream ss;
      ss << "The threshold cannot be negative. The value provided was "
         << threshold
         << " .";
      throw CycNegativeValueException(ss.str());
  }
  if ( size() != rhs.size() ) {
    return false;
  }
  for (const_iterator it = map_.begin(); it != map_.end(); it++) {
    if (rhs.count(it->first) == 0) {
      return false;
    }
    double minuend = rhs.massFraction(it->first);
    double subtrahend = massFraction(it->first);
    double diff = minuend - subtrahend;
    if (abs(minuend) == 0 || abs(subtrahend) == 0){
      if (abs(diff) > abs(diff)*threshold){
        return false;
      }
    } else if (abs(diff) > abs(minuend)*threshold || abs(diff) > abs(subtrahend)*threshold) {
      return false;
    }
  }
  return true;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CompMap::recorded() const {
  return (ID_ > 0);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Basis CompMap::basis() const {
  return basis_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Map CompMap::map() const {
  return map_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int CompMap::ID() const {
  return ID_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double CompMap::massFraction(const Iso& tope) const {
  if (count(tope) == 0 || mass_to_atom_ratio_ == 0) {
    return 0.0;
  }
  double factor = 1.0;
  if (basis_ != MASS) {
    factor = MT->gramsPerMol(tope) / mass_to_atom_ratio_;
  }
  return factor * map_.find(tope)->second;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double CompMap::atomFraction(const Iso& tope) const {
  if (count(tope) == 0 || mass_to_atom_ratio_ == 0) {
    return 0.0;
  }
  double factor = 1.0;
  if (basis_ != ATOM) {
    factor = 1 / (MT->gramsPerMol(tope) / mass_to_atom_ratio_);
  }
  return factor * map_.find(tope)->second;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMapPtr CompMap::parent() const {
  return parent_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int CompMap::decay_time() const {
  return decay_time_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool CompMap::normalized() const {
  return normalized_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double CompMap::mass_to_atom_ratio() const {
  return mass_to_atom_ratio_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMapPtr CompMap::me() {
  return shared_from_this();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CompMapPtr CompMap::root_comp() {
  CompMapPtr child = me();
  while (child->parent()) {
    child = child->parent();
  }
  return child;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int CompMap::root_decay_time() {
  CompMapPtr child = me();
  int time = decay_time();
  while (child->parent()) {
    child = child->parent();
    time += child->decay_time();
  }
  return time;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::massify() {
  change_basis(MASS);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::atomify() {
  change_basis(ATOM);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::normalize() {
  double sum;
  double other_sum;
  vector<double> vec;
  vector<double> other_vec;
  bool atom = (basis_ == ATOM);
  for (iterator it = map_.begin(); it != map_.end(); ++it) {
    validateEntry(it->first,it->second);
    vec.push_back(it->second);
    if (atom) {
      other_vec.push_back(it->second * MT->gramsPerMol(it->first));
    }
    else {
      other_vec.push_back(it->second / MT->gramsPerMol(it->first));
    }
  }
  sum = CycArithmetic::KahanSum(vec);
  other_sum = CycArithmetic::KahanSum(other_vec);
  if (sum == 0) {
    mass_to_atom_ratio_ = 0;
  } else if (atom){
    mass_to_atom_ratio_ = other_sum / sum;
  } else {
    mass_to_atom_ratio_ = sum / other_sum;
  }
  normalize(sum);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::init(Basis b) {
  basis_ = b;
  map_ = Map();
  normalized_ = false;
  mass_to_atom_ratio_ = 1;
  ID_ = 0;
  decay_time_ = 0;
  parent_.reset();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::change_basis(Basis b) {
  if (!normalized()) {
    normalize();
  }
  if (basis_ != b) { // only change if we have to
    for (iterator it = map_.begin(); it != map_.end(); ++it) {
      switch (b) {
      case ATOM:
        map_[it->first] = atomFraction(it->first);
        break;
      case MASS:
        map_[it->first] = massFraction(it->first);
        break;
      default:
        throw CycRangeException("Basis not atom or mass.");
        break;
      }
    }
    basis_ = b;
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::normalize(double sum) {
  if (sum != 1 && sum != 0) { // only normalize if needed
    for (iterator it = map_.begin(); it != map_.end(); it++) {
      it->second /= sum;
    }
  }
  normalized_ = true;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int CompMap::getAtomicNum(Iso tope) {
  validateIsotopeNumber(tope);
  return tope / 1000; // integer division;
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int CompMap::getMassNum(Iso tope) {
  validateIsotopeNumber(tope);
  return tope % 1000;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::validate() {
  for (Map::iterator it = map_.begin(); it != map_.end(); it ++) {
    validateEntry(it->first,it->second);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::validateEntry(const Iso& tope, const double& value) {
  validateIsotopeNumber(tope);
  validateValue(value);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::validateIsotopeNumber(const Iso& tope) {
  int lower_limit = 1001;
  int upper_limit = 1182949;
  if (tope < lower_limit || tope > upper_limit) {
    stringstream ss("");
    ss << tope;
    throw CycRangeException("Isotope identifier '" + ss.str() + "' is not valid.");
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::validateValue(const double& value) {
  if (value < 0.0) {
    string err_msg = "CompMap has negative quantity for an isotope.";
    throw CycRangeException(err_msg);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void CompMap::print() {
  CLOG(log_level_) << detail();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string CompMap::detail() {
  stringstream ss;
  vector<string> entries = compStrings();
  for (vector<string>::iterator entry = entries.begin();
       entry != entries.end(); entry++) {
    CLOG(log_level_) << *entry;
  }
  return "";
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::vector<std::string> CompMap::compStrings() {
  stringstream ss;
  vector<string> comp_strings;
  for (const_iterator entry = map_.begin(); entry != map_.end(); entry++) {
    ss.str("");
    ss << entry->first << ": " << entry->second << " % / kg";
    comp_strings.push_back(ss.str());
  }
  return comp_strings;
}
<|endoftext|>


<commit_before>
#include <qcheckbox.h>
#include <qdir.h>
#include <qlineedit.h>

#include <kaboutdata.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <ksimpleconfig.h>
#include <kurlrequester.h>

#include <kabc/stdaddressbook.h>
#include <kabc/resourcefile.h>

#include <kparts/genericfactory.h>

#include <ksync_mainwindow.h>

#include <addressbooksyncee.h>

#include "addressbookbase.h"
#include "ksync_addressbookpart.h"

typedef KParts::GenericFactory< KSync::AddressBookPart> AddressBookPartFactory;
K_EXPORT_COMPONENT_FACTORY( libaddressbookpart,  AddressBookPartFactory );

using namespace KSync;

AddressBookPart::AddressBookPart( QWidget* parent,  const char* name,
                                  QObject* obj,  const char* ,
                                  const QStringList & )
    : ManipulatorPart( parent ? parent : obj ,  name )
{
    setInstance( AddressBookPartFactory::instance() );
    m_pixmap = KGlobal::iconLoader()->loadIcon("kaddressbook",  KIcon::Desktop,  48 );
}
AddressBookPart::~AddressBookPart(){
}
KAboutData *AddressBookPart::createAboutData(){
  return new KAboutData("KSyncAddressBookPart", I18N_NOOP("Sync AddressBook Part"), "0.0" );
}
QPixmap* AddressBookPart::pixmap(){
    return &m_pixmap;
}
QString AddressBookPart::type()const {
    return QString::fromLatin1("Addressbook");
}
QString AddressBookPart::name()const{
    return i18n("Addressbook");
}
QString AddressBookPart::iconName()const {
    return QString::fromLatin1("kaddressbook");
}
QString AddressBookPart::description()const {
    return i18n("The Addressbook Part");
}
bool AddressBookPart::configIsVisible()const {
    return false;
}
bool AddressBookPart::canSync()const{
    return true;
}
/*
 * SYnc it aye?
 * 1. get the currentProfile + Konnector
 * 2. get the paths + the path to the meta data
 * 3. search our AddressBookSyncee
 * 4. load the File
 * 5. do meta
 * 6. sync
 * 7. write Meta
 * 8. save
 * 9. write back
 * 10. party
 */
void AddressBookPart::sync( const Syncee::PtrList& in,
                            Syncee::PtrList& out ){
    kdDebug(5228) << "processEntry in AddressBookPart aye" << endl;
    /* 1. */
    Profile prof = core()->currentProfile();
    KonnectorProfile kon = core()->konnectorProfile();

    /* 2. */
    QString meta = kon.uid() + "/" + prof.uid() + "addressbook.rc";
    bool met = kon.kapabilities().isMetaSyncingEnabled();
    kdDebug(5228) << "Is meta syncing enabled? " << met << endl;

    /* 3. */
    Syncee* syncee = 0l;
    AddressBookSyncee* aBook=0l;
    QPtrListIterator<Syncee> syncIt( in );
    for ( ; syncIt.current(); ++syncIt ) {
        syncee = syncIt.current();
        if (syncee->type() == QString::fromLatin1("AddressBookSyncee") ) {
	    kdDebug(5228) << "Found our syncee" << endl;
            aBook = (AddressBookSyncee*) syncee;
            break;
        }

    }
    if (!aBook) {done(); return;}

    progress( Progress(i18n("Going to load AddressBook") ) );
    /* 4. */
    AddressBookSyncee* ourbook;
    ourbook = load();
    if (!ourbook) {
        error( Error(i18n("Could not load the AddressBook") ) );
        done();
    }

    /* 5. */
    if (met)
      doMeta( ourbook, meta );

    progress( Progress(i18n("Going to sync AddressBook") ) );
    /* 6. */
    Syncer sync( core()->syncUi(), core()->syncAlgorithm() );
    sync.addSyncee( aBook );
    sync.addSyncee( ourbook );
    sync.sync();

    /* 7. KABC seems broken so we do meta from save*/
/*    if (met)
      writeMeta( ourbook, meta );
*/

    progress( Progress(i18n("Going to save AddressBook") ) );
    /* 8. */
    save( ourbook, met ? meta : QString::null );

    /* writeback */
    out.append( ourbook );
    done();
}
void AddressBookPart::slotConfigOk(){
}
/*
 * let's load it
 * if path is empty or default Take KStdAddressBook
 * otherwise load the file
 */
AddressBookSyncee* AddressBookPart::load() {
    KABC::AddressBook* book;
    AddressBookSyncee* sync;
    kdDebug(5228) << "use default one " << endl;
    book =  KABC::StdAddressBook::self();
    if (!book->load() )
        return 0l;
    sync = book2syncee( book );
    return sync;
}
void AddressBookPart::doMeta( Syncee* syncee, const QString& path ) {
    kdDebug(5228) << "Do Meta" << endl;
    QString str = QDir::homeDirPath();
    str += "/.kitchensync/meta/konnector-" + path;
    if (!QFile::exists( str ) ) {
        kdDebug(5228) << "Path does not exist ->First Sync" << endl;
	kdDebug(5228) << "Path was " << str << "  " << path << endl;
        syncee->setFirstSync( true );
        syncee->setSyncMode( Syncee::MetaMode );
        return;
    }
    syncee->setSyncMode( Syncee::MetaMode );
    KSimpleConfig conf( str );

    SyncEntry* entry;
    QString timestmp;
    QStringList ids;

    /* mod + added */
    for (entry= syncee->firstEntry(); entry; entry = syncee->nextEntry() ) {
        ids << entry->id();
	kdDebug(5228) << "Entry " << entry->name() << endl << "Entry id" << entry->id() << endl;
        if ( conf.hasGroup( entry->id() )  ) {
            conf.setGroup( entry->id() );
            timestmp = conf.readEntry("time");
	    kdDebug(5228) << "Timestamp Old" << timestmp << endl;
	    kdDebug(5228) << "Timestamp New" << entry->timestamp() << endl;
            if ( timestmp != entry->timestamp() )
                entry->setState( SyncEntry::Modified );
        }
        /* added */
        else {
	    kdDebug(5228) << "Entry added" << endl;
            entry->setState( SyncEntry::Added );
        }
    }
    /* find removed item... through reversed mapping */
    QStringList groups = conf.groupList();
    QStringList::Iterator it;
    for (it = groups.begin(); it != groups.end(); ++it ) {
        // removed items if ids is not present
        if (!ids.contains( (*it) ) ) {
	    kdDebug(5228) << "Entry removed from abook" << (*it) << endl;
            KABC::Addressee adr;
            adr.setUid( (*it) );
            AddressBookSyncEntry* entry;
            entry = new AddressBookSyncEntry( adr );
            entry->setState( SyncEntry::Removed );
            syncee->addEntry( entry );
        }
    }
}
void AddressBookPart::writeMeta( KABC::AddressBook* book, const QString& path ) {
    /* no meta info to save */
    if (path.isEmpty() ) return;

    kdDebug(5228) << "WriteMeta AddressBookPart " << endl;
    QString str = QDir::homeDirPath();
    str += "/.kitchensync/meta/konnector-" + path;
    if (!QFile::exists( str ) ) {
        kdDebug(5228) << "Path does not exist " << endl;
	kdDebug(5228) << "Path = " << str << endl;
        KonnectorProfile kon = core()->konnectorProfile();
        QDir dir;
        dir.mkdir( dir.homeDirPath() + "/.kitchensync");
        dir.mkdir( dir.homeDirPath() + "/.kitchensync/meta");
        dir.mkdir( dir.homeDirPath() + "/.kitchensync/meta/konnector-" + kon.uid() );
	kdDebug(5228) << "Kon UID " << kon.uid() << endl;
    }
    KSimpleConfig conf( str );
    QStringList grpList = conf.groupList();
    QStringList::Iterator it;
    for ( it = grpList.begin(); it != grpList.end(); ++it ) {
        conf.deleteGroup( (*it) );
    }

    KABC::AddressBook::Iterator aIt;
    for ( aIt = book->begin(); aIt != book->end(); ++aIt ) {
        kdDebug(5228) << "Name " << (*aIt).realName() << endl;
        kdDebug(5228) << "UID  " << (*aIt).uid() << endl;
        kdDebug(5228) << "Timestamp " << (*aIt).revision().toString() << endl;

        conf.setGroup( (*aIt).uid() );
        conf.writeEntry( "time", (*aIt).revision().toString() );
    }
}
void AddressBookPart::save( AddressBookSyncee* sync, const QString& meta) {
    AddressBookSyncEntry* entry;
    KABC::AddressBook* book;

    // save to the std. addressbook
    book = KABC::StdAddressBook::self();
    /* clear the old book first */
    book->clear();

    for ( entry = (AddressBookSyncEntry*)sync->firstEntry();
          entry;
          entry= (AddressBookSyncEntry*) sync->nextEntry() ) {
        if( entry->state() != SyncEntry::Removed ) {
            KABC::Addressee adr = entry->addressee();
            adr.setResource( resource(entry->resource() ) );
            book->insertAddressee( adr );
        }
    }
    KABC::StdAddressBook::save();
    kdDebug(5228) << "dumped abook " << endl;
    writeMeta( book, meta );

    KABC::StdAddressBook::close();
}
/*bool AddressBookPart::pathIsDefault( const QString& path ) {
    if ( path.isEmpty() ) return true;
    if ( path.stripWhiteSpace() == QString::fromLatin1("default") )
        return true;

    kdDebug(5228) << "Path is not default" << endl;
    return false;
    }*/
AddressBookSyncee* AddressBookPart::book2syncee( KABC::AddressBook* book) {
    AddressBookSyncee* syncee = new AddressBookSyncee();
    AddressBookSyncEntry* entry=0l;
    KABC::AddressBook::Iterator it = book->begin();
    for ( ; it != book->end(); ++it ) {
        entry = new AddressBookSyncEntry( (*it) );
        QString res = (*it).resource() ? (*it).resource()->type() : QString::null;
        entry->setResource( res );
        syncee->addEntry( entry );
    }
    return syncee;
}
/*void AddressBookPart::saveAll( KABC::AddressBook* ab) {
    KABC::Resource *res = 0l;
    QPtrList<KABC::Resource> list = ab->resources();
    for (uint i = 0; i < list.count(); ++i ) {
        res = list.at( i );
        if (!res->readOnly() ) {
            KABC::Ticket* ticket = ab->requestSaveTicket( res );
            if (ticket)
                ab->save( ticket );
        }
    }
    }*/

KABC::Resource* AddressBookPart::resource( const QString& type ) {
    QPtrListIterator<KABC::Resource> it(KABC::StdAddressBook::self()->resources() );
    KABC::Resource* res = 0l;
    while ( (res = it.current()) ) {
        ++it;
        if ( res->type() == type )
            return res;
    }
    return 0;
}
#include "ksync_addressbookpart.moc"
<commit_msg>If the KABC::StdAddressBook::self() fails to open not only emit an error but return. This crash was found and debugged by Mathieu Chouniard. Thank you<commit_after>
#include <qcheckbox.h>
#include <qdir.h>
#include <qlineedit.h>

#include <kaboutdata.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <ksimpleconfig.h>
#include <kurlrequester.h>

#include <kabc/stdaddressbook.h>
#include <kabc/resourcefile.h>

#include <kparts/genericfactory.h>

#include <ksync_mainwindow.h>

#include <addressbooksyncee.h>

#include "addressbookbase.h"
#include "ksync_addressbookpart.h"

typedef KParts::GenericFactory< KSync::AddressBookPart> AddressBookPartFactory;
K_EXPORT_COMPONENT_FACTORY( libaddressbookpart,  AddressBookPartFactory );

using namespace KSync;

AddressBookPart::AddressBookPart( QWidget* parent,  const char* name,
                                  QObject* obj,  const char* ,
                                  const QStringList & )
    : ManipulatorPart( parent ? parent : obj ,  name )
{
    setInstance( AddressBookPartFactory::instance() );
    m_pixmap = KGlobal::iconLoader()->loadIcon("kaddressbook",  KIcon::Desktop,  48 );
}
AddressBookPart::~AddressBookPart(){
}
KAboutData *AddressBookPart::createAboutData(){
  return new KAboutData("KSyncAddressBookPart", I18N_NOOP("Sync AddressBook Part"), "0.0" );
}
QPixmap* AddressBookPart::pixmap(){
    return &m_pixmap;
}
QString AddressBookPart::type()const {
    return QString::fromLatin1("Addressbook");
}
QString AddressBookPart::name()const{
    return i18n("Addressbook");
}
QString AddressBookPart::iconName()const {
    return QString::fromLatin1("kaddressbook");
}
QString AddressBookPart::description()const {
    return i18n("The Addressbook Part");
}
bool AddressBookPart::configIsVisible()const {
    return false;
}
bool AddressBookPart::canSync()const{
    return true;
}
/*
 * SYnc it aye?
 * 1. get the currentProfile + Konnector
 * 2. get the paths + the path to the meta data
 * 3. search our AddressBookSyncee
 * 4. load the File
 * 5. do meta
 * 6. sync
 * 7. write Meta
 * 8. save
 * 9. write back
 * 10. party
 */
void AddressBookPart::sync( const Syncee::PtrList& in,
                            Syncee::PtrList& out ){
    kdDebug(5228) << "processEntry in AddressBookPart aye" << endl;
    /* 1. */
    Profile prof = core()->currentProfile();
    KonnectorProfile kon = core()->konnectorProfile();

    /* 2. */
    QString meta = kon.uid() + "/" + prof.uid() + "addressbook.rc";
    bool met = kon.kapabilities().isMetaSyncingEnabled();
    kdDebug(5228) << "Is meta syncing enabled? " << met << endl;

    /* 3. */
    Syncee* syncee = 0l;
    AddressBookSyncee* aBook=0l;
    QPtrListIterator<Syncee> syncIt( in );
    for ( ; syncIt.current(); ++syncIt ) {
        syncee = syncIt.current();
        if (syncee->type() == QString::fromLatin1("AddressBookSyncee") ) {
	    kdDebug(5228) << "Found our syncee" << endl;
            aBook = (AddressBookSyncee*) syncee;
            break;
        }

    }
    if (!aBook) {done(); return;}

    progress( Progress(i18n("Going to load AddressBook") ) );
    /* 4. */
    AddressBookSyncee* ourbook;
    ourbook = load();

    if (!ourbook) {
        error( Error(i18n("Could not load the AddressBook") ) );
        done();
        return;
    }

    /* 5. */
    if (met)
      doMeta( ourbook, meta );

    progress( Progress(i18n("Going to sync AddressBook") ) );
    /* 6. */
    Syncer sync( core()->syncUi(), core()->syncAlgorithm() );
    sync.addSyncee( aBook );
    sync.addSyncee( ourbook );
    sync.sync();

    /* 7. KABC seems broken so we do meta from save*/
/*    if (met)
      writeMeta( ourbook, meta );
*/

    progress( Progress(i18n("Going to save AddressBook") ) );
    /* 8. */
    save( ourbook, met ? meta : QString::null );

    /* writeback */
    out.append( ourbook );
    done();
}
void AddressBookPart::slotConfigOk(){
}
/*
 * let's load it
 * if path is empty or default Take KStdAddressBook
 * otherwise load the file
 */
AddressBookSyncee* AddressBookPart::load() {
    KABC::AddressBook* book;
    AddressBookSyncee* sync;
    kdDebug(5228) << "use default one " << endl;
    book =  KABC::StdAddressBook::self();
    if (!book->load() )
        return 0l;
    sync = book2syncee( book );
    return sync;
}
void AddressBookPart::doMeta( Syncee* syncee, const QString& path ) {
    kdDebug(5228) << "Do Meta" << endl;
    QString str = QDir::homeDirPath();
    str += "/.kitchensync/meta/konnector-" + path;
    if (!QFile::exists( str ) ) {
        kdDebug(5228) << "Path does not exist ->First Sync" << endl;
	kdDebug(5228) << "Path was " << str << "  " << path << endl;
        syncee->setFirstSync( true );
        syncee->setSyncMode( Syncee::MetaMode );
        return;
    }
    syncee->setSyncMode( Syncee::MetaMode );
    KSimpleConfig conf( str );

    SyncEntry* entry;
    QString timestmp;
    QStringList ids;

    /* mod + added */
    for (entry= syncee->firstEntry(); entry; entry = syncee->nextEntry() ) {
        ids << entry->id();
	kdDebug(5228) << "Entry " << entry->name() << endl << "Entry id" << entry->id() << endl;
        if ( conf.hasGroup( entry->id() )  ) {
            conf.setGroup( entry->id() );
            timestmp = conf.readEntry("time");
	    kdDebug(5228) << "Timestamp Old" << timestmp << endl;
	    kdDebug(5228) << "Timestamp New" << entry->timestamp() << endl;
            if ( timestmp != entry->timestamp() )
                entry->setState( SyncEntry::Modified );
        }
        /* added */
        else {
	    kdDebug(5228) << "Entry added" << endl;
            entry->setState( SyncEntry::Added );
        }
    }
    /* find removed item... through reversed mapping */
    QStringList groups = conf.groupList();
    QStringList::Iterator it;
    for (it = groups.begin(); it != groups.end(); ++it ) {
        // removed items if ids is not present
        if (!ids.contains( (*it) ) ) {
	    kdDebug(5228) << "Entry removed from abook" << (*it) << endl;
            KABC::Addressee adr;
            adr.setUid( (*it) );
            AddressBookSyncEntry* entry;
            entry = new AddressBookSyncEntry( adr );
            entry->setState( SyncEntry::Removed );
            syncee->addEntry( entry );
        }
    }
}
void AddressBookPart::writeMeta( KABC::AddressBook* book, const QString& path ) {
    /* no meta info to save */
    if (path.isEmpty() ) return;

    kdDebug(5228) << "WriteMeta AddressBookPart " << endl;
    QString str = QDir::homeDirPath();
    str += "/.kitchensync/meta/konnector-" + path;
    if (!QFile::exists( str ) ) {
        kdDebug(5228) << "Path does not exist " << endl;
	kdDebug(5228) << "Path = " << str << endl;
        KonnectorProfile kon = core()->konnectorProfile();
        QDir dir;
        dir.mkdir( dir.homeDirPath() + "/.kitchensync");
        dir.mkdir( dir.homeDirPath() + "/.kitchensync/meta");
        dir.mkdir( dir.homeDirPath() + "/.kitchensync/meta/konnector-" + kon.uid() );
	kdDebug(5228) << "Kon UID " << kon.uid() << endl;
    }
    KSimpleConfig conf( str );
    QStringList grpList = conf.groupList();
    QStringList::Iterator it;
    for ( it = grpList.begin(); it != grpList.end(); ++it ) {
        conf.deleteGroup( (*it) );
    }

    KABC::AddressBook::Iterator aIt;
    for ( aIt = book->begin(); aIt != book->end(); ++aIt ) {
        kdDebug(5228) << "Name " << (*aIt).realName() << endl;
        kdDebug(5228) << "UID  " << (*aIt).uid() << endl;
        kdDebug(5228) << "Timestamp " << (*aIt).revision().toString() << endl;

        conf.setGroup( (*aIt).uid() );
        conf.writeEntry( "time", (*aIt).revision().toString() );
    }
}
void AddressBookPart::save( AddressBookSyncee* sync, const QString& meta) {
    AddressBookSyncEntry* entry;
    KABC::AddressBook* book;

    // save to the std. addressbook
    book = KABC::StdAddressBook::self();
    /* clear the old book first */
    book->clear();

    for ( entry = (AddressBookSyncEntry*)sync->firstEntry();
          entry;
          entry= (AddressBookSyncEntry*) sync->nextEntry() ) {
        if( entry->state() != SyncEntry::Removed ) {
            KABC::Addressee adr = entry->addressee();
            adr.setResource( resource(entry->resource() ) );
            book->insertAddressee( adr );
        }
    }
    KABC::StdAddressBook::save();
    kdDebug(5228) << "dumped abook " << endl;
    writeMeta( book, meta );

    KABC::StdAddressBook::close();
}
/*bool AddressBookPart::pathIsDefault( const QString& path ) {
    if ( path.isEmpty() ) return true;
    if ( path.stripWhiteSpace() == QString::fromLatin1("default") )
        return true;

    kdDebug(5228) << "Path is not default" << endl;
    return false;
    }*/
AddressBookSyncee* AddressBookPart::book2syncee( KABC::AddressBook* book) {
    AddressBookSyncee* syncee = new AddressBookSyncee();
    AddressBookSyncEntry* entry=0l;
    KABC::AddressBook::Iterator it = book->begin();
    for ( ; it != book->end(); ++it ) {
        entry = new AddressBookSyncEntry( (*it) );
        QString res = (*it).resource() ? (*it).resource()->type() : QString::null;
        entry->setResource( res );
        syncee->addEntry( entry );
    }
    return syncee;
}
/*void AddressBookPart::saveAll( KABC::AddressBook* ab) {
    KABC::Resource *res = 0l;
    QPtrList<KABC::Resource> list = ab->resources();
    for (uint i = 0; i < list.count(); ++i ) {
        res = list.at( i );
        if (!res->readOnly() ) {
            KABC::Ticket* ticket = ab->requestSaveTicket( res );
            if (ticket)
                ab->save( ticket );
        }
    }
    }*/

KABC::Resource* AddressBookPart::resource( const QString& type ) {
    QPtrListIterator<KABC::Resource> it(KABC::StdAddressBook::self()->resources() );
    KABC::Resource* res = 0l;
    while ( (res = it.current()) ) {
        ++it;
        if ( res->type() == type )
            return res;
    }
    return 0;
}
#include "ksync_addressbookpart.moc"
<|endoftext|>


<commit_before>#include "gtest/gtest.h"

#include "../../cvmfs/statistics.h"

using namespace std;  // NOLINT

namespace perf {

TEST(T_Statistics, Counter) {
  Counter counter;
  EXPECT_EQ(0, counter.Get());
  counter.Set(1);
  EXPECT_EQ(1, counter.Get());
  counter.Inc();
  EXPECT_EQ(2, counter.Get());
  counter.Dec();
  EXPECT_EQ(1, counter.Get());
  EXPECT_EQ(1, counter.Xadd(-1));
  EXPECT_EQ(0, counter.Get());
  counter.Dec();
  EXPECT_EQ(-1, counter.Get());

  counter.Set(1024*1024);
  EXPECT_EQ("1048576", counter.Print());
  EXPECT_EQ("1024", counter.PrintKi());
  EXPECT_EQ("1048", counter.PrintK());
  EXPECT_EQ("1", counter.PrintM());
  EXPECT_EQ("1", counter.PrintMi());

  Counter counter2;
  EXPECT_EQ("inf", counter.PrintRatio(counter2));
  counter2.Set(1024);
  EXPECT_EQ("1024.000", counter.PrintRatio(counter2));
}

TEST(T_Statistics, Statistics) {
  Statistics statistics;

  Counter *counter = statistics.Register("test.counter", "a test counter");
  ASSERT_TRUE(counter != NULL);
  EXPECT_EQ(0, counter->Get());

  EXPECT_EQ(NULL, statistics.Register("test.counter", "Name Clash"));
  EXPECT_EQ(0, statistics.Lookup("test.counter")->Get());
  EXPECT_EQ("a test counter", statistics.LookupDesc("test.counter"));

  EXPECT_EQ(NULL, statistics.Lookup("test.unknown"));

  EXPECT_EQ("test.counter|0|a test counter\n",
            statistics.PrintList(Statistics::kPrintSimple));
}

}  // namespace perf
<commit_msg>style<commit_after>#include "gtest/gtest.h"

#include "../../cvmfs/statistics.h"

using namespace std;  // NOLINT

namespace perf {

TEST(T_Statistics, Counter) {
  Counter counter;
  EXPECT_EQ(0, counter.Get());
  counter.Set(1);
  EXPECT_EQ(1, counter.Get());
  counter.Inc();
  EXPECT_EQ(2, counter.Get());
  counter.Dec();
  EXPECT_EQ(1, counter.Get());
  EXPECT_EQ(1, counter.Xadd(-1));
  EXPECT_EQ(0, counter.Get());
  counter.Dec();
  EXPECT_EQ(-1, counter.Get());

  counter.Set(1024*1024);
  EXPECT_EQ("1048576", counter.Print());
  EXPECT_EQ("1024", counter.PrintKi());
  EXPECT_EQ("1048", counter.PrintK());
  EXPECT_EQ("1", counter.PrintM());
  EXPECT_EQ("1", counter.PrintMi());

  Counter counter2;
  EXPECT_EQ("inf", counter.PrintRatio(counter2));
  counter2.Set(1024);
  EXPECT_EQ("1024.000", counter.PrintRatio(counter2));
}

TEST(T_Statistics, Statistics) {
  Statistics statistics;

  Counter *counter = statistics.Register("test.counter", "a test counter");
  ASSERT_TRUE(counter != NULL);
  EXPECT_EQ(0, counter->Get());

  EXPECT_EQ(NULL, statistics.Register("test.counter", "Name Clash"));
  EXPECT_EQ(0, statistics.Lookup("test.counter")->Get());
  EXPECT_EQ("a test counter", statistics.LookupDesc("test.counter"));

  EXPECT_EQ(NULL, statistics.Lookup("test.unknown"));

  EXPECT_EQ("test.counter|0|a test counter\n",
            statistics.PrintList(Statistics::kPrintSimple));
}

}  // namespace perf
<|endoftext|>


<commit_before>// This file is distributed under the BSD License.
// See "license.txt" for details.
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
// and Jason Turner (lefticus@gmail.com)
// http://www.chaiscript.com

#include <boost/preprocessor.hpp>
#include <boost/preprocessor/arithmetic/inc.hpp>

#define param(z,n,text) BOOST_PP_CAT(_, BOOST_PP_INC(n))

#ifndef  BOOST_PP_IS_ITERATING
#ifndef __bind_first_hpp__
#define __bind_first_hpp__

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>

#define BOOST_PP_ITERATION_LIMITS ( 0, 8 )
#define BOOST_PP_FILENAME_1 <chaiscript/dispatchkit/bind_first.hpp>

#include BOOST_PP_ITERATE()

# endif
#else
# define n BOOST_PP_ITERATION()

namespace chaiscript
{

  template<typename Ret, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
    boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))>
      bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param)), boost::reference_wrapper<Class> &o)
      {
        return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~));
      }

  template<typename Ret, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
    boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))>
      bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param)) const, boost::reference_wrapper<Class> &o)
      {
        return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~));
      }

  template<typename Ret, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
    boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))>
      bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param)), Class *o)
      {
        return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~));
      }

  template<typename Ret, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
    boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))>
      bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param))const, Class *o)
      {
        return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~));
      }

  template<typename Ret, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
    boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))>
      bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param)), boost::shared_ptr<Class> o)
      {
        return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~));
      }

  template<typename Ret, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
    boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))>
      bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param))const, boost::shared_ptr<Class> o)
      {
        return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~));
      }

}

#endif
<commit_msg>Reduce # of required versions for bound_fun and enhance it to work with non-member functions<commit_after>// This file is distributed under the BSD License.
// See "license.txt" for details.
// Copyright 2009, Jonathan Turner (jturner@minnow-lang.org)
// and Jason Turner (lefticus@gmail.com)
// http://www.chaiscript.com

#include <boost/preprocessor.hpp>
#include <boost/preprocessor/arithmetic/inc.hpp>

#define param(z,n,text) BOOST_PP_CAT(_, BOOST_PP_INC(n))

#ifndef  BOOST_PP_IS_ITERATING
#ifndef __bind_first_hpp__
#define __bind_first_hpp__

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>

#define BOOST_PP_ITERATION_LIMITS ( 0, 8 )
#define BOOST_PP_FILENAME_1 <chaiscript/dispatchkit/bind_first.hpp>

#include BOOST_PP_ITERATE()

# endif
#else
# define n BOOST_PP_ITERATION()

namespace chaiscript
{

  template<typename Ret, typename O, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
    boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))>
      bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param)), const O &o)
      {
        return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~));
      }

  template<typename Ret, typename O, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
    boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))>
      bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param))const, const O &o)
      {
        return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~));
      }

  template<typename Ret,typename O BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) >
    boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))>
      bind_first(Ret (*f)(BOOST_PP_ENUM_PARAMS(n, Param)), const O &o)
      {
        return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~));
      }

}

#endif
<|endoftext|>


<commit_before>/*

Copyright (c) 2006, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef ROUTING_TABLE_HPP
#define ROUTING_TABLE_HPP

#include <vector>
#include <boost/cstdint.hpp>

#include <boost/utility.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/array.hpp>
#include <set>

#include <libtorrent/kademlia/logging.hpp>

#include <libtorrent/kademlia/node_id.hpp>
#include <libtorrent/kademlia/node_entry.hpp>
#include <libtorrent/session_settings.hpp>
#include <libtorrent/size_type.hpp>
#include <libtorrent/assert.hpp>
#include <libtorrent/ptime.hpp>

namespace libtorrent
{
	struct session_status;
}

namespace libtorrent { namespace dht
{

#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DECLARE_LOG(table);
#endif

typedef std::vector<node_entry> bucket_t;

struct routing_table_node
{
	bucket_t replacements;
	bucket_t live_nodes;
	ptime last_active;
};

// differences in the implementation from the description in
// the paper:
//
// * Nodes are not marked as being stale, they keep a counter
// 	that tells how many times in a row they have failed. When
// 	a new node is to be inserted, the node that has failed
// 	the most times is replaced. If none of the nodes in the
// 	bucket has failed, then it is put in the replacement
// 	cache (just like in the paper).

class TORRENT_EXPORT routing_table
{
public:
	routing_table(node_id const& id, int bucket_size
		, dht_settings const& settings);

	void status(session_status& s) const;

	void node_failed(node_id const& id);

	// adds an endpoint that will never be added to
	// the routing table
	void add_router_node(udp::endpoint router);

	// iterates over the router nodes added
	typedef std::set<udp::endpoint>::const_iterator router_iterator;
	router_iterator router_begin() const { return m_router_nodes.begin(); }
	router_iterator router_end() const { return m_router_nodes.end(); }

	bool add_node(node_entry const& e);

	// this function is called every time the node sees
	// a sign of a node being alive. This node will either
	// be inserted in the k-buckets or be moved to the top
	// of its bucket.
	bool node_seen(node_id const& id, udp::endpoint ep);

	// this may add a node to the routing table and mark it as
	// not pinged. If the bucket the node falls into is full,
	// the node will be ignored.
	void heard_about(node_id const& id, udp::endpoint const& ep);

	// if any bucket in the routing table needs to be refreshed
	// this function will return true and set the target to an
	// appropriate target inside that bucket
	bool need_refresh(node_id& target) const;

	enum
	{
		include_failed = 1
	};
	// fills the vector with the count nodes from our buckets that
	// are nearest to the given id.
	void find_node(node_id const& id, std::vector<node_entry>& l
		, int options, int count = 0);

	int bucket_size(int bucket)
	{
		int num_buckets = m_buckets.size();
		if (bucket < num_buckets) bucket = num_buckets - 1;
		table_t::iterator i = m_buckets.begin();
		std::advance(i, bucket);
		return (int)i->live_nodes.size();
	}

	void for_each_node(void (*)(void*, node_entry const&)
		, void (*)(void*, node_entry const&), void* userdata) const;

	int bucket_size() const { return m_bucket_size; }

	boost::tuple<int, int> size() const;
	size_type num_global_nodes() const;

	// returns true if there are no working nodes
	// in the routing table
	bool need_bootstrap() const;
	int num_active_buckets() const { return m_buckets.size(); }

	void replacement_cache(bucket_t& nodes) const;

#if defined TORRENT_DHT_VERBOSE_LOGGING || defined TORRENT_DEBUG
	// used for debug and monitoring purposes. This will print out
	// the state of the routing table to the given stream
	void print_state(std::ostream& os) const;
#endif

	void touch_bucket(node_id const& target);

private:

	typedef std::list<routing_table_node> table_t;

	table_t::iterator find_bucket(node_id const& id);

	// constant called k in paper
	int m_bucket_size;

	dht_settings const& m_settings;

	// (k-bucket, replacement cache) pairs
	// the first entry is the bucket the furthest
	// away from our own ID. Each time the bucket
	// closest to us (m_buckets.back()) has more than
	// bucket size nodes in it, another bucket is
	// added to the end and it's split up between them
	table_t m_buckets;

	node_id m_id; // our own node id

	// the last time need_bootstrap() returned true
	mutable ptime m_last_bootstrap;

	// this is a set of all the endpoints that have
	// been identified as router nodes. They will
	// be used in searches, but they will never
	// be added to the routing table.
	std::set<udp::endpoint> m_router_nodes;
};

} } // namespace libtorrent::dht

#endif // ROUTING_TABLE_HPP

<commit_msg>added missing include<commit_after>/*

Copyright (c) 2006, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef ROUTING_TABLE_HPP
#define ROUTING_TABLE_HPP

#include <vector>
#include <boost/cstdint.hpp>

#include <boost/utility.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/array.hpp>
#include <set>
#include <list>

#include <libtorrent/kademlia/logging.hpp>

#include <libtorrent/kademlia/node_id.hpp>
#include <libtorrent/kademlia/node_entry.hpp>
#include <libtorrent/session_settings.hpp>
#include <libtorrent/size_type.hpp>
#include <libtorrent/assert.hpp>
#include <libtorrent/ptime.hpp>

namespace libtorrent
{
	struct session_status;
}

namespace libtorrent { namespace dht
{

#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DECLARE_LOG(table);
#endif

typedef std::vector<node_entry> bucket_t;

struct routing_table_node
{
	bucket_t replacements;
	bucket_t live_nodes;
	ptime last_active;
};

// differences in the implementation from the description in
// the paper:
//
// * Nodes are not marked as being stale, they keep a counter
// 	that tells how many times in a row they have failed. When
// 	a new node is to be inserted, the node that has failed
// 	the most times is replaced. If none of the nodes in the
// 	bucket has failed, then it is put in the replacement
// 	cache (just like in the paper).

class TORRENT_EXPORT routing_table
{
public:
	routing_table(node_id const& id, int bucket_size
		, dht_settings const& settings);

	void status(session_status& s) const;

	void node_failed(node_id const& id);

	// adds an endpoint that will never be added to
	// the routing table
	void add_router_node(udp::endpoint router);

	// iterates over the router nodes added
	typedef std::set<udp::endpoint>::const_iterator router_iterator;
	router_iterator router_begin() const { return m_router_nodes.begin(); }
	router_iterator router_end() const { return m_router_nodes.end(); }

	bool add_node(node_entry const& e);

	// this function is called every time the node sees
	// a sign of a node being alive. This node will either
	// be inserted in the k-buckets or be moved to the top
	// of its bucket.
	bool node_seen(node_id const& id, udp::endpoint ep);

	// this may add a node to the routing table and mark it as
	// not pinged. If the bucket the node falls into is full,
	// the node will be ignored.
	void heard_about(node_id const& id, udp::endpoint const& ep);

	// if any bucket in the routing table needs to be refreshed
	// this function will return true and set the target to an
	// appropriate target inside that bucket
	bool need_refresh(node_id& target) const;

	enum
	{
		include_failed = 1
	};
	// fills the vector with the count nodes from our buckets that
	// are nearest to the given id.
	void find_node(node_id const& id, std::vector<node_entry>& l
		, int options, int count = 0);

	int bucket_size(int bucket)
	{
		int num_buckets = m_buckets.size();
		if (bucket < num_buckets) bucket = num_buckets - 1;
		table_t::iterator i = m_buckets.begin();
		std::advance(i, bucket);
		return (int)i->live_nodes.size();
	}

	void for_each_node(void (*)(void*, node_entry const&)
		, void (*)(void*, node_entry const&), void* userdata) const;

	int bucket_size() const { return m_bucket_size; }

	boost::tuple<int, int> size() const;
	size_type num_global_nodes() const;

	// returns true if there are no working nodes
	// in the routing table
	bool need_bootstrap() const;
	int num_active_buckets() const { return m_buckets.size(); }

	void replacement_cache(bucket_t& nodes) const;

#if defined TORRENT_DHT_VERBOSE_LOGGING || defined TORRENT_DEBUG
	// used for debug and monitoring purposes. This will print out
	// the state of the routing table to the given stream
	void print_state(std::ostream& os) const;
#endif

	void touch_bucket(node_id const& target);

private:

	typedef std::list<routing_table_node> table_t;

	table_t::iterator find_bucket(node_id const& id);

	// constant called k in paper
	int m_bucket_size;

	dht_settings const& m_settings;

	// (k-bucket, replacement cache) pairs
	// the first entry is the bucket the furthest
	// away from our own ID. Each time the bucket
	// closest to us (m_buckets.back()) has more than
	// bucket size nodes in it, another bucket is
	// added to the end and it's split up between them
	table_t m_buckets;

	node_id m_id; // our own node id

	// the last time need_bootstrap() returned true
	mutable ptime m_last_bootstrap;

	// this is a set of all the endpoints that have
	// been identified as router nodes. They will
	// be used in searches, but they will never
	// be added to the routing table.
	std::set<udp::endpoint> m_router_nodes;
};

} } // namespace libtorrent::dht

#endif // ROUTING_TABLE_HPP

<|endoftext|>


<commit_before>// Copyright (c) 2017 Sony Corporation. 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.

/** Batch Normalization
 */
#ifndef __NBLA_FUNCTION_BATCHNORM_HPP__
#define __NBLA_FUNCTION_BATCHNORM_HPP__

#include <nbla/cpu.hpp>
#include <nbla/function.hpp>
#include <nbla/function_registry.hpp>

#include <vector>

using std::vector;

namespace nbla {

NBLA_REGISTER_FUNCTION_HEADER(BatchNormalization, const vector<int> &, float,
                              float, bool);

/** Batch normalization at training time defined as
@f[
\begin{array}{lcl}
\mu &=& \frac{1}{M} \sum x_i\\
\sigma^2 &=& \frac{1}{M} \left(\sum x_i - \mu\right)^2\\
\hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}} \\
y_i &=& \hat{x}_i \gamma + \beta.
\end{array}
@f]
In testing, mean and variance computed by moving average calculated during
training are used.

Inputs:
- N-D array of input.
- N-D array of beta which is learned.
- N-D array of gamma which is learned.
- N-D array of running mean (modified during forward execution).
- N-D array of running variance (modified during forward execution).

Outputs (1 or 3):
- N-D array.
- (Optional) N-D array of running mean.
- (Optional) N-D array of running variance.

@tparam T Data type for computation.

@param axes Axes mean and variance are taken.
@param decay_rate Decay rate of running mean and variance.
@param eps Tiny value to avoid zero division by std.
@param batch_stat Use mini-batch statistics rather than running ones.

@sa Ioffe and Szegedy, Batch Normalization: Accelerating Deep Network Training
by Reducing Internal Covariate Shift. https://arxiv.org/abs/1502.03167

\ingroup FunctionImplGrp
 */
template <typename T>
class BatchNormalization
    : public BaseFunction<const vector<int> &, float, float, bool> {
protected:
  vector<int> axes_;
  float decay_rate_;
  float eps_;
  bool batch_stat_;
  Variable mean_;
  Variable var_;
  int size0_, size1_, size2_, size02_, size12_;

public:
  BatchNormalization(const Context &ctx, const vector<int> axes,
                     float decay_rate, float eps, bool batch_stat)
      : BaseFunction(ctx, axes, decay_rate, eps, batch_stat), axes_(axes),
        decay_rate_(decay_rate), eps_(eps), batch_stat_(batch_stat) {}
  virtual ~BatchNormalization() {}
  virtual shared_ptr<Function> copy() const {
    return create_BatchNormalization(ctx_, axes_, decay_rate_, eps_,
                                     batch_stat_);
  }
  virtual vector<dtypes> in_types() {
    return vector<dtypes>{get_dtype<T>(), get_dtype<T>(), get_dtype<T>(),
                          get_dtype<T>(), get_dtype<T>()};
  }
  virtual vector<dtypes> out_types() {
    return vector<dtypes>{get_dtype<T>(), get_dtype<T>(), get_dtype<T>()};
  }
  virtual int min_inputs() { return 5; }
  virtual int min_outputs() { return 1; }
  virtual string name() { return "BatchNormalization"; }
  virtual vector<string> allowed_array_classes() {
    return SingletonManager::get<Cpu>()->array_classes();
  }
  virtual bool grad_depends_output_data(int i, int o) const {
    // Gradient computation always requires output mean and var.
    return o > 0;
  }

protected:
  NBLA_API virtual void setup_impl(const Variables &inputs,
                                   const Variables &outputs);
  NBLA_API virtual void forward_impl(const Variables &inputs,
                                     const Variables &outputs);
  NBLA_API virtual void backward_impl(const Variables &inputs,
                                      const Variables &outputs,
                                      const vector<bool> &propagate_down,
                                      const vector<bool> &accum);
  NBLA_API virtual void forward_impl_batch(const Variables &inputs,
                                           const Variables &outputs);
  NBLA_API virtual void forward_impl_global(const Variables &inputs,
                                            const Variables &outputs);
  NBLA_API virtual void backward_impl_batch(const Variables &inputs,
                                            const Variables &outputs,
                                            const vector<bool> &propagate_down,
                                            const vector<bool> &accum);
};
}
#endif
<commit_msg>fix comments in BatchNormalization function<commit_after>// Copyright (c) 2017 Sony Corporation. 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.

/** Batch Normalization
 */
#ifndef __NBLA_FUNCTION_BATCHNORM_HPP__
#define __NBLA_FUNCTION_BATCHNORM_HPP__

#include <nbla/cpu.hpp>
#include <nbla/function.hpp>
#include <nbla/function_registry.hpp>

#include <vector>

using std::vector;

namespace nbla {

NBLA_REGISTER_FUNCTION_HEADER(BatchNormalization, const vector<int> &, float,
                              float, bool);

/** Batch normalization at training time defined as
@f[
\begin{array}{lcl}
\mu &=& \frac{1}{M} \sum x_i\\
\sigma^2 &=& \frac{1}{M} \left(\sum x_i - \mu\right)^2\\
\hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}} \\
y_i &=& \hat{x}_i \gamma + \beta.
\end{array}
@f]
In testing, mean and variance computed by moving average calculated during
training are used.

Inputs:
- N-D array of input.
- N-D array of beta which is learned.
- N-D array of gamma which is learned.
- N-D array of running mean (modified during forward execution).
- N-D array of running variance (modified during forward execution).

Outputs (1 or 3):
- N-D array.
- (Optional) N-D array of batch mean.
- (Optional) N-D array of batch variance.

@tparam T Data type for computation.

@param axes Axes mean and variance are taken.
@param decay_rate Decay rate of running mean and variance.
@param eps Tiny value to avoid zero division by std.
@param batch_stat Use mini-batch statistics rather than running ones.

@sa Ioffe and Szegedy, Batch Normalization: Accelerating Deep Network Training
by Reducing Internal Covariate Shift. https://arxiv.org/abs/1502.03167

\ingroup FunctionImplGrp
 */
template <typename T>
class BatchNormalization
    : public BaseFunction<const vector<int> &, float, float, bool> {
protected:
  vector<int> axes_;
  float decay_rate_;
  float eps_;
  bool batch_stat_;
  Variable mean_;
  Variable var_;
  int size0_, size1_, size2_, size02_, size12_;

public:
  BatchNormalization(const Context &ctx, const vector<int> axes,
                     float decay_rate, float eps, bool batch_stat)
      : BaseFunction(ctx, axes, decay_rate, eps, batch_stat), axes_(axes),
        decay_rate_(decay_rate), eps_(eps), batch_stat_(batch_stat) {}
  virtual ~BatchNormalization() {}
  virtual shared_ptr<Function> copy() const {
    return create_BatchNormalization(ctx_, axes_, decay_rate_, eps_,
                                     batch_stat_);
  }
  virtual vector<dtypes> in_types() {
    return vector<dtypes>{get_dtype<T>(), get_dtype<T>(), get_dtype<T>(),
                          get_dtype<T>(), get_dtype<T>()};
  }
  virtual vector<dtypes> out_types() {
    return vector<dtypes>{get_dtype<T>(), get_dtype<T>(), get_dtype<T>()};
  }
  virtual int min_inputs() { return 5; }
  virtual int min_outputs() { return 1; }
  virtual string name() { return "BatchNormalization"; }
  virtual vector<string> allowed_array_classes() {
    return SingletonManager::get<Cpu>()->array_classes();
  }
  virtual bool grad_depends_output_data(int i, int o) const {
    // Gradient computation always requires output mean and var.
    return o > 0;
  }

protected:
  NBLA_API virtual void setup_impl(const Variables &inputs,
                                   const Variables &outputs);
  NBLA_API virtual void forward_impl(const Variables &inputs,
                                     const Variables &outputs);
  NBLA_API virtual void backward_impl(const Variables &inputs,
                                      const Variables &outputs,
                                      const vector<bool> &propagate_down,
                                      const vector<bool> &accum);
  NBLA_API virtual void forward_impl_batch(const Variables &inputs,
                                           const Variables &outputs);
  NBLA_API virtual void forward_impl_global(const Variables &inputs,
                                            const Variables &outputs);
  NBLA_API virtual void backward_impl_batch(const Variables &inputs,
                                            const Variables &outputs,
                                            const vector<bool> &propagate_down,
                                            const vector<bool> &accum);
};
}
#endif
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program 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 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 Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
/******************************************************************************
 * Contributors:
 *     - damien.marchal@univ-lille1.fr
 *****************************************************************************/

#include <sofa/simulation/Node.h>
using sofa::simulation::Node ;

#include <SofaSimulationGraph/testing/BaseSimulationTest.h>
using sofa::helper::testing::BaseSimulationTest ;
using sofa::simulation::Node ;

using sofa::core::visual::VisualModel ;

class NodeContext_test: public BaseSimulationTest
{
public:

    void testGetNodeObjects()
    {
        std::stringstream scene ;
        scene << "<?xml version='1.0'?>"
                 "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' >               \n"
                 "   <OglModel/>                                                             \n"
                 "   <Node name='child1'>                                                    \n"
                 "      <OglModel/>                                                          \n"
                 "      <OglModel/>                                                          \n"
                 "      <MechanicalObject />                                                 \n"
                 "      <Node name='child2'>                                                 \n"
                 "          <OglModel/>                                                      \n"
                 "          <OglModel/>                                                      \n"
                 "      </Node>                                                              \n"
                 "   </Node>                                                                 \n"
                 "</Node>                                                                    \n" ;

        SceneInstance c("xml", scene.str()) ;
        c.initScene() ;

        Node* m_root = c.root.get() ;
        ASSERT_NE(m_root, nullptr) ;

        EXPECT_MSG_NOEMIT(Error, Warning) ;
        Node* node =m_root->getChild("child1") ;

        /// Query a specific model in a container, this is the old API
        std::vector<VisualModel*> results ;
        node->getNodeObjects<VisualModel, std::vector<VisualModel*> >( &results ) ;
        ASSERT_EQ( results.size() , (unsigned int)2 ) ;

        /// Query a specific model with a nicer syntax
        std::vector<VisualModel*> results2 ;
        ASSERT_EQ( node->getNodeObjects(results2).size(), (unsigned int)2 ) ;

        /// Query a specific model with a nicer syntax
        std::vector<VisualModel*> results3 ;
        ASSERT_EQ( node->getNodeObjects(&results3)->size(), (unsigned int)2 ) ;

        /// Query a specific model with a compact syntax, this returns std::vector<BaseObject*>
        /// So there is 4 base object in the scene.
        for(auto& m : node->getNodeObjects() ) { SOFA_UNUSED(m); }
        ASSERT_EQ( node->getNodeObjects().size(), (unsigned int)3 ) ;
    }

    void testGetTreeObjects()
    {
        std::stringstream scene ;
        scene << "<?xml version='1.0'?>"
                 "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' >               \n"
                 "   <OglModel/>                                                             \n"
                 "   <Node name='child1'>                                                    \n"
                 "      <OglModel/>                                                          \n"
                 "      <OglModel/>                                                          \n"
                 "      <MechanicalObject />                                                 \n"
                 "      <Node name='child2'>                                                 \n"
                 "          <OglModel/>                                                      \n"
                 "          <OglModel/>                                                      \n"
                 "      </Node>                                                              \n"
                 "   </Node>                                                                 \n"
                 "</Node>                                                                    \n" ;

        SceneInstance c("xml", scene.str()) ;
        c.initScene() ;

        Node* m_root = c.root.get() ;
        ASSERT_NE(m_root, nullptr) ;

        EXPECT_MSG_NOEMIT(Error, Warning) ;
        Node* node =m_root->getChild("child1") ;

        /// Query a specific model in a container, this is the old API
        std::vector<VisualModel*> results ;
        node->getTreeObjects<VisualModel, std::vector<VisualModel*> >( &results ) ;
        ASSERT_EQ( results.size() , (unsigned int)4  ) ;

        /// Query a specific model with a nicer syntax
        std::vector<VisualModel*> results2 ;
        ASSERT_EQ( node->getTreeObjects(results2).size(), (unsigned int)4 ) ;

        /// Query a specific model with a nicer syntax
        std::vector<VisualModel*> results3 ;
        ASSERT_EQ( node->getTreeObjects(&results3)->size(), (unsigned int)4 ) ;

        /// Query a specific model with a compact syntax, this returns std::vector<BaseObject*>
        /// So there is 4 base object in the scene.
        for(auto& m : node->getTreeObjects() ) { SOFA_UNUSED(m); }
        ASSERT_EQ( node->getTreeObjects().size(), (unsigned int)5 ) ;
    }
};

TEST_F(NodeContext_test , testGetNodeObjects )
{
    this->testGetNodeObjects();
}

TEST_F(NodeContext_test , testGetTreeObjects )
{
    this->testGetTreeObjects();
}
<commit_msg>[SofaKernel/frameworkextra_test] Fix test to correctly load the required plugin<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program 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 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 Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
/******************************************************************************
 * Contributors:
 *     - damien.marchal@univ-lille1.fr
 *****************************************************************************/

#include <sofa/simulation/Node.h>
using sofa::simulation::Node ;

#include <SofaSimulationGraph/testing/BaseSimulationTest.h>
using sofa::helper::testing::BaseSimulationTest ;
using sofa::simulation::Node ;

using sofa::core::visual::VisualModel ;

#include <sofa/helper/system/PluginManager.h>
using sofa::helper::system::PluginManager ;

class NodeContext_test: public BaseSimulationTest
{
public:

    NodeContext_test()
    {
        importPlugin("SofaAllCommonComponents") ;
    }

    void testGetNodeObjects()
    {
        std::stringstream scene ;
        scene << "<?xml version='1.0'?>"
                 "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' >               \n"
                 "   <OglModel/>                                                             \n"
                 "   <Node name='child1'>                                                    \n"
                 "      <OglModel/>                                                          \n"
                 "      <OglModel/>                                                          \n"
                 "      <MechanicalObject />                                                 \n"
                 "      <Node name='child2'>                                                 \n"
                 "          <OglModel/>                                                      \n"
                 "          <OglModel/>                                                      \n"
                 "      </Node>                                                              \n"
                 "   </Node>                                                                 \n"
                 "</Node>                                                                    \n" ;

        SceneInstance c("xml", scene.str()) ;
        c.initScene() ;

        Node* m_root = c.root.get() ;
        ASSERT_NE(m_root, nullptr) ;

        EXPECT_MSG_NOEMIT(Error, Warning) ;
        Node* node =m_root->getChild("child1") ;

        /// Query a specific model in a container, this is the old API
        std::vector<VisualModel*> results ;
        node->getNodeObjects<VisualModel, std::vector<VisualModel*> >( &results ) ;
        ASSERT_EQ( results.size() , (unsigned int)2 ) ;

        /// Query a specific model with a nicer syntax
        std::vector<VisualModel*> results2 ;
        ASSERT_EQ( node->getNodeObjects(results2).size(), (unsigned int)2 ) ;

        /// Query a specific model with a nicer syntax
        std::vector<VisualModel*> results3 ;
        ASSERT_EQ( node->getNodeObjects(&results3)->size(), (unsigned int)2 ) ;

        /// Query a specific model with a compact syntax, this returns std::vector<BaseObject*>
        /// So there is 4 base object in the scene.
        for(auto& m : node->getNodeObjects() ) { SOFA_UNUSED(m); }
        ASSERT_EQ( node->getNodeObjects().size(), (unsigned int)3 ) ;
    }

    void testGetTreeObjects()
    {
        std::stringstream scene ;
        scene << "<?xml version='1.0'?>"
                 "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' >               \n"
                 "   <OglModel/>                                                             \n"
                 "   <Node name='child1'>                                                    \n"
                 "      <OglModel/>                                                          \n"
                 "      <OglModel/>                                                          \n"
                 "      <MechanicalObject />                                                 \n"
                 "      <Node name='child2'>                                                 \n"
                 "          <OglModel/>                                                      \n"
                 "          <OglModel/>                                                      \n"
                 "      </Node>                                                              \n"
                 "   </Node>                                                                 \n"
                 "</Node>                                                                    \n" ;

        SceneInstance c("xml", scene.str()) ;
        c.initScene() ;

        Node* m_root = c.root.get() ;
        ASSERT_NE(m_root, nullptr) ;

        EXPECT_MSG_NOEMIT(Error, Warning) ;
        Node* node =m_root->getChild("child1") ;

        /// Query a specific model in a container, this is the old API
        std::vector<VisualModel*> results ;
        node->getTreeObjects<VisualModel, std::vector<VisualModel*> >( &results ) ;
        ASSERT_EQ( results.size() , (unsigned int)4  ) ;

        /// Query a specific model with a nicer syntax
        std::vector<VisualModel*> results2 ;
        ASSERT_EQ( node->getTreeObjects(results2).size(), (unsigned int)4 ) ;

        /// Query a specific model with a nicer syntax
        std::vector<VisualModel*> results3 ;
        ASSERT_EQ( node->getTreeObjects(&results3)->size(), (unsigned int)4 ) ;

        /// Query a specific model with a compact syntax, this returns std::vector<BaseObject*>
        /// So there is 4 base object in the scene.
        for(auto& m : node->getTreeObjects() ) { SOFA_UNUSED(m); }
        ASSERT_EQ( node->getTreeObjects().size(), (unsigned int)5 ) ;
    }
};

TEST_F(NodeContext_test , testGetNodeObjects )
{
    this->testGetNodeObjects();
}

TEST_F(NodeContext_test , testGetTreeObjects )
{
    this->testGetTreeObjects();
}
<|endoftext|>


<commit_before>#include "Vajra/Engine/AssetLibrary/AssetLibrary.h"
#include "Vajra/Engine/Components/DerivedComponents/Renderer/WaterRenderer.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/Timer/Timer.h"
#include "Vajra/Framework/OpenGL/OpenGLWrapper/OpenGLWrapper.h"
#include "Vajra/Framework/OpenGL/ShaderSet/ShaderSet.h"

WaterRenderer::WaterRenderer() : MeshRenderer() {
	this->init();
}

WaterRenderer::WaterRenderer(Object* object_) : MeshRenderer(object_)  {
	this->init();
}

WaterRenderer::~WaterRenderer() {
	this->destroy();
}

void WaterRenderer::InitMesh(std::string urlOfMesh) {
	MeshRenderer::InitMesh(urlOfMesh);
}

void WaterRenderer::SetScrollingUVs(float uvScrollSpeed) {
	this->scrollingUVs_speed = uvScrollSpeed;
}

void WaterRenderer::SetSecondaryTexture(std::string pathToTexture) {
	this->secondaryTexture = ENGINE->GetAssetLibrary()->GetAsset<TextureAsset>(pathToTexture);
}

void WaterRenderer::HandleMessage(MessageChunk messageChunk) {
	MeshRenderer::HandleMessage(messageChunk);

	switch (messageChunk->GetMessageType()) {
	case MESSAGE_TYPE_FRAME_EVENT: {
		this->scrollUVs();
	} break;

	default : {
	} break;
	}
}

void WaterRenderer::Draw() {
	ShaderSet* currentShaderSet = FRAMEWORK->GetOpenGLWrapper()->GetCurrentShaderSet();
	if (currentShaderSet->HasHandle(SHADER_VARIABLE_VARIABLENAME_scrolling_uv_offset)) {
		GLint scrolling_uv_offset_handle = currentShaderSet->GetHandle(SHADER_VARIABLE_VARIABLENAME_scrolling_uv_offset);
		GLCALL(glUniform1f, scrolling_uv_offset_handle, this->scrollingUVsOffset);
	}

	if (this->secondaryTexture) {
		this->secondaryTexture->Draw(2);
	}

	MeshRenderer::Draw();

}

void WaterRenderer::scrollUVs() {
	this->scrollingUVsOffset += this->scrollingUVs_speed * ENGINE->GetTimer()->GetDeltaFrameTime();
	// TODO [Hack] Don't blow floating point limit
	if (this->scrollingUVsOffset > 100000.0f) {
		this->scrollingUVsOffset -= 100000.0f;
	}
}

void WaterRenderer::init() {
	this->scrollingUVsOffset  = 0.0f;

	this->scrollingUVs_speed  = 0.1f;

	this->SetPreventCulling(true);

	this->addSubscriptionToMessageType(MESSAGE_TYPE_FRAME_EVENT, this->GetTypeId(), false);
}

void WaterRenderer::destroy() {
	this->removeSubscriptionToAllMessageTypes(this->GetTypeId());
}

<commit_msg>Fix that scrolling water texture thing, for reals.<commit_after>#include "Vajra/Engine/AssetLibrary/AssetLibrary.h"
#include "Vajra/Engine/Components/DerivedComponents/Renderer/WaterRenderer.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/Timer/Timer.h"
#include "Vajra/Framework/OpenGL/OpenGLWrapper/OpenGLWrapper.h"
#include "Vajra/Framework/OpenGL/ShaderSet/ShaderSet.h"

WaterRenderer::WaterRenderer() : MeshRenderer() {
	this->init();
}

WaterRenderer::WaterRenderer(Object* object_) : MeshRenderer(object_)  {
	this->init();
}

WaterRenderer::~WaterRenderer() {
	this->destroy();
}

void WaterRenderer::InitMesh(std::string urlOfMesh) {
	MeshRenderer::InitMesh(urlOfMesh);
}

void WaterRenderer::SetScrollingUVs(float uvScrollSpeed) {
	this->scrollingUVs_speed = uvScrollSpeed;
}

void WaterRenderer::SetSecondaryTexture(std::string pathToTexture) {
	this->secondaryTexture = ENGINE->GetAssetLibrary()->GetAsset<TextureAsset>(pathToTexture);
}

void WaterRenderer::HandleMessage(MessageChunk messageChunk) {
	MeshRenderer::HandleMessage(messageChunk);

	switch (messageChunk->GetMessageType()) {
	case MESSAGE_TYPE_FRAME_EVENT: {
		this->scrollUVs();
	} break;

	default : {
	} break;
	}
}

void WaterRenderer::Draw() {
	ShaderSet* currentShaderSet = FRAMEWORK->GetOpenGLWrapper()->GetCurrentShaderSet();
	if (currentShaderSet->HasHandle(SHADER_VARIABLE_VARIABLENAME_scrolling_uv_offset)) {
		GLint scrolling_uv_offset_handle = currentShaderSet->GetHandle(SHADER_VARIABLE_VARIABLENAME_scrolling_uv_offset);
		GLCALL(glUniform1f, scrolling_uv_offset_handle, this->scrollingUVsOffset);
	}

	if (this->secondaryTexture) {
		this->secondaryTexture->Draw(2);
	}

	MeshRenderer::Draw();

}

void WaterRenderer::scrollUVs() {
	this->scrollingUVsOffset += this->scrollingUVs_speed * ENGINE->GetTimer()->GetDeltaFrameTime();
	// TODO [Hack] Don't blow floating point limit
	if (this->scrollingUVsOffset > 1.0f) {
		this->scrollingUVsOffset -= 1.0f;
	}
}

void WaterRenderer::init() {
	this->scrollingUVsOffset  = 0.0f;

	this->scrollingUVs_speed  = 0.1f;

	this->SetPreventCulling(true);

	this->addSubscriptionToMessageType(MESSAGE_TYPE_FRAME_EVENT, this->GetTypeId(), false);
}

void WaterRenderer::destroy() {
	this->removeSubscriptionToAllMessageTypes(this->GetTypeId());
}

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkAxes.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 "vtkAxes.h"

#include "vtkCellArray.h"
#include "vtkFloatArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"

vtkCxxRevisionMacro(vtkAxes, "1.44");
vtkStandardNewMacro(vtkAxes);

// Construct with origin=(0,0,0) and scale factor=1.
vtkAxes::vtkAxes()
{
  this->Origin[0] = 0.0;
  this->Origin[1] = 0.0;
  this->Origin[2] = 0.0;

  this->ScaleFactor = 1.0;

  this->Symmetric = 0;
  this->ComputeNormals = 1;

  this->SetNumberOfInputPorts(0);
}

int vtkAxes::RequestData(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **vtkNotUsed(inputVector),
  vtkInformationVector *outputVector)
{
  // get the info object
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  // get the ouptut
  vtkPolyData *output = vtkPolyData::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));

  int numPts=6, numLines=3;
  vtkPoints *newPts;
  vtkCellArray *newLines;
  vtkFloatArray *newScalars;
  vtkFloatArray *newNormals;
  double x[3], n[3];
  vtkIdType ptIds[2];

  vtkDebugMacro(<<"Creating x-y-z axes");

  newPts = vtkPoints::New();
  newPts->Allocate(numPts);
  newLines = vtkCellArray::New();
  newLines->Allocate(newLines->EstimateSize(numLines,2));
  newScalars = vtkFloatArray::New();
  newScalars->Allocate(numPts);
  newScalars->SetName("Axes");
  newNormals = vtkFloatArray::New();
  newNormals->SetNumberOfComponents(3);
  newNormals->Allocate(numPts);
  newNormals->SetName("Normals");

//
// Create axes
//
  x[0] = this->Origin[0];
  x[1] = this->Origin[1];
  x[2] = this->Origin[2];
  if (this->Symmetric)
    {
    x[0] = this->Origin[0] - this->ScaleFactor;
    }
  n[0] = 0.0; n[1] = 1.0; n[2] = 0.0;
  ptIds[0] = newPts->InsertNextPoint(x);
  newScalars->InsertNextValue(0.0);
  newNormals->InsertNextTuple(n);

  x[0] = this->Origin[0] + this->ScaleFactor;
  x[1] = this->Origin[1];
  x[2] = this->Origin[2];
  ptIds[1] = newPts->InsertNextPoint(x);
  newLines->InsertNextCell(2,ptIds);
  newScalars->InsertNextValue(0.0);
  newNormals->InsertNextTuple(n);

  x[0] = this->Origin[0];
  x[1] = this->Origin[1];
  x[2] = this->Origin[2];
  if (this->Symmetric)
    {
    x[1] = this->Origin[1] - this->ScaleFactor;
    }
  n[0] = 0.0; n[1] = 0.0; n[2] = 1.0;
  ptIds[0] = newPts->InsertNextPoint(x);
  newScalars->InsertNextValue(0.25);
  newNormals->InsertNextTuple(n);

  x[0] = this->Origin[0];
  x[1] = this->Origin[1] + this->ScaleFactor;
  x[2] = this->Origin[2];
  ptIds[1] = newPts->InsertNextPoint(x);
  newScalars->InsertNextValue(0.25);
  newNormals->InsertNextTuple(n);
  newLines->InsertNextCell(2,ptIds);

  x[0] = this->Origin[0];
  x[1] = this->Origin[1];
  x[2] = this->Origin[2];
  if (this->Symmetric)
    {
    x[2] = this->Origin[2] - this->ScaleFactor;
    }
  n[0] = 1.0; n[1] = 0.0; n[2] = 0.0;
  ptIds[0] = newPts->InsertNextPoint(x);
  newScalars->InsertNextValue(0.5);
  newNormals->InsertNextTuple(n);

  x[0] = this->Origin[0];
  x[1] = this->Origin[1];
  x[2] = this->Origin[2] + this->ScaleFactor;
  ptIds[1] = newPts->InsertNextPoint(x);
  newScalars->InsertNextValue(0.5);
  newNormals->InsertNextTuple(n);
  newLines->InsertNextCell(2,ptIds);

  //
  // Update our output and release memory
  //
  output->SetPoints(newPts);
  newPts->Delete();

  output->GetPointData()->SetScalars(newScalars);
  newScalars->Delete();

  if (this->ComputeNormals)
    {
    output->GetPointData()->SetNormals(newNormals);
    }
  newNormals->Delete();

  output->SetLines(newLines);
  newLines->Delete();

  return 1;
}

//----------------------------------------------------------------------------
// This source does not know how to generate pieces yet.
int vtkAxes::ComputeDivisionExtents(vtkDataObject *vtkNotUsed(output),
                                      int idx, int numDivisions)
{
  if (idx == 0 && numDivisions == 1)
    {
    // I will give you the whole thing
    return 1;
    }
  else
    {
    // I have nothing to give you for this piece.
    return 0;
    }
}

void vtkAxes::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << "Origin: (" << this->Origin[0] << ", "
               << this->Origin[1] << ", "
               << this->Origin[2] << ")\n";
  os << indent << "Scale Factor: " << this->ScaleFactor << "\n";
  os << indent << "Symmetric: " << this->Symmetric << "\n";
  os << indent << "ComputeNormals: " << this->ComputeNormals << "\n";
}
<commit_msg>STYLE: minor style fix<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkAxes.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 "vtkAxes.h"

#include "vtkCellArray.h"
#include "vtkFloatArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"

vtkCxxRevisionMacro(vtkAxes, "1.45");
vtkStandardNewMacro(vtkAxes);

//----------------------------------------------------------------------------
// Construct with origin=(0,0,0) and scale factor=1.
vtkAxes::vtkAxes()
{
  this->Origin[0] = 0.0;
  this->Origin[1] = 0.0;
  this->Origin[2] = 0.0;

  this->ScaleFactor = 1.0;

  this->Symmetric = 0;
  this->ComputeNormals = 1;

  this->SetNumberOfInputPorts(0);
}

int vtkAxes::RequestData(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **vtkNotUsed(inputVector),
  vtkInformationVector *outputVector)
{
  // get the info object
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  // get the ouptut
  vtkPolyData *output = vtkPolyData::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));

  int numPts=6, numLines=3;
  vtkPoints *newPts;
  vtkCellArray *newLines;
  vtkFloatArray *newScalars;
  vtkFloatArray *newNormals;
  double x[3], n[3];
  vtkIdType ptIds[2];

  vtkDebugMacro(<<"Creating x-y-z axes");

  newPts = vtkPoints::New();
  newPts->Allocate(numPts);
  newLines = vtkCellArray::New();
  newLines->Allocate(newLines->EstimateSize(numLines,2));
  newScalars = vtkFloatArray::New();
  newScalars->Allocate(numPts);
  newScalars->SetName("Axes");
  newNormals = vtkFloatArray::New();
  newNormals->SetNumberOfComponents(3);
  newNormals->Allocate(numPts);
  newNormals->SetName("Normals");

//
// Create axes
//
  x[0] = this->Origin[0];
  x[1] = this->Origin[1];
  x[2] = this->Origin[2];
  if (this->Symmetric)
    {
    x[0] = this->Origin[0] - this->ScaleFactor;
    }
  n[0] = 0.0; n[1] = 1.0; n[2] = 0.0;
  ptIds[0] = newPts->InsertNextPoint(x);
  newScalars->InsertNextValue(0.0);
  newNormals->InsertNextTuple(n);

  x[0] = this->Origin[0] + this->ScaleFactor;
  x[1] = this->Origin[1];
  x[2] = this->Origin[2];
  ptIds[1] = newPts->InsertNextPoint(x);
  newLines->InsertNextCell(2,ptIds);
  newScalars->InsertNextValue(0.0);
  newNormals->InsertNextTuple(n);

  x[0] = this->Origin[0];
  x[1] = this->Origin[1];
  x[2] = this->Origin[2];
  if (this->Symmetric)
    {
    x[1] = this->Origin[1] - this->ScaleFactor;
    }
  n[0] = 0.0; n[1] = 0.0; n[2] = 1.0;
  ptIds[0] = newPts->InsertNextPoint(x);
  newScalars->InsertNextValue(0.25);
  newNormals->InsertNextTuple(n);

  x[0] = this->Origin[0];
  x[1] = this->Origin[1] + this->ScaleFactor;
  x[2] = this->Origin[2];
  ptIds[1] = newPts->InsertNextPoint(x);
  newScalars->InsertNextValue(0.25);
  newNormals->InsertNextTuple(n);
  newLines->InsertNextCell(2,ptIds);

  x[0] = this->Origin[0];
  x[1] = this->Origin[1];
  x[2] = this->Origin[2];
  if (this->Symmetric)
    {
    x[2] = this->Origin[2] - this->ScaleFactor;
    }
  n[0] = 1.0; n[1] = 0.0; n[2] = 0.0;
  ptIds[0] = newPts->InsertNextPoint(x);
  newScalars->InsertNextValue(0.5);
  newNormals->InsertNextTuple(n);

  x[0] = this->Origin[0];
  x[1] = this->Origin[1];
  x[2] = this->Origin[2] + this->ScaleFactor;
  ptIds[1] = newPts->InsertNextPoint(x);
  newScalars->InsertNextValue(0.5);
  newNormals->InsertNextTuple(n);
  newLines->InsertNextCell(2,ptIds);

  //
  // Update our output and release memory
  //
  output->SetPoints(newPts);
  newPts->Delete();

  output->GetPointData()->SetScalars(newScalars);
  newScalars->Delete();

  if (this->ComputeNormals)
    {
    output->GetPointData()->SetNormals(newNormals);
    }
  newNormals->Delete();

  output->SetLines(newLines);
  newLines->Delete();

  return 1;
}

//----------------------------------------------------------------------------
// This source does not know how to generate pieces yet.
int vtkAxes::ComputeDivisionExtents(vtkDataObject *vtkNotUsed(output),
                                      int idx, int numDivisions)
{
  if (idx == 0 && numDivisions == 1)
    {
    // I will give you the whole thing
    return 1;
    }
  else
    {
    // I have nothing to give you for this piece.
    return 0;
    }
}

//----------------------------------------------------------------------------
void vtkAxes::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << "Origin: (" << this->Origin[0] << ", "
               << this->Origin[1] << ", "
               << this->Origin[2] << ")\n";
  os << indent << "Scale Factor: " << this->ScaleFactor << "\n";
  os << indent << "Symmetric: " << this->Symmetric << "\n";
  os << indent << "ComputeNormals: " << this->ComputeNormals << "\n";
}
<|endoftext|>