<commit_before>#include <glog/logging.h>

#include <cstring>
#include <map>
#include <string>
#include <vector>

#include "boost/algorithm/string.hpp"
#include "caffe/caffe.hpp"

using caffe::Blob;
using caffe::Caffe;
using caffe::Net;
using caffe::Layer;
using caffe::shared_ptr;
using caffe::Timer;
using caffe::vector;

DEFINE_int32(gpu, -1,
    "Run in GPU mode on given device ID.");
DEFINE_string(solver, "",
    "The solver definition protocol buffer text file.");
DEFINE_string(model, "",
    "The model definition protocol buffer text file..");
DEFINE_string(snapshot, "",
    "Optional; the snapshot solver state to resume training.");
DEFINE_string(weights, "",
    "Optional; the pretrained weights to initialize finetuning. "
    "Cannot be set simultaneously with snapshot.");
DEFINE_int32(iterations, 50,
    "The number of iterations to run.");

// A simple registry for caffe commands.
typedef int (*BrewFunction)();
typedef std::map<caffe::string, BrewFunction> BrewMap;
BrewMap g_brew_map;

#define RegisterBrewFunction(func) \
namespace { \
class __Registerer_##func { \
 public: /* NOLINT */ \
  __Registerer_##func() { \
    g_brew_map[#func] = &func; \
  } \
}; \
__Registerer_##func g_registerer_##func; \
}

static BrewFunction GetBrewFunction(const caffe::string& name) {
  if (g_brew_map.count(name)) {
    return g_brew_map[name];
  } else {
    LOG(ERROR) << "Available caffe actions:";
    for (BrewMap::iterator it = g_brew_map.begin();
         it != g_brew_map.end(); ++it) {
      LOG(ERROR) << "\t" << it->first;
    }
    LOG(FATAL) << "Unknown action: " << name;
    return NULL;  // not reachable, just to suppress old compiler warnings.
  }
}

// caffe commands to call by
//     caffe <command> <args>
//
// To add a command, define a function "int command()" and register it with
// RegisterBrewFunction(action);

// Device Query: show diagnostic information for a GPU device.
int device_query() {
  CHECK_GT(FLAGS_gpu, -1) << "Need a device ID to query.";
  LOG(INFO) << "Querying device ID = " << FLAGS_gpu;
  caffe::Caffe::SetDevice(FLAGS_gpu);
  caffe::Caffe::DeviceQuery();
  return 0;
}
RegisterBrewFunction(device_query);

// Load the weights from the specified caffemodel(s) into the train and
// test nets.
void CopyLayers(caffe::Solver<float>* solver, const std::string& model_list) {
  std::vector<std::string> model_names;
  boost::split(model_names, model_list, boost::is_any_of(",") );
  for (int i = 0; i < model_names.size(); ++i) {
    LOG(INFO) << "Finetuning from " << model_names[i];
    solver->net()->CopyTrainedLayersFrom(model_names[i]);
    for (int j = 0; j < solver->test_nets().size(); ++j) {
      solver->test_nets()[j]->CopyTrainedLayersFrom(model_names[i]);
    }
  }
}

// Train / Finetune a model.
int train() {
  CHECK_GT(FLAGS_solver.size(), 0) << "Need a solver definition to train.";
  CHECK(!FLAGS_snapshot.size() || !FLAGS_weights.size())
      << "Give a snapshot to resume training or weights to finetune "
      "but not both.";

  caffe::SolverParameter solver_param;
  caffe::ReadProtoFromTextFileOrDie(FLAGS_solver, &solver_param);

  // If the gpu flag is not provided, allow the mode and device to be set
  // in the solver prototxt.
  if (FLAGS_gpu < 0
      && solver_param.solver_mode() == caffe::SolverParameter_SolverMode_GPU) {
    FLAGS_gpu = solver_param.device_id();
  }

  // Set device id and mode
  if (FLAGS_gpu >= 0) {
    LOG(INFO) << "Use GPU with device ID " << FLAGS_gpu;
    Caffe::SetDevice(FLAGS_gpu);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(INFO) << "Use CPU.";
    Caffe::set_mode(Caffe::CPU);
  }

  LOG(INFO) << "Starting Optimization";
  shared_ptr<caffe::Solver<float> >
    solver(caffe::GetSolver<float>(solver_param));

  if (FLAGS_snapshot.size()) {
    LOG(INFO) << "Resuming from " << FLAGS_snapshot;
    solver->Solve(FLAGS_snapshot);
  } else if (FLAGS_weights.size()) {
    CopyLayers(&*solver, FLAGS_weights);
    solver->Solve();
  } else {
    solver->Solve();
  }
  LOG(INFO) << "Optimization Done.";
  return 0;
}
RegisterBrewFunction(train);

// Test: score a model.
int test() {
  CHECK_GT(FLAGS_model.size(), 0) << "Need a model definition to score.";
  CHECK_GT(FLAGS_weights.size(), 0) << "Need model weights to score.";

  // Set device id and mode
  if (FLAGS_gpu >= 0) {
    LOG(INFO) << "Use GPU with device ID " << FLAGS_gpu;
    Caffe::SetDevice(FLAGS_gpu);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(INFO) << "Use CPU.";
    Caffe::set_mode(Caffe::CPU);
  }
  // Instantiate the caffe net.
  Net<float> caffe_net(FLAGS_model, caffe::TEST);
  caffe_net.CopyTrainedLayersFrom(FLAGS_weights);
  LOG(INFO) << "Running for " << FLAGS_iterations << " iterations.";

  vector<Blob<float>* > bottom_vec;
  vector<int> test_score_output_id;
  vector<float> test_score;
  float loss = 0;
  for (int i = 0; i < FLAGS_iterations; ++i) {
    float iter_loss;
    const vector<Blob<float>*>& result =
        caffe_net.Forward(bottom_vec, &iter_loss);
    loss += iter_loss;
    int idx = 0;
    for (int j = 0; j < result.size(); ++j) {
      const float* result_vec = result[j]->cpu_data();
      for (int k = 0; k < result[j]->count(); ++k, ++idx) {
        const float score = result_vec[k];
        if (i == 0) {
          test_score.push_back(score);
          test_score_output_id.push_back(j);
        } else {
          test_score[idx] += score;
        }
        const std::string& output_name = caffe_net.blob_names()[
            caffe_net.output_blob_indices()[j]];
        LOG(INFO) << "Batch " << i << ", " << output_name << " = " << score;
      }
    }
  }
  loss /= FLAGS_iterations;
  LOG(INFO) << "Loss: " << loss;
  for (int i = 0; i < test_score.size(); ++i) {
    const std::string& output_name = caffe_net.blob_names()[
        caffe_net.output_blob_indices()[test_score_output_id[i]]];
    const float loss_weight =
        caffe_net.blob_loss_weights()[caffe_net.output_blob_indices()[i]];
    std::ostringstream loss_msg_stream;
    const float mean_score = test_score[i] / FLAGS_iterations;
    if (loss_weight) {
      loss_msg_stream << " (* " << loss_weight
                      << " = " << loss_weight * mean_score << " loss)";
    }
    LOG(INFO) << output_name << " = " << mean_score << loss_msg_stream.str();
  }

  return 0;
}
RegisterBrewFunction(test);

// Time: benchmark the execution time of a model.
int time() {
  CHECK_GT(FLAGS_model.size(), 0) << "Need a model definition to time.";

  // Set device id and mode
  if (FLAGS_gpu >= 0) {
    LOG(INFO) << "Use GPU with device ID " << FLAGS_gpu;
    Caffe::SetDevice(FLAGS_gpu);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(INFO) << "Use CPU.";
    Caffe::set_mode(Caffe::CPU);
  }
  // Instantiate the caffe net.
  Net<float> caffe_net(FLAGS_model, caffe::TRAIN);

  // Do a clean forward and backward pass, so that memory allocation are done
  // and future iterations will be more stable.
  LOG(INFO) << "Performing Forward";
  // Note that for the speed benchmark, we will assume that the network does
  // not take any input blobs.
  float initial_loss;
  caffe_net.Forward(vector<Blob<float>*>(), &initial_loss);
  LOG(INFO) << "Initial loss: " << initial_loss;
  LOG(INFO) << "Performing Backward";
  caffe_net.Backward();

  const vector<shared_ptr<Layer<float> > >& layers = caffe_net.layers();
  const vector<vector<Blob<float>*> >& bottom_vecs = caffe_net.bottom_vecs();
  const vector<vector<Blob<float>*> >& top_vecs = caffe_net.top_vecs();
  const vector<vector<bool> >& bottom_need_backward =
      caffe_net.bottom_need_backward();
  LOG(INFO) << "*** Benchmark begins ***";
  LOG(INFO) << "Testing for " << FLAGS_iterations << " iterations.";
  Timer total_timer;
  total_timer.Start();
  Timer forward_timer;
  Timer backward_timer;
  Timer timer;
  std::vector<double> forward_time_per_layer(layers.size(), 0.0);
  std::vector<double> backward_time_per_layer(layers.size(), 0.0);
  double forward_time = 0.0;
  double backward_time = 0.0;
  for (int j = 0; j < FLAGS_iterations; ++j) {
    Timer iter_timer;
    iter_timer.Start();
    forward_timer.Start();
    for (int i = 0; i < layers.size(); ++i) {
      timer.Start();
      layers[i]->Forward(bottom_vecs[i], top_vecs[i]);
      forward_time_per_layer[i] += timer.MicroSeconds();
    }
    forward_time += forward_timer.MicroSeconds();
    backward_timer.Start();
    for (int i = layers.size() - 1; i >= 0; --i) {
      timer.Start();
      layers[i]->Backward(top_vecs[i], bottom_need_backward[i],
                          bottom_vecs[i]);
      backward_time_per_layer[i] += timer.MicroSeconds();
    }
    backward_time += backward_timer.MicroSeconds();
    LOG(INFO) << "Iteration: " << j + 1 << " forward-backward time: "
      << iter_timer.MilliSeconds() << " ms.";
  }
  LOG(INFO) << "Average time per layer: ";
  for (int i = 0; i < layers.size(); ++i) {
    const caffe::string& layername = layers[i]->layer_param().name();
    LOG(INFO) << std::setfill(' ') << std::setw(10) << layername <<
      "\tforward: " << forward_time_per_layer[i] / 1000 /
      FLAGS_iterations << " ms.";
    LOG(INFO) << std::setfill(' ') << std::setw(10) << layername  <<
      "\tbackward: " << backward_time_per_layer[i] / 1000 /
      FLAGS_iterations << " ms.";
  }
  total_timer.Stop();
  LOG(INFO) << "Average Forward pass: " << forward_time / 1000 /
    FLAGS_iterations << " ms.";
  LOG(INFO) << "Average Backward pass: " << backward_time / 1000 /
    FLAGS_iterations << " ms.";
  LOG(INFO) << "Average Forward-Backward: " << total_timer.MilliSeconds() /
    FLAGS_iterations << " ms.";
  LOG(INFO) << "Total Time: " << total_timer.MilliSeconds() << " ms.";
  LOG(INFO) << "*** Benchmark ends ***";
  return 0;
}
RegisterBrewFunction(time);

