<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <stdio.h>
#include <string>
#include <vector>

#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/common.h"
#include "webrtc/modules/audio_coding/main/interface/audio_coding_module.h"
#include "webrtc/modules/audio_coding/main/test/APITest.h"
#include "webrtc/modules/audio_coding/main/test/EncodeDecodeTest.h"
#include "webrtc/modules/audio_coding/main/test/iSACTest.h"
#include "webrtc/modules/audio_coding/main/test/opus_test.h"
#include "webrtc/modules/audio_coding/main/test/TestAllCodecs.h"
#include "webrtc/modules/audio_coding/main/test/TestFEC.h"
#include "webrtc/modules/audio_coding/main/test/TestStereo.h"
#include "webrtc/modules/audio_coding/main/test/TestVADDTX.h"
#include "webrtc/modules/audio_coding/main/test/TwoWayCommunication.h"
#include "webrtc/modules/audio_coding/main/test/utility.h"
#include "webrtc/system_wrappers/interface/trace.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/test/testsupport/gtest_disable.h"

using webrtc::Trace;

// This parameter is used to describe how to run the tests. It is normally
// set to 0, and all tests are run in quite mode.
#define ACM_TEST_MODE 0

TEST(AudioCodingModuleTest, TestAllCodecs) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
          "acm_allcodecs_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::TestAllCodecs(ACM_TEST_MODE, config).Perform();

  UseNewAcm(&config);
  webrtc::TestAllCodecs(ACM_TEST_MODE, config).Perform();

  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestEncodeDecode)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_encodedecode_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::EncodeDecodeTest(ACM_TEST_MODE, config).Perform();

  UseNewAcm(&config);
  webrtc::EncodeDecodeTest(ACM_TEST_MODE, config).Perform();

  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestFEC)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_fec_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::TestFEC(config).Perform();

  UseNewAcm(&config);
  webrtc::TestFEC(config).Perform();

  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestIsac)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_isac_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::ISACTest(ACM_TEST_MODE, config).Perform();

  UseNewAcm(&config);
  webrtc::ISACTest(ACM_TEST_MODE, config).Perform();

  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TwoWayCommunication)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_twowaycom_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::TwoWayCommunication(ACM_TEST_MODE, config).Perform();

  UseNewAcm(&config);
  webrtc::TwoWayCommunication(ACM_TEST_MODE, config).Perform();

  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestStereo)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_stereo_trace.txt").c_str());

  webrtc::Config config;
  UseLegacyAcm(&config);

  webrtc::TestStereo(ACM_TEST_MODE, config).Perform();
  UseNewAcm(&config);

  webrtc::TestStereo(ACM_TEST_MODE, config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestVADDTX)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_vaddtx_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::TestVADDTX(config).Perform();

  UseNewAcm(&config);
  webrtc::TestVADDTX(config).Perform();

  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, TestOpus) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_opus_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::OpusTest(config).Perform();

  UseNewAcm(&config);
  webrtc::OpusTest(config).Perform();

  Trace::ReturnTrace();
}

// The full API test is too long to run automatically on bots, but can be used
// for offline testing. User interaction is needed.
#ifdef ACM_TEST_FULL_API
  TEST(AudioCodingModuleTest, TestAPI) {
    Trace::CreateTrace();
    Trace::SetTraceFile((webrtc::test::OutputPath() +
        "acm_apitest_trace.txt").c_str());
    webrtc::Config config;

    UseLegacyAcm(&config);
    webrtc::APITest(config).Perform();

    UseNewAcm(&config);
    webrtc::APITest(config).Perform();

    Trace::ReturnTrace();
  }
#endif
<commit_msg>This CL separate all ACM tests with new and old implementation of ACM and NetEq. The reason is to debug an issue with failure on Android try bots. We need to see if the error only occurs with the new ACM/NetEq, or if it is a flakiness that affects both.<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <stdio.h>
#include <string>
#include <vector>

#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/common.h"
#include "webrtc/modules/audio_coding/main/interface/audio_coding_module.h"
#include "webrtc/modules/audio_coding/main/test/APITest.h"
#include "webrtc/modules/audio_coding/main/test/EncodeDecodeTest.h"
#include "webrtc/modules/audio_coding/main/test/iSACTest.h"
#include "webrtc/modules/audio_coding/main/test/opus_test.h"
#include "webrtc/modules/audio_coding/main/test/TestAllCodecs.h"
#include "webrtc/modules/audio_coding/main/test/TestFEC.h"
#include "webrtc/modules/audio_coding/main/test/TestStereo.h"
#include "webrtc/modules/audio_coding/main/test/TestVADDTX.h"
#include "webrtc/modules/audio_coding/main/test/TwoWayCommunication.h"
#include "webrtc/modules/audio_coding/main/test/utility.h"
#include "webrtc/system_wrappers/interface/trace.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/test/testsupport/gtest_disable.h"

using webrtc::Trace;

// This parameter is used to describe how to run the tests. It is normally
// set to 0, and all tests are run in quite mode.
#define ACM_TEST_MODE 0

TEST(AudioCodingModuleTest, TestAllCodecs) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
          "acm_allcodecs_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::TestAllCodecs(ACM_TEST_MODE, config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, TestAllCodecsNewACM) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
          "acm_allcodecs_trace_new.txt").c_str());
  webrtc::Config config;

  UseNewAcm(&config);
  webrtc::TestAllCodecs(ACM_TEST_MODE, config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestEncodeDecode)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_encodedecode_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::EncodeDecodeTest(ACM_TEST_MODE, config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestEncodeDecodeNewACM)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_encodedecode_trace_new.txt").c_str());
  webrtc::Config config;

  UseNewAcm(&config);
  webrtc::EncodeDecodeTest(ACM_TEST_MODE, config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestFEC)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_fec_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::TestFEC(config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestFECNewACM)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_fec_trace_new.txt").c_str());
  webrtc::Config config;

  UseNewAcm(&config);
  webrtc::TestFEC(config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestIsac)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_isac_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::ISACTest(ACM_TEST_MODE, config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestIsacNewACM)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_isac_trace_new.txt").c_str());
  webrtc::Config config;

  UseNewAcm(&config);
  webrtc::ISACTest(ACM_TEST_MODE, config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TwoWayCommunication)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_twowaycom_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::TwoWayCommunication(ACM_TEST_MODE, config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TwoWayCommunicationNewACM)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_twowaycom_trace_new.txt").c_str());
  webrtc::Config config;

  UseNewAcm(&config);
  webrtc::TwoWayCommunication(ACM_TEST_MODE, config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestStereo)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_stereo_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::TestStereo(ACM_TEST_MODE, config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestStereoNewACM)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_stereo_trace_new.txt").c_str());
  webrtc::Config config;

  UseNewAcm(&config);
  webrtc::TestStereo(ACM_TEST_MODE, config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestVADDTX)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_vaddtx_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::TestVADDTX(config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, DISABLED_ON_ANDROID(TestVADDTXNewACM)) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_vaddtx_trace_new.txt").c_str());
  webrtc::Config config;

  UseNewAcm(&config);
  webrtc::TestVADDTX(config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, TestOpus) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_opus_trace.txt").c_str());
  webrtc::Config config;

  UseLegacyAcm(&config);
  webrtc::OpusTest(config).Perform();
  Trace::ReturnTrace();
}

TEST(AudioCodingModuleTest, TestOpusNewACM) {
  Trace::CreateTrace();
  Trace::SetTraceFile((webrtc::test::OutputPath() +
      "acm_opus_trace_new.txt").c_str());
  webrtc::Config config;

  UseNewAcm(&config);
  webrtc::OpusTest(config).Perform();
  Trace::ReturnTrace();
}

// The full API test is too long to run automatically on bots, but can be used
// for offline testing. User interaction is needed.
#ifdef ACM_TEST_FULL_API
  TEST(AudioCodingModuleTest, TestAPI) {
    Trace::CreateTrace();
    Trace::SetTraceFile((webrtc::test::OutputPath() +
        "acm_apitest_trace.txt").c_str());
    webrtc::Config config;

    UseLegacyAcm(&config);
    webrtc::APITest(config).Perform();

    UseNewAcm(&config);
    webrtc::APITest(config).Perform();

    Trace::ReturnTrace();
  }
#endif
<|endoftext|>


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

#include <iostream>
#include <string>

#define DEF_ACTORSYSTEM_NOINLINE      // Excluding the static ActorSystem * ActorSystem::createAndStartSystem() method

#include "Pi.h"

class foo {
public:
    void test() {
        std::cout << "foo::test();" << std::endl;
    }

    static void bar() {
        std::cout << "foo::bar();" << std::endl;
    }
};

int main(int argn, char * argv[])
{
    only_test_for_api_export();

    ActorBase * actorBase = new ActorBase();
    IActorContext * context = actorBase->getActorContext();
    if (actorBase)
        delete actorBase;

    ActorSystem * actorSystem = ActorSystem::create("Factorial N");
    std::string systemName = actorSystem->getName();
    printf("Welcome to use Akee!\n", 0);
    printf("ActorSystem Name: %s.\n", systemName.c_str());
    printf("\n");

    class foo foo;
    foo.test();

    Pi::main(argn, argv);

    //int numOfWorkers = 4;
    //WorkerRouter workerRouter = actorSystem->getContext().actorOf(new Props(Worker.class()).withRouter(new RoundRobinRounter(numOfWorkers)));

    if (actorSystem)
        delete actorSystem;
    system("pause");
    return 0;
}
<commit_msg>小修改.<commit_after>
#include <stdio.h>
#include <stdlib.h>

#include <iostream>
#include <string>

#define DEF_ACTORSYSTEM_NOINLINE      // Excluding the static ActorSystem * ActorSystem::createAndStartSystem() method

#include "Pi.h"

class foo {
public:
    void test() {
        std::cout << "foo::test();" << std::endl;
    }

    static void bar() {
        std::cout << "foo::bar();" << std::endl;
    }
};

int main(int argn, char * argv[])
{
    only_test_for_api_export();

    ActorBase * actorBase = new ActorBase();
    IActorContext * context = actorBase->getActorContext();
    if (actorBase)
        delete actorBase;

    ActorSystem * actorSystem = ActorSystem::create("Factorial N");
    std::string systemName = actorSystem->getName();
    printf("Welcome to use Akee!\n", 0);
    printf("ActorSystem Name: %s.\n", systemName.c_str());
    printf("\n");

    class foo foo;
    foo.test();

    if (actorSystem)
        delete actorSystem;

    Pi::main(argn, argv);

    system("pause");
    return 0;
}
<|endoftext|>


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

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

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

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

#include "tensorflow/core/kernels/lookup_util.h"

#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/io/inputbuffer.h"

