<commit_before>#ifndef DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_HH
#define DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_HH

#include <dune/common/exceptions.hh>
#include <dune/common/parametertree.hh>

#include <dune/stuff/common/color.hh>

#include "model/interface.hh"
#include "model/default.hh"
#include "model/thermalblock.hh"
#include "model/affineparametric/default.hh"
//#include "model/affineparametric/twophase.hh"
//#include "model/affineparametric/thermalblock.hh"

namespace Dune {
namespace DetailedSolvers {
namespace LinearElliptic {

template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange, bool scalarDiffusion = true >
class Models
{
public:
  static std::vector< std::string > available()
  {
    return {
          "model.linearelliptic.default"
        , "model.linearelliptic.thermalblock"
        , "model.linearelliptic.affineparametric.default"
//        , "model.linearelliptic.affineparametric.twophase"
//        , "model.linearelliptic.affineparametric.thermalblock"
    };
  } // ... available()

  static Dune::ParameterTree defaultSettings(const std::string type, const std::string subname = "")
  {
    if (type == "model.linearelliptic.default")
      return ModelDefault< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >
          ::defaultSettings(subname);
    else if (type == "model.linearelliptic.thermalblock")
      return ModelThermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >
          ::defaultSettings(subname);
    else if (type == "model.linearelliptic.affineparametric.default")
      return ModelAffineParametricDefault<  DomainFieldType, dimDomain,
                                            RangeFieldType, dimRange, scalarDiffusion >::defaultSettings(subname);
//    else if (type == "model.linearelliptic.affineparametric.twophase")
//      return ModelAffineParametricTwoPhase< DomainFieldType, dimDomain,
//                                            RangeFieldType, dimRange >::createDefaultSettings(subname);
//    else if (type == "model.linearelliptic.affineparametric.thermalblock")
//      return ModelAffineParametricThermalblock< DomainFieldType, dimDomain,
//                                                RangeFieldType, dimRange >::createDefaultSettings(subname);
    else
      DUNE_THROW(Dune::RangeError,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " unknown model '" << type << "' requested!");
  } // ... createDefaultSettings(...)

  static ModelInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >*
  create(const std::string type = available()[0],
         const Dune::ParameterTree description = Dune::ParameterTree())
  {
    if (type == "model.linearelliptic.default")
      return ModelDefault< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >::create(description);
    else if (type == "model.linearelliptic.thermalblock")
      return ModelThermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >::create(description);
    else if (type == "model.linearelliptic.affineparametric.default")
      return ModelAffineParametricDefault<  DomainFieldType, dimDomain,
                                            RangeFieldType, dimRange, scalarDiffusion >::create(description);
//    else if (type == "model.linearelliptic.affineparametric.twophase")
//      return ModelAffineParametricTwoPhase< DomainFieldType, dimDomain,
//                                            RangeFieldType, dimRange >::create(description);
//    else if (type == "model.linearelliptic.affineparametric.thermalblock")
//      return ModelAffineParametricThermalblock< DomainFieldType, dimDomain,
//                                                RangeFieldType, dimRange >::create(description);
    else
      DUNE_THROW(Dune::RangeError,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " unknown model '" << type << "' requested!");
  } // ... create(...)
}; // class Models

} // namespace LinearElliptic
} // namespace DetailedSolvers
} // namespace Dune

#endif // DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_HH
<commit_msg>[linearelliptic.model] reenabled affineparametric.thermalblock<commit_after>#ifndef DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_HH
#define DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_HH

#include <dune/common/exceptions.hh>
#include <dune/common/parametertree.hh>

#include <dune/stuff/common/color.hh>

#include "model/interface.hh"
#include "model/default.hh"
#include "model/thermalblock.hh"
#include "model/affineparametric/default.hh"
//#include "model/affineparametric/twophase.hh"
#include "model/affineparametric/thermalblock.hh"

namespace Dune {
namespace DetailedSolvers {
namespace LinearElliptic {

template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange, bool scalarDiffusion = true >
class Models
{
public:
  static std::vector< std::string > available()
  {
    return {
          "model.linearelliptic.default"
        , "model.linearelliptic.thermalblock"
        , "model.linearelliptic.affineparametric.default"
//        , "model.linearelliptic.affineparametric.twophase"
        , "model.linearelliptic.affineparametric.thermalblock"
    };
  } // ... available()

  static Dune::ParameterTree defaultSettings(const std::string type, const std::string subname = "")
  {
    if (type == "model.linearelliptic.default")
      return ModelDefault< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >
          ::defaultSettings(subname);
    else if (type == "model.linearelliptic.thermalblock")
      return ModelThermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >
          ::defaultSettings(subname);
    else if (type == "model.linearelliptic.affineparametric.default")
      return ModelAffineParametricDefault<  DomainFieldType, dimDomain,
                                            RangeFieldType, dimRange, scalarDiffusion >::defaultSettings(subname);
//    else if (type == "model.linearelliptic.affineparametric.twophase")
//      return ModelAffineParametricTwoPhase< DomainFieldType, dimDomain,
//                                            RangeFieldType, dimRange >::defaultSettings(subname);
    else if (type == "model.linearelliptic.affineparametric.thermalblock")
      return ModelAffineParametricThermalblock< DomainFieldType, dimDomain,
                                                RangeFieldType, dimRange >::defaultSettings(subname);
    else
      DUNE_THROW(Dune::RangeError,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " unknown model '" << type << "' requested!");
  } // ... createDefaultSettings(...)

  static ModelInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >*
  create(const std::string type = available()[0],
         const Dune::ParameterTree description = Dune::ParameterTree())
  {
    if (type == "model.linearelliptic.default")
      return ModelDefault< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >::create(description);
    else if (type == "model.linearelliptic.thermalblock")
      return ModelThermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >::create(description);
    else if (type == "model.linearelliptic.affineparametric.default")
      return ModelAffineParametricDefault<  DomainFieldType, dimDomain,
                                            RangeFieldType, dimRange, scalarDiffusion >::create(description);
//    else if (type == "model.linearelliptic.affineparametric.twophase")
//      return ModelAffineParametricTwoPhase< DomainFieldType, dimDomain,
//                                            RangeFieldType, dimRange >::create(description);
    else if (type == "model.linearelliptic.affineparametric.thermalblock")
      return ModelAffineParametricThermalblock< DomainFieldType, dimDomain,
                                                RangeFieldType, dimRange >::create(description);
    else
      DUNE_THROW(Dune::RangeError,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " unknown model '" << type << "' requested!");
  } // ... create(...)
}; // class Models

} // namespace LinearElliptic
} // namespace DetailedSolvers
} // namespace Dune

#endif // DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_HH
<|endoftext|>


<commit_before>/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

#include <gtest/gtest.h>
#include <fluent-bit.h>
#include "data/json_invalid.h"
#include "data/json_small.h"
#include "data/json_long.h"

TEST(Outputs, json_invalid) {
    int i;
    int ret;
    int total;
    int bytes;
    char *p = (char *) JSON_INVALID;
    flb_ctx_t *ctx;
    int in_ffd;
    int out_ffd;

    ctx = flb_create();

    in_ffd = flb_input(ctx, (char *) "lib", NULL);
    EXPECT_TRUE(in_ffd >= 0);
    flb_input_set(ctx, in_ffd, "tag", "test", NULL);

    out_ffd = flb_output(ctx, (char *) "stdout", NULL);
    EXPECT_TRUE(out_ffd >= 0);
    flb_output_set(ctx, out_ffd, "match", "test", NULL);

    ret = flb_start(ctx);
    EXPECT_EQ(ret, 0);

    total = 0;
    for (i = 0; i < (int) sizeof(JSON_INVALID) - 1; i++) {
        bytes = flb_lib_push(ctx, in_ffd, p + i, 1);
        EXPECT_EQ(bytes, 1);
        total++;
    }

    flb_stop(ctx);
    flb_destroy(ctx);
}

/* It writes a very long JSON map (> 100KB) byte by byte */
TEST(Outputs, json_long) {
    int i;
    int ret;
    int total;
    int bytes;
    char *p = (char *) JSON_LONG;
    flb_ctx_t *ctx;
    int in_ffd;
    int out_ffd;

    ctx = flb_create();

    in_ffd = flb_input(ctx, (char *) "lib", NULL);
    EXPECT_TRUE(in_ffd >= 0);
    flb_input_set(ctx, in_ffd, "tag", "test", NULL);

    out_ffd = flb_output(ctx, (char *) "stdout", NULL);
    EXPECT_TRUE(out_ffd >= 0);
    flb_output_set(ctx, out_ffd, "match", "test", NULL);

    ret = flb_start(ctx);
    EXPECT_EQ(ret, 0);

    total = 0;
    for (i = 0; i < (int) sizeof(JSON_LONG) - 1; i++) {
        bytes = flb_lib_push(ctx, in_ffd, p + i, 1);
        EXPECT_EQ(bytes, 1);
        total++;
    }

    flb_stop(ctx);
    flb_destroy(ctx);
}

TEST(Outputs, json_small) {
    int i;
    int ret;
    int total;
    int bytes;
    char *p = (char *) JSON_SMALL;
    flb_ctx_t *ctx;
    int in_ffd;
    int out_ffd;

    ctx = flb_create();

    in_ffd = flb_input(ctx, (char *) "lib", NULL);
    EXPECT_TRUE(in_ffd >= 0);
    flb_input_set(ctx, in_ffd, "tag", "test", NULL);

    out_ffd = flb_output(ctx, (char *) "stdout", NULL);
    EXPECT_TRUE(out_ffd >= 0);
    flb_output_set(ctx, out_ffd, "match", "test", NULL);

    ret = flb_start(ctx);
    EXPECT_EQ(ret, 0);

    total = 0;
    for (i = 0; i < (int) sizeof(JSON_SMALL) - 1; i++) {
        bytes = flb_lib_push(ctx, in_ffd, p + i, 1);
        EXPECT_EQ(bytes, 1);
        total++;
    }

    flb_stop(ctx);
    flb_destroy(ctx);
}
<commit_msg>tests: fix the out_stdout test ends before flushing<commit_after>/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

#include <gtest/gtest.h>
#include <fluent-bit.h>
#include "data/json_invalid.h"
#include "data/json_small.h"
#include "data/json_long.h"

TEST(Outputs, json_invalid) {
    int i;
    int ret;
    int total;
    int bytes;
    char *p = (char *) JSON_INVALID;
    flb_ctx_t *ctx;
    int in_ffd;
    int out_ffd;

    ctx = flb_create();

    in_ffd = flb_input(ctx, (char *) "lib", NULL);
    EXPECT_TRUE(in_ffd >= 0);
    flb_input_set(ctx, in_ffd, "tag", "test", NULL);

    out_ffd = flb_output(ctx, (char *) "stdout", NULL);
    EXPECT_TRUE(out_ffd >= 0);
    flb_output_set(ctx, out_ffd, "match", "test", NULL);

    ret = flb_start(ctx);
    EXPECT_EQ(ret, 0);

    total = 0;
    for (i = 0; i < (int) sizeof(JSON_INVALID) - 1; i++) {
        bytes = flb_lib_push(ctx, in_ffd, p + i, 1);
        EXPECT_EQ(bytes, 1);
        total++;
    }

    sleep(1); /* waiting flush */

    flb_stop(ctx);
    flb_destroy(ctx);
}

