<commit_before>#ifndef HASH_ID_HPP_
#define HASH_ID_HPP_

#include <chrono>
#include <cstring>
#include <functional>
#include <iomanip>
#include <random>
#include <sstream>

namespace sm {

/**
 * 128 bit hash. Can be used as key to unordered containers.
 */
class HashId {
 public:
  /**
   * Initializes to an invalid Hash
   */
  inline HashId() {
    setInvalid();
  }
  /**
   * Copy constructor
   */
  inline HashId(const HashId& other){
    *this = other;
  }

  /**
   * Generates a random Hash ID seeded from the nanosecond time of the first
   * call of this function
   */
  inline static HashId random() {
    HashId generated;
    generated.randomize();
    return generated;
  }

  /**
   * Returns hexadecimal string for debugging or serialization
   */
  inline const std::string hexString() const {
    std::ostringstream ss;
    for (size_t i = 0; i < sizeof(val_); ++i){
      ss << std::hex << std::setfill('0') << std::setw(2) <<
          static_cast<int>(val_.c[i]);
    }
    return ss.str();
  }

  /**
   * Deserialize from hexadecimal string. Serialization and Deserialization
   * could be made more performant by using blobs.
   */
  inline bool fromHexString(const std::string& hexString) {
    // hexadecimal string takes 2 characters per byte
    if (hexString.size() != 2*sizeof(val_)){
      return false;
    }
    for (size_t i = 0; i < sizeof(val_); ++i){
      unsigned int integerValue;
      std::istringstream ss(std::string(hexString, 2*i, 2));
      ss >> std::hex >> integerValue;
      val_.c[i] = static_cast<unsigned char>(integerValue);
    }
    return true;
  }

  /**
   * Randomizes to ID seeded from the nanosecond time of the first
   * call of this function
   */
  inline void randomize(){
    static std::mt19937_64 rng(time64());
    val_.u64[0] = rng();
    val_.u64[1] = rng();
  }

  inline void operator =(const HashId& other) {
    memcpy(&val_, &other.val_, sizeof(val_));
  }

  inline bool operator <(const HashId& other) const {
    if (val_.u64[0] == other.val_.u64[0]){
      return val_.u64[1] < other.val_.u64[1];
    }
    return val_.u64[0] < other.val_.u64[0];
  }
  inline bool operator >(const HashId& other) const {
    if (val_.u64[0] == other.val_.u64[0]){
      return val_.u64[1] > other.val_.u64[1];
    }
    return val_.u64[0] > other.val_.u64[0];
  }
  inline bool operator ==(const HashId& other) const {
    return val_.u64[0] == other.val_.u64[0] && val_.u64[1] == other.val_.u64[1];
  }
  inline bool operator !=(const HashId& other) const{
    return !(*this == other);
  }

  /**
   * Invalidation mechanism
   */
  inline void setInvalid() {
    memset(&val_, 0, sizeof(val_));
  }
  inline bool isValid() const {
    return val_.u64[0] != 0 || val_.u64[1] != 0;
  }

 private:
  /**
   * Time seed from nanoseconds. Covers 584 years if we assume no two agents
   * initialize in the same nanosecond.
   */
  inline static int64_t time64() {
    std::chrono::high_resolution_clock::duration current =
        std::chrono::high_resolution_clock::now().time_since_epoch();
    using std::chrono::duration_cast;
    using std::chrono::nanoseconds;
    // count() specified to return at least 64 bits
    return duration_cast<nanoseconds>(current).count();
  }

  /**
   * Internal representation
   */
  union HashVal {
    unsigned char c[16];
    uint_fast64_t u64[2];
  };
  HashVal val_;
};

std::ostream& operator<<( std::ostream& out, const sm::HashId& hash ) {
  out << hash.hexString();
  return out;
}

} // namespace sm

namespace std{
  template<>
  struct hash<sm::HashId>{
    typedef sm::HashId argument_type;
    typedef std::size_t value_type;

    value_type operator()(const argument_type& hashId) const {
      return std::hash<std::string>()(hashId.hexString());
    }
  };
} // namespace std

#endif /* HASH_ID_HPP_ */
<commit_msg>Fixed non-inline definition in header which caused multiple definition when linking.<commit_after>#ifndef HASH_ID_HPP_
#define HASH_ID_HPP_

#include <chrono>
#include <cstring>
#include <functional>
#include <iomanip>
#include <random>
#include <sstream>

namespace sm {

/**
 * 128 bit hash. Can be used as key to unordered containers.
 */
class HashId {
 public:
  /**
   * Initializes to an invalid Hash
   */
  inline HashId() {
    setInvalid();
  }
  /**
   * Copy constructor
   */
  inline HashId(const HashId& other){
    *this = other;
  }

  /**
   * Generates a random Hash ID seeded from the nanosecond time of the first
   * call of this function
   */
  inline static HashId random() {
    HashId generated;
    generated.randomize();
    return generated;
  }

  /**
   * Returns hexadecimal string for debugging or serialization
   */
  inline const std::string hexString() const {
    std::ostringstream ss;
    for (size_t i = 0; i < sizeof(val_); ++i){
      ss << std::hex << std::setfill('0') << std::setw(2) <<
          static_cast<int>(val_.c[i]);
    }
    return ss.str();
  }

  /**
   * Deserialize from hexadecimal string. Serialization and Deserialization
   * could be made more performant by using blobs.
   */
  inline bool fromHexString(const std::string& hexString) {
    // hexadecimal string takes 2 characters per byte
    if (hexString.size() != 2*sizeof(val_)){
      return false;
    }
    for (size_t i = 0; i < sizeof(val_); ++i){
      unsigned int integerValue;
      std::istringstream ss(std::string(hexString, 2*i, 2));
      ss >> std::hex >> integerValue;
      val_.c[i] = static_cast<unsigned char>(integerValue);
    }
    return true;
  }

  /**
   * Randomizes to ID seeded from the nanosecond time of the first
   * call of this function
   */
  inline void randomize(){
    static std::mt19937_64 rng(time64());
    val_.u64[0] = rng();
    val_.u64[1] = rng();
  }

  inline void operator =(const HashId& other) {
    memcpy(&val_, &other.val_, sizeof(val_));
  }

  inline bool operator <(const HashId& other) const {
    if (val_.u64[0] == other.val_.u64[0]){
      return val_.u64[1] < other.val_.u64[1];
    }
    return val_.u64[0] < other.val_.u64[0];
  }
  inline bool operator >(const HashId& other) const {
    if (val_.u64[0] == other.val_.u64[0]){
      return val_.u64[1] > other.val_.u64[1];
    }
    return val_.u64[0] > other.val_.u64[0];
  }
  inline bool operator ==(const HashId& other) const {
    return val_.u64[0] == other.val_.u64[0] && val_.u64[1] == other.val_.u64[1];
  }
  inline bool operator !=(const HashId& other) const{
    return !(*this == other);
  }

  /**
   * Invalidation mechanism
   */
  inline void setInvalid() {
    memset(&val_, 0, sizeof(val_));
  }
  inline bool isValid() const {
    return val_.u64[0] != 0 || val_.u64[1] != 0;
  }

 private:
  /**
   * Time seed from nanoseconds. Covers 584 years if we assume no two agents
   * initialize in the same nanosecond.
   */
  inline static int64_t time64() {
    std::chrono::high_resolution_clock::duration current =
        std::chrono::high_resolution_clock::now().time_since_epoch();
    using std::chrono::duration_cast;
    using std::chrono::nanoseconds;
    // count() specified to return at least 64 bits
    return duration_cast<nanoseconds>(current).count();
  }

  /**
   * Internal representation
   */
  union HashVal {
    unsigned char c[16];
    uint_fast64_t u64[2];
  };
  HashVal val_;
};

} // namespace sm

namespace std{

inline ostream& operator<<(ostream& out, const sm::HashId& hash) {
  out << hash.hexString();
  return out;
}

template<>
struct hash<sm::HashId>{
  typedef sm::HashId argument_type;
  typedef std::size_t value_type;

  value_type operator()(const argument_type& hashId) const {
    return std::hash<std::string>()(hashId.hexString());
  }
};
} // namespace std

#endif /* HASH_ID_HPP_ */
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: dockWidget.C,v 1.3 2003/09/08 16:39:40 amoll Exp $

#include <BALL/VIEW/WIDGETS/dockWidget.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <qmenubar.h>
#include <qlabel.h>

using std::endl;

namespace BALL
{
	namespace VIEW
	{

DockWidget::DockWidget(QWidget* parent, const char* name)
: QDockWindow(QDockWindow::InDock, parent),
	ModularWidget(name)
{
  caption_label_ = new QLabel(this, "caption_label");
	caption_label_->resize(120, 12);
  caption_label_->setSizePolicy( QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed, 0, 0, false));
  caption_label_->setPaletteBackgroundColor( QColor( 255, 255, 127 ) );
  QFont caption_label_font(caption_label_->font());
  caption_label_font.setFamily( "Helvetica" );
  caption_label_font.setPointSize( 11 );
  caption_label_->setFont( caption_label_font );
  caption_label_->setFrameShape(QLabel::NoFrame);
  caption_label_->setAlignment(QLabel::AlignCenter);

	setOrientation(Qt::Vertical);
	boxLayout()->addWidget(caption_label_);
  resize( QSize(132, 293));

	if (name != 0)
	{
		setCaption(name);
		setName(name);
		caption_label_->setText(name);
	}
	else
	{
		setName("DockWidget");
	}

	registerWidget(this);
}

void DockWidget::setGuest(QWidget& guest)
{
	QPoint p;
	guest.reparent(this, p, true);
	guest.resize(120,1000);
  guest.setSizePolicy( QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding, 0, 0, false));
	boxLayout()->addWidget(&guest);
	setMinimumSize(20, 20);
	setCloseMode(QDockWindow::Always);
	setResizeEnabled(true);
}

void DockWidget::initializeWidget(MainControl& main_control)
	throw()
{
	window_menu_entry_id_ =
		main_control.insertMenuEntry(MainControl::WINDOWS, getIdentifier(), this, SLOT(switchShowWidget()));
	getMainControl()->menuBar()->setItemChecked(window_menu_entry_id_, true);
}

void DockWidget::finalizeWidget(MainControl& main_control)
	throw()
{
	main_control.removeMenuEntry(MainControl::WINDOWS, getIdentifier(), this, SLOT(switchShowWidget()));
}

void DockWidget::switchShowWidget()
	throw()
{
	QMenuBar* menu = getMainControl()->menuBar();
	if (menu->isItemChecked(window_menu_entry_id_))
	{
		hide();
		menu->setItemChecked(window_menu_entry_id_, false);
	}
	else
	{
		show();
		menu->setItemChecked(window_menu_entry_id_, true);
	}
}

void DockWidget::writePreferences(INIFile& inifile)
	throw()
{
	inifile.insertValue("WINDOWS", getIdentifier() + "::on",
		String(getMainControl()->menuBar()->isItemChecked(window_menu_entry_id_)));
}

void DockWidget::fetchPreferences(INIFile & inifile)
	throw()
{
	if (!inifile.hasEntry("WINDOWS", getIdentifier() + "::on")) return;
	if (inifile.getValue( "WINDOWS", getIdentifier() + "::on").toUnsignedInt() == 0)
	{
		switchShowWidget();
	}
}

void DockWidget::close()
{
Log.error() << "#~~#   1" << std::endl;
	QDockWindow::close();
}

} } // namespaces
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: dockWidget.C,v 1.4 2003/09/09 23:23:22 amoll Exp $

