<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/c/eager/gradient_checker.h"

#include <memory>

#include "absl/types/span.h"
#include "tensorflow/c/eager/abstract_tensor_handle.h"
#include "tensorflow/c/eager/c_api_unified_experimental.h"
#include "tensorflow/c/eager/unified_api_testutil.h"
#include "tensorflow/c/experimental/ops/math_ops.h"
#include "tensorflow/c/tf_status_helper.h"
#include "tensorflow/c/tf_tensor.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace gradients {
namespace internal {
namespace {

using tensorflow::TF_StatusPtr;

void CompareNumericalAndManualGradients(
    Model model, AbstractContext* ctx,
    absl::Span<AbstractTensorHandle* const> inputs, int input_index,
    float* expected_grad, int num_grad, bool use_function,
    double abs_error = 1e-2) {
  AbstractTensorHandle* numerical_grad;
  Status s = CalcNumericalGrad(ctx, model, inputs, input_index, use_function,
                               &numerical_grad);
  ASSERT_EQ(errors::OK, s.code()) << s.error_message();

  TF_Tensor* numerical_tensor;
  s = GetValue(numerical_grad, &numerical_tensor);
  ASSERT_EQ(errors::OK, s.code()) << s.error_message();
  auto num_elem_numerical = TF_TensorElementCount(numerical_tensor);
  ASSERT_EQ(num_elem_numerical, num_grad);

  float* dnumerical = new float[num_elem_numerical]{0};
  memcpy(&dnumerical[0], TF_TensorData(numerical_tensor),
         TF_TensorByteSize(numerical_tensor));

  for (int j = 0; j < num_grad; j++) {
    ASSERT_NEAR(dnumerical[j], expected_grad[j], abs_error);
  }
  delete dnumerical;
  TF_DeleteTensor(numerical_tensor);
}

Status MatMulModel(AbstractContext* ctx,
                   absl::Span<AbstractTensorHandle* const> inputs,
                   absl::Span<AbstractTensorHandle*> outputs) {
  return ops::MatMul(ctx, inputs, outputs, "MatMul",
                     /*transpose_a=*/false,
                     /*transpose_b=*/false);
}

Status MulModel(AbstractContext* ctx,
                absl::Span<AbstractTensorHandle* const> inputs,
                absl::Span<AbstractTensorHandle*> outputs) {
  return ops::Mul(ctx, inputs, outputs, "Mul");
}

// TODO(vnvo2409): Add more tests from `python/ops/gradient_checker_v2_test.py`.
// These tests should not be confused with `[*]_grad_test` which compare the
// result of `gradient_checker` and `[*]_grad`. The tests here test the
// functionality of `gradient_checker` by comparing the result with expected
// manual user-provided gradients.
class GradientCheckerTest
    : public ::testing::TestWithParam<std::tuple<const char*, bool, bool>> {
 protected:
  void SetUp() override {
    TF_StatusPtr status(TF_NewStatus());
    TF_SetTracingImplementation(std::get<0>(GetParam()), status.get());
    Status s = StatusFromTF_Status(status.get());
    CHECK_EQ(errors::OK, s.code()) << s.error_message();

    {
      AbstractContext* ctx_raw = nullptr;
      Status s =
          BuildImmediateExecutionContext(std::get<1>(GetParam()), &ctx_raw);
      ASSERT_EQ(errors::OK, s.code()) << s.error_message();
      ctx_.reset(ctx_raw);
    }
  }

  AbstractContextPtr ctx_;

 public:
  bool UseMlir() const { return strcmp(std::get<0>(GetParam()), "mlir") == 0; }
  bool UseFunction() const { return std::get<2>(GetParam()); }
};

TEST_P(GradientCheckerTest, TestMatMul) {
  float A_vals[] = {1.0f, 2.0f, 3.0f, 4.0f};
  int64_t A_dims[] = {2, 2};
  AbstractTensorHandlePtr A;
  {
    AbstractTensorHandle* A_raw;
    Status s =
        TestTensorHandleWithDimsFloat(ctx_.get(), A_vals, A_dims, 2, &A_raw);
    ASSERT_EQ(errors::OK, s.code()) << s.error_message();
    A.reset(A_raw);
  }
  float B_vals[] = {.5f, -1.0f, 1.0f, 1.0f};
  int64_t B_dims[] = {2, 2};
  AbstractTensorHandlePtr B;
  {
    AbstractTensorHandle* B_raw;
    Status s =
        TestTensorHandleWithDimsFloat(ctx_.get(), B_vals, B_dims, 2, &B_raw);
    ASSERT_EQ(errors::OK, s.code()) << s.error_message();
    B.reset(B_raw);
  }

  float expected_dA[4] = {-.5f, 2.0f, -.5f, 2.0f};
  ASSERT_NO_FATAL_FAILURE(CompareNumericalAndManualGradients(
      MatMulModel, ctx_.get(), {A.get(), B.get()}, 0, expected_dA, 4,
      UseFunction()));
}

TEST_P(GradientCheckerTest, TestMul) {
  AbstractTensorHandlePtr x;
  {
    AbstractTensorHandle* x_raw = nullptr;
    Status s = TestScalarTensorHandle(ctx_.get(), 2.0f, &x_raw);
    ASSERT_EQ(errors::OK, s.code()) << s.error_message();
    x.reset(x_raw);
  }

  AbstractTensorHandlePtr y;
  {
    AbstractTensorHandle* y_raw = nullptr;
    Status s = TestScalarTensorHandle(ctx_.get(), 7.0f, &y_raw);
    ASSERT_EQ(errors::OK, s.code()) << s.error_message();
    y.reset(y_raw);
  }

  float expected_dx[1] = {7.0f};
  ASSERT_NO_FATAL_FAILURE(CompareNumericalAndManualGradients(
      MulModel, ctx_.get(), {x.get(), y.get()}, 0, expected_dx, 1,
      UseFunction()));
}

#ifdef PLATFORM_GOOGLE
INSTANTIATE_TEST_SUITE_P(
    UnifiedCAPI, GradientCheckerTest,
    ::testing::Combine(::testing::Values("graphdef"),
                       /*tfrt*/ ::testing::Values(false),
                       /*use_function*/ ::testing::Values(true, false)));
#else
INSTANTIATE_TEST_SUITE_P(
    UnifiedCAPI, GradientCheckerTest,
    ::testing::Combine(::testing::Values("graphdef"),
                       /*tfrt*/ ::testing::Values(false),
                       /*use_function*/ ::testing::Values(true, false)));
#endif
}  // namespace
}  // namespace internal
}  // namespace gradients
}  // namespace tensorflow
<commit_msg>use `delete[]` instead of `delete`<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/c/eager/gradient_checker.h"

#include <memory>

#include "absl/types/span.h"
#include "tensorflow/c/eager/abstract_tensor_handle.h"
#include "tensorflow/c/eager/c_api_unified_experimental.h"
#include "tensorflow/c/eager/unified_api_testutil.h"
#include "tensorflow/c/experimental/ops/math_ops.h"
#include "tensorflow/c/tf_status_helper.h"
#include "tensorflow/c/tf_tensor.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace gradients {
namespace internal {
namespace {

using tensorflow::TF_StatusPtr;

void CompareNumericalAndManualGradients(
    Model model, AbstractContext* ctx,
    absl::Span<AbstractTensorHandle* const> inputs, int input_index,
    float* expected_grad, int num_grad, bool use_function,
    double abs_error = 1e-2) {
  AbstractTensorHandle* numerical_grad;
  Status s = CalcNumericalGrad(ctx, model, inputs, input_index, use_function,
                               &numerical_grad);
  ASSERT_EQ(errors::OK, s.code()) << s.error_message();

  TF_Tensor* numerical_tensor;
  s = GetValue(numerical_grad, &numerical_tensor);
  ASSERT_EQ(errors::OK, s.code()) << s.error_message();
  auto num_elem_numerical = TF_TensorElementCount(numerical_tensor);
  ASSERT_EQ(num_elem_numerical, num_grad);

  float* dnumerical = new float[num_elem_numerical]{0};
  memcpy(&dnumerical[0], TF_TensorData(numerical_tensor),
         TF_TensorByteSize(numerical_tensor));

  for (int j = 0; j < num_grad; j++) {
    ASSERT_NEAR(dnumerical[j], expected_grad[j], abs_error);
  }
  delete[] dnumerical;
  TF_DeleteTensor(numerical_tensor);
}

Status MatMulModel(AbstractContext* ctx,
                   absl::Span<AbstractTensorHandle* const> inputs,
                   absl::Span<AbstractTensorHandle*> outputs) {
  return ops::MatMul(ctx, inputs, outputs, "MatMul",
                     /*transpose_a=*/false,
                     /*transpose_b=*/false);
}

Status MulModel(AbstractContext* ctx,
                absl::Span<AbstractTensorHandle* const> inputs,
                absl::Span<AbstractTensorHandle*> outputs) {
  return ops::Mul(ctx, inputs, outputs, "Mul");
}

// TODO(vnvo2409): Add more tests from `python/ops/gradient_checker_v2_test.py`.
// These tests should not be confused with `[*]_grad_test` which compare the
// result of `gradient_checker` and `[*]_grad`. The tests here test the
// functionality of `gradient_checker` by comparing the result with expected
// manual user-provided gradients.
class GradientCheckerTest
    : public ::testing::TestWithParam<std::tuple<const char*, bool, bool>> {
 protected:
  void SetUp() override {
    TF_StatusPtr status(TF_NewStatus());
    TF_SetTracingImplementation(std::get<0>(GetParam()), status.get());
    Status s = StatusFromTF_Status(status.get());
    CHECK_EQ(errors::OK, s.code()) << s.error_message();

    {
      AbstractContext* ctx_raw = nullptr;
      Status s =
          BuildImmediateExecutionContext(std::get<1>(GetParam()), &ctx_raw);
      ASSERT_EQ(errors::OK, s.code()) << s.error_message();
      ctx_.reset(ctx_raw);
    }
  }

  AbstractContextPtr ctx_;

 public:
  bool UseMlir() const { return strcmp(std::get<0>(GetParam()), "mlir") == 0; }
  bool UseFunction() const { return std::get<2>(GetParam()); }
};

TEST_P(GradientCheckerTest, TestMatMul) {
  float A_vals[] = {1.0f, 2.0f, 3.0f, 4.0f};
  int64_t A_dims[] = {2, 2};
  AbstractTensorHandlePtr A;
  {
    AbstractTensorHandle* A_raw;
    Status s =
        TestTensorHandleWithDimsFloat(ctx_.get(), A_vals, A_dims, 2, &A_raw);
    ASSERT_EQ(errors::OK, s.code()) << s.error_message();
    A.reset(A_raw);
  }
  float B_vals[] = {.5f, -1.0f, 1.0f, 1.0f};
  int64_t B_dims[] = {2, 2};
  AbstractTensorHandlePtr B;
  {
    AbstractTensorHandle* B_raw;
    Status s =
        TestTensorHandleWithDimsFloat(ctx_.get(), B_vals, B_dims, 2, &B_raw);
    ASSERT_EQ(errors::OK, s.code()) << s.error_message();
    B.reset(B_raw);
  }

  float expected_dA[4] = {-.5f, 2.0f, -.5f, 2.0f};
  ASSERT_NO_FATAL_FAILURE(CompareNumericalAndManualGradients(
      MatMulModel, ctx_.get(), {A.get(), B.get()}, 0, expected_dA, 4,
      UseFunction()));
}

TEST_P(GradientCheckerTest, TestMul) {
  AbstractTensorHandlePtr x;
  {
    AbstractTensorHandle* x_raw = nullptr;
    Status s = TestScalarTensorHandle(ctx_.get(), 2.0f, &x_raw);
    ASSERT_EQ(errors::OK, s.code()) << s.error_message();
    x.reset(x_raw);
  }

  AbstractTensorHandlePtr y;
  {
    AbstractTensorHandle* y_raw = nullptr;
    Status s = TestScalarTensorHandle(ctx_.get(), 7.0f, &y_raw);
    ASSERT_EQ(errors::OK, s.code()) << s.error_message();
    y.reset(y_raw);
  }

  float expected_dx[1] = {7.0f};
  ASSERT_NO_FATAL_FAILURE(CompareNumericalAndManualGradients(
      MulModel, ctx_.get(), {x.get(), y.get()}, 0, expected_dx, 1,
      UseFunction()));
}

#ifdef PLATFORM_GOOGLE
INSTANTIATE_TEST_SUITE_P(
    UnifiedCAPI, GradientCheckerTest,
    ::testing::Combine(::testing::Values("graphdef"),
                       /*tfrt*/ ::testing::Values(false),
                       /*use_function*/ ::testing::Values(true, false)));
#else
INSTANTIATE_TEST_SUITE_P(
    UnifiedCAPI, GradientCheckerTest,
    ::testing::Combine(::testing::Values("graphdef"),
                       /*tfrt*/ ::testing::Values(false),
                       /*use_function*/ ::testing::Values(true, false)));
#endif
}  // namespace
}  // namespace internal
}  // namespace gradients
}  // namespace tensorflow
<|endoftext|>


