<commit_before>
#include "potentialfunctioncbspl.h"

PotentialFunctionCBSPL::PotentialFunctionCBSPL(const int nlam_,
        const int ncutcoeff_, const double min_, const double max_) :
                        PotentialFunction(nlam_,min_,max_) {

    /* Here nlam_ is the total number of coeff values that are to be optimized
     * To ensure that potential and force go to zero smoothly near cut-off,
     * as suggested in Ref. PCCP, 11, 1901, 2009, coeff values leading up to
     * cut-off and beyond take a value of zero.
     *
     * Since region less than rmin is not sampled sufficiently for stability
     * first _nexcl coefficients are not optimized instead their values are
     * extrapolated from first statistically significant knot values near rmin
     */

    // number of break points = _lam.size() - 2
    _nbreak = _lam.size() - 2;

     _dr = ( _cut_off )/( double (_nbreak - 1) );

    // break point locations
    // since ncoeff = nbreak +2 , r values for last two coefficients are also
    // computed
    _rbreak.resize(_lam.size(),false);

    _rbreak.clear();

    for( int i = 0; i < _lam.size(); i++)
        _rbreak(i) = i*_dr;

   // exclude knots corresponding to r <= _min
    _nexcl = min( int( ( _min )/_dr ), _nbreak - 2 ) + 1;

    // account for finite numerical division of _min/_dr
    // e.g. 0.24/0.02 may result in 11.99999999999999
    if( _rbreak(_nexcl) == _min ) _nexcl++;

    _ncutcoeff = ncutcoeff_;

    _M.resize(4,4,false);
    _M.clear();
    _M(0,0) =  1.0; _M(0,1) =  4.0; _M(0,2) =  1.0; _M(0,3) = 0.0;
    _M(1,0) = -3.0; _M(1,1) =  0.0; _M(1,2) =  3.0; _M(1,3) = 0.0;
    _M(2,0) =  3.0; _M(2,1) = -6.0; _M(2,2) =  3.0; _M(2,3) = 0.0;
    _M(3,0) = -1.0; _M(3,1) =  3.0; _M(3,2) = -3.0; _M(3,3) = 1.0;
    _M /= 6.0;

}

int PotentialFunctionCBSPL::getOptParamSize() const {

    return _lam.size() - _nexcl - _ncutcoeff;
}

void PotentialFunctionCBSPL::setParam(string filename) {

        Table param;
        param.Load(filename);

        _lam.clear();

        if( param.size() != _lam.size()) {

            throw std::runtime_error("Potential parameters size mismatch!\n"
                    "Check input parameter file \""
                    + filename + "\" \nThere should be "
                    + boost::lexical_cast<string>( _lam.size() ) + " parameters");
        } else {
            // force last _ncutcoeff to be zero
            for( int i = 0; i < _lam.size() - _ncutcoeff; i++){

                _rbreak(i) = param.x(i);
                _lam(i) = param.y(i);

            }

        }

    }

void PotentialFunctionCBSPL::SaveParam(const string& filename){

    extrapolExclParam();

    Table param;
    param.SetHasYErr(false);
    param.resize(_lam.size(), false);

    // write extrapolated knots with flag 'o'
    for (int i = 0; i < _nexcl; i++){

        param.set(i, _rbreak(i), _lam(i), 'o');
    }

    for (int i = _nexcl; i < _lam.size(); i++){

        param.set(i, _rbreak(i), _lam(i), 'i');
    }

    param.Save(filename);

}

void PotentialFunctionCBSPL::SavePotTab(const string& filename,
        const double step) {

    extrapolExclParam();
    PotentialFunction::SavePotTab(filename,step,0.0,_cut_off);

}

void PotentialFunctionCBSPL::extrapolExclParam(){

	// extrapolate first _nexcl knot values using exponential extrapolation
	// u(r) = a * exp( b * r)
	// a = u0 * exp ( - m * r0/u0 )
	// b = m/u0
	// m = (u1-u0)/(r1-r0)
	double u0 = _lam(_nexcl);
        if( u0 < 0.0 ) {
		throw std::runtime_error("min r value for cbspl is too large.\n"
                    "reference value for exponential extrapolation can not be negative");
	}
	double r0 = _rbreak(_nexcl);
	double m = (_lam(_nexcl + 1) - _lam(_nexcl)) /
	(_rbreak(_nexcl + 1) - _rbreak(_nexcl));
	double a = u0 * exp(-m * r0 / u0);
	double b = m / u0;
	for (int i = 0; i < _nexcl; i++) {
		double r = _rbreak(i);
		double u = a * exp(b * r);
		_lam(i) = u;
	}
}

void PotentialFunctionCBSPL::setOptParam(const int i, const double val){

    _lam( i + _nexcl ) = val;

}

double PotentialFunctionCBSPL::getOptParam(const int i) const{

    return _lam( i + _nexcl );

}

double PotentialFunctionCBSPL::CalculateF (const double r) const {

    if( r <= _cut_off){

        ub::vector<double> R;
        ub::vector<double> B;

        int indx = min( int( r /_dr ) , _nbreak-2 );

        double rk = indx*_dr;

        double t = ( r - rk)/_dr;

        R.resize(4,false); R.clear();

        R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t;

        ub::vector<double> RM = ub::prod(R,_M);

        B.resize(4,false); B.clear();

        B(0) = _lam(indx); B(1) = _lam(indx+1); B(2) = _lam(indx+2);
        B(3) = _lam(indx+3);

        double u = ub::inner_prod(B,RM);

        return u;

    } else {

        return 0.0;

    }

}
    // calculate first derivative w.r.t. ith parameter
double PotentialFunctionCBSPL::CalculateDF(const int i, const double r) const{

    // since first _nexcl parameters are not optimized for stability reasons
    //i = i + _nexcl;

    if ( r <= _cut_off ) {

        int indx = min( int( ( r )/_dr ), _nbreak-2 );

        if ( i + _nexcl >= indx && i + _nexcl <= indx+3 ){

            ub::vector<double> R;

            double rk = indx*_dr;

            double t = ( r - rk)/_dr;

            R.resize(4,false); R.clear();

            R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t;

            ub::vector<double> RM = ub::prod(R,_M);

            return RM(i + _nexcl-indx);

        }else{

            return 0.0;

        }

    } else {

        return 0;

    }
}
    // calculate second derivative w.r.t. ith parameter
double PotentialFunctionCBSPL::CalculateD2F(const int i, const int j,
        const double r) const {

    // for cubic B-SPlines D2F is zero for all lamdas
    return 0.0;

}
<commit_msg>cbspl knot extrapolation: also check for zero reference knot value<commit_after>
#include "potentialfunctioncbspl.h"

PotentialFunctionCBSPL::PotentialFunctionCBSPL(const int nlam_,
        const int ncutcoeff_, const double min_, const double max_) :
                        PotentialFunction(nlam_,min_,max_) {

    /* Here nlam_ is the total number of coeff values that are to be optimized
     * To ensure that potential and force go to zero smoothly near cut-off,
     * as suggested in Ref. PCCP, 11, 1901, 2009, coeff values leading up to
     * cut-off and beyond take a value of zero.
     *
     * Since region less than rmin is not sampled sufficiently for stability
     * first _nexcl coefficients are not optimized instead their values are
     * extrapolated from first statistically significant knot values near rmin
     */

    // number of break points = _lam.size() - 2
    _nbreak = _lam.size() - 2;

     _dr = ( _cut_off )/( double (_nbreak - 1) );

    // break point locations
    // since ncoeff = nbreak +2 , r values for last two coefficients are also
    // computed
    _rbreak.resize(_lam.size(),false);

    _rbreak.clear();

    for( int i = 0; i < _lam.size(); i++)
        _rbreak(i) = i*_dr;

   // exclude knots corresponding to r <= _min
    _nexcl = min( int( ( _min )/_dr ), _nbreak - 2 ) + 1;

    // account for finite numerical division of _min/_dr
    // e.g. 0.24/0.02 may result in 11.99999999999999
    if( _rbreak(_nexcl) == _min ) _nexcl++;

    _ncutcoeff = ncutcoeff_;

    _M.resize(4,4,false);
    _M.clear();
    _M(0,0) =  1.0; _M(0,1) =  4.0; _M(0,2) =  1.0; _M(0,3) = 0.0;
    _M(1,0) = -3.0; _M(1,1) =  0.0; _M(1,2) =  3.0; _M(1,3) = 0.0;
    _M(2,0) =  3.0; _M(2,1) = -6.0; _M(2,2) =  3.0; _M(2,3) = 0.0;
    _M(3,0) = -1.0; _M(3,1) =  3.0; _M(3,2) = -3.0; _M(3,3) = 1.0;
    _M /= 6.0;

}

int PotentialFunctionCBSPL::getOptParamSize() const {

    return _lam.size() - _nexcl - _ncutcoeff;
}

void PotentialFunctionCBSPL::setParam(string filename) {

        Table param;
        param.Load(filename);

        _lam.clear();

        if( param.size() != _lam.size()) {

            throw std::runtime_error("Potential parameters size mismatch!\n"
                    "Check input parameter file \""
                    + filename + "\" \nThere should be "
                    + boost::lexical_cast<string>( _lam.size() ) + " parameters");
        } else {
            // force last _ncutcoeff to be zero
            for( int i = 0; i < _lam.size() - _ncutcoeff; i++){

                _rbreak(i) = param.x(i);
                _lam(i) = param.y(i);

            }

        }

    }

void PotentialFunctionCBSPL::SaveParam(const string& filename){

    extrapolExclParam();

    Table param;
    param.SetHasYErr(false);
    param.resize(_lam.size(), false);

    // write extrapolated knots with flag 'o'
    for (int i = 0; i < _nexcl; i++){

        param.set(i, _rbreak(i), _lam(i), 'o');
    }

    for (int i = _nexcl; i < _lam.size(); i++){

        param.set(i, _rbreak(i), _lam(i), 'i');
    }

    param.Save(filename);

}

void PotentialFunctionCBSPL::SavePotTab(const string& filename,
        const double step) {

    extrapolExclParam();
    PotentialFunction::SavePotTab(filename,step,0.0,_cut_off);

}

void PotentialFunctionCBSPL::extrapolExclParam(){

	// extrapolate first _nexcl knot values using exponential extrapolation
	// u(r) = a * exp( b * r)
	// a = u0 * exp ( - m * r0/u0 )
	// b = m/u0
	// m = (u1-u0)/(r1-r0)
	double u0 = _lam(_nexcl);
        if( u0 <= 0.0 ) {
		throw std::runtime_error("min r value for cbspl is too large,\n"
                    "choose min r such that knot value at (rmin+dr) > 0,\n"
                    "else exponentially extrapolated knot values in "
 		    "the repulsive core would be negative or zero.\n");
	}
	double r0 = _rbreak(_nexcl);
	double m = (_lam(_nexcl + 1) - _lam(_nexcl)) /
	(_rbreak(_nexcl + 1) - _rbreak(_nexcl));
	double a = u0 * exp(-m * r0 / u0);
	double b = m / u0;
	for (int i = 0; i < _nexcl; i++) {
		double r = _rbreak(i);
		double u = a * exp(b * r);
		_lam(i) = u;
	}
}

void PotentialFunctionCBSPL::setOptParam(const int i, const double val){

    _lam( i + _nexcl ) = val;

}

double PotentialFunctionCBSPL::getOptParam(const int i) const{

    return _lam( i + _nexcl );

}