int main(int argc, char** argv) {
  // Print output to stderr (while still logging).
  FLAGS_alsologtostderr = 1;
  // Usage message.
  gflags::SetUsageMessage("command line brew\n"
      "usage: caffe <command> <args>\n\n"
      "commands:\n"
      "  train           train or finetune a model\n"
      "  test            score a model\n"
      "  device_query    show GPU diagnostic information\n"
      "  time            benchmark model execution time");
  // Run tool or show usage.
  caffe::GlobalInit(&argc, &argv);
  if (argc == 2) {
    return GetBrewFunction(caffe::string(argv[1]))();
  } else {
    gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/caffe");
  }
}
<commit_msg>fix blob_loss_weights index in test() in caffe.cpp<commit_after>#include <glog/logging.h>

#include <cstring>
#include <map>
#include <string>
#include <vector>

#include "boost/algorithm/string.hpp"
#include "caffe/caffe.hpp"

using caffe::Blob;
using caffe::Caffe;
using caffe::Net;
using caffe::Layer;
using caffe::shared_ptr;
using caffe::Timer;
using caffe::vector;

DEFINE_int32(gpu, -1,
    "Run in GPU mode on given device ID.");
DEFINE_string(solver, "",
    "The solver definition protocol buffer text file.");
DEFINE_string(model, "",
    "The model definition protocol buffer text file..");
DEFINE_string(snapshot, "",
    "Optional; the snapshot solver state to resume training.");
DEFINE_string(weights, "",
    "Optional; the pretrained weights to initialize finetuning. "
    "Cannot be set simultaneously with snapshot.");
DEFINE_int32(iterations, 50,
    "The number of iterations to run.");

// A simple registry for caffe commands.
typedef int (*BrewFunction)();
typedef std::map<caffe::string, BrewFunction> BrewMap;
BrewMap g_brew_map;

#define RegisterBrewFunction(func) \
namespace { \
class __Registerer_##func { \
 public: /* NOLINT */ \
  __Registerer_##func() { \
    g_brew_map[#func] = &func; \
  } \
}; \
__Registerer_##func g_registerer_##func; \
}

static BrewFunction GetBrewFunction(const caffe::string& name) {
  if (g_brew_map.count(name)) {
    return g_brew_map[name];
  } else {
    LOG(ERROR) << "Available caffe actions:";
    for (BrewMap::iterator it = g_brew_map.begin();
         it != g_brew_map.end(); ++it) {
      LOG(ERROR) << "\t" << it->first;
    }
    LOG(FATAL) << "Unknown action: " << name;
    return NULL;  // not reachable, just to suppress old compiler warnings.
  }
}

// caffe commands to call by
//     caffe <command> <args>
//
// To add a command, define a function "int command()" and register it with
// RegisterBrewFunction(action);

// Device Query: show diagnostic information for a GPU device.
int device_query() {
  CHECK_GT(FLAGS_gpu, -1) << "Need a device ID to query.";
  LOG(INFO) << "Querying device ID = " << FLAGS_gpu;
  caffe::Caffe::SetDevice(FLAGS_gpu);
  caffe::Caffe::DeviceQuery();
  return 0;
}
RegisterBrewFunction(device_query);

// Load the weights from the specified caffemodel(s) into the train and
// test nets.
void CopyLayers(caffe::Solver<float>* solver, const std::string& model_list) {
  std::vector<std::string> model_names;
  boost::split(model_names, model_list, boost::is_any_of(",") );
  for (int i = 0; i < model_names.size(); ++i) {
    LOG(INFO) << "Finetuning from " << model_names[i];
    solver->net()->CopyTrainedLayersFrom(model_names[i]);
    for (int j = 0; j < solver->test_nets().size(); ++j) {
      solver->test_nets()[j]->CopyTrainedLayersFrom(model_names[i]);
    }
  }
}

// Train / Finetune a model.
int train() {
  CHECK_GT(FLAGS_solver.size(), 0) << "Need a solver definition to train.";
  CHECK(!FLAGS_snapshot.size() || !FLAGS_weights.size())
      << "Give a snapshot to resume training or weights to finetune "
      "but not both.";

  caffe::SolverParameter solver_param;
  caffe::ReadProtoFromTextFileOrDie(FLAGS_solver, &solver_param);

  // If the gpu flag is not provided, allow the mode and device to be set
  // in the solver prototxt.
  if (FLAGS_gpu < 0
      && solver_param.solver_mode() == caffe::SolverParameter_SolverMode_GPU) {
    FLAGS_gpu = solver_param.device_id();
  }

  // Set device id and mode
  if (FLAGS_gpu >= 0) {
    LOG(INFO) << "Use GPU with device ID " << FLAGS_gpu;
    Caffe::SetDevice(FLAGS_gpu);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(INFO) << "Use CPU.";
    Caffe::set_mode(Caffe::CPU);
  }

  LOG(INFO) << "Starting Optimization";
  shared_ptr<caffe::Solver<float> >
    solver(caffe::GetSolver<float>(solver_param));

  if (FLAGS_snapshot.size()) {
    LOG(INFO) << "Resuming from " << FLAGS_snapshot;
    solver->Solve(FLAGS_snapshot);
  } else if (FLAGS_weights.size()) {
    CopyLayers(&*solver, FLAGS_weights);
    solver->Solve();
  } else {
    solver->Solve();
  }
  LOG(INFO) << "Optimization Done.";
  return 0;
}
RegisterBrewFunction(train);

// Test: score a model.
int test() {
  CHECK_GT(FLAGS_model.size(), 0) << "Need a model definition to score.";
  CHECK_GT(FLAGS_weights.size(), 0) << "Need model weights to score.";

  // Set device id and mode
  if (FLAGS_gpu >= 0) {
    LOG(INFO) << "Use GPU with device ID " << FLAGS_gpu;
    Caffe::SetDevice(FLAGS_gpu);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(INFO) << "Use CPU.";
    Caffe::set_mode(Caffe::CPU);
  }
  // Instantiate the caffe net.
  Net<float> caffe_net(FLAGS_model, caffe::TEST);
  caffe_net.CopyTrainedLayersFrom(FLAGS_weights);
  LOG(INFO) << "Running for " << FLAGS_iterations << " iterations.";

  vector<Blob<float>* > bottom_vec;
  vector<int> test_score_output_id;
  vector<float> test_score;
  float loss = 0;
  for (int i = 0; i < FLAGS_iterations; ++i) {
    float iter_loss;
    const vector<Blob<float>*>& result =
        caffe_net.Forward(bottom_vec, &iter_loss);
    loss += iter_loss;
    int idx = 0;
    for (int j = 0; j < result.size(); ++j) {
      const float* result_vec = result[j]->cpu_data();
      for (int k = 0; k < result[j]->count(); ++k, ++idx) {
        const float score = result_vec[k];
        if (i == 0) {
          test_score.push_back(score);
          test_score_output_id.push_back(j);
        } else {
          test_score[idx] += score;
        }
        const std::string& output_name = caffe_net.blob_names()[
            caffe_net.output_blob_indices()[j]];
        LOG(INFO) << "Batch " << i << ", " << output_name << " = " << score;
      }
    }
  }
  loss /= FLAGS_iterations;
  LOG(INFO) << "Loss: " << loss;
  for (int i = 0; i < test_score.size(); ++i) {
    const std::string& output_name = caffe_net.blob_names()[
        caffe_net.output_blob_indices()[test_score_output_id[i]]];
    const float loss_weight = caffe_net.blob_loss_weights()[
        caffe_net.output_blob_indices()[test_score_output_id[i]]];
    std::ostringstream loss_msg_stream;
    const float mean_score = test_score[i] / FLAGS_iterations;
    if (loss_weight) {
      loss_msg_stream << " (* " << loss_weight
                      << " = " << loss_weight * mean_score << " loss)";
    }
    LOG(INFO) << output_name << " = " << mean_score << loss_msg_stream.str();
  }

  return 0;
}
RegisterBrewFunction(test);

// Time: benchmark the execution time of a model.
int time() {
  CHECK_GT(FLAGS_model.size(), 0) << "Need a model definition to time.";

  // Set device id and mode
  if (FLAGS_gpu >= 0) {
    LOG(INFO) << "Use GPU with device ID " << FLAGS_gpu;
    Caffe::SetDevice(FLAGS_gpu);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(INFO) << "Use CPU.";
    Caffe::set_mode(Caffe::CPU);
  }
  // Instantiate the caffe net.
  Net<float> caffe_net(FLAGS_model, caffe::TRAIN);

  // Do a clean forward and backward pass, so that memory allocation are done
  // and future iterations will be more stable.
  LOG(INFO) << "Performing Forward";
  // Note that for the speed benchmark, we will assume that the network does
  // not take any input blobs.
  float initial_loss;
  caffe_net.Forward(vector<Blob<float>*>(), &initial_loss);
  LOG(INFO) << "Initial loss: " << initial_loss;
  LOG(INFO) << "Performing Backward";
  caffe_net.Backward();

  const vector<shared_ptr<Layer<float> > >& layers = caffe_net.layers();
  const vector<vector<Blob<float>*> >& bottom_vecs = caffe_net.bottom_vecs();
  const vector<vector<Blob<float>*> >& top_vecs = caffe_net.top_vecs();
  const vector<vector<bool> >& bottom_need_backward =
      caffe_net.bottom_need_backward();
  LOG(INFO) << "*** Benchmark begins ***";
  LOG(INFO) << "Testing for " << FLAGS_iterations << " iterations.";
  Timer total_timer;
  total_timer.Start();
  Timer forward_timer;
  Timer backward_timer;
  Timer timer;
  std::vector<double> forward_time_per_layer(layers.size(), 0.0);
  std::vector<double> backward_time_per_layer(layers.size(), 0.0);
  double forward_time = 0.0;
  double backward_time = 0.0;
  for (int j = 0; j < FLAGS_iterations; ++j) {
    Timer iter_timer;
    iter_timer.Start();
    forward_timer.Start();
    for (int i = 0; i < layers.size(); ++i) {
      timer.Start();
      layers[i]->Forward(bottom_vecs[i], top_vecs[i]);
      forward_time_per_layer[i] += timer.MicroSeconds();
    }
    forward_time += forward_timer.MicroSeconds();
    backward_timer.Start();
    for (int i = layers.size() - 1; i >= 0; --i) {
      timer.Start();
      layers[i]->Backward(top_vecs[i], bottom_need_backward[i],
                          bottom_vecs[i]);
      backward_time_per_layer[i] += timer.MicroSeconds();
    }
    backward_time += backward_timer.MicroSeconds();
    LOG(INFO) << "Iteration: " << j + 1 << " forward-backward time: "
      << iter_timer.MilliSeconds() << " ms.";
  }
  LOG(INFO) << "Average time per layer: ";
  for (int i = 0; i < layers.size(); ++i) {
    const caffe::string& layername = layers[i]->layer_param().name();
    LOG(INFO) << std::setfill(' ') << std::setw(10) << layername <<
      "\tforward: " << forward_time_per_layer[i] / 1000 /
      FLAGS_iterations << " ms.";
    LOG(INFO) << std::setfill(' ') << std::setw(10) << layername  <<
      "\tbackward: " << backward_time_per_layer[i] / 1000 /
      FLAGS_iterations << " ms.";
  }
  total_timer.Stop();
  LOG(INFO) << "Average Forward pass: " << forward_time / 1000 /
    FLAGS_iterations << " ms.";
  LOG(INFO) << "Average Backward pass: " << backward_time / 1000 /
    FLAGS_iterations << " ms.";
  LOG(INFO) << "Average Forward-Backward: " << total_timer.MilliSeconds() /
    FLAGS_iterations << " ms.";
  LOG(INFO) << "Total Time: " << total_timer.MilliSeconds() << " ms.";
  LOG(INFO) << "*** Benchmark ends ***";
  return 0;
}
RegisterBrewFunction(time);