/* It writes a very long JSON map (> 100KB) byte by byte */
TEST(Outputs, json_long) {
    int i;
    int ret;
    int total;
    int bytes;
    char *p = (char *) JSON_LONG;
    flb_ctx_t *ctx;
    int in_ffd;
    int out_ffd;

    ctx = flb_create();

    in_ffd = flb_input(ctx, (char *) "lib", NULL);
    EXPECT_TRUE(in_ffd >= 0);
    flb_input_set(ctx, in_ffd, "tag", "test", NULL);

    out_ffd = flb_output(ctx, (char *) "stdout", NULL);
    EXPECT_TRUE(out_ffd >= 0);
    flb_output_set(ctx, out_ffd, "match", "test", NULL);

    ret = flb_start(ctx);
    EXPECT_EQ(ret, 0);

    total = 0;
    for (i = 0; i < (int) sizeof(JSON_LONG) - 1; i++) {
        bytes = flb_lib_push(ctx, in_ffd, p + i, 1);
        EXPECT_EQ(bytes, 1);
        total++;
    }

    sleep(1); /* waiting flush */

    flb_stop(ctx);
    flb_destroy(ctx);
}

TEST(Outputs, json_small) {
    int i;
    int ret;
    int total;
    int bytes;
    char *p = (char *) JSON_SMALL;
    flb_ctx_t *ctx;
    int in_ffd;
    int out_ffd;

    ctx = flb_create();

    in_ffd = flb_input(ctx, (char *) "lib", NULL);
    EXPECT_TRUE(in_ffd >= 0);
    flb_input_set(ctx, in_ffd, "tag", "test", NULL);

    out_ffd = flb_output(ctx, (char *) "stdout", NULL);
    EXPECT_TRUE(out_ffd >= 0);
    flb_output_set(ctx, out_ffd, "match", "test", NULL);

    ret = flb_start(ctx);
    EXPECT_EQ(ret, 0);

    total = 0;
    for (i = 0; i < (int) sizeof(JSON_SMALL) - 1; i++) {
        bytes = flb_lib_push(ctx, in_ffd, p + i, 1);
        EXPECT_EQ(bytes, 1);
        total++;
    }

    sleep(1); /* waiting flush */

    flb_stop(ctx);
    flb_destroy(ctx);
}
<|endoftext|>