double PotentialFunctionCBSPL::CalculateF (const double r) const {

    if( r <= _cut_off){

        ub::vector<double> R;
        ub::vector<double> B;

        int indx = min( int( r /_dr ) , _nbreak-2 );

        double rk = indx*_dr;

        double t = ( r - rk)/_dr;

        R.resize(4,false); R.clear();

        R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t;

        ub::vector<double> RM = ub::prod(R,_M);

        B.resize(4,false); B.clear();

        B(0) = _lam(indx); B(1) = _lam(indx+1); B(2) = _lam(indx+2);
        B(3) = _lam(indx+3);

        double u = ub::inner_prod(B,RM);

        return u;

    } else {

        return 0.0;

    }

}
    // calculate first derivative w.r.t. ith parameter
double PotentialFunctionCBSPL::CalculateDF(const int i, const double r) const{

    // since first _nexcl parameters are not optimized for stability reasons
    //i = i + _nexcl;

    if ( r <= _cut_off ) {

        int indx = min( int( ( r )/_dr ), _nbreak-2 );

        if ( i + _nexcl >= indx && i + _nexcl <= indx+3 ){

            ub::vector<double> R;

            double rk = indx*_dr;

            double t = ( r - rk)/_dr;

            R.resize(4,false); R.clear();

            R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t;

            ub::vector<double> RM = ub::prod(R,_M);

            return RM(i + _nexcl-indx);

        }else{

            return 0.0;

        }

    } else {

        return 0;

    }
}
    // calculate second derivative w.r.t. ith parameter
double PotentialFunctionCBSPL::CalculateD2F(const int i, const int j,
        const double r) const {

    // for cubic B-SPlines D2F is zero for all lamdas
    return 0.0;

}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_BINARY_OPERATOR_HPP
#define STAN_MATH_OPENCL_KERNEL_GENERATOR_BINARY_OPERATOR_HPP
#ifdef STAN_OPENCL

#include <stan/math/opencl/matrix_cl_view.hpp>
#include <stan/math/opencl/err/check_matching_dims.hpp>
#include <stan/math/opencl/multiply.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/opencl/kernel_generator/type_str.hpp>
#include <stan/math/opencl/kernel_generator/name_generator.hpp>
#include <stan/math/opencl/kernel_generator/operation.hpp>
#include <stan/math/opencl/kernel_generator/scalar.hpp>
#include <stan/math/opencl/kernel_generator/as_operation.hpp>
#include <stan/math/opencl/kernel_generator/is_valid_expression.hpp>
#include <string>
#include <type_traits>
#include <set>
#include <utility>

namespace stan {
namespace math {

/**
 * Represents a binary operation in kernel generator expressions.
 * @tparam Derived derived type
 * @tparam T_a type of first argument
 * @tparam T_b type of second argument
 */
template <typename Derived, typename T_a, typename T_b>
class binary_operation
    : public operation<
          Derived,
          typename std::common_type<
              typename std::remove_reference_t<T_a>::ReturnScalar,
              typename std::remove_reference_t<T_b>::ReturnScalar>::type> {
 public:
  static_assert(
      std::is_base_of<operation_base, std::remove_reference_t<T_a>>::value,
      "binary_operation: a must be an operation!");
  static_assert(
      std::is_base_of<operation_base, std::remove_reference_t<T_b>>::value,
      "binary_operation: b must be an operation!");

  using ReturnScalar = typename std::common_type<
      typename std::remove_reference_t<T_a>::ReturnScalar,
      typename std::remove_reference_t<T_b>::ReturnScalar>::type;
  using base = operation<Derived, ReturnScalar>;
  using base::instance;
  using base::var_name;

  /**
   * Constructor
   * @param a first argument
   * @param b sedond argument
   * @param op operation
   */
  binary_operation(T_a&& a, T_b&& b, const std::string& op) //NOLINT
      : a_(std::forward<T_a>(a)), b_(std::forward<T_b>(b)), op_(op) {
    const std::string function = "binary_operator" + op;
    if (a.rows() != base::dynamic && b.rows() != base::dynamic) {
      check_size_match(function.c_str(), "Rows of ", "a", a.rows(), "rows of ",
                       "b", b.rows());
    }
    if (a.cols() != base::dynamic && b.cols() != base::dynamic) {
      check_size_match(function.c_str(), "Columns of ", "a", a.cols(),
                       "columns of ", "b", b.cols());
    }
  }

  /**
   * generates kernel code for this and nested expressions.
   * @param ng name generator for this kernel
   * @param[in,out] generated set of already generated operations
   * @param i row index variable name
   * @param j column index variable name
   * @return part of kernel with code for this and nested expressions
   */
  inline kernel_parts generate(name_generator& ng, std::set<int>& generated,
                               const std::string& i,
                               const std::string& j) const {
    if (generated.count(instance) == 0) {
      kernel_parts a_parts = a_.generate(ng, generated, i, j);
      kernel_parts b_parts = b_.generate(ng, generated, i, j);
      generated.insert(instance);
      var_name = ng.generate();
      kernel_parts res;
      res.body = a_parts.body + b_parts.body + type_str<ReturnScalar>::name
                 + " " + var_name + " = " + a_.var_name + op_ + b_.var_name
                 + ";\n";
      res.args = a_parts.args + b_parts.args;
      return res;
    } else {
      return {};
    }
  }

  /**
   * Sets kernel arguments for this and nested expressions.
   * @param[in,out] generated set of expressions that already set their kernel
   * arguments
   * @param kernel kernel to set arguments on
   * @param[in,out] arg_num consecutive number of the first argument to set.
   * This is incremented for each argument set by this function.
   */
  inline void set_args(std::set<int>& generated, cl::Kernel& kernel,
                       int& arg_num) const {
    if (generated.count(instance) == 0) {
      generated.insert(instance);
      a_.set_args(generated, kernel, arg_num);
      b_.set_args(generated, kernel, arg_num);
    }
  }

  /**
   * Adds event for any matrices used by this or nested expressions.
   * @param e the event to add
   */
  inline void add_event(cl::Event& e) const {
    a_.add_event(e);
    b_.add_event(e);
  }

  /**
   * Number of rows of a matrix that would be the result of evaluating this
   * expression.
   * @return number of rows
   */
  inline int rows() const {
    int a_rows = a_.rows();
    return a_rows == base::dynamic ? b_.rows() : a_rows;
  }

  /**
   * Number of columns of a matrix that would be the result of evaluating this
   * expression.
   * @return number of columns
   */
  inline int cols() const {
    int a_cols = a_.cols();
    return a_cols == base::dynamic ? b_.cols() : a_cols;
  }

  /**
   * View of a matrix that would be the result of evaluating this expression.
   * @return view
   */
  inline matrix_cl_view view() const { return either(a_.view(), b_.view()); }

 protected:
  T_a a_;
  T_b b_;
  std::string op_;
};

/**
 * Represents addition in kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 */
template <typename T_a, typename T_b>
class addition__ : public binary_operation<addition__<T_a, T_b>, T_a, T_b> {
 public:
  /**
   * Constructor.
   * @param a first expression
   * @param b second expression
   */
  addition__(T_a&& a, T_b&& b) //NOLINT
      : binary_operation<addition__<T_a, T_b>, T_a, T_b>(
            std::forward<T_a>(a), std::forward<T_b>(b), "+") {}
};

/**
 * Addition of two kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 * @param a first argument
 * @param b second argument
 * @return Addition of given expressions
 */
template <typename T_a, typename T_b,
          typename = enable_if_all_valid_expressions<T_a, T_b>>
inline addition__<as_operation_t<T_a>, as_operation_t<T_b>>
operator+(T_a&& a, T_b&& b) { //NOLINT
  return {as_operation(std::forward<T_a>(a)),
          as_operation(std::forward<T_b>(b))};
}

/**
 * Represents subtraction in kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 */
template <typename T_a, typename T_b>
class subtraction__
    : public binary_operation<subtraction__<T_a, T_b>, T_a, T_b> {
 public:
  /**
   * Constructor.
   * @param a first expression
   * @param b second expression
   */
  subtraction__(T_a&& a, T_b&& b) //NOLINT
      : binary_operation<subtraction__<T_a, T_b>, T_a, T_b>(
            std::forward<T_a>(a), std::forward<T_b>(b), "-") {}
};

/**
 * Subtraction of two kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 * @param a first expression
 * @param b second expression
 * @return Subtraction of given expressions
 */
template <typename T_a, typename T_b,
          typename = enable_if_all_valid_expressions<T_a, T_b>>
inline subtraction__<as_operation_t<T_a>, as_operation_t<T_b>> operator-(
    T_a&& a, T_b&& b) { //NOLINT
  return {as_operation(std::forward<T_a>(a)),
          as_operation(std::forward<T_b>(b))};
}

/**
 * Represents element-wise multiplication in kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 */
template <typename T_a, typename T_b,
          typename = enable_if_all_valid_expressions<T_a, T_b>>
class elewise_multiplication__
    : public binary_operation<elewise_multiplication__<T_a, T_b>, T_a, T_b> {
 public:
  /**
   * Constructor.
   * @param a first expression
   * @param b second expression
   */
  elewise_multiplication__(T_a&& a, T_b&& b) //NOLINT
      : binary_operation<elewise_multiplication__<T_a, T_b>, T_a, T_b>(
            std::forward<T_a>(a), std::forward<T_b>(b), "*") {}

  /**
   * View of a matrix that would be the result of evaluating this expression.
   * @return view
   */
  inline matrix_cl_view view() const {
    using base = binary_operation<elewise_multiplication__<T_a, T_b>, T_a, T_b>;
    return both(base::a_.view(), base::b_.view());
  }
};

/**
 * Element-wise multiplication of two kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 * @param a first expression
 * @param b second expression
 * @return Element-wise multiplication of given expressions
 */
template <typename T_a, typename T_b>
inline elewise_multiplication__<as_operation_t<T_a>, as_operation_t<T_b>>
elewise_multiplication(T_a&& a, T_b&& b) { //NOLINT
  return {as_operation(std::forward<T_a>(a)),
          as_operation(std::forward<T_b>(b))};
}

/**
 * Multiplication of a scalar and a kernel generator expression.
 * @tparam T_a type of scalar
 * @tparam T_b type of expression
 * @param a scalar
 * @param b expression
 * @return Multiplication of given arguments
 */
template <typename T_a, typename T_b, typename = enable_if_arithmetic<T_a>,
          typename = enable_if_all_valid_expressions<T_b>>
inline elewise_multiplication__<scalar__<T_a>, as_operation_t<T_b>>
operator*(T_a&& a, T_b&& b) { //NOLINT
  return {as_operation(std::forward<T_a>(a)),
          as_operation(std::forward<T_b>(b))};
}

/**
 * Multiplication of a kernel generator expression and a scalar.
 * @tparam T_a type of expression
 * @tparam T_b type of scalar
 * @param a expression
 * @param b scalar
 * @return Multiplication of given arguments
 */
template <typename T_a, typename T_b,
          typename = enable_if_all_valid_expressions<T_a>,
          typename = enable_if_arithmetic<T_b>>
inline elewise_multiplication__<as_operation_t<T_a>, scalar__<T_b>>
operator*(T_a&& a, const T_b b) { //NOLINT
  return {as_operation(std::forward<T_a>(a)), as_operation(b)};
}

/**
 * Matrix multiplication of two kernel generator expressions. Evaluates both
 * expressions before calculating the matrix product.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 * @param a first expression
 * @param b second expression
 * @return Matrix product of given arguments
 */
template <typename T_a, typename T_b,
          typename = enable_if_all_valid_expressions_and_none_scalar<T_a, T_b>>
inline matrix_cl<double> operator*(const T_a& a, const T_b& b) {
  // no need for perfect forwarding as operations are evaluated
  return as_operation(a).eval() * as_operation(b).eval();
}

/**
 * Represents element-wise division in kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 */
template <typename T_a, typename T_b>
class elewise_division__
    : public binary_operation<elewise_division__<T_a, T_b>, T_a, T_b> {
 public:
  /**
   * Constructor.
   * @param a first expression
   * @param b second expression
   */
  elewise_division__(T_a&& a, T_b&& b) //NOLINT
      : binary_operation<elewise_division__<T_a, T_b>, T_a, T_b>(
            std::forward<T_a>(a), std::forward<T_b>(b), "/") {}

  /**
   * View of a matrix that would be the result of evaluating this expression.
   * @return view
   */
  inline matrix_cl_view view() const {
    using base = binary_operation<elewise_division__<T_a, T_b>, T_a, T_b>;
    return either(base::a_.view(), invert(base::b_.view()));
  }
};

/**
 * Element-wise division of two kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 * @param a first expression
 * @param b second expression
 * @return Element-wise division of given expressions
 */
template <typename T_a, typename T_b,
          typename = enable_if_all_valid_expressions<T_a, T_b>>
inline elewise_division__<as_operation_t<T_a>, as_operation_t<T_b>>
elewise_division(T_a&& a, T_b&& b) { //NOLINT
  return {as_operation(std::forward<T_a>(a)),
          as_operation(std::forward<T_b>(b))};
}

}  // namespace math
}  // namespace stan
#endif
#endif
<commit_msg>format<commit_after>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_BINARY_OPERATOR_HPP
#define STAN_MATH_OPENCL_KERNEL_GENERATOR_BINARY_OPERATOR_HPP
#ifdef STAN_OPENCL