namespace tensorflow {
namespace lookup {
namespace {

static const int kInputBufferSize = 1 * 1024 * 1024; /* bytes */
static const int kLineNumber = -1;
static const int kWholeLine = -2;

Status GetNumLinesInTextFile(Env* env, const string& vocab_file,
                             int64* num_lines) {
  std::unique_ptr<RandomAccessFile> file;
  TF_RETURN_IF_ERROR(env->NewRandomAccessFile(vocab_file, &file));

  io::InputBuffer input_buffer(file.get(), kInputBufferSize);
  string line;
  Status s = input_buffer.ReadLine(&line);
  int64 next_id = 0;
  while (s.ok()) {
    next_id++;
    s = input_buffer.ReadLine(&line);
  }
  if (!errors::IsOutOfRange(s)) {
    return s;
  }
  *num_lines = next_id;
  return Status::OK();
}

// Iterator that reads a text file. Each iteration process one line, it parses
// the line and populates the keys and values tensors used for initialization
// with a single key and corresponding value.
//
// What information of the line to populate the key or values is specified by
// providing key_index and value_index.
class TextFileLineIterator
    : public InitializableLookupTable::InitTableIterator {
 public:
  TextFileLineIterator()
      : valid_(false),
        vocab_size_(-1),
        status_(errors::FailedPrecondition("Not initialized")) {}

  // Initialize iterator.
  //
  // Prepares the file 'filename' and sets the data types to return the keys and
  // values tensors. It requires the indices of the tokens in the line given a
  // delimiter to specify where to pick the data from.
  //
  // - Index -2 means the entire line as string.
  // - Index -1 means the line number stored in int64.
  // - Index >= 0 represent index (starting at zero) of the split line based on
  //   delimiter.
  Status Init(const string& filename, int64 vocab_size, char delimiter,
              DataType key_dtype, int64 key_index, DataType value_dtype,
              int64 value_index, Env* env) {
    filename_ = filename;
    vocab_size_ = vocab_size;
    delimiter_ = delimiter;
    key_ = Tensor(key_dtype, TensorShape({}));
    value_ = Tensor(value_dtype, TensorShape({}));
    key_index_ = key_index;
    value_index_ = value_index;
    env_ = env;

    status_ = env->NewRandomAccessFile(filename_, &file_);
    if (!status_.ok()) return status_;

    input_buffer_.reset(new io::InputBuffer(file_.get(), kInputBufferSize));
    valid_ = true;
    next_id_ = 0;
    ignore_split_ = std::max(key_index_, value_index_) < 0;
    Next();
    return status_;
  }

  void Next() override {
    if (!valid_) return;

    string line;
    status_ = input_buffer_->ReadLine(&line);
    if (!status_.ok()) {
      if (errors::IsOutOfRange(status_) && vocab_size_ != -1 &&
          next_id_ != vocab_size_) {
        status_ = errors::InvalidArgument("Invalid vocab_size in ", filename_,
                                          ": expected ", vocab_size_,
                                          " but got ", next_id_);
      }
      valid_ = false;
      return;
    }
    if (vocab_size_ != -1 && next_id_ >= vocab_size_) {
      LOG(WARNING) << "Truncated " << filename_ << " before its end at "
                   << vocab_size_ << " records.";
      LOG(WARNING) << "next_id_  : " << next_id_;
      status_ = errors::OutOfRange("Finished reading ", vocab_size_,
                                   " of lines from ", filename_);
      valid_ = false;
      return;
    }
    if (line.empty()) {
      status_ = errors::InvalidArgument("Invalid content in ", filename_,
                                        ": empty line found at position ",
                                        input_buffer_->Tell(), ".");
      valid_ = false;
      return;
    }

    std::vector<string> tokens;
    if (!ignore_split_) {
      tokens = str_util::Split(line, delimiter_);
      if (std::max(key_index_, value_index_) >= tokens.size()) {
        status_ = errors::InvalidArgument(
            "Invalid number of columns in ", filename_, " line ", next_id_,
            " (", line, ") : expected ", std::max(key_index_, value_index_),
            " got ", tokens.size());
        valid_ = false;
        return;
      }
    }
    status_ = SetValue(line, tokens, key_index_, &key_);
    if (!status_.ok()) {
      valid_ = false;
      return;
    }
    status_ = SetValue(line, tokens, value_index_, &value_);
    if (!status_.ok()) {
      valid_ = false;
      return;
    }

    next_id_++;
  }

  bool Valid() const override { return valid_; }

  const Tensor& keys() const override { return key_; }

  const Tensor& values() const override { return value_; }

  Status status() const override { return status_; }

  int64 total_size() const override {
    if (vocab_size_ == -1) {
      int64 new_size;
      Status status = GetNumLinesInTextFile(env_, filename_, &new_size);
      if (!status.ok()) {
        LOG(WARNING) << "Unable to get line count: " << status;
        new_size = -1;
      }
      *const_cast<int64*>(&vocab_size_) = new_size;
    }
    return vocab_size_;
  }

 private:
  Tensor key_;
  Tensor value_;
  bool valid_;  // true if the iterator points to an existing range.
  int64 key_index_;
  int64 value_index_;
  Env* env_;
  int64 next_id_;
  int64 vocab_size_;
  string filename_;
  char delimiter_;
  Status status_;
  bool ignore_split_;
  std::unique_ptr<RandomAccessFile> file_;  // must outlive input_buffer_
  std::unique_ptr<io::InputBuffer> input_buffer_;

  // Set the corresponding value from line or tokens based on 'index' into the
  // tensor 't'. The value is transformed to the given data type 'dtype'.
  Status SetValue(const string& line, const std::vector<string>& tokens,
                  int64 index, Tensor* tensor) {
    if (index == kLineNumber) {
      tensor->flat<int64>()(0) = next_id_;
      return Status::OK();
    }
    const string& token = (index == kWholeLine) ? line : tokens[index];
    const DataType& dtype = tensor->dtype();
    switch (dtype) {
      case DT_INT32: {
        int32 value;
        if (!strings::safe_strto32(token.c_str(), &value)) {
          valid_ = false;
          return errors::InvalidArgument("Field ", token, " in line ", next_id_,
                                         " is not a valid int32.");
        }
        tensor->flat<int32>()(0) = value;
      } break;
      case DT_INT64: {
        int64 value;
        if (!strings::safe_strto64(token.c_str(), &value)) {
          valid_ = false;
          return errors::InvalidArgument("Field ", token, " in line ", next_id_,
                                         " is not a valid int64.");
        }
        tensor->flat<int64>()(0) = value;
      } break;
      case DT_FLOAT: {
        float value;
        if (!strings::safe_strtof(token.c_str(), &value)) {
          valid_ = false;
          return errors::InvalidArgument("Field ", token, " in line ", next_id_,
                                         " is not a valid float.");
        }
        tensor->flat<float>()(0) = value;
      } break;
      case DT_DOUBLE: {
        double value;
        if (!strings::safe_strtod(token.c_str(), &value)) {
          valid_ = false;
          return errors::InvalidArgument("Field ", token, " in line ", next_id_,
                                         " is not a valid double.");
        }
        tensor->flat<double>()(0) = value;
      } break;
      case DT_STRING:
        tensor->flat<string>()(0) = token;
        break;
      default:
        valid_ = false;
        return errors::InvalidArgument("Data type ", DataTypeString(dtype),
                                       " not supported.");
    }
    return Status::OK();
  }

  TF_DISALLOW_COPY_AND_ASSIGN(TextFileLineIterator);
};

Status GetTableHandle(const string& input_name, OpKernelContext* ctx,
                      string* container, string* table_handle) {
  {
    mutex* mu;
    TF_RETURN_IF_ERROR(ctx->input_ref_mutex(input_name, &mu));
    mutex_lock l(*mu);
    Tensor tensor;
    TF_RETURN_IF_ERROR(ctx->mutable_input(input_name, &tensor, true));
    if (tensor.NumElements() != 2) {
      return errors::InvalidArgument(
          "Lookup table handle must be scalar, but had shape: ",
          tensor.shape().DebugString());
    }
    auto h = tensor.flat<string>();
    *container = h(0);
    *table_handle = h(1);
  }
  return Status::OK();
}

}  // namespace

Status GetLookupTable(const string& input_name, OpKernelContext* ctx,
                      LookupInterface** table) {
  string container;
  string table_handle;
  DataType handle_dtype;
  TF_RETURN_IF_ERROR(ctx->input_dtype(input_name, &handle_dtype));
  if (handle_dtype == DT_RESOURCE) {
    ResourceHandle handle;
    TF_RETURN_IF_ERROR(HandleFromInput(ctx, input_name, &handle));
    return LookupResource(ctx, handle, table);
  } else {
    TF_RETURN_IF_ERROR(
        GetTableHandle(input_name, ctx, &container, &table_handle));
    return ctx->resource_manager()->Lookup(container, table_handle, table);
  }
}

Status GetInitializableLookupTable(const string& input_name,
                                   OpKernelContext* ctx,
                                   InitializableLookupTable** table) {
  LookupInterface* lookup_table;
  DataType handle_dtype;
  TF_RETURN_IF_ERROR(ctx->input_dtype(input_name, &handle_dtype));
  if (handle_dtype == DT_RESOURCE) {
    ResourceHandle handle;
    TF_RETURN_IF_ERROR(HandleFromInput(ctx, input_name, &handle));
    TF_RETURN_IF_ERROR(LookupResource(ctx, handle, &lookup_table));
    *table = lookup_table->GetInitializableLookupTable();
    if (*table == nullptr) {
      lookup_table->Unref();
      return errors::InvalidArgument("Table ", handle.container(), " ",
                                     handle.name(), " is not initializable");
    }
  } else {
    string container;
    string table_handle;
    TF_RETURN_IF_ERROR(
        GetTableHandle(input_name, ctx, &container, &table_handle));
    TF_RETURN_IF_ERROR(ctx->resource_manager()->Lookup(container, table_handle,
                                                       &lookup_table));
    *table = lookup_table->GetInitializableLookupTable();
    if (*table == nullptr) {
      lookup_table->Unref();
      return errors::InvalidArgument("Table ", container, " ", table_handle,
                                     " is not initializable");
    }
  }
  return Status::OK();
}

Status CheckTableDataTypes(const LookupInterface& table, DataType key_dtype,
                           DataType value_dtype, const string& table_name) {
  if (table.key_dtype() != key_dtype || table.value_dtype() != value_dtype) {
    return errors::InvalidArgument(
        "Conflicting key/value dtypes ", DataTypeString(key_dtype), "->",
        DataTypeString(value_dtype), " with ",
        DataTypeString(table.key_dtype()), "-",
        DataTypeString(table.value_dtype()), " for table ", table_name);
  }
  return Status::OK();
}

// Helper function to initialize an InitializableLookupTable from a text file.
Status InitializeTableFromTextFile(const string& filename, int64 vocab_size,
                                   char delimiter, int32 key_index,
                                   int32 value_index, Env* env,
                                   InitializableLookupTable* table) {
  if (key_index == kLineNumber && table->key_dtype() != DT_INT64) {
    return errors::InvalidArgument(
        "Key index for line number requires table key dtype of int64, got ",
        DataTypeString(table->key_dtype()));
  }
  const DataType& key_dtype = table->key_dtype();
  const DataType& value_dtype = table->value_dtype();
  if (key_index == kWholeLine && !DataTypeIsInteger(key_dtype) &&
      key_dtype != DT_STRING) {
    return errors::InvalidArgument(
        "Key index for whole line requires string or integer table key, got ",
        DataTypeString(table->key_dtype()));
  }
  if (value_index == kLineNumber && value_dtype != DT_INT64) {
    return errors::InvalidArgument(
        "Value index for line number requires table value dtype of int64, got ",
        DataTypeString(table->value_dtype()));
  }
  if (value_index == kWholeLine && value_dtype != DT_STRING) {
    return errors::InvalidArgument(
        "Value index for whole line requires table value dtype of string, got ",
        DataTypeString(table->value_dtype()));
  }

  TextFileLineIterator iter;
  TF_RETURN_IF_ERROR(iter.Init(filename, vocab_size, delimiter, key_dtype,
                               key_index, value_dtype, value_index, env));
  // For initialization from files, ignore if the table is already
  // initialized. The table shared name should contain the filename to
  // avoid trying to initialize the same table from the same file at the same
  // time.
  Status s = table->Initialize(iter);
  if (errors::IsFailedPrecondition(s) && table->is_initialized()) {
    LOG(INFO) << "Table trying to initialize from file " << filename
              << " is already initialized.";
    return Status::OK();
  }
  return s;
}

}  // namespace lookup
}  // namespace tensorflow
<commit_msg>Fixed warning in the file<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

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

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

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

#include "tensorflow/core/kernels/lookup_util.h"

#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/io/inputbuffer.h"