<commit_before>/* Copyright 2015 Google Inc. All Rights Reserved.

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

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

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

#include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"

#include <vector>
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/op_segment.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/core/notification.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/host_info.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session_options.h"
#include "tensorflow/core/public/version.h"
#include "tensorflow/core/util/device_name_utils.h"

namespace tensorflow {
namespace test {

Benchmark::Benchmark(const string& device, Graph* g,
                     const SessionOptions* options, Graph* init) {

  SessionOptions default_options;
  if (!options) {
    options = &default_options;
  }

  testing::StopTiming();
  string t = str_util::Uppercase(device);
  device_ =
      DeviceFactory::NewDevice(t, *options, "/job:localhost/replica:0/task:0");
  CHECK(device_) << "Could not create a " << device << " device";

  pool_ = new thread::ThreadPool(options->env, "blocking",
                                 port::NumSchedulableCPUs());

  auto runner = [this](std::function<void()> closure) {
    pool_->Schedule(closure);
  };

  rendez_ = NewLocalRendezvous();

  const int graph_def_version = g->versions().producer();

  LocalExecutorParams params;
  params.device = device_;
  params.function_library = nullptr;
  params.create_kernel = [this, graph_def_version](const NodeDef& ndef,
                                                   OpKernel** kernel) {
    return CreateNonCachedKernel(device_, nullptr, ndef, graph_def_version,
                                 kernel);
  };
  params.delete_kernel = [](OpKernel* kernel) {
    DeleteNonCachedKernel(kernel);
  };

  if (init) {
    Executor* init_exec;
    TF_CHECK_OK(NewLocalExecutor(params, init, &init_exec));
    Executor::Args args;
    args.rendezvous = rendez_;
    args.runner = runner;
    TF_CHECK_OK(init_exec->Run(args));
    delete init_exec;
  }

  TF_CHECK_OK(NewLocalExecutor(params, g, &exec_));
}

Benchmark::~Benchmark() {
  if (device_) {
    rendez_->Unref();
    delete exec_;
    delete device_;
    delete pool_;
  }
}

void Benchmark::Run(int iters) { RunWithArgs({}, {}, iters); }

string GetRendezvousKey(const Node* node) {
  string send_device;
  TF_CHECK_OK(GetNodeAttr(node->def(), "send_device", &send_device));
  string recv_device;
  TF_CHECK_OK(GetNodeAttr(node->def(), "recv_device", &recv_device));
  string tensor_name;
  TF_CHECK_OK(GetNodeAttr(node->def(), "tensor_name", &tensor_name));
  uint64 send_device_incarnation;
  TF_CHECK_OK(GetNodeAttr(node->def(), "send_device_incarnation",
                          reinterpret_cast<int64*>(&send_device_incarnation)));
  return Rendezvous::CreateKey(send_device, send_device_incarnation,
                               recv_device, tensor_name, FrameAndIter(0, 0));
}

void Benchmark::RunWithArgs(
    const std::vector<std::pair<const Node*, Tensor>>& inputs,
    const std::vector<const Node*>& outputs, int iters) {
  if (device_) {
    // Gets inputs' and outputs' rendezvous keys.
    std::vector<std::pair<string, Tensor>> in;
    for (const auto& p : inputs) {
      in.push_back({GetRendezvousKey(p.first), p.second});
    }
    std::vector<string> out;
    for (const auto& n : outputs) {
      out.push_back(GetRendezvousKey(n));
    }
    Tensor unused;  // In benchmark, we don't care the return value.
    bool is_dead;

    // Warm up
    Executor::Args args;
    args.rendezvous = rendez_;
    args.runner = [this](std::function<void()> closure) {
      pool_->Schedule(closure);
    };
    for (int i = 0; i < 3; ++i) {
      for (const auto& p : in) {
        rendez_->Send(p.first, Rendezvous::Args(), p.second, false);
      }
      TF_CHECK_OK(exec_->Run(args));
      for (const string& key : out) {
        rendez_->Recv(key, Rendezvous::Args(), &unused, &is_dead);
      }
    }
    TF_CHECK_OK(device_->Sync());

    testing::StartTiming();
    while (iters-- > 0) {
      for (const auto& p : in) {
        rendez_->Send(p.first, Rendezvous::Args(), p.second, false);
      }
      TF_CHECK_OK(exec_->Run(args));
      for (const string& key : out) {
        rendez_->Recv(key, Rendezvous::Args(), &unused, &is_dead);
      }
    }

    TF_CHECK_OK(device_->Sync());
    testing::StopTiming();
  }
}

}  // end namespace test
}  // end namespace tensorflow
<commit_msg>Don't do anything in benchmarks if iters == 0. Change: 122740998<commit_after>/* Copyright 2015 Google Inc. All Rights Reserved.

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

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

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

#include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"

#include <vector>
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/op_segment.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/core/notification.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/host_info.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session_options.h"
#include "tensorflow/core/public/version.h"
#include "tensorflow/core/util/device_name_utils.h"

namespace tensorflow {
namespace test {

Benchmark::Benchmark(const string& device, Graph* g,
                     const SessionOptions* options, Graph* init) {

  SessionOptions default_options;
  if (!options) {
    options = &default_options;
  }

  testing::StopTiming();
  string t = str_util::Uppercase(device);
  device_ =
      DeviceFactory::NewDevice(t, *options, "/job:localhost/replica:0/task:0");
  CHECK(device_) << "Could not create a " << device << " device";

  pool_ = new thread::ThreadPool(options->env, "blocking",
                                 port::NumSchedulableCPUs());

  auto runner = [this](std::function<void()> closure) {
    pool_->Schedule(closure);
  };

  rendez_ = NewLocalRendezvous();

  const int graph_def_version = g->versions().producer();

  LocalExecutorParams params;
  params.device = device_;
  params.function_library = nullptr;
  params.create_kernel = [this, graph_def_version](const NodeDef& ndef,
                                                   OpKernel** kernel) {
    return CreateNonCachedKernel(device_, nullptr, ndef, graph_def_version,
                                 kernel);
  };
  params.delete_kernel = [](OpKernel* kernel) {
    DeleteNonCachedKernel(kernel);
  };

  if (init) {
    Executor* init_exec;
    TF_CHECK_OK(NewLocalExecutor(params, init, &init_exec));
    Executor::Args args;
    args.rendezvous = rendez_;
    args.runner = runner;
    TF_CHECK_OK(init_exec->Run(args));
    delete init_exec;
  }

  TF_CHECK_OK(NewLocalExecutor(params, g, &exec_));
}

Benchmark::~Benchmark() {
  if (device_) {
    rendez_->Unref();
    delete exec_;
    delete device_;
    delete pool_;
  }
}

void Benchmark::Run(int iters) { RunWithArgs({}, {}, iters); }

string GetRendezvousKey(const Node* node) {
  string send_device;
  TF_CHECK_OK(GetNodeAttr(node->def(), "send_device", &send_device));
  string recv_device;
  TF_CHECK_OK(GetNodeAttr(node->def(), "recv_device", &recv_device));
  string tensor_name;
  TF_CHECK_OK(GetNodeAttr(node->def(), "tensor_name", &tensor_name));
  uint64 send_device_incarnation;
  TF_CHECK_OK(GetNodeAttr(node->def(), "send_device_incarnation",
                          reinterpret_cast<int64*>(&send_device_incarnation)));
  return Rendezvous::CreateKey(send_device, send_device_incarnation,
                               recv_device, tensor_name, FrameAndIter(0, 0));
}

void Benchmark::RunWithArgs(
    const std::vector<std::pair<const Node*, Tensor>>& inputs,
    const std::vector<const Node*>& outputs, int iters) {
  if (!device_ || iters == 0) {
    return;
  }
  // Gets inputs' and outputs' rendezvous keys.
  std::vector<std::pair<string, Tensor>> in;
  for (const auto& p : inputs) {
    in.push_back({GetRendezvousKey(p.first), p.second});
  }
  std::vector<string> out;
  for (const auto& n : outputs) {
    out.push_back(GetRendezvousKey(n));
  }
  Tensor unused;  // In benchmark, we don't care the return value.
  bool is_dead;

  // Warm up
  Executor::Args args;
  args.rendezvous = rendez_;
  args.runner = [this](std::function<void()> closure) {
    pool_->Schedule(closure);
  };
  for (int i = 0; i < 3; ++i) {
    for (const auto& p : in) {
      rendez_->Send(p.first, Rendezvous::Args(), p.second, false);
    }
    TF_CHECK_OK(exec_->Run(args));
    for (const string& key : out) {
      rendez_->Recv(key, Rendezvous::Args(), &unused, &is_dead);
    }
  }
  TF_CHECK_OK(device_->Sync());

  testing::StartTiming();
  while (iters-- > 0) {
    for (const auto& p : in) {
      rendez_->Send(p.first, Rendezvous::Args(), p.second, false);
    }
    TF_CHECK_OK(exec_->Run(args));
    for (const string& key : out) {
      rendez_->Recv(key, Rendezvous::Args(), &unused, &is_dead);
    }
  }

  TF_CHECK_OK(device_->Sync());
  testing::StopTiming();
}

}  // end namespace test
}  // end namespace tensorflow
<|endoftext|>


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

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

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

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

#if TENSORFLOW_USE_SYCL

#define EIGEN_USE_SYCL

#include "tensorflow/core/common_runtime/sycl/sycl_device_context.h"
#include "tensorflow/core/common_runtime/dma_helper.h"

#define EIGEN_USE_SYCL
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"

namespace tensorflow {

void SYCLDeviceContext::CopyCPUTensorToDevice(const Tensor *cpu_tensor,
                                              Device *device,
                                              Tensor *device_tensor,
                                              StatusCallback done) const {
  const int64 total_bytes = cpu_tensor->TotalBytes();
  if (total_bytes > 0) {
    const void *src_ptr = DMAHelper::base(cpu_tensor);
    void *dst_ptr = DMAHelper::base(device_tensor);
    switch (cpu_tensor->dtype()) {
    case DT_FLOAT:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<float *>(dst_ptr), static_cast<const float *>(src_ptr),
          total_bytes);
      break;
    case DT_DOUBLE:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<double *>(dst_ptr), static_cast<const double *>(src_ptr),
          total_bytes);
      break;
    case DT_INT32:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<int32 *>(dst_ptr), static_cast<const int32 *>(src_ptr),
          total_bytes);
      break;
    case DT_INT64:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<int64 *>(dst_ptr), static_cast<const int64 *>(src_ptr),
          total_bytes);
      break;
    case DT_HALF:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<Eigen::half *>(dst_ptr),
          static_cast<const Eigen::half *>(src_ptr), total_bytes);
      break;
    case DT_COMPLEX64:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<std::complex<float> *>(dst_ptr),
          static_cast<const std::complex<float> *>(src_ptr), total_bytes);
      break;
    case DT_COMPLEX128:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<std::complex<double> *>(dst_ptr),
          static_cast<const std::complex<double> *>(src_ptr), total_bytes);
      break;
    case DT_INT8:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<int8 *>(dst_ptr), static_cast<const int8 *>(src_ptr),
          total_bytes);
      break;
    case DT_INT16:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<int16 *>(dst_ptr), static_cast<const int16 *>(src_ptr),
          total_bytes);
      break;
    case DT_UINT8:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<uint8 *>(dst_ptr), static_cast<const uint8 *>(src_ptr),
          total_bytes);
      break;
    case DT_UINT16:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<uint16 *>(dst_ptr), static_cast<const uint16 *>(src_ptr),
          total_bytes);
      break;
    case DT_BOOL:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<bool *>(dst_ptr), static_cast<const bool *>(src_ptr),
          total_bytes);
      break;
    default:
      assert(false && "unsupported type");
    }
  }
  done(Status::OK());
}

void SYCLDeviceContext::CopyDeviceTensorToCPU(const Tensor *device_tensor,
                                              StringPiece edge_name,
                                              Device *device,
                                              Tensor *cpu_tensor,
                                              StatusCallback done) {
  const int64 total_bytes = device_tensor->TotalBytes();
  if (total_bytes > 0) {
    device->eigen_sycl_device()->deallocate_all();
    const void* src_ptr = DMAHelper::base(device_tensor);
    void* dst_ptr = DMAHelper::base(cpu_tensor);
    switch (device_tensor->dtype()) {
    case DT_FLOAT:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<float *>(dst_ptr), static_cast<const float *>(src_ptr),
          total_bytes);
      break;
    case DT_DOUBLE:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<double *>(dst_ptr), static_cast<const double *>(src_ptr),
          total_bytes);
      break;
    case DT_INT32:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<int32 *>(dst_ptr), static_cast<const int32 *>(src_ptr),
          total_bytes);
      break;
    case DT_INT64:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<int64 *>(dst_ptr), static_cast<const int64 *>(src_ptr),
          total_bytes);
      break;
    case DT_HALF:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<Eigen::half *>(dst_ptr),
          static_cast<const Eigen::half *>(src_ptr), total_bytes);
      break;
    case DT_COMPLEX64:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<std::complex<float> *>(dst_ptr),
          static_cast<const std::complex<float> *>(src_ptr), total_bytes);
      break;
    case DT_COMPLEX128:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<std::complex<double> *>(dst_ptr),
          static_cast<const std::complex<double> *>(src_ptr), total_bytes);
      break;
    case DT_INT8:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<int8 *>(dst_ptr), static_cast<const int8 *>(src_ptr),
          total_bytes);
      break;
    case DT_INT16:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<int16 *>(dst_ptr), static_cast<const int16 *>(src_ptr),
          total_bytes);
      break;
    case DT_UINT8:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<uint8 *>(dst_ptr), static_cast<const uint8 *>(src_ptr),
          total_bytes);
      break;
    case DT_UINT16:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<uint16 *>(dst_ptr), static_cast<const uint16 *>(src_ptr),
          total_bytes);
      break;
    case DT_BOOL:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<bool *>(dst_ptr), static_cast<const bool *>(src_ptr),
          total_bytes);
      break;
    default:
      assert(false && "unsupported type");
    }
  }
  done(Status::OK());
}

}  // namespace tensorflow
#endif // TENSORFLOW_USE_SYCL
<commit_msg>Don't deallocate in CopyDeviceTensorToCPU, this hack isn't needed anymorewq<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

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

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

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

#if TENSORFLOW_USE_SYCL

#define EIGEN_USE_SYCL

#include "tensorflow/core/common_runtime/sycl/sycl_device_context.h"
#include "tensorflow/core/common_runtime/dma_helper.h"

#define EIGEN_USE_SYCL
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"

namespace tensorflow {

void SYCLDeviceContext::CopyCPUTensorToDevice(const Tensor *cpu_tensor,
                                              Device *device,
                                              Tensor *device_tensor,
                                              StatusCallback done) const {
  const int64 total_bytes = cpu_tensor->TotalBytes();
  if (total_bytes > 0) {
    const void *src_ptr = DMAHelper::base(cpu_tensor);
    void *dst_ptr = DMAHelper::base(device_tensor);
    switch (cpu_tensor->dtype()) {
    case DT_FLOAT:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<float *>(dst_ptr), static_cast<const float *>(src_ptr),
          total_bytes);
      break;
    case DT_DOUBLE:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<double *>(dst_ptr), static_cast<const double *>(src_ptr),
          total_bytes);
      break;
    case DT_INT32:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<int32 *>(dst_ptr), static_cast<const int32 *>(src_ptr),
          total_bytes);
      break;
    case DT_INT64:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<int64 *>(dst_ptr), static_cast<const int64 *>(src_ptr),
          total_bytes);
      break;
    case DT_HALF:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<Eigen::half *>(dst_ptr),
          static_cast<const Eigen::half *>(src_ptr), total_bytes);
      break;
    case DT_COMPLEX64:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<std::complex<float> *>(dst_ptr),
          static_cast<const std::complex<float> *>(src_ptr), total_bytes);
      break;
    case DT_COMPLEX128:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<std::complex<double> *>(dst_ptr),
          static_cast<const std::complex<double> *>(src_ptr), total_bytes);
      break;
    case DT_INT8:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<int8 *>(dst_ptr), static_cast<const int8 *>(src_ptr),
          total_bytes);
      break;
    case DT_INT16:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<int16 *>(dst_ptr), static_cast<const int16 *>(src_ptr),
          total_bytes);
      break;
    case DT_UINT8:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<uint8 *>(dst_ptr), static_cast<const uint8 *>(src_ptr),
          total_bytes);
      break;
    case DT_UINT16:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<uint16 *>(dst_ptr), static_cast<const uint16 *>(src_ptr),
          total_bytes);
      break;
    case DT_BOOL:
      device->eigen_sycl_device()->memcpyHostToDevice(
          static_cast<bool *>(dst_ptr), static_cast<const bool *>(src_ptr),
          total_bytes);
      break;
    default:
      assert(false && "unsupported type");
    }
  }
  done(Status::OK());
}

void SYCLDeviceContext::CopyDeviceTensorToCPU(const Tensor *device_tensor,
                                              StringPiece edge_name,
                                              Device *device,
                                              Tensor *cpu_tensor,
                                              StatusCallback done) {
  const int64 total_bytes = device_tensor->TotalBytes();
  if (total_bytes > 0) {
    const void* src_ptr = DMAHelper::base(device_tensor);
    void* dst_ptr = DMAHelper::base(cpu_tensor);
    switch (device_tensor->dtype()) {
    case DT_FLOAT:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<float *>(dst_ptr), static_cast<const float *>(src_ptr),
          total_bytes);
      break;
    case DT_DOUBLE:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<double *>(dst_ptr), static_cast<const double *>(src_ptr),
          total_bytes);
      break;
    case DT_INT32:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<int32 *>(dst_ptr), static_cast<const int32 *>(src_ptr),
          total_bytes);
      break;
    case DT_INT64:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<int64 *>(dst_ptr), static_cast<const int64 *>(src_ptr),
          total_bytes);
      break;
    case DT_HALF:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<Eigen::half *>(dst_ptr),
          static_cast<const Eigen::half *>(src_ptr), total_bytes);
      break;
    case DT_COMPLEX64:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<std::complex<float> *>(dst_ptr),
          static_cast<const std::complex<float> *>(src_ptr), total_bytes);
      break;
    case DT_COMPLEX128:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<std::complex<double> *>(dst_ptr),
          static_cast<const std::complex<double> *>(src_ptr), total_bytes);
      break;
    case DT_INT8:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<int8 *>(dst_ptr), static_cast<const int8 *>(src_ptr),
          total_bytes);
      break;
    case DT_INT16:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<int16 *>(dst_ptr), static_cast<const int16 *>(src_ptr),
          total_bytes);
      break;
    case DT_UINT8:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<uint8 *>(dst_ptr), static_cast<const uint8 *>(src_ptr),
          total_bytes);
      break;
    case DT_UINT16:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<uint16 *>(dst_ptr), static_cast<const uint16 *>(src_ptr),
          total_bytes);
      break;
    case DT_BOOL:
      device->eigen_sycl_device()->memcpyDeviceToHost(
          static_cast<bool *>(dst_ptr), static_cast<const bool *>(src_ptr),
          total_bytes);
      break;
    default:
      assert(false && "unsupported type");
    }
  }
  done(Status::OK());
}

}  // namespace tensorflow
#endif // TENSORFLOW_USE_SYCL
<|endoftext|>


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

#include <znc/Client.h>
#include <znc/Modules.h>
#include <znc/IRCNetwork.h>

#include <boost/regex.hpp>

using std::vector;

/*

Tested:
WeeChat 0.3.8 (Dec 17 2012)                                          - Yes, tested
Purple IRC                                                           - No, tested using finch (not Pidgin)
HexChat 2.10.0 [x64] / Windows 7 SP1 [3.69GHz]                       - Sometimes, requires a script
irssi v0.8.15                                                        - No, tested
Android IRC v2.1.15                                                  - Yes, tested on Kindle Fire
Yaaic - Yet another Android IRC client - http://www.yaaic.org        - Yes, tested with port on BB10 OS (no version info?)
Communi 2.2.0                                                        - No, tested with TinCanIRC on BB10 OS

Informed:
IRCCloud irccloud.com                                                - Yes, from wiki
xchat 2.8.6 Ubuntu                                                   - Sometimes, requires a script, from wiki
Textual IRC Client: www.textualapp.com  v5.0.0                      - Yes, from wiki
mIRC v7.29 Khaled Mardam-Bey                                         - Sometimes, requires a script, from wiki
Using libcommuni 3.0.1 - http://communi.github.com                   - Yes, as informed by the author
Colloquy 1.5.2 (5977) - iPhone OS 7.1.2 (ARM) - http://colloquy.mobi - Yes, from wiki

No information:
Android IRC Client (3.3.4 - Build 54a08b6 (dirty)-)                  - Not tested
AndChat 1.4.3.2 http://www.andchat.net                               - Not tested
*/