#include <stan/math/opencl/matrix_cl_view.hpp>
#include <stan/math/opencl/err/check_matching_dims.hpp>
#include <stan/math/opencl/multiply.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/opencl/kernel_generator/type_str.hpp>
#include <stan/math/opencl/kernel_generator/name_generator.hpp>
#include <stan/math/opencl/kernel_generator/operation.hpp>
#include <stan/math/opencl/kernel_generator/scalar.hpp>
#include <stan/math/opencl/kernel_generator/as_operation.hpp>
#include <stan/math/opencl/kernel_generator/is_valid_expression.hpp>
#include <string>
#include <type_traits>
#include <set>
#include <utility>

namespace stan {
namespace math {

/**
 * Represents a binary operation in kernel generator expressions.
 * @tparam Derived derived type
 * @tparam T_a type of first argument
 * @tparam T_b type of second argument
 */
template <typename Derived, typename T_a, typename T_b>
class binary_operation
    : public operation<
          Derived,
          typename std::common_type<
              typename std::remove_reference_t<T_a>::ReturnScalar,
              typename std::remove_reference_t<T_b>::ReturnScalar>::type> {
 public:
  static_assert(
      std::is_base_of<operation_base, std::remove_reference_t<T_a>>::value,
      "binary_operation: a must be an operation!");
  static_assert(
      std::is_base_of<operation_base, std::remove_reference_t<T_b>>::value,
      "binary_operation: b must be an operation!");

  using ReturnScalar = typename std::common_type<
      typename std::remove_reference_t<T_a>::ReturnScalar,
      typename std::remove_reference_t<T_b>::ReturnScalar>::type;
  using base = operation<Derived, ReturnScalar>;
  using base::instance;
  using base::var_name;

  /**
   * Constructor
   * @param a first argument
   * @param b sedond argument
   * @param op operation
   */
  binary_operation(T_a&& a, T_b&& b, const std::string& op)  //NOLINT
      : a_(std::forward<T_a>(a)), b_(std::forward<T_b>(b)), op_(op) {
    const std::string function = "binary_operator" + op;
    if (a.rows() != base::dynamic && b.rows() != base::dynamic) {
      check_size_match(function.c_str(), "Rows of ", "a", a.rows(), "rows of ",
                       "b", b.rows());
    }
    if (a.cols() != base::dynamic && b.cols() != base::dynamic) {
      check_size_match(function.c_str(), "Columns of ", "a", a.cols(),
                       "columns of ", "b", b.cols());
    }
  }

  /**
   * generates kernel code for this and nested expressions.
   * @param ng name generator for this kernel
   * @param[in,out] generated set of already generated operations
   * @param i row index variable name
   * @param j column index variable name
   * @return part of kernel with code for this and nested expressions
   */
  inline kernel_parts generate(name_generator& ng, std::set<int>& generated,
                               const std::string& i,
                               const std::string& j) const {
    if (generated.count(instance) == 0) {
      kernel_parts a_parts = a_.generate(ng, generated, i, j);
      kernel_parts b_parts = b_.generate(ng, generated, i, j);
      generated.insert(instance);
      var_name = ng.generate();
      kernel_parts res;
      res.body = a_parts.body + b_parts.body + type_str<ReturnScalar>::name
                 + " " + var_name + " = " + a_.var_name + op_ + b_.var_name
                 + ";\n";
      res.args = a_parts.args + b_parts.args;
      return res;
    } else {
      return {};
    }
  }

  /**
   * Sets kernel arguments for this and nested expressions.
   * @param[in,out] generated set of expressions that already set their kernel
   * arguments
   * @param kernel kernel to set arguments on
   * @param[in,out] arg_num consecutive number of the first argument to set.
   * This is incremented for each argument set by this function.
   */
  inline void set_args(std::set<int>& generated, cl::Kernel& kernel,
                       int& arg_num) const {
    if (generated.count(instance) == 0) {
      generated.insert(instance);
      a_.set_args(generated, kernel, arg_num);
      b_.set_args(generated, kernel, arg_num);
    }
  }

  /**
   * Adds event for any matrices used by this or nested expressions.
   * @param e the event to add
   */
  inline void add_event(cl::Event& e) const {
    a_.add_event(e);
    b_.add_event(e);
  }

  /**
   * Number of rows of a matrix that would be the result of evaluating this
   * expression.
   * @return number of rows
   */
  inline int rows() const {
    int a_rows = a_.rows();
    return a_rows == base::dynamic ? b_.rows() : a_rows;
  }

  /**
   * Number of columns of a matrix that would be the result of evaluating this
   * expression.
   * @return number of columns
   */
  inline int cols() const {
    int a_cols = a_.cols();
    return a_cols == base::dynamic ? b_.cols() : a_cols;
  }

  /**
   * View of a matrix that would be the result of evaluating this expression.
   * @return view
   */
  inline matrix_cl_view view() const { return either(a_.view(), b_.view()); }

 protected:
  T_a a_;
  T_b b_;
  std::string op_;
};

/**
 * Represents addition in kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 */
template <typename T_a, typename T_b>
class addition__ : public binary_operation<addition__<T_a, T_b>, T_a, T_b> {
 public:
  /**
   * Constructor.
   * @param a first expression
   * @param b second expression
   */
  addition__(T_a&& a, T_b&& b)  //NOLINT
      : binary_operation<addition__<T_a, T_b>, T_a, T_b>(
            std::forward<T_a>(a), std::forward<T_b>(b), "+") {}
};

/**
 * Addition of two kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 * @param a first argument
 * @param b second argument
 * @return Addition of given expressions
 */
template <typename T_a, typename T_b,
          typename = enable_if_all_valid_expressions<T_a, T_b>>
inline addition__<as_operation_t<T_a>, as_operation_t<T_b>> operator+(
    T_a&& a, T_b&& b) {  // NOLINT
  return {as_operation(std::forward<T_a>(a)),
          as_operation(std::forward<T_b>(b))};
}

/**
 * Represents subtraction in kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 */
template <typename T_a, typename T_b>
class subtraction__
    : public binary_operation<subtraction__<T_a, T_b>, T_a, T_b> {
 public:
  /**
   * Constructor.
   * @param a first expression
   * @param b second expression
   */
  subtraction__(T_a&& a, T_b&& b)  //NOLINT
      : binary_operation<subtraction__<T_a, T_b>, T_a, T_b>(
            std::forward<T_a>(a), std::forward<T_b>(b), "-") {}
};

/**
 * Subtraction of two kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 * @param a first expression
 * @param b second expression
 * @return Subtraction of given expressions
 */
template <typename T_a, typename T_b,
          typename = enable_if_all_valid_expressions<T_a, T_b>>
inline subtraction__<as_operation_t<T_a>, as_operation_t<T_b>> operator-(
    T_a&& a, T_b&& b) {  //NOLINT
  return {as_operation(std::forward<T_a>(a)),
          as_operation(std::forward<T_b>(b))};
}

/**
 * Represents element-wise multiplication in kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 */
template <typename T_a, typename T_b,
          typename = enable_if_all_valid_expressions<T_a, T_b>>
class elewise_multiplication__
    : public binary_operation<elewise_multiplication__<T_a, T_b>, T_a, T_b> {
 public:
  /**
   * Constructor.
   * @param a first expression
   * @param b second expression
   */
  elewise_multiplication__(T_a&& a, T_b&& b)  //NOLINT
      : binary_operation<elewise_multiplication__<T_a, T_b>, T_a, T_b>(
            std::forward<T_a>(a), std::forward<T_b>(b), "*") {}

  /**
   * View of a matrix that would be the result of evaluating this expression.
   * @return view
   */
  inline matrix_cl_view view() const {
    using base = binary_operation<elewise_multiplication__<T_a, T_b>, T_a, T_b>;
    return both(base::a_.view(), base::b_.view());
  }
};

/**
 * Element-wise multiplication of two kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 * @param a first expression
 * @param b second expression
 * @return Element-wise multiplication of given expressions
 */
template <typename T_a, typename T_b>
inline elewise_multiplication__<as_operation_t<T_a>, as_operation_t<T_b>>
elewise_multiplication(T_a&& a, T_b&& b) {  //NOLINT
  return {as_operation(std::forward<T_a>(a)),
          as_operation(std::forward<T_b>(b))};
}

/**
 * Multiplication of a scalar and a kernel generator expression.
 * @tparam T_a type of scalar
 * @tparam T_b type of expression
 * @param a scalar
 * @param b expression
 * @return Multiplication of given arguments
 */
template <typename T_a, typename T_b, typename = enable_if_arithmetic<T_a>,
          typename = enable_if_all_valid_expressions<T_b>>
inline elewise_multiplication__<scalar__<T_a>, as_operation_t<T_b>> operator*(
    T_a&& a, T_b&& b) {  // NOLINT
  return {as_operation(std::forward<T_a>(a)),
          as_operation(std::forward<T_b>(b))};
}

/**
 * Multiplication of a kernel generator expression and a scalar.
 * @tparam T_a type of expression
 * @tparam T_b type of scalar
 * @param a expression
 * @param b scalar
 * @return Multiplication of given arguments
 */
template <typename T_a, typename T_b,
          typename = enable_if_all_valid_expressions<T_a>,
          typename = enable_if_arithmetic<T_b>>
inline elewise_multiplication__<as_operation_t<T_a>, scalar__<T_b>> operator*(
    T_a&& a, const T_b b) {  // NOLINT
  return {as_operation(std::forward<T_a>(a)), as_operation(b)};
}

/**
 * Matrix multiplication of two kernel generator expressions. Evaluates both
 * expressions before calculating the matrix product.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 * @param a first expression
 * @param b second expression
 * @return Matrix product of given arguments
 */
template <typename T_a, typename T_b,
          typename = enable_if_all_valid_expressions_and_none_scalar<T_a, T_b>>
inline matrix_cl<double> operator*(const T_a& a, const T_b& b) {
  // no need for perfect forwarding as operations are evaluated
  return as_operation(a).eval() * as_operation(b).eval();
}

/**
 * Represents element-wise division in kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 */
template <typename T_a, typename T_b>
class elewise_division__
    : public binary_operation<elewise_division__<T_a, T_b>, T_a, T_b> {
 public:
  /**
   * Constructor.
   * @param a first expression
   * @param b second expression
   */
  elewise_division__(T_a&& a, T_b&& b)  //NOLINT
      : binary_operation<elewise_division__<T_a, T_b>, T_a, T_b>(
            std::forward<T_a>(a), std::forward<T_b>(b), "/") {}

  /**
   * View of a matrix that would be the result of evaluating this expression.
   * @return view
   */
  inline matrix_cl_view view() const {
    using base = binary_operation<elewise_division__<T_a, T_b>, T_a, T_b>;
    return either(base::a_.view(), invert(base::b_.view()));
  }
};

/**
 * Element-wise division of two kernel generator expressions.
 * @tparam T_a type of first expression
 * @tparam T_b type of second expression
 * @param a first expression
 * @param b second expression
 * @return Element-wise division of given expressions
 */
template <typename T_a, typename T_b,
          typename = enable_if_all_valid_expressions<T_a, T_b>>
inline elewise_division__<as_operation_t<T_a>, as_operation_t<T_b>>
elewise_division(T_a&& a, T_b&& b) {  //NOLINT
  return {as_operation(std::forward<T_a>(a)),
          as_operation(std::forward<T_b>(b))};
}

}  // namespace math
}  // namespace stan
#endif
#endif
<|endoftext|>