#include <BALL/VIEW/WIDGETS/dockWidget.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <qmenubar.h>
#include <qlabel.h>

using std::endl;

namespace BALL
{
	namespace VIEW
	{

DockWidget::DockWidget(QWidget* parent, const char* name)
: QDockWindow(QDockWindow::InDock, parent),
	ModularWidget(name)
{
	layout_ = new QVBoxLayout(this);
  caption_label_ = new QLabel(this, "caption_label");
	caption_label_->resize(120, 12);
  caption_label_->setSizePolicy( QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed, 0, 0, false));
  caption_label_->setPaletteBackgroundColor( QColor( 255, 255, 127 ) );
  QFont caption_label_font(caption_label_->font());
  caption_label_font.setFamily( "Helvetica" );
  caption_label_font.setPointSize( 11 );
  caption_label_->setFont( caption_label_font );
  caption_label_->setFrameShape(QLabel::NoFrame);
  caption_label_->setAlignment(QLabel::AlignCenter);
	layout_->addWidget(caption_label_);
	boxLayout()->addItem(layout_);

	setOrientation(Qt::Vertical);
  resize( QSize(132, 293));

	if (name != 0)
	{
		setCaption(name);
		setName(name);
		caption_label_->setText(name);
	}
	else
	{
		setName("DockWidget");
	}

	registerWidget(this);
}

void DockWidget::setGuest(QWidget& guest)
{
	QPoint p;
	guest.reparent(this, p, true);
	guest.resize(120,1000);
  guest.setSizePolicy( QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding, 0, 0, false));
	layout_->addWidget(&guest);
	setMinimumSize(20, 20);
	setCloseMode(QDockWindow::Always);
	setResizeEnabled(true);
}

void DockWidget::initializeWidget(MainControl& main_control)
	throw()
{
	window_menu_entry_id_ =
		main_control.insertMenuEntry(MainControl::WINDOWS, getIdentifier(), this, SLOT(switchShowWidget()));
	getMainControl()->menuBar()->setItemChecked(window_menu_entry_id_, true);
}

void DockWidget::finalizeWidget(MainControl& main_control)
	throw()
{
	main_control.removeMenuEntry(MainControl::WINDOWS, getIdentifier(), this, SLOT(switchShowWidget()));
}

void DockWidget::switchShowWidget()
	throw()
{
	QMenuBar* menu = getMainControl()->menuBar();
	if (menu->isItemChecked(window_menu_entry_id_))
	{
		hide();
		menu->setItemChecked(window_menu_entry_id_, false);
	}
	else
	{
		show();
		menu->setItemChecked(window_menu_entry_id_, true);
	}
}

void DockWidget::writePreferences(INIFile& inifile)
	throw()
{
	inifile.insertValue("WINDOWS", getIdentifier() + "::on",
		String(getMainControl()->menuBar()->isItemChecked(window_menu_entry_id_)));
}

void DockWidget::fetchPreferences(INIFile & inifile)
	throw()
{
	if (!inifile.hasEntry("WINDOWS", getIdentifier() + "::on")) return;
	if (inifile.getValue( "WINDOWS", getIdentifier() + "::on").toUnsignedInt() == 0)
	{
		switchShowWidget();
	}
}

void DockWidget::close()
{
Log.error() << "#~~#   1" << std::endl;
	QDockWindow::close();
}

} } // namespaces
<|endoftext|>


<commit_before>// v2.1.0: this model doesn't always converge to the expected distribution
#include <gtest/gtest.h>
#include <test/CmdStan/models/model_test_fixture.hpp>

class Models_BugsExamples_Vol3_HepatitisME :
  public Model_Test_Fixture<Models_BugsExamples_Vol3_HepatitisME> {
protected:
  virtual void SetUp() {}
public:
  static std::vector<std::string> get_model_path() {
    std::vector<std::string> model_path;
    model_path.push_back("models");
    model_path.push_back("bugs_examples");
    model_path.push_back("vol3");
    model_path.push_back("hepatitis");
    model_path.push_back("hepatitisME");
    return model_path;
  }
  static bool has_data() {
    return true;
  }

  static bool has_init() {
    return false;
  }

  static int num_iterations() {
    return 5000;
  }

  static std::vector<int> skip_chains_test() {
    std::vector<int> params_to_skip;
    return params_to_skip;
  }

  static void populate_chains() {
    default_populate_chains();
  }

  static std::vector<std::pair<int, double> >
  get_expected_values() {
    using std::make_pair;
    std::vector<std::pair<int, double> > expected_values;

    expected_values.push_back(make_pair(chains->index("alpha0"), 6.129));
    expected_values.push_back(make_pair(chains->index("beta0"), -1.075));
    expected_values.push_back(make_pair(chains->index("gamma"), 1.082));
    expected_values.push_back(make_pair(chains->index("sigma_y"), 1.029));

    return expected_values;
  }

};

INSTANTIATE_TYPED_TEST_CASE_P(Models_BugsExamples_Vol3_HepatitisME,
            Model_Test_Fixture,
            Models_BugsExamples_Vol3_HepatitisME);
<commit_msg>disabling bugs_examples/vol3/hepatits/hepatitsME test<commit_after>// v2.1.0: this model doesn't always converge to the expected distribution
#include <gtest/gtest.h>
#include <test/CmdStan/models/model_test_fixture.hpp>

class Models_BugsExamples_Vol3_HepatitisME :
  public Model_Test_Fixture<Models_BugsExamples_Vol3_HepatitisME> {
protected:
  virtual void SetUp() {}
public:
  static std::vector<std::string> get_model_path() {
    std::vector<std::string> model_path;
    model_path.push_back("models");
    model_path.push_back("bugs_examples");
    model_path.push_back("vol3");
    model_path.push_back("hepatitis");
    model_path.push_back("hepatitisME");
    return model_path;
  }
  static bool has_data() {
    return true;
  }

  static bool has_init() {
    return false;
  }

  static int num_iterations() {
    return 5000;
  }

  static std::vector<int> skip_chains_test() {
    std::vector<int> params_to_skip;
    return params_to_skip;
  }

  static void populate_chains() {
    default_populate_chains();
  }

  static std::vector<std::pair<int, double> >
  get_expected_values() {
    using std::make_pair;
    std::vector<std::pair<int, double> > expected_values;

    expected_values.push_back(make_pair(chains->index("alpha0"), 6.129));
    expected_values.push_back(make_pair(chains->index("beta0"), -1.075));
    expected_values.push_back(make_pair(chains->index("gamma"), 1.082));
    expected_values.push_back(make_pair(chains->index("sigma_y"), 1.029));

    return expected_values;
  }

};

INSTANTIATE_TYPED_TEST_CASE_P(DISABLED_Models_BugsExamples_Vol3_HepatitisME,
            Model_Test_Fixture,
            Models_BugsExamples_Vol3_HepatitisME);
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// ConstantValue.cpp
// Compile-time constant representation
//
// File is under the MIT license; see LICENSE for details
//------------------------------------------------------------------------------
#include "slang/numeric/ConstantValue.h"

#include "../text/FormatBuffer.h"
#include <fmt/format.h>

#include "slang/util/Hash.h"

namespace slang {

template<typename T>
struct always_false : std::false_type {};

const ConstantValue ConstantValue::Invalid;

std::string ConstantValue::toString() const {
    return std::visit(
        [](auto&& arg) {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, std::monostate>)
                return "<unset>"s;
            else if constexpr (std::is_same_v<T, SVInt>)
                return arg.toString();
            else if constexpr (std::is_same_v<T, real_t>)
                return fmt::format("{}", double(arg));
            else if constexpr (std::is_same_v<T, shortreal_t>)
                return fmt::format("{}", float(arg));
            else if constexpr (std::is_same_v<T, ConstantValue::NullPlaceholder>)
                return "null"s;
            else if constexpr (std::is_same_v<T, Elements>) {
                FormatBuffer buffer;
                buffer.append("[");
                for (auto& element : arg) {
                    buffer.append(element.toString());
                    buffer.append(",");
                }

                if (!arg.empty())
                    buffer.pop_back();
                buffer.append("]");
                return buffer.str();
            }
            else if constexpr (std::is_same_v<T, std::string>)
                return arg;
            else if constexpr (std::is_same_v<T, Map>) {
                FormatBuffer buffer;
                buffer.append("[");
                for (auto& [key, val] : *arg)
                    buffer.format("{}:{},", key.toString(), val.toString());

                if (arg->defaultValue)
                    buffer.format("default:{}", arg->defaultValue.toString());
                else if (!arg->empty())
                    buffer.pop_back();

                buffer.append("]");
                return buffer.str();
            }
            else if constexpr (std::is_same_v<T, Queue>) {
                FormatBuffer buffer;
                buffer.append("[");
                for (auto& element : *arg) {
                    buffer.append(element.toString());
                    buffer.append(",");
                }

                if (!arg->empty())
                    buffer.pop_back();
                buffer.append("]");
                return buffer.str();
            }
            else
                static_assert(always_false<T>::value, "Missing case");
        },
        value);
}

size_t ConstantValue::hash() const {
    size_t h = value.index();
    std::visit(
        [&h](auto&& arg) noexcept {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, std::monostate>)
                hash_combine(h, 0);
            else if constexpr (std::is_same_v<T, SVInt>)
                hash_combine(h, arg.hash());
            else if constexpr (std::is_same_v<T, real_t>)
                hash_combine(h, std::hash<double>()(arg));
            else if constexpr (std::is_same_v<T, shortreal_t>)
                hash_combine(h, std::hash<float>()(arg));
            else if constexpr (std::is_same_v<T, ConstantValue::NullPlaceholder>)
                hash_combine(h, 0);
            else if constexpr (std::is_same_v<T, Elements>) {
                for (auto& element : arg)
                    hash_combine(h, element.hash());
            }
            else if constexpr (std::is_same_v<T, std::string>)
                hash_combine(h, std::hash<std::string>()(arg));
            else if constexpr (std::is_same_v<T, Map>) {
                for (auto& [key, val] : *arg) {
                    hash_combine(h, key.hash());
                    hash_combine(h, val.hash());
                }
            }
            else if constexpr (std::is_same_v<T, Queue>) {
                for (auto& element : *arg)
                    hash_combine(h, element.hash());
            }
            else {
                static_assert(always_false<T>::value, "Missing case");
            }
        },
        value);
    return h;
}

ConstantValue ConstantValue::getSlice(int32_t upper, int32_t lower,
                                      const ConstantValue& defaultValue) const {
    if (isInteger())
        return integer().slice(upper, lower);

    if (isUnpacked()) {
        span<const ConstantValue> elems = elements();
        std::vector<ConstantValue> result{ size_t(upper - lower + 1) };
        ConstantValue* dest = result.data();

        for (int32_t i = lower; i <= upper; i++) {
            if (i < 0 || size_t(i) >= elems.size())
                *dest++ = defaultValue;
            else
                *dest++ = elems[size_t(i)];
        }

        return result;
    }

    if (isQueue()) {
        auto& q = *queue();
        SVQueue result;
        for (int32_t i = lower; i <= upper; i++) {
            if (i >= 0 && i < q.size())
                result.push_back(q[size_t(i)]);
        }

        return result;
    }

    if (isString()) {
        ASSERT(upper == lower);
        ASSERT(upper >= 0);
        return SVInt(8, (uint64_t)str()[size_t(upper)], false);
    }

    return nullptr;
}