<commit_before>/* Copyright 2016 Carnegie Mellon University, NVIDIA Corporation
 *
 * 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 "scanner/evaluators/video/decoder_evaluator.h"
#include "scanner/evaluators/serialize.h"
#include "scanner/metadata.pb.h"

#include "scanner/util/memory.h"

namespace scanner {

DecoderEvaluator::DecoderEvaluator(const EvaluatorConfig& config,
                                   DeviceType device_type,
                                   VideoDecoderType decoder_type,
                                   i32 num_devices)
    : device_type_(device_type),
      device_id_(config.device_ids[0]),
      decoder_type_(decoder_type),
      num_devices_(num_devices) {
}

void DecoderEvaluator::configure(const BatchConfig& config) {
  reset();
  config_ = config;
  for (const InputFormat& m : config.formats) {
    frame_sizes_.push_back(m.width() * m.height() * 3);
  }
  for (size_t i = 0; i < config.formats.size(); ++i) {
    if (decoders_.size() <= i) {
      VideoDecoder* decoder = VideoDecoder::make_from_config(
          device_type_, device_id_, decoder_type_, device_type_, num_devices_);
      assert(decoder);
      decoders_.emplace_back(decoder);
    }
    decoders_[i]->configure(config.formats[i]);
  }
  i32 out_col_idx = 0;
  video_column_idxs_.clear();
  regular_column_idxs_.clear();
  for (size_t i = 0; i < config.input_columns.size(); ++i) {
    if (config.input_columns[i] == base_column_name()) {
      video_column_idxs_.push_back(
          std::make_tuple(static_cast<i32>(i), out_col_idx++));
    } else if (config.input_columns[i] != base_column_args_name()) {
      regular_column_idxs_.push_back(
          std::make_tuple(static_cast<i32>(i), out_col_idx++));
    }
  }
  cached_video_.resize(0);
  cached_video_.resize(video_column_idxs_.size());
  discontinuity_.resize(0);
  discontinuity_.resize(video_column_idxs_.size());
}

void DecoderEvaluator::reset() {

  for (size_t i = 0; i < video_column_idxs_.size(); ++i) {
    VideoDecoder* decoder = decoders_[i].get();
    if (decoder->decoded_frames_buffered() > 0) {
      while (decoder->discard_frame()) {
      };
    }

    CachedEncodedVideo& cache = cached_video_[i];
    if (cache.encoded_buffer) {
      delete[] cache.encoded_buffer;
    }
    cache.encoded_buffer = nullptr;
    cache.encoded_buffer_size = 0;
    cache.current_start_keyframe = -1;
    cache.current_end_keyframe = -1;
    cache.encoded_buffer_offset = 0;
    cache.current_frame = -1;
    discontinuity_[i] = true;
  }
}

void DecoderEvaluator::evaluate(const BatchedColumns& input_columns,
                                BatchedColumns& output_columns) {
  assert(input_columns.size() ==
         video_column_idxs_.size() * 2 + regular_column_idxs_.size());

  auto start = now();

  i64 total_frames_decoded = 0;
  i64 total_frames_used = 0;

  i32 video_num = 0;
  for (std::tuple<i32, i32> idxs : video_column_idxs_) {
    assert(video_num < frame_sizes_.size());
    size_t frame_size = frame_sizes_.at(video_num);
    VideoDecoder* decoder = decoders_.at(video_num).get();
    i64 frames_passed = 0;

    i32 col_idx;
    i32 out_col_idx;
    std::tie(col_idx, out_col_idx) = idxs;

    const Column& frame_col = input_columns[col_idx];
    const Column& args_col = input_columns[col_idx + 1];
    size_t num_inputs = frame_col.rows.size();

    // We cache the encoded video because work items in an io item
    // expect previous rows to have given the encoded buffer
    CachedEncodedVideo& cache = cached_video_[video_num];
    size_t current_input = 0;
    while (current_input < num_inputs) {
      const u8*& encoded_buffer = cache.encoded_buffer;
      size_t& encoded_buffer_size = cache.encoded_buffer_size;
      i64& current_start_keyframe = cache.current_start_keyframe;
      i64& current_end_keyframe = cache.current_end_keyframe;
      std::vector<i64> valid_frames;

      bool clear_cache = false;
      for (; current_input < num_inputs; current_input++) {
        const u8* in_encoded_buffer = frame_col.rows[current_input].buffer;
        size_t in_encoded_buffer_size = frame_col.rows[current_input].size;

        u8* decode_args_buffer = args_col.rows[current_input].buffer;
        size_t decode_args_buffer_size = args_col.rows[current_input].size;

        DecodeArgs args;
        if (device_type_ == DeviceType::GPU) {
#ifdef HAVE_CUDA
          u8* buffer = new u8[decode_args_buffer_size];
          memcpy_buffer(buffer, CPU_DEVICE, decode_args_buffer,
                        {DeviceType::GPU, device_id_}, decode_args_buffer_size);
          args = deserialize_decode_args(buffer, decode_args_buffer_size);
          delete[] buffer;

#else
          LOG(FATAL) << "Not built with cuda support!";
#endif
        } else {
          args = deserialize_decode_args(decode_args_buffer,
                                         decode_args_buffer_size);
        }

        if (current_start_keyframe == -1) {
          current_start_keyframe = args.start_keyframe();
          current_end_keyframe = args.end_keyframe();
        }
        if (args.start_keyframe() == current_start_keyframe &&
            args.end_keyframe() == current_end_keyframe) {
          valid_frames.push_back(args.valid_frame());
        } else {
          clear_cache = true;
          break;
        }

        // Get the video buffer
        if (encoded_buffer == nullptr) {
          if (device_type_ == DeviceType::GPU) {
#ifdef HAVE_CUDA
            u8* buffer = new u8[in_encoded_buffer_size];
            memcpy_buffer(buffer, CPU_DEVICE, in_encoded_buffer,
                          {DeviceType::GPU, device_id_},
                          in_encoded_buffer_size);
            encoded_buffer = buffer;
#else
            LOG(FATAL) << "Not built with cuda support!";
#endif
          } else {
            // Need to copy because we cache it
            u8* buffer = new u8[in_encoded_buffer_size];
            memcpy_buffer(buffer, CPU_DEVICE, in_encoded_buffer, CPU_DEVICE,
                          in_encoded_buffer_size);
            encoded_buffer = buffer;
          }
          encoded_buffer_size = in_encoded_buffer_size;
        }
      }

      i32 total_output_frames = static_cast<i32>(valid_frames.size());
      size_t& encoded_buffer_offset = cache.encoded_buffer_offset;
      i32& current_frame = cache.current_frame;
      // May have switched buffer since last evaluation
      if (total_output_frames > 0) {
        u8* output_block = new_block_buffer({device_type_, device_id_},
                                            total_output_frames * frame_size,
                                            total_output_frames);

        if (current_frame == -1) {
          current_frame = cache.current_start_keyframe;
        }
        i32 valid_index = 0;
        while (valid_index < total_output_frames) {
          auto video_start = now();

          if (decoder->decoded_frames_buffered() > 0) {
            // New frames
            bool more_frames = true;
            while (more_frames && valid_index < total_output_frames) {
              if (current_frame == valid_frames[valid_index]) {
                u8* decoded_buffer = output_block + valid_index * frame_size;
                more_frames = decoder->get_frame(decoded_buffer, frame_size);
                output_columns[out_col_idx].rows.push_back(
                    Row{decoded_buffer, frame_size});
                valid_index++;
                total_frames_used++;
              } else {
                more_frames = decoder->discard_frame();
              }
              current_frame++;
              total_frames_decoded++;
            }
            continue;
          }

          i32 encoded_packet_size = 0;
          const u8* encoded_packet = NULL;
          if (encoded_buffer_offset < encoded_buffer_size) {
            encoded_packet_size = *reinterpret_cast<const i32*>(
                encoded_buffer + encoded_buffer_offset);
            encoded_buffer_offset += sizeof(i32);
            encoded_packet = encoded_buffer + encoded_buffer_offset;
            encoded_buffer_offset += encoded_packet_size;
          }
          printf("current frame %d, packet size %lu, size %lu, offset %lu\n",
                 current_frame, encoded_packet_size, encoded_buffer_size,
                 encoded_buffer_offset);

          decoder->feed(encoded_packet, encoded_packet_size,
                        discontinuity_[video_num]);
          // Set a discontinuity if we sent an empty packet to reset
          // the stream next time
          discontinuity_[video_num] = (encoded_packet_size == 0);
        }
        // Wait on all memcpys from frames to be done
        decoder->wait_until_frames_copied();
      }

      if (clear_cache) {
        // HACK(apoms): just always force discontinuity for now instead of
        //  properly figuring out if the previous frame was abut
        discontinuity_[video_num] = true;

        delete[] encoded_buffer;
        encoded_buffer = nullptr;
        encoded_buffer_size = 0;
        current_start_keyframe = -1;
        current_end_keyframe = -1;
        encoded_buffer_offset = 0;
        current_frame = -1;
      }
    }
    video_num++;
  }

  // Forward all inputs
  for (std::tuple<i32, i32> idxs : regular_column_idxs_) {
    i32 col_idx;
    i32 out_col_idx;
    std::tie(col_idx, out_col_idx) = idxs;

    output_columns[out_col_idx].rows.insert(
        output_columns[out_col_idx].rows.end(),
        input_columns[col_idx].rows.begin(), input_columns[col_idx].rows.end());
    }

    if (profiler_) {
      profiler_->add_interval("decode", start, now());
      profiler_->increment("effective_frames", total_frames_used);
      profiler_->increment("decoded_frames", total_frames_decoded);
    }
  }

  DecoderEvaluatorFactory::DecoderEvaluatorFactory(
      DeviceType device_type, VideoDecoderType decoder_type)
      : device_type_(device_type), decoder_type_(decoder_type) {
    num_devices_ = device_type_ == DeviceType::GPU ? 1 : 8;
  }

  EvaluatorCapabilities DecoderEvaluatorFactory::get_capabilities() {
    EvaluatorCapabilities caps;
    caps.device_type = device_type_;
    caps.max_devices = num_devices_;
    caps.warmup_size = 0;
    caps.can_overlap = true;
    return caps;
  }

  std::vector<std::string> DecoderEvaluatorFactory::get_output_columns(
      const std::vector<std::string>& input_columns) {
    std::vector<std::string> output_columns;
    for (const std::string& col : input_columns) {
      if (col != base_column_args_name()) {
        output_columns.push_back(col);
      }
    }
    return output_columns;
  }

  Evaluator* DecoderEvaluatorFactory::new_evaluator(
      const EvaluatorConfig& config) {
    return new DecoderEvaluator(config, device_type_, decoder_type_,
                                num_devices_);
  }
}
<commit_msg>Remove extraneous print<commit_after>/* Copyright 2016 Carnegie Mellon University, NVIDIA Corporation
 *
 * 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 "scanner/evaluators/video/decoder_evaluator.h"
#include "scanner/evaluators/serialize.h"
#include "scanner/metadata.pb.h"

#include "scanner/util/memory.h"

namespace scanner {

DecoderEvaluator::DecoderEvaluator(const EvaluatorConfig& config,
                                   DeviceType device_type,
                                   VideoDecoderType decoder_type,
                                   i32 num_devices)
    : device_type_(device_type),
      device_id_(config.device_ids[0]),
      decoder_type_(decoder_type),
      num_devices_(num_devices) {
}

void DecoderEvaluator::configure(const BatchConfig& config) {
  reset();
  config_ = config;
  for (const InputFormat& m : config.formats) {
    frame_sizes_.push_back(m.width() * m.height() * 3);
  }
  for (size_t i = 0; i < config.formats.size(); ++i) {
    if (decoders_.size() <= i) {
      VideoDecoder* decoder = VideoDecoder::make_from_config(
          device_type_, device_id_, decoder_type_, device_type_, num_devices_);
      assert(decoder);
      decoders_.emplace_back(decoder);
    }
    decoders_[i]->configure(config.formats[i]);
  }
  i32 out_col_idx = 0;
  video_column_idxs_.clear();
  regular_column_idxs_.clear();
  for (size_t i = 0; i < config.input_columns.size(); ++i) {
    if (config.input_columns[i] == base_column_name()) {
      video_column_idxs_.push_back(
          std::make_tuple(static_cast<i32>(i), out_col_idx++));
    } else if (config.input_columns[i] != base_column_args_name()) {
      regular_column_idxs_.push_back(
          std::make_tuple(static_cast<i32>(i), out_col_idx++));
    }
  }
  cached_video_.resize(0);
  cached_video_.resize(video_column_idxs_.size());
  discontinuity_.resize(0);
  discontinuity_.resize(video_column_idxs_.size());
}

void DecoderEvaluator::reset() {

  for (size_t i = 0; i < video_column_idxs_.size(); ++i) {
    VideoDecoder* decoder = decoders_[i].get();
    if (decoder->decoded_frames_buffered() > 0) {
      while (decoder->discard_frame()) {
      };
    }

    CachedEncodedVideo& cache = cached_video_[i];
    if (cache.encoded_buffer) {
      delete[] cache.encoded_buffer;
    }
    cache.encoded_buffer = nullptr;
    cache.encoded_buffer_size = 0;
    cache.current_start_keyframe = -1;
    cache.current_end_keyframe = -1;
    cache.encoded_buffer_offset = 0;
    cache.current_frame = -1;
    discontinuity_[i] = true;
  }
}

void DecoderEvaluator::evaluate(const BatchedColumns& input_columns,
                                BatchedColumns& output_columns) {
  assert(input_columns.size() ==
         video_column_idxs_.size() * 2 + regular_column_idxs_.size());

  auto start = now();

  i64 total_frames_decoded = 0;
  i64 total_frames_used = 0;

  i32 video_num = 0;
  for (std::tuple<i32, i32> idxs : video_column_idxs_) {
    assert(video_num < frame_sizes_.size());
    size_t frame_size = frame_sizes_.at(video_num);
    VideoDecoder* decoder = decoders_.at(video_num).get();
    i64 frames_passed = 0;

    i32 col_idx;
    i32 out_col_idx;
    std::tie(col_idx, out_col_idx) = idxs;

    const Column& frame_col = input_columns[col_idx];
    const Column& args_col = input_columns[col_idx + 1];
    size_t num_inputs = frame_col.rows.size();

    // We cache the encoded video because work items in an io item
    // expect previous rows to have given the encoded buffer
    CachedEncodedVideo& cache = cached_video_[video_num];
    size_t current_input = 0;
    while (current_input < num_inputs) {
      const u8*& encoded_buffer = cache.encoded_buffer;
      size_t& encoded_buffer_size = cache.encoded_buffer_size;
      i64& current_start_keyframe = cache.current_start_keyframe;
      i64& current_end_keyframe = cache.current_end_keyframe;
      std::vector<i64> valid_frames;

      bool clear_cache = false;
      for (; current_input < num_inputs; current_input++) {
        const u8* in_encoded_buffer = frame_col.rows[current_input].buffer;
        size_t in_encoded_buffer_size = frame_col.rows[current_input].size;

        u8* decode_args_buffer = args_col.rows[current_input].buffer;
        size_t decode_args_buffer_size = args_col.rows[current_input].size;

        DecodeArgs args;
        if (device_type_ == DeviceType::GPU) {
#ifdef HAVE_CUDA
          u8* buffer = new u8[decode_args_buffer_size];
          memcpy_buffer(buffer, CPU_DEVICE, decode_args_buffer,
                        {DeviceType::GPU, device_id_}, decode_args_buffer_size);
          args = deserialize_decode_args(buffer, decode_args_buffer_size);
          delete[] buffer;

#else
          LOG(FATAL) << "Not built with cuda support!";
#endif
        } else {
          args = deserialize_decode_args(decode_args_buffer,
                                         decode_args_buffer_size);
        }

        if (current_start_keyframe == -1) {
          current_start_keyframe = args.start_keyframe();
          current_end_keyframe = args.end_keyframe();
        }
        if (args.start_keyframe() == current_start_keyframe &&
            args.end_keyframe() == current_end_keyframe) {
          valid_frames.push_back(args.valid_frame());
        } else {
          clear_cache = true;
          break;
        }

        // Get the video buffer
        if (encoded_buffer == nullptr) {
          if (device_type_ == DeviceType::GPU) {
#ifdef HAVE_CUDA
            u8* buffer = new u8[in_encoded_buffer_size];
            memcpy_buffer(buffer, CPU_DEVICE, in_encoded_buffer,
                          {DeviceType::GPU, device_id_},
                          in_encoded_buffer_size);
            encoded_buffer = buffer;
#else
            LOG(FATAL) << "Not built with cuda support!";
#endif
          } else {
            // Need to copy because we cache it
            u8* buffer = new u8[in_encoded_buffer_size];
            memcpy_buffer(buffer, CPU_DEVICE, in_encoded_buffer, CPU_DEVICE,
                          in_encoded_buffer_size);
            encoded_buffer = buffer;
          }
          encoded_buffer_size = in_encoded_buffer_size;
        }
      }

      i32 total_output_frames = static_cast<i32>(valid_frames.size());
      size_t& encoded_buffer_offset = cache.encoded_buffer_offset;
      i32& current_frame = cache.current_frame;
      // May have switched buffer since last evaluation
      if (total_output_frames > 0) {
        u8* output_block = new_block_buffer({device_type_, device_id_},
                                            total_output_frames * frame_size,
                                            total_output_frames);

        if (current_frame == -1) {
          current_frame = cache.current_start_keyframe;
        }
        i32 valid_index = 0;
        while (valid_index < total_output_frames) {
          auto video_start = now();

          if (decoder->decoded_frames_buffered() > 0) {
            // New frames
            bool more_frames = true;
            while (more_frames && valid_index < total_output_frames) {
              if (current_frame == valid_frames[valid_index]) {
                u8* decoded_buffer = output_block + valid_index * frame_size;
                more_frames = decoder->get_frame(decoded_buffer, frame_size);
                output_columns[out_col_idx].rows.push_back(
                    Row{decoded_buffer, frame_size});
                valid_index++;
                total_frames_used++;
              } else {
                more_frames = decoder->discard_frame();
              }
              current_frame++;
              total_frames_decoded++;
            }
            continue;
          }

          i32 encoded_packet_size = 0;
          const u8* encoded_packet = NULL;
          if (encoded_buffer_offset < encoded_buffer_size) {
            encoded_packet_size = *reinterpret_cast<const i32*>(
                encoded_buffer + encoded_buffer_offset);
            encoded_buffer_offset += sizeof(i32);
            encoded_packet = encoded_buffer + encoded_buffer_offset;
            encoded_buffer_offset += encoded_packet_size;
          }

          decoder->feed(encoded_packet, encoded_packet_size,
                        discontinuity_[video_num]);
          // Set a discontinuity if we sent an empty packet to reset
          // the stream next time
          discontinuity_[video_num] = (encoded_packet_size == 0);
        }
        // Wait on all memcpys from frames to be done
        decoder->wait_until_frames_copied();
      }

      if (clear_cache) {
        // HACK(apoms): just always force discontinuity for now instead of
        //  properly figuring out if the previous frame was abut
        discontinuity_[video_num] = true;

        delete[] encoded_buffer;
        encoded_buffer = nullptr;
        encoded_buffer_size = 0;
        current_start_keyframe = -1;
        current_end_keyframe = -1;
        encoded_buffer_offset = 0;
        current_frame = -1;
      }
    }
    video_num++;
  }

  // Forward all inputs
  for (std::tuple<i32, i32> idxs : regular_column_idxs_) {
    i32 col_idx;
    i32 out_col_idx;
    std::tie(col_idx, out_col_idx) = idxs;

    output_columns[out_col_idx].rows.insert(
        output_columns[out_col_idx].rows.end(),
        input_columns[col_idx].rows.begin(), input_columns[col_idx].rows.end());
    }

    if (profiler_) {
      profiler_->add_interval("decode", start, now());
      profiler_->increment("effective_frames", total_frames_used);
      profiler_->increment("decoded_frames", total_frames_decoded);
    }
  }

  DecoderEvaluatorFactory::DecoderEvaluatorFactory(
      DeviceType device_type, VideoDecoderType decoder_type)
      : device_type_(device_type), decoder_type_(decoder_type) {
    num_devices_ = device_type_ == DeviceType::GPU ? 1 : 8;
  }

  EvaluatorCapabilities DecoderEvaluatorFactory::get_capabilities() {
    EvaluatorCapabilities caps;
    caps.device_type = device_type_;
    caps.max_devices = num_devices_;
    caps.warmup_size = 0;
    caps.can_overlap = true;
    return caps;
  }

  std::vector<std::string> DecoderEvaluatorFactory::get_output_columns(
      const std::vector<std::string>& input_columns) {
    std::vector<std::string> output_columns;
    for (const std::string& col : input_columns) {
      if (col != base_column_args_name()) {
        output_columns.push_back(col);
      }
    }
    return output_columns;
  }

  Evaluator* DecoderEvaluatorFactory::new_evaluator(
      const EvaluatorConfig& config) {
    return new DecoderEvaluator(config, device_type_, decoder_type_,
                                num_devices_);
  }
}
<|endoftext|>


<commit_before>ca3064d9-4b02-11e5-9ddd-28cfe9171a43<commit_msg>fixed bug<commit_after>ca3a5f9e-4b02-11e5-b58a-28cfe9171a43<|endoftext|>


<commit_before>
#include <algorithm>

namespace scm {
namespace gl {

template<typename s>
ray_impl<s>::ray_impl()
  : _origin(typename ray_impl::vec3_type::value_type(0)),
    _direction(typename ray_impl::vec3_type::value_type(0))
{
}

template<typename s>
ray_impl<s>::ray_impl(const ray_impl<s>& p)
  : _origin(p._origin),
    _direction(p._direction)
{
}

template<typename s>
ray_impl<s>::ray_impl(const typename ray_impl<s>::vec3_type& org,
                      const typename ray_impl::vec3_type& dir)
  : _origin(org),
    _direction(dir)
{
    normalize();
}

template<typename s>
ray_impl<s>&
ray_impl<s>::operator=(const ray_impl<s>& rhs)
{
    ray_impl<s> tmp(rhs);
    swap(tmp);
    return (*this);
}

template<typename s>
void
ray_impl<s>::swap(ray_impl<s>& rhs)
{
    std::swap(_origin,    rhs._origin);
    std::swap(_direction, rhs._direction);
}

template<typename s>
void
ray_impl<s>::transform(const typename ray_impl<s>::mat4_type& t)
{
    using namespace scm::math;

    mat4_type inv_trans = transpose(inverse(t));

    _direction = vec3_type(inv_trans * vec4_type(_direction, typename vec4_type::value_type(0)));
    _origin    = vec3_type(t         * vec4_type(_origin,    typename vec4_type::value_type(1)));

    normalize();
}

template<typename s>
void
ray_impl<s>::transform_preinverted(const typename ray_impl<s>::mat4_type& it)
{
    using namespace scm::math;

    mat4_type inv_trans = transpose(it);

    _direction = vec3_type(inv_trans   * vec4_type(_direction, typename vec4_type::value_type(0)));
    _origin    = vec3_type(inverse(it) * vec4_type(_origin,    typename vec4_type::value_type(1)));

    normalize();
}

template<typename s>
const typename ray_impl<s>::vec3_type&
ray_impl<s>::origin() const
{
    return (_origin);
}

template<typename s>
const typename ray_impl<s>::vec3_type&
ray_impl<s>::direction() const
{
    return (_direction);
}

template<typename s>
void
ray_impl<s>::normalize()
{
    _direction = math::normalize(_direction);
}

} // namespace gl
} // namespace scm
<commit_msg>fixed ray transform<commit_after>
#include <algorithm>

namespace scm {
namespace gl {

template<typename s>
ray_impl<s>::ray_impl()
  : _origin(typename ray_impl::vec3_type::value_type(0)),
    _direction(typename ray_impl::vec3_type::value_type(0))
{
}

template<typename s>
ray_impl<s>::ray_impl(const ray_impl<s>& p)
  : _origin(p._origin),
    _direction(p._direction)
{
}

template<typename s>
ray_impl<s>::ray_impl(const typename ray_impl<s>::vec3_type& org,
                      const typename ray_impl::vec3_type& dir)
  : _origin(org),
    _direction(dir)
{
    normalize();
}

template<typename s>
ray_impl<s>&
ray_impl<s>::operator=(const ray_impl<s>& rhs)
{
    ray_impl<s> tmp(rhs);
    swap(tmp);
    return (*this);
}

template<typename s>
void
ray_impl<s>::swap(ray_impl<s>& rhs)
{
    std::swap(_origin,    rhs._origin);
    std::swap(_direction, rhs._direction);
}

template<typename s>
void
ray_impl<s>::transform(const typename ray_impl<s>::mat4_type& t)
{
    using namespace scm::math;

    //mat4_type inv_trans = transpose(inverse(t));

    //_direction = vec3_type(inv_trans * vec4_type(_direction, typename vec4_type::value_type(0)));
    _direction = vec3_type(t * vec4_type(_direction, typename vec4_type::value_type(0)));
    _origin    = vec3_type(t * vec4_type(_origin,    typename vec4_type::value_type(1)));

    normalize();
}

template<typename s>
void
ray_impl<s>::transform_preinverted(const typename ray_impl<s>::mat4_type& it)
{
    using namespace scm::math;

    //mat4_type inv_trans = transpose(it);

    //_direction = vec3_type(inv_trans   * vec4_type(_direction, typename vec4_type::value_type(0)));
    _direction = vec3_type(inverse(it) * vec4_type(_direction, typename vec4_type::value_type(0)));
    _origin    = vec3_type(inverse(it) * vec4_type(_origin,    typename vec4_type::value_type(1)));

    normalize();
}

template<typename s>
const typename ray_impl<s>::vec3_type&
ray_impl<s>::origin() const
{
    return (_origin);
}

template<typename s>
const typename ray_impl<s>::vec3_type&
ray_impl<s>::direction() const
{
    return (_direction);
}

template<typename s>
void
ray_impl<s>::normalize()
{
    _direction = math::normalize(_direction);
}

} // namespace gl
} // namespace scm
<|endoftext|>


<commit_before>41af35c7-2748-11e6-b865-e0f84713e7b8<commit_msg>bug fix<commit_after>41bcb8eb-2748-11e6-b74a-e0f84713e7b8<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include<iostream>
#include<cerrno>

#include<wiringPi.h>

#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
#include<sys/socket.h>
#include<sys/un.h>
#include<sys/types.h>
#include<unistd.h>
#include<signal.h>

#define MAXTIMINGS  85
#define DHTPIN      24

namespace {

int dht11_dat[5] = { 0, 0, 0, 0, 0 };

void read_data(){
    uint8_t laststate   = HIGH;
    uint8_t counter     = 0;
    uint8_t j       = 0, i;
    float   f; /* fahrenheit */

    dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;

    /* pull pin down for 18 milliseconds */
    pinMode( DHTPIN, OUTPUT );
    digitalWrite( DHTPIN, LOW );
    delay( 18 );
    /* then pull it up for 40 microseconds */
    digitalWrite( DHTPIN, HIGH );
    delayMicroseconds( 40 );
    /* prepare to read the pin */
    pinMode( DHTPIN, INPUT );

    /* detect change and read data */
    for ( i = 0; i < MAXTIMINGS; i++ ){
        counter = 0;
        while ( digitalRead( DHTPIN ) == laststate ){
            counter++;
            delayMicroseconds( 1 );
            if ( counter == 255 )
            {
                break;
            }
        }

        laststate = digitalRead( DHTPIN );

        if ( counter == 255 ){
            break;
        }

        /* ignore first 3 transitions */
        if ( (i >= 4) && (i % 2 == 0) ){
            /* shove each bit into the storage bytes */
            dht11_dat[j / 8] <<= 1;
            if ( counter > 16 ){
                dht11_dat[j / 8] |= 1;
            }
            j++;
        }
    }

    /*
     * check we read 40 bits (8bit x 5 ) + verify checksum in the last byte
     * print it out if data is good
     */
    if ( (j >= 40) && (dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) ){
        f = dht11_dat[2] * 9. / 5. + 32;
        printf( "Humidity = %d.%d %% Temperature = %d.%d *C (%.1f *F)\n",
            dht11_dat[0], dht11_dat[1], dht11_dat[2], dht11_dat[3], f );
    } else {
        printf( "Data not good, skip\n" );
    }
}