<commit_before>/* tnt/object.cpp
 * Copyright (C) 2005 Tommi Maekitalo
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <tnt/object.h>
#include <cxxtools/log.h>

log_define("tntnet.object")

namespace tnt
{
  unsigned Object::addRef()
  {
    return ++refs;
  }

  unsigned Object::release()
  {
    if (--refs == 0)
    {
      delete this;
      return 0;
    }
    else
      return refs;
  }
}
<commit_msg>remove unused logging-declarations<commit_after>/* tnt/object.cpp
 * Copyright (C) 2005 Tommi Maekitalo
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <tnt/object.h>

namespace tnt
{
  unsigned Object::addRef()
  {
    return ++refs;
  }

  unsigned Object::release()
  {
    if (--refs == 0)
    {
      delete this;
      return 0;
    }
    else
      return refs;
  }
}
<|endoftext|>


<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/platform/platform.h"

#if !defined(IS_MOBILE_PLATFORM) && defined(PLATFORM_POSIX) && \
    (defined(__clang__) || defined(__GNUC__))
#define TF_GENERATE_STACKTRACE
#endif

#if defined(TF_GENERATE_STACKTRACE)
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include <string>

#include "tensorflow/core/platform/stacktrace.h"

#endif  // defined(TF_GENERATE_STACKTRACE)

namespace tensorflow {
namespace testing {

#if defined(TF_GENERATE_STACKTRACE)
// This function will print stacktrace to STDERR.
// It avoids using malloc, so it makes sure to dump the stack even when the heap
// is corrupted. However, it can dump mangled symbols.
inline void SafePrintStackTrace() {
  static const char begin_msg[] = "*** BEGIN MANGLED STACK TRACE ***\n";
  (void)write(STDERR_FILENO, begin_msg, strlen(begin_msg));

  int buffer_size = 128;
  void *trace[128];
  // Run backtrace to get the size of the stacktrace
  buffer_size = backtrace(trace, buffer_size);

  // Print a mangled stacktrace to STDERR as safely as possible.
  backtrace_symbols_fd(trace, buffer_size, STDERR_FILENO);

  static const char end_msg[] = "*** END MANGLED STACK TRACE ***\n\n";
  (void)write(STDERR_FILENO, end_msg, strlen(end_msg));
}

static void StacktraceHandler(int sig, siginfo_t *si, void *v) {
  // Make sure our handler does not deadlock. And this should be the last thing
  // our program does. Therefore, set a timer to kill the program in 60
  // seconds.
  struct itimerval timer;
  timer.it_value.tv_sec = 60;
  timer.it_value.tv_usec = 0;
  timer.it_interval.tv_sec = 0;
  timer.it_interval.tv_usec = 0;
  setitimer(ITIMER_REAL, &timer, 0);

  struct sigaction sa_timeout;
  memset(&sa_timeout, 0, sizeof(sa_timeout));
  sa_timeout.sa_handler = SIG_DFL;
  sigaction(SIGALRM, &sa_timeout, 0);

  char buf[128];

  snprintf(buf, sizeof(buf), "*** Received signal %d ***\n", sig);
  (void)write(STDERR_FILENO, buf, strlen(buf));

  // Print "a" stack trace, as safely as possible.
  SafePrintStackTrace();

  // Up until this line, we made sure not to allocate memory, to be able to dump
  // a stack trace even in the event of heap corruption. After this line, we
  // will try to print more human readable things to the terminal.
  // But these have a higher probability to fail.
  std::string stacktrace = CurrentStackTrace();
  (void)write(STDERR_FILENO, stacktrace.c_str(), stacktrace.length());

  // Abort the program.
  struct sigaction sa;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;
  sa.sa_handler = SIG_DFL;
  sigaction(SIGABRT, &sa, NULL);
  abort();
}

void InstallStacktraceHandler() {
  int handled_signals[] = {SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE};

  for (int i = 0; i < sizeof(handled_signals) / sizeof(int); i++) {
    int sig = handled_signals[i];
    struct sigaction sa;
    struct sigaction osa;

    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_SIGINFO | SA_RESETHAND;
    sa.sa_sigaction = &StacktraceHandler;
    if (sigaction(sig, &sa, &osa) != 0) {
      char buf[128];
      snprintf(buf, sizeof(buf),
               "Warning, can't install backtrace signal handler for signal %d, "
               "errno:%d \n",
               sig, errno);
      (void)write(STDERR_FILENO, buf, strlen(buf));
    } else if (osa.sa_handler != SIG_DFL) {
      char buf[128];
      snprintf(buf, sizeof(buf),
               "Warning, backtrace signal handler for signal %d overwrote "
               "previous handler.\n",
               sig);
      (void)write(STDERR_FILENO, buf, strlen(buf));
    }
  }
}

#else
void InstallStacktraceHandler() {}
#endif  // defined(TF_GENERATE_STACKTRACE)

}  // namespace testing
}  // namespace tensorflow
<commit_msg>in resolution of [Wsign-compare] warning id 7<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/platform/platform.h"

#if !defined(IS_MOBILE_PLATFORM) && defined(PLATFORM_POSIX) && \
    (defined(__clang__) || defined(__GNUC__))
#define TF_GENERATE_STACKTRACE
#endif

#if defined(TF_GENERATE_STACKTRACE)
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include <string>

#include "tensorflow/core/platform/stacktrace.h"

#endif  // defined(TF_GENERATE_STACKTRACE)

namespace tensorflow {
namespace testing {

#if defined(TF_GENERATE_STACKTRACE)
// This function will print stacktrace to STDERR.
// It avoids using malloc, so it makes sure to dump the stack even when the heap
// is corrupted. However, it can dump mangled symbols.
inline void SafePrintStackTrace() {
  static const char begin_msg[] = "*** BEGIN MANGLED STACK TRACE ***\n";
  (void)write(STDERR_FILENO, begin_msg, strlen(begin_msg));

  int buffer_size = 128;
  void *trace[128];
  // Run backtrace to get the size of the stacktrace
  buffer_size = backtrace(trace, buffer_size);

  // Print a mangled stacktrace to STDERR as safely as possible.
  backtrace_symbols_fd(trace, buffer_size, STDERR_FILENO);

  static const char end_msg[] = "*** END MANGLED STACK TRACE ***\n\n";
  (void)write(STDERR_FILENO, end_msg, strlen(end_msg));
}

static void StacktraceHandler(int sig, siginfo_t *si, void *v) {
  // Make sure our handler does not deadlock. And this should be the last thing
  // our program does. Therefore, set a timer to kill the program in 60
  // seconds.
  struct itimerval timer;
  timer.it_value.tv_sec = 60;
  timer.it_value.tv_usec = 0;
  timer.it_interval.tv_sec = 0;
  timer.it_interval.tv_usec = 0;
  setitimer(ITIMER_REAL, &timer, 0);

  struct sigaction sa_timeout;
  memset(&sa_timeout, 0, sizeof(sa_timeout));
  sa_timeout.sa_handler = SIG_DFL;
  sigaction(SIGALRM, &sa_timeout, 0);

  char buf[128];

  snprintf(buf, sizeof(buf), "*** Received signal %d ***\n", sig);
  (void)write(STDERR_FILENO, buf, strlen(buf));

  // Print "a" stack trace, as safely as possible.
  SafePrintStackTrace();

  // Up until this line, we made sure not to allocate memory, to be able to dump
  // a stack trace even in the event of heap corruption. After this line, we
  // will try to print more human readable things to the terminal.
  // But these have a higher probability to fail.
  std::string stacktrace = CurrentStackTrace();
  (void)write(STDERR_FILENO, stacktrace.c_str(), stacktrace.length());

  // Abort the program.
  struct sigaction sa;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;
  sa.sa_handler = SIG_DFL;
  sigaction(SIGABRT, &sa, NULL);
  abort();
}

void InstallStacktraceHandler() {
  int handled_signals[] = {SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE};

  size_t array_limit = sizeof(handled_signals) / sizeof(int);
  for (size_t i = 0; i < array_limit; i++) {
    int sig = handled_signals[i];
    struct sigaction sa;
    struct sigaction osa;

    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_SIGINFO | SA_RESETHAND;
    sa.sa_sigaction = &StacktraceHandler;
    if (sigaction(sig, &sa, &osa) != 0) {
      char buf[128];
      snprintf(buf, sizeof(buf),
               "Warning, can't install backtrace signal handler for signal %d, "
               "errno:%d \n",
               sig, errno);
      (void)write(STDERR_FILENO, buf, strlen(buf));
    } else if (osa.sa_handler != SIG_DFL) {
      char buf[128];
      snprintf(buf, sizeof(buf),
               "Warning, backtrace signal handler for signal %d overwrote "
               "previous handler.\n",
               sig);
      (void)write(STDERR_FILENO, buf, strlen(buf));
    }
  }
}

#else
void InstallStacktraceHandler() {}
#endif  // defined(TF_GENERATE_STACKTRACE)

}  // namespace testing
}  // namespace tensorflow
<|endoftext|>


<commit_before>#include "../lib/matrix.hpp"
#include "../lib/image.hpp"
#include "../lib/time.hpp"

void conv(matrix &x, const matrix &k) {
  matrix y;
  y.create(x.rows + k.rows, x.cols + k.cols);

  for (unsigned row = 0; row < x.rows; row++) {
    for (unsigned col = 0; col < x.cols; col++) {
      auto yrow = row + k.rows / 2;
      auto ycol = col + k.cols / 2;
      y(yrow, ycol) = x(row, col);
    }
  }

  // Compute sum of k
  int weight = 0;
  for (unsigned row = 0; row < k.rows; row++) {
    for (unsigned col = 0; col < k.cols; col++) {
      weight += k(row, col);
    }
  }

  // Do the convolution
  for (unsigned row = 0; row < x.rows; row++) {
    for (unsigned col = 0; col < x.cols; col++) {
    int t = 0;

    auto yrow = row;
    for (int krow = k.rows - 1; krow >= 0; krow--, yrow++) {
        auto ycol = col;
        for (int kcol = k.cols - 1; kcol >= 0; kcol--, ycol++) {
			t += y(yrow, ycol) * k(krow, kcol);
        }
    }

    if (weight != 0) {
        t /= weight;
    }

    x(row, col) = t;
    }
  }
}

int binomial_coefficient(int n, int k) {
  if (n <= 1 || k == 0) {
    return 1;
  } else {
    return binomial_coefficient(n - 1, k - 1) * n / k;
  }
}

matrix binomial(int n) {
  if ((n & 1) == 0) {
    throw std::invalid_argument("n must be odd");
  }

  matrix x, y;
  x.create(1, n);
  y.create(n, 1);

  for (int i = 0; i < n / 2; i++) {
    x(0, i) = x(0, n - i - 1) = binomial_coefficient(n - 1, i);
    y(i, 0) = y(n - i - 1, 0) = binomial_coefficient(n - 1, i);
  }

  x(0, n / 2) = binomial_coefficient(n - 1, n / 2);
  y(n / 2, 0) = binomial_coefficient(n - 1, n / 2);

  return y * x;
}

int main(int argc, char **argv) {
  auto bmp = load_image("C:\\Users\\Joe\\Desktop\\test.jpg");
  auto orig = bmp;

  matrix kernel = binomial(3);

  auto start = now();
  conv(bmp, kernel);
  auto stop = now();

  printf("%g\n", to_seconds(start, stop));

  save_png(bmp, "C:\\Users\\Joe\\Desktop\\test.png");
  return 0;
}
<commit_msg>Fix formatting<commit_after>#include "../lib/matrix.hpp"
#include "../lib/image.hpp"
#include "../lib/time.hpp"

void conv(matrix &x, const matrix &k) {
  matrix y;
  y.create(x.rows + k.rows, x.cols + k.cols);

  for (unsigned row = 0; row < x.rows; row++) {
    for (unsigned col = 0; col < x.cols; col++) {
      auto yrow = row + k.rows / 2;
      auto ycol = col + k.cols / 2;
      y(yrow, ycol) = x(row, col);
    }
  }

  // Compute sum of k
  int weight = 0;
  for (unsigned row = 0; row < k.rows; row++) {
    for (unsigned col = 0; col < k.cols; col++) {
      weight += k(row, col);
    }
  }

  // Do the convolution
  for (unsigned row = 0; row < x.rows; row++) {
    for (unsigned col = 0; col < x.cols; col++) {
      int t = 0;

      auto yrow = row;
      for (int krow = k.rows - 1; krow >= 0; krow--, yrow++) {
        auto ycol = col;
        for (int kcol = k.cols - 1; kcol >= 0; kcol--, ycol++) {
          t += y(yrow, ycol) * k(krow, kcol);
        }
      }

      if (weight != 0) {
        t /= weight;
      }

      x(row, col) = t;
    }
  }
}

int binomial_coefficient(int n, int k) {
  if (n <= 1 || k == 0) {
    return 1;
  } else {
    return binomial_coefficient(n - 1, k - 1) * n / k;
  }
}

matrix binomial(int n) {
  if ((n & 1) == 0) {
    throw std::invalid_argument("n must be odd");
  }

  matrix x, y;
  x.create(1, n);
  y.create(n, 1);

  for (int i = 0; i < n / 2; i++) {
    x(0, i) = x(0, n - i - 1) = binomial_coefficient(n - 1, i);
    y(i, 0) = y(n - i - 1, 0) = binomial_coefficient(n - 1, i);
  }

  x(0, n / 2) = binomial_coefficient(n - 1, n / 2);
  y(n / 2, 0) = binomial_coefficient(n - 1, n / 2);

  return y * x;
}

int main(int argc, char **argv) {
  auto bmp = load_image("C:\\Users\\Joe\\Desktop\\test.jpg");
  auto orig = bmp;

  matrix kernel = binomial(3);

  auto start = now();
  conv(bmp, kernel);
  auto stop = now();

  printf("%g\n", to_seconds(start, stop));

  save_png(bmp, "C:\\Users\\Joe\\Desktop\\test.png");
  return 0;
}
<|endoftext|>


<commit_before>#include "TCP.h"

#include "os.h"
#include "Endian.h"

#if defined( __POSIX__ )
	#include <arpa/inet.h>
    #include <sys/socket.h>
    #include <string.h>

	#if !defined( SOCKET_ERROR )
		#define SOCKET_ERROR    ( -1 )
	#endif
#elif defined( __WIN_API__ )
	#include <WinSock2.h>
#endif

#if defined( __OS_X__ )
    #define INVALID_SOCKET  ( -1 )
#endif

#ifdef __WIN_API__
    typedef int socklen_t;
#endif

/*
====================
xiTCPListen::CreateOnPort

	Allocates memory and constructs a TCP listen server socket
	If it fails, the memory is cleaned up and a nullptr returned
====================
*/
xiTCPListen * xiTCPListen::CreateOnPort( const uint16_t port ) {
	xiTCPListen * const self = new xiTCPListen();

	if ( self->status == STATUS_INVALID ) {
		delete( self );

		return nullptr;
	}

	if ( !self->BindToPortV4( port ) ) {
		delete( self );

		return nullptr;
	}

	self->Grab();

	return self;
}