class CPrivmsgAuto : public CModule {
	void StatusCommand(const CString& sLine) {
		if (m_sNoPrefixClients.find(m_pClient) != m_sNoPrefixClients.end()) {
			PutModule("This client receives non-prefixed privmsg");
		} else {
			PutModule("This client receives prefixed privmsg");
		}
	}

	void ToggleCommand(const CString& sLine) {
		if (m_sNoPrefixClients.find(m_pClient) != m_sNoPrefixClients.end()) {
			m_sNoPrefixClients.erase(m_sNoPrefixClients.find(m_pClient));
			PutModule("This client will receive prefixed privmsg");
		} else {
			m_sNoPrefixClients.insert(m_pClient);
			PutModule("This client will receive non-prefixed privmsg");
		}
	}

public:
	MODCONSTRUCTOR(CPrivmsgAuto) {
		// Replace this with a command system to let people set their own, ship with known defaults?
		m_vCapableVersions.push_back(boost::regex("Android IRC v")); // Version?
		m_vCapableVersions.push_back(boost::regex("WeeChat")); // Version?
		m_vCapableVersions.push_back(boost::regex("Yaaic")); // Version?
		m_vCapableVersions.push_back(boost::regex("IRCCloud")); // Version?
		m_vCapableVersions.push_back(boost::regex("Colloquy")); // Version?
		m_vCapableVersions.push_back(boost::regex("Using libcommuni 3\\.(?:[1-9]+|0\\.[1-9]+)"));
		m_vCapableVersions.push_back(boost::regex("Textual .*(?:2\\.[1-9]{1}[0-9]*|[3-9]{1}[0-9]*)\\."));

		// The following require scripts ---
		m_vCapableVersions.push_back(boost::regex("HexChat 2\\.(?:9\\.[6-9]{1}|1(?:[0-9])+)"));
		m_vCapableVersions.push_back(boost::regex("xchat 2\\.(?:8\\.[6-9]{1}|1(?:[0-9])+)"));
		m_vCapableVersions.push_back(boost::regex("mIRC v(?:7\\.(?:(?:2[7-9])|(?:[3-9]|[0-9]{3,}))|(?:[8-9]|[0-9]{2,}))"));

		// Commands
		AddHelpCommand();
		AddCommand("Status", static_cast<CModCommand::ModCmdFunc>(&CPrivmsgAuto::StatusCommand));
		AddCommand("Toggle", static_cast<CModCommand::ModCmdFunc>(&CPrivmsgAuto::ToggleCommand));
	}

	// When loaded, send a ctcp version to all connected clients.
	virtual bool OnLoad(const CString& sArgsi, CString& sMessage) {
		if (m_pNetwork) {
			vector<CClient*> vClients = m_pNetwork->GetClients();
			for (std::vector<CClient*>::size_type i = 0; i != vClients.size(); i++) {
				if (vClients[i]->GetNetwork()) {
					if (m_pNetwork->IsIRCConnected ()) {
						vClients[i]->PutClient(":*privmsg_auto!znc@znc.in PRIVMSG " + m_pNetwork->GetIRCNick().GetNick() + " :\x01VERSION\x01");
					} else {
						vClients[i]->PutClient(":*privmsg_auto!znc@znc.in PRIVMSG " + m_pNetwork->GetNick() + " :\x01VERSION\x01");
					}
				}
			}
		}
		return true;
	}

	virtual void OnClientLogin() {
		m_pClient->PutClient(":*privmsg_auto!znc@znc.in PRIVMSG " + m_pNetwork->GetIRCNick().GetNick() + " :\001" + "VERSION" + "\001");
	}

	virtual void onClientDisconnect() {
		if (m_sNoPrefixClients.find(m_pClient) != m_sNoPrefixClients.end()) {
			m_sNoPrefixClients.erase(m_sNoPrefixClients.find(m_pClient));
		}
	}

	virtual void OnModNotice(const CString& sLine) {
		if (sLine.StartsWith("\001VERSION")) {
			CString line = CString(sLine);
			line.LeftChomp(9);
			line.RightChomp(1);
			bool found = false;

			for(std::vector<boost::regex>::size_type i = 0; i != m_vCapableVersions.size(); i++) {
				if (boost::regex_search(line, m_vCapableVersions[i])) {
					found = true;
					break;
				}
			}
//			PutModule(line);
			if (found) {
				m_sNoPrefixClients.insert(m_pClient);
//				PutModule("This client supports not-prefixed privmsg!");
//			} else {
//				PutModule("This client does not support non-prefixed privmsg");
			}
		}
	}

	virtual EModRet OnUserMsg(CString& sTarget, CString& sMessage) {
		if (m_pNetwork && m_pNetwork->GetIRCSock() && !m_pNetwork->IsChan(sTarget)) {
			vector<CClient*> vClients = m_pNetwork->GetClients();
			for (std::vector<CClient*>::size_type i = 0; i != vClients.size(); i++) {
				if (vClients[i] != m_pClient) {
					if (m_sNoPrefixClients.find(vClients[i]) != m_sNoPrefixClients.end()) {
						m_pNetwork->PutUser(":" + m_pNetwork->GetIRCNick().GetNickMask() + " PRIVMSG " + sTarget + " :" + sMessage, vClients[i], NULL);
					} else {
						m_pNetwork->PutUser(":" + sTarget + "!prefix@privmsg.znc.in PRIVMSG " + m_pNetwork->GetIRCNick().GetNick() + " :-> " + sMessage, vClients[i], NULL);
					}
				}
			}
		}

		return CONTINUE;
	}

	virtual EModRet OnUserAction(CString& sTarget, CString& sMessage) {
		if (m_pNetwork && m_pNetwork->GetIRCSock() && !m_pNetwork->IsChan(sTarget)) {
			vector<CClient*> vClients = m_pNetwork->GetClients();
			for (std::vector<CClient*>::size_type i = 0; i != vClients.size(); i++) {
				if (vClients[i] != m_pClient) {
					if (m_sNoPrefixClients.find(vClients[i]) != m_sNoPrefixClients.end()) {
						m_pNetwork->PutUser(":" + m_pNetwork->GetIRCNick().GetNickMask() + " PRIVMSG " + sTarget + " :\x01" + "ACTION " + sMessage + "\x01", vClients[i], NULL);
					} else {
						m_pNetwork->PutUser(":" + sTarget + "!prefix@privmsg.znc.in PRIVMSG " + m_pNetwork->GetIRCNick().GetNick() + " :\x01" + "ACTION -> " + sMessage + "\x01", vClients[i], NULL);
					}
				}
			}
		}

		return CONTINUE;
	}
private:
	std::set<CClient*> m_sNoPrefixClients;
	vector<boost::regex> m_vCapableVersions;
};

template<> void TModInfo<CPrivmsgAuto>(CModInfo& Info) {
	Info.SetWikiPage("privmsg_auto");
	Info.AddType(CModInfo::NetworkModule);
	Info.SetHasArgs(false);
}

NETWORKMODULEDEFS(CPrivmsgAuto, "Send outgoing PRIVMSGs and CTCP ACTIONs to other clients using ugly prefixes")
<commit_msg>Remove redundant AddInfo<commit_after>/*
 * Copyright (C) 2004-2014 ZNC, see the NOTICE file for details.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <znc/Client.h>
#include <znc/Modules.h>
#include <znc/IRCNetwork.h>

#include <boost/regex.hpp>

using std::vector;

/*

Tested:
WeeChat 0.3.8 (Dec 17 2012)                                          - Yes, tested
Purple IRC                                                           - No, tested using finch (not Pidgin)
HexChat 2.10.0 [x64] / Windows 7 SP1 [3.69GHz]                       - Sometimes, requires a script
irssi v0.8.15                                                        - No, tested
Android IRC v2.1.15                                                  - Yes, tested on Kindle Fire
Yaaic - Yet another Android IRC client - http://www.yaaic.org        - Yes, tested with port on BB10 OS (no version info?)
Communi 2.2.0                                                        - No, tested with TinCanIRC on BB10 OS

Informed:
IRCCloud irccloud.com                                                - Yes, from wiki
xchat 2.8.6 Ubuntu                                                   - Sometimes, requires a script, from wiki
Textual IRC Client: www.textualapp.com  v5.0.0                      - Yes, from wiki
mIRC v7.29 Khaled Mardam-Bey                                         - Sometimes, requires a script, from wiki
Using libcommuni 3.0.1 - http://communi.github.com                   - Yes, as informed by the author
Colloquy 1.5.2 (5977) - iPhone OS 7.1.2 (ARM) - http://colloquy.mobi - Yes, from wiki

No information:
Android IRC Client (3.3.4 - Build 54a08b6 (dirty)-)                  - Not tested
AndChat 1.4.3.2 http://www.andchat.net                               - Not tested
*/

class CPrivmsgAuto : public CModule {
	void StatusCommand(const CString& sLine) {
		if (m_sNoPrefixClients.find(m_pClient) != m_sNoPrefixClients.end()) {
			PutModule("This client receives non-prefixed privmsg");
		} else {
			PutModule("This client receives prefixed privmsg");
		}
	}