bool ConstantValue::isTrue() const {
    return std::visit(
        [](auto&& arg) noexcept {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, SVInt>)
                return (bool)(logic_t)arg;
            else if constexpr (std::is_same_v<T, real_t>)
                return (bool)arg;
            else if constexpr (std::is_same_v<T, shortreal_t>)
                return (bool)arg;
            else
                return false;
        },
        value);
}

bool ConstantValue::isFalse() const {
    return std::visit(
        [](auto&& arg) noexcept {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, SVInt>) {
                logic_t l = (logic_t)arg;
                return !l.isUnknown() && l.value == 0;
            }
            else if constexpr (std::is_same_v<T, real_t>)
                return !(bool)arg;
            else if constexpr (std::is_same_v<T, shortreal_t>)
                return !(bool)arg;
            else if constexpr (std::is_same_v<T, ConstantValue::NullPlaceholder>)
                return true;
            else
                return false;
        },
        value);
}

bool ConstantValue::hasUnknown() const {
    return std::visit(
        [](auto&& arg) noexcept {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, SVInt>) {
                return arg.hasUnknown();
            }
            else if constexpr (std::is_same_v<T, Elements>) {
                for (auto& element : arg) {
                    if (element.hasUnknown())
                        return true;
                }
                return false;
            }
            else if constexpr (std::is_same_v<T, Map>) {
                for (auto& [key, val] : *arg) {
                    if (key.hasUnknown() || val.hasUnknown())
                        return true;
                }
                return false;
            }
            else if constexpr (std::is_same_v<T, Queue>) {
                for (auto& element : *arg) {
                    if (element.hasUnknown())
                        return true;
                }
                return false;
            }
            else {
                return false;
            }
        },
        value);
}

ConstantValue ConstantValue::convertToInt(bitwidth_t width, bool isSigned, bool isFourState) const {
    if (isReal())
        return SVInt::fromDouble(width, real(), isSigned);

    if (isShortReal())
        return SVInt::fromFloat(width, shortReal(), isSigned);

    if (!isInteger())
        return nullptr;

    SVInt result = integer();
    if (!isFourState)
        result.flattenUnknowns();

    // [11.8.3] says that during an assignment we sign extend iff the rhs is signed.
    // That means we should resize first, and only then change the sign flag if desired.
    if (width != result.getBitWidth())
        result = result.resize(width);

    result.setSigned(isSigned);
    return result;
}

ConstantValue ConstantValue::convertToReal() const {
    if (isReal())
        return *this;

    if (isShortReal())
        return real_t(shortReal());

    if (isInteger())
        return real_t(integer().toDouble());

    return nullptr;
}

ConstantValue ConstantValue::convertToShortReal() const {
    if (isShortReal())
        return *this;

    if (isReal())
        return shortreal_t((float)real());

    if (isInteger())
        return shortreal_t(integer().toFloat());

    return nullptr;
}

ConstantValue ConstantValue::convertToStr() const {
    if (isString())
        return *this;

    if (!isInteger())
        return nullptr;

    // Conversion is described in [6.16]: take each 8 bit chunk,
    // remove it if it's zero, otherwise add as character to the string.
    // TODO: unknown bits?

    const SVInt& val = integer();
    int32_t msb = int32_t(val.getBitWidth() - 1);
    int32_t extraBits = int32_t(val.getBitWidth() % 8);

    std::string result;
    if (extraBits) {
        auto c = val.slice(msb, msb - extraBits + 1).as<uint8_t>();
        if (c && *c)
            result.push_back(char(*c));
        msb -= extraBits;
    }

    while (msb >= 7) {
        auto c = val.slice(msb, msb - 7).as<uint8_t>();
        if (c && *c)
            result.push_back(char(*c));
        msb -= 8;
    }

    return result;
}

std::ostream& operator<<(std::ostream& os, const ConstantValue& cv) {
    return os << cv.toString();
}

bool operator==(const ConstantValue& lhs, const ConstantValue& rhs) {
    return std::visit(
        [&](auto&& arg) noexcept(
            !std::is_same_v<std::decay_t<decltype(arg)>, ConstantValue::Elements>) {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, std::monostate>)
                return rhs.bad();
            else if constexpr (std::is_same_v<T, SVInt>)
                return rhs.isInteger() && exactlyEqual(arg, rhs.integer());
            else if constexpr (std::is_same_v<T, real_t>)
                return rhs.isReal() && arg == double(rhs.real());
            else if constexpr (std::is_same_v<T, shortreal_t>)
                return rhs.isShortReal() && arg == float(rhs.shortReal());
            else if constexpr (std::is_same_v<T, ConstantValue::NullPlaceholder>)
                return rhs.isNullHandle();
            else if constexpr (std::is_same_v<T, ConstantValue::Elements>) {
                if (!rhs.isUnpacked())
                    return false;

                return arg == std::get<ConstantValue::Elements>(rhs.value);
            }
            else if constexpr (std::is_same_v<T, std::string>)
                return rhs.isString() && arg == rhs.str();
            else if constexpr (std::is_same_v<T, ConstantValue::Map>) {
                if (!rhs.isMap())
                    return false;

                return *arg == *rhs.map();
            }
            else if constexpr (std::is_same_v<T, ConstantValue::Queue>) {
                if (!rhs.isQueue())
                    return false;

                return *arg == *rhs.queue();
            }
            else {
                static_assert(always_false<T>::value, "Missing case");
            }
        },
        lhs.value);
}

bool operator<(const ConstantValue& lhs, const ConstantValue& rhs) {
    return std::visit(
        [&](auto&& arg) noexcept(
            !std::is_same_v<std::decay_t<decltype(arg)>, ConstantValue::Elements>) {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, std::monostate>)
                return false;
            else if constexpr (std::is_same_v<T, SVInt>)
                return rhs.isInteger() && bool(arg < rhs.integer());
            else if constexpr (std::is_same_v<T, real_t>)
                return rhs.isReal() && arg < double(rhs.real());
            else if constexpr (std::is_same_v<T, shortreal_t>)
                return rhs.isShortReal() && arg < float(rhs.shortReal());
            else if constexpr (std::is_same_v<T, ConstantValue::NullPlaceholder>)
                return false;
            else if constexpr (std::is_same_v<T, ConstantValue::Elements>) {
                if (!rhs.isUnpacked())
                    return false;

                return arg < std::get<ConstantValue::Elements>(rhs.value);
            }
            else if constexpr (std::is_same_v<T, std::string>)
                return rhs.isString() && arg < rhs.str();
            else if constexpr (std::is_same_v<T, ConstantValue::Map>) {
                if (!rhs.isMap())
                    return false;

                return *arg < *rhs.map();
            }
            else if constexpr (std::is_same_v<T, ConstantValue::Queue>) {
                if (!rhs.isQueue())
                    return false;

                return *arg < *rhs.queue();
            }
            else {
                static_assert(always_false<T>::value, "Missing case");
            }
        },
        lhs.value);
}

ConstantRange ConstantRange::subrange(ConstantRange select) const {
    int32_t l = lower();
    ConstantRange result;
    result.left = select.lower() + l;
    result.right = select.upper() + l;

    ASSERT(result.right <= upper());
    if (isLittleEndian())
        return result;
    else
        return result.reverse();
}

int32_t ConstantRange::translateIndex(int32_t index) const {
    if (!isLittleEndian())
        return upper() - index;
    else
        return index - lower();
}

bool ConstantRange::containsPoint(int32_t index) const {
    return index >= lower() && index <= upper();
}

std::string ConstantRange::toString() const {
    return fmt::format("[{}:{}]", left, right);
}

std::ostream& operator<<(std::ostream& os, const ConstantRange& cr) {
    return os << cr.toString();
}

} // namespace slang
<commit_msg>Fix GCC warning<commit_after>//------------------------------------------------------------------------------
// ConstantValue.cpp
// Compile-time constant representation
//
// File is under the MIT license; see LICENSE for details
//------------------------------------------------------------------------------
#include "slang/numeric/ConstantValue.h"

#include "../text/FormatBuffer.h"
#include <fmt/format.h>

#include "slang/util/Hash.h"

namespace slang {

template<typename T>
struct always_false : std::false_type {};

const ConstantValue ConstantValue::Invalid;

std::string ConstantValue::toString() const {
    return std::visit(
        [](auto&& arg) {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, std::monostate>)
                return "<unset>"s;
            else if constexpr (std::is_same_v<T, SVInt>)
                return arg.toString();
            else if constexpr (std::is_same_v<T, real_t>)
                return fmt::format("{}", double(arg));
            else if constexpr (std::is_same_v<T, shortreal_t>)
                return fmt::format("{}", float(arg));
            else if constexpr (std::is_same_v<T, ConstantValue::NullPlaceholder>)
                return "null"s;
            else if constexpr (std::is_same_v<T, Elements>) {
                FormatBuffer buffer;
                buffer.append("[");
                for (auto& element : arg) {
                    buffer.append(element.toString());
                    buffer.append(",");
                }

                if (!arg.empty())
                    buffer.pop_back();
                buffer.append("]");
                return buffer.str();
            }
            else if constexpr (std::is_same_v<T, std::string>)
                return arg;
            else if constexpr (std::is_same_v<T, Map>) {
                FormatBuffer buffer;
                buffer.append("[");
                for (auto& [key, val] : *arg)
                    buffer.format("{}:{},", key.toString(), val.toString());

                if (arg->defaultValue)
                    buffer.format("default:{}", arg->defaultValue.toString());
                else if (!arg->empty())
                    buffer.pop_back();

                buffer.append("]");
                return buffer.str();
            }
            else if constexpr (std::is_same_v<T, Queue>) {
                FormatBuffer buffer;
                buffer.append("[");
                for (auto& element : *arg) {
                    buffer.append(element.toString());
                    buffer.append(",");
                }

                if (!arg->empty())
                    buffer.pop_back();
                buffer.append("]");
                return buffer.str();
            }
            else
                static_assert(always_false<T>::value, "Missing case");
        },
        value);
}

size_t ConstantValue::hash() const {
    size_t h = value.index();
    std::visit(
        [&h](auto&& arg) noexcept {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, std::monostate>)
                hash_combine(h, 0);
            else if constexpr (std::is_same_v<T, SVInt>)
                hash_combine(h, arg.hash());
            else if constexpr (std::is_same_v<T, real_t>)
                hash_combine(h, std::hash<double>()(arg));
            else if constexpr (std::is_same_v<T, shortreal_t>)
                hash_combine(h, std::hash<float>()(arg));
            else if constexpr (std::is_same_v<T, ConstantValue::NullPlaceholder>)
                hash_combine(h, 0);
            else if constexpr (std::is_same_v<T, Elements>) {
                for (auto& element : arg)
                    hash_combine(h, element.hash());
            }
            else if constexpr (std::is_same_v<T, std::string>)
                hash_combine(h, std::hash<std::string>()(arg));
            else if constexpr (std::is_same_v<T, Map>) {
                for (auto& [key, val] : *arg) {
                    hash_combine(h, key.hash());
                    hash_combine(h, val.hash());
                }
            }
            else if constexpr (std::is_same_v<T, Queue>) {
                for (auto& element : *arg)
                    hash_combine(h, element.hash());
            }
            else {
                static_assert(always_false<T>::value, "Missing case");
            }
        },
        value);
    return h;
}