/*
====================
xiTCPListen::xiTCPListen

	Protected constructor
	This is called internally
	Starts a native TCP socket
====================
*/
xiTCPListen::xiTCPListen() {
	status = STATUS_NOT_BOUND;
	nativeHandle = OpenNativeSocket( SOCK_STREAM );

	if ( nativeHandle == INVALID_SOCKET ) {
		status = STATUS_INVALID;
	}
}

/*
====================
xiTCPListen::~xiTCPListen

	Protected destructor
	The parent Protobase class does the important destruction
====================
*/
xiTCPListen::~xiTCPListen() {
}

/*
====================
xiTCPListen::Listen

	Listens for incoming TCP connections
	Returns a new xiTCP socket for communicating on new connections
====================
*/
xiTCP * xiTCPListen::Listen( addressInfo_s * const senderInfo ) {
	const int listenStatus = listen( nativeHandle, 1 );
	if ( !listenStatus ) {
		// worked, open connection
		xiTCP * const newConnection = CreateOnSocket( nativeHandle, senderInfo );

		return newConnection;
	} else {
		status = STATUS_ERROR;
	}

	return nullptr;
}

/*
====================
xiTCPListen::CreateOnSocket

	Internally used to construct the listen socket
	The native handle is given to the method, as opposed to created by the method
====================
*/
xiTCP * xiTCPListen::CreateOnSocket( const socketHandle_t _nativeHandle, addressInfo_s * const senderInfo ) {
	xiTCP * const self = new xiTCP();
	self->Accept( _nativeHandle, senderInfo );

	if ( self->status == STATUS_INVALID ) {
		delete( self );

		return nullptr;
	}

	self->Grab();

	return self;
}

/*
====================
xiTCP::ConnectTo

	Use this to create a TCP socket for connecting with a TCP listen server
	The address information of the server is needed for the connection
	It will attempt the connection and only return a valid pointer if the connection is successful
====================
*/
xiTCP * xiTCP::ConnectTo( const addressInfo_s * const listenInfo ) {
	xiTCP * const self = new xiTCP();

	self->nativeHandle = OpenNativeSocket( SOCK_STREAM );
	if ( self->nativeHandle == INVALID_SOCKET ) {
		self->status = STATUS_INVALID;
	}

	if ( self->status == STATUS_INVALID ) {
		delete( self );

		return nullptr;
	}

	if ( !self->BindToPortV4( 0 ) ) {
		delete( self );

		return nullptr;
	}

	const bool isConnected = self->Connect( listenInfo );
	if ( !isConnected ) {
		delete( self );

		return nullptr;
	}

	self->Grab();

	return self;
}

/*
====================
xiTCP::Accept

	Used internally when a xiTCP socket is created by a listen server
	This method is "accepts" the socket as being bound by the listen socket
====================
*/
void xiTCP::Accept( const socketHandle_t _nativeHandle, addressInfo_s * const senderInfo ) {
	sockaddr_in target;
	socklen_t targetLength = ( int )sizeof( target );
	memset( &target, 0, sizeof( target ) );

	nativeHandle = accept( _nativeHandle, ( sockaddr * )&target, &targetLength );

	if ( nativeHandle == INVALID_SOCKET ) {
		status = STATUS_INVALID;
	} else {
#ifdef __WIN_API__
		senderInfo->address.protocolV4[0] = target.sin_addr.S_un.S_un_b.s_b1;
		senderInfo->address.protocolV4[1] = target.sin_addr.S_un.S_un_b.s_b2;
		senderInfo->address.protocolV4[2] = target.sin_addr.S_un.S_un_b.s_b3;
		senderInfo->address.protocolV4[3] = target.sin_addr.S_un.S_un_b.s_b4;
#elif defined( __POSIX__ )
        memcpy( &senderInfo->address.protocolV4[0], &target.sin_addr.s_addr, sizeof( target.sin_addr.s_addr ) );
#endif

		senderInfo->port = ( uint16_t )Endian::NetworkToHostUnsigned( target.sin_port, sizeof( target.sin_port ) );
	}
}

/*
====================
xiTCP::Connect

	Used internally to start the client to server connection
====================
*/
bool xiTCP::Connect( const addressInfo_s * const listenInfo ) {
	sockaddr_in target;
	int targetLength = ( int )sizeof( target );
	memset( &target, 0, sizeof( target ) );

#ifdef __WIN_API__
	target.sin_family = AF_INET;
	target.sin_addr.S_un.S_un_b.s_b1 = listenInfo->address.protocolV4[0];
	target.sin_addr.S_un.S_un_b.s_b2 = listenInfo->address.protocolV4[1];
	target.sin_addr.S_un.S_un_b.s_b3 = listenInfo->address.protocolV4[2];
	target.sin_addr.S_un.S_un_b.s_b4 = listenInfo->address.protocolV4[3];
#else
    memcpy( &target.sin_addr.s_addr, &listenInfo->address.protocolV4[0], sizeof( target.sin_addr.s_addr ) );
#endif

	target.sin_port = ( uint16_t )Endian::HostToNetworkUnsigned( listenInfo->port, sizeof( listenInfo->port ) );

	const int connectResult = connect( nativeHandle, ( sockaddr * )&target, targetLength );
	if ( connectResult == SOCKET_ERROR ) {
		return false;
	}

	return true;
}

/*
====================
xiTCP::ReadIntoBuffer

	Calls the operating system's recv function to read from the TCP connection
====================
*/
byteLen_t xiTCP::ReadIntoBuffer( char * const buffer, const int32_t bufferLength ) {
	return recv( nativeHandle, buffer, bufferLength, 0 );
}

/*
====================
xiTCP::SendBuffer

	Calls the operating system's send function to send a buffer down the connection
====================
*/
byteLen_t xiTCP::SendBuffer( const char * const buffer, const int32_t bufferLength ) {
	return send( nativeHandle, buffer, bufferLength, 0 );
}