bool revoke_root(){
    if (getuid() == 0) {
        if (setgid(1000) != 0){
            std::cout << "asgard:dht11: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl;
            return false;
        }

        if (setuid(1000) != 0){
            std::cout << "asgard:dht11: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl;
            return false;
        }
    }

    if (setuid(0) != -1){
        std::cout << "asgard:dht11: managed to regain root privileges, exiting..." << std::endl;
        return false;
    }

    return true;
}

} //end of namespace

int main(){
    //Run the wiringPi setup (as root)
    wiringPiSetup();

    //Drop root privileges and run as pi:pi again
    if(!revoke_root()){
       std::cout << "asgard:dht11: unable to revoke root privileges, exiting..." << std::endl;
       return 1;
    }

    while (1){
        read_data();
        delay(1000);
    }

    return(0);
}
<commit_msg>Remove fahrenheit<commit_after>//=======================================================================
// Copyright (c) 2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include<iostream>
#include<cerrno>

#include<wiringPi.h>

#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
#include<sys/socket.h>
#include<sys/un.h>
#include<sys/types.h>
#include<unistd.h>
#include<signal.h>

#define MAXTIMINGS  85
#define DHTPIN      24

namespace {

int dht11_dat[5] = { 0, 0, 0, 0, 0 };

void read_data(){
    uint8_t laststate   = HIGH;
    uint8_t counter     = 0;
    uint8_t j       = 0, i;

    dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;

    /* pull pin down for 18 milliseconds */
    pinMode( DHTPIN, OUTPUT );
    digitalWrite( DHTPIN, LOW );
    delay( 18 );
    /* then pull it up for 40 microseconds */
    digitalWrite( DHTPIN, HIGH );
    delayMicroseconds( 40 );
    /* prepare to read the pin */
    pinMode( DHTPIN, INPUT );

    /* detect change and read data */
    for ( i = 0; i < MAXTIMINGS; i++ ){
        counter = 0;
        while ( digitalRead( DHTPIN ) == laststate ){
            counter++;
            delayMicroseconds( 1 );
            if ( counter == 255 )
            {
                break;
            }
        }

        laststate = digitalRead( DHTPIN );

        if ( counter == 255 ){
            break;
        }

        /* ignore first 3 transitions */
        if ( (i >= 4) && (i % 2 == 0) ){
            /* shove each bit into the storage bytes */
            dht11_dat[j / 8] <<= 1;
            if ( counter > 16 ){
                dht11_dat[j / 8] |= 1;
            }
            j++;
        }
    }

    /*
     * check we read 40 bits (8bit x 5 ) + verify checksum in the last byte
     * print it out if data is good
     */
    if ( (j >= 40) && (dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) ){
        printf( "Humidity = %d.%d %% Temperature = %d.%d\n",
            dht11_dat[0], dht11_dat[1], dht11_dat[2], dht11_dat[3]);
    } else {
        printf( "Data not good, skip\n" );
    }
}

bool revoke_root(){
    if (getuid() == 0) {
        if (setgid(1000) != 0){
            std::cout << "asgard:dht11: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl;
            return false;
        }

        if (setuid(1000) != 0){
            std::cout << "asgard:dht11: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl;
            return false;
        }
    }

    if (setuid(0) != -1){
        std::cout << "asgard:dht11: managed to regain root privileges, exiting..." << std::endl;
        return false;
    }

    return true;
}

} //end of namespace