ConstantValue ConstantValue::getSlice(int32_t upper, int32_t lower,
                                      const ConstantValue& defaultValue) const {
    if (isInteger())
        return integer().slice(upper, lower);

    if (isUnpacked()) {
        span<const ConstantValue> elems = elements();
        std::vector<ConstantValue> result{ size_t(upper - lower + 1) };
        ConstantValue* dest = result.data();

        for (int32_t i = lower; i <= upper; i++) {
            if (i < 0 || size_t(i) >= elems.size())
                *dest++ = defaultValue;
            else
                *dest++ = elems[size_t(i)];
        }

        return result;
    }

    if (isQueue()) {
        auto& q = *queue();
        SVQueue result;
        for (int32_t i = lower; i <= upper; i++) {
            if (i >= 0 && size_t(i) < q.size())
                result.push_back(q[size_t(i)]);
        }

        return result;
    }

    if (isString()) {
        ASSERT(upper == lower);
        ASSERT(upper >= 0);
        return SVInt(8, (uint64_t)str()[size_t(upper)], false);
    }

    return nullptr;
}

bool ConstantValue::isTrue() const {
    return std::visit(
        [](auto&& arg) noexcept {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, SVInt>)
                return (bool)(logic_t)arg;
            else if constexpr (std::is_same_v<T, real_t>)
                return (bool)arg;
            else if constexpr (std::is_same_v<T, shortreal_t>)
                return (bool)arg;
            else
                return false;
        },
        value);
}

bool ConstantValue::isFalse() const {
    return std::visit(
        [](auto&& arg) noexcept {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, SVInt>) {
                logic_t l = (logic_t)arg;
                return !l.isUnknown() && l.value == 0;
            }
            else if constexpr (std::is_same_v<T, real_t>)
                return !(bool)arg;
            else if constexpr (std::is_same_v<T, shortreal_t>)
                return !(bool)arg;
            else if constexpr (std::is_same_v<T, ConstantValue::NullPlaceholder>)
                return true;
            else
                return false;
        },
        value);
}

bool ConstantValue::hasUnknown() const {
    return std::visit(
        [](auto&& arg) noexcept {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, SVInt>) {
                return arg.hasUnknown();
            }
            else if constexpr (std::is_same_v<T, Elements>) {
                for (auto& element : arg) {
                    if (element.hasUnknown())
                        return true;
                }
                return false;
            }
            else if constexpr (std::is_same_v<T, Map>) {
                for (auto& [key, val] : *arg) {
                    if (key.hasUnknown() || val.hasUnknown())
                        return true;
                }
                return false;
            }
            else if constexpr (std::is_same_v<T, Queue>) {
                for (auto& element : *arg) {
                    if (element.hasUnknown())
                        return true;
                }
                return false;
            }
            else {
                return false;
            }
        },
        value);
}

ConstantValue ConstantValue::convertToInt(bitwidth_t width, bool isSigned, bool isFourState) const {
    if (isReal())
        return SVInt::fromDouble(width, real(), isSigned);

    if (isShortReal())
        return SVInt::fromFloat(width, shortReal(), isSigned);

    if (!isInteger())
        return nullptr;

    SVInt result = integer();
    if (!isFourState)
        result.flattenUnknowns();

    // [11.8.3] says that during an assignment we sign extend iff the rhs is signed.
    // That means we should resize first, and only then change the sign flag if desired.
    if (width != result.getBitWidth())
        result = result.resize(width);

    result.setSigned(isSigned);
    return result;
}

ConstantValue ConstantValue::convertToReal() const {
    if (isReal())
        return *this;

    if (isShortReal())
        return real_t(shortReal());

    if (isInteger())
        return real_t(integer().toDouble());

    return nullptr;
}

ConstantValue ConstantValue::convertToShortReal() const {
    if (isShortReal())
        return *this;

    if (isReal())
        return shortreal_t((float)real());

    if (isInteger())
        return shortreal_t(integer().toFloat());

    return nullptr;
}

ConstantValue ConstantValue::convertToStr() const {
    if (isString())
        return *this;

    if (!isInteger())
        return nullptr;

    // Conversion is described in [6.16]: take each 8 bit chunk,
    // remove it if it's zero, otherwise add as character to the string.
    // TODO: unknown bits?

    const SVInt& val = integer();
    int32_t msb = int32_t(val.getBitWidth() - 1);
    int32_t extraBits = int32_t(val.getBitWidth() % 8);

    std::string result;
    if (extraBits) {
        auto c = val.slice(msb, msb - extraBits + 1).as<uint8_t>();
        if (c && *c)
            result.push_back(char(*c));
        msb -= extraBits;
    }

    while (msb >= 7) {
        auto c = val.slice(msb, msb - 7).as<uint8_t>();
        if (c && *c)
            result.push_back(char(*c));
        msb -= 8;
    }

    return result;
}

std::ostream& operator<<(std::ostream& os, const ConstantValue& cv) {
    return os << cv.toString();
}

bool operator==(const ConstantValue& lhs, const ConstantValue& rhs) {
    return std::visit(
        [&](auto&& arg) noexcept(
            !std::is_same_v<std::decay_t<decltype(arg)>, ConstantValue::Elements>) {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, std::monostate>)
                return rhs.bad();
            else if constexpr (std::is_same_v<T, SVInt>)
                return rhs.isInteger() && exactlyEqual(arg, rhs.integer());
            else if constexpr (std::is_same_v<T, real_t>)
                return rhs.isReal() && arg == double(rhs.real());
            else if constexpr (std::is_same_v<T, shortreal_t>)
                return rhs.isShortReal() && arg == float(rhs.shortReal());
            else if constexpr (std::is_same_v<T, ConstantValue::NullPlaceholder>)
                return rhs.isNullHandle();
            else if constexpr (std::is_same_v<T, ConstantValue::Elements>) {
                if (!rhs.isUnpacked())
                    return false;

                return arg == std::get<ConstantValue::Elements>(rhs.value);
            }
            else if constexpr (std::is_same_v<T, std::string>)
                return rhs.isString() && arg == rhs.str();
            else if constexpr (std::is_same_v<T, ConstantValue::Map>) {
                if (!rhs.isMap())
                    return false;

                return *arg == *rhs.map();
            }
            else if constexpr (std::is_same_v<T, ConstantValue::Queue>) {
                if (!rhs.isQueue())
                    return false;

                return *arg == *rhs.queue();
            }
            else {
                static_assert(always_false<T>::value, "Missing case");
            }
        },
        lhs.value);
}

bool operator<(const ConstantValue& lhs, const ConstantValue& rhs) {
    return std::visit(
        [&](auto&& arg) noexcept(
            !std::is_same_v<std::decay_t<decltype(arg)>, ConstantValue::Elements>) {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, std::monostate>)
                return false;
            else if constexpr (std::is_same_v<T, SVInt>)
                return rhs.isInteger() && bool(arg < rhs.integer());
            else if constexpr (std::is_same_v<T, real_t>)
                return rhs.isReal() && arg < double(rhs.real());
            else if constexpr (std::is_same_v<T, shortreal_t>)
                return rhs.isShortReal() && arg < float(rhs.shortReal());
            else if constexpr (std::is_same_v<T, ConstantValue::NullPlaceholder>)
                return false;
            else if constexpr (std::is_same_v<T, ConstantValue::Elements>) {
                if (!rhs.isUnpacked())
                    return false;

                return arg < std::get<ConstantValue::Elements>(rhs.value);
            }
            else if constexpr (std::is_same_v<T, std::string>)
                return rhs.isString() && arg < rhs.str();
            else if constexpr (std::is_same_v<T, ConstantValue::Map>) {
                if (!rhs.isMap())
                    return false;

                return *arg < *rhs.map();
            }
            else if constexpr (std::is_same_v<T, ConstantValue::Queue>) {
                if (!rhs.isQueue())
                    return false;

                return *arg < *rhs.queue();
            }
            else {
                static_assert(always_false<T>::value, "Missing case");
            }
        },
        lhs.value);
}

ConstantRange ConstantRange::subrange(ConstantRange select) const {
    int32_t l = lower();
    ConstantRange result;
    result.left = select.lower() + l;
    result.right = select.upper() + l;

    ASSERT(result.right <= upper());
    if (isLittleEndian())
        return result;
    else
        return result.reverse();
}

int32_t ConstantRange::translateIndex(int32_t index) const {
    if (!isLittleEndian())
        return upper() - index;
    else
        return index - lower();
}

bool ConstantRange::containsPoint(int32_t index) const {
    return index >= lower() && index <= upper();
}

std::string ConstantRange::toString() const {
    return fmt::format("[{}:{}]", left, right);
}

std::ostream& operator<<(std::ostream& os, const ConstantRange& cr) {
    return os << cr.toString();
}

} // namespace slang
<|endoftext|>


<commit_before>//
//  NSolver::calc_time_step.cpp
//
//  Created by Lei Qiao on 15/8/9.
//  A work based on deal.II tutorial step-33.
//

#include <NSolver/solver/NSolver.h>

namespace NSFEMSolver
{
  using namespace dealii;

  // @sect4{NSolver::calc_time_step}
  //
  // Determine time step size of next time step.
  template <int dim>
  void NSolver<dim>::calc_time_step()
  {
    if (parameters->rigid_reference_time_step)
      {
        time_step = parameters->reference_time_step * CFL_number;
      }
    else
      {
        FEValues<dim> fe_v (*mapping_ptr, fe, quadrature, update_values);
        const unsigned int   n_q_points = fe_v.n_quadrature_points;
        std::vector<Vector<double> > solution_values (n_q_points,
                                                      Vector<double> (dim+2));
        double min_time_step = parameters->reference_time_step;
        typename DoFHandler<dim>::active_cell_iterator
        cell = dof_handler.begin_active(),
        endc = dof_handler.end();
        for (; cell!=endc; ++cell)
          if (cell -> is_locally_owned())
            {
              fe_v.reinit (cell);
              fe_v.get_function_values (current_solution, solution_values);
              const double cell_size = fe_v.get_cell()->minimum_vertex_distance();
              for (unsigned int q=0; q<n_q_points; ++q)
                {
                  const double sound_speed
                    = EulerEquations<dim>::template compute_sound_speed (solution_values[q]);
                  const double velocity
                  = EulerEquations<dim>::template compute_velocity_magnitude (solution_values[q]);
                  min_time_step = std::min (min_time_step, cell_size / velocity+sound_speed);
                }
            }
        time_step = Utilities::MPI::min (min_time_step, mpi_communicator) * CFL_number;
      }
  }

#include "NSolver.inst"
}
<commit_msg>compute cell characteristics length for time step size evaluation as 'Volume/mean_face_area'<commit_after>//
//  NSolver::calc_time_step.cpp
//
//  Created by Lei Qiao on 15/8/9.
//  A work based on deal.II tutorial step-33.
//

#include <NSolver/solver/NSolver.h>

namespace NSFEMSolver
{
  using namespace dealii;

  // @sect4{NSolver::calc_time_step}
  //
  // Determine time step size of next time step.
  template <int dim>
  void NSolver<dim>::calc_time_step()
  {
    if (parameters->rigid_reference_time_step)
      {
        time_step = parameters->reference_time_step * CFL_number;
      }
    else
      {
        FEValues<dim> fe_v (*mapping_ptr, fe, quadrature, update_values);
        const unsigned int   n_q_points = fe_v.n_quadrature_points;
        std::vector<Vector<double> > solution_values (n_q_points,
                                                      Vector<double> (dim+2));
        double min_time_step = parameters->reference_time_step;
        typename DoFHandler<dim>::active_cell_iterator
        cell = dof_handler.begin_active(),
        endc = dof_handler.end();
        for (; cell!=endc; ++cell)
          if (cell -> is_locally_owned())
            {
              fe_v.reinit (cell);
              fe_v.get_function_values (current_solution, solution_values);

              const double cell_volumn = cell->measure();
              double face_area = 0.0;
              for (unsigned int face_no=0;
                   face_no < GeometryInfo<dim>::faces_per_cell;
                   ++face_no)
                {
                  face_area += cell->face (face_no)->measure();
                }
              const double cell_charact_length
                = static_cast<double> (GeometryInfo<dim>::faces_per_cell)
                  * cell_volumn/face_area;

              for (unsigned int q=0; q<n_q_points; ++q)
                {
                  const double sound_speed
                    = EulerEquations<dim>::template compute_sound_speed (solution_values[q]);
                  const double velocity
                  = EulerEquations<dim>::template compute_velocity_magnitude (solution_values[q]);
                  min_time_step = std::min (min_time_step, cell_charact_length / velocity+sound_speed);
                }
            }
        time_step = Utilities::MPI::min (min_time_step, mpi_communicator) * CFL_number;
      }
  }

#include "NSolver.inst"
}
<|endoftext|>