	void ToggleCommand(const CString& sLine) {
		if (m_sNoPrefixClients.find(m_pClient) != m_sNoPrefixClients.end()) {
			m_sNoPrefixClients.erase(m_sNoPrefixClients.find(m_pClient));
			PutModule("This client will receive prefixed privmsg");
		} else {
			m_sNoPrefixClients.insert(m_pClient);
			PutModule("This client will receive non-prefixed privmsg");
		}
	}

public:
	MODCONSTRUCTOR(CPrivmsgAuto) {
		// Replace this with a command system to let people set their own, ship with known defaults?
		m_vCapableVersions.push_back(boost::regex("Android IRC v")); // Version?
		m_vCapableVersions.push_back(boost::regex("WeeChat")); // Version?
		m_vCapableVersions.push_back(boost::regex("Yaaic")); // Version?
		m_vCapableVersions.push_back(boost::regex("IRCCloud")); // Version?
		m_vCapableVersions.push_back(boost::regex("Colloquy")); // Version?
		m_vCapableVersions.push_back(boost::regex("Using libcommuni 3\\.(?:[1-9]+|0\\.[1-9]+)"));
		m_vCapableVersions.push_back(boost::regex("Textual .*(?:2\\.[1-9]{1}[0-9]*|[3-9]{1}[0-9]*)\\."));

		// The following require scripts ---
		m_vCapableVersions.push_back(boost::regex("HexChat 2\\.(?:9\\.[6-9]{1}|1(?:[0-9])+)"));
		m_vCapableVersions.push_back(boost::regex("xchat 2\\.(?:8\\.[6-9]{1}|1(?:[0-9])+)"));
		m_vCapableVersions.push_back(boost::regex("mIRC v(?:7\\.(?:(?:2[7-9])|(?:[3-9]|[0-9]{3,}))|(?:[8-9]|[0-9]{2,}))"));

		// Commands
		AddHelpCommand();
		AddCommand("Status", static_cast<CModCommand::ModCmdFunc>(&CPrivmsgAuto::StatusCommand));
		AddCommand("Toggle", static_cast<CModCommand::ModCmdFunc>(&CPrivmsgAuto::ToggleCommand));
	}

	// When loaded, send a ctcp version to all connected clients.
	virtual bool OnLoad(const CString& sArgsi, CString& sMessage) {
		if (m_pNetwork) {
			vector<CClient*> vClients = m_pNetwork->GetClients();
			for (std::vector<CClient*>::size_type i = 0; i != vClients.size(); i++) {
				if (vClients[i]->GetNetwork()) {
					if (m_pNetwork->IsIRCConnected ()) {
						vClients[i]->PutClient(":*privmsg_auto!znc@znc.in PRIVMSG " + m_pNetwork->GetIRCNick().GetNick() + " :\x01VERSION\x01");
					} else {
						vClients[i]->PutClient(":*privmsg_auto!znc@znc.in PRIVMSG " + m_pNetwork->GetNick() + " :\x01VERSION\x01");
					}
				}
			}
		}
		return true;
	}

	virtual void OnClientLogin() {
		m_pClient->PutClient(":*privmsg_auto!znc@znc.in PRIVMSG " + m_pNetwork->GetIRCNick().GetNick() + " :\001" + "VERSION" + "\001");
	}

	virtual void onClientDisconnect() {
		if (m_sNoPrefixClients.find(m_pClient) != m_sNoPrefixClients.end()) {
			m_sNoPrefixClients.erase(m_sNoPrefixClients.find(m_pClient));
		}
	}

	virtual void OnModNotice(const CString& sLine) {
		if (sLine.StartsWith("\001VERSION")) {
			CString line = CString(sLine);
			line.LeftChomp(9);
			line.RightChomp(1);
			bool found = false;

			for(std::vector<boost::regex>::size_type i = 0; i != m_vCapableVersions.size(); i++) {
				if (boost::regex_search(line, m_vCapableVersions[i])) {
					found = true;
					break;
				}
			}
//			PutModule(line);
			if (found) {
				m_sNoPrefixClients.insert(m_pClient);
//				PutModule("This client supports not-prefixed privmsg!");
//			} else {
//				PutModule("This client does not support non-prefixed privmsg");
			}
		}
	}

	virtual EModRet OnUserMsg(CString& sTarget, CString& sMessage) {
		if (m_pNetwork && m_pNetwork->GetIRCSock() && !m_pNetwork->IsChan(sTarget)) {
			vector<CClient*> vClients = m_pNetwork->GetClients();
			for (std::vector<CClient*>::size_type i = 0; i != vClients.size(); i++) {
				if (vClients[i] != m_pClient) {
					if (m_sNoPrefixClients.find(vClients[i]) != m_sNoPrefixClients.end()) {
						m_pNetwork->PutUser(":" + m_pNetwork->GetIRCNick().GetNickMask() + " PRIVMSG " + sTarget + " :" + sMessage, vClients[i], NULL);
					} else {
						m_pNetwork->PutUser(":" + sTarget + "!prefix@privmsg.znc.in PRIVMSG " + m_pNetwork->GetIRCNick().GetNick() + " :-> " + sMessage, vClients[i], NULL);
					}
				}
			}
		}

		return CONTINUE;
	}

	virtual EModRet OnUserAction(CString& sTarget, CString& sMessage) {
		if (m_pNetwork && m_pNetwork->GetIRCSock() && !m_pNetwork->IsChan(sTarget)) {
			vector<CClient*> vClients = m_pNetwork->GetClients();
			for (std::vector<CClient*>::size_type i = 0; i != vClients.size(); i++) {
				if (vClients[i] != m_pClient) {
					if (m_sNoPrefixClients.find(vClients[i]) != m_sNoPrefixClients.end()) {
						m_pNetwork->PutUser(":" + m_pNetwork->GetIRCNick().GetNickMask() + " PRIVMSG " + sTarget + " :\x01" + "ACTION " + sMessage + "\x01", vClients[i], NULL);
					} else {
						m_pNetwork->PutUser(":" + sTarget + "!prefix@privmsg.znc.in PRIVMSG " + m_pNetwork->GetIRCNick().GetNick() + " :\x01" + "ACTION -> " + sMessage + "\x01", vClients[i], NULL);
					}
				}
			}
		}

		return CONTINUE;
	}
private:
	std::set<CClient*> m_sNoPrefixClients;
	vector<boost::regex> m_vCapableVersions;
};

template<> void TModInfo<CPrivmsgAuto>(CModInfo& Info) {
	Info.SetWikiPage("privmsg_auto");
	Info.SetHasArgs(false);
}

NETWORKMODULEDEFS(CPrivmsgAuto, "Send outgoing PRIVMSGs and CTCP ACTIONs to other clients using ugly prefixes")
<|endoftext|>


<commit_before>#include "platform/i_platform.h"
#include "soldier_spawn_system.h"
#include "engine.h"
#include "core/i_health_component.h"
#include "core/actor_factory.h"
#include "core/i_position_component.h"
#include "core/i_inventory_component.h"
#include "soldier_created_event.h"
#include "core/map/soldier_spawn_point_map_element_system.h"
#include "core/player_controller_component.h"
#include "render/visual_box_multiplier_component.h"

namespace engine {

SoldierSpawnSystem::SoldierSpawnSystem()
    : mScene( Scene::Get() )
    , mProgramState( core::ProgramState::Get() )
    , mActorFactory( ActorFactory::Get() )
    , mPlayerAutoId( AutoId( "player" ) )
{
}

void SoldierSpawnSystem::Init()
{
    mOnRevive = EventServer<core::ReviveEvent>::Get().Subscribe( boost::bind( &SoldierSpawnSystem::OnRevive, this, _1 ) );
}

void SoldierSpawnSystem::Update( double DeltaTime )
{
}

void SoldierSpawnSystem::OnRevive( core::ReviveEvent const& Evt )
{
    if ( mEnabled )
    {
        std::auto_ptr<Actor> player( Spawn( *Evt.mClientData ) );
        render::VisualBoxMultiplierComponent* vboxC( new render::VisualBoxMultiplierComponent() );
        vboxC->SetWidth( 2.0 );
        player->AddComponent( std::auto_ptr<Component>( vboxC ) );
        mScene.AddActor( player.release() );
    }
}

Opt<SoldierSpawnSystem> SoldierSpawnSystem::Get()
{
    return Engine::Get().GetSystem<SoldierSpawnSystem>();
}

std::auto_ptr<Actor> SoldierSpawnSystem::Spawn( core::ClientData& clientData )
{
    map::SpawnPoints_t spawnPoints( map::SoldierSpawnPointMapElementSystem::Get()->GetActiveSpawnPoints() );
    map::SpawnPoint spawnPoint( spawnPoints[RandomGenerator::global()() % spawnPoints.size()] );
    return Spawn( clientData, spawnPoint );
}

std::auto_ptr<Actor> SoldierSpawnSystem::Spawn( core::ClientData& clientData, map::SpawnPoint spawnPoint )
{
    std::auto_ptr<Actor> player( mActorFactory( mPlayerAutoId ) );
    return Spawn( clientData, spawnPoint, player );
}

std::auto_ptr<Actor> SoldierSpawnSystem::Spawn( core::ClientData& clientData, map::SpawnPoint spawnPoint, std::auto_ptr<Actor> player )
{
    Opt<Actor> clientActor( mScene.GetActor( clientData.mClientActorGUID ) );
    if( clientActor.IsValid() )
    {
        Opt<IHealthComponent> healthC = clientActor->Get<IHealthComponent>();
        if ( healthC.IsValid() && healthC->IsAlive() )
        {
            L1( "Cannot spawn soldier for clientData (%s) current soldier still alive!\n", clientData.mClientName.c_str() );
            return std::auto_ptr<Actor>();
        }
    }
    else
    {
        L2( "No actor for clientData(%s). (it might be an error on revive)\n", clientData.mClientName.c_str() );
    }
    L2( "player is valid %d", player.get() );
    Opt<IPositionComponent> positionC = player->Get<IPositionComponent>();
    L2( "positionC is valid %d", positionC.IsValid() );
    positionC->SetX( spawnPoint.mX );
    positionC->SetY( spawnPoint.mY );

    //TODO: temporary till normal inventory sync
    Opt<IInventoryComponent> inventoryC = player->Get<IInventoryComponent>();
    if ( inventoryC.IsValid() )
    {
        inventoryC->SetSelectedWeapon( AutoId( "pistol" ) );
    }

    Opt<PlayerControllerComponent> playerControllerC( player->Get<PlayerControllerComponent>() );
    if ( playerControllerC.IsValid() )
    {
        playerControllerC->mControllerId = clientData.mClientId;
        if ( mProgramState.mControlledActorGUID == clientData.mClientActorGUID
             && mProgramState.mMode != core::ProgramState::Server )
        {
            playerControllerC->SetEnabled( true );
            playerControllerC->mActive = true;
            mProgramState.mControlledActorGUID = player->GetGUID();
        }
    }
    clientData.mClientActorGUID = player->GetGUID(); //TODO: might seek for a better place
    L2( "player created clientId:%d clientName:%s actorId:%d\n", clientData.mClientId, clientData.mClientName.c_str(), clientData.mClientActorGUID );

    if ( mProgramState.mMode != core::ProgramState::Server &&
         mProgramState.mClientDatas.begin()->mClientActorGUID == player->GetGUID() )
    {
        Scene::Get().SetPlayerModels( Opt<Actor>( player.get() ) );
    }
    EventServer<SoldierCreatedEvent>::Get().SendEvent( SoldierCreatedEvent( clientData, Opt<Actor>( player.get() ) ) );
    return player;
}

} // namespace engine

<commit_msg>Remove debug code<commit_after>#include "platform/i_platform.h"
#include "soldier_spawn_system.h"
#include "engine.h"
#include "core/i_health_component.h"
#include "core/actor_factory.h"
#include "core/i_position_component.h"
#include "core/i_inventory_component.h"
#include "soldier_created_event.h"
#include "core/map/soldier_spawn_point_map_element_system.h"
#include "core/player_controller_component.h"