int main(){
    //Run the wiringPi setup (as root)
    wiringPiSetup();

    //Drop root privileges and run as pi:pi again
    if(!revoke_root()){
       std::cout << "asgard:dht11: unable to revoke root privileges, exiting..." << std::endl;
       return 1;
    }

    while (1){
        read_data();
        delay(1000);
    }

    return(0);
}
<|endoftext|>


<commit_before>cc247c33-2747-11e6-b7b2-e0f84713e7b8<commit_msg>Initial commit.2<commit_after>cc4ec014-2747-11e6-b14c-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream>
#include <string.h>
using namespace std;

// disable if you dont want it to be loud
#define VERBOSE 1

// definitions
bool findExtension(string,string);
bool renameFile(char *, string);

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

#if VERBOSE
	cout << "number of arguments: " << argc << endl;
	for (int i = 0; i < argc; i++)
	{
		cout << i << ": " << argv[i] << endl;
	}
#endif

	// if there are more than 1 arguments, do the conversion
	if (argc > 1)
	{
		// open file for reading - one at a time
		for (int i = 0; i < argc; i++)
		{
			// convert the char[] to string for easier parsing
			string temp = argv[i];

			/************************** ADD NEW EXTENSIONS HERE **************************/
			if (findExtension(".grb", temp)) // what we are looking for
			{
				// extension found, convert to *.GKO - board outline
				renameFile(argv[i], ".GKO"); // what we want to convert to

			}
			else if (findExtension(".drl", temp))
			{
				// extension found, convert to *.XLN - drill file
				renameFile(argv[i], ".XLN");
			}
		}
	}
	else
	{
		// nothing to convert, abort
		return 0;
	}

	// end of program
	return 0;
}

bool findExtension(string extension, string argument_string)
{
	if (argument_string.find(extension))
		return true;
	else
		return false;
}

bool renameFile(char * old_file, string new_extension)
{
	// extract file name from old_file - contains the whole directory
	string temp = old_file;
	int token_pos = temp.find_last_of('\\');

	// eliminate everything before and including the '\'
	temp.erase(0, token_pos);

	// concatinate the string with our new extension
	temp += new_extension;

	// rename the file
	if (rename(old_file, new_extension.c_str()))
		return true;
	else
		return false;
}

<commit_msg>works, saves the old extension as part of the file - final version 1.0<commit_after>#include <iostream>
#include <string.h>
using namespace std;

// disable if you dont want it to be loud
#define VERBOSE 1

// definitions
bool findExtension(string,string);
bool renameFile(char *, string);

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

#if VERBOSE
	cout << "number of arguments: " << argc << endl;
	for (int i = 0; i < argc; i++)
	{
		cout << i << ": " << argv[i] << endl;
	}
#endif

	// if there are more than 1 arguments, do the conversion
	if (argc > 1)
	{
		// open file for reading - one at a time
		for (int i = 1; i < argc; i++)
		{
			// convert the char[] to string for easier parsing
			string temp = argv[i];

#if VERBOSE
			cout << "i = " << i << " and argv[i] = " << endl << argv[i] << endl;
#endif

			/************************** ADD NEW EXTENSIONS HERE **************************/
			if (findExtension(".gbr", temp)) // what we are looking for
			{
				// extension found, convert to *.GKO - board outline
				if (renameFile(argv[i], ".GKO"))// what we want to convert to
				{
#if VERBOSE
					cout << "sucessful rename to .GKO" << endl;
#endif
				}

			}
			else if (findExtension(".drl", temp))
			{
				// extension found, convert to *.XLN - drill file
				if(renameFile(argv[i], ".XLN"))
				{
#if VERBOSE
					cout << "sucessful rename to .XLN" << endl;
#endif
				}
			}
		}
	}
	else
	{
		// nothing to convert, abort
		return 0;
	}

	// end of program
	return 0;
}

bool findExtension(string extension, string argument_string)
{
	int temp = argument_string.find(extension);

	if (temp > 0)
	{
#if VERBOSE
		cout << "sucessful find of " << extension.c_str() << " at pos " << temp << endl;
#endif
		return true;
	}
	else
	{
#if VERBOSE
		cout << "unsucessful find of " << extension.c_str() << " at pos " << temp << endl;
#endif
		return false;
	}
}

bool renameFile(char * old_file, string new_extension)
{
	// extract file name from old_file - contains the whole directory
	string temp = old_file;
	int token_pos = temp.find_last_of('\\');

	cout << "token_pos: " << token_pos << endl;

	// eliminate everything before and including the '\'
	temp.erase(0, token_pos+1);

	// concatinate the string with our new extension
	temp += new_extension;

	cout << "old_file: " << old_file << endl;
	cout << "new file name: " << temp.c_str() << endl;

	// rename the file
	if (rename(old_file, temp.c_str()))
		return true;
	else
		return false;
}

void compressFiles(char * names)
{
#ifdef _WIN32
	//zip directory

#else
	//tar directory
#endif
}<|endoftext|>