<commit_before><commit_msg>n#791985: Automatically rotate chart labels (if overlapping).<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2011 Esrille Inc.
 *
 * 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.
 */

// A test harness for the implementation report of
//       the CSS2.1 Conformance Test Suite
// http://test.csswg.org/suites/css2.1/20110323/

#include <unistd.h>
#include <sys/wait.h>

#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>

enum {
    INTERACTIVE,
    HEADLESS,
    REPORT,
    UPDATE
};

int processOutput(std::istream& stream, std::string& result)
{
    std::string output;
    bool completed = false;
    while (std::getline(stream, output)) {
        if (!completed) {
            if (output == "## complete")
                completed = true;
            continue;
        }
        if (output == "##")
            break;
        result += output + '\n';
    }
    return 0;
}

int runTest(int argc, char* argv[], std::string url, std::string& result)
{
    int pipefd[2];
    pipe(pipefd);

    pid_t pid = fork();
    if (pid == -1) {
        std::cerr << "error: no more process to create\n";
        return -1;
    }
    if (pid == 0) {
        close(1);
        dup(pipefd[1]);
        close(pipefd[0]);

        url = "http://localhost:8000/" + url;
        argv[argc - 1] = strdup(url.c_str());
        execvp(argv[0], argv);
        exit(EXIT_FAILURE);
    }
    close(pipefd[1]);

#if 104400 <= BOOST_VERSION
    boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle);
#else
    boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], true);
#endif
    processOutput(stream, result);
    return pid;
}

void killTest(int pid)
{
    int status;
    kill(pid, SIGTERM);
    if (wait(&status) == -1)
        std::cerr << "error: failed to wait for a test process to complete\n";
}

bool loadLog(const std::string& path, std::string& result, std::string& log)
{
    std::ifstream file(path.c_str());
    if (!file) {
        result = "?";
        return false;
    }
    std::string line;
    std::getline(file, line);
    size_t pos = line.find('\t');
    if (pos != std::string::npos)
        result = line.substr(pos + 1);
    else {
        result = "?";
        return false;
    }
    log.clear();
    while (std::getline(file, line))
        log += line + '\n';
    return true;
}

bool saveLog(const std::string& path, const std::string& url, const std::string& result, const std::string& log)
{
    std::ofstream file(path.c_str(), std::ios_base::out | std::ios_base::trunc);
    if (!file) {
        std::cerr << "error: failed to open the report file\n";
        return false;
    }
    file << "# " << url.c_str() << '\t' << result << '\n' << log;
    file.flush();
    file.close();
    return true;
}

int main(int argc, char* argv[])
{
    int mode = HEADLESS;

    int argi = 1;
    while (*argv[argi] == '-') {
        switch (argv[argi][1]) {
        case 'i':
            mode = INTERACTIVE;
            break;
        case 'r':
            mode = REPORT;
            break;
        case 'u':
            mode = UPDATE;
            break;
        default:
            break;
        }
        ++argi;
    }

    if (argc < argi + 2) {
        std::cout << "usage: " << argv[0] << " [-i] report.data command [argument ...]\n";
        return EXIT_FAILURE;
    }

    std::ifstream data(argv[argi]);
    if (!data) {
        std::cerr << "error: " << argv[argi] << ": no such file\n";
        return EXIT_FAILURE;
    }

    std::ofstream report("report.data", std::ios_base::out | std::ios_base::trunc);
    if (!report) {
        std::cerr << "error: failed to open the report file\n";
        return EXIT_FAILURE;
    }

    char* args[argc - argi + 1];
    for (int i = 2; i < argc; ++i)
        args[i - 2] = argv[i + argi - 1];
    args[argc - argi] = 0;

    std::string result;
    std::string url;
    std::string undo;
    bool redo = false;
    while (data) {
        if (result == "undo") {
            std::swap(url, undo);
            redo = true;
        } else if (redo) {
            std::swap(url, undo);
            redo = false;
        } else {
            std::string line;
            std::getline(data, line);
            if (line.empty() || line[0] == '#' || line == "testname    result  comment") {
                report << line << '\n';
                continue;
            }
            undo = url;
            std::stringstream s(line, std::stringstream::in);
            s >> url;
        }
        if (url.empty())
            continue;

        std::string path(url);
        size_t pos = path.rfind('.');
        if (pos != std::string::npos) {
            path.erase(pos);
            path += ".log";
        }
        std::string evaluation;
        std::string log;
        loadLog(path, evaluation, log);

        pid_t pid = -1;
        std::string output;
        switch (mode) {
        case REPORT:
            break;
        case UPDATE:
            if (evaluation[0] == '?')
                break;
            // FALL THROUGH
        default:
            pid = runTest(argc - argi, args, url, output);
            break;
        }

        if (0 < pid && output.empty())
            result = "fatal";
        else if (mode == INTERACTIVE) {
            std::cout << "## complete\n" << output;
            std::cout << '[' << url << "] ";
            if (evaluation.empty() || evaluation[0] == '?')
                std::cout << "pass? ";
            else {
                std::cout << evaluation << "? ";
                if (evaluation != "pass")
                    std::cout << '\a';
            }
            std::getline(std::cin, result);
            if (result.empty()) {
                if (evaluation.empty() || evaluation[0] == '?')
                    result = "pass";
                else
                    result = evaluation;
            } else if (result == "p" || result == "\x1b")
                result = "pass";
            else if (result == "f")
                result = "fail";
            else if (result == "i")
                result = "invalid";
            else if (result == "k") // keep
                result = evaluation;
            else if (result == "n")
                result = "na";
            else if (result == "s")
                result = "skip";
            else if (result == "u")
                result = "uncertain";
            else if (result == "q" || result == "quit")
                break;
            else if (result == "z")
                result = "undo";
            if (result != "undo" && !saveLog(path, url, result, output)) {
                std::cerr << "error: failed to open the report file\n";
                return EXIT_FAILURE;
            }
        } else if (mode == HEADLESS) {
            if (evaluation != "?" && output != log)
                result = "uncertain";
            else
                result = evaluation;
            std::cout << url << '\t' << result << '\n';
        } else if (mode == REPORT) {
            result = evaluation;
            std::cout << url << '\t' << result << '\n';
        } else if (mode == UPDATE) {
            result = evaluation;
            if (result[0] != '?') {
                if (!saveLog(path, url, result, output)) {
                    std::cerr << "error: failed to open the report file\n";
                    return EXIT_FAILURE;
                }
                std::cout << url << '\t' << result << '\n';
            }
        }

        if (0 < pid)
            killTest(pid);

        if (result != "undo")
            report << url << '\t' << result << '\n';
    }
    report.close();
}
<commit_msg>(harness) : Support #userstyle directive.<commit_after>/*
 * Copyright 2011, 2012 Esrille Inc.
 *
 * 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.
 */

// A test harness for the implementation report of
//       the CSS2.1 Conformance Test Suite
// http://test.csswg.org/suites/css2.1/20110323/

#include <unistd.h>
#include <sys/wait.h>

#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>

enum {
    INTERACTIVE,
    HEADLESS,
    REPORT,
    UPDATE
};

int processOutput(std::istream& stream, std::string& result)
{
    std::string output;
    bool completed = false;
    while (std::getline(stream, output)) {
        if (!completed) {
            if (output == "## complete")
                completed = true;
            continue;
        }
        if (output == "##")
            break;
        result += output + '\n';
    }
    return 0;
}

int runTest(int argc, char* argv[], std::string userStyle, std::string url, std::string& result)
{
    int pipefd[2];
    pipe(pipefd);

    pid_t pid = fork();
    if (pid == -1) {
        std::cerr << "error: no more process to create\n";
        return -1;
    }
    if (pid == 0) {
        close(1);
        dup(pipefd[1]);
        close(pipefd[0]);
        int argi = argc - 1;
        if (!userStyle.empty())
            argv[argi++] = strdup(userStyle.c_str());
        url = "http://localhost:8000/" + url;
        argv[argi++] = strdup(url.c_str());
        argv[argi] = 0;
        execvp(argv[0], argv);
        exit(EXIT_FAILURE);
    }
    close(pipefd[1]);

#if 104400 <= BOOST_VERSION
    boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle);
#else
    boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], true);
#endif
    processOutput(stream, result);
    return pid;
}

void killTest(int pid)
{
    int status;
    kill(pid, SIGTERM);
    if (wait(&status) == -1)
        std::cerr << "error: failed to wait for a test process to complete\n";
}

bool loadLog(const std::string& path, std::string& result, std::string& log)
{
    std::ifstream file(path.c_str());
    if (!file) {
        result = "?";
        return false;
    }
    std::string line;
    std::getline(file, line);
    size_t pos = line.find('\t');
    if (pos != std::string::npos)
        result = line.substr(pos + 1);
    else {
        result = "?";
        return false;
    }
    log.clear();
    while (std::getline(file, line))
        log += line + '\n';
    return true;
}

bool saveLog(const std::string& path, const std::string& url, const std::string& result, const std::string& log)
{
    std::ofstream file(path.c_str(), std::ios_base::out | std::ios_base::trunc);
    if (!file) {
        std::cerr << "error: failed to open the report file\n";
        return false;
    }
    file << "# " << url.c_str() << '\t' << result << '\n' << log;
    file.flush();
    file.close();
    return true;
}