namespace tensorflow {
namespace lookup {
namespace {

static const int kInputBufferSize = 1 * 1024 * 1024; /* bytes */
static const int kLineNumber = -1;
static const int kWholeLine = -2;

Status GetNumLinesInTextFile(Env* env, const string& vocab_file,
                             int64* num_lines) {
  std::unique_ptr<RandomAccessFile> file;
  TF_RETURN_IF_ERROR(env->NewRandomAccessFile(vocab_file, &file));

  io::InputBuffer input_buffer(file.get(), kInputBufferSize);
  string line;
  Status s = input_buffer.ReadLine(&line);
  int64 next_id = 0;
  while (s.ok()) {
    next_id++;
    s = input_buffer.ReadLine(&line);
  }
  if (!errors::IsOutOfRange(s)) {
    return s;
  }
  *num_lines = next_id;
  return Status::OK();
}

// Iterator that reads a text file. Each iteration process one line, it parses
// the line and populates the keys and values tensors used for initialization
// with a single key and corresponding value.
//
// What information of the line to populate the key or values is specified by
// providing key_index and value_index.
class TextFileLineIterator
    : public InitializableLookupTable::InitTableIterator {
 public:
  TextFileLineIterator()
      : valid_(false),
        vocab_size_(-1),
        status_(errors::FailedPrecondition("Not initialized")) {}

  // Initialize iterator.
  //
  // Prepares the file 'filename' and sets the data types to return the keys and
  // values tensors. It requires the indices of the tokens in the line given a
  // delimiter to specify where to pick the data from.
  //
  // - Index -2 means the entire line as string.
  // - Index -1 means the line number stored in int64.
  // - Index >= 0 represent index (starting at zero) of the split line based on
  //   delimiter.
  Status Init(const string& filename, int64 vocab_size, char delimiter,
              DataType key_dtype, int64 key_index, DataType value_dtype,
              int64 value_index, Env* env) {
    filename_ = filename;
    vocab_size_ = vocab_size;
    delimiter_ = delimiter;
    key_ = Tensor(key_dtype, TensorShape({}));
    value_ = Tensor(value_dtype, TensorShape({}));
    key_index_ = key_index;
    value_index_ = value_index;
    env_ = env;

    status_ = env->NewRandomAccessFile(filename_, &file_);
    if (!status_.ok()) return status_;

    input_buffer_.reset(new io::InputBuffer(file_.get(), kInputBufferSize));
    valid_ = true;
    next_id_ = 0;
    ignore_split_ = std::max(key_index_, value_index_) < 0;
    Next();
    return status_;
  }

  void Next() override {
    if (!valid_) return;

    string line;
    status_ = input_buffer_->ReadLine(&line);
    if (!status_.ok()) {
      if (errors::IsOutOfRange(status_) && vocab_size_ != -1 &&
          next_id_ != vocab_size_) {
        status_ = errors::InvalidArgument("Invalid vocab_size in ", filename_,
                                          ": expected ", vocab_size_,
                                          " but got ", next_id_);
      }
      valid_ = false;
      return;
    }
    if (vocab_size_ != -1 && next_id_ >= vocab_size_) {
      LOG(WARNING) << "Truncated " << filename_ << " before its end at "
                   << vocab_size_ << " records.";
      LOG(WARNING) << "next_id_  : " << next_id_;
      status_ = errors::OutOfRange("Finished reading ", vocab_size_,
                                   " of lines from ", filename_);
      valid_ = false;
      return;
    }
    if (line.empty()) {
      status_ = errors::InvalidArgument("Invalid content in ", filename_,
                                        ": empty line found at position ",
                                        input_buffer_->Tell(), ".");
      valid_ = false;
      return;
    }

    std::vector<string> tokens;
    if (!ignore_split_) {
      tokens = str_util::Split(line, delimiter_);
      if (std::max(key_index_, value_index_) >= tokens.size()) {
        status_ = errors::InvalidArgument(
            "Invalid number of columns in ", filename_, " line ", next_id_,
            " (", line, ") : expected ", std::max(key_index_, value_index_),
            " got ", tokens.size());
        valid_ = false;
        return;
      }
    }
    status_ = SetValue(line, tokens, key_index_, &key_);
    if (!status_.ok()) {
      valid_ = false;
      return;
    }
    status_ = SetValue(line, tokens, value_index_, &value_);
    if (!status_.ok()) {
      valid_ = false;
      return;
    }

    next_id_++;
  }

  bool Valid() const override { return valid_; }

  const Tensor& keys() const override { return key_; }

  const Tensor& values() const override { return value_; }

  Status status() const override { return status_; }

  int64 total_size() const override {
    if (vocab_size_ == -1) {
      int64 new_size = -1;
      Status status = GetNumLinesInTextFile(env_, filename_, &new_size);
      if (!status.ok()) {
        LOG(WARNING) << "Unable to get line count: " << status;
        new_size = -1;
      }
      *const_cast<int64*>(&vocab_size_) = new_size;
    }
    return vocab_size_;
  }

 private:
  Tensor key_;
  Tensor value_;
  bool valid_;  // true if the iterator points to an existing range.
  int64 key_index_;
  int64 value_index_;
  Env* env_;
  int64 next_id_;
  int64 vocab_size_;
  string filename_;
  char delimiter_;
  Status status_;
  bool ignore_split_;
  std::unique_ptr<RandomAccessFile> file_;  // must outlive input_buffer_
  std::unique_ptr<io::InputBuffer> input_buffer_;

  // Set the corresponding value from line or tokens based on 'index' into the
  // tensor 't'. The value is transformed to the given data type 'dtype'.
  Status SetValue(const string& line, const std::vector<string>& tokens,
                  int64 index, Tensor* tensor) {
    if (index == kLineNumber) {
      tensor->flat<int64>()(0) = next_id_;
      return Status::OK();
    }
    const string& token = (index == kWholeLine) ? line : tokens[index];
    const DataType& dtype = tensor->dtype();
    switch (dtype) {
      case DT_INT32: {
        int32 value;
        if (!strings::safe_strto32(token.c_str(), &value)) {
          valid_ = false;
          return errors::InvalidArgument("Field ", token, " in line ", next_id_,
                                         " is not a valid int32.");
        }
        tensor->flat<int32>()(0) = value;
      } break;
      case DT_INT64: {
        int64 value;
        if (!strings::safe_strto64(token.c_str(), &value)) {
          valid_ = false;
          return errors::InvalidArgument("Field ", token, " in line ", next_id_,
                                         " is not a valid int64.");
        }
        tensor->flat<int64>()(0) = value;
      } break;
      case DT_FLOAT: {
        float value;
        if (!strings::safe_strtof(token.c_str(), &value)) {
          valid_ = false;
          return errors::InvalidArgument("Field ", token, " in line ", next_id_,
                                         " is not a valid float.");
        }
        tensor->flat<float>()(0) = value;
      } break;
      case DT_DOUBLE: {
        double value;
        if (!strings::safe_strtod(token.c_str(), &value)) {
          valid_ = false;
          return errors::InvalidArgument("Field ", token, " in line ", next_id_,
                                         " is not a valid double.");
        }
        tensor->flat<double>()(0) = value;
      } break;
      case DT_STRING:
        tensor->flat<string>()(0) = token;
        break;
      default:
        valid_ = false;
        return errors::InvalidArgument("Data type ", DataTypeString(dtype),
                                       " not supported.");
    }
    return Status::OK();
  }

  TF_DISALLOW_COPY_AND_ASSIGN(TextFileLineIterator);
};

Status GetTableHandle(const string& input_name, OpKernelContext* ctx,
                      string* container, string* table_handle) {
  {
    mutex* mu;
    TF_RETURN_IF_ERROR(ctx->input_ref_mutex(input_name, &mu));
    mutex_lock l(*mu);
    Tensor tensor;
    TF_RETURN_IF_ERROR(ctx->mutable_input(input_name, &tensor, true));
    if (tensor.NumElements() != 2) {
      return errors::InvalidArgument(
          "Lookup table handle must be scalar, but had shape: ",
          tensor.shape().DebugString());
    }
    auto h = tensor.flat<string>();
    *container = h(0);
    *table_handle = h(1);
  }
  return Status::OK();
}

}  // namespace

Status GetLookupTable(const string& input_name, OpKernelContext* ctx,
                      LookupInterface** table) {
  string container;
  string table_handle;
  DataType handle_dtype;
  TF_RETURN_IF_ERROR(ctx->input_dtype(input_name, &handle_dtype));
  if (handle_dtype == DT_RESOURCE) {
    ResourceHandle handle;
    TF_RETURN_IF_ERROR(HandleFromInput(ctx, input_name, &handle));
    return LookupResource(ctx, handle, table);
  } else {
    TF_RETURN_IF_ERROR(
        GetTableHandle(input_name, ctx, &container, &table_handle));
    return ctx->resource_manager()->Lookup(container, table_handle, table);
  }
}

Status GetInitializableLookupTable(const string& input_name,
                                   OpKernelContext* ctx,
                                   InitializableLookupTable** table) {
  LookupInterface* lookup_table;
  DataType handle_dtype;
  TF_RETURN_IF_ERROR(ctx->input_dtype(input_name, &handle_dtype));
  if (handle_dtype == DT_RESOURCE) {
    ResourceHandle handle;
    TF_RETURN_IF_ERROR(HandleFromInput(ctx, input_name, &handle));
    TF_RETURN_IF_ERROR(LookupResource(ctx, handle, &lookup_table));
    *table = lookup_table->GetInitializableLookupTable();
    if (*table == nullptr) {
      lookup_table->Unref();
      return errors::InvalidArgument("Table ", handle.container(), " ",
                                     handle.name(), " is not initializable");
    }
  } else {
    string container;
    string table_handle;
    TF_RETURN_IF_ERROR(
        GetTableHandle(input_name, ctx, &container, &table_handle));
    TF_RETURN_IF_ERROR(ctx->resource_manager()->Lookup(container, table_handle,
                                                       &lookup_table));
    *table = lookup_table->GetInitializableLookupTable();
    if (*table == nullptr) {
      lookup_table->Unref();
      return errors::InvalidArgument("Table ", container, " ", table_handle,
                                     " is not initializable");
    }
  }
  return Status::OK();
}

Status CheckTableDataTypes(const LookupInterface& table, DataType key_dtype,
                           DataType value_dtype, const string& table_name) {
  if (table.key_dtype() != key_dtype || table.value_dtype() != value_dtype) {
    return errors::InvalidArgument(
        "Conflicting key/value dtypes ", DataTypeString(key_dtype), "->",
        DataTypeString(value_dtype), " with ",
        DataTypeString(table.key_dtype()), "-",
        DataTypeString(table.value_dtype()), " for table ", table_name);
  }
  return Status::OK();
}

// Helper function to initialize an InitializableLookupTable from a text file.
Status InitializeTableFromTextFile(const string& filename, int64 vocab_size,
                                   char delimiter, int32 key_index,
                                   int32 value_index, Env* env,
                                   InitializableLookupTable* table) {
  if (key_index == kLineNumber && table->key_dtype() != DT_INT64) {
    return errors::InvalidArgument(
        "Key index for line number requires table key dtype of int64, got ",
        DataTypeString(table->key_dtype()));
  }
  const DataType& key_dtype = table->key_dtype();
  const DataType& value_dtype = table->value_dtype();
  if (key_index == kWholeLine && !DataTypeIsInteger(key_dtype) &&
      key_dtype != DT_STRING) {
    return errors::InvalidArgument(
        "Key index for whole line requires string or integer table key, got ",
        DataTypeString(table->key_dtype()));
  }
  if (value_index == kLineNumber && value_dtype != DT_INT64) {
    return errors::InvalidArgument(
        "Value index for line number requires table value dtype of int64, got ",
        DataTypeString(table->value_dtype()));
  }
  if (value_index == kWholeLine && value_dtype != DT_STRING) {
    return errors::InvalidArgument(
        "Value index for whole line requires table value dtype of string, got ",
        DataTypeString(table->value_dtype()));
  }

  TextFileLineIterator iter;
  TF_RETURN_IF_ERROR(iter.Init(filename, vocab_size, delimiter, key_dtype,
                               key_index, value_dtype, value_index, env));
  // For initialization from files, ignore if the table is already
  // initialized. The table shared name should contain the filename to
  // avoid trying to initialize the same table from the same file at the same
  // time.
  Status s = table->Initialize(iter);
  if (errors::IsFailedPrecondition(s) && table->is_initialized()) {
    LOG(INFO) << "Table trying to initialize from file " << filename
              << " is already initialized.";
    return Status::OK();
  }
  return s;
}

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


<commit_before>// Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chain.h"
#include "chainparams.h"
#include "pow.h"
#include "random.h"
#include "util.h"
#include "test/test_bitcoin.h"

#include <boost/test/unit_test.hpp>

using namespace std;

BOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup)

/* Test calculation of next difficulty target with no constraints applying */
BOOST_AUTO_TEST_CASE(get_next_work)
{
    SelectParams(CBaseChainParams::MAIN);
    const Consensus::Params& params = Params().GetConsensus();

    int64_t nLastRetargetTime = 1261130161; // Block #30240
    CBlockIndex pindexLast;
    pindexLast.nHeight = 32255;
    pindexLast.nTime = 1262152739;  // Block #32255
    pindexLast.nBits = 0x1d00ffff;
    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00d86a);
}