int main(int argc, char** argv) {
  // Print output to stderr (while still logging).
  FLAGS_alsologtostderr = 1;
  // Usage message.
  gflags::SetUsageMessage("command line brew\n"
      "usage: caffe <command> <args>\n\n"
      "commands:\n"
      "  train           train or finetune a model\n"
      "  test            score a model\n"
      "  device_query    show GPU diagnostic information\n"
      "  time            benchmark model execution time");
  // Run tool or show usage.
  caffe::GlobalInit(&argc, &argv);
  if (argc == 2) {
    return GetBrewFunction(caffe::string(argv[1]))();
  } else {
    gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/caffe");
  }
}
<|endoftext|>


<commit_before>#include "tagpool.h"

TagPool::TagPool(SQLiteDB *db, QObject *parent) :
    QObject(parent),db_(db)
{
    connect(db_, SIGNAL(sigOpened()),
            this, SLOT(loadDBtags()));
}

QString TagPool::tagType(QString tag)
{
    if (tagcache_.contains(tag)){
        return tagcache_.value(tag);
    } else {
        return queryType(tag);
    }
}

QStringList TagPool::tagsInString(QString str) const
{
    QStringList tgts;

    // rip file extension name
    QRegExp rx(".*(?=(\\.(zip|rar|cb[zr]))$)");
    int pos = 0;
    if ((pos = rx.indexIn(str, pos)) != -1){
        str = rx.cap();
    }
    qDebug() << str;

    // regex section take out
    QStringList expli;
    QMap<int,QString> caps;
    expli << "([^\\[\\]]+)(?=\\])"      // [*]
          << "([^\\(\\)]+)(?=\\))"      // (*)
          << "([^【】]+)(?=】)"      // 【 】
          << "([^（）]+)(?=）)"      // （）
          << "([^\\[\\]\\(\\)【】（）~\\s\\-]+)";
    for ( int i =0; i< expli.size(); ++i){
        rx.setPattern(expli.at(i));
        pos = 0;
        while ((pos = rx.indexIn(str, pos)) != -1) {
            if (!caps.contains(pos)){
                caps.insert(pos,rx.cap());
            }
            pos += rx.matchedLength();
        }
    }
    auto e = caps.begin();
    while( e != caps.end()){
        tgts << e.value();
        ++e;
    }
    qDebug() << tgts;

    // return results
    return tgts;
}

QStringList TagPool::typeOptions() const
{
    QStringList li = db_->schema()->tables();
    li.removeAll("file");
    li.removeAll("rank");
    li.removeAll("tag");
    li.removeAll("link");
    return li;
}

void TagPool::handleTagTypeChange(QString tagName, QString type, QString oldType)
{
    if ( tagName.isEmpty())
        return;
    if (type.isEmpty()){    //remove
        db_->remove("tag", "name", tagName);
        tagcache_.remove(tagName);
    } else {
        QStringList cols, vs;
        cols << "name" << "type";
        vs << tagName <<  type;
        if( db_->hitValue("tag", "name", tagName) ){ // exist, update
            db_->update("tag", cols, vs, "name", tagName );
        } else {
            db_->insert("tag", cols, vs);
        }
    }
}

void TagPool::insertTags2Table()
{
    QSqlQuery q = db_->selectAll("tag");
    QStringList cols, vs;
    while(q.next()){
        cols << "name";
        vs << q.record().value(0).toString();
        db_->insert(q.record().value(1).toString(),cols,vs);
        cols.clear();
        vs.clear();
    }
}

void TagPool::loadDBtags()
{
    QStringList names = db_->allTableNameDotValuesOfField("name", "file");
    QString ndv, n, v;
    int pos;
    for (int i = 0; i < names.size(); ++i){
        ndv = names.at(i);
        pos = ndv.indexOf(".");
        n  = ndv.left(pos);
        v = ndv.mid(pos+1);
        tagcache_.insert(v, n);
    }

    QSqlQuery q = db_->selectAll("tag");
    while(q.next()){
        tagcache_.insert(q.record().value(0).toString(), q.record().value(1).toString());
    }
}

QString TagPool::queryType(QString tag)
{
    if (!db_->isOpen())
        return QString();

    return db_->whichTableContainsName(tag);
}
<commit_msg>avoid insert duplicate tags into DB tables.<commit_after>#include "tagpool.h"

TagPool::TagPool(SQLiteDB *db, QObject *parent) :
    QObject(parent),db_(db)
{
    connect(db_, SIGNAL(sigOpened()),
            this, SLOT(loadDBtags()));
}

QString TagPool::tagType(QString tag)
{
    if (tagcache_.contains(tag)){
        return tagcache_.value(tag);
    } else {
        return queryType(tag);
    }
}

QStringList TagPool::tagsInString(QString str) const
{
    QStringList tgts;

    // rip file extension name
    QRegExp rx(".*(?=(\\.(zip|rar|cb[zr]))$)");
    int pos = 0;
    if ((pos = rx.indexIn(str, pos)) != -1){
        str = rx.cap();
    }
    qDebug() << str;

    // regex section take out
    QStringList expli;
    QMap<int,QString> caps;
    expli << "([^\\[\\]]+)(?=\\])"      // [*]
          << "([^\\(\\)]+)(?=\\))"      // (*)
          << "([^【】]+)(?=】)"      // 【 】
          << "([^（）]+)(?=）)"      // （）
          << "([^\\[\\]\\(\\)【】（）~\\s\\-]+)";
    for ( int i =0; i< expli.size(); ++i){
        rx.setPattern(expli.at(i));
        pos = 0;
        while ((pos = rx.indexIn(str, pos)) != -1) {
            if (!caps.contains(pos)){
                caps.insert(pos,rx.cap());
            }
            pos += rx.matchedLength();
        }
    }
    auto e = caps.begin();
    while( e != caps.end()){
        tgts << e.value();
        ++e;
    }
    qDebug() << tgts;

    // return results
    return tgts;
}

QStringList TagPool::typeOptions() const
{
    QStringList li = db_->schema()->tables();
    li.removeAll("file");
    li.removeAll("rank");
    li.removeAll("tag");
    li.removeAll("link");
    return li;
}

void TagPool::handleTagTypeChange(QString tagName, QString type, QString oldType)
{
    if ( tagName.isEmpty())
        return;
    if (type.isEmpty()){    //remove
        db_->remove("tag", "name", tagName);
        tagcache_.remove(tagName);
    } else {
        QStringList cols, vs;
        cols << "name" << "type";
        vs << tagName <<  type;
        if( db_->hitValue("tag", "name", tagName) ){ // exist, update
            db_->update("tag", cols, vs, "name", tagName );
        } else {
            db_->insert("tag", cols, vs);
        }
    }
}

void TagPool::insertTags2Table()
{
    QSqlQuery q = db_->selectAll("tag");
    QString ttype, tn;
    while(q.next()){
        ttype = q.record().value(1).toString();
        tn = q.record().value(0).toString();
        if (!db_->hitValue(ttype,"name",tn)){
            QStringList cols, vs;
            cols << "name";
            vs << tn;
            db_->insert(ttype,cols,vs);
        }
    }
}

void TagPool::loadDBtags()
{
    QStringList names = db_->allTableNameDotValuesOfField("name", "file");
    QString ndv, n, v;
    int pos;
    for (int i = 0; i < names.size(); ++i){
        ndv = names.at(i);
        pos = ndv.indexOf(".");
        n  = ndv.left(pos);
        v = ndv.mid(pos+1);
        tagcache_.insert(v, n);
    }

    QSqlQuery q = db_->selectAll("tag");
    while(q.next()){
        tagcache_.insert(q.record().value(0).toString(), q.record().value(1).toString());
    }
}

QString TagPool::queryType(QString tag)
{
    if (!db_->isOpen())
        return QString();

    return db_->whichTableContainsName(tag);
}
<|endoftext|>


<commit_before>#include "Overlook.h"
#include <Mmsystem.h>