int main(int argc, char* argv[])
{
    int mode = HEADLESS;

    int argi = 1;
    while (*argv[argi] == '-') {
        switch (argv[argi][1]) {
        case 'i':
            mode = INTERACTIVE;
            break;
        case 'r':
            mode = REPORT;
            break;
        case 'u':
            mode = UPDATE;
            break;
        default:
            break;
        }
        ++argi;
    }

    if (argc < argi + 2) {
        std::cout << "usage: " << argv[0] << " [-i] report.data command [argument ...]\n";
        return EXIT_FAILURE;
    }

    std::ifstream data(argv[argi]);
    if (!data) {
        std::cerr << "error: " << argv[argi] << ": no such file\n";
        return EXIT_FAILURE;
    }

    std::ofstream report("report.data", std::ios_base::out | std::ios_base::trunc);
    if (!report) {
        std::cerr << "error: failed to open the report file\n";
        return EXIT_FAILURE;
    }

    char* args[argc - argi + 2];
    for (int i = 2; i < argc; ++i)
        args[i - 2] = argv[i + argi - 1];
    args[argc - argi] = args[argc - argi + 1] = 0;

    std::string result;
    std::string url;
    std::string undo;
    std::string userStyle;
    bool redo = false;
    while (data) {
        if (result == "undo") {
            std::swap(url, undo);
            redo = true;
        } else if (redo) {
            std::swap(url, undo);
            redo = false;
        } else {
            std::string line;
            std::getline(data, line);
            if (line.empty() || line == "testname    result  comment") {
                report << line << '\n';
                continue;
            }
            if (line[0] == '#') {
                if (line.compare(1, 9, "userstyle") == 0) {
                    if (10 < line.length()) {
                        std::stringstream s(line.substr(10), std::stringstream::in);
                        s >> userStyle;
                    } else
                        userStyle.clear();
                }
                report << line << '\n';
                continue;
            }
            undo = url;
            std::stringstream s(line, std::stringstream::in);
            s >> url;
        }
        if (url.empty())
            continue;

        std::string path(url);
        size_t pos = path.rfind('.');
        if (pos != std::string::npos) {
            path.erase(pos);
            path += ".log";
        }
        std::string evaluation;
        std::string log;
        loadLog(path, evaluation, log);

        pid_t pid = -1;
        std::string output;
        switch (mode) {
        case REPORT:
            break;
        case UPDATE:
            if (evaluation[0] == '?')
                break;
            // FALL THROUGH
        default:
            pid = runTest(argc - argi, args, userStyle, url, output);
            break;
        }

        if (0 < pid && output.empty())
            result = "fatal";
        else if (mode == INTERACTIVE) {
            std::cout << "## complete\n" << output;
            std::cout << '[' << url << "] ";
            if (evaluation.empty() || evaluation[0] == '?')
                std::cout << "pass? ";
            else {
                std::cout << evaluation << "? ";
                if (evaluation != "pass")
                    std::cout << '\a';
            }
            std::getline(std::cin, result);
            if (result.empty()) {
                if (evaluation.empty() || evaluation[0] == '?')
                    result = "pass";
                else
                    result = evaluation;
            } else if (result == "p" || result == "\x1b")
                result = "pass";
            else if (result == "f")
                result = "fail";
            else if (result == "i")
                result = "invalid";
            else if (result == "k") // keep
                result = evaluation;
            else if (result == "n")
                result = "na";
            else if (result == "s")
                result = "skip";
            else if (result == "u")
                result = "uncertain";
            else if (result == "q" || result == "quit")
                break;
            else if (result == "z")
                result = "undo";
            if (result != "undo" && !saveLog(path, url, result, output)) {
                std::cerr << "error: failed to open the report file\n";
                return EXIT_FAILURE;
            }
        } else if (mode == HEADLESS) {
            if (evaluation != "?" && output != log)
                result = "uncertain";
            else
                result = evaluation;
            std::cout << url << '\t' << result << '\n';
        } else if (mode == REPORT) {
            result = evaluation;
            std::cout << url << '\t' << result << '\n';
        } else if (mode == UPDATE) {
            result = evaluation;
            if (result[0] != '?') {
                if (!saveLog(path, url, result, output)) {
                    std::cerr << "error: failed to open the report file\n";
                    return EXIT_FAILURE;
                }
                std::cout << url << '\t' << result << '\n';
            }
        }

        if (0 < pid)
            killTest(pid);

        if (result != "undo")
            report << url << '\t' << result << '\n';
    }
    report.close();
}
<|endoftext|>


<commit_before>/*
 * By: ulises-jeremias
 * From: http://www.spoj.com/problems/PARTY/
 * Name: PARTY - Party Schedule
 * Date: 27/09/2017
 */

#include <iostream>
#include <utility>

using namespace std;

int n, k, party[105][2];
pair<int, int> DP[105][505];

pair<int, int> dp(int i, int cap)
{
        if (i == n || cap == 0) {
                return pair<int, int>(0, 0);
        }
        if (DP[i][cap].first != -1) {
                return DP[i][cap];
        }
        DP[i][cap] = dp(i + 1, cap);
        if (cap >= party[i][0]) {
                pair<int, int> a = dp(i + 1, cap - party[i][0]);
                a.first += party[i][0];
                a.second += party[i][1];
                if (a.second > DP[i][cap].second) {
                        DP[i][cap] = a;
                } else if (a.second == DP[i][cap].second) {
                        DP[i][cap].first = min(a.first, DP[i][cap].first);
                }
        }
        return DP[i][cap];
}

int main(int argc, char const *argv[])
{
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);

        int i, j;
        while (cin >> k >> n, n || k) {
                for (i = 0; i < n; i++) {
                        cin >> party[i][0] >> party[i][1];
                }
                for (i = 0; i < n; i++) {
                        for (j = 0; j <= k; j++) {
                                DP[i][j] = pair<int, int>(-1, -1);
                        }
                }
                pair<int, int> answer = dp(0, k);
                cout << answer.first << " " << answer.second << endl;
        }
        return 0;
}
<commit_msg>Solved<commit_after>/*
 * By: ulises-jeremias
 * From: http://www.spoj.com/problems/PARTY/
 * Name: PARTY - Party Schedule
 * Date: 27/09/2017
 */

#include <iostream>
#include <utility>

using namespace std;

int n, k, party[105][2];
pair<int, int> DP[105][505];

pair<int, int> dp(int i, int cap)
{
        if (i == n || cap == 0) {
                return pair<int, int>(0, 0);
        }

        if (DP[i][cap].first != -1) {
                return DP[i][cap];
        }

        DP[i][cap] = dp(i + 1, cap);
        if (cap >= party[i][0]) {
                pair<int, int> a = dp(i + 1, cap - party[i][0]);
                a.first += party[i][0];
                a.second += party[i][1];

                if (a.second > DP[i][cap].second) {
                        DP[i][cap] = a;
                } else if (a.second == DP[i][cap].second) {
                        DP[i][cap].first = min(a.first, DP[i][cap].first);
                }
        }

        return DP[i][cap];
}

int main(int argc, char const *argv[])
{
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);

        int i, j;
        while (cin >> k >> n, n || k) {
                for (i = 0; i < n; i++) {
                        cin >> party[i][0] >> party[i][1];
                }

                for (i = 0; i < n; i++) {
                        for (j = 0; j <= k; j++) {
                                DP[i][j] = pair<int, int>(-1, -1);
                        }
                }

                pair<int, int> answer = dp(0, k);
                cout << answer.first << " " << answer.second << endl;
        }
        return 0;
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2013 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 "webrtc/modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h"
#include "webrtc/modules/remote_bitrate_estimator/test/bwe_test.h"
#include "webrtc/test/testsupport/fileutils.h"