namespace engine {

SoldierSpawnSystem::SoldierSpawnSystem()
    : mScene( Scene::Get() )
    , mProgramState( core::ProgramState::Get() )
    , mActorFactory( ActorFactory::Get() )
    , mPlayerAutoId( AutoId( "player" ) )
{
}

void SoldierSpawnSystem::Init()
{
    mOnRevive = EventServer<core::ReviveEvent>::Get().Subscribe( boost::bind( &SoldierSpawnSystem::OnRevive, this, _1 ) );
}

void SoldierSpawnSystem::Update( double DeltaTime )
{
}

void SoldierSpawnSystem::OnRevive( core::ReviveEvent const& Evt )
{
    if ( mEnabled )
    {
        std::auto_ptr<Actor> player( Spawn( *Evt.mClientData ) );
        mScene.AddActor( player.release() );
    }
}

Opt<SoldierSpawnSystem> SoldierSpawnSystem::Get()
{
    return Engine::Get().GetSystem<SoldierSpawnSystem>();
}

std::auto_ptr<Actor> SoldierSpawnSystem::Spawn( core::ClientData& clientData )
{
    map::SpawnPoints_t spawnPoints( map::SoldierSpawnPointMapElementSystem::Get()->GetActiveSpawnPoints() );
    map::SpawnPoint spawnPoint( spawnPoints[RandomGenerator::global()() % spawnPoints.size()] );
    return Spawn( clientData, spawnPoint );
}

std::auto_ptr<Actor> SoldierSpawnSystem::Spawn( core::ClientData& clientData, map::SpawnPoint spawnPoint )
{
    std::auto_ptr<Actor> player( mActorFactory( mPlayerAutoId ) );
    return Spawn( clientData, spawnPoint, player );
}

std::auto_ptr<Actor> SoldierSpawnSystem::Spawn( core::ClientData& clientData, map::SpawnPoint spawnPoint, std::auto_ptr<Actor> player )
{
    Opt<Actor> clientActor( mScene.GetActor( clientData.mClientActorGUID ) );
    if( clientActor.IsValid() )
    {
        Opt<IHealthComponent> healthC = clientActor->Get<IHealthComponent>();
        if ( healthC.IsValid() && healthC->IsAlive() )
        {
            L1( "Cannot spawn soldier for clientData (%s) current soldier still alive!\n", clientData.mClientName.c_str() );
            return std::auto_ptr<Actor>();
        }
    }
    else
    {
        L2( "No actor for clientData(%s). (it might be an error on revive)\n", clientData.mClientName.c_str() );
    }
    L2( "player is valid %d", player.get() );
    Opt<IPositionComponent> positionC = player->Get<IPositionComponent>();
    L2( "positionC is valid %d", positionC.IsValid() );
    positionC->SetX( spawnPoint.mX );
    positionC->SetY( spawnPoint.mY );

    //TODO: temporary till normal inventory sync
    Opt<IInventoryComponent> inventoryC = player->Get<IInventoryComponent>();
    if ( inventoryC.IsValid() )
    {
        inventoryC->SetSelectedWeapon( AutoId( "pistol" ) );
    }

    Opt<PlayerControllerComponent> playerControllerC( player->Get<PlayerControllerComponent>() );
    if ( playerControllerC.IsValid() )
    {
        playerControllerC->mControllerId = clientData.mClientId;
        if ( mProgramState.mControlledActorGUID == clientData.mClientActorGUID
             && mProgramState.mMode != core::ProgramState::Server )
        {
            playerControllerC->SetEnabled( true );
            playerControllerC->mActive = true;
            mProgramState.mControlledActorGUID = player->GetGUID();
        }
    }
    clientData.mClientActorGUID = player->GetGUID(); //TODO: might seek for a better place
    L2( "player created clientId:%d clientName:%s actorId:%d\n", clientData.mClientId, clientData.mClientName.c_str(), clientData.mClientActorGUID );

    if ( mProgramState.mMode != core::ProgramState::Server &&
         mProgramState.mClientDatas.begin()->mClientActorGUID == player->GetGUID() )
    {
        Scene::Get().SetPlayerModels( Opt<Actor>( player.get() ) );
    }
    EventServer<SoldierCreatedEvent>::Get().SendEvent( SoldierCreatedEvent( clientData, Opt<Actor>( player.get() ) ) );
    return player;
}

} // namespace engine

<|endoftext|>


<commit_before>// Reference: VTK/Examples/VisualizationAlgorithms/Python/StreamlinesWithLineWidget.py

// Compatibility with Paraview
//#define vtkRenderingCore_AUTOINIT 4(vtkInteractionStyle,vtkRenderingFreeType,vtkRenderingFreeTypeOpenGL,vtkRenderingOpenGL)
//#define vtkRenderingVolume_AUTOINIT 1(vtkRenderingVolumeOpenGL)
// Compatibility with Paraview

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

#include <list>
#include <iterator>

#include "vtkDataSet.h"
#include "vtkSmartPointer.h"
#include "vtkLineSource.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkInteractorStyleTrackballCamera.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkActor.h"
#include "vtkPolyDataMapper.h"
#include "vtkOutlineFilter.h"
#include "vtkProperty.h"
#include <vtkXMLImageDataReader.h>
#include <vtkInterpolatedVelocityField.h>
#include <vtkImageData.h>
#include <vtkLineWidget.h>
#include <vtkCallbackCommand.h>
// streamline
#include "vtkStreamLine.h"

#include "vtkEddaReader.h"
#include "vtkSamplingArray.h"

using namespace std;

vtkLineWidget *lineWidget;
vtkRenderWindow *renWin;
vtkPolyData *seeds ;

vtkSmartPointer<vtkDataSet> getData(char *filename)
{
  vtkEddaReader *reader = vtkEddaReader::New();
  reader->SetFileName(filename);
  reader->Update();

  return reader->GetOutput();
}

void computeStreamlines(vtkObject* caller, unsigned long eventId, void *clientdata, void *calldata)
{
	double *point1 = lineWidget->GetPoint1();
	double *point2 = lineWidget->GetPoint2();
	printf("LineWidget Point1: %lf %lf %lf, Point2: %lf %lf %lf\n", point1[0], point1[1], point1[2], point2[0], point2[1], point2[2]);

	lineWidget->GetPolyData(seeds);
	renWin->Render();
}

int main(int argc, char **argv)
{
  // choose one of the following:
  //vtkSmartPointer<vtkDataSet> data = getData_plot3d();
  //vtkSmartPointer<vtkDataSet> data = getData_vts();
  vtkSmartPointer<vtkDataSet> data = getData(argv[1]);

  // rake
  lineWidget = vtkLineWidget::New();
  lineWidget->SetInputData(data);
  lineWidget->SetResolution(21); // 22 seeds along the line
  lineWidget->SetAlignToYAxis();
  lineWidget->PlaceWidget();
  lineWidget->ClampToBoundsOn();
  seeds = vtkPolyData::New();
  lineWidget->GetPolyData(seeds);

  // use vtkStreamLine
  vtkStreamLine *streamer = vtkStreamLine::New();
  streamer->SetInputData(data);
  streamer->SetSourceData(seeds);
  streamer->SetMaximumPropagationTime(10);
  streamer->SetIntegrationStepLength(.5);
  streamer->SetStepLength(.05);
  streamer->SetIntegrationDirectionToIntegrateBothDirections();
  streamer->VorticityOff();

  vtkPolyDataMapper *mapper = vtkPolyDataMapper::New();
  mapper->SetInputConnection(streamer->GetOutputPort());
  mapper->SetScalarRange(data->GetScalarRange());
  vtkActor *actor = vtkActor::New();
  actor->SetMapper(mapper);

  //
  // outline
  //
  vtkOutlineFilter *outline = vtkOutlineFilter::New();
  outline->SetInputData(data);

  vtkPolyDataMapper *outlineMapper = vtkPolyDataMapper::New();
  outlineMapper->SetInputConnection(outline->GetOutputPort());

  vtkActor *outlineActor = vtkActor::New();
  outlineActor->SetMapper(outlineMapper);
  outlineActor->GetProperty()->SetColor(0,0,0);

  //
  // renderer
  //
  vtkRenderer *ren = vtkRenderer::New();
  renWin = vtkRenderWindow::New();
  renWin->AddRenderer(ren);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);
  vtkInteractorStyleTrackballCamera *style = vtkInteractorStyleTrackballCamera::New();
  iren->SetInteractorStyle(style);

  // line widget interactor
  lineWidget->SetInteractor(iren);
  lineWidget->SetDefaultRenderer(ren);
  vtkCallbackCommand *callback = vtkCallbackCommand::New();
  callback->SetCallback(computeStreamlines);
  lineWidget->AddObserver(vtkCommand::EndInteractionEvent, callback);

  ren->AddActor(actor);
  ren->AddActor(outlineActor);
  ren->SetBackground(.5,.5,.5);

  renWin->SetSize(500,500);

  iren->Initialize();
  renWin->Render();
  iren->Start();

  return 0;
}

<commit_msg>UI of test_pipeline<commit_after>// Reference: VTK/Examples/VisualizationAlgorithms/Python/StreamlinesWithLineWidget.py

// Compatibility with Paraview
//#define vtkRenderingCore_AUTOINIT 4(vtkInteractionStyle,vtkRenderingFreeType,vtkRenderingFreeTypeOpenGL,vtkRenderingOpenGL)
//#define vtkRenderingVolume_AUTOINIT 1(vtkRenderingVolumeOpenGL)
// Compatibility with Paraview

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

#include <list>
#include <iterator>

#include "vtkDataSet.h"
#include "vtkSmartPointer.h"
#include "vtkLineSource.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkInteractorStyleTrackballCamera.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkActor.h"
#include "vtkPolyDataMapper.h"
#include "vtkOutlineFilter.h"
#include "vtkProperty.h"
#include <vtkXMLImageDataReader.h>
#include <vtkInterpolatedVelocityField.h>
#include <vtkImageData.h>
#include <vtkLineWidget.h>
#include <vtkCallbackCommand.h>
// streamline
#include "vtkStreamLine.h"

#include "vtkEddaReader.h"
#include "vtkSamplingArray.h"

using namespace std;

vtkLineWidget *lineWidget;
vtkRenderWindow *renWin;
vtkPolyData *seeds ;

vtkSmartPointer<vtkDataSet> getData(char *filename)
{
  vtkEddaReader *reader = vtkEddaReader::New();
  reader->SetFileName(filename);
  reader->Update();

  return reader->GetOutput();
}

void computeStreamlines(vtkObject* caller, unsigned long eventId, void *clientdata, void *calldata)
{
	double *point1 = lineWidget->GetPoint1();
	double *point2 = lineWidget->GetPoint2();
	printf("LineWidget Point1: %lf %lf %lf, Point2: %lf %lf %lf\n", point1[0], point1[1], point1[2], point2[0], point2[1], point2[2]);

	lineWidget->GetPolyData(seeds);
	renWin->Render();
}