<commit_before>/**
 * @mainpage	COSSB(Component-based Open & Simple Service Broker)
 * @details	COSSB�뒗 �궗臾쇱씤�꽣�꽬(IoT) �쑀臾댁꽑 �꽕�듃�썙�겕 �솚寃쎌뿉�꽌 留먮떒 �옣移섍컙 �꽌鍮꾩뒪 �긽�샇�슫�슜�꽦(Inter-operability)怨� �솗�옣�꽦�쓣 吏��썝 �븯湲곗쐞�븳 �냼�봽�듃�썾�뼱 �봽�젅�엫�썙�겕�엯�땲�떎.
 */

/**
 * @file		engine.cpp
 * @brief		COSSB Engine
 * @author		Byunghun Hwang<bhhwang@nsynapse.com>
 * @date 		2015. 6. 9
 * @details	COSSB Engine main starter
 */

#include <iostream>
#include <csignal>
#include <cstdlib>
#include <popt.h>
#include <memory>

#include "cossb.hpp"

using namespace std;
using namespace cossb;

void destroy() {
	cossb::core::cossb_destroy();
	cout << "Terminated." << endl;
	_exit(EXIT_SUCCESS);
}

/**
 * @brief	SIGINT signal callback function
 * @details	Stop all services and destroy all instances
 */
void sigc_interrupt(int param) {
	cossb::core::cossb_destroy();
	cout << "Successfully terminated." << endl;
	_exit(EXIT_FAILURE);
}

/**
 * @brief	Main routine
 * @param	command
 * @details	Start with default components
 */
int main(int argc, char* argv[])
{
	signal(SIGINT, sigc_interrupt);

	char* config_file = nullptr;
	struct poptOption optionTable[] =
	{
		{"run",		'r', POPT_ARG_NONE, 0, 'r', "Run Engine with default configuration", ""},
		{"version",	'v', POPT_ARG_NONE, 0, 'v', "Version", "version"},
		{"config", 	'c', POPT_ARG_STRING, (void*)config_file, 'c', "Open configuration file", "XML Configuration file"},
		POPT_AUTOHELP
		POPT_TABLEEND
	};
	poptContext optionCon = poptGetContext(NULL, argc, (const char**)argv, optionTable, 0);
	poptSetOtherOptionHelp(optionCon, "<option>");

	if(argc<2)
	{
		std::cout << poptStrerror(POPT_ERROR_NOARG) << endl;
		_exit(EXIT_SUCCESS);
	}

	int opt = 0;
	while((opt = poptGetNextOpt(optionCon))>=0)
	{
		switch(opt)
		{
		// install components
		case 'v':
		{
			std::cout << COSSB_NAME << COSSB_VERSION << " (Released " << __DATE__ << " " <<__TIME__ << ")" << std::endl;
			_exit(EXIT_SUCCESS);

		} break;

		//load configuration file
		case 'c':
		{
			string manifest = (const char*)poptGetOptArg(optionCon);
			if(!manifest.empty())
			{
				if(!cossb::core::cossb_init(manifest.c_str()))
					destroy();
			}
		}
			break;

		//run with default configuration file(manifest.xml)
		case 'r':
		{
			if(!cossb::core::cossb_init("manifest.xml"))
				destroy();
		}
		break;

		}
	}

	if (opt<-1)
	{
		cout << poptBadOption(optionCon, POPT_BADOPTION_NOALIAS) << ":" << poptStrerror(opt) << endl;
		destroy();
	}

	pause();
	poptFreeContext(optionCon);

	destroy();

	return 0;
}
<commit_msg>edit main<commit_after>/**
 * @mainpage	COSSB(Component-based Open & Simple Service Broker)
 * @details	COSSB�뒗 �궗臾쇱씤�꽣�꽬(IoT) �쑀臾댁꽑 �꽕�듃�썙�겕 �솚寃쎌뿉�꽌 留먮떒 �옣移섍컙 �꽌鍮꾩뒪 �긽�샇�슫�슜�꽦(Inter-operability)怨� �솗�옣�꽦�쓣 吏��썝 �븯湲곗쐞�븳 �냼�봽�듃�썾�뼱 �봽�젅�엫�썙�겕�엯�땲�떎.
 */

/**
 * @file		engine.cpp
 * @brief		COSSB Engine
 * @author		Byunghun Hwang<bhhwang@nsynapse.com>
 * @date 		2015. 6. 9
 * @details	COSSB Engine main starter
 */

#include <iostream>
#include <csignal>
#include <cstdlib>
#include <popt.h>
#include <memory>

#include "cossb.hpp"

using namespace std;
using namespace cossb;

void destroy() {
	cossb::core::cossb_destroy();
	cout << "Terminated." << endl;
	_exit(EXIT_SUCCESS);
}

/**
 * @brief	SIGINT signal callback function
 * @details	Stop all services and destroy all instances
 */
void sigc_interrupt(int param) {
	cossb::core::cossb_destroy();
	cout << "Terminated." << endl;
	_exit(EXIT_FAILURE);
}

/**
 * @brief	Main routine
 * @param	command
 * @details	Start with default components
 */