/*
====================
xiTCP::xiTCP

	Constructor
	Defaults a TCP connection as not bound
====================
*/
xiTCP::xiTCP() {
	status = STATUS_NOT_BOUND;
}

/*
====================
xiTCP::~xiTCP

	Deconstructor
	Protobase does the important destruction
====================
*/
xiTCP::~xiTCP() {
}<commit_msg>Replaced #else defined with #elif to better help compile errors<commit_after>#include "TCP.h"

#include "os.h"
#include "Endian.h"

#if defined( __POSIX__ )
	#include <arpa/inet.h>
	#include <sys/socket.h>
	#include <string.h>

	#if !defined( SOCKET_ERROR )
		#define SOCKET_ERROR    ( -1 )
	#endif
#elif defined( __WIN_API__ )
	#include <WinSock2.h>
#endif

#if defined( __OS_X__ )
	#define INVALID_SOCKET  ( -1 )
#endif

#if defined( __WIN_API__ )
	typedef int socklen_t;
#endif

/*
====================
xiTCPListen::CreateOnPort

	Allocates memory and constructs a TCP listen server socket
	If it fails, the memory is cleaned up and a nullptr returned
====================
*/
xiTCPListen * xiTCPListen::CreateOnPort( const uint16_t port ) {
	xiTCPListen * const self = new xiTCPListen();

	if ( self->status == STATUS_INVALID ) {
		delete( self );

		return nullptr;
	}

	if ( !self->BindToPortV4( port ) ) {
		delete( self );

		return nullptr;
	}

	self->Grab();

	return self;
}

/*
====================
xiTCPListen::xiTCPListen

	Protected constructor
	This is called internally
	Starts a native TCP socket
====================
*/
xiTCPListen::xiTCPListen() {
	status = STATUS_NOT_BOUND;
	nativeHandle = OpenNativeSocket( SOCK_STREAM );

	if ( nativeHandle == INVALID_SOCKET ) {
		status = STATUS_INVALID;
	}
}

/*
====================
xiTCPListen::~xiTCPListen

	Protected destructor
	The parent Protobase class does the important destruction
====================
*/
xiTCPListen::~xiTCPListen() {
}

/*
====================
xiTCPListen::Listen

	Listens for incoming TCP connections
	Returns a new xiTCP socket for communicating on new connections
====================
*/
xiTCP * xiTCPListen::Listen( addressInfo_s * const senderInfo ) {
	const int listenStatus = listen( nativeHandle, 1 );
	if ( !listenStatus ) {
		// worked, open connection
		xiTCP * const newConnection = CreateOnSocket( nativeHandle, senderInfo );

		return newConnection;
	} else {
		status = STATUS_ERROR;
	}

	return nullptr;
}

/*
====================
xiTCPListen::CreateOnSocket

	Internally used to construct the listen socket
	The native handle is given to the method, as opposed to created by the method
====================
*/
xiTCP * xiTCPListen::CreateOnSocket( const socketHandle_t _nativeHandle, addressInfo_s * const senderInfo ) {
	xiTCP * const self = new xiTCP();
	self->Accept( _nativeHandle, senderInfo );

	if ( self->status == STATUS_INVALID ) {
		delete( self );

		return nullptr;
	}

	self->Grab();

	return self;
}

/*
====================
xiTCP::ConnectTo

	Use this to create a TCP socket for connecting with a TCP listen server
	The address information of the server is needed for the connection
	It will attempt the connection and only return a valid pointer if the connection is successful
====================
*/
xiTCP * xiTCP::ConnectTo( const addressInfo_s * const listenInfo ) {
	xiTCP * const self = new xiTCP();

	self->nativeHandle = OpenNativeSocket( SOCK_STREAM );
	if ( self->nativeHandle == INVALID_SOCKET ) {
		self->status = STATUS_INVALID;
	}

	if ( self->status == STATUS_INVALID ) {
		delete( self );

		return nullptr;
	}

	if ( !self->BindToPortV4( 0 ) ) {
		delete( self );

		return nullptr;
	}

	const bool isConnected = self->Connect( listenInfo );
	if ( !isConnected ) {
		delete( self );

		return nullptr;
	}

	self->Grab();

	return self;
}

/*
====================
xiTCP::Accept

	Used internally when a xiTCP socket is created by a listen server
	This method is "accepts" the socket as being bound by the listen socket
====================
*/
void xiTCP::Accept( const socketHandle_t _nativeHandle, addressInfo_s * const senderInfo ) {
	sockaddr_in target;
	socklen_t targetLength = ( int )sizeof( target );
	memset( &target, 0, sizeof( target ) );

	nativeHandle = accept( _nativeHandle, ( sockaddr * )&target, &targetLength );

	if ( nativeHandle == INVALID_SOCKET ) {
		status = STATUS_INVALID;
	} else {
#if defined( __WIN_API__ )
		senderInfo->address.protocolV4[0] = target.sin_addr.S_un.S_un_b.s_b1;
		senderInfo->address.protocolV4[1] = target.sin_addr.S_un.S_un_b.s_b2;
		senderInfo->address.protocolV4[2] = target.sin_addr.S_un.S_un_b.s_b3;
		senderInfo->address.protocolV4[3] = target.sin_addr.S_un.S_un_b.s_b4;
#elif defined( __POSIX__ )
        memcpy( &senderInfo->address.protocolV4[0], &target.sin_addr.s_addr, sizeof( target.sin_addr.s_addr ) );
#endif

		senderInfo->port = ( uint16_t )Endian::NetworkToHostUnsigned( target.sin_port, sizeof( target.sin_port ) );
	}
}

/*
====================
xiTCP::Connect

	Used internally to start the client to server connection
====================
*/
bool xiTCP::Connect( const addressInfo_s * const listenInfo ) {
	sockaddr_in target;
	int targetLength = ( int )sizeof( target );
	memset( &target, 0, sizeof( target ) );

#if defined( __WIN_API__ )
	target.sin_family = AF_INET;
	target.sin_addr.S_un.S_un_b.s_b1 = listenInfo->address.protocolV4[0];
	target.sin_addr.S_un.S_un_b.s_b2 = listenInfo->address.protocolV4[1];
	target.sin_addr.S_un.S_un_b.s_b3 = listenInfo->address.protocolV4[2];
	target.sin_addr.S_un.S_un_b.s_b4 = listenInfo->address.protocolV4[3];
#elif defined( __POSIX__ )
    memcpy( &target.sin_addr.s_addr, &listenInfo->address.protocolV4[0], sizeof( target.sin_addr.s_addr ) );
#endif

	target.sin_port = ( uint16_t )Endian::HostToNetworkUnsigned( listenInfo->port, sizeof( listenInfo->port ) );

	const int connectResult = connect( nativeHandle, ( sockaddr * )&target, targetLength );
	if ( connectResult == SOCKET_ERROR ) {
		return false;
	}

	return true;
}

/*
====================
xiTCP::ReadIntoBuffer

	Calls the operating system's recv function to read from the TCP connection
====================
*/
byteLen_t xiTCP::ReadIntoBuffer( char * const buffer, const int32_t bufferLength ) {
	return recv( nativeHandle, buffer, bufferLength, 0 );
}

/*
====================
xiTCP::SendBuffer

	Calls the operating system's send function to send a buffer down the connection
====================
*/
byteLen_t xiTCP::SendBuffer( const char * const buffer, const int32_t bufferLength ) {
	return send( nativeHandle, buffer, bufferLength, 0 );
}

/*
====================
xiTCP::xiTCP

	Constructor
	Defaults a TCP connection as not bound
====================
*/
xiTCP::xiTCP() {
	status = STATUS_NOT_BOUND;
}

/*
====================
xiTCP::~xiTCP

	Deconstructor
	Protobase does the important destruction
====================
*/
xiTCP::~xiTCP() {
}
<|endoftext|>


<commit_before>#include "DuplicateSession.h"
#include <MessageDuplicateDataRequest.pb.h>
#include <BlockHub.h>
#include <MRT.h>
#include <MasterSession.h>
#include <MessageSyncBlock.pb.h>

DuplicateSession::DuplicateSession()
{

}

DuplicateSession::DuplicateSession( uptr<MessageDuplicateBlock> msg )
{
    this->message_block_ = move_ptr( msg );

    this->path_          = this->message_block_->path();
    this->part_id_       = this->message_block_->partid();
    this->file_offset_   = this->message_block_->fileoffset();
    this->remote_index_  = this->message_block_->index();
    this->remote_ip_     = this->message_block_->address();

    this->index_ = BlockHub::Instance()->FindBlock( this->path_ ,
                                                    this->part_id_ );

    if(this->index_ == nullptr )
        this->index_ = BlockHub::Instance()->CreateBlock( (int)this->part_id_ ,
                                                          this->file_offset_ ,
                                                          this->path_ );

    Logger::Log( "duplicate session created % part:% size:% from %" ,
                  this->index_->Path ,
                  this->index_->PartId ,
                  this->index_->Size ,
                  this->remote_ip_ );

}

DuplicateSession::~DuplicateSession()
{
    if ( this->worker_ != nullptr )
    {
        MRT::SyncWorker::Stop( this->worker_ );
    }
}

void DuplicateSession::SendRequest()
{
    uptr<MessageDuplicateDataRequest> message = make_uptr( MessageDuplicateDataRequest );
    message->set_index     ( this->remote_index_ );
    message->set_token     ( "" );
    message->set_offset    ( this->block_offset_ );
    message->set_size      ( BLOCK_TRANSFER_SIZE );
    message->set_sessionid ( this->Id() );
    this->SendMessage      ( move_ptr( message ) );
    RetryTimer             ();

     Logger::Log( "duplicate session send request % part:% size:% from %" ,
                  this->index_->Path ,
                  this->index_->PartId ,
                  this->index_->Size ,
                  this->remote_ip_ );
}

void DuplicateSession::OnConnect()
{

}

bool DuplicateSession::DuplicateFinish()
{
    return this->finish_;
}

void DuplicateSession::RetryTimer()
{
    if ( this->worker_ != nullptr )
    {
        MRT::SyncWorker::Stop( this->worker_ );
    }

    this->worker_ = MRT::SyncWorker::Create( 15000 , [] ( MRT::SyncWorker* worker ) {

        DuplicateSession* session = (DuplicateSession*) worker->Data();
        if ( session == nullptr ) return true;
        session->SendRequest();
        return false;

    } , nullptr , this );

}

void DuplicateSession::AcceptBlock( uptr<MessageDuplicateData> msg )
{
    auto wsize = BlockHub::Instance()->WriteBlock( this->index_->Index ,
                                                   msg->offset() ,
                                                   msg->data().c_str() ,
                                                   msg->data().size() );
    this->index_->Size = msg->offset() + wsize;

    if ( msg->islast() )
    {
        BlockHub::Instance()->SaveBlockIndex( this->index_ );

        auto sync = make_uptr   ( MessageBlockMeta );
        sync->set_fileoffset    ( this->index_->FileOffset );
        sync->set_index         ( this->index_->Index );
        sync->set_partid        ( this->index_->PartId );
        sync->set_path          ( this->index_->Path );
        sync->set_size          ( this->index_->Size );
        sync->set_status        ( 0 );
        MasterSession::Instance ()->SendMessage( move_ptr( sync ) );

        Logger::Log( "duplicate path % part:% size:% from %" ,
                     this->index_->Path ,
                     this->index_->PartId ,
                     this->index_->Size ,
                     this->remote_ip_ );

        if ( this->worker_ != nullptr )
        {
            MRT::SyncWorker::Stop( this->worker_ );
        }
        this->finish_ = true;

        Logger::Log( "duplicate session close % part:% size:% from %" ,
                      this->index_->Path ,
                      this->index_->PartId ,
                      this->index_->Size ,
                      this->remote_ip_ );

        this->Close();
        return;
    }

    this->block_offset_ = msg->offset() + wsize;
    this->SendRequest();
}
<commit_msg>try fix bugs<commit_after>#include "DuplicateSession.h"
#include <MessageDuplicateDataRequest.pb.h>
#include <BlockHub.h>
#include <MRT.h>
#include <MasterSession.h>
#include <MessageSyncBlock.pb.h>
#include <DuplicateConnector.h>