/* Test the constraint on the upper bound for next work */
BOOST_AUTO_TEST_CASE(get_next_work_pow_limit)
{
    SelectParams(CBaseChainParams::MAIN);
    const Consensus::Params& params = Params().GetConsensus();

    int64_t nLastRetargetTime = 1231006505; // Block #0
    CBlockIndex pindexLast;
    pindexLast.nHeight = 2015;
    pindexLast.nTime = 1233061996;  // Block #2015
    pindexLast.nBits = 0x1d00ffff;
    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00ffff);
}

/* Test the constraint on the lower bound for actual time taken */
BOOST_AUTO_TEST_CASE(get_next_work_lower_limit_actual)
{
    SelectParams(CBaseChainParams::MAIN);
    const Consensus::Params& params = Params().GetConsensus();

    int64_t nLastRetargetTime = 1279008237; // Block #66528
    CBlockIndex pindexLast;
    pindexLast.nHeight = 68543;
    pindexLast.nTime = 1279297671;  // Block #68543
    pindexLast.nBits = 0x1c05a3f4;
    // MVF-Core begin
    // due to reversal of multiply-divide calculation in CalculateNextWorkRequired,
    // this rounds slightly differently (change in last digit)
    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1c0168fc);
    // MVF-Core end
}

/* Test the constraint on the upper bound for actual time taken */
BOOST_AUTO_TEST_CASE(get_next_work_upper_limit_actual)
{
    SelectParams(CBaseChainParams::MAIN);
    const Consensus::Params& params = Params().GetConsensus();

    int64_t nLastRetargetTime = 1263163443; // NOTE: Not an actual block time
    CBlockIndex pindexLast;
    pindexLast.nHeight = 46367;
    pindexLast.nTime = 1269211443;  // Block #46367
    pindexLast.nBits = 0x1c387f6f;
    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00e1fd);
}

BOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)
{
    SelectParams(CBaseChainParams::MAIN);
    const Consensus::Params& params = Params().GetConsensus();

    std::vector<CBlockIndex> blocks(10000);
    for (int i = 0; i < 10000; i++) {
        blocks[i].pprev = i ? &blocks[i - 1] : NULL;
        blocks[i].nHeight = i;
        blocks[i].nTime = 1269211443 + i * params.nPowTargetSpacing;
        blocks[i].nBits = 0x207fffff; /* target 0x7fffff000... */
        blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0);
    }

    for (int j = 0; j < 1000; j++) {
        CBlockIndex *p1 = &blocks[GetRand(10000)];
        CBlockIndex *p2 = &blocks[GetRand(10000)];
        CBlockIndex *p3 = &blocks[GetRand(10000)];

        int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, params);
        BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime());
    }
}

// MVF-Core begin
// added unit test after we found that on regtest, difficulty calculation
// can lead to overflow of 256-bit integer.
// We reversed the order of multiplication and division so that the
// division is done first.
BOOST_AUTO_TEST_CASE(MVFCheckDiffCalculation_test)
{
    SelectParams(CBaseChainParams::REGTEST);
    const Consensus::Params& params = Params().GetConsensus();
    arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
    arith_uint256 bnNew;
    arith_uint256 bnOld;
    unsigned int oldnBits = 0x1f10f1aa;
    int64_t nTargetTimespan = 3600, nActualTimespan = 3880;
    bnNew.SetCompact(oldnBits);
    bnOld = bnNew;
    bnNew /= nTargetTimespan;   // division first, else might overflow
    bnNew *= nActualTimespan;

    if (bnNew > bnPowLimit)
        bnNew = bnPowLimit;

    BOOST_CHECK_EQUAL(bnOld.ToString(), "0010f1aa00000000000000000000000000000000000000000000000000000000");
    BOOST_CHECK_EQUAL(bnNew.ToString(), "00124309b60b60b60b60b60b60b60b60b60b60b60b60b60b60b60b60b60b5218");
}
// MVF-Core end

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>sync pow_tests.cpp / MVFCheckOverflowCalculation_test to MVF-BU<commit_after>// Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chain.h"
#include "chainparams.h"
#include "pow.h"
#include "random.h"
#include "util.h"
#include "test/test_bitcoin.h"

#include <boost/test/unit_test.hpp>

using namespace std;

BOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup)

/* Test calculation of next difficulty target with no constraints applying */
BOOST_AUTO_TEST_CASE(get_next_work)
{
    SelectParams(CBaseChainParams::MAIN);
    const Consensus::Params& params = Params().GetConsensus();

    int64_t nLastRetargetTime = 1261130161; // Block #30240
    CBlockIndex pindexLast;
    pindexLast.nHeight = 32255;
    pindexLast.nTime = 1262152739;  // Block #32255
    pindexLast.nBits = 0x1d00ffff;
    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00d86a);
}

/* Test the constraint on the upper bound for next work */
BOOST_AUTO_TEST_CASE(get_next_work_pow_limit)
{
    SelectParams(CBaseChainParams::MAIN);
    const Consensus::Params& params = Params().GetConsensus();

    int64_t nLastRetargetTime = 1231006505; // Block #0
    CBlockIndex pindexLast;
    pindexLast.nHeight = 2015;
    pindexLast.nTime = 1233061996;  // Block #2015
    pindexLast.nBits = 0x1d00ffff;
    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00ffff);
}

/* Test the constraint on the lower bound for actual time taken */
BOOST_AUTO_TEST_CASE(get_next_work_lower_limit_actual)
{
    SelectParams(CBaseChainParams::MAIN);
    const Consensus::Params& params = Params().GetConsensus();

    int64_t nLastRetargetTime = 1279008237; // Block #66528
    CBlockIndex pindexLast;
    pindexLast.nHeight = 68543;
    pindexLast.nTime = 1279297671;  // Block #68543
    pindexLast.nBits = 0x1c05a3f4;
    // MVF-Core begin
    // due to reversal of multiply-divide calculation in CalculateNextWorkRequired,
    // this rounds slightly differently (change in last digit)
    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1c0168fc);
    // MVF-Core end
}

/* Test the constraint on the upper bound for actual time taken */
BOOST_AUTO_TEST_CASE(get_next_work_upper_limit_actual)
{
    SelectParams(CBaseChainParams::MAIN);
    const Consensus::Params& params = Params().GetConsensus();

    int64_t nLastRetargetTime = 1263163443; // NOTE: Not an actual block time
    CBlockIndex pindexLast;
    pindexLast.nHeight = 46367;
    pindexLast.nTime = 1269211443;  // Block #46367
    pindexLast.nBits = 0x1c387f6f;
    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1d00e1fd);
}

BOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)
{
    SelectParams(CBaseChainParams::MAIN);
    const Consensus::Params& params = Params().GetConsensus();

    std::vector<CBlockIndex> blocks(10000);
    for (int i = 0; i < 10000; i++) {
        blocks[i].pprev = i ? &blocks[i - 1] : NULL;
        blocks[i].nHeight = i;
        blocks[i].nTime = 1269211443 + i * params.nPowTargetSpacing;
        blocks[i].nBits = 0x207fffff; /* target 0x7fffff000... */
        blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0);
    }

    for (int j = 0; j < 1000; j++) {
        CBlockIndex *p1 = &blocks[GetRand(10000)];
        CBlockIndex *p2 = &blocks[GetRand(10000)];
        CBlockIndex *p3 = &blocks[GetRand(10000)];

        int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, params);
        BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime());
    }
}

// MVF-Core begin
/* added unit test after we found that on regtest, difficulty calculation
   can lead to overflow of 256-bit integer. Here an excessive retarget time
   is set in order to trigger the overflow case, in which case the previous
   difficulty is re-used. */
BOOST_AUTO_TEST_CASE(MVFCheckOverflowCalculation_test)
{
    SelectParams(CBaseChainParams::REGTEST);
    const Consensus::Params& params = Params().GetConsensus();

    FinalActivateForkHeight = 2016;

    int64_t nLastRetargetTime = 7;  // Force an excessive retarget time to trigger overflow
    CBlockIndex pindexLast;
    pindexLast.nHeight = 2024;
    pindexLast.nTime = 1279297671;  // Block #68543
    pindexLast.nBits = 0x207aaaaa;  // Almost overflowing already

    // an overflow causes the POW limit to be returned
    // need to set -force-retarget, otherwise cannot test overflow
    // because it would never reach the computation
    SoftSetBoolArg("-force-retarget", true);
    BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x207fffff);
}
// MVF-Core end

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include "IECoreMaya/ObjectVectorParameterHandler.h"
#include "IECoreMaya/FromMayaPlugConverter.h"
#include "IECoreMaya/ObjectData.h"

#include "IECore/MessageHandler.h"
#include "IECore/TypedObjectParameter.h"
#include "IECore/ObjectVector.h"

#include "maya/MFnTypedAttribute.h"

using namespace std;
using namespace IECore;
using namespace IECoreMaya;

static ParameterHandler::Description< ObjectVectorParameterHandler > registrar( ObjectVectorParameter::staticTypeId() );

MObject ObjectVectorParameterHandler::create( IECore::ConstParameterPtr parameter, const MString &attributeName ) const
{
	ConstObjectVectorParameterPtr p = IECore::runTimeCast< const ObjectVectorParameter >( parameter );
	if( !p )
	{
		return MObject::kNullObj;
	}

	MFnTypedAttribute fnTAttr;
	MObject result = fnTAttr.create( attributeName, attributeName, ObjectData::id );
	fnTAttr.setArray( true );
	fnTAttr.setDisconnectBehavior( MFnAttribute::kDelete );

	return result;
}

MStatus ObjectVectorParameterHandler::update( IECore::ConstParameterPtr parameter, MObject &attribute ) const
{
	ConstObjectVectorParameterPtr p = IECore::runTimeCast< const ObjectVectorParameter >( parameter );
	if( !p )
	{
		return MS::kFailure;
	}

	MFnTypedAttribute fnTAttr( attribute );
	if( !fnTAttr.hasObj( attribute ) )
	{
		return MS::kFailure;
	}

	return MS::kSuccess;
}

MStatus ObjectVectorParameterHandler::setValue( IECore::ConstParameterPtr parameter, MPlug &plug ) const
{
	ConstObjectVectorParameterPtr p = IECore::runTimeCast<const ObjectVectorParameter>( parameter );
	if( !p )
	{
		return MS::kFailure;
	}

	/// \todo Can we implement this?

	return MS::kSuccess;
}

MStatus ObjectVectorParameterHandler::setValue( const MPlug &plug, IECore::ParameterPtr parameter ) const
{
	ObjectVectorParameterPtr p = IECore::runTimeCast<ObjectVectorParameter>( parameter );
	if( !p )
	{
		return MS::kFailure;
	}

	MStatus s;

	ObjectVectorPtr v = new ObjectVector;

	unsigned numElements = const_cast<MPlug &>( plug ).evaluateNumElements();
	for( unsigned i=0; i<numElements; i++ )
	{
		MPlug elementPlug = plug.elementByPhysicalIndex( i, &s );
		assert( s );

		ObjectPtr obj = 0;
		FromMayaConverterPtr c = FromMayaPlugConverter::create( elementPlug, Object::staticTypeId() );
		if( c )
		{
			obj = c->convert();
		}

		v->members().resize( max( elementPlug.logicalIndex() + 1, v->members().size() ), 0 );
		v->members()[elementPlug.logicalIndex()] = obj;
	}

	p->setValue( v );

	return MS::kSuccess;
}
<commit_msg>Fixed 64-bit build<commit_after>#include "IECoreMaya/ObjectVectorParameterHandler.h"
#include "IECoreMaya/FromMayaPlugConverter.h"
#include "IECoreMaya/ObjectData.h"

#include "IECore/MessageHandler.h"
#include "IECore/TypedObjectParameter.h"
#include "IECore/ObjectVector.h"

#include "maya/MFnTypedAttribute.h"

using namespace std;
using namespace IECore;
using namespace IECoreMaya;