int main(int argc, char* argv[])
{
	signal(SIGINT, sigc_interrupt);

	char* config_file = nullptr;
	struct poptOption optionTable[] =
	{
		{"run",		'r', POPT_ARG_NONE, 0, 'r', "Run Engine with default configuration", ""},
		{"version",	'v', POPT_ARG_NONE, 0, 'v', "Version", "version"},
		{"config", 	'c', POPT_ARG_STRING, (void*)config_file, 'c', "Open configuration file", "XML Configuration file"},
		POPT_AUTOHELP
		POPT_TABLEEND
	};
	poptContext optionCon = poptGetContext(NULL, argc, (const char**)argv, optionTable, 0);
	poptSetOtherOptionHelp(optionCon, "<option>");

	if(argc<2)
	{
		std::cout << poptStrerror(POPT_ERROR_NOARG) << endl;
		_exit(EXIT_SUCCESS);
	}

	int opt = 0;
	while((opt = poptGetNextOpt(optionCon))>=0)
	{
		switch(opt)
		{
		// install components
		case 'v':
		{
			std::cout << COSSB_NAME << COSSB_VERSION << " (Released " << __DATE__ << " " <<__TIME__ << ")" << std::endl;
			_exit(EXIT_SUCCESS);

		} break;

		//load configuration file
		case 'c':
		{
			string manifest = (const char*)poptGetOptArg(optionCon);
			if(!manifest.empty())
			{
				if(!cossb::core::cossb_init(manifest.c_str()))
					destroy();
			}
		}
			break;

		//run with default configuration file(manifest.xml)
		case 'r':
		{
			if(!cossb::core::cossb_init("manifest.xml"))
				destroy();
		}
		break;

		}
	}

	if (opt<-1)
	{
		cout << poptBadOption(optionCon, POPT_BADOPTION_NOALIAS) << ":" << poptStrerror(opt) << endl;
		destroy();
	}

	//start the cossb service
	cossb::core::cossb_start();

	pause();
	poptFreeContext(optionCon);

	destroy();

	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
#include <regex>
#include "BinaryTreeAVL.h"
#include "NodoVocabulario.h"

void ayuda( std::string );
void leerArchivo( BinaryTreeAVL&, std::string, bool );
void insertarPalabra(BinaryTreeAVL&, std::string );
int validarPalabra( std::string );
std::string voltearPalabra(std::string palabra);
int scorePalabra( BinaryTreeAVL&, std::string );

int main()
{
  BinaryTreeAVL tree;
  bool exit = false, init = false, init_inverse = false;
  std::string comando;
  do
  {
    std::cout << "$ ";
    std::getline( std::cin, comando );
    std::string aux = comando.substr( 0, comando.find( " " ) );
    if( comando.find( "ayuda" ) != std::string::npos )
    {
      ayuda( comando );
      std::cout << std::endl;
    }
    else
    {
      if( aux == "init_inverse" && !init_inverse )
      {
        //TODO funcion init_inverse
        leerArchivo( tree, comando, false);
        init_inverse = true;
        std::cout << std::endl;
      }
      else
      {
        if( aux == "score" )
        {
          std::string palabra = comando.substr( comando.find( " " ) + 1 );
          //TODO funcion score
          int scoreP = scorePalabra(tree, palabra);
          if(scoreP == -1){
            std::cout << "----------------------------------------------------" << std::endl;
            std::cout << "ERROR" << std::endl;
            std::cout << "La palabra " << palabra << " tiene caracteres invalidos." << std::endl;
            std::cout << "----------------------------------------------------" << std::endl;
          }
          else{
            if(scoreP == -2){
              std::cout << "----------------------------------------------------" << std::endl;
              std::cout << "ERROR" << std::endl;
              std::cout << "La palabra " << palabra << " no se encuentra en el diccionario." << std::endl;
              std::cout << "----------------------------------------------------" << std::endl;
            }
            else{
              std::cout << "El puntaje de la palabra " << palabra << " es: " << scoreP << std::endl;
              std::cout << std::endl;
            }
          }

        }
        else
        {
          if( aux == "init" && !init )
          {
            //TODO funcion init
            leerArchivo( tree, comando, true);
            init = true;
            std::cout << std::endl;
          }
          else
            if( aux == "exit" )
              exit = true;
            else
              if( init || init_inverse )
              {
                if( init )
                  std::cout << "Diccionario";
                else
                  std::cout << "Diccionario inverso";
                std::cout << " ya ha sido inicializado." << std::endl;
                std::cout << std::endl;
              }
              else
              {
                std::cout << "Error comando inexistente, teclee \"ayuda\" para ver una lista de comandos" << std::endl;
                std::cout << std::endl;
              }
        }

      }
    }
  }while( !exit );
  return 0;
}

void ayuda( std::string comando )
{
  if( comando == "ayuda init_inverse" )
  {
    std::cout << "comando: init_inverse words_file.txt." << std::endl;
    std::cout << "descripción: Inicializa el sistema a partir del archivo words_file.txt, que" << std::endl
              << "contiene un diccionario de palabras aceptadas en el idioma ingles" << std::endl
              << "(idioma original del juego). A diferencia del comando init, este comando" << std::endl
              << "almacena las palabras en sentido inverso (leidas de derecha a izquierda)" << std::endl;
  }
  else
    if( comando == "ayuda init" )
    {
      std::cout << "comando: init words_file.txt" << std::endl;
      std::cout << "descripción: Inicializa el sistema a partir del archivo words_file.txt, que" << std::endl
                << "contiene un diccionario de palabras aceptadas en el idioma ingles" << std::endl
                << "(idioma original del juego)." << std::endl << std::endl;
    }
    else
      if( comando == "ayuda score" )
      {
        std::cout << "comando: score word" << std::endl;
        std::cout << "descripción: El comando permite conocer la puntuacion que puede obtenerse con" << std::endl
                  << "una palabra dada, de acuerdo a la tabla de puntuacion de cada letra." << std::endl;
      }
      else
        if( comando == "ayuda exit" )
        {
          std::cout << "comando: exit" << std::endl;
          std::cout << "descripción: Termina la ejecucion de la aplicacion." << std::endl;
        }
        else
        {
          if( comando == "ayuda" )
          {
            std::cout << "Teclee \"ayuda <comando>\" para obtener más informacion del comando" << std::endl;
            std::cout << std::endl << "\tinit [nombre del archivo]" << std::endl;
            std::cout << "\tinit_inverse [nombre del archivo]" << std::endl;
            std::cout << "\tscore [palabra]" << std::endl;
            std::cout << "\texit" << std::endl;
          }
          else
          std::cout << "Error comando inexistente, teclee \"ayuda\" para ver una lista de comandos" << std::endl;

        }
}

void leerArchivo( BinaryTreeAVL& tree, std::string comando, bool tipo )
{
  std::string nombreArc, linea;
  nombreArc = comando.substr( comando.find( " " ) + 1 );
  std::ifstream archivo( nombreArc.c_str( ) );
  if( archivo.is_open() )
  {
    while( !archivo.eof() )
    {
      archivo >> linea;
      std::transform(linea.begin(),linea.end(),linea.begin(),::tolower);
      if(tipo == true)
        insertarPalabra(tree , linea);
      else
        insertarPalabra(tree, voltearPalabra(linea));
    }
    std::cout << std::endl << "----------------------------------------------------" << std::endl;
    std::cout << "El diccionario se inicializo." << std::endl;
    std::cout << "----------------------------------------------------" << std::endl;

  }
  else
  {
    std::cout << "----------------------------------------------------" << std::endl;
    std::cout << "ERROR" << std::endl;
    std::cout << "apertura del archivo: " << nombreArc << " fallida." << std::endl;
    std::cout << "----------------------------------------------------" << std::endl;
  }
}

void insertarPalabra(BinaryTreeAVL& tree, std::string palabra){
  if(validarPalabra(palabra) == 1){
    BinaryNodeAVL* nodoLetra = tree.search(palabra[0]);
    if(nodoLetra != nullptr){
      nodoLetra->getData().insertarPalabra(palabra);
    }
    else{
      NodoVocabulario* nodo = new NodoVocabulario(palabra[0]);
      tree.insert(*nodo);
      nodo->insertarPalabra(palabra);
    }
  }
  else{
    std::cout << "----------------------------------------------------" << std::endl;
    std::cout << "ERROR" << std::endl;
    std::cout << "La palabra: " << palabra << " tiene caracteres invalidos." << std::endl;
    std::cout << "----------------------------------------------------" << std::endl;
  }
}

int validarPalabra( std::string palabra )
{
    int verificado = 0;
    for( unsigned int i = 0; i < palabra.size(); i++ )
    {
        char caracter = palabra[i];
        if( ( caracter >= 65 && caracter <= 90 ) || ( caracter >= 97 && caracter <= 122 ) )
            verificado = 1;
        else
        {
          verificado = 0;
          break;
        }
    }
    return verificado;
}

std::string voltearPalabra(std::string palabra)
{
    int ind = 0;
    std::string nPalabra;
    nPalabra.resize(palabra.size());
    for(std::string::reverse_iterator apun = palabra.rbegin(); apun != palabra.rend(); apun++)
    {
        nPalabra[ind]=*apun;
        ind++;
    }
    return nPalabra;
}

int scorePalabra(BinaryTreeAVL& tree, std::string palabra){
  if(validarPalabra(palabra) == 1){
    BinaryNodeAVL* nodoLetra = tree.search(palabra[0]);
    if(nodoLetra != nullptr){
      std::map<std::string, int>::iterator iterador = nodoLetra->getData().getPalabras().find(palabra);
      if(iterador != nodoLetra->getData().getPalabras().end())
        return((nodoLetra->getData().getPalabras())[palabra]);
      else
        return (-2);
    }
    else
      return (-2);
  }
  return (-1);
}
<commit_msg>arreglo en el main<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
#include <regex>
#include "BinaryTreeAVL.h"
#include "NodoVocabulario.h"

void ayuda( std::string );
void leerArchivo( BinaryTreeAVL&, std::string, bool );
void insertarPalabra(BinaryTreeAVL&, std::string );
int validarPalabra( std::string );
std::string voltearPalabra(std::string palabra);
int scorePalabra( BinaryTreeAVL&, std::string );

int main()
{
  BinaryTreeAVL tree;
  bool exit = false, init = false, init_inverse = false;
  std::string comando;
  do
  {
    std::cout << "$ ";
    std::getline( std::cin, comando );
    std::string aux = comando.substr( 0, comando.find( " " ) );
    if( comando.find( "ayuda" ) != std::string::npos )
    {
      ayuda( comando );
      std::cout << std::endl;
    }
    else
    {
      if( aux == "init_inverse" && !init_inverse )
      {
        //TODO funcion init_inverse
        leerArchivo( tree, comando, false);
        init_inverse = true;
        std::cout << std::endl;
      }
      else
      {
        if( aux == "score" )
        {
          std::string palabra = comando.substr( comando.find( " " ) + 1 );
          //TODO funcion score
          int scoreP = scorePalabra(tree, palabra);
          if(scoreP == -1){
            std::cout << "----------------------------------------------------" << std::endl;
            std::cout << "ERROR" << std::endl;
            std::cout << "La palabra " << palabra << " tiene caracteres invalidos." << std::endl;
            std::cout << "----------------------------------------------------" << std::endl;
          }
          else{
            if(scoreP == -2){
              std::cout << "----------------------------------------------------" << std::endl;
              std::cout << "ERROR" << std::endl;
              std::cout << "La palabra " << palabra << " no se encuentra en el diccionario." << std::endl;
              std::cout << "----------------------------------------------------" << std::endl;
            }
            else{
              std::cout << "El puntaje de la palabra " << palabra << " es: " << scoreP << std::endl;
              std::cout << std::endl;
            }
          }

        }
        else
        {
          if( aux == "init" && !init )
          {
            //TODO funcion init
            leerArchivo( tree, comando, true);
            init = true;
            std::cout << std::endl;
          }
          else
            if( aux == "exit" )
              exit = true;
            else
              if( ( aux == "init" && init ) || ( aux == "init_inverse" && init_inverse ) )
              {
                if( init )
                  std::cout << "Diccionario";
                else
                  std::cout << "Diccionario inverso";
                std::cout << " ya ha sido inicializado." << std::endl;
                std::cout << std::endl;
              }
              else
              {
                std::cout << "Error comando inexistente, teclee \"ayuda\" para ver una lista de comandos" << std::endl;
                std::cout << std::endl;
              }
        }

      }
    }
  }while( !exit );
  return 0;
}

void ayuda( std::string comando )
{
  if( comando == "ayuda init_inverse" )
  {
    std::cout << "comando: init_inverse words_file.txt." << std::endl;
    std::cout << "descripción: Inicializa el sistema a partir del archivo words_file.txt, que" << std::endl
              << "contiene un diccionario de palabras aceptadas en el idioma ingles" << std::endl
              << "(idioma original del juego). A diferencia del comando init, este comando" << std::endl
              << "almacena las palabras en sentido inverso (leidas de derecha a izquierda)" << std::endl;
  }
  else
    if( comando == "ayuda init" )
    {
      std::cout << "comando: init words_file.txt" << std::endl;
      std::cout << "descripción: Inicializa el sistema a partir del archivo words_file.txt, que" << std::endl
                << "contiene un diccionario de palabras aceptadas en el idioma ingles" << std::endl
                << "(idioma original del juego)." << std::endl << std::endl;
    }
    else
      if( comando == "ayuda score" )
      {
        std::cout << "comando: score word" << std::endl;
        std::cout << "descripción: El comando permite conocer la puntuacion que puede obtenerse con" << std::endl
                  << "una palabra dada, de acuerdo a la tabla de puntuacion de cada letra." << std::endl;
      }
      else
        if( comando == "ayuda exit" )
        {
          std::cout << "comando: exit" << std::endl;
          std::cout << "descripción: Termina la ejecucion de la aplicacion." << std::endl;
        }
        else
        {
          if( comando == "ayuda" )
          {
            std::cout << "Teclee \"ayuda <comando>\" para obtener más informacion del comando" << std::endl;
            std::cout << std::endl << "\tinit [nombre del archivo]" << std::endl;
            std::cout << "\tinit_inverse [nombre del archivo]" << std::endl;
            std::cout << "\tscore [palabra]" << std::endl;
            std::cout << "\texit" << std::endl;
          }
          else
          std::cout << "Error comando inexistente, teclee \"ayuda\" para ver una lista de comandos" << std::endl;

        }
}

void leerArchivo( BinaryTreeAVL& tree, std::string comando, bool tipo )
{
  std::string nombreArc, linea;
  nombreArc = comando.substr( comando.find( " " ) + 1 );
  std::ifstream archivo( nombreArc.c_str( ) );
  if( archivo.is_open() )
  {
    while( !archivo.eof() )
    {
      archivo >> linea;
      std::transform(linea.begin(),linea.end(),linea.begin(),::tolower);
      if(tipo == true)
        insertarPalabra(tree , linea);
      else
        insertarPalabra(tree, voltearPalabra(linea));
    }
    std::cout << std::endl << "----------------------------------------------------" << std::endl;
    std::cout << "El diccionario se inicializo." << std::endl;
    std::cout << "----------------------------------------------------" << std::endl;

  }
  else
  {
    std::cout << "----------------------------------------------------" << std::endl;
    std::cout << "ERROR" << std::endl;
    std::cout << "apertura del archivo: " << nombreArc << " fallida." << std::endl;
    std::cout << "----------------------------------------------------" << std::endl;
  }
}

void insertarPalabra(BinaryTreeAVL& tree, std::string palabra){
  if(validarPalabra(palabra) == 1){
    BinaryNodeAVL* nodoLetra = tree.search(palabra[0]);
    if(nodoLetra != nullptr){
      nodoLetra->getData().insertarPalabra(palabra);
    }
    else{
      NodoVocabulario* nodo = new NodoVocabulario(palabra[0]);
      tree.insert(*nodo);
      nodo->insertarPalabra(palabra);
    }
  }
  else{
    std::cout << "----------------------------------------------------" << std::endl;
    std::cout << "ERROR" << std::endl;
    std::cout << "La palabra: " << palabra << " tiene caracteres invalidos." << std::endl;
    std::cout << "----------------------------------------------------" << std::endl;
  }
}

int validarPalabra( std::string palabra )
{
    int verificado = 0;
    for( unsigned int i = 0; i < palabra.size(); i++ )
    {
        char caracter = palabra[i];
        if( ( caracter >= 65 && caracter <= 90 ) || ( caracter >= 97 && caracter <= 122 ) )
            verificado = 1;
        else
        {
          verificado = 0;
          break;
        }
    }
    return verificado;
}

std::string voltearPalabra(std::string palabra)
{
    int ind = 0;
    std::string nPalabra;
    nPalabra.resize(palabra.size());
    for(std::string::reverse_iterator apun = palabra.rbegin(); apun != palabra.rend(); apun++)
    {
        nPalabra[ind]=*apun;
        ind++;
    }
    return nPalabra;
}

int scorePalabra(BinaryTreeAVL& tree, std::string palabra){
  if(validarPalabra(palabra) == 1){
    BinaryNodeAVL* nodoLetra = tree.search(palabra[0]);
    if(nodoLetra != nullptr){
      std::map<std::string, int>::iterator iterador = nodoLetra->getData().getPalabras().find(palabra);
      if(iterador != nodoLetra->getData().getPalabras().end())
        return((nodoLetra->getData().getPalabras())[palabra]);
      else
        return (-2);
    }
    else
      return (-2);
  }
  return (-1);
}
<|endoftext|>


<commit_before>#include "filters.hh"

namespace Kakoune
{

void colorize_regex(DisplayBuffer& display_buffer,
                    const boost::regex& ex, Color color)
{
    BufferIterator display_begin = display_buffer.begin()->begin();
    BufferIterator display_end   = display_buffer.back().end();

    boost::regex_iterator<BufferIterator> re_it(display_begin, display_end,
                                                ex, boost::match_nosubs);
    boost::regex_iterator<BufferIterator> re_end;
    DisplayBuffer::iterator atom_it = display_buffer.begin();
    for (; re_it != re_end; ++re_it)
    {
        BufferIterator begin = (*re_it)[0].first;
        BufferIterator end   = (*re_it)[0].second;
        auto begin_atom_it = display_buffer.atom_containing(begin, atom_it);
        auto end_atom_it   = display_buffer.atom_containing(end, atom_it);
        if (begin_atom_it == end_atom_it)
        {
            if (begin_atom_it->begin() != begin)
                begin_atom_it = ++display_buffer.split(begin_atom_it, begin);
            if (begin_atom_it->end() != end)
                begin_atom_it = display_buffer.split(begin_atom_it, end);

            begin_atom_it->fg_color() = color;
        }
        atom_it = begin_atom_it;
    }
}

void colorize_cplusplus(DisplayBuffer& display_buffer)
{
    static boost::regex preprocessor("(\\`|(?<=\\n))\\h*#\\h*[^\\n]*(?=\\n)");
    colorize_regex(display_buffer, preprocessor, Color::Magenta);

    static boost::regex comments("//[^\\n]*\\n");
    colorize_regex(display_buffer, comments, Color::Cyan);

    static boost::regex strings("(?<!')\"(\\\\\"|[^\"])*\"");
    colorize_regex(display_buffer, strings, Color::Magenta);

    static boost::regex values("\\<(true|false|NULL|nullptr)\\>|\\<-?\\d+[fdiu]?|'\\\\?[^']?'");
    colorize_regex(display_buffer, values, Color::Red);

    static boost::regex builtin_types("\\<(void|int|char|unsigned|float|bool|size_t)\\>");
    colorize_regex(display_buffer, builtin_types, Color::Yellow);

    static boost::regex control_keywords("\\<(while|for|if|else|do|switch|case|default|goto|break|continue|return|using|try|catch|throw)\\>");
    colorize_regex(display_buffer, control_keywords, Color::Blue);

    //static boost::regex operators("->|\\+|\\-|\\*|/|\\\\|\\&|\\|\\^|[<>=!+-]=|=|\\(|\\)|\\[|\\]|\\{|\\}|\\<(not|and|or|xor)\\>");
    //colorize_regex(display_buffer, operators, Color::Green);

    static boost::regex types_keywords("\\<(const|auto|namespace|static|volatile|class|struct|enum|union|public|protected|private|template|typedef)\\>");
    colorize_regex(display_buffer, types_keywords, Color::Green);
}

void expand_tabulations(DisplayBuffer& display_buffer)
{
    const int tabstop = 8;
    for (auto atom_it = display_buffer.begin();
         atom_it != display_buffer.end(); ++atom_it)
    {
        for (BufferIterator it = atom_it->begin(); it != atom_it->end(); ++it)
        {
            if (*it == '\t')
            {
                if (it != atom_it->begin())
                    atom_it = ++display_buffer.split(atom_it, it);

                if (it+1 != atom_it->end())
                    atom_it = display_buffer.split(atom_it, it+1);

                BufferCoord pos = it.buffer().line_and_column_at(it);

                int column = 0;
                for (auto line_it = it.buffer().iterator_at({pos.line, 0});
                     line_it != it; ++line_it)
                {
                    assert(*line_it != '\n');
                    if (*line_it == '\t')
                        column += tabstop - (column % tabstop);
                    else
                       ++column;
                }

                int count = tabstop - (column % tabstop);
                display_buffer.replace_atom_content(atom_it,
                                                    std::string(count, ' '));
            }
        }
    }
}

void show_line_numbers(DisplayBuffer& display_buffer)
{
    const Buffer& buffer = display_buffer.front().begin().buffer();
    BufferCoord coord = buffer.line_and_column_at(display_buffer.begin()->begin());

    int last_line = buffer.line_and_column_at(display_buffer.back().end()-1).line;

    for (; coord.line <= last_line; ++coord.line)
    {
        BufferIterator line_start = buffer.iterator_at(coord);
        DisplayBuffer::iterator atom_it = display_buffer.atom_containing(line_start);
        if (atom_it != display_buffer.end())
        {
            if (atom_it->begin() != line_start)
            {
                if (not atom_it->splitable())
                    continue;

                atom_it = ++display_buffer.split(atom_it, line_start);
            }
            atom_it = display_buffer.insert(
                atom_it,
                DisplayAtom(atom_it->coord(),
                            atom_it->begin(), atom_it->begin(),
                            Color::Black, Color::White));

            char buffer[6];
            snprintf(buffer, 6, "%3d ", coord.line + 1);
            display_buffer.replace_atom_content(atom_it, buffer);
        }
    }
}

}
<commit_msg>Filters: tweak colorize_cplusplus<commit_after>#include "filters.hh"

namespace Kakoune
{

void colorize_regex(DisplayBuffer& display_buffer,
                    const boost::regex& ex, Color color)
{
    BufferIterator display_begin = display_buffer.begin()->begin();
    BufferIterator display_end   = display_buffer.back().end();

    boost::regex_iterator<BufferIterator> re_it(display_begin, display_end,
                                                ex, boost::match_nosubs);
    boost::regex_iterator<BufferIterator> re_end;
    DisplayBuffer::iterator atom_it = display_buffer.begin();
    for (; re_it != re_end; ++re_it)
    {
        BufferIterator begin = (*re_it)[0].first;
        BufferIterator end   = (*re_it)[0].second;
        auto begin_atom_it = display_buffer.atom_containing(begin, atom_it);
        auto end_atom_it   = display_buffer.atom_containing(end, atom_it);
        if (begin_atom_it == end_atom_it)
        {
            if (begin_atom_it->begin() != begin)
                begin_atom_it = ++display_buffer.split(begin_atom_it, begin);
            if (begin_atom_it->end() != end)
                begin_atom_it = display_buffer.split(begin_atom_it, end);

            begin_atom_it->fg_color() = color;
        }
        atom_it = begin_atom_it;
    }
}

void colorize_cplusplus(DisplayBuffer& display_buffer)
{
    static boost::regex preprocessor("(\\`|(?<=\\n))\\h*#\\h*[^\\n]*(?=\\n)");
    colorize_regex(display_buffer, preprocessor, Color::Magenta);

    static boost::regex comments("//[^\\n]*\\n");
    colorize_regex(display_buffer, comments, Color::Cyan);

    static boost::regex strings("(?<!')\"(\\\\\"|[^\"])*\"");
    colorize_regex(display_buffer, strings, Color::Magenta);

    static boost::regex values("\\<(true|false|NULL|nullptr)\\>|\\<-?\\d+[fdiu]?|'\\\\?[^']?'");
    colorize_regex(display_buffer, values, Color::Red);

    static boost::regex builtin_types("\\<(void|int|char|unsigned|float|bool|size_t)\\>");
    colorize_regex(display_buffer, builtin_types, Color::Yellow);

    static boost::regex control_keywords("\\<(while|for|if|else|do|switch|case|default|goto|break|continue|return|using|try|catch|throw)\\>");
    colorize_regex(display_buffer, control_keywords, Color::Blue);

    //static boost::regex operators("->|\\+|\\-|\\*|/|\\\\|\\&|\\|\\^|[<>=!+-]=|=|\\(|\\)|\\[|\\]|\\{|\\}|\\<(not|and|or|xor)\\>");
    //colorize_regex(display_buffer, operators, Color::Green);

    static boost::regex types_keywords("\\<(const|auto|namespace|static|volatile|class|struct|enum|union|public|protected|private|template|typedef|virtual)\\>");
    colorize_regex(display_buffer, types_keywords, Color::Green);
}

void expand_tabulations(DisplayBuffer& display_buffer)
{
    const int tabstop = 8;
    for (auto atom_it = display_buffer.begin();
         atom_it != display_buffer.end(); ++atom_it)
    {
        for (BufferIterator it = atom_it->begin(); it != atom_it->end(); ++it)
        {
            if (*it == '\t')
            {
                if (it != atom_it->begin())
                    atom_it = ++display_buffer.split(atom_it, it);

                if (it+1 != atom_it->end())
                    atom_it = display_buffer.split(atom_it, it+1);

                BufferCoord pos = it.buffer().line_and_column_at(it);

                int column = 0;
                for (auto line_it = it.buffer().iterator_at({pos.line, 0});
                     line_it != it; ++line_it)
                {
                    assert(*line_it != '\n');
                    if (*line_it == '\t')
                        column += tabstop - (column % tabstop);
                    else
                       ++column;
                }

                int count = tabstop - (column % tabstop);
                display_buffer.replace_atom_content(atom_it,
                                                    std::string(count, ' '));
            }
        }
    }
}

void show_line_numbers(DisplayBuffer& display_buffer)
{
    const Buffer& buffer = display_buffer.front().begin().buffer();
    BufferCoord coord = buffer.line_and_column_at(display_buffer.begin()->begin());

    int last_line = buffer.line_and_column_at(display_buffer.back().end()-1).line;

    for (; coord.line <= last_line; ++coord.line)
    {
        BufferIterator line_start = buffer.iterator_at(coord);
        DisplayBuffer::iterator atom_it = display_buffer.atom_containing(line_start);
        if (atom_it != display_buffer.end())
        {
            if (atom_it->begin() != line_start)
            {
                if (not atom_it->splitable())
                    continue;

                atom_it = ++display_buffer.split(atom_it, line_start);
            }
            atom_it = display_buffer.insert(
                atom_it,
                DisplayAtom(atom_it->coord(),
                            atom_it->begin(), atom_it->begin(),
                            Color::Black, Color::White));

            char buffer[6];
            snprintf(buffer, 6, "%3d ", coord.line + 1);
            display_buffer.replace_atom_content(atom_it, buffer);
        }
    }
}

}
<|endoftext|>


<commit_before>#include "Halide.h"
#include <stdio.h>

#include "test/common/halide_test_dirs.h"

using namespace Halide;

void testCompileToOutput(Func j) {
    std::string fn_object = Internal::get_test_tmp_dir() + "compile_to_multitarget";
#ifdef _MSC_VER
    std::string expected_lib = fn_object + ".lib";
#else
    std::string expected_lib = fn_object + ".a";
#endif
    std::string expected_h = fn_object + ".h";

    Internal::ensure_no_file_exists(expected_lib);
    Internal::ensure_no_file_exists(expected_h);

    std::vector<Target> targets = {
        Target("x86-64-osx-profile-debug-avx2-avx-sse41"),
        Target("x86-64-osx-profile-debug-avx-sse41"),
        Target("x86-64-osx-profile-debug-sse41"),
        Target("x86-64-osx-profile-debug"),
        Target("x86-64-osx-profile"),
    };
    j.compile_to_multitarget_static_library(fn_object, j.infer_arguments(), targets);

    Internal::assert_file_exists(expected_lib);
    Internal::assert_file_exists(expected_h);
}

int main(int argc, char **argv) {
    Param<float> factor("factor");
    Func f, g, h, j;
    Var x, y;
    f(x, y) = x + y;
    g(x, y) = cast<float>(f(x, y) + f(x+1, y));
    h(x, y) = f(x, y) + g(x, y);
    j(x, y) = h(x, y) * 2 * factor;

    f.compute_root();
    g.compute_root();
    h.compute_root();

    testCompileToOutput(j);

    printf("Success!\n");
    return 0;
}
<commit_msg>Revert mistaken checkin<commit_after>#include "Halide.h"
#include <stdio.h>

#include "test/common/halide_test_dirs.h"

using namespace Halide;

void testCompileToOutput(Func j) {
    std::string fn_object = Internal::get_test_tmp_dir() + "compile_to_multitarget";
#ifdef _MSC_VER
    std::string expected_lib = fn_object + ".lib";
#else
    std::string expected_lib = fn_object + ".a";
#endif
    std::string expected_h = fn_object + ".h";

    Internal::ensure_no_file_exists(expected_lib);
    Internal::ensure_no_file_exists(expected_h);

    std::vector<Target> targets = {
        Target("host-profile-debug"),
        Target("host-profile"),
    };
    j.compile_to_multitarget_static_library(fn_object, j.infer_arguments(), targets);

    Internal::assert_file_exists(expected_lib);
    Internal::assert_file_exists(expected_h);
}

int main(int argc, char **argv) {
    Param<float> factor("factor");
    Func f, g, h, j;
    Var x, y;
    f(x, y) = x + y;
    g(x, y) = cast<float>(f(x, y) + f(x+1, y));
    h(x, y) = f(x, y) + g(x, y);
    j(x, y) = h(x, y) * 2 * factor;

    f.compute_root();
    g.compute_root();
    h.compute_root();

    testCompileToOutput(j);

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


<commit_before>#include "format.h"

#include <utf8.h>

#include "number.h"

namespace format {

bool parse(const std::string &fmt, Spec &spec)
{
    spec.fill = ' ';
    spec.align = 0;
    spec.alternate = false;
    spec.sign = 0;
    spec.width = -1;
    spec.thousands = false;
    spec.precision = -1;
    spec.type = 0;
    if (fmt.empty()) {
        return true;
    }
    size_t i = 0;
    if (fmt[i] == '<' || fmt[i] == '>' || fmt[i] == '=' || fmt[i] == '^') {
        spec.align = fmt[i];
        ++i;
    }
    if (fmt[i] == '+' || fmt[i] == '-' || fmt[i] == ' ') {
        spec.sign = fmt[i];
        ++i;
    }
    if (fmt[i] == '0') {
        spec.fill = '0';
        if (spec.align == 0) {
            spec.align = '=';
        }
        ++i;
    }
    if (isdigit(fmt[i])) {
        size_t end = 0;
        spec.width = std::stoi(fmt.substr(i), &end, 10);
        i += end;
    }
    if (fmt[i] == ',') {
        spec.thousands = true;
        ++i;
    }
    if (fmt[i] == '.') {
        ++i;
        size_t end = 0;
        spec.precision = std::stoi(fmt.substr(i), &end, 10);
        i += end;
    }
    spec.type = fmt[i];
    switch (spec.type) {
        case 0:
        case 's':
            if (spec.sign || spec.alternate || spec.align == '=') {
                return false;
            }
            break;
        case 'd':
        case 'x':
            return true;
        default:
            return false;
    }
    return true;
}

static std::string fillstr(const Spec &spec, int n)
{
    if (spec.fill < 128) {
        return std::string(n, static_cast<char>(spec.fill));
    }
    std::string r;
    while (n > 0) {
        utf8::append(spec.fill, std::back_inserter(r));
        n--;
    }
    return r;
}

std::string format(const std::string &str, const Spec &spec)
{
    static const char hexdigit[] = "0123456789abcdef";

    std::string r = str;
    if (spec.type == 'x') {
        Number x = number_from_string(str);
        r = "";
        Number base = number_from_uint32(16);
        // TODO: handle negative numbers
        while (not number_is_zero(x)) {
            r.push_back(hexdigit[number_to_uint32(number_modulo(x, base))]);
            x = number_floor(number_divide(x, base));
        }
        std::reverse(r.begin(), r.end());
    }
    if (spec.precision >= 0 && static_cast<int>(r.length()) > spec.precision) {
        r = r.substr(0, spec.precision);
    }
    if (spec.width >= 0) {
        int len = static_cast<int>(r.length());
        if (len < spec.width) {
            int space = spec.width - len;
            if (spec.align == 0 || spec.align == '<') {
                r += fillstr(spec, space);
            } else if (spec.align == '>' || spec.align == '=') {
                r = fillstr(spec, space) + r;
            } else if (spec.align == '^') {
                r = fillstr(spec, space/2) + r + fillstr(spec, space - space/2);
            }
        }
    }
    return r;
}

} // namespace format
<commit_msg>Add required include<commit_after>#include "format.h"

#include <algorithm>

#include <utf8.h>

#include "number.h"

namespace format {

bool parse(const std::string &fmt, Spec &spec)
{
    spec.fill = ' ';
    spec.align = 0;
    spec.alternate = false;
    spec.sign = 0;
    spec.width = -1;
    spec.thousands = false;
    spec.precision = -1;
    spec.type = 0;
    if (fmt.empty()) {
        return true;
    }
    size_t i = 0;
    if (fmt[i] == '<' || fmt[i] == '>' || fmt[i] == '=' || fmt[i] == '^') {
        spec.align = fmt[i];
        ++i;
    }
    if (fmt[i] == '+' || fmt[i] == '-' || fmt[i] == ' ') {
        spec.sign = fmt[i];
        ++i;
    }
    if (fmt[i] == '0') {
        spec.fill = '0';
        if (spec.align == 0) {
            spec.align = '=';
        }
        ++i;
    }
    if (isdigit(fmt[i])) {
        size_t end = 0;
        spec.width = std::stoi(fmt.substr(i), &end, 10);
        i += end;
    }
    if (fmt[i] == ',') {
        spec.thousands = true;
        ++i;
    }
    if (fmt[i] == '.') {
        ++i;
        size_t end = 0;
        spec.precision = std::stoi(fmt.substr(i), &end, 10);
        i += end;
    }
    spec.type = fmt[i];
    switch (spec.type) {
        case 0:
        case 's':
            if (spec.sign || spec.alternate || spec.align == '=') {
                return false;
            }
            break;
        case 'd':
        case 'x':
            return true;
        default:
            return false;
    }
    return true;
}

static std::string fillstr(const Spec &spec, int n)
{
    if (spec.fill < 128) {
        return std::string(n, static_cast<char>(spec.fill));
    }
    std::string r;
    while (n > 0) {
        utf8::append(spec.fill, std::back_inserter(r));
        n--;
    }
    return r;
}

std::string format(const std::string &str, const Spec &spec)
{
    static const char hexdigit[] = "0123456789abcdef";

    std::string r = str;
    if (spec.type == 'x') {
        Number x = number_from_string(str);
        r = "";
        Number base = number_from_uint32(16);
        // TODO: handle negative numbers
        while (not number_is_zero(x)) {
            r.push_back(hexdigit[number_to_uint32(number_modulo(x, base))]);
            x = number_floor(number_divide(x, base));
        }
        std::reverse(r.begin(), r.end());
    }
    if (spec.precision >= 0 && static_cast<int>(r.length()) > spec.precision) {
        r = r.substr(0, spec.precision);
    }
    if (spec.width >= 0) {
        int len = static_cast<int>(r.length());
        if (len < spec.width) {
            int space = spec.width - len;
            if (spec.align == 0 || spec.align == '<') {
                r += fillstr(spec, space);
            } else if (spec.align == '>' || spec.align == '=') {
                r = fillstr(spec, space) + r;
            } else if (spec.align == '^') {
                r = fillstr(spec, space/2) + r + fillstr(spec, space - space/2);
            }
        }
    }
    return r;
}

} // namespace format
<|endoftext|>


<commit_before>/** @file
 * @author Edouard DUPIN
 *
 * @copyright 2016, Edouard DUPIN, all right reserved
 *
 * @license MPL v2.0 (see license file)
 */

#include <eproperty/debug.hpp>
#include <eproperty/List.hpp>
#include <eproperty/Property.hpp>
#include <eproperty/InterfaceData.hpp>

eproperty::InterfaceData::InterfaceData() {

}

eproperty::InterfaceData::~InterfaceData() {
	clean();
}

// note this pointer is not allocated and not free at the end of the class
void eproperty::InterfaceData::add(eproperty::Property* _pointerOnProperty) {
	if (_pointerOnProperty == nullptr) {
		EPROPERTY_ERROR("Try to link a nullptr properties");
		return;
	}
	for (auto &it : m_list) {
		if(    it != nullptr
		    && it->getName() == _pointerOnProperty->getName()) {
			EPROPERTY_CRITICAL("2 property can not have the same name ... ==> generate runtime error");
		}
	}
	m_list.pushBack(_pointerOnProperty);
}

void eproperty::InterfaceData::clean() {
	// remove all pointer on these propertys
	m_list.clear();
}

// Note no lock is needed at this level, because the lock is done is the upper elements ...
// the property set might be done with a pool of property, allone, the overhed is bigger ...
bool eproperty::InterfaceData::set(const etk::String& _property, const etk::String& _value) {
	for (auto &it : m_list) {
		if(    it != nullptr
		    && it->getName() == _property) {
			it->setString(_value);
			return true;
		}
	}
	// can not find the propertys :
	return false;
}

etk::String eproperty::InterfaceData::get(const etk::String& _property) const {
	for (auto &it : m_list) {
		if(    it != nullptr
		    && it->getName() == _property) {
			return it->getString();
		}
	}
	return "???";
}

void eproperty::InterfaceData::display(bool _changeOnly) const {
	EPROPERTY_INFO("    Object propertys:");
	for (auto &it : m_list) {
		if(it != nullptr) {
			etk::String paramName = it->getName();
			etk::String paramVal = it->getString();
			etk::String paramInfo = it->getInfo();
			if (    _changeOnly == false
			     || it->isDefault() == false) {
				EPROPERTY_INFO("    |       param='" << paramName << "' value=" << paramVal << "     (" << paramInfo << ")");
			}
		} else {
			EPROPERTY_INFO("    |       param=nullptr");
		}
	}
}

etk::Map<etk::String, etk::String> eproperty::InterfaceData::getAll(bool _notIfDefault) const {
	etk::Map<etk::String, etk::String> out;
	for (auto &it : m_list) {
		if(it != nullptr) {
			etk::String paramName = it->getName();
			etk::String paramVal = it->getString();
			if (    _notIfDefault == false
			     || it->isDefault() == false) {
				out.insert(etk::makePair(paramName, paramVal));
			}
		}
	}
	return out;
}

size_t eproperty::InterfaceData::size() const {
	return m_list.size();
}

eproperty::Property* eproperty::InterfaceData::getRaw(const size_t& _id) const {
	if (_id >= m_list.size()) {
		EPROPERTY_ERROR("Wrong ID for property list. " << _id << " >= " << m_list.size());
		return nullptr;
	}
	return m_list[_id];
}

eproperty::Property* eproperty::InterfaceData::getRaw(const etk::String _name) const {
	for (auto &it : m_list) {
		if(it->getName() == _name) {
			return it;
		}
	}
	return nullptr;
}

<commit_msg>[DEV] continue removing STL<commit_after>/** @file
 * @author Edouard DUPIN
 *
 * @copyright 2016, Edouard DUPIN, all right reserved
 *
 * @license MPL v2.0 (see license file)
 */

#include <eproperty/debug.hpp>
#include <eproperty/List.hpp>
#include <eproperty/Property.hpp>
#include <eproperty/InterfaceData.hpp>

eproperty::InterfaceData::InterfaceData() {

}

eproperty::InterfaceData::~InterfaceData() {
	clean();
}

// note this pointer is not allocated and not free at the end of the class
void eproperty::InterfaceData::add(eproperty::Property* _pointerOnProperty) {
	if (_pointerOnProperty == nullptr) {
		EPROPERTY_ERROR("Try to link a nullptr properties");
		return;
	}
	for (auto &it : m_list) {
		if(    it != nullptr
		    && it->getName() == _pointerOnProperty->getName()) {
			EPROPERTY_CRITICAL("2 property can not have the same name ... ==> generate runtime error");
		}
	}
	m_list.pushBack(_pointerOnProperty);
}

void eproperty::InterfaceData::clean() {
	// remove all pointer on these propertys
	m_list.clear();
}

// Note no lock is needed at this level, because the lock is done is the upper elements ...
// the property set might be done with a pool of property, allone, the overhed is bigger ...
bool eproperty::InterfaceData::set(const etk::String& _property, const etk::String& _value) {
	for (auto &it : m_list) {
		if(    it != nullptr
		    && it->getName() == _property) {
			it->setString(_value);
			return true;
		}
	}
	// can not find the propertys :
	return false;
}

etk::String eproperty::InterfaceData::get(const etk::String& _property) const {
	for (auto &it : m_list) {
		if(    it != nullptr
		    && it->getName() == _property) {
			return it->getString();
		}
	}
	return "???";
}

void eproperty::InterfaceData::display(bool _changeOnly) const {
	EPROPERTY_INFO("    Object propertys:");
	for (auto &it : m_list) {
		if(it != nullptr) {
			etk::String paramName = it->getName();
			etk::String paramVal = it->getString();
			etk::String paramInfo = it->getInfo();
			if (    _changeOnly == false
			     || it->isDefault() == false) {
				EPROPERTY_INFO("    |       param='" << paramName << "' value=" << paramVal << "     (" << paramInfo << ")");
			}
		} else {
			EPROPERTY_INFO("    |       param=nullptr");
		}
	}
}

etk::Map<etk::String, etk::String> eproperty::InterfaceData::getAll(bool _notIfDefault) const {
	etk::Map<etk::String, etk::String> out;
	for (auto &it : m_list) {
		if(it != nullptr) {
			etk::String paramName = it->getName();
			etk::String paramVal = it->getString();
			if (    _notIfDefault == false
			     || it->isDefault() == false) {
				out.set(paramName, paramVal);
			}
		}
	}
	return out;
}

size_t eproperty::InterfaceData::size() const {
	return m_list.size();
}

eproperty::Property* eproperty::InterfaceData::getRaw(const size_t& _id) const {
	if (_id >= m_list.size()) {
		EPROPERTY_ERROR("Wrong ID for property list. " << _id << " >= " << m_list.size());
		return nullptr;
	}
	return m_list[_id];
}

eproperty::Property* eproperty::InterfaceData::getRaw(const etk::String _name) const {
	for (auto &it : m_list) {
		if(it->getName() == _name) {
			return it;
		}
	}
	return nullptr;
}

<|endoftext|>


<commit_before>// Copyright (C) 2015 Alexandre Janniaux
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Core/Posix/MutexImpl.hpp>
#include <Nazara/Core/Debug.hpp>

NzMutexImpl::NzMutexImpl()
{
	pthread_mutex_init(&m_handle, nullptr);
}

NzMutexImpl::~NzMutexImpl()
{
	pthread_mutex_destroy(&m_handle);
}

void NzMutexImpl::Lock()
{
	pthread_mutex_lock(&m_handle);
}

bool NzMutexImpl::TryLock()
{
	return pthread_mutex_trylock(&m_handle) == 0;
}

void NzMutexImpl::Unlock()
{
	pthread_mutex_unlock(&m_handle);
}
<commit_msg>NzMutex is now a recursive mutex<commit_after>// Copyright (C) 2015 Alexandre Janniaux
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Core/Posix/MutexImpl.hpp>
#include <Nazara/Core/Debug.hpp>

NzMutexImpl::NzMutexImpl()
{
	pthread_mutexattr_t attr;
	pthread_mutexattr_init(&attr);
	pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);

	pthread_mutex_init(&m_handle, &attr);
}

NzMutexImpl::~NzMutexImpl()
{
	pthread_mutex_destroy(&m_handle);
}

void NzMutexImpl::Lock()
{
	pthread_mutex_lock(&m_handle);
}

bool NzMutexImpl::TryLock()
{
	return pthread_mutex_trylock(&m_handle) == 0;
}

void NzMutexImpl::Unlock()
{
	pthread_mutex_unlock(&m_handle);
}
<|endoftext|>