int main(int argc, char **argv)
{
  // choose one of the following:
  //vtkSmartPointer<vtkDataSet> data = getData_plot3d();
  //vtkSmartPointer<vtkDataSet> data = getData_vts();
  vtkSmartPointer<vtkDataSet> data = getData(argv[1]);

  // rake
  lineWidget = vtkLineWidget::New();
  lineWidget->SetInputData(data);
  lineWidget->SetResolution(21); // 22 seeds along the line
  lineWidget->SetAlignToYAxis();
  lineWidget->PlaceWidget();
  lineWidget->ClampToBoundsOn();
  seeds = vtkPolyData::New();
  lineWidget->GetPolyData(seeds);

  // use vtkStreamLine
  vtkStreamLine *streamer = vtkStreamLine::New();
  streamer->SetInputData(data);
  streamer->SetSourceData(seeds);
  streamer->SetMaximumPropagationTime(10);
  streamer->SetIntegrationStepLength(.5);
  streamer->SetStepLength(.05);
  streamer->SetIntegrationDirectionToIntegrateBothDirections();
  streamer->VorticityOff();

  vtkPolyDataMapper *mapper = vtkPolyDataMapper::New();
  mapper->SetInputConnection(streamer->GetOutputPort());
  mapper->SetScalarRange(data->GetScalarRange());
  //mapper->SetScalarRange(0, 20); // for 20 seeds
  mapper->SetColorModeToMapScalars();
  vtkActor *actor = vtkActor::New();
  actor->SetMapper(mapper);

  //
  // outline
  //
  vtkOutlineFilter *outline = vtkOutlineFilter::New();
  outline->SetInputData(data);

  vtkPolyDataMapper *outlineMapper = vtkPolyDataMapper::New();
  outlineMapper->SetInputConnection(outline->GetOutputPort());

  vtkActor *outlineActor = vtkActor::New();
  outlineActor->SetMapper(outlineMapper);
  outlineActor->GetProperty()->SetColor(0,0,0);

  //
  // renderer
  //
  vtkRenderer *ren = vtkRenderer::New();
  renWin = vtkRenderWindow::New();
  renWin->AddRenderer(ren);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);
  vtkInteractorStyleTrackballCamera *style = vtkInteractorStyleTrackballCamera::New();
  iren->SetInteractorStyle(style);

  // line widget interactor
  lineWidget->SetInteractor(iren);
  lineWidget->SetDefaultRenderer(ren);
  vtkCallbackCommand *callback = vtkCallbackCommand::New();
  callback->SetCallback(computeStreamlines);
  lineWidget->AddObserver(vtkCommand::EndInteractionEvent, callback);

  ren->AddActor(actor);
  ren->AddActor(outlineActor);
  ren->SetBackground(.5,.5,.5);

  renWin->SetSize(500,500);

  iren->Initialize();

  // Sign up to receive TimerEvent
  iren->AddObserver(vtkCommand::TimerEvent, callback);
  int timerId = iren->CreateRepeatingTimer(100);

  renWin->Render();
  iren->Start();

  return 0;
}

<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkProgressAccumulator.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#include "itkProgressAccumulator.h"

namespace itk {

ProgressAccumulator
::ProgressAccumulator()
{
  m_MiniPipelineFilter = 0;

  // Initialize the progress values
  this->ResetProgress();

  // Create a member command
  m_CallbackCommand = CommandType::New();
  m_CallbackCommand->SetCallbackFunction( this, & Self::ReportProgress );
}

ProgressAccumulator
::~ProgressAccumulator()
{
  UnregisterAllFilters();
}

void
ProgressAccumulator
::RegisterInternalFilter(GenericFilterType *filter,float weight)
{
  // Observe the filter
  unsigned long progressTag =
    filter->AddObserver(ProgressEvent(), m_CallbackCommand);
  unsigned long iterationTag =
    filter->AddObserver(IterationEvent(), m_CallbackCommand);

  // Create a record for the filter
  struct FilterRecord record;
  record.Filter = filter;
  record.Weight = weight;
  record.ProgressObserverTag = progressTag;
  record.IterationObserverTag = iterationTag;
  record.Progress = 0.0f;

  // Add the record to the list
  m_FilterRecord.push_back(record);
}

void
ProgressAccumulator
::UnregisterAllFilters()
{
  // The filters should no longer be observing us
  FilterRecordVector::iterator it;
  for(it = m_FilterRecord.begin(); it != m_FilterRecord.end();++it)
    {
    it->Filter->RemoveObserver(it->ProgressObserverTag);
    it->Filter->RemoveObserver(it->IterationObserverTag);
    }

  // Clear the filter array
  m_FilterRecord.clear();

  // Reset the progress meter
  ResetProgress();
}

void
ProgressAccumulator
::ResetProgress()
{
  // Reset the accumulated progress
  m_AccumulatedProgress     = 0.0f;
  m_BaseAccumulatedProgress = 0.0f;

  // Reset each of the individial progress meters
  FilterRecordVector::iterator it;
  for(it = m_FilterRecord.begin();it != m_FilterRecord.end();++it)
    {
    it->Progress = 0.0f;
    it->Filter->SetProgress( 0.0f );
    }
}

void
ProgressAccumulator
::ResetFilterProgressAndKeepAccumulatedProgress()
{
  m_BaseAccumulatedProgress = m_AccumulatedProgress;
  // Reset each of the individial progress meters
  FilterRecordVector::iterator it;
  for(it = m_FilterRecord.begin();it != m_FilterRecord.end();++it)
    {
    it->Progress = 0.0f;
    it->Filter->SetProgress( 0.0f );
    }
}

void
ProgressAccumulator
::ReportProgress(Object *who, const EventObject &event)
{
  ProgressEvent  pe;
  IterationEvent ie;
  if( typeid( event ) == typeid( pe ) )
    {
    // Add up the progress from different filters
    m_AccumulatedProgress = m_BaseAccumulatedProgress;

    FilterRecordVector::iterator it;
    for(it = m_FilterRecord.begin();it != m_FilterRecord.end();++it)
      {
      m_AccumulatedProgress += it->Filter->GetProgress() * it->Weight;
      }

    // Update the progress of the client mini-pipeline filter
    m_MiniPipelineFilter->UpdateProgress(m_AccumulatedProgress);

    // check for abort
    if ( m_MiniPipelineFilter->GetAbortGenerateData() )
      {
      // Abort the filter that is reporting progress
      FilterRecordVector::iterator fit;
      for(fit = m_FilterRecord.begin();fit != m_FilterRecord.end();++it)
        {
        if (who == fit->Filter)
          {
          fit->Filter->AbortGenerateDataOn();
          }
        }
      }
    }
  else if (typeid( event ) == typeid ( ie ) )
    {
    }
}

void ProgressAccumulator
::PrintSelf(std::ostream &os, Indent indent) const
{
  Superclass::PrintSelf(os,indent);

  if (m_MiniPipelineFilter)
    {
    os << indent << m_MiniPipelineFilter << std::endl;
    }
  os << indent << m_AccumulatedProgress     << std::endl;
  os << indent << m_BaseAccumulatedProgress << std::endl;
}

} // End namespace itk
<commit_msg>BUG:  last checkin was incomplete.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkProgressAccumulator.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
#include "itkProgressAccumulator.h"

namespace itk {

ProgressAccumulator
::ProgressAccumulator()
{
  m_MiniPipelineFilter = 0;

  // Initialize the progress values
  this->ResetProgress();

  // Create a member command
  m_CallbackCommand = CommandType::New();
  m_CallbackCommand->SetCallbackFunction( this, & Self::ReportProgress );
}

ProgressAccumulator
::~ProgressAccumulator()
{
  UnregisterAllFilters();
}

void
ProgressAccumulator
::RegisterInternalFilter(GenericFilterType *filter,float weight)
{
  // Observe the filter
  unsigned long progressTag =
    filter->AddObserver(ProgressEvent(), m_CallbackCommand);
  unsigned long iterationTag =
    filter->AddObserver(IterationEvent(), m_CallbackCommand);

  // Create a record for the filter
  struct FilterRecord record;
  record.Filter = filter;
  record.Weight = weight;
  record.ProgressObserverTag = progressTag;
  record.IterationObserverTag = iterationTag;
  record.Progress = 0.0f;

  // Add the record to the list
  m_FilterRecord.push_back(record);
}

void
ProgressAccumulator
::UnregisterAllFilters()
{
  // The filters should no longer be observing us
  FilterRecordVector::iterator it;
  for(it = m_FilterRecord.begin(); it != m_FilterRecord.end();++it)
    {
    it->Filter->RemoveObserver(it->ProgressObserverTag);
    it->Filter->RemoveObserver(it->IterationObserverTag);
    }

  // Clear the filter array
  m_FilterRecord.clear();

  // Reset the progress meter
  ResetProgress();
}

void
ProgressAccumulator
::ResetProgress()
{
  // Reset the accumulated progress
  m_AccumulatedProgress     = 0.0f;
  m_BaseAccumulatedProgress = 0.0f;

  // Reset each of the individial progress meters
  FilterRecordVector::iterator it;
  for(it = m_FilterRecord.begin();it != m_FilterRecord.end();++it)
    {
    it->Progress = 0.0f;
    it->Filter->SetProgress( 0.0f );
    }
}

void
ProgressAccumulator
::ResetFilterProgressAndKeepAccumulatedProgress()
{
  m_BaseAccumulatedProgress = m_AccumulatedProgress;
  // Reset each of the individial progress meters
  FilterRecordVector::iterator it;
  for(it = m_FilterRecord.begin();it != m_FilterRecord.end();++it)
    {
    it->Progress = 0.0f;
    it->Filter->SetProgress( 0.0f );
    }
}

void
ProgressAccumulator
::ReportProgress(Object *who, const EventObject &event)
{
  ProgressEvent  pe;
  IterationEvent ie;
  if( typeid( event ) == typeid( pe ) )
    {
    // Add up the progress from different filters
    m_AccumulatedProgress = m_BaseAccumulatedProgress;

    FilterRecordVector::iterator it;
    for(it = m_FilterRecord.begin();it != m_FilterRecord.end();++it)
      {
      m_AccumulatedProgress += it->Filter->GetProgress() * it->Weight;
      }

    // Update the progress of the client mini-pipeline filter
    m_MiniPipelineFilter->UpdateProgress(m_AccumulatedProgress);

    // check for abort
    if ( m_MiniPipelineFilter->GetAbortGenerateData() )
      {
      // Abort the filter that is reporting progress
      FilterRecordVector::iterator fit;
      for(fit = m_FilterRecord.begin();fit != m_FilterRecord.end();++fit)
        {
        if (who == fit->Filter)
          {
          fit->Filter->AbortGenerateDataOn();
          }
        }
      }
    }
  else if (typeid( event ) == typeid ( ie ) )
    {
    }
}

void ProgressAccumulator
::PrintSelf(std::ostream &os, Indent indent) const
{
  Superclass::PrintSelf(os,indent);

  if (m_MiniPipelineFilter)
    {
    os << indent << m_MiniPipelineFilter << std::endl;
    }
  os << indent << m_AccumulatedProgress     << std::endl;
  os << indent << m_BaseAccumulatedProgress << std::endl;
}

} // End namespace itk
<|endoftext|>