namespace webrtc {
namespace testing {
namespace bwe {
std::vector<const PacketSenderFactory*> VideoSenderFactories(uint32_t count) {
  static const VideoPacketSenderFactory factories[] = {
    VideoPacketSenderFactory(30.00f, 150, 0x1234, 0.13f),
    VideoPacketSenderFactory(15.00f, 500, 0x2345, 0.16f),
    VideoPacketSenderFactory(30.00f, 1200, 0x3456, 0.26f),
    VideoPacketSenderFactory(7.49f, 150, 0x4567, 0.05f),
    VideoPacketSenderFactory(7.50f, 150, 0x5678, 0.15f),
    VideoPacketSenderFactory(7.51f, 150, 0x6789, 0.25f),
    VideoPacketSenderFactory(15.02f, 150, 0x7890, 0.27f),
    VideoPacketSenderFactory(15.03f, 150, 0x8901, 0.38f),
    VideoPacketSenderFactory(30.02f, 150, 0x9012, 0.39f),
    VideoPacketSenderFactory(30.03f, 150, 0x0123, 0.52f)
  };

  assert(count <= sizeof(factories) / sizeof(factories[0]));

  std::vector<const PacketSenderFactory*> result;
  for (uint32_t i = 0; i < count; ++i) {
    result.push_back(&factories[i]);
  }

  return result;
}

std::vector<BweTestConfig::EstimatorConfig> EstimatorConfigs() {
  static const RemoteBitrateEstimatorFactory factories[] = {
    RemoteBitrateEstimatorFactory(),
    AbsoluteSendTimeRemoteBitrateEstimatorFactory()
  };

  std::vector<BweTestConfig::EstimatorConfig> result;
  result.push_back(BweTestConfig::EstimatorConfig("TOF", &factories[0]));
  result.push_back(BweTestConfig::EstimatorConfig("AST", &factories[1]));
  return result;
}

BweTestConfig MakeBweTestConfig(uint32_t sender_count) {
  BweTestConfig result = {
    VideoSenderFactories(sender_count), EstimatorConfigs()
  };
  return result;
}

INSTANTIATE_TEST_CASE_P(VideoSendersTest, BweTest,
    ::testing::Values(MakeBweTestConfig(1),
                      MakeBweTestConfig(3)));

TEST_P(BweTest, UnlimitedSpeed) {
  VerboseLogging(false);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, SteadyLoss) {
  LossFilter loss(this);
  loss.SetLoss(20.0);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, IncreasingLoss1) {
  LossFilter loss(this);
  for (int i = 0; i < 76; ++i) {
    loss.SetLoss(i);
    RunFor(5000);
  }
}

TEST_P(BweTest, SteadyDelay) {
  DelayFilter delay(this);
  delay.SetDelay(1000);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, IncreasingDelay1) {
  DelayFilter delay(this);
  RunFor(10 * 60 * 1000);
  for (int i = 0; i < 30 * 2; ++i) {
    delay.SetDelay(i);
    RunFor(10 * 1000);
  }
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, IncreasingDelay2) {
  DelayFilter delay(this);
  RateCounterFilter counter(this);
  RunFor(1 * 60 * 1000);
  for (int i = 1; i < 51; ++i) {
    delay.SetDelay(10.0f * i);
    RunFor(10 * 1000);
  }
  delay.SetDelay(0.0f);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, JumpyDelay1) {
  DelayFilter delay(this);
  RunFor(10 * 60 * 1000);
  for (int i = 1; i < 200; ++i) {
    delay.SetDelay((10 * i) % 500);
    RunFor(1000);
    delay.SetDelay(1.0f);
    RunFor(1000);
  }
  delay.SetDelay(0.0f);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, SteadyJitter) {
  JitterFilter jitter(this);
  RateCounterFilter counter(this);
  jitter.SetJitter(20);
  RunFor(2 * 60 * 1000);
}

TEST_P(BweTest, IncreasingJitter1) {
  JitterFilter jitter(this);
  for (int i = 0; i < 2 * 60 * 2; ++i) {
    jitter.SetJitter(i);
    RunFor(10 * 1000);
  }
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, IncreasingJitter2) {
  JitterFilter jitter(this);
  RunFor(30 * 1000);
  for (int i = 1; i < 51; ++i) {
    jitter.SetJitter(10.0f * i);
    RunFor(10 * 1000);
  }
  jitter.SetJitter(0.0f);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, SteadyReorder) {
  ReorderFilter reorder(this);
  reorder.SetReorder(20.0);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, IncreasingReorder1) {
  ReorderFilter reorder(this);
  for (int i = 0; i < 76; ++i) {
    reorder.SetReorder(i);
    RunFor(5000);
  }
}

TEST_P(BweTest, SteadyChoke) {
  ChokeFilter choke(this);
  choke.SetCapacity(140);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, IncreasingChoke1) {
  ChokeFilter choke(this);
  for (int i = 1200; i >= 100; i -= 100) {
    choke.SetCapacity(i);
    RunFor(5000);
  }
}

TEST_P(BweTest, IncreasingChoke2) {
  ChokeFilter choke(this);
  RunFor(60 * 1000);
  for (int i = 1200; i >= 100; i -= 20) {
    choke.SetCapacity(i);
    RunFor(1000);
  }
}

TEST_P(BweTest, Multi1) {
  DelayFilter delay(this);
  ChokeFilter choke(this);
  RateCounterFilter counter(this);
  choke.SetCapacity(1000);
  RunFor(1 * 60 * 1000);
  for (int i = 1; i < 51; ++i) {
    delay.SetDelay(100.0f * i);
    RunFor(10 * 1000);
  }
  RunFor(500 * 1000);
  delay.SetDelay(0.0f);
  RunFor(5 * 60 * 1000);
}

TEST_P(BweTest, Multi2) {
  ChokeFilter choke(this);
  JitterFilter jitter(this);
  RateCounterFilter counter(this);
  choke.SetCapacity(2000);
  jitter.SetJitter(120);
  RunFor(5 * 60 * 1000);
}
}  // namespace bwe
}  // namespace testing
}  // namespace webrtc
<commit_msg>Disabled some of the remote bitrate estimator baseline tests.<commit_after>/*
 *  Copyright (c) 2013 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 "webrtc/modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h"
#include "webrtc/modules/remote_bitrate_estimator/test/bwe_test.h"
#include "webrtc/test/testsupport/fileutils.h"

namespace webrtc {
namespace testing {
namespace bwe {
std::vector<const PacketSenderFactory*> VideoSenderFactories(uint32_t count) {
  static const VideoPacketSenderFactory factories[] = {
    VideoPacketSenderFactory(30.00f, 150, 0x1234, 0.13f),
    VideoPacketSenderFactory(15.00f, 500, 0x2345, 0.16f),
    VideoPacketSenderFactory(30.00f, 1200, 0x3456, 0.26f),
    VideoPacketSenderFactory(7.49f, 150, 0x4567, 0.05f),
    VideoPacketSenderFactory(7.50f, 150, 0x5678, 0.15f),
    VideoPacketSenderFactory(7.51f, 150, 0x6789, 0.25f),
    VideoPacketSenderFactory(15.02f, 150, 0x7890, 0.27f),
    VideoPacketSenderFactory(15.03f, 150, 0x8901, 0.38f),
    VideoPacketSenderFactory(30.02f, 150, 0x9012, 0.39f),
    VideoPacketSenderFactory(30.03f, 150, 0x0123, 0.52f)
  };

  assert(count <= sizeof(factories) / sizeof(factories[0]));

  std::vector<const PacketSenderFactory*> result;
  for (uint32_t i = 0; i < count; ++i) {
    result.push_back(&factories[i]);
  }

  return result;
}

std::vector<BweTestConfig::EstimatorConfig> EstimatorConfigs() {
  static const RemoteBitrateEstimatorFactory factories[] = {
    RemoteBitrateEstimatorFactory(),
    AbsoluteSendTimeRemoteBitrateEstimatorFactory()
  };

  std::vector<BweTestConfig::EstimatorConfig> result;
  result.push_back(BweTestConfig::EstimatorConfig("TOF", &factories[0]));
  result.push_back(BweTestConfig::EstimatorConfig("AST", &factories[1]));
  return result;
}

BweTestConfig MakeBweTestConfig(uint32_t sender_count) {
  BweTestConfig result = {
    VideoSenderFactories(sender_count), EstimatorConfigs()
  };
  return result;
}

INSTANTIATE_TEST_CASE_P(VideoSendersTest, BweTest,
    ::testing::Values(MakeBweTestConfig(1),
                      MakeBweTestConfig(3)));

TEST_P(BweTest, UnlimitedSpeed) {
  VerboseLogging(false);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, DISABLED_SteadyLoss) {
  LossFilter loss(this);
  loss.SetLoss(20.0);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, IncreasingLoss1) {
  LossFilter loss(this);
  for (int i = 0; i < 76; ++i) {
    loss.SetLoss(i);
    RunFor(5000);
  }
}

TEST_P(BweTest, SteadyDelay) {
  DelayFilter delay(this);
  delay.SetDelay(1000);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, DISABLED_IncreasingDelay1) {
  DelayFilter delay(this);
  RunFor(10 * 60 * 1000);
  for (int i = 0; i < 30 * 2; ++i) {
    delay.SetDelay(i);
    RunFor(10 * 1000);
  }
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, IncreasingDelay2) {
  DelayFilter delay(this);
  RateCounterFilter counter(this);
  RunFor(1 * 60 * 1000);
  for (int i = 1; i < 51; ++i) {
    delay.SetDelay(10.0f * i);
    RunFor(10 * 1000);
  }
  delay.SetDelay(0.0f);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, JumpyDelay1) {
  DelayFilter delay(this);
  RunFor(10 * 60 * 1000);
  for (int i = 1; i < 200; ++i) {
    delay.SetDelay((10 * i) % 500);
    RunFor(1000);
    delay.SetDelay(1.0f);
    RunFor(1000);
  }
  delay.SetDelay(0.0f);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, SteadyJitter) {
  JitterFilter jitter(this);
  RateCounterFilter counter(this);
  jitter.SetJitter(20);
  RunFor(2 * 60 * 1000);
}

TEST_P(BweTest, IncreasingJitter1) {
  JitterFilter jitter(this);
  for (int i = 0; i < 2 * 60 * 2; ++i) {
    jitter.SetJitter(i);
    RunFor(10 * 1000);
  }
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, IncreasingJitter2) {
  JitterFilter jitter(this);
  RunFor(30 * 1000);
  for (int i = 1; i < 51; ++i) {
    jitter.SetJitter(10.0f * i);
    RunFor(10 * 1000);
  }
  jitter.SetJitter(0.0f);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, SteadyReorder) {
  ReorderFilter reorder(this);
  reorder.SetReorder(20.0);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, IncreasingReorder1) {
  ReorderFilter reorder(this);
  for (int i = 0; i < 76; ++i) {
    reorder.SetReorder(i);
    RunFor(5000);
  }
}

TEST_P(BweTest, DISABLED_SteadyChoke) {
  ChokeFilter choke(this);
  choke.SetCapacity(140);
  RunFor(10 * 60 * 1000);
}

TEST_P(BweTest, DISABLED_IncreasingChoke1) {
  ChokeFilter choke(this);
  for (int i = 1200; i >= 100; i -= 100) {
    choke.SetCapacity(i);
    RunFor(5000);
  }
}

TEST_P(BweTest, DISABLED_IncreasingChoke2) {
  ChokeFilter choke(this);
  RunFor(60 * 1000);
  for (int i = 1200; i >= 100; i -= 20) {
    choke.SetCapacity(i);
    RunFor(1000);
  }
}

TEST_P(BweTest, DISABLED_Multi1) {
  DelayFilter delay(this);
  ChokeFilter choke(this);
  RateCounterFilter counter(this);
  choke.SetCapacity(1000);
  RunFor(1 * 60 * 1000);
  for (int i = 1; i < 51; ++i) {
    delay.SetDelay(100.0f * i);
    RunFor(10 * 1000);
  }
  RunFor(500 * 1000);
  delay.SetDelay(0.0f);
  RunFor(5 * 60 * 1000);
}

TEST_P(BweTest, Multi2) {
  ChokeFilter choke(this);
  JitterFilter jitter(this);
  RateCounterFilter counter(this);
  choke.SetCapacity(2000);
  jitter.SetJitter(120);
  RunFor(5 * 60 * 1000);
}
}  // namespace bwe
}  // namespace testing
}  // namespace webrtc
<|endoftext|>


<commit_before><commit_msg>Refactoring ...<commit_after><|endoftext|>


<commit_before>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file CdsdkCommon.cpp CDSDK - Common functions
//

// includes
#include "stdafx.h"
#include "CdsdkCommon.hpp"
#include "CameraException.hpp"
#include "CdsdkSourceInfoImpl.hpp"
#include "ErrorText.hpp"

using namespace CDSDK;

void CDSDK::CheckError(const CString& cszFunction, cdError err, LPCSTR pszFile, UINT uiLine)
{
   if (err == cdOK)
      return;

   cdError componentId = err & cdERROR_COMPONENTID_MASK;
   cdError errorId = err & cdERROR_ERRORID_MASK;

   CString cszMessage;
   cszMessage.Format(_T("Error in function \"%s\": %s, %s%s (%08x)"),
      cszFunction.GetString(),
      componentId == cdERROR_CLIENT_COMPONENTID ? _T("Client") :
      componentId == cdERROR_LLSDK_COMPONENTID ? _T("LLSDK") :
      componentId == cdERROR_HLSDK_COMPONENTID ? _T("HLSDK") :
      componentId == cdERROR_PROPERTY_PARSING_COMPONENTID ? _T("PropertyParsing") :
      componentId == cdERROR_VIEW_DEVELOPMENT_COMPONENTID ? _T("ViewDevelopment") :
      componentId == cdERROR_VIEW_DECODING_COMPONENTID ? _T("ViewDecoding") :
      componentId == cdERROR_COLOR_MAPPING_COMPONENTID ? _T("ColorMapping") :
      componentId == cdERROR_PICTURE_COLLECTION_COMPONENTID ? _T("PictureCollection") :
      componentId == cdERROR_SETUP_COMPONENTID ? _T("Setup") :
      componentId == cdERROR_IWRAP_COMPONENTID ? _T("IWrap") :
      componentId == cdERROR_PSUSD_COMPONENTID ? _T("PSUSD") :
      componentId == cdERROR_CDSDK_COMPONENTID ? _T("CDSDK") :
      componentId == cdERROR_RDSDK_COMPONENTID ? _T("RDSDK") :  _T("???"),
      ErrorTextFromErrorId(errorId),
      (err & cdERROR_ISSPECIFIC_MASK) != 0 ? _T(", IsSpecific") : _T(""),
      err);

   throw CameraException(cszFunction, cszMessage, err, pszFile, uiLine);
}

Ref::Ref()
{
   cdVersionInfo version = {0};
   version.Size = sizeof(version);
   version.MajorVersion = 7;
   version.MinorVersion = 3;

   cdUInt32 option = 0; // reserved

   // may return cdINVALID_PARAMETER when version mismatch with dlls used
   // may return cdINVALID_FN_CALL when called a second time
   cdError err = CDStartSDK(&version, option);
   LOG_TRACE(_T("CDStartSDK(&version, 0) returned %08x\n"), err);
   CheckError(_T("CDStartSDK"), err, __FILE__, __LINE__);
}

Ref::~Ref() throw()
{
   // may return cdMEM_FREE_FAILED
   cdError err = CDFinishSDK();
   LOG_TRACE(_T("CDFinishSDK() returned %08x\n"), err);
}

void Ref::AddVersionText(CString& cszVersionText) const
{
   cszVersionText += _T("CD-SDK (Canon Digital camera SDK)\n");

   cdVersionInfo versionInfo = { sizeof(versionInfo) };

   // may return cdINVALID_PARAMETER
   cdError err = CDGetSDKVersion(&versionInfo);
   LOG_TRACE(_T("CDGetSDKVersion() returned %08x\n"), err);

   CString cszTemp;
   cszTemp.Format(_T("   CD-SDK %u.%u.%u (%hs)\n"),
      versionInfo.MajorVersion,
      versionInfo.MinorVersion,
      versionInfo.ReleaseVersion,
      versionInfo.chVersion);

   cszVersionText += cszTemp;
   cszVersionText += _T("\n");
}

/// SEH-safe call to CDEnumDeviceReset() function
cdError CDEnumDeviceReset_SEH(cdUInt32 Kind, cdHEnum* phEnum)
{
   __try
   {
      cdError err = CDEnumDeviceReset(Kind, phEnum);
      return err;
   }
   __except(EXCEPTION_EXECUTE_HANDLER)
   {
      DWORD dwCode = GetExceptionCode();
      LOG_TRACE(_T("CDEnumDeviceReset(1, %08x) caused a structured exception: 0x%08x\n"), *phEnum, dwCode);
      return dwCode;
   }
}

void Ref::EnumerateDevices(std::vector<std::shared_ptr<SourceInfo>>& vecSourceDevices) const
{
   cdUInt32 uiCount = 0;
   cdHEnum hEnum = 0;

   // may return cdINVALID_PARAMETER, or any exception code
   cdError err = CDEnumDeviceReset_SEH(1, &hEnum);
   if (err != cdOK) LOG_TRACE(_T("CDEnumDeviceReset(1, %08x) returned %08x\n"), hEnum, err);
   CheckError(_T("CDEnumDeviceReset"), err, __FILE__, __LINE__);

   // returns cdINVALID_HANDLE, cdINVALID_PARAMETER
   err = CDGetDeviceCount(hEnum, &uiCount);
   if (err != cdOK) LOG_TRACE(_T("CDGetDeviceCount(%08x, &count = %u) returned %08x\n"), hEnum, uiCount, err);
   CheckError(_T("CDGetDeviceCount"), err, __FILE__, __LINE__);

   for (cdUInt32 ui=0; ui<uiCount; ui++)
   {
      std::shared_ptr<CDSDK::SourceInfoImpl> spImpl(new SourceInfoImpl(const_cast<Ref*>(this)->shared_from_this()));

      cdSourceInfo& si = spImpl->GetSourceInfo();

      // may return cdINVALID_PARAMETER, cdINVALID_HANDLE, cdENUM_NA
      err = CDEnumDeviceNext(hEnum, &si);
      if ((err & cdERROR_ERRORID_MASK) == cdENUM_NA)
         break; // done

      if (err != cdOK) LOG_TRACE(_T("CDEnumDeviceNext(%08x, &si = \"%hs\") returned %08x\n"), hEnum, si.Name, err);

      CheckError(_T("CDEnumDeviceNext"), err, __FILE__, __LINE__);

      LOG_TRACE(_T("device %u, ModelName=%hs, InternalName=%hs, PortType=%s\n"),
         ui,
         si.Name,
         si.NameInOS,
         si.PortType == cdPORT_TYPE_NO_PORT ? _T("None") :
         si.PortType == cdPORT_TYPE_STI ? _T("STI") :
         si.PortType == cdPORT_TYPE_WIA ? _T("WIA") :
         si.PortType == cdPORT_TYPE_ANY ? _T("Any") : _T("???")
         );

      vecSourceDevices.push_back(spImpl);
   }

   // may return cdINVALID_HANDLE, cdINVALID_FN_CALL
   err = CDEnumDeviceRelease(hEnum);
   if (err != cdOK) LOG_TRACE(_T("CDEnumDeviceRelease(%08x) returned %08x\n"), hEnum, err);
   CheckError(_T("CDEnumDeviceRelease"), err, __FILE__, __LINE__);
}
<commit_msg>output CDSDK connection details for STI and WIA<commit_after>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file CdsdkCommon.cpp CDSDK - Common functions
//

// includes
#include "stdafx.h"
#include "CdsdkCommon.hpp"
#include "CameraException.hpp"
#include "CdsdkSourceInfoImpl.hpp"
#include "ErrorText.hpp"

using namespace CDSDK;

void CDSDK::CheckError(const CString& cszFunction, cdError err, LPCSTR pszFile, UINT uiLine)
{
   if (err == cdOK)
      return;

   cdError componentId = err & cdERROR_COMPONENTID_MASK;
   cdError errorId = err & cdERROR_ERRORID_MASK;

   CString cszMessage;
   cszMessage.Format(_T("Error in function \"%s\": %s, %s%s (%08x)"),
      cszFunction.GetString(),
      componentId == cdERROR_CLIENT_COMPONENTID ? _T("Client") :
      componentId == cdERROR_LLSDK_COMPONENTID ? _T("LLSDK") :
      componentId == cdERROR_HLSDK_COMPONENTID ? _T("HLSDK") :
      componentId == cdERROR_PROPERTY_PARSING_COMPONENTID ? _T("PropertyParsing") :
      componentId == cdERROR_VIEW_DEVELOPMENT_COMPONENTID ? _T("ViewDevelopment") :
      componentId == cdERROR_VIEW_DECODING_COMPONENTID ? _T("ViewDecoding") :
      componentId == cdERROR_COLOR_MAPPING_COMPONENTID ? _T("ColorMapping") :
      componentId == cdERROR_PICTURE_COLLECTION_COMPONENTID ? _T("PictureCollection") :
      componentId == cdERROR_SETUP_COMPONENTID ? _T("Setup") :
      componentId == cdERROR_IWRAP_COMPONENTID ? _T("IWrap") :
      componentId == cdERROR_PSUSD_COMPONENTID ? _T("PSUSD") :
      componentId == cdERROR_CDSDK_COMPONENTID ? _T("CDSDK") :
      componentId == cdERROR_RDSDK_COMPONENTID ? _T("RDSDK") :  _T("???"),
      ErrorTextFromErrorId(errorId),
      (err & cdERROR_ISSPECIFIC_MASK) != 0 ? _T(", IsSpecific") : _T(""),
      err);

   throw CameraException(cszFunction, cszMessage, err, pszFile, uiLine);
}

Ref::Ref()
{
   cdVersionInfo version = {0};
   version.Size = sizeof(version);
   version.MajorVersion = 7;
   version.MinorVersion = 3;

   cdUInt32 option = 0; // reserved

   // may return cdINVALID_PARAMETER when version mismatch with dlls used
   // may return cdINVALID_FN_CALL when called a second time
   cdError err = CDStartSDK(&version, option);
   LOG_TRACE(_T("CDStartSDK(&version, 0) returned %08x\n"), err);
   CheckError(_T("CDStartSDK"), err, __FILE__, __LINE__);
}

Ref::~Ref() throw()
{
   // may return cdMEM_FREE_FAILED
   cdError err = CDFinishSDK();
   LOG_TRACE(_T("CDFinishSDK() returned %08x\n"), err);
}

void Ref::AddVersionText(CString& cszVersionText) const
{
   cszVersionText += _T("CD-SDK (Canon Digital camera SDK)\n");

   cdVersionInfo versionInfo = { sizeof(versionInfo) };

   // may return cdINVALID_PARAMETER
   cdError err = CDGetSDKVersion(&versionInfo);
   LOG_TRACE(_T("CDGetSDKVersion() returned %08x\n"), err);

   CString cszTemp;
   cszTemp.Format(_T("   CD-SDK %u.%u.%u (%hs)\n"),
      versionInfo.MajorVersion,
      versionInfo.MinorVersion,
      versionInfo.ReleaseVersion,
      versionInfo.chVersion);

   cszVersionText += cszTemp;
   cszVersionText += _T("\n");
}

/// SEH-safe call to CDEnumDeviceReset() function
cdError CDEnumDeviceReset_SEH(cdUInt32 Kind, cdHEnum* phEnum)
{
   __try
   {
      cdError err = CDEnumDeviceReset(Kind, phEnum);
      return err;
   }
   __except(EXCEPTION_EXECUTE_HANDLER)
   {
      DWORD dwCode = GetExceptionCode();
      LOG_TRACE(_T("CDEnumDeviceReset(1, %08x) caused a structured exception: 0x%08x\n"), *phEnum, dwCode);
      return dwCode;
   }
}

void Ref::EnumerateDevices(std::vector<std::shared_ptr<SourceInfo>>& vecSourceDevices) const
{
   cdUInt32 uiCount = 0;
   cdHEnum hEnum = 0;

   // may return cdINVALID_PARAMETER, or any exception code
   cdError err = CDEnumDeviceReset_SEH(1, &hEnum);
   if (err != cdOK) LOG_TRACE(_T("CDEnumDeviceReset(1, %08x) returned %08x\n"), hEnum, err);
   CheckError(_T("CDEnumDeviceReset"), err, __FILE__, __LINE__);

   // returns cdINVALID_HANDLE, cdINVALID_PARAMETER
   err = CDGetDeviceCount(hEnum, &uiCount);
   if (err != cdOK) LOG_TRACE(_T("CDGetDeviceCount(%08x, &count = %u) returned %08x\n"), hEnum, uiCount, err);
   CheckError(_T("CDGetDeviceCount"), err, __FILE__, __LINE__);

   for (cdUInt32 ui=0; ui<uiCount; ui++)
   {
      std::shared_ptr<CDSDK::SourceInfoImpl> spImpl(new SourceInfoImpl(const_cast<Ref*>(this)->shared_from_this()));

      cdSourceInfo& si = spImpl->GetSourceInfo();

      // may return cdINVALID_PARAMETER, cdINVALID_HANDLE, cdENUM_NA
      err = CDEnumDeviceNext(hEnum, &si);
      if ((err & cdERROR_ERRORID_MASK) == cdENUM_NA)
         break; // done

      if (err != cdOK) LOG_TRACE(_T("CDEnumDeviceNext(%08x, &si = \"%hs\") returned %08x\n"), hEnum, si.Name, err);

      CheckError(_T("CDEnumDeviceNext"), err, __FILE__, __LINE__);

      CString cszDetails;
      switch (si.PortType)
      {
      case cdPORT_TYPE_STI:
         cszDetails.Format(_T(", DataType=%s, DeviceInternalName=%ls"),
            si.u.STI.DataType == cdDEV_DATA_TYPE_UNKNOWN ? _T("Unknown") :
            si.u.STI.DataType == cdDEV_DATA_TYPE_UNDECIDED ? _T("Undecided") :
            si.u.STI.DataType == cdDEV_DATA_TYPE_1 ? _T("Type 1") :
            si.u.STI.DataType == cdDEV_DATA_TYPE_2 ? _T("Type 2") : _T("???"),
            si.u.STI.DeviceInternalName);
         break;

      case cdPORT_TYPE_WIA:
         cszDetails.Format(_T(", DataType=%s, DeviceID=%ls"),
            si.u.WIA.DataType == cdDEV_DATA_TYPE_UNKNOWN ? _T("Unknown") :
            si.u.WIA.DataType == cdDEV_DATA_TYPE_UNDECIDED ? _T("Undecided") :
            si.u.WIA.DataType == cdDEV_DATA_TYPE_1 ? _T("Type 1") :
            si.u.WIA.DataType == cdDEV_DATA_TYPE_2 ? _T("Type 2") : _T("???"),
            si.u.WIA.pDIPDevID);
         break;
      };

      LOG_TRACE(_T("device %u, ModelName=%hs, InternalName=%hs, PortType=%s%s\n"),
         ui,
         si.Name,
         si.NameInOS,
         si.PortType == cdPORT_TYPE_NO_PORT ? _T("None") :
         si.PortType == cdPORT_TYPE_STI ? _T("STI") :
         si.PortType == cdPORT_TYPE_WIA ? _T("WIA") :
         si.PortType == cdPORT_TYPE_ANY ? _T("Any") : _T("???"),
         cszDetails.GetString());

      vecSourceDevices.push_back(spImpl);
   }

   // may return cdINVALID_HANDLE, cdINVALID_FN_CALL
   err = CDEnumDeviceRelease(hEnum);
   if (err != cdOK) LOG_TRACE(_T("CDEnumDeviceRelease(%08x) returned %08x\n"), hEnum, err);
   CheckError(_T("CDEnumDeviceRelease"), err, __FILE__, __LINE__);
}
<|endoftext|>