DuplicateSession::DuplicateSession()
{

}

DuplicateSession::DuplicateSession( uptr<MessageDuplicateBlock> msg )
{
    this->message_block_ = move_ptr( msg );

    this->path_          = this->message_block_->path();
    this->part_id_       = this->message_block_->partid();
    this->file_offset_   = this->message_block_->fileoffset();
    this->remote_index_  = this->message_block_->index();
    this->remote_ip_     = this->message_block_->address();

    this->index_ = BlockHub::Instance()->FindBlock( this->path_ ,
                                                    this->part_id_ );

    if(this->index_ == nullptr )
        this->index_ = BlockHub::Instance()->CreateBlock( (int)this->part_id_ ,
                                                          this->file_offset_ ,
                                                          this->path_ );

    Logger::Log( "duplicate session created % part:% size:% from %" ,
                  this->index_->Path ,
                  this->index_->PartId ,
                  this->index_->Size ,
                  this->remote_ip_ );

}

DuplicateSession::~DuplicateSession()
{
    if ( this->worker_ != nullptr )
    {
        MRT::SyncWorker::Stop( this->worker_ );
    }
}

void DuplicateSession::SendRequest()
{
    uptr<MessageDuplicateDataRequest> message = make_uptr( MessageDuplicateDataRequest );
    message->set_index     ( this->remote_index_ );
    message->set_token     ( "" );
    message->set_offset    ( this->block_offset_ );
    message->set_size      ( BLOCK_TRANSFER_SIZE );
    message->set_sessionid ( this->Id() );
    this->SendMessage      ( move_ptr( message ) );
    RetryTimer             ();

     Logger::Log( "duplicate session send request % part:% size:% from %" ,
                  this->index_->Path ,
                  this->index_->PartId ,
                  this->index_->Size ,
                  this->remote_ip_ );
}

void DuplicateSession::OnConnect()
{

}

bool DuplicateSession::DuplicateFinish()
{
    return this->finish_;
}

void DuplicateSession::RetryTimer()
{
    if ( this->worker_ != nullptr )
    {
        MRT::SyncWorker::Stop( this->worker_ );
    }

    this->worker_ = MRT::SyncWorker::Create( 15000 , [] ( MRT::SyncWorker* worker ) {

        DuplicateSession* session = (DuplicateSession*) worker->Data();

        sptr<DuplicateConnector> connector = make_sptr( DuplicateConnector , move_ptr( session->message_block_ ) );
        MRT::Maraton::Instance()->Regist( connector );

        session->Close();
        return false;

    } , nullptr , this );

}

void DuplicateSession::AcceptBlock( uptr<MessageDuplicateData> msg )
{
    auto wsize = BlockHub::Instance()->WriteBlock( this->index_->Index ,
                                                   msg->offset() ,
                                                   msg->data().c_str() ,
                                                   msg->data().size() );
    this->index_->Size = msg->offset() + wsize;

    if ( msg->islast() )
    {
        BlockHub::Instance()->SaveBlockIndex( this->index_ );

        auto sync = make_uptr   ( MessageBlockMeta );
        sync->set_fileoffset    ( this->index_->FileOffset );
        sync->set_index         ( this->index_->Index );
        sync->set_partid        ( this->index_->PartId );
        sync->set_path          ( this->index_->Path );
        sync->set_size          ( this->index_->Size );
        sync->set_status        ( 0 );
        MasterSession::Instance ()->SendMessage( move_ptr( sync ) );

        Logger::Log( "duplicate path % part:% size:% from %" ,
                     this->index_->Path ,
                     this->index_->PartId ,
                     this->index_->Size ,
                     this->remote_ip_ );

        if ( this->worker_ != nullptr )
        {
            MRT::SyncWorker::Stop( this->worker_ );
        }
        this->finish_ = true;

        Logger::Log( "duplicate session close % part:% size:% from %" ,
                      this->index_->Path ,
                      this->index_->PartId ,
                      this->index_->Size ,
                      this->remote_ip_ );

        this->Close();
        return;
    }

    this->block_offset_ = msg->offset() + wsize;
    this->SendRequest();
}
<|endoftext|>


<commit_before>#include "Base64.h"

#include <cassert>