namespace Overlook {

Game::Game() {
	for(int i = 0; i < USEDSYMBOL_COUNT; i++)
		signal[i] = 0;
}

void Game::Refresh() {
	lock.Enter();

	Automation& a = GetAutomation();
	MetaTrader& mt = GetMetaTrader();
	System& sys = GetSystem();

	int count = 100;

	VectorMap<int, double> volat_sum, spread_sum, trend_sum, opp_sum, best_cases;
	int max_level = -10;

	opps.SetCount(a.sym_count);
	for(int i = 0; i < a.sym_count; i++) {
		SlowAutomation& sa = a.slow[i];
		GameOpportunity& go = opps[i];
		int end = sa.processbits_cursor - 1;
		int begin = max(0, end - count);

		int sys_sym = sys.used_symbols_id[i];
		const Price& askbid = mt.GetAskBid()[sys_sym];
		double spread = askbid.ask - askbid.bid;
		double volat = 0;
		int prev_sig = 0;
		int trend = 0;
		double max = -DBL_MAX, min = DBL_MAX;
		for(int j = begin; j < end; j++) {

			double open  = sa.open_buf[j];
			double close = sa.open_buf[j+1];

			if (open > max) max = open;
			if (open < min) min = open;

			int sig = close > open ? +1 : -1;
			if (sig == prev_sig)
				trend++;
			prev_sig = sig;
		}
		volat = max - min;

		volat_sum.Add(i, volat / sa.point);
		spread_sum.Add(i, volat / spread);
		trend_sum.Add(i, trend);

		sa.GetOutputValues(go.signal, go.level);
		opp_sum.Add(i, go.level);

		{
			double open  = sa.open_buf[end-2];
			double close = sa.open_buf[end];
			double best_case;
			if (open >= close) best_case = +(close / (open + spread) - 1.0);
			else               best_case = -(close / (open - spread) - 1.0);
			best_cases.Add(i, best_case);
		}
	}

	SortByValue(volat_sum,  StdGreater<double>());
	SortByValue(spread_sum, StdGreater<double>());
	SortByValue(best_cases, StdGreater<double>());
	SortByValue(trend_sum,  StdGreater<int>());
	SortByValue(opp_sum,    StdGreater<int>());

	GetMetaTrader()._GetOrders(0, false);

	GetExchangeSlots().Refresh();
	Slot* slot = GetExchangeSlots().FindCurrent();
	bool signal_changed = false;

	for(int i = 0; i < a.sym_count; i++) {
		GameOpportunity& go = opps[i];
		SlowAutomation& sa  = a.slow[i];

		go.vol_idx    = volat_sum.Find(i);
		go.spread_idx = spread_sum.Find(i);
		go.trend_idx  = trend_sum.Find(i);
		go.opp_idx    = opp_sum.Find(i);
		go.bcase_idx  = best_cases.Find(i);

		if (go.spread_idx < 6)
			max_level = max(max_level, go.level);

		int sys_sym = sys.used_symbols_id[i];
		if (slot) {
			String sym = sys.GetSymbol(sys_sym);
			String a = sym.Left(3);
			String b = sym.Right(3);

			go.is_active = false;
			if (slot->currencies.Find(a) != -1) go.is_active = true;
			if (slot->currencies.Find(b) != -1) go.is_active = true;
		}

		double lots = 0.0, profit = 0.0;
		const auto& open_orders = mt.GetOpenOrders();
		for(int j = 0; j < open_orders.GetCount(); j++) {
			const Order& o = open_orders[j];
			if (o.symbol == sys_sym) {
				lots += o.volume;
				profit = o.profit;
			}
		}
		go.profit = lots > 0.0 ? profit / (lots / 0.01) : 0.0;

		if (go.prev_lots == 0.0 && lots > 0.0) {

			// Clear drawer
			go.open_profits.SetCount(0);

			// Set opening time
			go.opened = GetUtcTime();
		}
		go.prev_lots = lots;

		if (lots > 0.0) {
			// Check SL/TP limits
			if (go.profit > tplimit || go.profit < sllimit) {
				signal[i] = 0;
				signal_changed = true;
			}

			// Check time limits
			int length = (GetUtcTime().Get() - go.opened.Get()) / 60;
			if (length >= timelimit) {
				signal[i] = 0;
				signal_changed = true;
			}

			go.open_profits.Add(go.profit);
		}
		else {
			if (autostart && go.spread_idx < spread_limit && go.level > 0) {
				if (!inversesig)
					signal[i] =  go.signal ? -1 : +1;
				else
					signal[i] = !go.signal ? -1 : +1;
				signal_changed = true;
			}
		}
	}

	if (signal_changed)
		sys.RefreshReal();

	if (max_level != prev_max_level && max_level > 0)
		PlaySound(TEXT("alert.wav"), NULL, SND_ASYNC | SND_FILENAME);
	prev_max_level = max_level;

	lock.Leave();
}

}
<commit_msg>Prevent useless restarts<commit_after>#include "Overlook.h"
#include <Mmsystem.h>

namespace Overlook {

Game::Game() {
	for(int i = 0; i < USEDSYMBOL_COUNT; i++)
		signal[i] = 0;
}

void Game::Refresh() {
	lock.Enter();

	Automation& a = GetAutomation();
	MetaTrader& mt = GetMetaTrader();
	System& sys = GetSystem();

	int count = 100;

	VectorMap<int, double> volat_sum, spread_sum, trend_sum, opp_sum, best_cases;
	int max_level = -10;

	opps.SetCount(a.sym_count);
	for(int i = 0; i < a.sym_count; i++) {
		SlowAutomation& sa = a.slow[i];
		GameOpportunity& go = opps[i];
		int end = sa.processbits_cursor - 1;
		int begin = max(0, end - count);

		int sys_sym = sys.used_symbols_id[i];
		const Price& askbid = mt.GetAskBid()[sys_sym];
		double spread = askbid.ask - askbid.bid;
		double volat = 0;
		int prev_sig = 0;
		int trend = 0;
		double max = -DBL_MAX, min = DBL_MAX;
		for(int j = begin; j < end; j++) {

			double open  = sa.open_buf[j];
			double close = sa.open_buf[j+1];

			if (open > max) max = open;
			if (open < min) min = open;

			int sig = close > open ? +1 : -1;
			if (sig == prev_sig)
				trend++;
			prev_sig = sig;
		}
		volat = max - min;

		volat_sum.Add(i, volat / sa.point);
		spread_sum.Add(i, volat / spread);
		trend_sum.Add(i, trend);

		sa.GetOutputValues(go.signal, go.level);
		opp_sum.Add(i, go.level);

		{
			double open  = sa.open_buf[end-2];
			double close = sa.open_buf[end];
			double best_case;
			if (open >= close) best_case = +(close / (open + spread) - 1.0);
			else               best_case = -(close / (open - spread) - 1.0);
			best_cases.Add(i, best_case);
		}
	}

	SortByValue(volat_sum,  StdGreater<double>());
	SortByValue(spread_sum, StdGreater<double>());
	SortByValue(best_cases, StdGreater<double>());
	SortByValue(trend_sum,  StdGreater<int>());
	SortByValue(opp_sum,    StdGreater<int>());

	GetMetaTrader()._GetOrders(0, false);

	GetExchangeSlots().Refresh();
	Slot* slot = GetExchangeSlots().FindCurrent();
	bool signal_changed = false;

	for(int i = 0; i < a.sym_count; i++) {
		GameOpportunity& go = opps[i];
		SlowAutomation& sa  = a.slow[i];

		go.vol_idx    = volat_sum.Find(i);
		go.spread_idx = spread_sum.Find(i);
		go.trend_idx  = trend_sum.Find(i);
		go.opp_idx    = opp_sum.Find(i);
		go.bcase_idx  = best_cases.Find(i);

		if (go.spread_idx < 6)
			max_level = max(max_level, go.level);

		int sys_sym = sys.used_symbols_id[i];
		if (slot) {
			String sym = sys.GetSymbol(sys_sym);
			String a = sym.Left(3);
			String b = sym.Right(3);

			go.is_active = false;
			if (slot->currencies.Find(a) != -1) go.is_active = true;
			if (slot->currencies.Find(b) != -1) go.is_active = true;
		}

		double lots = 0.0, profit = 0.0;
		const auto& open_orders = mt.GetOpenOrders();
		for(int j = 0; j < open_orders.GetCount(); j++) {
			const Order& o = open_orders[j];
			if (o.symbol == sys_sym) {
				lots += o.volume;
				profit = o.profit;
			}
		}
		go.profit = lots > 0.0 ? profit / (lots / 0.01) : 0.0;

		if (go.prev_lots == 0.0 && lots > 0.0) {

			// Clear drawer
			go.open_profits.SetCount(0);

			// Set opening time
			go.opened = GetUtcTime();
		}
		go.prev_lots = lots;

		bool start = autostart && go.spread_idx < spread_limit && go.level > 0;
		int startsig = 0;
		if (!inversesig)
			startsig =  go.signal ? -1 : +1;
		else
			startsig = !go.signal ? -1 : +1;

		if (lots > 0.0) {

			if (start && startsig == signal[i]) {
				// Don't check limits
			} else {
				// Check SL/TP limits
				if (go.profit > tplimit || go.profit < sllimit) {
					signal[i] = 0;
					signal_changed = true;
				}

				// Check time limits
				int length = (GetUtcTime().Get() - go.opened.Get()) / 60;
				if (length >= timelimit) {
					signal[i] = 0;
					signal_changed = true;
				}
			}

			go.open_profits.Add(go.profit);
		}
		else {
			if (start) {
				signal[i] = startsig;
				signal_changed = true;
			}
		}
	}

	if (signal_changed)
		sys.RefreshReal();

	if (max_level != prev_max_level && max_level > 0)
		PlaySound(TEXT("alert.wav"), NULL, SND_ASYNC | SND_FILENAME);
	prev_max_level = max_level;

	lock.Leave();
}

}
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include <sofa/component/collision/InciseAlongPathPerformer.h>
#include <sofa/component/topology/TriangleSetGeometryAlgorithms.h>

#include <sofa/helper/Factory.inl>