static ParameterHandler::Description< ObjectVectorParameterHandler > registrar( ObjectVectorParameter::staticTypeId() );

MObject ObjectVectorParameterHandler::create( IECore::ConstParameterPtr parameter, const MString &attributeName ) const
{
	ConstObjectVectorParameterPtr p = IECore::runTimeCast< const ObjectVectorParameter >( parameter );
	if( !p )
	{
		return MObject::kNullObj;
	}

	MFnTypedAttribute fnTAttr;
	MObject result = fnTAttr.create( attributeName, attributeName, ObjectData::id );
	fnTAttr.setArray( true );
	fnTAttr.setDisconnectBehavior( MFnAttribute::kDelete );

	return result;
}

MStatus ObjectVectorParameterHandler::update( IECore::ConstParameterPtr parameter, MObject &attribute ) const
{
	ConstObjectVectorParameterPtr p = IECore::runTimeCast< const ObjectVectorParameter >( parameter );
	if( !p )
	{
		return MS::kFailure;
	}

	MFnTypedAttribute fnTAttr( attribute );
	if( !fnTAttr.hasObj( attribute ) )
	{
		return MS::kFailure;
	}

	return MS::kSuccess;
}

MStatus ObjectVectorParameterHandler::setValue( IECore::ConstParameterPtr parameter, MPlug &plug ) const
{
	ConstObjectVectorParameterPtr p = IECore::runTimeCast<const ObjectVectorParameter>( parameter );
	if( !p )
	{
		return MS::kFailure;
	}

	/// \todo Can we implement this?

	return MS::kSuccess;
}

MStatus ObjectVectorParameterHandler::setValue( const MPlug &plug, IECore::ParameterPtr parameter ) const
{
	ObjectVectorParameterPtr p = IECore::runTimeCast<ObjectVectorParameter>( parameter );
	if( !p )
	{
		return MS::kFailure;
	}

	MStatus s;

	ObjectVectorPtr v = new ObjectVector;

	unsigned numElements = const_cast<MPlug &>( plug ).evaluateNumElements();
	for( unsigned i=0; i<numElements; i++ )
	{
		MPlug elementPlug = plug.elementByPhysicalIndex( i, &s );
		assert( s );

		ObjectPtr obj = 0;
		FromMayaConverterPtr c = FromMayaPlugConverter::create( elementPlug, Object::staticTypeId() );
		if( c )
		{
			obj = c->convert();
		}

		v->members().resize( std::max<ObjectVector::MemberContainer::size_type>( elementPlug.logicalIndex() + 1, v->members().size() ), 0 );
		v->members()[elementPlug.logicalIndex()] = obj;
	}

	p->setValue( v );

	return MS::kSuccess;
}
<|endoftext|>


<commit_before>

#include "SeagullGame.h"
#include "BirdCharacter.h"

ABirdCharacter::ABirdCharacter(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)
{
	// Structure to hold one-time initialization
	struct FConstructorStatics
	{

	};
	// Correct the mesh's axis - REMOVE THIS WITH NEW MESH
	Mesh->AddLocalRotation(FRotator(0.f,270.0f,0.f));

	// Create a spring arm component
	SpringArm = PCIP.CreateDefaultSubobject<USpringArmComponent>(this, TEXT("SpringArm0"));
	SpringArm->AttachTo(Mesh);
	SpringArm->TargetArmLength = 160.0f; // The camera follows at this distance behind the character
	SpringArm->SocketOffset = FVector(0.f, 0.f, 60.f);
	SpringArm->bEnableCameraLag = false;
	SpringArm->CameraLagSpeed = 15.f;

	// Further mesh axis correction
	SpringArm->AddLocalRotation(FRotator(0.f, 90.0f, 0.0f));

	// Create camera component
	Camera = PCIP.CreateDefaultSubobject<UCameraComponent>(this, TEXT("Camera0"));
	Camera->AttachTo(SpringArm, USpringArmComponent::SocketName);
	Camera->bUseControllerViewRotation = false; // Don't rotate camera with controller

	// Set handling parameters
	TurnSpeed = 50.f;
}

// Frame loop
void ABirdCharacter::Tick(float DeltaSeconds)
{
	// If both wings were pressed, thrust upwards and don't rotate
	if (RightFlapped && LeftFlapped)
	{
		// Manage the length of the force using a timer
		BothTimer += DeltaSeconds;
		if (BothTimer < 0.3f){
			// Launch the player upwards at a moderate strength
			const FVector LaunchForce = FVector(0.f, 0.f, 450.0f);
			// Set a max limit on vertical velocity
			if (GetVelocity().Z < 500.0f){
				LaunchCharacter(LaunchForce, false, false);
			}
		}
	}
	else if (RightFlapped)
	{
		// Manage the length of the force using a timer
		RightTimer += DeltaSeconds;
		if (RightTimer < 0.15f){
			// Rotate the bird clockwise
			RotateBird(1.0f);
			// Launch the player upwards at a weak strength
			const FVector LaunchForce = FVector(0.f, 0.f, 50.0f);
			// Set a max limit on vertical velocity
			if (GetVelocity().Z < 100.0f){

				LaunchCharacter(LaunchForce, false, false);
			}
		}
	}
	else if (LeftFlapped)
	{
		// Manage the length of the force using a timer
		LeftTimer += DeltaSeconds;
		if (LeftTimer < 0.15f){
			// Rotate the bird counter-clockwise
			RotateBird(-1.0f);
			// Launch the player upwards at a weak strength
			const FVector LaunchForce = FVector(0.f, 0.f, 50.0f);
			// Set a max limit on vertical velocity
			if (GetVelocity().Z < 100.0f){
				LaunchCharacter(LaunchForce, false, false);
			}
		}
	}

	// Calculate change in rotation this frame
	FRotator DeltaRotation(0, 0, 0);
	DeltaRotation.Pitch = CurrentPitchSpeed * DeltaSeconds;
	DeltaRotation.Yaw = CurrentYawSpeed * DeltaSeconds;
	DeltaRotation.Roll = CurrentRollSpeed * DeltaSeconds;

	// Apply the calculated rotation
	AddControllerYawInput(DeltaRotation.Yaw);

	// Smoothly interpolate to target yaw speed
	CurrentYawSpeed = FMath::FInterpTo(CurrentYawSpeed, 0.0f, GetWorld()->GetDeltaSeconds(), 2.0f);

	// Call any parent class Tick implementation
	Super::Tick(DeltaSeconds);
}

void ABirdCharacter::ReceiveHit(class UPrimitiveComponent* MyComp, class AActor* Other, class UPrimitiveComponent* OtherComp, bool bSelfMoved, FVector HitLocation, FVector HitNormal, FVector NormalImpulse, const FHitResult& Hit)
{
	Super::ReceiveHit(MyComp, Other, OtherComp, bSelfMoved, HitLocation, HitNormal, NormalImpulse, Hit);

}

void ABirdCharacter::SetupPlayerInputComponent(class UInputComponent* InputComponent)
{
	check(InputComponent);

	InputComponent->BindAxis("Forward", this, &ABirdCharacter::ThrustInput);

	InputComponent->BindAxis("RightWing", this, &ABirdCharacter::OnRightFlap);
}

void ABirdCharacter::ThrustInput(float Val)
{
	ForwardPressed = true;

	// find out which way is forward
	FRotator Rotation = Controller->GetControlRotation();

	// add movement in that direction
	const FVector Direction = FRotationMatrix(Rotation).GetScaledAxis(EAxis::X);
	AddMovementInput(Direction, Val);
}

void ABirdCharacter::OnRightFlap(float Val)
{
	if (Val == -0.5f)
	{
		RightFlapped = false;
		LeftFlapped = true;
	}
	else if (Val == 1.0f)
	{
		RightFlapped = true;
		LeftFlapped = false;
	}
	else if (Val == 0.5f)
	{
		RightFlapped = true;
		LeftFlapped = true;
	}
	else if (Val == 0.0f)
	{
		RightFlapped = false;
		LeftFlapped = false;
		BothTimer = 0.0f;
		RightTimer = 0.0f;
		LeftTimer = 0.0f;
	}

}
void ABirdCharacter::RotateBird(float Val)
{
	//Rotate the bird based on turn speed
	float TargetYawSpeed = (TurnSpeed * Val);

	// Smoothly interpolate to target yaw speed
	CurrentYawSpeed = FMath::FInterpTo(CurrentYawSpeed, TargetYawSpeed, GetWorld()->GetDeltaSeconds(), 2.f);

	// find out which way is forward
	FRotator Rotation = Controller->GetControlRotation();
}

<commit_msg>Slight tweak to upwards force of bird<commit_after>

#include "SeagullGame.h"
#include "BirdCharacter.h"

ABirdCharacter::ABirdCharacter(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)
{
	// Structure to hold one-time initialization
	struct FConstructorStatics
	{

	};
	// Correct the mesh's axis - REMOVE THIS WITH NEW MESH
	Mesh->AddLocalRotation(FRotator(0.f,270.0f,0.f));

	// Create a spring arm component
	SpringArm = PCIP.CreateDefaultSubobject<USpringArmComponent>(this, TEXT("SpringArm0"));
	SpringArm->AttachTo(Mesh);
	SpringArm->TargetArmLength = 160.0f; // The camera follows at this distance behind the character
	SpringArm->SocketOffset = FVector(0.f, 0.f, 60.f);
	SpringArm->bEnableCameraLag = false;
	SpringArm->CameraLagSpeed = 15.f;

	// Further mesh axis correction
	SpringArm->AddLocalRotation(FRotator(0.f, 90.0f, 0.0f));

	// Create camera component
	Camera = PCIP.CreateDefaultSubobject<UCameraComponent>(this, TEXT("Camera0"));
	Camera->AttachTo(SpringArm, USpringArmComponent::SocketName);
	Camera->bUseControllerViewRotation = false; // Don't rotate camera with controller

	// Set handling parameters
	TurnSpeed = 50.f;
}

// Frame loop
void ABirdCharacter::Tick(float DeltaSeconds)
{
	// If both wings were pressed, thrust upwards and don't rotate
	if (RightFlapped && LeftFlapped)
	{
		// Manage the length of the force using a timer
		BothTimer += DeltaSeconds;
		if (BothTimer < 0.3f){
			// Launch the player upwards at a moderate strength
			const FVector LaunchForce = FVector(0.f, 0.f, 350.0f);
			// Set a max limit on vertical velocity
			if (GetVelocity().Z < 500.0f){
				LaunchCharacter(LaunchForce, false, false);
			}
		}
	}
	else if (RightFlapped)
	{
		// Manage the length of the force using a timer
		RightTimer += DeltaSeconds;
		if (RightTimer < 0.15f){
			// Rotate the bird clockwise
			RotateBird(1.0f);
			// Launch the player upwards at a weak strength
			const FVector LaunchForce = FVector(0.f, 0.f, 50.0f);
			// Set a max limit on vertical velocity
			if (GetVelocity().Z < 100.0f){

				LaunchCharacter(LaunchForce, false, false);
			}
		}
	}
	else if (LeftFlapped)
	{
		// Manage the length of the force using a timer
		LeftTimer += DeltaSeconds;
		if (LeftTimer < 0.15f){
			// Rotate the bird counter-clockwise
			RotateBird(-1.0f);
			// Launch the player upwards at a weak strength
			const FVector LaunchForce = FVector(0.f, 0.f, 50.0f);
			// Set a max limit on vertical velocity
			if (GetVelocity().Z < 100.0f){
				LaunchCharacter(LaunchForce, false, false);
			}
		}
	}

	// Calculate change in rotation this frame
	FRotator DeltaRotation(0, 0, 0);
	DeltaRotation.Pitch = CurrentPitchSpeed * DeltaSeconds;
	DeltaRotation.Yaw = CurrentYawSpeed * DeltaSeconds;
	DeltaRotation.Roll = CurrentRollSpeed * DeltaSeconds;

	// Apply the calculated rotation
	AddControllerYawInput(DeltaRotation.Yaw);

	// Smoothly interpolate to target yaw speed
	CurrentYawSpeed = FMath::FInterpTo(CurrentYawSpeed, 0.0f, GetWorld()->GetDeltaSeconds(), 2.0f);

	// Call any parent class Tick implementation
	Super::Tick(DeltaSeconds);
}