static char alphabet1[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static char alphabet2[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

using namespace std;

string
Base64::encode(const unsigned char * input, size_t length, const char * indent, int max_line_length) {
  string out;
  int line_len = 0;
  if (indent) out += indent;
  size_t pos = 0, rem = length;

  for (; rem >= 3; pos += 3, rem -= 3) {
    unsigned int tmp = (input[pos] << 16) | (input[pos + 1] << 8) | input[pos + 2];
    out += alphabet1[(tmp >> 18)];
    out += alphabet1[(tmp >> 12) & 0x3f];
    out += alphabet1[(tmp >> 6) & 0x3f];
    out += alphabet1[tmp & 0x3f ];
    line_len += 4;
    if (max_line_length && line_len >= max_line_length) {
      out += "\n";
      if (indent) out += indent;
      line_len = 0;
    }
  }
  if (rem == 2) {
    unsigned int tmp = (input[pos] << 16) | (input[pos + 1] << 8);
    out += alphabet1[(tmp >> 18)];
    out += alphabet1[(tmp >> 12) & 0x3f];
    out += alphabet1[(tmp >> 6) & 0x3f];
    out += '=';
  } else if (rem == 1) {
    unsigned int tmp = (input[pos] << 16);
    out += alphabet1[(tmp >> 18)];
    out += alphabet1[(tmp >> 12) & 0x3f];
    out += '=';
    out += '=';
  }
  return out;
}

unsigned char base64_decode_digit(char c) {
  switch (c) {
  case '+': case '-': return 62;
  case '/': case '_': return 63;
  default:
    if (isdigit(c)) return (unsigned char)(c - '0' + 26 + 26);
    else if (islower(c)) return (unsigned char)(c - 'a' + 26);
    else if (isupper(c)) return (unsigned char)(c - 'A');
    else assert(0);
  }
  return 0xff;
}

unsigned long long
Base64::decode64BitId(const std::string & input) {
  unsigned long long n = 0;
  for (unsigned int i = 0; i < input.size(); i++) {
    int c = base64_decode_digit(input[i]);
    n = 64 * n + c;
  }

  return n;
}

string
Base64::encode64BitId(unsigned long long a) {
  string s;
  while (a) {
    int b = a & 63;
    a = a >> 6;
    s = alphabet2[b] + s;
  }
  return s;
}
<commit_msg>add inline<commit_after>#include "Base64.h"

#include <cassert>

static char alphabet1[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static char alphabet2[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

using namespace std;

string
Base64::encode(const unsigned char * input, size_t length, const char * indent, int max_line_length) {
  string out;
  int line_len = 0;
  if (indent) out += indent;
  size_t pos = 0, rem = length;

  for (; rem >= 3; pos += 3, rem -= 3) {
    unsigned int tmp = (input[pos] << 16) | (input[pos + 1] << 8) | input[pos + 2];
    out += alphabet1[(tmp >> 18)];
    out += alphabet1[(tmp >> 12) & 0x3f];
    out += alphabet1[(tmp >> 6) & 0x3f];
    out += alphabet1[tmp & 0x3f ];
    line_len += 4;
    if (max_line_length && line_len >= max_line_length) {
      out += "\n";
      if (indent) out += indent;
      line_len = 0;
    }
  }
  if (rem == 2) {
    unsigned int tmp = (input[pos] << 16) | (input[pos + 1] << 8);
    out += alphabet1[(tmp >> 18)];
    out += alphabet1[(tmp >> 12) & 0x3f];
    out += alphabet1[(tmp >> 6) & 0x3f];
    out += '=';
  } else if (rem == 1) {
    unsigned int tmp = (input[pos] << 16);
    out += alphabet1[(tmp >> 18)];
    out += alphabet1[(tmp >> 12) & 0x3f];
    out += '=';
    out += '=';
  }
  return out;
}

static inline unsigned char base64_decode_digit(char c) {
  switch (c) {
  case '+': case '-': return 62;
  case '/': case '_': return 63;
  default:
    if (isdigit(c)) return (unsigned char)(c - '0' + 26 + 26);
    else if (islower(c)) return (unsigned char)(c - 'a' + 26);
    else if (isupper(c)) return (unsigned char)(c - 'A');
    else assert(0);
  }
  return 0xff;
}

unsigned long long
Base64::decode64BitId(const std::string & input) {
  unsigned long long n = 0;
  for (unsigned int i = 0; i < input.size(); i++) {
    int c = base64_decode_digit(input[i]);
    n = 64 * n + c;
  }

  return n;
}

string
Base64::encode64BitId(unsigned long long a) {
  string s;
  while (a) {
    int b = a & 63;
    a = a >> 6;
    s = alphabet2[b] + s;
  }
  return s;
}
<|endoftext|>


<commit_before>#include <math.h>
#include <stdio.h>
#include <ratio>

#include "pyramid.h"
#include "HalideBuffer.h"

#include <vector>
using std::vector;
using namespace Halide;

template<bool B, typename T>
struct cond {
    static constexpr bool value = B;
    using type = T;
};

template <typename First, typename... Rest>
struct select : std::conditional<First::value, First, typename select<Rest...>::type> { };

template<typename First>
struct select<First> {
    //static_assert(T::value, "No case of select was chosen");
    using type = std::conditional<First::value, typename First::type, void>;
};

template<int a>
struct tester : public select<cond<a == 0, std::ratio<1, 2>>,
                              cond<a == 1, std::ratio<3, 2>>,
                              cond<a == 2, std::ratio<7, 2>>>::type {};

int main(int argc, char **argv) {
    Image<float> input(1024, 1024);

    using T0 = tester<0>::type; printf("t0 %d %d\n", (int)T0::num, (int)T0::den);
    using T1 = tester<1>::type; printf("t0 %d %d\n", (int)T1::num, (int)T1::den);
    using T2 = tester<2>::type; printf("t0 %d %d\n", (int)T2::num, (int)T2::den);
    //using T3 = tester<3>::type; printf("t0 %d %d\n", (int)T3::num, (int)T3::den);

    // Put some junk in the input. Keep it to small integers so the float averaging stays exact.
    for (int y = 0; y < input.height(); y++) {
        for (int x = 0; x < input.width(); x++) {
            input(x, y) = ((x * 17 + y)/8) % 32;
        }
    }

    vector<Image<float>> levels(10);

    for (int l = 0; l < 10; l++) {
        levels[l] = Image<float>(1024 >> l, 1024 >> l);
    }

    // Will throw a compiler error if we didn't compile the generator with 10 levels.
    pyramid(input,
            levels[0], levels[1], levels[2], levels[3], levels[4],
            levels[5], levels[6], levels[7], levels[8], levels[9]);

    // The bottom level should be the input
    for (int y = 0; y < input.height(); y++) {
        for (int x = 0; x < input.width(); x++) {
            if (input(x, y) != levels[0](x, y)) {
                printf("input(%d, %d) = %f, but levels[0](%d, %d) = %f\n",
                       x, y, input(x, y), x, y, levels[0](x, y));
                return -1;
            }
        }
    }

    // The remaining levels should be averaging of the levels above them.
    for (int l = 1; l < 10; l++) {
        for (int y = 0; y < input.height() >> l; y++) {
            for (int x = 0; x < input.width() >> l; x++) {
                float correct = (levels[l-1](2*x, 2*y) +
                                 levels[l-1](2*x+1, 2*y) +
                                 levels[l-1](2*x, 2*y+1) +
                                 levels[l-1](2*x+1, 2*y+1))/4;
                float actual = levels[l](x, y);
                if (correct != actual) {
                    printf("levels[%d](%d, %d) = %f instead of %f\n",
                           l, x, y, actual, correct);
                    return -1;
                }
            }
        }
    }

    printf("Success!\n");
    return 0;
}
<commit_msg>remove scalpel left in patient<commit_after>#include <math.h>
#include <stdio.h>

#include "pyramid.h"
#include "HalideBuffer.h"

#include <vector>
using std::vector;
using namespace Halide;

int main(int argc, char **argv) {
    Image<float> input(1024, 1024);

    // Put some junk in the input. Keep it to small integers so the float averaging stays exact.
    for (int y = 0; y < input.height(); y++) {
        for (int x = 0; x < input.width(); x++) {
            input(x, y) = ((x * 17 + y)/8) % 32;
        }
    }

    vector<Image<float>> levels(10);

    for (int l = 0; l < 10; l++) {
        levels[l] = Image<float>(1024 >> l, 1024 >> l);
    }

    // Will throw a compiler error if we didn't compile the generator with 10 levels.
    pyramid(input,
            levels[0], levels[1], levels[2], levels[3], levels[4],
            levels[5], levels[6], levels[7], levels[8], levels[9]);

    // The bottom level should be the input
    for (int y = 0; y < input.height(); y++) {
        for (int x = 0; x < input.width(); x++) {
            if (input(x, y) != levels[0](x, y)) {
                printf("input(%d, %d) = %f, but levels[0](%d, %d) = %f\n",
                       x, y, input(x, y), x, y, levels[0](x, y));
                return -1;
            }
        }
    }

    // The remaining levels should be averaging of the levels above them.
    for (int l = 1; l < 10; l++) {
        for (int y = 0; y < input.height() >> l; y++) {
            for (int x = 0; x < input.width() >> l; x++) {
                float correct = (levels[l-1](2*x, 2*y) +
                                 levels[l-1](2*x+1, 2*y) +
                                 levels[l-1](2*x, 2*y+1) +
                                 levels[l-1](2*x+1, 2*y+1))/4;
                float actual = levels[l](x, y);
                if (correct != actual) {
                    printf("levels[%d](%d, %d) = %f instead of %f\n",
                           l, x, y, actual, correct);
                    return -1;
                }
            }
        }
    }

    printf("Success!\n");
    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: addrdlg.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 17:14:38 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _ADDRDLG_HXX
#define _ADDRDLG_HXX

#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif

class SwAddrDlg : public SfxSingleTabDialog
{
public:

     SwAddrDlg( Window* pParent, SfxItemSet& rSet );
    ~SwAddrDlg();
};

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1462); FILE MERGED 2005/09/05 13:44:55 rt 1.1.1.1.1462.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: addrdlg.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 08:58:21 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _ADDRDLG_HXX
#define _ADDRDLG_HXX

#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif

class SwAddrDlg : public SfxSingleTabDialog
{
public:

     SwAddrDlg( Window* pParent, SfxItemSet& rSet );
    ~SwAddrDlg();
};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: colwd.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 15:45:41 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SVX_DLGUTIL_HXX //autogen
#include <svx/dlgutil.hxx>
#endif

#ifndef _COLWD_HXX
#include <colwd.hxx>
#endif
#ifndef _TABLEMGR_HXX
#include <tablemgr.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _WDOCSH_HXX
#include <wdocsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _SWMODULE_HXX
#include <swmodule.hxx>
#endif
#ifndef _MODCFG_HXX
#include <modcfg.hxx>
#endif
#ifndef _USRPREF_HXX
#include <usrpref.hxx>
#endif

#ifndef _CMDID_H
#include <cmdid.h>
#endif
#ifndef _COLWD_HRC
#include <colwd.hrc>
#endif
#ifndef _TABLE_HRC
#include <table.hrc>
#endif

IMPL_LINK_INLINE_START( SwTableWidthDlg, LoseFocusHdl, Edit *, EMPTYARG )
{
    USHORT nId = (USHORT)aColEdit.GetValue()-1;
    const SwTwips lWidth = rFnc.GetColWidth(nId);
    aWidthEdit.SetValue(aWidthEdit.Normalize(lWidth), FUNIT_TWIP);
    aWidthEdit.SetMax(aWidthEdit.Normalize(rFnc.GetMaxColWidth(nId)), FUNIT_TWIP);
    return 0;
}
IMPL_LINK_INLINE_END( SwTableWidthDlg, LoseFocusHdl, Edit *, EMPTYARG )

SwTableWidthDlg::SwTableWidthDlg(Window *pParent, SwTableFUNC &rTableFnc ) :

    SvxStandardDialog( pParent, SW_RES(DLG_COL_WIDTH) ),

    aColFT(this,        SW_RES(FT_COL)),
    aColEdit(this,      SW_RES(ED_COL)),
    aWidthFT(this,      SW_RES(FT_WIDTH)),
    aWidthEdit(this,    SW_RES(ED_WIDTH)),
    aWidthFL(this,     SW_RES(FL_WIDTH)),
    aOKBtn(this,        SW_RES(BT_OK)),
    aCancelBtn(this,    SW_RES(BT_CANCEL)),
    aHelpBtn(this,      SW_RES(BT_HELP)),
    rFnc(rTableFnc)
{
    FreeResource();

    BOOL bIsWeb = rTableFnc.GetShell()
                    ? 0 != PTR_CAST( SwWebDocShell,
                            rTableFnc.GetShell()->GetView().GetDocShell() )
                    : FALSE;
    FieldUnit eFieldUnit = SW_MOD()->GetUsrPref( bIsWeb )->GetMetric();
    ::SetFieldUnit(aWidthEdit, eFieldUnit );

    aColEdit.SetValue( rFnc.GetCurColNum() +1 );
    aWidthEdit.SetMin(aWidthEdit.Normalize(MINLAY), FUNIT_TWIP);
    if(!aWidthEdit.GetMin())
        aWidthEdit.SetMin(1);

    if(rFnc.GetColCount() == 0)
        aWidthEdit.SetMin(aWidthEdit.Normalize(rFnc.GetColWidth(0)), FUNIT_TWIP);
    aColEdit.SetMax(rFnc.GetColCount() +1 );
    aColEdit.SetModifyHdl(LINK(this,SwTableWidthDlg, LoseFocusHdl));
    LoseFocusHdl();
}

void SwTableWidthDlg::Apply()
{
    rFnc.InitTabCols();
    rFnc.SetColWidth( aColEdit.GetValue()-1,
            aWidthEdit.Denormalize(aWidthEdit.GetValue(FUNIT_TWIP)));
}

<commit_msg>INTEGRATION: CWS tune03 (1.6.580); FILE MERGED 2004/07/19 19:11:42 mhu 1.6.580.1: #i29979# Added SW_DLLPUBLIC/PRIVATE (see swdllapi.h) to exported symbols/classes.<commit_after>/*************************************************************************
 *
 *  $RCSfile: colwd.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-23 09:08:43 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#pragma hdrstop

#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SVX_DLGUTIL_HXX //autogen
#include <svx/dlgutil.hxx>
#endif

#ifndef _COLWD_HXX
#include <colwd.hxx>
#endif
#ifndef _TABLEMGR_HXX
#include <tablemgr.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _WDOCSH_HXX
#include <wdocsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _SWMODULE_HXX
#include <swmodule.hxx>
#endif
#ifndef _MODCFG_HXX
#include <modcfg.hxx>
#endif
#ifndef _USRPREF_HXX
#include <usrpref.hxx>
#endif

#ifndef _CMDID_H
#include <cmdid.h>
#endif
#ifndef _COLWD_HRC
#include <colwd.hrc>
#endif
#ifndef _TABLE_HRC
#include <table.hrc>
#endif

IMPL_LINK_INLINE_START( SwTableWidthDlg, LoseFocusHdl, Edit *, EMPTYARG )
{
    USHORT nId = (USHORT)aColEdit.GetValue()-1;
    const SwTwips lWidth = rFnc.GetColWidth(nId);
    aWidthEdit.SetValue(aWidthEdit.Normalize(lWidth), FUNIT_TWIP);
    aWidthEdit.SetMax(aWidthEdit.Normalize(rFnc.GetMaxColWidth(nId)), FUNIT_TWIP);
    return 0;
}
IMPL_LINK_INLINE_END( SwTableWidthDlg, LoseFocusHdl, Edit *, EMPTYARG )

SwTableWidthDlg::SwTableWidthDlg(Window *pParent, SwTableFUNC &rTableFnc ) :

    SvxStandardDialog( pParent, SW_RES(DLG_COL_WIDTH) ),

    aColFT(this,        SW_RES(FT_COL)),
    aColEdit(this,      SW_RES(ED_COL)),
    aWidthFT(this,      SW_RES(FT_WIDTH)),
    aWidthEdit(this,    SW_RES(ED_WIDTH)),
    aWidthFL(this,     SW_RES(FL_WIDTH)),
    aOKBtn(this,        SW_RES(BT_OK)),
    aCancelBtn(this,    SW_RES(BT_CANCEL)),
    aHelpBtn(this,      SW_RES(BT_HELP)),
    rFnc(rTableFnc)
{
    FreeResource();

    BOOL bIsWeb = rTableFnc.GetShell()
                    ? 0 != PTR_CAST( SwWebDocShell,
                            rTableFnc.GetShell()->GetView().GetDocShell() )
                    : FALSE;
    FieldUnit eFieldUnit = SW_MOD()->GetUsrPref( bIsWeb )->GetMetric();
    ::SetFieldUnit(aWidthEdit, eFieldUnit );

    aColEdit.SetValue( rFnc.GetCurColNum() +1 );
    aWidthEdit.SetMin(aWidthEdit.Normalize(MINLAY), FUNIT_TWIP);
    if(!aWidthEdit.GetMin())
        aWidthEdit.SetMin(1);

    if(rFnc.GetColCount() == 0)
        aWidthEdit.SetMin(aWidthEdit.Normalize(rFnc.GetColWidth(0)), FUNIT_TWIP);
    aColEdit.SetMax(rFnc.GetColCount() +1 );
    aColEdit.SetModifyHdl(LINK(this,SwTableWidthDlg, LoseFocusHdl));
    LoseFocusHdl();
}

void SwTableWidthDlg::Apply()
{
    rFnc.InitTabCols();
    rFnc.SetColWidth( aColEdit.GetValue()-1,
            aWidthEdit.Denormalize(aWidthEdit.GetValue(FUNIT_TWIP)));
}

<|endoftext|>