namespace sofa
{

namespace component
{

namespace collision
{
helper::Creator<InteractionPerformer::InteractionPerformerFactory, InciseAlongPathPerformer>  InciseAlongPathPerformerClass("InciseAlongPath");

void InciseAlongPathPerformer::start()
{
    startBody=this->interactor->getBodyPicked();

    if (cpt == 0) // register first position of incision
    {
        firstIncisionBody = startBody;
        cpt++;
        initialNbTriangles = startBody.body->getMeshTopology()->getNbTriangles();
        initialNbPoints = startBody.body->getMeshTopology()->getNbPoints();
    }
}

void InciseAlongPathPerformer::execute()
{

    if (freezePerformer) // This performer has been freezed
    {
        if (currentMethod == 1)
            startBody=this->interactor->getBodyPicked();

        return;
    }

    if (currentMethod == 0) // incise from clic to clic
    {
        if (firstBody.body == NULL) // first clic
            firstBody=startBody;
        else
        {
            if (firstBody.indexCollisionElement != startBody.indexCollisionElement)
                secondBody=startBody;
        }

        if (firstBody.body == NULL || secondBody.body == NULL) return;

        sofa::core::componentmodel::topology::TopologyModifier* topologyModifier;
        firstBody.body->getContext()->get(topologyModifier);

        // Handle Removing of topological element (from any type of topology)
        if(topologyModifier)
        {
            topologyChangeManager.incisionCollisionModel(firstBody.body, firstBody.indexCollisionElement, firstBody.point,
                    secondBody.body,  secondBody.indexCollisionElement,  secondBody.point,
                    snapingValue, snapingBorderValue );
        }

        firstBody = secondBody;
        secondBody.body = NULL;

        this->interactor->setBodyPicked(secondBody);
    }
    else
    {

        BodyPicked currentBody=this->interactor->getBodyPicked();
        if (currentBody.body == NULL || startBody.body == NULL) return;

        if (currentBody.indexCollisionElement == startBody.indexCollisionElement) return;

        sofa::core::componentmodel::topology::TopologyModifier* topologyModifier;
        startBody.body->getContext()->get(topologyModifier);

        // Handle Removing of topological element (from any type of topology)
        if(topologyModifier)
        {
            topologyChangeManager.incisionCollisionModel(startBody.body, startBody.indexCollisionElement, startBody.point,
                    currentBody.body,  currentBody.indexCollisionElement,  currentBody.point,
                    snapingValue, snapingBorderValue );
        }
        startBody = currentBody;
        firstBody = currentBody;

        currentBody.body=NULL;
        this->interactor->setBodyPicked(currentBody);
    }

}

void InciseAlongPathPerformer::setPerformerFreeze()
{
    freezePerformer = true;
    if (fullcut)
        this->PerformCompleteIncision();

    fullcut = true;
}

void InciseAlongPathPerformer::PerformCompleteIncision()
{
    if (firstIncisionBody.body == NULL || startBody.body == NULL)
    {
        std::cout << "Error: One picked body is null." << std::endl;
        return;
    }

    if (firstIncisionBody.indexCollisionElement == startBody.indexCollisionElement)
    {
        std::cout << "Error: picked body are the same." << std::endl;
        return;
    }

    // Initial point could have move due to gravity: looking for new coordinates of first incision point and triangle index.
    bool findTri = false;
    sofa::helper::vector <unsigned int> triAroundVertex = startBody.body->getMeshTopology()->getTrianglesAroundVertex(initialNbPoints);

    // Check if point index and triangle index are consistent.
    for (unsigned int j = 0; j<triAroundVertex.size(); ++j)
        if (triAroundVertex[j] == initialNbTriangles)
        {
            findTri = true;
            break;
        }

    if (!findTri)
    {
        std::cout << "Error: initial point of incision has not been found." << std::endl;
        return;
    }

    // Get new coordinate of first incision point:
    sofa::component::container::MechanicalObject<defaulttype::Vec3dTypes>* MechanicalObject=NULL;
    startBody.body->getContext()->get(MechanicalObject, sofa::core::objectmodel::BaseContext::SearchRoot);
    sofa::defaulttype::Vector3& the_point = (*MechanicalObject->getX())[initialNbPoints];

    // Get triangle index that will be incise
    // - Creating direction of incision
    sofa::defaulttype::Vector3 dir = startBody.point - the_point;
    // - looking for triangle in this direction
    sofa::component::topology::TriangleSetGeometryAlgorithms<Vec3Types>* triangleGeometry;
    startBody.body->getContext()->get(triangleGeometry);
    int the_triangle = triangleGeometry->getTriangleInDirection(initialNbPoints, dir);

    if (the_triangle == -1)
    {
        std::cout << "Error: initial triangle of incision has not been found." << std::endl;
        return;
    }

    sofa::core::componentmodel::topology::TopologyModifier* topologyModifier;
    startBody.body->getContext()->get(topologyModifier);
    // Handle Removing of topological element (from any type of topology)
    if(topologyModifier)
    {
        topologyChangeManager.incisionCollisionModel(startBody.body,  startBody.indexCollisionElement,  startBody.point,
                firstIncisionBody.body, (unsigned int)the_triangle, the_point,
                snapingValue, snapingBorderValue );
    }

    startBody = firstIncisionBody;
    firstIncisionBody.body = NULL;

    finishIncision = false; //Incure no second cut
}

InciseAlongPathPerformer::~InciseAlongPathPerformer()
{
    if (secondBody.body)
        secondBody.body= NULL;

    if (firstBody.body)
        firstBody.body = NULL;

    if (startBody.body)
        startBody.body = NULL;

    if (firstIncisionBody.body)
        firstIncisionBody.body = NULL;

    this->interactor->setBodyPicked(firstIncisionBody);
}

}
}
}

<commit_msg>r6961/sofa-dev : FIX: incision method with the mouse, when clicking outside the mesh.<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include <sofa/component/collision/InciseAlongPathPerformer.h>
#include <sofa/component/topology/TriangleSetGeometryAlgorithms.h>

#include <sofa/helper/Factory.inl>

namespace sofa
{

namespace component
{

namespace collision
{
helper::Creator<InteractionPerformer::InteractionPerformerFactory, InciseAlongPathPerformer>  InciseAlongPathPerformerClass("InciseAlongPath");

void InciseAlongPathPerformer::start()
{
    startBody=this->interactor->getBodyPicked();

    if (startBody.body == 0)
        return;

    if (cpt == 0) // register first position of incision
    {
        firstIncisionBody = startBody;
        cpt++;
        initialNbTriangles = startBody.body->getMeshTopology()->getNbTriangles();
        initialNbPoints = startBody.body->getMeshTopology()->getNbPoints();
    }
}

void InciseAlongPathPerformer::execute()
{

    if (freezePerformer) // This performer has been freezed
    {
        if (currentMethod == 1)
            startBody=this->interactor->getBodyPicked();

        return;
    }

    if (currentMethod == 0) // incise from clic to clic
    {
        if (firstBody.body == NULL) // first clic
            firstBody=startBody;
        else
        {
            if (firstBody.indexCollisionElement != startBody.indexCollisionElement)
                secondBody=startBody;
        }

        if (firstBody.body == NULL || secondBody.body == NULL) return;

        sofa::core::componentmodel::topology::TopologyModifier* topologyModifier;
        firstBody.body->getContext()->get(topologyModifier);

        // Handle Removing of topological element (from any type of topology)
        if(topologyModifier)
        {
            topologyChangeManager.incisionCollisionModel(firstBody.body, firstBody.indexCollisionElement, firstBody.point,
                    secondBody.body,  secondBody.indexCollisionElement,  secondBody.point,
                    snapingValue, snapingBorderValue );
        }

        firstBody = secondBody;
        secondBody.body = NULL;

        this->interactor->setBodyPicked(secondBody);
    }
    else
    {

        BodyPicked currentBody=this->interactor->getBodyPicked();
        if (currentBody.body == NULL || startBody.body == NULL) return;

        if (currentBody.indexCollisionElement == startBody.indexCollisionElement) return;

        sofa::core::componentmodel::topology::TopologyModifier* topologyModifier;
        startBody.body->getContext()->get(topologyModifier);

        // Handle Removing of topological element (from any type of topology)
        if(topologyModifier)
        {
            topologyChangeManager.incisionCollisionModel(startBody.body, startBody.indexCollisionElement, startBody.point,
                    currentBody.body,  currentBody.indexCollisionElement,  currentBody.point,
                    snapingValue, snapingBorderValue );
        }
        startBody = currentBody;
        firstBody = currentBody;

        currentBody.body=NULL;
        this->interactor->setBodyPicked(currentBody);
    }

}

void InciseAlongPathPerformer::setPerformerFreeze()
{
    freezePerformer = true;
    if (fullcut)
        this->PerformCompleteIncision();

    fullcut = true;
}

void InciseAlongPathPerformer::PerformCompleteIncision()
{
    if (firstIncisionBody.body == NULL || startBody.body == NULL)
    {
        std::cout << "Error: One picked body is null." << std::endl;
        return;
    }

    if (firstIncisionBody.indexCollisionElement == startBody.indexCollisionElement)
    {
        std::cout << "Error: picked body are the same." << std::endl;
        return;
    }

    // Initial point could have move due to gravity: looking for new coordinates of first incision point and triangle index.
    bool findTri = false;
    sofa::helper::vector <unsigned int> triAroundVertex = startBody.body->getMeshTopology()->getTrianglesAroundVertex(initialNbPoints);

    // Check if point index and triangle index are consistent.
    for (unsigned int j = 0; j<triAroundVertex.size(); ++j)
        if (triAroundVertex[j] == initialNbTriangles)
        {
            findTri = true;
            break;
        }

    if (!findTri)
    {
        std::cout << "Error: initial point of incision has not been found." << std::endl;
        return;
    }

    // Get new coordinate of first incision point:
    sofa::component::container::MechanicalObject<defaulttype::Vec3dTypes>* MechanicalObject=NULL;
    startBody.body->getContext()->get(MechanicalObject, sofa::core::objectmodel::BaseContext::SearchRoot);
    sofa::defaulttype::Vector3& the_point = (*MechanicalObject->getX())[initialNbPoints];

    // Get triangle index that will be incise
    // - Creating direction of incision
    sofa::defaulttype::Vector3 dir = startBody.point - the_point;
    // - looking for triangle in this direction
    sofa::component::topology::TriangleSetGeometryAlgorithms<Vec3Types>* triangleGeometry;
    startBody.body->getContext()->get(triangleGeometry);
    int the_triangle = triangleGeometry->getTriangleInDirection(initialNbPoints, dir);

    if (the_triangle == -1)
    {
        std::cout << "Error: initial triangle of incision has not been found." << std::endl;
        return;
    }

    sofa::core::componentmodel::topology::TopologyModifier* topologyModifier;
    startBody.body->getContext()->get(topologyModifier);
    // Handle Removing of topological element (from any type of topology)
    if(topologyModifier)
    {
        topologyChangeManager.incisionCollisionModel(startBody.body,  startBody.indexCollisionElement,  startBody.point,
                firstIncisionBody.body, (unsigned int)the_triangle, the_point,
                snapingValue, snapingBorderValue );
    }

    startBody = firstIncisionBody;
    firstIncisionBody.body = NULL;

    finishIncision = false; //Incure no second cut
}

InciseAlongPathPerformer::~InciseAlongPathPerformer()
{
    if (secondBody.body)
        secondBody.body= NULL;

    if (firstBody.body)
        firstBody.body = NULL;

    if (startBody.body)
        startBody.body = NULL;

    if (firstIncisionBody.body)
        firstIncisionBody.body = NULL;

    this->interactor->setBodyPicked(firstIncisionBody);
}

}
}
}

<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/video/capture/win/pin_base_win.h"

#include "base/logging.h"