void ABirdCharacter::ReceiveHit(class UPrimitiveComponent* MyComp, class AActor* Other, class UPrimitiveComponent* OtherComp, bool bSelfMoved, FVector HitLocation, FVector HitNormal, FVector NormalImpulse, const FHitResult& Hit)
{
	Super::ReceiveHit(MyComp, Other, OtherComp, bSelfMoved, HitLocation, HitNormal, NormalImpulse, Hit);

}

void ABirdCharacter::SetupPlayerInputComponent(class UInputComponent* InputComponent)
{
	check(InputComponent);

	InputComponent->BindAxis("Forward", this, &ABirdCharacter::ThrustInput);

	InputComponent->BindAxis("RightWing", this, &ABirdCharacter::OnRightFlap);
}

void ABirdCharacter::ThrustInput(float Val)
{
	ForwardPressed = true;

	// find out which way is forward
	FRotator Rotation = Controller->GetControlRotation();

	// add movement in that direction
	const FVector Direction = FRotationMatrix(Rotation).GetScaledAxis(EAxis::X);
	AddMovementInput(Direction, Val);
}

void ABirdCharacter::OnRightFlap(float Val)
{
	if (Val == -0.5f)
	{
		RightFlapped = false;
		LeftFlapped = true;
	}
	else if (Val == 1.0f)
	{
		RightFlapped = true;
		LeftFlapped = false;
	}
	else if (Val == 0.5f)
	{
		RightFlapped = true;
		LeftFlapped = true;
	}
	else if (Val == 0.0f)
	{
		RightFlapped = false;
		LeftFlapped = false;
		BothTimer = 0.0f;
		RightTimer = 0.0f;
		LeftTimer = 0.0f;
	}

}
void ABirdCharacter::RotateBird(float Val)
{
	//Rotate the bird based on turn speed
	float TargetYawSpeed = (TurnSpeed * Val);

	// Smoothly interpolate to target yaw speed
	CurrentYawSpeed = FMath::FInterpTo(CurrentYawSpeed, TargetYawSpeed, GetWorld()->GetDeltaSeconds(), 2.f);

	// find out which way is forward
	FRotator Rotation = Controller->GetControlRotation();
}

<|endoftext|>


<commit_before>#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::get;

#ifdef HAVE_OPENVX
PERF_TEST_P(Size_MatType, Accumulate,
    testing::Combine(
        testing::Values(::perf::szODD, ::perf::szQVGA, ::perf::szVGA, ::perf::sz1080p),
        testing::Values(CV_16SC1, CV_32FC1)
    )
)
#else
PERF_TEST_P( Size_MatType, Accumulate,
             testing::Combine(
                 testing::Values(::perf::szODD, ::perf::szQVGA, ::perf::szVGA, ::perf::sz1080p),
                 testing::Values(CV_32FC1)
             )
           )
#endif
{
    Size sz = get<0>(GetParam());
    int dstType = get<1>(GetParam());

    Mat src(sz, CV_8UC1);
    Mat dst(sz, dstType);

    declare.time(100);
    declare.in(src, WARMUP_RNG).out(dst);

    TEST_CYCLE() accumulate(src, dst);

    SANITY_CHECK(dst);
}

#ifdef HAVE_OPENVX
PERF_TEST_P(Size_MatType, AccumulateSquare,
    testing::Combine(
        testing::Values(::perf::szODD, ::perf::szQVGA, ::perf::szVGA, ::perf::sz1080p),
        testing::Values(CV_16SC1, CV_32FC1)
    )
)
#else
PERF_TEST_P( Size_MatType, AccumulateSquare,
             testing::Combine(
                 testing::Values(::perf::szODD, ::perf::szQVGA, ::perf::szVGA, ::perf::sz1080p),
                 testing::Values(CV_32FC1)
             )
           )
#endif
{
    Size sz = get<0>(GetParam());
    int dstType = get<1>(GetParam());

    Mat src(sz, CV_8UC1);
    Mat dst(sz, dstType);

    declare.time(100);
    declare.in(src, WARMUP_RNG).out(dst);

    TEST_CYCLE() accumulateSquare(src, dst);

    SANITY_CHECK(dst);
}

#ifdef HAVE_OPENVX
PERF_TEST_P(Size_MatType, AccumulateWeighted,
    testing::Combine(
        testing::Values(::perf::szODD, ::perf::szQVGA, ::perf::szVGA, ::perf::sz1080p),
        testing::Values(CV_8UC1, CV_32FC1)
    )
)
#else
PERF_TEST_P( Size_MatType, AccumulateWeighted,
             testing::Combine(
                 testing::Values(::perf::szODD, ::perf::szQVGA, ::perf::szVGA, ::perf::sz1080p),
                 testing::Values(CV_32FC1)
             )
           )
#endif
{
    Size sz = get<0>(GetParam());
    int dstType = get<1>(GetParam());

    Mat src(sz, CV_8UC1);
    Mat dst(sz, dstType);

    declare.time(100);
    declare.in(src, WARMUP_RNG).out(dst);

    TEST_CYCLE() accumulateWeighted(src, dst, 0.314);

    SANITY_CHECK(dst);
}
<commit_msg>Fix for accumulate performance test in case of multiple iterations<commit_after>#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::get;

#ifdef HAVE_OPENVX
PERF_TEST_P(Size_MatType, Accumulate,
    testing::Combine(
        testing::Values(::perf::szODD, ::perf::szQVGA, ::perf::szVGA, ::perf::sz1080p),
        testing::Values(CV_16SC1, CV_32FC1)
    )
)
#else
PERF_TEST_P( Size_MatType, Accumulate,
             testing::Combine(
                 testing::Values(::perf::szODD, ::perf::szQVGA, ::perf::szVGA, ::perf::sz1080p),
                 testing::Values(CV_32FC1)
             )
           )
#endif
{
    Size sz = get<0>(GetParam());
    int dstType = get<1>(GetParam());

    Mat src(sz, CV_8UC1);
    Mat dst(sz, dstType);

    declare.time(100);
    declare.in(src, WARMUP_RNG).out(dst);

    TEST_CYCLE() { dst.setTo(cv::Scalar::all(0)); accumulate(src, dst); }

    SANITY_CHECK(dst);
}

#ifdef HAVE_OPENVX
PERF_TEST_P(Size_MatType, AccumulateSquare,
    testing::Combine(
        testing::Values(::perf::szODD, ::perf::szQVGA, ::perf::szVGA, ::perf::sz1080p),
        testing::Values(CV_16SC1, CV_32FC1)
    )
)
#else
PERF_TEST_P( Size_MatType, AccumulateSquare,
             testing::Combine(
                 testing::Values(::perf::szODD, ::perf::szQVGA, ::perf::szVGA, ::perf::sz1080p),
                 testing::Values(CV_32FC1)
             )
           )
#endif
{
    Size sz = get<0>(GetParam());
    int dstType = get<1>(GetParam());

    Mat src(sz, CV_8UC1);
    Mat dst(sz, dstType);

    declare.time(100);
    declare.in(src, WARMUP_RNG).out(dst);

    TEST_CYCLE() { dst.setTo(cv::Scalar::all(0)); accumulateSquare(src, dst); }

    SANITY_CHECK(dst);
}

#ifdef HAVE_OPENVX
PERF_TEST_P(Size_MatType, AccumulateWeighted,
    testing::Combine(
        testing::Values(::perf::szODD, ::perf::szQVGA, ::perf::szVGA, ::perf::sz1080p),
        testing::Values(CV_8UC1, CV_32FC1)
    )
)
#else
PERF_TEST_P( Size_MatType, AccumulateWeighted,
             testing::Combine(
                 testing::Values(::perf::szODD, ::perf::szQVGA, ::perf::szVGA, ::perf::sz1080p),
                 testing::Values(CV_32FC1)
             )
           )
#endif
{
    Size sz = get<0>(GetParam());
    int dstType = get<1>(GetParam());

    Mat src(sz, CV_8UC1);
    Mat dst(sz, dstType);

    declare.time(100);
    declare.in(src, WARMUP_RNG).out(dst);

    TEST_CYCLE() { dst.setTo(cv::Scalar::all(0)); accumulateWeighted(src, dst, 0.314); }

    SANITY_CHECK(dst);
}
<|endoftext|>


<commit_before>
#include "tests/gtest/gtest.h"
#include <cmath>

#include "pbrt.h"
#include "rng.h"
#include "efloat.h"
#include "parallel.h"

static float GetFloat(RNG &rng) {
    float f;
    do {
        f = BitsToFloat(rng.UniformUInt32());
    } while (std::isnan(f));
    return f;
}

static double GetDouble(RNG &rng) {
    double d;
    do {
        d = BitsToFloat(uint64_t(rng.UniformUInt32()) |
                        (uint64_t(rng.UniformUInt32()) << 32));
    } while (std::isnan(d));
    return d;
}

TEST(FloatingPoint, NextUpDownFloat) {
    EXPECT_GT(NextFloatUp(-0.f), 0.f);
    EXPECT_LT(NextFloatDown(0.f), 0.f);

    EXPECT_EQ(NextFloatUp((float)Infinity), (float)Infinity);
    EXPECT_LT(NextFloatDown((float)Infinity), (float)Infinity);

    EXPECT_EQ(NextFloatDown(-(float)Infinity), -(float)Infinity);
    EXPECT_GT(NextFloatUp(-(float)Infinity), -(float)Infinity);

    RNG rng;
    for (int i = 0; i < 100000; ++i) {
        float f = GetFloat(rng);
        if (std::isinf(f)) continue;

        EXPECT_EQ(std::nextafter(f, (float)Infinity), NextFloatUp(f));
        EXPECT_EQ(std::nextafter(f, -(float)Infinity), NextFloatDown(f));
    }
}

TEST(FloatingPoint, NextUpDownDouble) {
    EXPECT_GT(NextFloatUp(-0.), 0.);
    EXPECT_LT(NextFloatDown(0.), 0.);

    EXPECT_EQ(NextFloatUp((double)Infinity), (double)Infinity);
    EXPECT_LT(NextFloatDown((double)Infinity), (double)Infinity);

    EXPECT_EQ(NextFloatDown(-(double)Infinity), -(double)Infinity);
    EXPECT_GT(NextFloatUp(-(double)Infinity), -(double)Infinity);

    RNG rng(3);
    for (int i = 0; i < 100000; ++i) {
        double d = GetDouble(rng);
        if (std::isinf(d)) continue;

        EXPECT_EQ(std::nextafter(d, (double)Infinity), NextFloatUp(d));
        EXPECT_EQ(std::nextafter(d, -(double)Infinity), NextFloatDown(d));
    }
}

TEST(FloatingPoint, FloatBits) {
    RNG rng(1);
    for (int i = 0; i < 100000; ++i) {
        uint32_t ui = rng.UniformUInt32();
        float f = BitsToFloat(ui);
        if (std::isnan(f)) continue;

        EXPECT_EQ(ui, FloatToBits(f));
    }
}

TEST(FloatingPoint, DoubleBits) {
    RNG rng(2);
    for (int i = 0; i < 100000; ++i) {
        uint64_t ui = (uint64_t(rng.UniformUInt32()) |
                       (uint64_t(rng.UniformUInt32()) << 32));
        double f = BitsToFloat(ui);

        if (std::isnan(f)) continue;

        EXPECT_EQ(ui, FloatToBits(f));
    }
}

