<commit_before>#include "Math/Polynomial.h"
#include "Math/Derivator.h"
#include "Math/IFunction.h"
#include "Math/Functor.h"
#include "Math/WrappedFunction.h"
#include "Math/WrappedParamFunction.h"
#include <iostream>
#include <vector>
#include <cassert>
#include <cmath>

#ifdef HAVE_ROOTLIBS

#include "TStopwatch.h"
#include "TF1.h"
#include "Math/WrappedTF1.h"
#include "Math/WrappedMultiTF1.h"
#include "Math/DistFunc.h"

#endif

const double ERRORLIMIT = 1E-5;

typedef double ( * FP ) ( double, void * );
typedef double ( * FP2 ) ( double );

double myfunc ( double x, void * ) {

  return std::pow( x, 1.5);
}

double myfunc2 ( double x) {
  return std::pow( x, 1.5);
}

int testDerivation() {

   int status = 0;

  // Derivative of an IGenFunction
  // Works when compiled c++, compiled ACLiC, interpreted by CINT
  ROOT::Math::Polynomial *f1 = new ROOT::Math::Polynomial(2);

  std::vector<double> p(3);
  p[0] = 2;
  p[1] = 3;
  p[2] = 4;
  f1->SetParameters(&p[0]);

  ROOT::Math::Derivator *der = new ROOT::Math::Derivator(*f1);

  double step = 1E-8;
  double x0 = 2;

  der->SetFunction(*f1);
  double result = der->Eval(x0);
  std::cout << "Derivative of function inheriting from IGenFunction f(x) = 2 + 3x + 4x^2 at x = 2" << std::endl;
  std::cout << "Return code:  " << der->Status() << std::endl;
  std::cout << "Result:       " << result << " +/- " << der->Error() << std::endl;
  std::cout << "Exact result: " << f1->Derivative(x0) << std::endl;
  std::cout << "EvalForward:  " << der->EvalForward(*f1, x0) << std::endl;
  std::cout << "EvalBackward: " << der->EvalBackward(x0, step) << std::endl << std::endl;;
  status += fabs(result-f1->Derivative(x0)) > ERRORLIMIT;

  // Derivative of a free function
  // Works when compiled c++, compiled ACLiC, does not work when interpreted by CINT
  FP f2 = &myfunc;
  der->SetFunction(f2);

  std::cout << "Derivative of a free function f(x) = x^(3/2) at x = 2" << std::endl;
  std::cout << "EvalCentral:  " << der->EvalCentral(x0) << std::endl;
  std::cout << "EvalForward:  " << der->EvalForward(x0) << std::endl;
  std::cout << "EvalBackward: " << der->EvalBackward(x0) << std::endl;

  std::cout << "Exact result: " << 1.5*sqrt(x0) << std::endl << std::endl;

  status += fabs(der->EvalCentral(x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalForward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalBackward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;

  // Derivative of a free function wrapped in an IGenFunction
  // Works when compiled c++, compiled ACLiC, does not work when interpreted by CINT
  ROOT::Math::Functor1D *f3 = new ROOT::Math::Functor1D (&myfunc2);

  std::cout << "Derivative of a free function wrapped in a Functor f(x) = x^(3/2) at x = 2" << std::endl;
  std::cout << "EvalCentral:  " << der->Eval( *f3, x0) << std::endl;
  der->SetFunction(*f3);
  std::cout << "EvalForward:  " << der->EvalForward(x0) << std::endl;
  std::cout << "EvalBackward: " << der->EvalBackward(x0) << std::endl;
  std::cout << "Exact result: " << 1.5*sqrt(x0) << std::endl << std::endl;

  status += fabs(der->Eval( *f3, x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalForward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalBackward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;

  // tets case when an empty Derivator is used

  ROOT::Math::Derivator der2;
  std::cout << "Tes a derivator without a function" << std::endl;
  std::cout << der2.Eval(1.0) << std::endl;

  // Derivative of a multidim TF1 function

// #ifdef LATER
//   TF2 * f2d = new TF2("f2d","x*x + y*y",-10,10,-10,10);
//   // find gradient at x={1,1}
//   double vx[2] = {1.,2.};
//   ROOT::Math::WrappedTF1 fx(*f2d);

//   std::cout << "Derivative of a  f(x,y) = x^2 + y^2 at x = 1,y=2" << std::endl;
//   std::cout << "df/dx  = " << der->EvalCentral(fx,1.) << std::endl;
//   WrappedFunc fy(*f2d,0,vx);
//   std::cout << "df/dy  = " << der->EvalCentral(fy,2.) << std::endl;
// #endif

  return status;
}

#ifdef HAVE_ROOTLIBS

void testDerivPerf() {

   std::cout << "\n\n***************************************************************\n";
   std::cout << "Test derivation performances....\n\n";

  ROOT::Math::Polynomial f1(2);
  double p[3] = {2,3,4};
  f1.SetParameters(p);

  TStopwatch timer;
  int n = 1000000;
  double x1 = 0; double x2 = 10;
  double dx = (x2-x1)/double(n);

  timer.Start();
  double s1 = 0;
  ROOT::Math::Derivator der(f1);
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= der.EvalCentral(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator :\t" << timer.RealTime() << std::endl;
  int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     ROOT::Math::Derivator der2(f1);
     double x = x1 + dx*i;
     s1+= der2.EvalForward(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(2):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= ROOT::Math::Derivator::Eval(f1,x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(3):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  TF1 f2("pol","pol2",0,10);
  f2.SetParameters(p);

  timer.Start();
  double s2 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s2+= f2.Derivative(x);
  }
  timer.Stop();
  std::cout << "Time using TF1::Derivative :\t\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18);
  std::cout << s2 << std::endl;
  std::cout.precision(pr);

}

double userFunc(const double *x, const double *y) {
   return std::exp(-x[0]);
}
double userFunc1(double x) { return userFunc(&x, 0); }

double userFunc2(const double * x) { return userFunc(x, 0); }

void testDerivPerfUser() {

   std::cout << "\n\n***************************************************************\n";
   std::cout << "Test derivation performances - using a User function\n\n";

  ROOT::Math::WrappedFunction<> f1(userFunc1);

  TStopwatch timer;
  int n = 1000000;
  double x1 = 0; double x2 = 10;
  double dx = (x2-x1)/double(n);

  timer.Start();
  double s1 = 0;
  ROOT::Math::Derivator der(f1);
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= der.EvalCentral(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator :\t" << timer.RealTime() << std::endl;
  int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     ROOT::Math::Derivator der2(f1);
     double x = x1 + dx*i;
     s1+= der2.EvalForward(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(2):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= ROOT::Math::Derivator::Eval(f1,x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(3):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  TF1 f2("uf",userFunc,0,10,0);

  timer.Start();
  double s2 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s2+= f2.Derivative(x);
  }
  timer.Stop();
  std::cout << "Time using TF1::Derivative :\t\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18);
  std::cout << s2 << std::endl;
  std::cout.precision(pr);

  //typedef double( * FN ) (const double *, const double * );
  ROOT::Math::WrappedMultiFunction<> f3(userFunc2,1);
  timer.Start();
  s1 = 0;
  double xx[1];
  for (int i = 0; i < n; ++i) {
     xx[0] = x1 + dx*i;
     s1+= ROOT::Math::Derivator::Eval(f3,xx,0);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator Multi:\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

}

double gausFunc( const double * x, const double * p) {
   return p[0] * ROOT::Math::normal_pdf(x[0], p[2], p[1] );
}

void testDerivPerfParam() {

   std::cout << "\n\n***************************************************************\n";
   std::cout << "Test derivation performances - using a Gaussian Param function\n\n";

   //TF1 gaus("gaus","gaus",-10,10);
   TF1 gaus("gaus",gausFunc,-10,10,3);
  double params[3] = {10,1.,1.};
  gaus.SetParameters(params);

  ROOT::Math::WrappedTF1 f1(gaus);

  TStopwatch timer;
  int n = 300000;
  double x1 = 0; double x2 = 10;
  double dx = (x2-x1)/double(n);

  timer.Start();
  double s1 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     // param derivatives
     s1 += ROOT::Math::Derivator::Eval(f1,x,params,0);
     s1 += ROOT::Math::Derivator::Eval(f1,x,params,1);
     s1 += ROOT::Math::Derivator::Eval(f1,x,params,2);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator (1D) :\t" << timer.RealTime() << std::endl;
  int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  ROOT::Math::WrappedParamFunction<> f2(&gausFunc,1,params,params+3);
  double xx[1];

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     xx[0] = x1 + dx*i;
     s1 += ROOT::Math::Derivator::Eval(f2,xx,params,0);
     s1 += ROOT::Math::Derivator::Eval(f2,xx,params,1);
     s1 += ROOT::Math::Derivator::Eval(f2,xx,params,2);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(ND):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  // test that func parameters have not been changed
  assert( std::fabs(params[0] - gaus.GetParameter(0)) < 1.E-15);
  assert( std::fabs(params[1] - gaus.GetParameter(1)) < 1.E-15);
  assert( std::fabs(params[2] - gaus.GetParameter(2)) < 1.E-15);

  timer.Start();
  s1 = 0;
  double g[3];
  for (int i = 0; i < n; ++i) {
     xx[0] = x1 + dx*i;
     gaus.GradientPar(xx,g,1E-8);
     s1 += g[0];
     s1 += g[1];
     s1 += g[2];
  }
  timer.Stop();
  std::cout << "Time using TF1::ParamGradient:\t\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

}

#endif

int main() {

  int status = 0;

  status += testDerivation();

#ifdef HAVE_ROOTLIBS
  testDerivPerf();
  testDerivPerfUser();
  testDerivPerfParam();
#endif

  return status;

}
<commit_msg>Fix a warning<commit_after>#include "Math/Polynomial.h"
#include "Math/Derivator.h"
#include "Math/IFunction.h"
#include "Math/Functor.h"
#include "Math/WrappedFunction.h"
#include "Math/WrappedParamFunction.h"
#include <iostream>
#include <vector>
#include <cassert>
#include <cmath>

#ifdef HAVE_ROOTLIBS

#include "TStopwatch.h"
#include "TF1.h"
#include "Math/WrappedTF1.h"
#include "Math/WrappedMultiTF1.h"
#include "Math/DistFunc.h"

#endif

const double ERRORLIMIT = 1E-5;

typedef double ( * FP ) ( double, void * );
typedef double ( * FP2 ) ( double );

double myfunc ( double x, void * ) {

  return std::pow( x, 1.5);
}

double myfunc2 ( double x) {
  return std::pow( x, 1.5);
}

int testDerivation() {

   int status = 0;

  // Derivative of an IGenFunction
  // Works when compiled c++, compiled ACLiC, interpreted by CINT
  ROOT::Math::Polynomial *f1 = new ROOT::Math::Polynomial(2);

  std::vector<double> p(3);
  p[0] = 2;
  p[1] = 3;
  p[2] = 4;
  f1->SetParameters(&p[0]);

  ROOT::Math::Derivator *der = new ROOT::Math::Derivator(*f1);

  double step = 1E-8;
  double x0 = 2;

  der->SetFunction(*f1);
  double result = der->Eval(x0);
  std::cout << "Derivative of function inheriting from IGenFunction f(x) = 2 + 3x + 4x^2 at x = 2" << std::endl;
  std::cout << "Return code:  " << der->Status() << std::endl;
  std::cout << "Result:       " << result << " +/- " << der->Error() << std::endl;
  std::cout << "Exact result: " << f1->Derivative(x0) << std::endl;
  std::cout << "EvalForward:  " << der->EvalForward(*f1, x0) << std::endl;
  std::cout << "EvalBackward: " << der->EvalBackward(x0, step) << std::endl << std::endl;;
  status += fabs(result-f1->Derivative(x0)) > ERRORLIMIT;

  // Derivative of a free function
  // Works when compiled c++, compiled ACLiC, does not work when interpreted by CINT
  FP f2 = &myfunc;
  der->SetFunction(f2);

  std::cout << "Derivative of a free function f(x) = x^(3/2) at x = 2" << std::endl;
  std::cout << "EvalCentral:  " << der->EvalCentral(x0) << std::endl;
  std::cout << "EvalForward:  " << der->EvalForward(x0) << std::endl;
  std::cout << "EvalBackward: " << der->EvalBackward(x0) << std::endl;

  std::cout << "Exact result: " << 1.5*sqrt(x0) << std::endl << std::endl;

  status += fabs(der->EvalCentral(x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalForward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalBackward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;

  // Derivative of a free function wrapped in an IGenFunction
  // Works when compiled c++, compiled ACLiC, does not work when interpreted by CINT
  ROOT::Math::Functor1D *f3 = new ROOT::Math::Functor1D (&myfunc2);

  std::cout << "Derivative of a free function wrapped in a Functor f(x) = x^(3/2) at x = 2" << std::endl;
  std::cout << "EvalCentral:  " << der->Eval( *f3, x0) << std::endl;
  der->SetFunction(*f3);
  std::cout << "EvalForward:  " << der->EvalForward(x0) << std::endl;
  std::cout << "EvalBackward: " << der->EvalBackward(x0) << std::endl;
  std::cout << "Exact result: " << 1.5*sqrt(x0) << std::endl << std::endl;

  status += fabs(der->Eval( *f3, x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalForward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;
  status += fabs(der->EvalBackward(x0)-1.5*sqrt(x0)) > ERRORLIMIT;

  // tets case when an empty Derivator is used

  ROOT::Math::Derivator der2;
  std::cout << "Tes a derivator without a function" << std::endl;
  std::cout << der2.Eval(1.0) << std::endl;

  // Derivative of a multidim TF1 function

// #ifdef LATER
//   TF2 * f2d = new TF2("f2d","x*x + y*y",-10,10,-10,10);
//   // find gradient at x={1,1}
//   double vx[2] = {1.,2.};
//   ROOT::Math::WrappedTF1 fx(*f2d);

//   std::cout << "Derivative of a  f(x,y) = x^2 + y^2 at x = 1,y=2" << std::endl;
//   std::cout << "df/dx  = " << der->EvalCentral(fx,1.) << std::endl;
//   WrappedFunc fy(*f2d,0,vx);
//   std::cout << "df/dy  = " << der->EvalCentral(fy,2.) << std::endl;
// #endif

  return status;
}

#ifdef HAVE_ROOTLIBS

void testDerivPerf() {

   std::cout << "\n\n***************************************************************\n";
   std::cout << "Test derivation performances....\n\n";

  ROOT::Math::Polynomial f1(2);
  double p[3] = {2,3,4};
  f1.SetParameters(p);

  TStopwatch timer;
  int n = 1000000;
  double x1 = 0; double x2 = 10;
  double dx = (x2-x1)/double(n);

  timer.Start();
  double s1 = 0;
  ROOT::Math::Derivator der(f1);
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= der.EvalCentral(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator :\t" << timer.RealTime() << std::endl;
  int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     ROOT::Math::Derivator der2(f1);
     double x = x1 + dx*i;
     s1+= der2.EvalForward(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(2):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= ROOT::Math::Derivator::Eval(f1,x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(3):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  TF1 f2("pol","pol2",0,10);
  f2.SetParameters(p);

  timer.Start();
  double s2 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s2+= f2.Derivative(x);
  }
  timer.Stop();
  std::cout << "Time using TF1::Derivative :\t\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18);
  std::cout << s2 << std::endl;
  std::cout.precision(pr);

}

double userFunc(const double *x, const double *) {
   return std::exp(-x[0]);
}
double userFunc1(double x) { return userFunc(&x, 0); }

double userFunc2(const double * x) { return userFunc(x, 0); }

void testDerivPerfUser() {

   std::cout << "\n\n***************************************************************\n";
   std::cout << "Test derivation performances - using a User function\n\n";

  ROOT::Math::WrappedFunction<> f1(userFunc1);

  TStopwatch timer;
  int n = 1000000;
  double x1 = 0; double x2 = 10;
  double dx = (x2-x1)/double(n);

  timer.Start();
  double s1 = 0;
  ROOT::Math::Derivator der(f1);
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= der.EvalCentral(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator :\t" << timer.RealTime() << std::endl;
  int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     ROOT::Math::Derivator der2(f1);
     double x = x1 + dx*i;
     s1+= der2.EvalForward(x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(2):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= ROOT::Math::Derivator::Eval(f1,x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(3):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  TF1 f2("uf",userFunc,0,10,0);

  timer.Start();
  double s2 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s2+= f2.Derivative(x);
  }
  timer.Stop();
  std::cout << "Time using TF1::Derivative :\t\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18);
  std::cout << s2 << std::endl;
  std::cout.precision(pr);

  //typedef double( * FN ) (const double *, const double * );
  ROOT::Math::WrappedMultiFunction<> f3(userFunc2,1);
  timer.Start();
  s1 = 0;
  double xx[1];
  for (int i = 0; i < n; ++i) {
     xx[0] = x1 + dx*i;
     s1+= ROOT::Math::Derivator::Eval(f3,xx,0);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator Multi:\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

}

double gausFunc( const double * x, const double * p) {
   return p[0] * ROOT::Math::normal_pdf(x[0], p[2], p[1] );
}

void testDerivPerfParam() {

   std::cout << "\n\n***************************************************************\n";
   std::cout << "Test derivation performances - using a Gaussian Param function\n\n";

   //TF1 gaus("gaus","gaus",-10,10);
   TF1 gaus("gaus",gausFunc,-10,10,3);
  double params[3] = {10,1.,1.};
  gaus.SetParameters(params);

  ROOT::Math::WrappedTF1 f1(gaus);

  TStopwatch timer;
  int n = 300000;
  double x1 = 0; double x2 = 10;
  double dx = (x2-x1)/double(n);

  timer.Start();
  double s1 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     // param derivatives
     s1 += ROOT::Math::Derivator::Eval(f1,x,params,0);
     s1 += ROOT::Math::Derivator::Eval(f1,x,params,1);
     s1 += ROOT::Math::Derivator::Eval(f1,x,params,2);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator (1D) :\t" << timer.RealTime() << std::endl;
  int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  ROOT::Math::WrappedParamFunction<> f2(&gausFunc,1,params,params+3);
  double xx[1];

  timer.Start();
  s1 = 0;
  for (int i = 0; i < n; ++i) {
     xx[0] = x1 + dx*i;
     s1 += ROOT::Math::Derivator::Eval(f2,xx,params,0);
     s1 += ROOT::Math::Derivator::Eval(f2,xx,params,1);
     s1 += ROOT::Math::Derivator::Eval(f2,xx,params,2);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Derivator(ND):\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

  // test that func parameters have not been changed
  assert( std::fabs(params[0] - gaus.GetParameter(0)) < 1.E-15);
  assert( std::fabs(params[1] - gaus.GetParameter(1)) < 1.E-15);
  assert( std::fabs(params[2] - gaus.GetParameter(2)) < 1.E-15);

  timer.Start();
  s1 = 0;
  double g[3];
  for (int i = 0; i < n; ++i) {
     xx[0] = x1 + dx*i;
     gaus.GradientPar(xx,g,1E-8);
     s1 += g[0];
     s1 += g[1];
     s1 += g[2];
  }
  timer.Stop();
  std::cout << "Time using TF1::ParamGradient:\t\t" << timer.RealTime() << std::endl;
  pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr);

}

#endif

int main() {

  int status = 0;

  status += testDerivation();

#ifdef HAVE_ROOTLIBS
  testDerivPerf();
  testDerivPerfUser();
  testDerivPerfParam();
#endif

  return status;

}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <Context.h>
#include <Filter.h>
#include <sstream>
#include <algorithm>
#include <i18n.h>
#include <util.h>
#include <text.h>
#include <CmdContext.h>
#include <CmdConfig.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdContext::CmdContext ()
{
  _keyword     = "context";
  _usage       = "task          context [<name> | subcommand]";
  _description = STRING_CMD_CONTEXT_USAGE;
  _read_only   = true;
  _displays_id = false;
}

////////////////////////////////////////////////////////////////////////////////
int CmdContext::execute (std::string& output)
{
  int rc = 0;
  std::stringstream out;

  // Get the non-attribute, non-fancy command line arguments.
  std::vector <std::string> words = context.cli.getWords ();

  if (words.size () > 0)
  {
    std::string subcommand = words[0];

    if (subcommand == "define")
      rc = defineContext (words, out);
    else if (subcommand == "delete")
      rc = deleteContext (words, out);
    else if (subcommand == "list")
      rc = listContexts (words, out);
    else if (subcommand == "none")
      rc = unsetContext (words, out);
    else if (subcommand == "show")
      rc = showContext (words, out);
    else
      rc = setContext (words, out);
  }

  output = out.str ();
  return rc;
}

////////////////////////////////////////////////////////////////////////////////
// Joins all the words in the specified interval <from, to) to one string,
// which is then returned.
//
// If to is specified as 0 (default value), all the remaining words will be joined.
//
std::string CmdContext::joinWords (std::vector <std::string>& words, unsigned int from, unsigned int to /* = 0 */)
{
  std::string value = "";

  if (to == 0)
    to = words.size();

  for (unsigned int i = from; i < to; ++i)
  {
    if (i > from)
      value += " ";

    value += words[i];
  }

  return value;
}

////////////////////////////////////////////////////////////////////////////////
// Returns all user defined contexts.
//
std::vector <std::string> CmdContext::getContexts ()
{
  std::vector <std::string> contexts;

  for (auto& name : context.config)
    if (name.first.substr (0, 8) == "context.")
      contexts.push_back (name.first.substr (8));

  return contexts;
}

////////////////////////////////////////////////////////////////////////////////
// Defines a new user-provided context.
//  - The context definition is written into .taskrc as a context.<name> variable.
//  - Deletion of the context requires confirmation if rc.confirmation=yes.
//
// Returns: 0 if the addition of the config variable was successful, 1 otherwise
//
// Invoked with: task context define <name> <filter>
// Example:      task context define home project:Home
//
int CmdContext::defineContext (std::vector <std::string>& words, std::stringstream& out)
{
  int rc = 0;
  bool confirmation = context.config.getBoolean ("confirmation");

  if (words.size () > 2)
  {
    std::string name = "context." + words[1];
    std::string value = joinWords (words, 2);

    // Check if the value is a proper filter by filtering current pending.data
    Filter filter;
    std::vector <Task> filtered;
    auto pending = context.tdb2.pending.get_tasks ();

    try
    {
      // This result is not used, and is just to check validity.
      context.cli.addRawFilter ("( " + value + " )");
      filter.subset (pending, filtered);
    }
    catch (std::string exception)
    {
      throw format (STRING_CMD_CONTEXT_DEF_ABRT2, exception);
    }

    // Make user explicitly confirm filters that are matching no pending tasks
    if (filtered.size () == 0)
      if (confirmation &&
          ! confirm (format (STRING_CMD_CONTEXT_DEF_CONF, value)))
        throw std::string (STRING_CMD_CONTEXT_DEF_ABRT);

    // Set context definition config variable
    bool success = CmdConfig::setConfigVariable (name, value, confirmation);

    if (success)
      out << format (STRING_CMD_CONTEXT_DEF_SUCC, words[1]) << "\n";
    else
    {
      out << format (STRING_CMD_CONTEXT_DEF_FAIL, words[1]) << "\n";
      rc = 1;
    }
  }
  else
  {
    out << STRING_CMD_CONTEXT_DEF_USAG << "\n";
    rc = 1;
  }

  return rc;
}

////////////////////////////////////////////////////////////////////////////////
// Deletes the specified context.
//  - If the deleted context is currently active, unset it.
//  - Deletion of the context requires confirmation if rc.confirmation=yes.
//
// Returns: 0 if the removal of the config variable was successful, 1 otherwise
//
// Invoked with: task context delete <name>
// Example:      task context delete home
//
int CmdContext::deleteContext (std::vector <std::string>& words, std::stringstream& out)
{
  int rc = 0;

  if (words.size () > 1)
  {
    // Delete the specified context
    std::string name = "context." + words[1];

    bool confirmation = context.config.getBoolean ("confirmation");
    rc = CmdConfig::unsetConfigVariable(name, confirmation);

    // If the currently set context was deleted, unset it
    std::string currentContext = context.config.get ("context");

    if (currentContext == words[1])
      CmdConfig::unsetConfigVariable("context", false);

    // Output feedback
    if (rc == 0)
      out << format (STRING_CMD_CONTEXT_DEL_SUCC, words[1]) << "\n";
    else
      out << format (STRING_CMD_CONTEXT_DEL_FAIL, words[1]) << "\n";
  }
  else
  {
    out << STRING_CMD_CONTEXT_DEL_USAG << "\n";
    rc = 1;
  }

  return rc;
}

////////////////////////////////////////////////////////////////////////////////
// Render a list of context names and their definitions.
//
// Returns: 0 the resulting list is non-empty, 1 otherwise
//
// Invoked with: task context list
// Example:      task context list
//
int CmdContext::listContexts (std::vector <std::string>& words, std::stringstream& out)
{
  int rc = 0;
  std::vector <std::string> contexts = getContexts();

  if (contexts.size ())
  {
    std::sort (contexts.begin (), contexts.end ());

    ViewText view;
    view.width (context.getWidth ());
    view.add (Column::factory ("string", "Name"));
    view.add (Column::factory ("string", "Definition"));
    view.add (Column::factory ("string", "Active"));

    Color label (context.config.get ("color.label"));
    view.colorHeader (label);

    std::string activeContext = context.config.get ("context");

    for (auto& userContext : contexts)
    {
      std::string definition = context.config.get ("context." + userContext);

      std::string active = "no";

      if (userContext == activeContext)
          active = "yes";

      int row = view.addRow ();
      view.set (row, 0, userContext);
      view.set (row, 1, definition);
      view.set (row, 2, active);
    }

    out << optionalBlankLine ()
        << view.render ()
        << optionalBlankLine ();
  }
  else
  {
    out << STRING_CMD_CONTEXT_LIST_EMPT << "\n";
    rc = 1;
  }

  return rc;
}

////////////////////////////////////////////////////////////////////////////////
// Sets the specified context as currently active.
//   - If some other context was active, the value of currently active context
//     is replaced, not added.
//   - Setting of the context does not require confirmation.
//
// Returns: 0 if the setting of the context was successful, 1 otherwise
//
// Invoked with: task context <name>
// Example:      task context home
//
int CmdContext::setContext (std::vector <std::string>& words, std::stringstream& out)
{
  int rc = 0;
  std::string value = words[0];
  std::vector <std::string> contexts = getContexts ();

  // Check that the specified context is defined
  if (std::find (contexts.begin (), contexts.end (), value) == contexts.end ())
    throw format (STRING_CMD_CONTEXT_SET_NFOU, value);

  // Set the active context.
  // Should always succeed, as we do not require confirmation.
  bool success = CmdConfig::setConfigVariable ("context", value, false);

  if (success)
    out << format (STRING_CMD_CONTEXT_SET_SUCC, value) << "\n";
  else
  {
    out << format (STRING_CMD_CONTEXT_SET_FAIL, value) << "\n";
    rc = 1;
  }

  return rc;
}

////////////////////////////////////////////////////////////////////////////////
// Shows the currently active context.
//
// Returns: Always returns 0.
//
// Invoked with: task context show
// Example:      task context show
//
int CmdContext::showContext (std::vector <std::string>& words, std::stringstream& out)
{
  std::string currentContext = context.config.get ("context");

  if (currentContext == "")
    out << STRING_CMD_CONTEXT_SHOW_EMPT << "\n";
  else
  {
    std::string currentFilter = context.config.get ("context." + currentContext);
    out << format (STRING_CMD_CONTEXT_SHOW, currentContext, currentFilter) << "\n";
  }

  return 0;
}

////////////////////////////////////////////////////////////////////////////////
// Unsets the currently active context.
//   - Unsetting of the context does not require confirmation.
//
// Returns: 0 if the unsetting of the context was successful, 1 otherwise (also
//          returned if no context is currently active)
//
// Invoked with: task context none
// Example:      task context none
//
int CmdContext::unsetContext (std::vector <std::string>& words, std::stringstream& out)
{
  int rc = 0;
  int status = CmdConfig::unsetConfigVariable ("context", false);

  if (status == 0)
    out << STRING_CMD_CONTEXT_NON_SUCC << "\n";
  else
  {
    out << STRING_CMD_CONTEXT_NON_FAIL << "\n";
    rc = 1;
  }

  return rc;
}

////////////////////////////////////////////////////////////////////////////////
CmdCompletionContext::CmdCompletionContext ()
{
  _keyword     = "_context";
  _usage       = "task          _context";
  _description = STRING_CMD_HCONTEXT_USAGE;
  _read_only   = true;
  _displays_id = false;
}

////////////////////////////////////////////////////////////////////////////////
int CmdCompletionContext::execute (std::string& output)
{
  std::vector <std::string> userContexts = CmdContext::getContexts ();

  for (auto& userContext : userContexts)
    output += userContext + "\n";

  return 0;
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>CmdContext: Converted from CLI to CLI2<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <Context.h>
#include <Filter.h>
#include <sstream>
#include <algorithm>
#include <i18n.h>
#include <util.h>
#include <text.h>
#include <CmdContext.h>
#include <CmdConfig.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdContext::CmdContext ()
{
  _keyword     = "context";
  _usage       = "task          context [<name> | subcommand]";
  _description = STRING_CMD_CONTEXT_USAGE;
  _read_only   = true;
  _displays_id = false;
}

////////////////////////////////////////////////////////////////////////////////
int CmdContext::execute (std::string& output)
{
  int rc = 0;
  std::stringstream out;

  // Get the non-attribute, non-fancy command line arguments.
  std::vector <std::string> words = context.cli2.getWords ();

  if (words.size () > 0)
  {
    std::string subcommand = words[0];

    if (subcommand == "define")
      rc = defineContext (words, out);
    else if (subcommand == "delete")
      rc = deleteContext (words, out);
    else if (subcommand == "list")
      rc = listContexts (words, out);
    else if (subcommand == "none")
      rc = unsetContext (words, out);
    else if (subcommand == "show")
      rc = showContext (words, out);
    else
      rc = setContext (words, out);
  }

  output = out.str ();
  return rc;
}

////////////////////////////////////////////////////////////////////////////////
// Joins all the words in the specified interval <from, to) to one string,
// which is then returned.
//
// If to is specified as 0 (default value), all the remaining words will be joined.
//
std::string CmdContext::joinWords (std::vector <std::string>& words, unsigned int from, unsigned int to /* = 0 */)
{
  std::string value = "";

  if (to == 0)
    to = words.size();

  for (unsigned int i = from; i < to; ++i)
  {
    if (i > from)
      value += " ";

    value += words[i];
  }

  return value;
}

////////////////////////////////////////////////////////////////////////////////
// Returns all user defined contexts.
//
std::vector <std::string> CmdContext::getContexts ()
{
  std::vector <std::string> contexts;

  for (auto& name : context.config)
    if (name.first.substr (0, 8) == "context.")
      contexts.push_back (name.first.substr (8));

  return contexts;
}

////////////////////////////////////////////////////////////////////////////////
// Defines a new user-provided context.
//  - The context definition is written into .taskrc as a context.<name> variable.
//  - Deletion of the context requires confirmation if rc.confirmation=yes.
//
// Returns: 0 if the addition of the config variable was successful, 1 otherwise
//
// Invoked with: task context define <name> <filter>
// Example:      task context define home project:Home
//
int CmdContext::defineContext (std::vector <std::string>& words, std::stringstream& out)
{
  int rc = 0;
  bool confirmation = context.config.getBoolean ("confirmation");

  if (words.size () > 2)
  {
    std::string name = "context." + words[1];
    std::string value = joinWords (words, 2);

    // Check if the value is a proper filter by filtering current pending.data
    Filter filter;
    std::vector <Task> filtered;
    auto pending = context.tdb2.pending.get_tasks ();

    try
    {
      // This result is not used, and is just to check validity.
      context.cli.addRawFilter ("( " + value + " )");
      filter.subset (pending, filtered);
    }
    catch (std::string exception)
    {
      throw format (STRING_CMD_CONTEXT_DEF_ABRT2, exception);
    }

    // Make user explicitly confirm filters that are matching no pending tasks
    if (filtered.size () == 0)
      if (confirmation &&
          ! confirm (format (STRING_CMD_CONTEXT_DEF_CONF, value)))
        throw std::string (STRING_CMD_CONTEXT_DEF_ABRT);

    // Set context definition config variable
    bool success = CmdConfig::setConfigVariable (name, value, confirmation);

    if (success)
      out << format (STRING_CMD_CONTEXT_DEF_SUCC, words[1]) << "\n";
    else
    {
      out << format (STRING_CMD_CONTEXT_DEF_FAIL, words[1]) << "\n";
      rc = 1;
    }
  }
  else
  {
    out << STRING_CMD_CONTEXT_DEF_USAG << "\n";
    rc = 1;
  }

  return rc;
}

////////////////////////////////////////////////////////////////////////////////
// Deletes the specified context.
//  - If the deleted context is currently active, unset it.
//  - Deletion of the context requires confirmation if rc.confirmation=yes.
//
// Returns: 0 if the removal of the config variable was successful, 1 otherwise
//
// Invoked with: task context delete <name>
// Example:      task context delete home
//
int CmdContext::deleteContext (std::vector <std::string>& words, std::stringstream& out)
{
  int rc = 0;

  if (words.size () > 1)
  {
    // Delete the specified context
    std::string name = "context." + words[1];

    bool confirmation = context.config.getBoolean ("confirmation");
    rc = CmdConfig::unsetConfigVariable(name, confirmation);

    // If the currently set context was deleted, unset it
    std::string currentContext = context.config.get ("context");

    if (currentContext == words[1])
      CmdConfig::unsetConfigVariable("context", false);

    // Output feedback
    if (rc == 0)
      out << format (STRING_CMD_CONTEXT_DEL_SUCC, words[1]) << "\n";
    else
      out << format (STRING_CMD_CONTEXT_DEL_FAIL, words[1]) << "\n";
  }
  else
  {
    out << STRING_CMD_CONTEXT_DEL_USAG << "\n";
    rc = 1;
  }

  return rc;
}

////////////////////////////////////////////////////////////////////////////////
// Render a list of context names and their definitions.
//
// Returns: 0 the resulting list is non-empty, 1 otherwise
//
// Invoked with: task context list
// Example:      task context list
//
int CmdContext::listContexts (std::vector <std::string>& words, std::stringstream& out)
{
  int rc = 0;
  std::vector <std::string> contexts = getContexts();

  if (contexts.size ())
  {
    std::sort (contexts.begin (), contexts.end ());

    ViewText view;
    view.width (context.getWidth ());
    view.add (Column::factory ("string", "Name"));
    view.add (Column::factory ("string", "Definition"));
    view.add (Column::factory ("string", "Active"));

    Color label (context.config.get ("color.label"));
    view.colorHeader (label);

    std::string activeContext = context.config.get ("context");

    for (auto& userContext : contexts)
    {
      std::string definition = context.config.get ("context." + userContext);

      std::string active = "no";

      if (userContext == activeContext)
          active = "yes";

      int row = view.addRow ();
      view.set (row, 0, userContext);
      view.set (row, 1, definition);
      view.set (row, 2, active);
    }

    out << optionalBlankLine ()
        << view.render ()
        << optionalBlankLine ();
  }
  else
  {
    out << STRING_CMD_CONTEXT_LIST_EMPT << "\n";
    rc = 1;
  }

  return rc;
}

////////////////////////////////////////////////////////////////////////////////
// Sets the specified context as currently active.
//   - If some other context was active, the value of currently active context
//     is replaced, not added.
//   - Setting of the context does not require confirmation.
//
// Returns: 0 if the setting of the context was successful, 1 otherwise
//
// Invoked with: task context <name>
// Example:      task context home
//
int CmdContext::setContext (std::vector <std::string>& words, std::stringstream& out)
{
  int rc = 0;
  std::string value = words[0];
  std::vector <std::string> contexts = getContexts ();

  // Check that the specified context is defined
  if (std::find (contexts.begin (), contexts.end (), value) == contexts.end ())
    throw format (STRING_CMD_CONTEXT_SET_NFOU, value);

  // Set the active context.
  // Should always succeed, as we do not require confirmation.
  bool success = CmdConfig::setConfigVariable ("context", value, false);

  if (success)
    out << format (STRING_CMD_CONTEXT_SET_SUCC, value) << "\n";
  else
  {
    out << format (STRING_CMD_CONTEXT_SET_FAIL, value) << "\n";
    rc = 1;
  }

  return rc;
}

////////////////////////////////////////////////////////////////////////////////
// Shows the currently active context.
//
// Returns: Always returns 0.
//
// Invoked with: task context show
// Example:      task context show
//
int CmdContext::showContext (std::vector <std::string>& words, std::stringstream& out)
{
  std::string currentContext = context.config.get ("context");

  if (currentContext == "")
    out << STRING_CMD_CONTEXT_SHOW_EMPT << "\n";
  else
  {
    std::string currentFilter = context.config.get ("context." + currentContext);
    out << format (STRING_CMD_CONTEXT_SHOW, currentContext, currentFilter) << "\n";
  }

  return 0;
}

////////////////////////////////////////////////////////////////////////////////
// Unsets the currently active context.
//   - Unsetting of the context does not require confirmation.
//
// Returns: 0 if the unsetting of the context was successful, 1 otherwise (also
//          returned if no context is currently active)
//
// Invoked with: task context none
// Example:      task context none
//
int CmdContext::unsetContext (std::vector <std::string>& words, std::stringstream& out)
{
  int rc = 0;
  int status = CmdConfig::unsetConfigVariable ("context", false);

  if (status == 0)
    out << STRING_CMD_CONTEXT_NON_SUCC << "\n";
  else
  {
    out << STRING_CMD_CONTEXT_NON_FAIL << "\n";
    rc = 1;
  }

  return rc;
}

////////////////////////////////////////////////////////////////////////////////
CmdCompletionContext::CmdCompletionContext ()
{
  _keyword     = "_context";
  _usage       = "task          _context";
  _description = STRING_CMD_HCONTEXT_USAGE;
  _read_only   = true;
  _displays_id = false;
}

////////////////////////////////////////////////////////////////////////////////
int CmdCompletionContext::execute (std::string& output)
{
  std::vector <std::string> userContexts = CmdContext::getContexts ();

  for (auto& userContext : userContexts)
    output += userContext + "\n";

  return 0;
}

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>#include <nan.h>

#include "../kv-types.h"

#include "env.h"
#include "txn.h"
#include "db.h"

using namespace v8;
using namespace kv;
using namespace kv::lmdb;

template<class T> int mdb_cmp_fn(const MDB_val *a, const MDB_val *b) {
	T ta((const char*)a->mv_data, a->mv_size), tb((const char*)b->mv_data, b->mv_size);
	return ta.compare(tb);
}

template<class T> struct mdb_cmp_setter {
	static void set_cmp(MDB_txn*, MDB_dbi) { }
	static void set_dup_cmp(MDB_txn*, MDB_dbi) { }
};

template<class N> struct mdb_cmp_setter<number_type<N> > {
	static void set_cmp(MDB_txn* txn, MDB_dbi dbi) {
		mdb_set_compare(txn, dbi, mdb_cmp_fn<number_type<N> >);
	}

	static void set_dup_cmp(MDB_txn* txn, MDB_dbi dbi) {
		mdb_set_dupsort(txn, dbi, mdb_cmp_fn<number_type<N> >);
	}
};

#define DB_EXPORT(KT, VT) db<KT, VT>::setup_export(exports);
void kv::lmdb::setup_db_export(v8::Handle<v8::Object>& exports) {
	KV_TYPE_EACH(DB_EXPORT);
}

template <class K, class V> void db<K, V>::setup_export(Handle<Object>& exports) {
	char class_name[64];
	sprintf(class_name, "DB_%s_%s", K::type_name, V::type_name);

	// Prepare constructor template
	Local<FunctionTemplate> dbiTpl = NanNew<FunctionTemplate>(db::ctor);
	dbiTpl->SetClassName(NanNew(class_name));
	dbiTpl->InstanceTemplate()->SetInternalFieldCount(1);

	// Add functions to the prototype
	NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "close", db::close);
	NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "get", db::get);
	NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "put", db::put);
	NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "del", db::del);
	// TODO: wrap mdb_stat too

	// Set exports
	exports->Set(NanNew(class_name), dbiTpl->GetFunction());
}

#define KVDB db<K, V>
#define KVDB_METHOD(fn) template <class K, class V> NAN_METHOD(KVDB::fn)

KVDB_METHOD(ctor) {
	int rc = 0;
	NanScope();

	MDB_txn *txn;
	MDB_dbi dbi;
	env *ew = node::ObjectWrap::Unwrap<env>(args[0]->ToObject());

	if (args[1]->IsObject()) {
		Local<Object> options = args[1]->ToObject();
		NanUtf8String name(options->Get(NanNew("name")));
		bool allowdup = options->Get(NanNew("allowDup"))->BooleanValue();

		// Open transaction
		rc = mdb_txn_begin(ew->_env, NULL, 0, &txn);
		if (rc != 0) {
			mdb_txn_abort(txn);
			NanThrowError(mdb_strerror(rc));
			NanReturnUndefined();
		}

		// Open database
		rc = mdb_dbi_open(txn, *name, MDB_CREATE, &dbi);
		if (rc != 0) {
			mdb_txn_abort(txn);
			NanThrowError(mdb_strerror(rc));
			NanReturnUndefined();
		}

		// Set compare function.
		mdb_cmp_setter<K>::set_cmp(txn, dbi);
		if (allowdup) mdb_cmp_setter<V>::set_dup_cmp(txn, dbi);

		// Commit transaction
		rc = mdb_txn_commit(txn);
		if (rc != 0) {
			NanThrowError(mdb_strerror(rc));
			NanReturnUndefined();
		}
	}
	else {
		NanThrowError("Invalid parameters.");
		NanReturnUndefined();
	}

	db* ptr = new db(ew->_env, dbi);
	ptr->Wrap(args.This());
	NanReturnValue(args.This());
}

KVDB_METHOD(close) {
	NanScope();

	db *dw = ObjectWrap::Unwrap<db>(args.This());
	mdb_dbi_close(dw->_env, dw->_dbi);

	NanReturnUndefined();
}

class kv::lmdb::txn_scope {
public:
	txn_scope(Local<Value> arg, MDB_env *env, bool readonly = false) : _txn(NULL), _created(false), _commit(false) {
		if (arg->IsObject()) {
			_txn = node::ObjectWrap::Unwrap<txn>(arg->ToObject())->_txn;
		} else {
			_created = true;
			mdb_txn_begin(env, NULL, readonly ? MDB_RDONLY : 0, &_txn);
		}
	}

	~txn_scope() {
		if (_created) {
			if (!_commit) mdb_txn_abort(_txn);
			else mdb_txn_commit(_txn);
		}
	}

	MDB_txn *operator*() {
		return _txn;
	}

	void commit() {
		_commit = true;
	}

private:
	MDB_txn *_txn;
	bool _created;
	bool _commit;
};

KVDB_METHOD(get) {
	NanScope();

	db *dw = ObjectWrap::Unwrap<db>(args.This());
	K key = K(args[0]);
	txn_scope tc(args[1], dw->_env, true);

	MDB_val k, v;
	k.mv_data = (void*)key.data();
	k.mv_size = key.size();

	int rc = mdb_get(*tc, dw->_dbi, &k, &v);

	if (rc == MDB_NOTFOUND) {
		NanReturnNull();
	}

	if (rc != 0) {
		NanThrowError(mdb_strerror(rc));
		NanReturnUndefined();
	}

	V val((const char*)v.mv_data, v.mv_size);
	NanReturnValue(val.v8value());
}

KVDB_METHOD(put) {
	NanScope();

	db *dw = ObjectWrap::Unwrap<db>(args.This());
	K key = K(args[0]);
	V val = V(args[1]);
	txn_scope tc(args[2], dw->_env);

	MDB_val k, v;
	k.mv_data = (void*)key.data();
	k.mv_size = key.size();
	v.mv_data = (void*)val.data();
	v.mv_size = val.size();

	int rc = mdb_put(*tc, dw->_dbi, &k, &v, 0);
	if (rc != 0) {
		NanThrowError(mdb_strerror(rc));
		NanReturnUndefined();
	}

	tc.commit();
	NanReturnValue(NanNew(true));
}

KVDB_METHOD(del) {
	NanScope();

	db *dw = ObjectWrap::Unwrap<db>(args.This());
	K key = K(args[0]);
	txn_scope tc(args[1], dw->_env);

	MDB_val k;
	k.mv_data = (void*)key.data();
	k.mv_size = key.size();

	int rc = mdb_del(*tc, dw->_dbi, &k, NULL);
	if (rc != 0) {
		NanThrowError(mdb_strerror(rc));
		NanReturnUndefined();
	}

	tc.commit();
	NanReturnValue(NanNew(true));
}

template <class K, class V> db<K, V>::db(MDB_env* env, MDB_dbi dbi) : _dbi(dbi), _env(env) {

}
<commit_msg>return false when del non-exist key.<commit_after>#include <nan.h>

#include "../kv-types.h"

#include "env.h"
#include "txn.h"
#include "db.h"

using namespace v8;
using namespace kv;
using namespace kv::lmdb;

template<class T> int mdb_cmp_fn(const MDB_val *a, const MDB_val *b) {
	T ta((const char*)a->mv_data, a->mv_size), tb((const char*)b->mv_data, b->mv_size);
	return ta.compare(tb);
}

template<class T> struct mdb_cmp_setter {
	static void set_cmp(MDB_txn*, MDB_dbi) { }
	static void set_dup_cmp(MDB_txn*, MDB_dbi) { }
};

template<class N> struct mdb_cmp_setter<number_type<N> > {
	static void set_cmp(MDB_txn* txn, MDB_dbi dbi) {
		mdb_set_compare(txn, dbi, mdb_cmp_fn<number_type<N> >);
	}

	static void set_dup_cmp(MDB_txn* txn, MDB_dbi dbi) {
		mdb_set_dupsort(txn, dbi, mdb_cmp_fn<number_type<N> >);
	}
};

#define DB_EXPORT(KT, VT) db<KT, VT>::setup_export(exports);
void kv::lmdb::setup_db_export(v8::Handle<v8::Object>& exports) {
	KV_TYPE_EACH(DB_EXPORT);
}

template <class K, class V> void db<K, V>::setup_export(Handle<Object>& exports) {
	char class_name[64];
	sprintf(class_name, "DB_%s_%s", K::type_name, V::type_name);

	// Prepare constructor template
	Local<FunctionTemplate> dbiTpl = NanNew<FunctionTemplate>(db::ctor);
	dbiTpl->SetClassName(NanNew(class_name));
	dbiTpl->InstanceTemplate()->SetInternalFieldCount(1);

	// Add functions to the prototype
	NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "close", db::close);
	NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "get", db::get);
	NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "put", db::put);
	NODE_SET_METHOD(dbiTpl->PrototypeTemplate(), "del", db::del);
	// TODO: wrap mdb_stat too

	// Set exports
	exports->Set(NanNew(class_name), dbiTpl->GetFunction());
}

#define KVDB db<K, V>
#define KVDB_METHOD(fn) template <class K, class V> NAN_METHOD(KVDB::fn)

KVDB_METHOD(ctor) {
	int rc = 0;
	NanScope();

	MDB_txn *txn;
	MDB_dbi dbi;
	env *ew = node::ObjectWrap::Unwrap<env>(args[0]->ToObject());

	if (args[1]->IsObject()) {
		Local<Object> options = args[1]->ToObject();
		NanUtf8String name(options->Get(NanNew("name")));
		bool allowdup = options->Get(NanNew("allowDup"))->BooleanValue();

		// Open transaction
		rc = mdb_txn_begin(ew->_env, NULL, 0, &txn);
		if (rc != 0) {
			mdb_txn_abort(txn);
			NanThrowError(mdb_strerror(rc));
			NanReturnUndefined();
		}

		// Open database
		rc = mdb_dbi_open(txn, *name, MDB_CREATE, &dbi);
		if (rc != 0) {
			mdb_txn_abort(txn);
			NanThrowError(mdb_strerror(rc));
			NanReturnUndefined();
		}

		// Set compare function.
		mdb_cmp_setter<K>::set_cmp(txn, dbi);
		if (allowdup) mdb_cmp_setter<V>::set_dup_cmp(txn, dbi);

		// Commit transaction
		rc = mdb_txn_commit(txn);
		if (rc != 0) {
			NanThrowError(mdb_strerror(rc));
			NanReturnUndefined();
		}
	}
	else {
		NanThrowError("Invalid parameters.");
		NanReturnUndefined();
	}

	db* ptr = new db(ew->_env, dbi);
	ptr->Wrap(args.This());
	NanReturnValue(args.This());
}

KVDB_METHOD(close) {
	NanScope();

	db *dw = ObjectWrap::Unwrap<db>(args.This());
	mdb_dbi_close(dw->_env, dw->_dbi);

	NanReturnUndefined();
}

class kv::lmdb::txn_scope {
public:
	txn_scope(Local<Value> arg, MDB_env *env, bool readonly = false) : _txn(NULL), _created(false), _commit(false) {
		if (arg->IsObject()) {
			_txn = node::ObjectWrap::Unwrap<txn>(arg->ToObject())->_txn;
		} else {
			_created = true;
			mdb_txn_begin(env, NULL, readonly ? MDB_RDONLY : 0, &_txn);
		}
	}

	~txn_scope() {
		if (_created) {
			if (!_commit) mdb_txn_abort(_txn);
			else mdb_txn_commit(_txn);
		}
	}

	MDB_txn *operator*() {
		return _txn;
	}

	void commit() {
		_commit = true;
	}

private:
	MDB_txn *_txn;
	bool _created;
	bool _commit;
};

KVDB_METHOD(get) {
	NanScope();

	db *dw = ObjectWrap::Unwrap<db>(args.This());
	K key = K(args[0]);
	txn_scope tc(args[1], dw->_env, true);

	MDB_val k, v;
	k.mv_data = (void*)key.data();
	k.mv_size = key.size();

	int rc = mdb_get(*tc, dw->_dbi, &k, &v);

	if (rc == MDB_NOTFOUND) {
		NanReturnNull();
	}

	if (rc != 0) {
		NanThrowError(mdb_strerror(rc));
		NanReturnUndefined();
	}

	V val((const char*)v.mv_data, v.mv_size);
	NanReturnValue(val.v8value());
}

KVDB_METHOD(put) {
	NanScope();

	db *dw = ObjectWrap::Unwrap<db>(args.This());
	K key = K(args[0]);
	V val = V(args[1]);
	txn_scope tc(args[2], dw->_env);

	MDB_val k, v;
	k.mv_data = (void*)key.data();
	k.mv_size = key.size();
	v.mv_data = (void*)val.data();
	v.mv_size = val.size();

	int rc = mdb_put(*tc, dw->_dbi, &k, &v, 0);
	if (rc != 0) {
		NanThrowError(mdb_strerror(rc));
		NanReturnUndefined();
	}

	tc.commit();
	NanReturnValue(NanNew(true));
}

KVDB_METHOD(del) {
	NanScope();

	db *dw = ObjectWrap::Unwrap<db>(args.This());
	K key = K(args[0]);
	txn_scope tc(args[1], dw->_env);

	MDB_val k;
	k.mv_data = (void*)key.data();
	k.mv_size = key.size();

	int rc = mdb_del(*tc, dw->_dbi, &k, NULL);

	if (rc == MDB_NOTFOUND) {
		NanReturnValue(NanNew(false));
	}

	if (rc != 0) {
		NanThrowError(mdb_strerror(rc));
		NanReturnUndefined();
	}

	tc.commit();
	NanReturnValue(NanNew(true));
}

template <class K, class V> db<K, V>::db(MDB_env* env, MDB_dbi dbi) : _dbi(dbi), _env(env) {

}
<|endoftext|>


<commit_before>// =============================================================================
// Event Class for .NET Style Events
// by Clint Caywood
// February 18, 2010
// =============================================================================

#ifndef EVENT_HPP
#define EVENT_HPP

#include <vector>
#include <algorithm>
#include <iostream>
#include <stdio.h>
#include "Delegate.hpp"

template <typename T>
class Event
{
    typedef typename std::vector< Delegate<T>* >::iterator iter;
    public:
        void operator+=(Delegate<T>* delegate)
        {
            // An object can only subscribe once
            if (find(_delegates.begin(), _delegates.end(), delegate) == _delegates.end())
            {
                _delegates.push_back(delegate);
            }
        }
        void operator-=(Delegate<T>* delegate)
        {
            iter i = _delegates.begin();
            while (i != _delegates.end())
            {
                if (*i == delegate)
                {
                    i = _delegates.erase(i);
                }
                else
                {
                    ++i;
                }
            }
        }
        void operator()(T param)
        {
            for (iter i = _delegates.begin(); i != _delegates.end(); ++i)
            {
                if((*i) != NULL)
                (*i)->operator()(param);
            }
        }

        typename std::vector<Delegate<T>* >::size_type numDelegates()
        {
            return _delegates.size();
        }

    private:
        std::vector< Delegate<T>* > _delegates;
};

#endif
<commit_msg>Adds Clear() to Event.<commit_after>// =============================================================================
// Event Class for .NET Style Events
// by Clint Caywood
// February 18, 2010
// =============================================================================

#ifndef EVENT_HPP
#define EVENT_HPP

#include <vector>
#include <algorithm>
#include <iostream>
#include <stdio.h>
#include "Delegate.hpp"

template <typename T>
class Event
{
    typedef typename std::vector< Delegate<T>* >::iterator iter;
    public:
        void operator+=(Delegate<T>* delegate)
        {
            // An object can only subscribe once
            if (find(_delegates.begin(), _delegates.end(), delegate) == _delegates.end())
            {
                _delegates.push_back(delegate);
            }
        }
        void operator-=(Delegate<T>* delegate)
        {
            iter i = _delegates.begin();
            while (i != _delegates.end())
            {
                if (*i == delegate)
                {
                    i = _delegates.erase(i);
                }
                else
                {
                    ++i;
                }
            }
        }
        void operator()(T param)
        {
            for (iter i = _delegates.begin(); i != _delegates.end(); ++i)
            {
                if((*i) != NULL)
                (*i)->operator()(param);
            }
        }

        typename std::vector<Delegate<T>* >::size_type numDelegates()
        {
            return _delegates.size();
        }

        void Clear()
        {
            _delegates.clear();
        }

    private:
        std::vector< Delegate<T>* > _delegates;
};

#endif
<|endoftext|>


<commit_before>
#include "logging.h"

#include <stdio.h>              /* printf, fopen */
#include <stdarg.h>             /* va_args */
#include <string.h>             /* memcpy */
#include <time.h>               /* time_t */

static const char* loglevel2string (const enum TCAM_LOG_LEVEL level)
{
    switch (level)
    {
        case TCAM_LOG_OFF:
            return "OFF";
        case TCAM_LOG_DEBUG:
            return "DEBUG";
        case TCAM_LOG_INFO:
            return "INFO";
        case TCAM_LOG_WARNING:
            return "WARNING";
        case TCAM_LOG_ERROR:
            return "ERROR";
        default:
            return NULL;
    }
}

static enum TCAM_LOG_LEVEL string2loglevel (const char* level)
{

    if (strcmp("OFF", level) == 0)
    {
        return TCAM_LOG_OFF;
    }
    else if (strcmp("DEBUG", level) == 0)
    {
        return TCAM_LOG_DEBUG;
    }
    else if (strcmp("INFO", level) == 0)
    {
        return TCAM_LOG_INFO;
    }
    else if (strcmp("WARNING", level) == 0)
    {
        return TCAM_LOG_WARNING;
    }
    else if (strcmp("ERROR", level) == 0)
    {
        return TCAM_LOG_ERROR;
    }
    else
        return TCAM_LOG_ERROR;
}

Logger::Logger ():
    callback(nullptr),
    logfile(nullptr)
{

    load_default_settings();
    // TODO: make environment variable name configurable
    char* log_def = getenv("TCAM_LOG");
    if (log_def != nullptr)
    {
        printf("ENV: %s\n", log_def);

        level = string2loglevel(log_def);
    }
}

void Logger::load_default_settings ()
{
    level = TCAM_LOG_ERROR;
    target = STDIO;
    log_file = "tmp/tis.log";
}

void Logger::log (const char* module,
                  enum TCAM_LOG_LEVEL level,
                  const char* function,
                  int line,
                  const char* message,
                  va_list args)
{
    if (level < this->level)
    {
        return;
    }

    char msg[1024];
    char buffer [2056];

    /* fill user defined message */
    vsprintf(msg, message, args);

    clock_t t;
    t = clock();
    /* write complete message */
    sprintf(buffer,
            "%-10ld <%s> %s:%d: %s\n",
            /* ctime(&timer), */
            t,
            loglevel2string(level),
            function,
            line,
            msg);

    switch (target)
    {
        case STDIO:
            log_to_stdout(buffer);
            break;
        case LOGFILE:
            log_to_file(buffer);
            break;
        case USER_DEFINED:
            //logger.callback(level, file, line, message, args);
            break;
        default:
            break;
    }
}

void Logger::log_to_stdout (const char* message)
{
    fprintf(stdout, "%s", message);
    fflush(stdout);
}

void Logger::log_to_file (const char* message)
{}

void Logger::set_log_level (enum TCAM_LOG_LEVEL l)
{
    level = l;
}

enum TCAM_LOG_LEVEL Logger::get_log_level () const
{
    return level;
}

void Logger::set_target (enum TCAM_LOG_TARGET t)
{
    target = t;
}

enum TCAM_LOG_TARGET Logger::get_target () const
{
    return target;
}

void Logger::set_log_file (const std::string& filename)
{
    log_file = filename;
}

std::string Logger::get_log_file () const
{
    return log_file;
}

void Logger::set_external_callback (logging_callback c)
{
    callback = c;
}

void Logger::delete_external_callback ()
{
    callback = nullptr;
}

void Logger::open_logfile ()
{
    if (!log_file.empty())
        logfile = fopen(log_file.c_str(), "a+");
}

void Logger::close_logfile ()
{
    if (logfile != NULL)
    {
        fclose(logfile);
        logfile = NULL;
    }
}

Logger& Logger::getInstance ()
{
    static Logger instance;

    return instance;
}

void tcam_set_logging_level (enum TCAM_LOG_LEVEL level)
{
    Logger::getInstance().set_log_level(level);
}

enum TCAM_LOG_LEVEL tcam_get_logging_level ()
{
    return Logger::getInstance().get_log_level();
}

void tcam_logging_init(enum TCAM_LOG_TARGET target, enum TCAM_LOG_LEVEL level)
{
    tcam_set_logging_target(target);
    tcam_set_logging_level(level);
}

void tcam_set_logging_target (enum TCAM_LOG_TARGET target)
{
    Logger::getInstance().set_target(target);
}

void tcam_set_logging_file (const char* logfile_name)
{
    Logger::getInstance().set_log_file(logfile_name);
}

const char* tcam_get_logging_file ()
{
    return Logger::getInstance().get_log_file().c_str();
}

void tcam_logging (enum TCAM_LOG_LEVEL level, const char* file, int line, const char* message, ...)
{
    if (Logger::getInstance().get_log_level() > level ||
        Logger::getInstance().get_log_level() == TCAM_LOG_OFF)
    {
        return;
    }

    va_list args;
    va_start(args, message);

    Logger::getInstance().log("", level, file, line, message, args);

    va_end(args);
}

void tcam_logging (const char* module, enum TCAM_LOG_LEVEL level, const char* function, int line, const char* message, ...)
{
    if (Logger::getInstance().get_log_level() > level ||
        Logger::getInstance().get_log_level() == TCAM_LOG_OFF)
    {
        return;
    }

    va_list args;
    va_start(args, message);

    Logger::getInstance().log(module, level, function, line, message, args);

    va_end(args);
}
<commit_msg>Correct defualt file path of tcam log file<commit_after>
#include "logging.h"

#include <stdio.h>              /* printf, fopen */
#include <stdarg.h>             /* va_args */
#include <string.h>             /* memcpy */
#include <time.h>               /* time_t */

static const char* loglevel2string (const enum TCAM_LOG_LEVEL level)
{
    switch (level)
    {
        case TCAM_LOG_OFF:
            return "OFF";
        case TCAM_LOG_DEBUG:
            return "DEBUG";
        case TCAM_LOG_INFO:
            return "INFO";
        case TCAM_LOG_WARNING:
            return "WARNING";
        case TCAM_LOG_ERROR:
            return "ERROR";
        default:
            return NULL;
    }
}

static enum TCAM_LOG_LEVEL string2loglevel (const char* level)
{

    if (strcmp("OFF", level) == 0)
    {
        return TCAM_LOG_OFF;
    }
    else if (strcmp("DEBUG", level) == 0)
    {
        return TCAM_LOG_DEBUG;
    }
    else if (strcmp("INFO", level) == 0)
    {
        return TCAM_LOG_INFO;
    }
    else if (strcmp("WARNING", level) == 0)
    {
        return TCAM_LOG_WARNING;
    }
    else if (strcmp("ERROR", level) == 0)
    {
        return TCAM_LOG_ERROR;
    }
    else
        return TCAM_LOG_ERROR;
}

Logger::Logger ():
    callback(nullptr),
    logfile(nullptr)
{

    load_default_settings();
    // TODO: make environment variable name configurable
    char* log_def = getenv("TCAM_LOG");
    if (log_def != nullptr)
    {
        printf("ENV: %s\n", log_def);

        level = string2loglevel(log_def);
    }
}

void Logger::load_default_settings ()
{
    level = TCAM_LOG_ERROR;
    target = STDIO;
    log_file = "/tmp/tis.log";
}

void Logger::log (const char* module,
                  enum TCAM_LOG_LEVEL level,
                  const char* function,
                  int line,
                  const char* message,
                  va_list args)
{
    if (level < this->level)
    {
        return;
    }

    char msg[1024];
    char buffer [2056];

    /* fill user defined message */
    vsprintf(msg, message, args);

    clock_t t;
    t = clock();
    /* write complete message */
    sprintf(buffer,
            "%-10ld <%s> %s:%d: %s\n",
            /* ctime(&timer), */
            t,
            loglevel2string(level),
            function,
            line,
            msg);

    switch (target)
    {
        case STDIO:
            log_to_stdout(buffer);
            break;
        case LOGFILE:
            log_to_file(buffer);
            break;
        case USER_DEFINED:
            //logger.callback(level, file, line, message, args);
            break;
        default:
            break;
    }
}

void Logger::log_to_stdout (const char* message)
{
    fprintf(stdout, "%s", message);
    fflush(stdout);
}

void Logger::log_to_file (const char* message)
{}

void Logger::set_log_level (enum TCAM_LOG_LEVEL l)
{
    level = l;
}

enum TCAM_LOG_LEVEL Logger::get_log_level () const
{
    return level;
}

void Logger::set_target (enum TCAM_LOG_TARGET t)
{
    target = t;
}

enum TCAM_LOG_TARGET Logger::get_target () const
{
    return target;
}

void Logger::set_log_file (const std::string& filename)
{
    log_file = filename;
}

std::string Logger::get_log_file () const
{
    return log_file;
}

void Logger::set_external_callback (logging_callback c)
{
    callback = c;
}

void Logger::delete_external_callback ()
{
    callback = nullptr;
}

void Logger::open_logfile ()
{
    if (!log_file.empty())
        logfile = fopen(log_file.c_str(), "a+");
}

void Logger::close_logfile ()
{
    if (logfile != NULL)
    {
        fclose(logfile);
        logfile = NULL;
    }
}

Logger& Logger::getInstance ()
{
    static Logger instance;

    return instance;
}

void tcam_set_logging_level (enum TCAM_LOG_LEVEL level)
{
    Logger::getInstance().set_log_level(level);
}

enum TCAM_LOG_LEVEL tcam_get_logging_level ()
{
    return Logger::getInstance().get_log_level();
}

void tcam_logging_init(enum TCAM_LOG_TARGET target, enum TCAM_LOG_LEVEL level)
{
    tcam_set_logging_target(target);
    tcam_set_logging_level(level);
}

void tcam_set_logging_target (enum TCAM_LOG_TARGET target)
{
    Logger::getInstance().set_target(target);
}

void tcam_set_logging_file (const char* logfile_name)
{
    Logger::getInstance().set_log_file(logfile_name);
}

const char* tcam_get_logging_file ()
{
    return Logger::getInstance().get_log_file().c_str();
}

void tcam_logging (enum TCAM_LOG_LEVEL level, const char* file, int line, const char* message, ...)
{
    if (Logger::getInstance().get_log_level() > level ||
        Logger::getInstance().get_log_level() == TCAM_LOG_OFF)
    {
        return;
    }

    va_list args;
    va_start(args, message);

    Logger::getInstance().log("", level, file, line, message, args);

    va_end(args);
}

void tcam_logging (const char* module, enum TCAM_LOG_LEVEL level, const char* function, int line, const char* message, ...)
{
    if (Logger::getInstance().get_log_level() > level ||
        Logger::getInstance().get_log_level() == TCAM_LOG_OFF)
    {
        return;
    }

    va_list args;
    va_start(args, message);

    Logger::getInstance().log(module, level, function, line, message, args);

    va_end(args);
}
<|endoftext|>


<commit_before>
#include "idTable.h"

// @Author: Vik Singh
// @Date: 12/30/2004

// CLASS Id

Id::Id (IdTable * table) { this->table = table; }

Id::Id (const u_int32_t * num, IdTable * table) {
  for (int i = 0; i < 5; i += 1)
    key[i] = *(num + i);
  this->table = table;
}

Id::Id (const std::string& idString, IdTable * table) {
  this->table = table;
}

std::bitset<160> Id::toBitWord (u_int32_t num) {
  return std::bitset<160> (num);
  /* std::bitset<160> result;
    for (int i = 0; i < 32 && num >= 1; i += 1) {
      if (num % 2)
        result.set (i);
      num /= 2;
    }
  return result; */
}

std::string Id::toHexWord (u_int32_t num) {
  const std::string HEX_DIGITS = "0123456789ABCDEF";
  char result[] = {'0','0','0','0','0','0','0','0','\0'};
  int remainder;
  for (int i = 0; i < 8 && num >= 1; i += 1) {
    if (remainder = num % 16)
      result[7 - i] = HEX_DIGITS.at (remainder);
    num /= 16;
  }
  return std::string (result);
}

std::bitset<160> Id::toBitSet () const {
  std::bitset<160> result;
  for (int i = 0; i < 5; i += 1)
    result ^= toBitWord (key[i]) <<
      ((4 - i) * 32);
  return result;
}

std::string Id::toHexString () const {
  std::string currentWord;
  char result[] =
  {'0','0','0','0','0','0','0','0','0','0',
   '0','0','0','0','0','0','0','0','0','0',
   '0','0','0','0','0','0','0','0','0','0',
   '0','0','0','0','0','0','0','0','0','0', '\0'};
  for (int i = 0; i < 5; i += 1) {
    currentWord = toHexWord (key[i]);
      for (int j = i * 8; j < (i * 8) + 8; j += 1)
	result[j] = currentWord.at (j % 8);
  }
  return std::string (result);
}

size_t Id::hashCode () const {
  size_t result = 0;
  for (int i = 0; i < 5; i += 1)
    result ^= key[i];
  return result;
}

u_int32_t Id::getWord (const int index) const {
  assert (index >= 0 && index < 5);
  return key[index];
}

// CLASS IdTable

IdTable::IdTable () { maxSize = 0; }

void IdTable::initialize_gc (const size_t num) {
  maxSize = num;
}

bool IdTable::equalByVal (const Id * x, const Id * y) {
  for (int i = 0; i < 5; i += 1) {
    if (x->key[i] == y->key[i]) continue;
    else return false;
  }
  return true;
}

// const Id * create (const XDR * xdr);

const Id * IdTable::create (const std::string& idString) {
  Id * result = new Id (this); // use New ref<Id> (idString);
  return storeId (result);
}

const Id * IdTable::create (const u_int32_t * random) {
  Id * result = new Id (random, this); // use New ref<Id> (random);
  return storeId (result);
}

const Id * IdTable::create () {
  Id * result = new Id (this); // auto gen with dev/urandom
  return storeId (result);
}

size_t IdTable::size () const {
  return idSet.size ();
}

void IdTable::remove (const Id * idPtr) {
  idSet.erase (idPtr);
}

void IdTable::clear () {
  idSet.clear ();
}

const Id * IdTable::storeId (const Id * idKey) {
  std::map<const Id *, int, IdComparator>::iterator
    idFound = idSet.find (idKey);
  if (idFound != idSet.end ()) {
    delete idKey;
    return idFound->first;
  }
  else {
    add (idKey);
    return idKey;
  }
}

void IdTable::add (const Id * idKey) {
  idSet.insert (std::pair<const Id *, int> (idKey, 0));
  if (maxSize == 0) return;
  else if (idSet.size () > maxSize)
    gc ();
}

// ref<Id> 's are deleted automatically from the set when
// refcount goes to zero - look at Id::finalize ()
void IdTable::gc () {
  /**
   * Get the size of @idSet
   * divide size by 2
   * first half = old
   * second half = recent
   * fudge factor = desired size, keep collecting until ff
   * reached
   * within this set order @Id's by # of references
   * within this set order @Id's by time of last use
   *
   */
  std::map<const Id *, int, IdComparator>::iterator items =
    idSet.begin ();
  while (items != idSet.end ()) {
  }
}

<commit_msg>Added parentheses around assignment/boolean expression within an if.<commit_after>
#include "idTable.h"

// @Author: Vik Singh
// @Date: 12/30/2004

// CLASS Id

Id::Id (IdTable * table) { this->table = table; }

Id::Id (const u_int32_t * num, IdTable * table) {
  for (int i = 0; i < 5; i += 1)
    key[i] = *(num + i);
  this->table = table;
}

Id::Id (const std::string& idString, IdTable * table) {
  this->table = table;
}

std::bitset<160> Id::toBitWord (u_int32_t num) {
  return std::bitset<160> (num);
  /* std::bitset<160> result;
    for (int i = 0; i < 32 && num >= 1; i += 1) {
      if (num % 2)
        result.set (i);
      num /= 2;
    }
  return result; */
}

std::string Id::toHexWord (u_int32_t num) {
  const std::string HEX_DIGITS = "0123456789ABCDEF";
  char result[] = {'0','0','0','0','0','0','0','0','\0'};
  int remainder;
  for (int i = 0; i < 8 && num >= 1; i += 1) {
    if ((remainder = num % 16))
      result[7 - i] = HEX_DIGITS.at (remainder);
    num /= 16;
  }
  return std::string (result);
}

std::bitset<160> Id::toBitSet () const {
  std::bitset<160> result;
  for (int i = 0; i < 5; i += 1)
    result ^= toBitWord (key[i]) <<
      ((4 - i) * 32);
  return result;
}

std::string Id::toHexString () const {
  std::string currentWord;
  char result[] =
  {'0','0','0','0','0','0','0','0','0','0',
   '0','0','0','0','0','0','0','0','0','0',
   '0','0','0','0','0','0','0','0','0','0',
   '0','0','0','0','0','0','0','0','0','0', '\0'};
  for (int i = 0; i < 5; i += 1) {
    currentWord = toHexWord (key[i]);
      for (int j = i * 8; j < (i * 8) + 8; j += 1)
	result[j] = currentWord.at (j % 8);
  }
  return std::string (result);
}

size_t Id::hashCode () const {
  size_t result = 0;
  for (int i = 0; i < 5; i += 1)
    result ^= key[i];
  return result;
}

u_int32_t Id::getWord (const int index) const {
  assert (index >= 0 && index < 5);
  return key[index];
}

// CLASS IdTable

IdTable::IdTable () { maxSize = 0; }

void IdTable::initialize_gc (const size_t num) {
  maxSize = num;
}

bool IdTable::equalByVal (const Id * x, const Id * y) {
  for (int i = 0; i < 5; i += 1) {
    if (x->key[i] == y->key[i]) continue;
    else return false;
  }
  return true;
}

// const Id * create (const XDR * xdr);

const Id * IdTable::create (const std::string& idString) {
  Id * result = new Id (this); // use New ref<Id> (idString);
  return storeId (result);
}

const Id * IdTable::create (const u_int32_t * random) {
  Id * result = new Id (random, this); // use New ref<Id> (random);
  return storeId (result);
}

const Id * IdTable::create () {
  Id * result = new Id (this); // auto gen with dev/urandom
  return storeId (result);
}

size_t IdTable::size () const {
  return idSet.size ();
}

void IdTable::remove (const Id * idPtr) {
  idSet.erase (idPtr);
}

void IdTable::clear () {
  idSet.clear ();
}

const Id * IdTable::storeId (const Id * idKey) {
  std::map<const Id *, int, IdComparator>::iterator
    idFound = idSet.find (idKey);
  if (idFound != idSet.end ()) {
    delete idKey;
    return idFound->first;
  }
  else {
    add (idKey);
    return idKey;
  }
}

void IdTable::add (const Id * idKey) {
  idSet.insert (std::pair<const Id *, int> (idKey, 0));
  if (maxSize == 0) return;
  else if (idSet.size () > maxSize)
    gc ();
}

// ref<Id> 's are deleted automatically from the set when
// refcount goes to zero - look at Id::finalize ()
void IdTable::gc () {
  /**
   * Get the size of @idSet
   * divide size by 2
   * first half = old
   * second half = recent
   * fudge factor = desired size, keep collecting until ff
   * reached
   * within this set order @Id's by # of references
   * within this set order @Id's by time of last use
   *
   */
  std::map<const Id *, int, IdComparator>::iterator items =
    idSet.begin ();
  while (items != idSet.end ()) {
  }
}

<|endoftext|>


<commit_before>/* Calf DSP Library
 * RDF file generator for LADSPA plugins.
 * Copyright (C) 2007 Krzysztof Foltman
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 */
#include <getopt.h>
#include <stdint.h>
#include <stdlib.h>
#include <config.h>
#include <calf/giface.h>
#include <calf/modules.h>

using namespace std;
using namespace synth;

static struct option long_options[] = {
    {"help", 0, 0, 'h'},
    {"version", 0, 0, 'v'},
    {"mode", 0, 0, 'm'},
    {0,0,0,0},
};

void make_rdf()
{
    string rdf;
    rdf =
        "<?xml version='1.0' encoding='ISO-8859-1'?>\n"
        "<!DOCTYPE rdf:RDF [\n"
        "  <!ENTITY rdf 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'>\n"
        "  <!ENTITY rdfs 'http://www.w3.org/2000/01/rdf-schema#'>\n"
        "  <!ENTITY dc 'http://purl.org/dc/elements/1.1/'>\n"
        "  <!ENTITY ladspa 'http://ladspa.org/ontology#'>\n"
        "]>\n";

    rdf += "<rdf:RDF xmlns:rdf=\"&rdf;\" xmlns:rdfs=\"&rdfs;\" xmlns:dc=\"&dc;\" xmlns:ladspa=\"&ladspa;\">\n";

    rdf += synth::get_builtin_modules_rdf();

    rdf += "</rdf:RDF>\n";

    printf("%s\n", rdf.c_str());
}

static void add_port(string &ports, const char *symbol, const char *name, const char *direction, int pidx)
{
    stringstream ss;
    const char *ind = "        ";

    if (ports != "") ports += " , ";
    ss << "[\n";
    if (direction) ss << ind << "a lv2:" << direction << "Port ;\n";
    ss << ind << "a lv2:AudioPort ;\n";
    ss << ind << "lv2:index " << pidx << " ;\n";
    ss << ind << "lv2:symbol \"" << symbol << "\" ;\n";
    ss << ind << "lv2:name \"" << name << "\" ;\n";
    ss << "    ]";
    ports += ss.str();
}

static void add_ctl_port(string &ports, parameter_properties &pp, int pidx)
{
    stringstream ss;
    const char *ind = "        ";

    if (ports != "") ports += " , ";
    ss << "[\n";
    ss << ind << "a lv2:InputPort ;\n";
    ss << ind << "a lv2:ControlPort ;\n";
    ss << ind << "lv2:index " << pidx << " ;\n";
    ss << ind << "lv2:symbol \"" << pp.short_name << "\" ;\n";
    ss << ind << "lv2:name \"" << pp.name << "\" ;\n";
    if ((pp.flags & PF_TYPEMASK) == PF_BOOL)
        ss << ind << "lv2:portProperty lv2:toggled ;\n";
    else if ((pp.flags & PF_TYPEMASK) == PF_ENUM)
    {
        ss << ind << "lv2:portProperty lv2:integer ;\n";
        for (int i = (int)pp.min; i <= (int)pp.max; i++)
            ss << ind << "lv2:scalePoint [ rdfs:label \"" << pp.choices[i - (int)pp.min] << "\"; rdf:value " << i <<" ] ;\n";
    }
    else if ((pp.flags & PF_TYPEMASK) > 0)
        ss << ind << "lv2:portProperty lv2:integer ;\n";
    ss << showpoint;
    ss << ind << "lv2:default " << pp.def_value << " ;\n";
    ss << ind << "lv2:minimum " << pp.min << " ;\n";
    ss << ind << "lv2:maximum " << pp.max << " ;\n";
    ss << "    ]";
    ports += ss.str();
}

void make_ttl()
{
    string ttl;

    ttl =
        "@prefix lv2:  <http://lv2plug.in/ns/lv2core#> .\n"
        "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
        "@prefix doap: <http://usefulinc.com/ns/doap#> .\n"
        "@prefix guiext: <http://ll-plugins.nongnu.org/lv2/ext/gui#> .\n"
        "\n"
    ;

    vector<synth::giface_plugin_info> plugins;
    synth::get_all_plugins(plugins);

    map<string, string> classes;

    const char *ptypes[] = {
        "Flanger", "Reverb", "Generator", "Instrument", "Oscillator",
        "Utility", "Converter", "Analyser", "Mixer", "Simulator",
        "Delay", "Modulator", "Phaser", "Chorus", "Filter",
        "Lowpass", "Highpass", "Bandpass", "Comb", "Allpass",
        "Amplifier", "Distortion", "Waveshaper", "Dynamics", "Compressor",
        "Expander", "Limiter", "Gate", NULL
    };

    for(const char **p = ptypes; *p; p++) {
        string name = string(*p) + "Plugin";
        classes[name] = "lv2:" + name;
    }

#if USE_LV2_GUI
    ttl += "<http://calf.sourceforge.net/plugins/gui/gtk2-gui>\n    a guiext:GtkGUI ;\n    guiext:binary <calflv2gui.so> .\n\n";
#endif

    for (unsigned int i = 0; i < plugins.size(); i++) {
        synth::giface_plugin_info &pi = plugins[i];
        ttl += string("<http://calf.sourceforge.net/plugins/")
            + string(pi.info->label)
            + "> a lv2:Plugin ;\n";

        if (classes.count(pi.info->plugin_type))
            ttl += "    a " + classes[pi.info->plugin_type]+" ;\n";

        ttl += "    doap:name \""+string(pi.info->name)+"\" ;\n";

#if USE_LV2_GUI
        ttl += "    guiext:gui <http://calf.sourceforge.net/plugins/gui/gtk2-gui> ;\n";
#endif

#if USE_PHAT
        ttl += "    doap:license <http://usefulinc.com/doap/licenses/gpl> ;\n";
#else
        ttl += "    doap:license <http://usefulinc.com/doap/licenses/lgpl> ;\n";
#endif
        if (pi.rt_capable)
            ttl += "    lv2:optionalFeature lv2:hardRtCapable ;\n";

        string ports = "";
        int pn = 0;
        const char *in_names[] = { "in_l", "in_r" };
        const char *out_names[] = { "out_l", "out_r" };
        for (int i = 0; i < pi.inputs; i++)
            add_port(ports, in_names[i], in_names[i], "Input", pn++);
        for (int i = 0; i < pi.outputs; i++)
            add_port(ports, out_names[i], out_names[i], "Output", pn++);
        for (int i = 0; i < pi.params; i++)
            add_ctl_port(ports, pi.param_props[i], pn++);
        if (!ports.empty())
            ttl += "    lv2:port " + ports + "\n";
        ttl += ".\n\n";
    }
    printf("%s\n", ttl.c_str());
}

void make_manifest()
{
    string ttl;

    ttl =
        "@prefix lv2:  <http://lv2plug.in/ns/lv2core#> .\n"
        "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\n";

    vector<synth::giface_plugin_info> plugins;
    synth::get_all_plugins(plugins);
    for (unsigned int i = 0; i < plugins.size(); i++)
        ttl += string("<http://calf.sourceforge.net/plugins/")
            + string(plugins[i].info->label)
            + "> a lv2:Plugin ; lv2:binary <calf.so> ; rdfs:seeAlso <calf.ttl> .\n";

    printf("%s\n", ttl.c_str());
}

int main(int argc, char *argv[])
{
    string mode = "rdf";
    while(1) {
        int option_index;
        int c = getopt_long(argc, argv, "hvm:", long_options, &option_index);
        if (c == -1)
            break;
        switch(c) {
            case 'h':
            case '?':
                printf("LADSPA RDF / LV2 TTL generator for Calf plugin pack\nSyntax: %s [--help] [--version] [--mode rdf|ttl|manifest]\n", argv[0]);
                return 0;
            case 'v':
                printf("%s\n", PACKAGE_STRING);
                return 0;
            case 'm':
                mode = optarg;
                if (mode != "rdf" && mode != "ttl" && mode != "manifest") {
                    fprintf(stderr, "calfmakerdf: Invalid mode %s\n", optarg);
                    return 1;
                }
                break;
        }
    }
    if (mode == "rdf")
        make_rdf();
    if (mode == "ttl")
        make_ttl();
    if (mode == "manifest")
        make_manifest();
    return 0;
}
<commit_msg>+ LV2: Fixed classification for instrument plugins (they're still useless because of lack of MIDI port)<commit_after>/* Calf DSP Library
 * RDF file generator for LADSPA plugins.
 * Copyright (C) 2007 Krzysztof Foltman
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 */
#include <getopt.h>
#include <stdint.h>
#include <stdlib.h>
#include <config.h>
#include <calf/giface.h>
#include <calf/modules.h>

using namespace std;
using namespace synth;

static struct option long_options[] = {
    {"help", 0, 0, 'h'},
    {"version", 0, 0, 'v'},
    {"mode", 0, 0, 'm'},
    {0,0,0,0},
};

void make_rdf()
{
    string rdf;
    rdf =
        "<?xml version='1.0' encoding='ISO-8859-1'?>\n"
        "<!DOCTYPE rdf:RDF [\n"
        "  <!ENTITY rdf 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'>\n"
        "  <!ENTITY rdfs 'http://www.w3.org/2000/01/rdf-schema#'>\n"
        "  <!ENTITY dc 'http://purl.org/dc/elements/1.1/'>\n"
        "  <!ENTITY ladspa 'http://ladspa.org/ontology#'>\n"
        "]>\n";

    rdf += "<rdf:RDF xmlns:rdf=\"&rdf;\" xmlns:rdfs=\"&rdfs;\" xmlns:dc=\"&dc;\" xmlns:ladspa=\"&ladspa;\">\n";

    rdf += synth::get_builtin_modules_rdf();

    rdf += "</rdf:RDF>\n";

    printf("%s\n", rdf.c_str());
}

static void add_port(string &ports, const char *symbol, const char *name, const char *direction, int pidx)
{
    stringstream ss;
    const char *ind = "        ";

    if (ports != "") ports += " , ";
    ss << "[\n";
    if (direction) ss << ind << "a lv2:" << direction << "Port ;\n";
    ss << ind << "a lv2:AudioPort ;\n";
    ss << ind << "lv2:index " << pidx << " ;\n";
    ss << ind << "lv2:symbol \"" << symbol << "\" ;\n";
    ss << ind << "lv2:name \"" << name << "\" ;\n";
    ss << "    ]";
    ports += ss.str();
}

static void add_ctl_port(string &ports, parameter_properties &pp, int pidx)
{
    stringstream ss;
    const char *ind = "        ";

    if (ports != "") ports += " , ";
    ss << "[\n";
    ss << ind << "a lv2:InputPort ;\n";
    ss << ind << "a lv2:ControlPort ;\n";
    ss << ind << "lv2:index " << pidx << " ;\n";
    ss << ind << "lv2:symbol \"" << pp.short_name << "\" ;\n";
    ss << ind << "lv2:name \"" << pp.name << "\" ;\n";
    if ((pp.flags & PF_TYPEMASK) == PF_BOOL)
        ss << ind << "lv2:portProperty lv2:toggled ;\n";
    else if ((pp.flags & PF_TYPEMASK) == PF_ENUM)
    {
        ss << ind << "lv2:portProperty lv2:integer ;\n";
        for (int i = (int)pp.min; i <= (int)pp.max; i++)
            ss << ind << "lv2:scalePoint [ rdfs:label \"" << pp.choices[i - (int)pp.min] << "\"; rdf:value " << i <<" ] ;\n";
    }
    else if ((pp.flags & PF_TYPEMASK) > 0)
        ss << ind << "lv2:portProperty lv2:integer ;\n";
    ss << showpoint;
    ss << ind << "lv2:default " << pp.def_value << " ;\n";
    ss << ind << "lv2:minimum " << pp.min << " ;\n";
    ss << ind << "lv2:maximum " << pp.max << " ;\n";
    ss << "    ]";
    ports += ss.str();
}

void make_ttl()
{
    string ttl;

    ttl =
        "@prefix lv2:  <http://lv2plug.in/ns/lv2core#> .\n"
        "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
        "@prefix doap: <http://usefulinc.com/ns/doap#> .\n"
        "@prefix guiext: <http://ll-plugins.nongnu.org/lv2/ext/gui#> .\n"
        "\n"
    ;

    vector<synth::giface_plugin_info> plugins;
    synth::get_all_plugins(plugins);

    map<string, string> classes;

    const char *ptypes[] = {
        "Flanger", "Reverb", "Generator", "Instrument", "Oscillator",
        "Utility", "Converter", "Analyser", "Mixer", "Simulator",
        "Delay", "Modulator", "Phaser", "Chorus", "Filter",
        "Lowpass", "Highpass", "Bandpass", "Comb", "Allpass",
        "Amplifier", "Distortion", "Waveshaper", "Dynamics", "Compressor",
        "Expander", "Limiter", "Gate", NULL
    };

    for(const char **p = ptypes; *p; p++) {
        string name = string(*p) + "Plugin";
        classes[name] = "lv2:" + name;
    }
    classes["SynthesizerPlugin"] = "lv2:InstrumentPlugin";

#if USE_LV2_GUI
    ttl += "<http://calf.sourceforge.net/plugins/gui/gtk2-gui>\n    a guiext:GtkGUI ;\n    guiext:binary <calflv2gui.so> .\n\n";
#endif

    for (unsigned int i = 0; i < plugins.size(); i++) {
        synth::giface_plugin_info &pi = plugins[i];
        ttl += string("<http://calf.sourceforge.net/plugins/")
            + string(pi.info->label)
            + "> a lv2:Plugin ;\n";

        if (classes.count(pi.info->plugin_type))
            ttl += "    a " + classes[pi.info->plugin_type]+" ;\n";

        ttl += "    doap:name \""+string(pi.info->name)+"\" ;\n";

#if USE_LV2_GUI
        ttl += "    guiext:gui <http://calf.sourceforge.net/plugins/gui/gtk2-gui> ;\n";
#endif

#if USE_PHAT
        ttl += "    doap:license <http://usefulinc.com/doap/licenses/gpl> ;\n";
#else
        ttl += "    doap:license <http://usefulinc.com/doap/licenses/lgpl> ;\n";
#endif
        if (pi.rt_capable)
            ttl += "    lv2:optionalFeature lv2:hardRtCapable ;\n";

        string ports = "";
        int pn = 0;
        const char *in_names[] = { "in_l", "in_r" };
        const char *out_names[] = { "out_l", "out_r" };
        for (int i = 0; i < pi.inputs; i++)
            add_port(ports, in_names[i], in_names[i], "Input", pn++);
        for (int i = 0; i < pi.outputs; i++)
            add_port(ports, out_names[i], out_names[i], "Output", pn++);
        for (int i = 0; i < pi.params; i++)
            add_ctl_port(ports, pi.param_props[i], pn++);
        if (!ports.empty())
            ttl += "    lv2:port " + ports + "\n";
        ttl += ".\n\n";
    }
    printf("%s\n", ttl.c_str());
}

void make_manifest()
{
    string ttl;

    ttl =
        "@prefix lv2:  <http://lv2plug.in/ns/lv2core#> .\n"
        "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\n";

    vector<synth::giface_plugin_info> plugins;
    synth::get_all_plugins(plugins);
    for (unsigned int i = 0; i < plugins.size(); i++)
        ttl += string("<http://calf.sourceforge.net/plugins/")
            + string(plugins[i].info->label)
            + "> a lv2:Plugin ; lv2:binary <calf.so> ; rdfs:seeAlso <calf.ttl> .\n";

    printf("%s\n", ttl.c_str());
}

int main(int argc, char *argv[])
{
    string mode = "rdf";
    while(1) {
        int option_index;
        int c = getopt_long(argc, argv, "hvm:", long_options, &option_index);
        if (c == -1)
            break;
        switch(c) {
            case 'h':
            case '?':
                printf("LADSPA RDF / LV2 TTL generator for Calf plugin pack\nSyntax: %s [--help] [--version] [--mode rdf|ttl|manifest]\n", argv[0]);
                return 0;
            case 'v':
                printf("%s\n", PACKAGE_STRING);
                return 0;
            case 'm':
                mode = optarg;
                if (mode != "rdf" && mode != "ttl" && mode != "manifest") {
                    fprintf(stderr, "calfmakerdf: Invalid mode %s\n", optarg);
                    return 1;
                }
                break;
        }
    }
    if (mode == "rdf")
        make_rdf();
    if (mode == "ttl")
        make_ttl();
    if (mode == "manifest")
        make_manifest();
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>am c2bb5391: Merge "Use GetEntryPointFromQuickCompiledCode instead of GetQuickOatCodeOffset"<commit_after><|endoftext|>


<commit_before>/* Copyright (c) 2011, Jon Maken
 * License: 3-clause BSD
 * Revision: 12/09/2011 2:36:08 PM
 *
 * Example:
 *
 *      HiRes::Statistics<double> stats =
 *          for_each(istream_iterator<double>(cin),
 *                   istream_iterator<double><(),
 *                   HiRes::Statistics<double>());
 */

#include <algorithm>
#include <iterator>
#include <iostream>
#include <iomanip>
#include <vector>

#if defined(_WIN32)
#  include <io.h>
#  define executable "basic_stats.exe"
#else
#  include <unistd.h>
#  define executable "basic_stats"
#endif

#include "hrtimer.h"
#include "statistics.h"

const int TEST_COUNT = 20;

int main(int argc, char* argv[])
{
    using namespace std;

    double rv = 0.0;
    vector<double> data;
    HiRes::Timer<HiRes::us> tmr_us;

    for (int i = 0; i < TEST_COUNT; i++)
    {
        tmr_us.start();
        _access(executable, 4);
        rv = tmr_us.stop();
        data.push_back(rv);
    }

    HiRes::Statistics<double> stats =
        for_each(data.begin(), data.end(), HiRes::Statistics<double>());

    cout    << "Count = " << stats.count() << '\n'
            << "Min = " << stats.min() << '\n'
            << "Max = " << stats.max() << '\n'
            << "Sum = " << stats.sum() << '\n'
            << "Sum of Squares = " << stats.sum_of_squares() << '\n'
            << "Mean = " << stats.mean() << '\n'
            << "Variance = " << stats.variance() << '\n'
            << "Stdev = " << stats.stdev() << '\n'
            << "Coefficient of Variation = " << stats.cv() << endl;

    return 0;
}
<commit_msg>Fix _access symbol naming<commit_after>/* Copyright (c) 2011, Jon Maken
 * License: 3-clause BSD
 * Revision: 12/09/2011 2:36:08 PM
 *
 * Example:
 *
 *      HiRes::Statistics<double> stats =
 *          for_each(istream_iterator<double>(cin),
 *                   istream_iterator<double><(),
 *                   HiRes::Statistics<double>());
 */

#include <algorithm>
#include <iterator>
#include <iostream>
#include <iomanip>
#include <vector>

#if defined(_WIN32)
#  include <io.h>
#  define executable "basic_stats.exe"
#  define access _access
#else
#  include <unistd.h>
#  define executable "basic_stats"
#endif

#include "hrtimer.h"
#include "statistics.h"

const int TEST_COUNT = 20;

int main(int argc, char* argv[])
{
    using namespace std;

    double rv = 0.0;
    vector<double> data;
    HiRes::Timer<HiRes::us> tmr_us;

    for (int i = 0; i < TEST_COUNT; i++)
    {
        tmr_us.start();
        access(executable, 4);
        rv = tmr_us.stop();
        data.push_back(rv);
    }

    HiRes::Statistics<double> stats =
        for_each(data.begin(), data.end(), HiRes::Statistics<double>());

    cout    << "Count = " << stats.count() << '\n'
            << "Min = " << stats.min() << '\n'
            << "Max = " << stats.max() << '\n'
            << "Sum = " << stats.sum() << '\n'
            << "Sum of Squares = " << stats.sum_of_squares() << '\n'
            << "Mean = " << stats.mean() << '\n'
            << "Variance = " << stats.variance() << '\n'
            << "Stdev = " << stats.stdev() << '\n'
            << "Coefficient of Variation = " << stats.cv() << endl;

    return 0;
}
<|endoftext|>