namespace media {

// Implement IEnumPins.
class TypeEnumerator
    : public IEnumMediaTypes,
      public base::RefCounted<TypeEnumerator> {
 public:
  explicit TypeEnumerator(PinBase* pin)
      : pin_(pin),
        index_(0) {
  }

  ~TypeEnumerator() {
  }

  // Implement from IUnknown.
  STDMETHOD(QueryInterface)(REFIID iid, void** object_ptr) {
    if (iid == IID_IEnumMediaTypes || iid == IID_IUnknown) {
      AddRef();
      *object_ptr = static_cast<IEnumMediaTypes*>(this);
      return S_OK;
    }
    return E_NOINTERFACE;
  }

  STDMETHOD_(ULONG, AddRef)() {
    base::RefCounted<TypeEnumerator>::AddRef();
    return 1;
  }

  STDMETHOD_(ULONG, Release)() {
    base::RefCounted<TypeEnumerator>::Release();
    return 1;
  }

  // Implement IEnumMediaTypes.
  STDMETHOD(Next)(ULONG count, AM_MEDIA_TYPE** types, ULONG* fetched) {
    ULONG types_fetched = 0;

    while (types_fetched < count) {
      // Allocate AM_MEDIA_TYPE that we will store the media type in.
      AM_MEDIA_TYPE* type = reinterpret_cast<AM_MEDIA_TYPE*>(CoTaskMemAlloc(
          sizeof(AM_MEDIA_TYPE)));
      if (!type) {
        FreeAllocatedMediaTypes(types_fetched, types);
        return E_OUTOFMEMORY;
      }
      ZeroMemory(type, sizeof(AM_MEDIA_TYPE));

      // Allocate a VIDEOINFOHEADER and connect it to the AM_MEDIA_TYPE.
      type->cbFormat = sizeof(VIDEOINFOHEADER);
      BYTE *format = reinterpret_cast<BYTE*>(CoTaskMemAlloc(
          sizeof(VIDEOINFOHEADER)));
      if (!format) {
        CoTaskMemFree(type);
        FreeAllocatedMediaTypes(types_fetched, types);
        return E_OUTOFMEMORY;
      }
      type->pbFormat = format;
      // Get the media type from the pin.
      if (pin_->GetValidMediaType(index_++, type)) {
        types[types_fetched++] = type;
      } else {
        CoTaskMemFree(format);
        CoTaskMemFree(type);
        break;
      }
    }

    if (fetched)
      *fetched = types_fetched;

    return types_fetched == count ? S_OK : S_FALSE;
  }

  STDMETHOD(Skip)(ULONG count) {
    index_ += count;
    return S_OK;
  }

  STDMETHOD(Reset)() {
    index_ = 0;
    return S_OK;
  }

  STDMETHOD(Clone)(IEnumMediaTypes** clone) {
    TypeEnumerator* type_enum = new TypeEnumerator(pin_);
    if (!type_enum)
      return E_OUTOFMEMORY;
    type_enum->AddRef();
    type_enum->index_ = index_;
    *clone = type_enum;
    return S_OK;
  }

 private:
  void FreeAllocatedMediaTypes(ULONG allocated, AM_MEDIA_TYPE** types) {
    for (ULONG i = 0; i < allocated; ++i) {
      CoTaskMemFree(types[i]->pbFormat);
      CoTaskMemFree(types[i]);
    }
  }

  scoped_refptr<PinBase> pin_;
  int index_;
};

PinBase::PinBase(IBaseFilter* owner)
    : owner_(owner) {
  memset(&current_media_type_, 0, sizeof(current_media_type_));
}

PinBase::~PinBase() {
}

void PinBase::SetOwner(IBaseFilter* owner) {
  owner_ = owner;
}

// Called on an output pin to and establish a
//   connection.
STDMETHODIMP PinBase::Connect(IPin* receive_pin,
                              const AM_MEDIA_TYPE* media_type) {
  if (!receive_pin || !media_type)
    return E_POINTER;

  current_media_type_ = *media_type;
  receive_pin->AddRef();
  connected_pin_.Attach(receive_pin);
  HRESULT hr = receive_pin->ReceiveConnection(this, media_type);

  return hr;
}

// Called from an output pin on an input pin to and establish a
// connection.
STDMETHODIMP PinBase::ReceiveConnection(IPin* connector,
                                        const AM_MEDIA_TYPE* media_type) {
  if (!IsMediaTypeValid(media_type))
    return VFW_E_TYPE_NOT_ACCEPTED;

  current_media_type_ = current_media_type_;
  connector->AddRef();
  connected_pin_.Attach(connector);
  return S_OK;
}

STDMETHODIMP PinBase::Disconnect() {
  if (!connected_pin_)
    return S_FALSE;

  connected_pin_.Release();
  return S_OK;
}

STDMETHODIMP PinBase::ConnectedTo(IPin** pin) {
  *pin = connected_pin_;
  if (!connected_pin_)
    return VFW_E_NOT_CONNECTED;

  connected_pin_.get()->AddRef();
  return S_OK;
}

STDMETHODIMP PinBase::ConnectionMediaType(AM_MEDIA_TYPE* media_type) {
  if (!connected_pin_)
    return VFW_E_NOT_CONNECTED;
  *media_type = current_media_type_;
  return S_OK;
}

STDMETHODIMP PinBase::QueryPinInfo(PIN_INFO* info) {
  info->dir = PINDIR_INPUT;
  info->pFilter = owner_;
  if (owner_)
    owner_->AddRef();
  info->achName[0] = L'\0';

  return S_OK;
}

STDMETHODIMP PinBase::QueryDirection(PIN_DIRECTION* pin_dir) {
  *pin_dir = PINDIR_INPUT;
  return S_OK;
}

STDMETHODIMP PinBase::QueryId(LPWSTR* id) {
  NOTREACHED();
  return E_OUTOFMEMORY;
}

STDMETHODIMP PinBase::QueryAccept(const AM_MEDIA_TYPE* media_type) {
  return S_FALSE;
}

STDMETHODIMP PinBase::EnumMediaTypes(IEnumMediaTypes** types) {
  *types = new TypeEnumerator(this);
  (*types)->AddRef();
  return S_OK;
}

STDMETHODIMP PinBase::QueryInternalConnections(IPin** pins, ULONG* no_pins) {
  return E_NOTIMPL;
}

STDMETHODIMP PinBase::EndOfStream() {
  return S_OK;
}

STDMETHODIMP PinBase::BeginFlush() {
  return S_OK;
}

STDMETHODIMP PinBase::EndFlush() {
  return S_OK;
}

STDMETHODIMP PinBase::NewSegment(REFERENCE_TIME start,
                                 REFERENCE_TIME stop,
                                 double rate) {
  NOTREACHED();
  return E_NOTIMPL;
}

// Inherited from IMemInputPin.
STDMETHODIMP PinBase::GetAllocator(IMemAllocator** allocator) {
  return VFW_E_NO_ALLOCATOR;
}

STDMETHODIMP PinBase::NotifyAllocator(IMemAllocator* allocator,
                                      BOOL read_only) {
  return S_OK;
}

STDMETHODIMP PinBase::GetAllocatorRequirements(
    ALLOCATOR_PROPERTIES* properties) {
  return E_NOTIMPL;
}

STDMETHODIMP PinBase::ReceiveMultiple(IMediaSample** samples,
                                      long sample_count,
                                      long* processed) {
  NOTREACHED();
  return VFW_E_INVALIDMEDIATYPE;
}

STDMETHODIMP PinBase::ReceiveCanBlock() {
  return S_FALSE;
}

// Inherited from IUnknown.
STDMETHODIMP PinBase::QueryInterface(REFIID id, void** object_ptr) {
  if (id == IID_IPin || id == IID_IUnknown) {
    *object_ptr = static_cast<IPin*>(this);
  } else if (id == IID_IMemInputPin) {
    *object_ptr = static_cast<IMemInputPin*>(this);
  } else {
    return E_NOINTERFACE;
  }
  AddRef();
  return S_OK;
}

STDMETHODIMP_(ULONG) PinBase::AddRef() {
  base::RefCounted<PinBase>::AddRef();
  return 1;
}

STDMETHODIMP_(ULONG) PinBase::Release() {
  base::RefCounted<PinBase>::Release();
  return 1;
}

}  // namespace media
<commit_msg>PinBase: Fix assign-to-self bug.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/video/capture/win/pin_base_win.h"

#include "base/logging.h"

namespace media {

// Implement IEnumPins.
class TypeEnumerator
    : public IEnumMediaTypes,
      public base::RefCounted<TypeEnumerator> {
 public:
  explicit TypeEnumerator(PinBase* pin)
      : pin_(pin),
        index_(0) {
  }

  ~TypeEnumerator() {
  }

  // Implement from IUnknown.
  STDMETHOD(QueryInterface)(REFIID iid, void** object_ptr) {
    if (iid == IID_IEnumMediaTypes || iid == IID_IUnknown) {
      AddRef();
      *object_ptr = static_cast<IEnumMediaTypes*>(this);
      return S_OK;
    }
    return E_NOINTERFACE;
  }

  STDMETHOD_(ULONG, AddRef)() {
    base::RefCounted<TypeEnumerator>::AddRef();
    return 1;
  }

  STDMETHOD_(ULONG, Release)() {
    base::RefCounted<TypeEnumerator>::Release();
    return 1;
  }

  // Implement IEnumMediaTypes.
  STDMETHOD(Next)(ULONG count, AM_MEDIA_TYPE** types, ULONG* fetched) {
    ULONG types_fetched = 0;

    while (types_fetched < count) {
      // Allocate AM_MEDIA_TYPE that we will store the media type in.
      AM_MEDIA_TYPE* type = reinterpret_cast<AM_MEDIA_TYPE*>(CoTaskMemAlloc(
          sizeof(AM_MEDIA_TYPE)));
      if (!type) {
        FreeAllocatedMediaTypes(types_fetched, types);
        return E_OUTOFMEMORY;
      }
      ZeroMemory(type, sizeof(AM_MEDIA_TYPE));

      // Allocate a VIDEOINFOHEADER and connect it to the AM_MEDIA_TYPE.
      type->cbFormat = sizeof(VIDEOINFOHEADER);
      BYTE *format = reinterpret_cast<BYTE*>(CoTaskMemAlloc(
          sizeof(VIDEOINFOHEADER)));
      if (!format) {
        CoTaskMemFree(type);
        FreeAllocatedMediaTypes(types_fetched, types);
        return E_OUTOFMEMORY;
      }
      type->pbFormat = format;
      // Get the media type from the pin.
      if (pin_->GetValidMediaType(index_++, type)) {
        types[types_fetched++] = type;
      } else {
        CoTaskMemFree(format);
        CoTaskMemFree(type);
        break;
      }
    }

    if (fetched)
      *fetched = types_fetched;

    return types_fetched == count ? S_OK : S_FALSE;
  }

  STDMETHOD(Skip)(ULONG count) {
    index_ += count;
    return S_OK;
  }

  STDMETHOD(Reset)() {
    index_ = 0;
    return S_OK;
  }

  STDMETHOD(Clone)(IEnumMediaTypes** clone) {
    TypeEnumerator* type_enum = new TypeEnumerator(pin_);
    if (!type_enum)
      return E_OUTOFMEMORY;
    type_enum->AddRef();
    type_enum->index_ = index_;
    *clone = type_enum;
    return S_OK;
  }

 private:
  void FreeAllocatedMediaTypes(ULONG allocated, AM_MEDIA_TYPE** types) {
    for (ULONG i = 0; i < allocated; ++i) {
      CoTaskMemFree(types[i]->pbFormat);
      CoTaskMemFree(types[i]);
    }
  }

  scoped_refptr<PinBase> pin_;
  int index_;
};

PinBase::PinBase(IBaseFilter* owner)
    : owner_(owner) {
  memset(&current_media_type_, 0, sizeof(current_media_type_));
}

PinBase::~PinBase() {
}

void PinBase::SetOwner(IBaseFilter* owner) {
  owner_ = owner;
}

// Called on an output pin to and establish a
//   connection.
STDMETHODIMP PinBase::Connect(IPin* receive_pin,
                              const AM_MEDIA_TYPE* media_type) {
  if (!receive_pin || !media_type)
    return E_POINTER;

  current_media_type_ = *media_type;
  receive_pin->AddRef();
  connected_pin_.Attach(receive_pin);
  HRESULT hr = receive_pin->ReceiveConnection(this, media_type);

  return hr;
}

// Called from an output pin on an input pin to and establish a
// connection.
STDMETHODIMP PinBase::ReceiveConnection(IPin* connector,
                                        const AM_MEDIA_TYPE* media_type) {
  if (!IsMediaTypeValid(media_type))
    return VFW_E_TYPE_NOT_ACCEPTED;

  current_media_type_ = *media_type;
  connector->AddRef();
  connected_pin_.Attach(connector);
  return S_OK;
}

STDMETHODIMP PinBase::Disconnect() {
  if (!connected_pin_)
    return S_FALSE;

  connected_pin_.Release();
  return S_OK;
}

STDMETHODIMP PinBase::ConnectedTo(IPin** pin) {
  *pin = connected_pin_;
  if (!connected_pin_)
    return VFW_E_NOT_CONNECTED;

  connected_pin_.get()->AddRef();
  return S_OK;
}

STDMETHODIMP PinBase::ConnectionMediaType(AM_MEDIA_TYPE* media_type) {
  if (!connected_pin_)
    return VFW_E_NOT_CONNECTED;
  *media_type = current_media_type_;
  return S_OK;
}

STDMETHODIMP PinBase::QueryPinInfo(PIN_INFO* info) {
  info->dir = PINDIR_INPUT;
  info->pFilter = owner_;
  if (owner_)
    owner_->AddRef();
  info->achName[0] = L'\0';

  return S_OK;
}

STDMETHODIMP PinBase::QueryDirection(PIN_DIRECTION* pin_dir) {
  *pin_dir = PINDIR_INPUT;
  return S_OK;
}

STDMETHODIMP PinBase::QueryId(LPWSTR* id) {
  NOTREACHED();
  return E_OUTOFMEMORY;
}

STDMETHODIMP PinBase::QueryAccept(const AM_MEDIA_TYPE* media_type) {
  return S_FALSE;
}

STDMETHODIMP PinBase::EnumMediaTypes(IEnumMediaTypes** types) {
  *types = new TypeEnumerator(this);
  (*types)->AddRef();
  return S_OK;
}

STDMETHODIMP PinBase::QueryInternalConnections(IPin** pins, ULONG* no_pins) {
  return E_NOTIMPL;
}

STDMETHODIMP PinBase::EndOfStream() {
  return S_OK;
}

STDMETHODIMP PinBase::BeginFlush() {
  return S_OK;
}

STDMETHODIMP PinBase::EndFlush() {
  return S_OK;
}

STDMETHODIMP PinBase::NewSegment(REFERENCE_TIME start,
                                 REFERENCE_TIME stop,
                                 double rate) {
  NOTREACHED();
  return E_NOTIMPL;
}

// Inherited from IMemInputPin.
STDMETHODIMP PinBase::GetAllocator(IMemAllocator** allocator) {
  return VFW_E_NO_ALLOCATOR;
}

STDMETHODIMP PinBase::NotifyAllocator(IMemAllocator* allocator,
                                      BOOL read_only) {
  return S_OK;
}

STDMETHODIMP PinBase::GetAllocatorRequirements(
    ALLOCATOR_PROPERTIES* properties) {
  return E_NOTIMPL;
}

STDMETHODIMP PinBase::ReceiveMultiple(IMediaSample** samples,
                                      long sample_count,
                                      long* processed) {
  NOTREACHED();
  return VFW_E_INVALIDMEDIATYPE;
}

STDMETHODIMP PinBase::ReceiveCanBlock() {
  return S_FALSE;
}

// Inherited from IUnknown.
STDMETHODIMP PinBase::QueryInterface(REFIID id, void** object_ptr) {
  if (id == IID_IPin || id == IID_IUnknown) {
    *object_ptr = static_cast<IPin*>(this);
  } else if (id == IID_IMemInputPin) {
    *object_ptr = static_cast<IMemInputPin*>(this);
  } else {
    return E_NOINTERFACE;
  }
  AddRef();
  return S_OK;
}

STDMETHODIMP_(ULONG) PinBase::AddRef() {
  base::RefCounted<PinBase>::AddRef();
  return 1;
}

STDMETHODIMP_(ULONG) PinBase::Release() {
  base::RefCounted<PinBase>::Release();
  return 1;
}

}  // namespace media
<|endoftext|>