TEST(FloatingPoint, EFloat) {
    for (int trial = 0; trial < 1000; ++trial) {
        RNG rng(trial);
        EFloat ef = -10000 + 20000 * rng.UniformFloat();
        long double ld = (float)ef;

        for (int iter = 0; iter < 100; ++iter) {
            EXPECT_GE(ld, ef.LowerBound());
            EXPECT_LE(ld, ef.UpperBound());

            EFloat ef2 = 0;
            float f = -10000 + 20000 * rng.UniformFloat();
            switch (rng.UniformUInt32() % 4) {
            case 0:
                ef2 = f;
                break;
            case 1:
                ef2 = ef;
                break;
            case 3:
                ef2 = EFloat(f, std::abs(rng.UniformFloat() * .001 * f));
                break;
            }
            long double ld2 = (float)ef2;

            int op = rng.UniformUInt32() % 7;
            switch (op) {
            case 0:
                ef = -ef;
                ld = -ld;
                break;
            case 1:
                ef = ef + ef2;
                ld = ld + ld2;
                break;
            case 2:
                ef = ef - ef2;
                ld = ld - ld2;
                break;
            case 3:
                ef = ef * ef2;
                ld = ld * ld2;
                break;
            case 4:
                if (ef.LowerBound() * ef.UpperBound() > 0 &&
                    ef2.LowerBound() * ef2.UpperBound() > 0) {
                    ef = ef / ef2;
                    ld = ld / ld2;
                }
                break;
            case 5:
                if (ld >= 0 && ef.LowerBound() > 0) {
                    ef = sqrt(ef);
                    ld = std::sqrt(ld);
                }
                break;
            case 6:
                ef = abs(ef);
                ld = (ld < 0) ? -ld : ld;
                break;
            }

            if (std::isnan((float)ef) || std::isnan(ld) ||
                std::isinf((float)ef) || std::isinf(ld) ||
                std::isinf(ef.GetAbsoluteError()))
                break;
        }
    }
}

TEST(FloatingPoint, AtomicFloat) {
    AtomicFloat af(0);
    Float f = 0.;
    EXPECT_EQ(f, af);
    af.Add(1.0251);
    f += 1.0251;
    EXPECT_EQ(f, af);
    af.Add(2.);
    f += 2.;
    EXPECT_EQ(f, af);
}
<commit_msg>Improve EFloat tests.<commit_after>
#include "tests/gtest/gtest.h"
#include <cmath>

#include "pbrt.h"
#include "rng.h"
#include "efloat.h"
#include "parallel.h"

static float GetFloat(RNG &rng) {
    float f;
    do {
        f = BitsToFloat(rng.UniformUInt32());
    } while (std::isnan(f));
    return f;
}

static double GetDouble(RNG &rng) {
    double d;
    do {
        d = BitsToFloat(uint64_t(rng.UniformUInt32()) |
                        (uint64_t(rng.UniformUInt32()) << 32));
    } while (std::isnan(d));
    return d;
}

TEST(FloatingPoint, NextUpDownFloat) {
    EXPECT_GT(NextFloatUp(-0.f), 0.f);
    EXPECT_LT(NextFloatDown(0.f), 0.f);

    EXPECT_EQ(NextFloatUp((float)Infinity), (float)Infinity);
    EXPECT_LT(NextFloatDown((float)Infinity), (float)Infinity);

    EXPECT_EQ(NextFloatDown(-(float)Infinity), -(float)Infinity);
    EXPECT_GT(NextFloatUp(-(float)Infinity), -(float)Infinity);

    RNG rng;
    for (int i = 0; i < 100000; ++i) {
        float f = GetFloat(rng);
        if (std::isinf(f)) continue;

        EXPECT_EQ(std::nextafter(f, (float)Infinity), NextFloatUp(f));
        EXPECT_EQ(std::nextafter(f, -(float)Infinity), NextFloatDown(f));
    }
}

TEST(FloatingPoint, NextUpDownDouble) {
    EXPECT_GT(NextFloatUp(-0.), 0.);
    EXPECT_LT(NextFloatDown(0.), 0.);

    EXPECT_EQ(NextFloatUp((double)Infinity), (double)Infinity);
    EXPECT_LT(NextFloatDown((double)Infinity), (double)Infinity);

    EXPECT_EQ(NextFloatDown(-(double)Infinity), -(double)Infinity);
    EXPECT_GT(NextFloatUp(-(double)Infinity), -(double)Infinity);

    RNG rng(3);
    for (int i = 0; i < 100000; ++i) {
        double d = GetDouble(rng);
        if (std::isinf(d)) continue;

        EXPECT_EQ(std::nextafter(d, (double)Infinity), NextFloatUp(d));
        EXPECT_EQ(std::nextafter(d, -(double)Infinity), NextFloatDown(d));
    }
}

TEST(FloatingPoint, FloatBits) {
    RNG rng(1);
    for (int i = 0; i < 100000; ++i) {
        uint32_t ui = rng.UniformUInt32();
        float f = BitsToFloat(ui);
        if (std::isnan(f)) continue;

        EXPECT_EQ(ui, FloatToBits(f));
    }
}

TEST(FloatingPoint, DoubleBits) {
    RNG rng(2);
    for (int i = 0; i < 100000; ++i) {
        uint64_t ui = (uint64_t(rng.UniformUInt32()) |
                       (uint64_t(rng.UniformUInt32()) << 32));
        double f = BitsToFloat(ui);

        if (std::isnan(f)) continue;

        EXPECT_EQ(ui, FloatToBits(f));
    }
}

TEST(FloatingPoint, EFloat) {
    for (int trial = 0; trial < 100000; ++trial) {
        RNG rng(trial);
        // Return an exponentially-distributed floating-point value.
        auto getFloat = [&rng](Float minExp = -4., Float maxExp = 4.) {
            Float logu = Lerp(rng.UniformFloat(), minExp, maxExp);
            Float sign = rng.UniformFloat() < .5 ? -1. : 1.;
            return sign * std::pow(10, logu);
        };

        // We'll track a value in an EFloat and a precise version of the
        // same value. As we perform random arithmetic operations to ef,
        // we'll perform the same operations on efPrecise and make sure
        // that efPrecise remains within the error bounds that ef has
        // computed..
        EFloat ef = getFloat();
        long double efPrecise = (float)ef;

        for (int iter = 0; iter < 100; ++iter) {
            // Exit out if we've gone off to a bad place.
            if (std::isnan((float)ef) || std::isnan(efPrecise) ||
                std::isinf((float)ef) || std::isinf(efPrecise) ||
                std::isinf(ef.GetAbsoluteError()))
                break;

            // Make sure that the precise value is inside the bounds of the
            // EFloat's interval.
            EXPECT_GE(efPrecise, ef.LowerBound()) << "trial " << trial
                                                  << ", iter " << iter;
            EXPECT_LE(efPrecise, ef.UpperBound()) << "trial " << trial
                                                  << ", iter " << iter;

            // Choose a second value to (maybe) use as an operand below.
            EFloat ef2 = 0;
            long double efPrecise2;
            switch (rng.UniformUInt32(3)) {
            case 0: {
                // Choose a new random floating-point value; assume it is
                // fully precise.
                Float f = getFloat();
                ef2 = f;
                efPrecise2 = f;
                break;
            }
            case 1:
                // Use the same value as ef.
                ef2 = ef;
                efPrecise2 = efPrecise;
                break;
            case 2: {
                // Choose a random float and make up a small interval around it.
                Float f = getFloat();
                Float err = std::abs(getFloat(-8., -2.) * f);
                ef2 = EFloat(f, err);
                // Now compute a 'precise' value that's not equal to f, but
                // is instead somewhere within the error bounds.
                Float offset = rng.UniformFloat();
                efPrecise2 = (1. - offset) * ef2.LowerBound() +
                             offset * ef2.UpperBound();
                // Sometimes the result isn't actually inside the bounds,
                // due to round-off error.
                if (efPrecise2 >= ef2.UpperBound() ||
                    efPrecise2 <= ef2.LowerBound())
                    efPrecise2 = f;
#ifndef NDEBUG
                ef2 = EFloat(f, efPrecise2, err);
#else
                ef2 = EFloat(f, err);
#endif
                break;
            }
            }

            // Now do a random operation, upading the separate precise
            // value in the same manner.
            switch (rng.UniformUInt32(7)) {
            case 0:
                // Negation.
                ef = -ef;
                efPrecise = -efPrecise;
                break;
            case 1:
                // Addition.
                ef = ef + ef2;
                efPrecise = efPrecise + efPrecise2;
                break;
            case 2:
                // Subtraction.
                ef = ef - ef2;
                efPrecise = efPrecise - efPrecise2;
                break;
            case 3:
                // Multiplication.
                ef = ef * ef2;
                efPrecise = efPrecise * efPrecise2;
                break;
            case 4:
                // Division.
                if (ef.LowerBound() * ef.UpperBound() > 0 &&
                    ef2.LowerBound() * ef2.UpperBound() > 0) {
                    ef = ef / ef2;
                    efPrecise = efPrecise / efPrecise2;
                }
                break;
            case 5:
                // Sqrt.
                if (efPrecise >= 0 && ef.LowerBound() > 0) {
                    ef = sqrt(ef);
                    efPrecise = std::sqrt(efPrecise);
                }
                break;
            case 6:
                // Abs.
                ef = abs(ef);
                efPrecise = (efPrecise < 0) ? -efPrecise : efPrecise;
                break;
            }
        }
    }
}

TEST(FloatingPoint, AtomicFloat) {
    AtomicFloat af(0);
    Float f = 0.;
    EXPECT_EQ(f, af);
    af.Add(1.0251);
    f += 1.0251;
    EXPECT_EQ(f, af);
    af.Add(2.);
    f += 2.;
    EXPECT_EQ(f, af);
}
<|endoftext|>


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

#include <stddef.h>
#include <stdint.h>

#include <utility>

#include "base/bind.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "base/test/perf_time_logger.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/scoped_platform_handle.h"
#include "mojo/edk/system/handle_signals_state.h"
#include "mojo/edk/system/test_utils.h"
#include "mojo/edk/test/multiprocess_test_base.h"
#include "mojo/edk/test/test_utils.h"
#include "mojo/public/c/system/functions.h"
#include "mojo/public/cpp/system/message_pipe.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace mojo {
namespace edk {
namespace {

class MultiprocessMessagePipePerfTest : public test::MultiprocessTestBase {
 public:
  MultiprocessMessagePipePerfTest()
      : message_count_(0),
        message_size_(0) {}

  void SetUpMeasurement(int message_count, size_t message_size) {
    message_count_ = message_count;
    message_size_ = message_size;
    payload_ = std::string(message_size, '*');
    read_buffer_.resize(message_size * 2);
  }

 protected:
  void WriteWaitThenRead(MojoHandle mp) {
    CHECK_EQ(MojoWriteMessage(mp, payload_.data(),
                              static_cast<uint32_t>(payload_.size()), nullptr,
                              0, MOJO_WRITE_MESSAGE_FLAG_NONE),
             MOJO_RESULT_OK);
    HandleSignalsState hss;
    CHECK_EQ(MojoWait(mp, MOJO_HANDLE_SIGNAL_READABLE, MOJO_DEADLINE_INDEFINITE,
                      &hss),
             MOJO_RESULT_OK);
    uint32_t read_buffer_size = static_cast<uint32_t>(read_buffer_.size());
    CHECK_EQ(MojoReadMessage(mp, &read_buffer_[0], &read_buffer_size, nullptr,
                             nullptr, MOJO_READ_MESSAGE_FLAG_NONE),
             MOJO_RESULT_OK);
    CHECK_EQ(read_buffer_size, static_cast<uint32_t>(payload_.size()));
  }

  void SendQuitMessage(MojoHandle mp) {
    CHECK_EQ(MojoWriteMessage(mp, "", 0, nullptr, 0,
                              MOJO_WRITE_MESSAGE_FLAG_NONE),
             MOJO_RESULT_OK);
  }

  void Measure(MojoHandle mp) {
    // Have one ping-pong to ensure channel being established.
    WriteWaitThenRead(mp);

    std::string test_name =
        base::StringPrintf("IPC_Perf_%dx_%u", message_count_,
                           static_cast<unsigned>(message_size_));
    base::PerfTimeLogger logger(test_name.c_str());

    for (int i = 0; i < message_count_; ++i)
      WriteWaitThenRead(mp);

    logger.Done();
  }