<commit_before>/*
    Persons Model Example
    Copyright (C) 2012 Aleix Pol Gonzalez <aleixpol@blue-systems.com>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <QApplication>
#include <QTreeView>
#include <QSortFilterProxyModel>

#include <QVBoxLayout>
#include <QPushButton>

#include <QStyledItemDelegate>
#include <QPainter>

#include <personsmodel.h>
#include <personsmodelfeature.h>
#include <personmanager.h>

using namespace KPeople;

const int SPACING = 8;
const int PHOTO_SIZE = 32;

class PersonsDelegate : public QStyledItemDelegate
{
public:
    PersonsDelegate(QObject *parent = 0);
    ~PersonsDelegate();

    void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
    QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
};

PersonsDelegate::PersonsDelegate(QObject *parent)
:QStyledItemDelegate(parent)
{
}

PersonsDelegate::~PersonsDelegate()
{
}

void PersonsDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItemV4 optV4 = option;
    initStyleOption(&optV4, index);

    painter->save();

    painter->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);
    painter->setClipRect(optV4.rect);

    QStyle *style = QApplication::style();
    style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter);

    QRect contactPhotoRect = optV4.rect;
    contactPhotoRect.adjust(SPACING, SPACING, SPACING, SPACING);
    contactPhotoRect.setWidth(PHOTO_SIZE);
    contactPhotoRect.setHeight(PHOTO_SIZE);

    QImage avatar = index.data(Qt::DecorationRole).value<QImage>();
    painter->drawImage(contactPhotoRect, avatar);

    painter->drawRect(contactPhotoRect);

    QRect nameRect = optV4.rect;
    nameRect.adjust(SPACING + PHOTO_SIZE + SPACING, SPACING, 0, 0);

    painter->drawText(nameRect, index.data(Qt::DisplayRole).toString());

    QRect idRect = optV4.rect;
    idRect.adjust(SPACING + PHOTO_SIZE + SPACING, SPACING + 15, 0, 0);
    painter->drawText(idRect, index.data(PersonsModel::PersonIdRole).toString());

    painter->restore();
}

QSize PersonsDelegate::sizeHint (const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    return QSize(128, 48);
}

class ContactListApp : public QWidget
{
    Q_OBJECT
public:
    ContactListApp();
private Q_SLOTS:
    void onMergeClicked();
    void onUnmergeClicked();
private:
    PersonsModel *m_model;
    QTreeView *m_view;
};

ContactListApp::ContactListApp()
{
    m_view = new QTreeView(this);
    m_model = new PersonsModel(this);

    QVBoxLayout *layout = new QVBoxLayout(this);
    QSortFilterProxyModel *sortFilter = new QSortFilterProxyModel(m_view);
    sortFilter->setDynamicSortFilter(true);
    sortFilter->setSourceModel(m_model);
    sortFilter->sort(0);
    m_view->setRootIsDecorated(false);
    m_view->setModel(sortFilter);
    m_view->setItemDelegate(new PersonsDelegate(this));
    m_view->setSelectionMode(QAbstractItemView::MultiSelection);

    layout->addWidget(m_view);
    QPushButton *mergeButton = new QPushButton("Merge", this);
    connect(mergeButton, SIGNAL(released()), SLOT(onMergeClicked()));
    layout->addWidget(mergeButton);

    QPushButton *unmergeButton = new QPushButton("Unmerge", this);
    connect(unmergeButton, SIGNAL(released()), SLOT(onUnmergeClicked()));
    layout->addWidget(unmergeButton);
}

void ContactListApp::onMergeClicked()
{
    QModelIndexList indexes = m_view->selectionModel()->selectedIndexes();
    QStringList ids;
    Q_FOREACH(const QModelIndex &index, indexes) {
        ids << index.data(PersonsModel::PersonIdRole).toString();
    }

    if (!ids.isEmpty()) {
        PersonManager::instance()->mergeContacts(ids);
    }
}

void ContactListApp::onUnmergeClicked()
{
    QModelIndexList indexes = m_view->selectionModel()->selectedIndexes();
    if (indexes.size()) {
        QString id = indexes.first().data(PersonsModel::PersonIdRole).toString();
        PersonManager::instance()->unmergeContact(id);
    }
}

int main(int argc, char** argv)
{
    QApplication app(argc, argv);

    ContactListApp widget;
    widget.show();
    app.exec();
}

#include "contactlistwidgets.moc"
<commit_msg>Use less-annoying selection mode<commit_after>/*
    Persons Model Example
    Copyright (C) 2012 Aleix Pol Gonzalez <aleixpol@blue-systems.com>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <QApplication>
#include <QTreeView>
#include <QSortFilterProxyModel>

#include <QVBoxLayout>
#include <QPushButton>

#include <QStyledItemDelegate>
#include <QPainter>

#include <personsmodel.h>
#include <personsmodelfeature.h>
#include <personmanager.h>

using namespace KPeople;

const int SPACING = 8;
const int PHOTO_SIZE = 32;

class PersonsDelegate : public QStyledItemDelegate
{
public:
    PersonsDelegate(QObject *parent = 0);
    ~PersonsDelegate();

    void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
    QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const;
};

PersonsDelegate::PersonsDelegate(QObject *parent)
:QStyledItemDelegate(parent)
{
}

PersonsDelegate::~PersonsDelegate()
{
}

void PersonsDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItemV4 optV4 = option;
    initStyleOption(&optV4, index);

    painter->save();

    painter->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);
    painter->setClipRect(optV4.rect);

    QStyle *style = QApplication::style();
    style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter);

    QRect contactPhotoRect = optV4.rect;
    contactPhotoRect.adjust(SPACING, SPACING, SPACING, SPACING);
    contactPhotoRect.setWidth(PHOTO_SIZE);
    contactPhotoRect.setHeight(PHOTO_SIZE);

    QImage avatar = index.data(Qt::DecorationRole).value<QImage>();
    painter->drawImage(contactPhotoRect, avatar);

    painter->drawRect(contactPhotoRect);

    QRect nameRect = optV4.rect;
    nameRect.adjust(SPACING + PHOTO_SIZE + SPACING, SPACING, 0, 0);

    painter->drawText(nameRect, index.data(Qt::DisplayRole).toString());

    QRect idRect = optV4.rect;
    idRect.adjust(SPACING + PHOTO_SIZE + SPACING, SPACING + 15, 0, 0);
    painter->drawText(idRect, index.data(PersonsModel::PersonIdRole).toString());

    painter->restore();
}

QSize PersonsDelegate::sizeHint (const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    return QSize(128, 48);
}

class ContactListApp : public QWidget
{
    Q_OBJECT
public:
    ContactListApp();
private Q_SLOTS:
    void onMergeClicked();
    void onUnmergeClicked();
private:
    PersonsModel *m_model;
    QTreeView *m_view;
};

ContactListApp::ContactListApp()
{
    m_view = new QTreeView(this);
    m_model = new PersonsModel(this);

    QVBoxLayout *layout = new QVBoxLayout(this);
    QSortFilterProxyModel *sortFilter = new QSortFilterProxyModel(m_view);
    sortFilter->setDynamicSortFilter(true);
    sortFilter->setSourceModel(m_model);
    sortFilter->sort(0);
    m_view->setRootIsDecorated(false);
    m_view->setModel(sortFilter);
    m_view->setItemDelegate(new PersonsDelegate(this));
    m_view->setSelectionMode(QAbstractItemView::ExtendedSelection);

    layout->addWidget(m_view);
    QPushButton *mergeButton = new QPushButton("Merge", this);
    connect(mergeButton, SIGNAL(released()), SLOT(onMergeClicked()));
    layout->addWidget(mergeButton);

    QPushButton *unmergeButton = new QPushButton("Unmerge", this);
    connect(unmergeButton, SIGNAL(released()), SLOT(onUnmergeClicked()));
    layout->addWidget(unmergeButton);
}

void ContactListApp::onMergeClicked()
{
    QModelIndexList indexes = m_view->selectionModel()->selectedIndexes();
    QStringList ids;
    Q_FOREACH(const QModelIndex &index, indexes) {
        ids << index.data(PersonsModel::PersonIdRole).toString();
    }

    if (!ids.isEmpty()) {
        PersonManager::instance()->mergeContacts(ids);
    }
}

void ContactListApp::onUnmergeClicked()
{
    QModelIndexList indexes = m_view->selectionModel()->selectedIndexes();
    if (indexes.size()) {
        QString id = indexes.first().data(PersonsModel::PersonIdRole).toString();
        PersonManager::instance()->unmergeContact(id);
    }
}

int main(int argc, char** argv)
{
    QApplication app(argc, argv);

    ContactListApp widget;
    widget.show();
    app.exec();
}

#include "contactlistwidgets.moc"
<|endoftext|>


<commit_before>// g++ serial.c++ -lboost_system -lws2_32 -D _WIN32_WINNT=0x0501

#include <iostream>
#include "SimpleSerial.h"

using namespace std;
using namespace boost;

int main(int argc, char* argv[])
{

	string inputstr;
	cout << "Lab 5 Code Started" << endl;

	/*When you are dealing with IO devices, it is very important that calls to them be wrapped
	 * in 'try-catch' blocks. These blocks of code tell the program 'if something goes
	 * wrong (an exception) run whatever is in catch rather than simply killing the program.
	*/
    try {

		// Make a SimpleSerial object with the parameter for your Wunderboard/OS
    	SimpleSerial comm("/dev/ttyUSB0", 9600);
		// Start reading data from your wunderboard and displaying it to the screen.
    	while(1){
    		cout << comm.readLine() << endl;
    	}
		// Check if there is input to be read from the keyboard

		// If there is THEN read it, otherwise ignore the keyboard
		// If you just read data at it is 'EXIT' return from the program

    } catch(boost::system::system_error& e)
    {
        cout<<"Error: "<<e.what()<<endl;
        return 1;
    }
}
<commit_msg>got lab5 terminal stuff working as per email<commit_after>// g++ serial.c++ -lboost_system -lws2_32 -D _WIN32_WINNT=0x0501

#include <iostream>
#include "SimpleSerial.h"

using namespace std;
using namespace boost;

int main(int argc, char* argv[])
{

	string inputstr;
	cout << "Lab 5 Code Started" << endl;

	/*When you are dealing with IO devices, it is very important that calls to them be wrapped
	 * in 'try-catch' blocks. These blocks of code tell the program 'if something goes
	 * wrong (an exception) run whatever is in catch rather than simply killing the program.
	*/
    try {

		// Make a SimpleSerial object with the parameter for your Wunderboard/OS
    	SimpleSerial comm("/dev/ttyUSB0", 9600);
		// Start reading data from your wunderboard and displaying it to the screen.
    	while(1){
    		inputstr = comm.readLine();
    		cout << inputstr << endl;
    		if (!inputstr.compare("50") || !inputstr.compare("0")){
    			cout << "Please press 's' to continue or 'EXIT'" << endl;
    			cin >> inputstr;
    			if (!inputstr.compare("s")){
    				comm.writeString("s");
    			} else if (!inputstr.compare("EXIT")){
    				break;
    			} else {
    				cout << "Error! invalid input. try again!" << endl;
    			}
    		}
    	}
		// Check if there is input to be read from the keyboard

		// If there is THEN read it, otherwise ignore the keyboard
		// If you just read data at it is 'EXIT' return from the program

    } catch(boost::system::system_error& e)
    {
        cout<<"Error: "<<e.what()<<endl;
        return 1;
    }
}
<|endoftext|>