<commit_before>#include <clpeak.h>

#define MSTRINGIFY(...) #__VA_ARGS__

static const char *stringifiedKernels =
    #include "global_bandwidth_kernels.cl"
    #include "compute_sp_kernels.cl"
    #include "compute_hp_kernels.cl"
    #include "compute_dp_kernels.cl"
    #include "compute_integer_kernels.cl"
    ;

static const char *stringifiedKernelsNoInt =
    #include "global_bandwidth_kernels.cl"
    #include "compute_sp_kernels.cl"
    #include "compute_hp_kernels.cl"
    #include "compute_dp_kernels.cl"
    ;

#ifdef USE_STUB_OPENCL
// Prototype
extern "C" {
void stubOpenclReset();
}
#endif

clPeak::clPeak(): forcePlatform(false), forceDevice(false), useEventTimer(false),
    isGlobalBW(true), isComputeSP(true), isComputeDP(true), isComputeInt(true),
    isTransferBW(true), isKernelLatency(true),
    specifiedPlatform(0), specifiedDevice(0)
{
}

clPeak::~clPeak()
{
  if(log) delete log;
}

int clPeak::runAll()
{
  try
  {
#ifdef USE_STUB_OPENCL
    stubOpenclReset();
#endif
    vector<cl::Platform> platforms;
    cl::Platform::get(&platforms);

    log->xmlOpenTag("clpeak");
    log->xmlAppendAttribs("os", OS_NAME);
    for(size_t p=0; p < platforms.size(); p++)
    {
      if(forcePlatform && (p != specifiedPlatform))
        continue;

      std::string platformName = platforms[p].getInfo<CL_PLATFORM_NAME>();
      trimString(platformName);

      log->print(NEWLINE "Platform: " + platformName + NEWLINE);
      log->xmlOpenTag("platform");
      log->xmlAppendAttribs("name", platformName);

      bool isApple = (platformName.find("Apple") != std::string::npos)? true: false;

      cl_context_properties cps[3] = {
        CL_CONTEXT_PLATFORM,
        (cl_context_properties)(platforms[p])(),
        0
      };

      cl::Context ctx(CL_DEVICE_TYPE_ALL, cps);
      vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>();

      cl::Program prog;

      // FIXME Disabling integer compute tests on apple platform
      // Causes Segmentation fault: 11
      if(isApple)
      {
        cl::Program::Sources source(1, make_pair(stringifiedKernelsNoInt, (strlen(stringifiedKernelsNoInt)+1)));
        isComputeInt = false;
        prog = cl::Program(ctx, source);
      }
      else
      {
        cl::Program::Sources source(1, make_pair(stringifiedKernels, (strlen(stringifiedKernels)+1)));
        prog = cl::Program(ctx, source);
      }

      for(size_t d=0; d < devices.size(); d++)
      {
        if(forceDevice && (d != specifiedDevice))
          continue;

        device_info_t devInfo = getDeviceInfo(devices[d]);

        log->print(TAB "Device: " + devInfo.deviceName + NEWLINE);
        log->print(TAB TAB "Driver version  : ");
        log->print(devInfo.driverVersion);  log->print(" (" OS_NAME ")" NEWLINE);
        log->print(TAB TAB "Compute units   : ");
        log->print(devInfo.numCUs);         log->print(NEWLINE);
        log->print(TAB TAB "Clock frequency : ");
        log->print(devInfo.maxClockFreq);   log->print(" MHz" NEWLINE);
        log->xmlOpenTag("device");
        log->xmlAppendAttribs("name", devInfo.deviceName);
        log->xmlAppendAttribs("driver_version", devInfo.driverVersion);
        log->xmlAppendAttribs("compute_units", devInfo.numCUs);
        log->xmlAppendAttribs("clock_frequency", devInfo.maxClockFreq);
        log->xmlAppendAttribs("clock_frequency_unit", "MHz");

        try
        {
          vector<cl::Device> dev = {devices[d]};
          prog.build(dev, BUILD_OPTIONS);
        }
        catch (cl::Error &error)
        {
          UNUSED(error);
          log->print(TAB TAB "Build Log: " + prog.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[d])
                     + NEWLINE NEWLINE);
          continue;
        }

        cl::CommandQueue queue = cl::CommandQueue(ctx, devices[d], CL_QUEUE_PROFILING_ENABLE);

        runGlobalBandwidthTest(queue, prog, devInfo);
        runComputeSP(queue, prog, devInfo);
        runComputeHP(queue, prog, devInfo);
        runComputeDP(queue, prog, devInfo);
        runComputeInteger(queue, prog, devInfo);
        runTransferBandwidthTest(queue, prog, devInfo);
        runKernelLatency(queue, prog, devInfo);

        log->print(NEWLINE);
        log->xmlCloseTag();       // device
      }
      log->xmlCloseTag();           // platform
    }
    log->xmlCloseTag();               // clpeak
  }
  catch(cl::Error &error)
  {
    stringstream ss;
    ss << error.what() << " (" << error.err() << ")" NEWLINE;

    log->print(ss.str());
    return -1;
  }

  return 0;
}

float clPeak::run_kernel(cl::CommandQueue &queue, cl::Kernel &kernel, cl::NDRange &globalSize, cl::NDRange &localSize, uint iters)
{
  float timed = 0;

  // Dummy calls
  queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
  queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
  queue.finish();

  if(useEventTimer)
  {
    for(uint i=0; i<iters; i++)
    {
      cl::Event timeEvent;

      queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize, NULL, &timeEvent);
      queue.finish();
      timed += timeInUS(timeEvent);
    }
  } else      // std timer
  {
    Timer timer;

    timer.start();
    for(uint i=0; i<iters; i++)
    {
      queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
      queue.flush();
    }
    queue.finish();
    timed = timer.stopAndTime();
  }

  return (timed / static_cast<float>(iters));
}
<commit_msg>skip exit code for no platform error<commit_after>#include <clpeak.h>
#include <cstring>

#define MSTRINGIFY(...) #__VA_ARGS__

static const char *stringifiedKernels =
    #include "global_bandwidth_kernels.cl"
    #include "compute_sp_kernels.cl"
    #include "compute_hp_kernels.cl"
    #include "compute_dp_kernels.cl"
    #include "compute_integer_kernels.cl"
    ;

static const char *stringifiedKernelsNoInt =
    #include "global_bandwidth_kernels.cl"
    #include "compute_sp_kernels.cl"
    #include "compute_hp_kernels.cl"
    #include "compute_dp_kernels.cl"
    ;

#ifdef USE_STUB_OPENCL
// Prototype
extern "C" {
void stubOpenclReset();
}
#endif

clPeak::clPeak(): forcePlatform(false), forceDevice(false), useEventTimer(false),
    isGlobalBW(true), isComputeSP(true), isComputeDP(true), isComputeInt(true),
    isTransferBW(true), isKernelLatency(true),
    specifiedPlatform(0), specifiedDevice(0)
{
}

clPeak::~clPeak()
{
  if(log) delete log;
}