 private:
  int message_count_;
  size_t message_size_;
  std::string payload_;
  std::string read_buffer_;
  scoped_ptr<base::PerfTimeLogger> perf_logger_;
};

// For each message received, sends a reply message with the same contents
// repeated twice, until the other end is closed or it receives "quitquitquit"
// (which it doesn't reply to). It'll return the number of messages received,
// not including any "quitquitquit" message, modulo 100.
DEFINE_TEST_CLIENT_WITH_PIPE(PingPongClient, MultiprocessMessagePipePerfTest,
                             h) {
  std::string buffer(1000000, '\0');
  int rv = 0;
  while (true) {
    // Wait for our end of the message pipe to be readable.
    HandleSignalsState hss;
    MojoResult result =
        MojoWait(h, MOJO_HANDLE_SIGNAL_READABLE,
                 MOJO_DEADLINE_INDEFINITE, &hss);
    if (result != MOJO_RESULT_OK) {
      rv = result;
      break;
    }

    uint32_t read_size = static_cast<uint32_t>(buffer.size());
    CHECK_EQ(MojoReadMessage(h, &buffer[0],
                             &read_size, nullptr,
                             0, MOJO_READ_MESSAGE_FLAG_NONE),
             MOJO_RESULT_OK);

    // Empty message indicates quit.
    if (read_size == 0)
      break;

    CHECK_EQ(MojoWriteMessage(h, &buffer[0],
                              read_size,
                              nullptr, 0, MOJO_WRITE_MESSAGE_FLAG_NONE),
             MOJO_RESULT_OK);
  }

  return rv;
}

// Repeatedly sends messages as previous one got replied by the child.
// Waits for the child to close its end before quitting once specified
// number of messages has been sent.
#if defined(OS_ANDROID)
// Android multi-process tests are not executing the new process. This is flaky.
#define MAYBE_PingPong DISABLED_PingPong
#else
#define MAYBE_PingPong PingPong
#endif  // defined(OS_ANDROID)
TEST_F(MultiprocessMessagePipePerfTest, MAYBE_PingPong) {
  RUN_CHILD_ON_PIPE(PingPongClient, h)
    // This values are set to align with one at ipc_pertests.cc for comparison.
    const size_t kMsgSize[5] = {12, 144, 1728, 20736, 248832};
    const int kMessageCount[5] = {50000, 50000, 50000, 12000, 1000};

    for (size_t i = 0; i < 5; i++) {
      SetUpMeasurement(kMessageCount[i], kMsgSize[i]);
      Measure(h);
    }

    SendQuitMessage(h);
  END_CHILD()
}

}  // namespace
}  // namespace edk
}  // namespace mojo
<commit_msg>update perf test<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stddef.h>
#include <stdint.h>

#include <utility>

#include "base/bind.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "base/test/perf_time_logger.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/scoped_platform_handle.h"
#include "mojo/edk/system/handle_signals_state.h"
#include "mojo/edk/system/test_utils.h"
#include "mojo/edk/test/mojo_test_base.h"
#include "mojo/edk/test/test_utils.h"
#include "mojo/public/c/system/functions.h"
#include "mojo/public/cpp/system/message_pipe.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace mojo {
namespace edk {
namespace {

class MultiprocessMessagePipePerfTest : public test::MojoTestBase {
 public:
  MultiprocessMessagePipePerfTest()
      : message_count_(0),
        message_size_(0) {}

  void SetUpMeasurement(int message_count, size_t message_size) {
    message_count_ = message_count;
    message_size_ = message_size;
    payload_ = std::string(message_size, '*');
    read_buffer_.resize(message_size * 2);
  }

 protected:
  void WriteWaitThenRead(MojoHandle mp) {
    CHECK_EQ(MojoWriteMessage(mp, payload_.data(),
                              static_cast<uint32_t>(payload_.size()), nullptr,
                              0, MOJO_WRITE_MESSAGE_FLAG_NONE),
             MOJO_RESULT_OK);
    HandleSignalsState hss;
    CHECK_EQ(MojoWait(mp, MOJO_HANDLE_SIGNAL_READABLE, MOJO_DEADLINE_INDEFINITE,
                      &hss),
             MOJO_RESULT_OK);
    uint32_t read_buffer_size = static_cast<uint32_t>(read_buffer_.size());
    CHECK_EQ(MojoReadMessage(mp, &read_buffer_[0], &read_buffer_size, nullptr,
                             nullptr, MOJO_READ_MESSAGE_FLAG_NONE),
             MOJO_RESULT_OK);
    CHECK_EQ(read_buffer_size, static_cast<uint32_t>(payload_.size()));
  }

  void SendQuitMessage(MojoHandle mp) {
    CHECK_EQ(MojoWriteMessage(mp, "", 0, nullptr, 0,
                              MOJO_WRITE_MESSAGE_FLAG_NONE),
             MOJO_RESULT_OK);
  }

  void Measure(MojoHandle mp) {
    // Have one ping-pong to ensure channel being established.
    WriteWaitThenRead(mp);

    std::string test_name =
        base::StringPrintf("IPC_Perf_%dx_%u", message_count_,
                           static_cast<unsigned>(message_size_));
    base::PerfTimeLogger logger(test_name.c_str());

    for (int i = 0; i < message_count_; ++i)
      WriteWaitThenRead(mp);

    logger.Done();
  }

 private:
  int message_count_;
  size_t message_size_;
  std::string payload_;
  std::string read_buffer_;
  scoped_ptr<base::PerfTimeLogger> perf_logger_;
};

// For each message received, sends a reply message with the same contents
// repeated twice, until the other end is closed or it receives "quitquitquit"
// (which it doesn't reply to). It'll return the number of messages received,
// not including any "quitquitquit" message, modulo 100.
DEFINE_TEST_CLIENT_WITH_PIPE(PingPongClient, MultiprocessMessagePipePerfTest,
                             h) {
  std::string buffer(1000000, '\0');
  int rv = 0;
  while (true) {
    // Wait for our end of the message pipe to be readable.
    HandleSignalsState hss;
    MojoResult result =
        MojoWait(h, MOJO_HANDLE_SIGNAL_READABLE,
                 MOJO_DEADLINE_INDEFINITE, &hss);
    if (result != MOJO_RESULT_OK) {
      rv = result;
      break;
    }

    uint32_t read_size = static_cast<uint32_t>(buffer.size());
    CHECK_EQ(MojoReadMessage(h, &buffer[0],
                             &read_size, nullptr,
                             0, MOJO_READ_MESSAGE_FLAG_NONE),
             MOJO_RESULT_OK);

    // Empty message indicates quit.
    if (read_size == 0)
      break;

    CHECK_EQ(MojoWriteMessage(h, &buffer[0],
                              read_size,
                              nullptr, 0, MOJO_WRITE_MESSAGE_FLAG_NONE),
             MOJO_RESULT_OK);
  }

  return rv;
}

// Repeatedly sends messages as previous one got replied by the child.
// Waits for the child to close its end before quitting once specified
// number of messages has been sent.
#if defined(OS_ANDROID)
// Android multi-process tests are not executing the new process. This is flaky.
#define MAYBE_PingPong DISABLED_PingPong
#else
#define MAYBE_PingPong PingPong
#endif  // defined(OS_ANDROID)
TEST_F(MultiprocessMessagePipePerfTest, MAYBE_PingPong) {
  RUN_CHILD_ON_PIPE(PingPongClient, h)
    // This values are set to align with one at ipc_pertests.cc for comparison.
    const size_t kMsgSize[5] = {12, 144, 1728, 20736, 248832};
    const int kMessageCount[5] = {50000, 50000, 50000, 12000, 1000};

    for (size_t i = 0; i < 5; i++) {
      SetUpMeasurement(kMessageCount[i], kMsgSize[i]);
      Measure(h);
    }

    SendQuitMessage(h);
  END_CHILD()
}

}  // namespace
}  // namespace edk
}  // namespace mojo
<|endoftext|>


<commit_before>#include "keyboard_input.hpp"
#include "assert.hpp"

#include <ncurses.h>

#include <algorithm>
#include <vector>

using namespace std;

#define ASSERT_INVARIANTS                  \
                                           \
    ASSERT( pos >= 0 )                     \
    ASSERT( pos <= (int)buffer.length() );

KeyboardInput::KeyboardInput() : buffer()
                               , pos( 0 ) {
    ASSERT_INVARIANTS
}

void KeyboardInput::clear() {
    buffer.clear();
    pos = 0;
    ASSERT_INVARIANTS
}

static bool is_char_allowed( char c ) {
    static string const cs{
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "0123456789 +-*/^._,()[]!@#$%&={}|?<>`~"
    };
    return find( begin( cs ), end( cs ), c ) != end( cs );
}

void KeyboardInput::key_press( bool        ctrl,
                               bool        alt,
                               int         pressed,
                               char const* name ) {
    if( ctrl && !alt ) {
        if( name[1] == 'U' ) {
            buffer.erase( 0, pos );
            pos = 0;
            ASSERT_INVARIANTS
        }
        return;
    }
    if( pressed < 128 && is_char_allowed( char( pressed ) ) ) {
        buffer.insert( pos, 1, char( pressed ) );
        ++pos;
        ASSERT_INVARIANTS
        return;
    }
    switch( pressed ) {

    case KEY_LEFT:
        --pos;
        pos = (pos < 0) ? 0 : pos;
        ASSERT_INVARIANTS
        return;

    case KEY_RIGHT:
        ++pos;
        pos = (pos > (int)buffer.length()) ? buffer.length() : pos;
        ASSERT_INVARIANTS
        return;

    case KEY_BACKSPACE:
        if( pos > 0 ) {
            buffer.erase( pos-1, 1 );
            --pos;
            ASSERT_INVARIANTS
        }
        return;

    case KEY_DC:
        if( pos < (int)buffer.length() ) {
            buffer.erase( pos, 1 );
            ASSERT_INVARIANTS
        }
        return;

    case KEY_END:
        pos = buffer.length();
        ASSERT_INVARIANTS
        return;

    case KEY_HOME:
        pos = 0;
        ASSERT_INVARIANTS
        return;
    };
    ASSERT_INVARIANTS
}
<commit_msg>Fix backspace key on os x<commit_after>#include "keyboard_input.hpp"
#include "assert.hpp"

#include <ncurses.h>

#include <algorithm>
#include <vector>

using namespace std;

#define ASSERT_INVARIANTS                  \
                                           \
    ASSERT( pos >= 0 )                     \
    ASSERT( pos <= (int)buffer.length() );

KeyboardInput::KeyboardInput() : buffer()
                               , pos( 0 ) {
    ASSERT_INVARIANTS
}

void KeyboardInput::clear() {
    buffer.clear();
    pos = 0;
    ASSERT_INVARIANTS
}

static bool is_char_allowed( char c ) {
    static string const cs{
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "0123456789 +-*/^._,()[]!@#$%&={}|?<>`~"
    };
    return find( begin( cs ), end( cs ), c ) != end( cs );
}

void KeyboardInput::key_press( bool        ctrl,
                               bool        alt,
                               int         pressed,
                               char const* name ) {
    if( ctrl && !alt ) {
        if( name[1] == 'U' ) {
            buffer.erase( 0, pos );
            pos = 0;
            ASSERT_INVARIANTS
            return;
        }
        if( pressed == 0x7f ) {
            // Hack for OS X in which backspace seems
            // to appear as a control character with
            // the key being 0x7f.
            pressed = KEY_BACKSPACE;
            ctrl = alt = false;
        }
    }
    if( pressed < 128 && is_char_allowed( char( pressed ) ) ) {
        buffer.insert( pos, 1, char( pressed ) );
        ++pos;
        ASSERT_INVARIANTS
        return;
    }
    switch( pressed ) {

    case KEY_LEFT:
        --pos;
        pos = (pos < 0) ? 0 : pos;
        ASSERT_INVARIANTS
        return;

    case KEY_RIGHT:
        ++pos;
        pos = (pos > (int)buffer.length()) ? buffer.length() : pos;
        ASSERT_INVARIANTS
        return;

    case KEY_BACKSPACE:
        if( pos > 0 ) {
            buffer.erase( pos-1, 1 );
            --pos;
            ASSERT_INVARIANTS
        }
        return;

    case KEY_DC:
        if( pos < (int)buffer.length() ) {
            buffer.erase( pos, 1 );
            ASSERT_INVARIANTS
        }
        return;

    case KEY_END:
        pos = buffer.length();
        ASSERT_INVARIANTS
        return;

    case KEY_HOME:
        pos = 0;
        ASSERT_INVARIANTS
        return;
    };
    ASSERT_INVARIANTS
}
<|endoftext|>