int clPeak::runAll()
{
  try
  {
#ifdef USE_STUB_OPENCL
    stubOpenclReset();
#endif
    vector<cl::Platform> platforms;
    cl::Platform::get(&platforms);

    log->xmlOpenTag("clpeak");
    log->xmlAppendAttribs("os", OS_NAME);
    for(size_t p=0; p < platforms.size(); p++)
    {
      if(forcePlatform && (p != specifiedPlatform))
        continue;

      std::string platformName = platforms[p].getInfo<CL_PLATFORM_NAME>();
      trimString(platformName);

      log->print(NEWLINE "Platform: " + platformName + NEWLINE);
      log->xmlOpenTag("platform");
      log->xmlAppendAttribs("name", platformName);

      bool isApple = (platformName.find("Apple") != std::string::npos)? true: false;

      cl_context_properties cps[3] = {
        CL_CONTEXT_PLATFORM,
        (cl_context_properties)(platforms[p])(),
        0
      };

      cl::Context ctx(CL_DEVICE_TYPE_ALL, cps);
      vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>();

      cl::Program prog;

      // FIXME Disabling integer compute tests on apple platform
      // Causes Segmentation fault: 11
      if(isApple)
      {
        cl::Program::Sources source(1, make_pair(stringifiedKernelsNoInt, (strlen(stringifiedKernelsNoInt)+1)));
        isComputeInt = false;
        prog = cl::Program(ctx, source);
      }
      else
      {
        cl::Program::Sources source(1, make_pair(stringifiedKernels, (strlen(stringifiedKernels)+1)));
        prog = cl::Program(ctx, source);
      }

      for(size_t d=0; d < devices.size(); d++)
      {
        if(forceDevice && (d != specifiedDevice))
          continue;

        device_info_t devInfo = getDeviceInfo(devices[d]);

        log->print(TAB "Device: " + devInfo.deviceName + NEWLINE);
        log->print(TAB TAB "Driver version  : ");
        log->print(devInfo.driverVersion);  log->print(" (" OS_NAME ")" NEWLINE);
        log->print(TAB TAB "Compute units   : ");
        log->print(devInfo.numCUs);         log->print(NEWLINE);
        log->print(TAB TAB "Clock frequency : ");
        log->print(devInfo.maxClockFreq);   log->print(" MHz" NEWLINE);
        log->xmlOpenTag("device");
        log->xmlAppendAttribs("name", devInfo.deviceName);
        log->xmlAppendAttribs("driver_version", devInfo.driverVersion);
        log->xmlAppendAttribs("compute_units", devInfo.numCUs);
        log->xmlAppendAttribs("clock_frequency", devInfo.maxClockFreq);
        log->xmlAppendAttribs("clock_frequency_unit", "MHz");

        try
        {
          vector<cl::Device> dev = {devices[d]};
          prog.build(dev, BUILD_OPTIONS);
        }
        catch (cl::Error &error)
        {
          UNUSED(error);
          log->print(TAB TAB "Build Log: " + prog.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[d])
                     + NEWLINE NEWLINE);
          continue;
        }

        cl::CommandQueue queue = cl::CommandQueue(ctx, devices[d], CL_QUEUE_PROFILING_ENABLE);

        runGlobalBandwidthTest(queue, prog, devInfo);
        runComputeSP(queue, prog, devInfo);
        runComputeHP(queue, prog, devInfo);
        runComputeDP(queue, prog, devInfo);
        runComputeInteger(queue, prog, devInfo);
        runTransferBandwidthTest(queue, prog, devInfo);
        runKernelLatency(queue, prog, devInfo);

        log->print(NEWLINE);
        log->xmlCloseTag();       // device
      }
      log->xmlCloseTag();           // platform
    }
    log->xmlCloseTag();               // clpeak
  }
  catch(cl::Error &error)
  {
    stringstream ss;
    ss << error.what() << " (" << error.err() << ")" NEWLINE;

    log->print(ss.str());

    // skip error for no platform
    if(strcmp(error.what(), "clGetPlatformIDs") == 0)
    {
        log->print("no platforms found" NEWLINE);
    }
    else
    {
        return -1;
    }
  }

  return 0;
}

float clPeak::run_kernel(cl::CommandQueue &queue, cl::Kernel &kernel, cl::NDRange &globalSize, cl::NDRange &localSize, uint iters)
{
  float timed = 0;

  // Dummy calls
  queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
  queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
  queue.finish();

  if(useEventTimer)
  {
    for(uint i=0; i<iters; i++)
    {
      cl::Event timeEvent;

      queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize, NULL, &timeEvent);
      queue.finish();
      timed += timeInUS(timeEvent);
    }
  } else      // std timer
  {
    Timer timer;

    timer.start();
    for(uint i=0; i<iters; i++)
    {
      queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
      queue.flush();
    }
    queue.finish();
    timed = timer.stopAndTime();
  }

  return (timed / static_cast<float>(iters));
}
<|endoftext|>


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

#ifndef _CONNECTIVITY_MAB_COLUMNALIAS_HXX_
#define _CONNECTIVITY_MAB_COLUMNALIAS_HXX_

#ifndef _UNOTOOLS_CONFIGNODE_HXX_
#include <unotools/confignode.hxx>
#endif

#include <osl/mutex.hxx>
#include <vector>
#include <map>

namespace connectivity
{
    namespace mozab
    {
        typedef enum {
            FIRSTNAME = 0,
            LASTNAME,
            DISPLAYNAME,
            NICKNAME,
            PRIMARYEMAIL,
            SECONDEMAIL,
            PREFERMAILFORMAT,
            WORKPHONE,
            HOMEPHONE,
            FAXNUMBER,
            PAGERNUMBER,
            CELLULARNUMBER,
            HOMEADDRESS,
            HOMEADDRESS2,
            HOMECITY,
            HOMESTATE,
            HOMEZIPCODE,
            HOMECOUNTRY,
            WORKADDRESS,
            WORKADDRESS2,
            WORKCITY,
            WORKSTATE,
            WORKZIPCODE,
            WORKCOUNTRY,
            JOBTITLE,
            DEPARTMENT,
            COMPANY,
            WEBPAGE1,
            WEBPAGE2,
            BIRTHYEAR,
            BIRTHMONTH,
            BIRTHDAY,
            CUSTOM1,
            CUSTOM2,
            CUSTOM3,
            CUSTOM4,
            NOTES,
            END
        } ProgrammaticName;

        class OColumnAlias
        {
            /**
             * m_Alias holds aliases for the mozilla addressbook
              * column names. This member gets initialised during
                         * creation of the connection to the driver.
             * m_aAlias initialises m_aAliasMap which then can be
                 * used to find the corresponding programmatic name
             * when an alias is used as a query attribute. Mozilla
             * expects programmatic names from its clients.
               *
             * m_aAlias:   vector of aliases used to initialise m_aAliasMap.
             * m_AliasMap: map of {alias, programmaticname} pairs.
             *
             */
            private:
                ::std::vector< ::rtl::OUString> m_aAlias;
                ::std::map< ::rtl::OUString, ::rtl::OUString> m_aAliasMap;
            protected:
                ::osl::Mutex  m_aMutex;
            public:
                                void initialise(void);
                const ::std::vector< ::rtl::OUString> & getAlias(void) const;
                const ::std::map< ::rtl::OUString, ::rtl::OUString> & getAliasMap(void) const;
                void setAlias(const ::com::sun::star::uno::Reference<
                                                    ::com::sun::star::lang::XMultiServiceFactory > &);
            private:
                void setAliasMap(void);
            public:
                OColumnAlias(void);
                ~OColumnAlias(void);
        };
    }
}
#endif // _CONNECTIVITY_MAB_COLUMNALIAS_HXX_
<commit_msg>INTEGRATION: CWS dba205b (1.2.146); FILE MERGED 2006/08/09 19:52:36 fs 1.2.146.1: refactored the OColumnAlias class, in preparation of fixing #b6248060#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MColumnAlias.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: ihi $ $Date: 2006-10-18 13:07:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_COLUMNALIAS_HXX_
#define _CONNECTIVITY_MAB_COLUMNALIAS_HXX_

#ifndef _UNOTOOLS_CONFIGNODE_HXX_
#include <unotools/confignode.hxx>
#endif

#include <osl/mutex.hxx>
#include <vector>
#include <map>

namespace connectivity
{
    namespace mozab
    {
        class OColumnAlias
        {
        public:
            typedef enum {
                BEGIN = 0,

                FIRSTNAME = BEGIN,
                LASTNAME,
                DISPLAYNAME,
                NICKNAME,
                PRIMARYEMAIL,
                SECONDEMAIL,
                PREFERMAILFORMAT,
                WORKPHONE,
                HOMEPHONE,
                FAXNUMBER,
                PAGERNUMBER,
                CELLULARNUMBER,
                HOMEADDRESS,
                HOMEADDRESS2,
                HOMECITY,
                HOMESTATE,
                HOMEZIPCODE,
                HOMECOUNTRY,
                WORKADDRESS,
                WORKADDRESS2,
                WORKCITY,
                WORKSTATE,
                WORKZIPCODE,
                WORKCOUNTRY,
                JOBTITLE,
                DEPARTMENT,
                COMPANY,
                WEBPAGE1,
                WEBPAGE2,
                BIRTHYEAR,
                BIRTHMONTH,
                BIRTHDAY,
                CUSTOM1,
                CUSTOM2,
                CUSTOM3,
                CUSTOM4,
                NOTES,

                END
            } ProgrammaticName;

            struct AliasDescription
            {
                ::rtl::OUString     sProgrammaticName;
                ProgrammaticName    eProgrammaticNameIndex;

                AliasDescription()
                    :eProgrammaticNameIndex( END )
                {
                }

                AliasDescription( const ::rtl::OUString& _rName, ProgrammaticName _eIndex )
                    :sProgrammaticName( _rName ), eProgrammaticNameIndex( _eIndex )
                {
                }
            };

            typedef ::std::map< ::rtl::OUString, AliasDescription > AliasMap;

        private:
            AliasMap    m_aAliasMap;

        protected:
            ::osl::Mutex  m_aMutex;

        public:
            OColumnAlias(
                const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & );

            ProgrammaticName getProgrammaticNameIndex( const ::rtl::OUString& _rAliasName ) const;
            inline bool hasAlias( const ::rtl::OUString& _rAlias ) const
            {
                return m_aAliasMap.find( _rAlias ) != m_aAliasMap.end();
            }
            ::rtl::OUString getProgrammaticNameOrFallbackToAlias( const ::rtl::OUString& _rAlias ) const;

            inline AliasMap::const_iterator begin() const { return m_aAliasMap.begin(); }
            inline AliasMap::const_iterator end() const { return m_aAliasMap.end(); }

        private:
            void initialize( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB );
        };
    }
}
#endif // _CONNECTIVITY_MAB_COLUMNALIAS_HXX_
<|endoftext|>