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

#include "views/controls/button/native_button.h"

#include "base/i18n/rtl.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "views/controls/native/native_view_host.h"

#if defined(OS_WIN)
#include "ui/gfx/platform_font_win.h"
#elif defined(OS_LINUX)
#include <gdk/gdkkeysyms.h>
#include "views/screen.h"
#endif

namespace views {

#if defined(OS_WIN)
// The min size in DLUs comes from
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwue/html/ch14e.asp
static const int kMinWidthDLUs = 50;
static const int kMinHeightDLUs = 14;

// Horizontal padding (on each side).
static const int kButtonBorderHWidth = 8;
#else
// Horizontal padding (on each side).
static const int kButtonBorderHWidth = 0;
#endif

// static
const char NativeButtonBase::kViewClassName[] = "views/NativeButtonBase";

////////////////////////////////////////////////////////////////////////////////
// NativeButtonBase, public:

NativeButtonBase::NativeButtonBase(ButtonListener* listener)
    : Button(listener),
      native_wrapper_(NULL),
      is_default_(false),
      need_elevation_(false),
      ignore_minimum_size_(false) {
  InitBorder();
  set_focusable(true);
}

NativeButtonBase::NativeButtonBase(ButtonListener* listener,
                                   const std::wstring& label)
    : Button(listener),
      native_wrapper_(NULL),
      is_default_(false),
      need_elevation_(false),
      ignore_minimum_size_(false) {
  SetLabel(label);  // SetLabel takes care of label layout in RTL UI.
  InitBorder();
  set_focusable(true);
}

NativeButtonBase::~NativeButtonBase() {
}

void NativeButtonBase::SetLabel(const std::wstring& label) {
  label_ = WideToUTF16Hack(label);

  // Even though we create a flipped HWND for a native button when the locale
  // is right-to-left, Windows does not render text for the button using a
  // right-to-left context (perhaps because the parent HWND is not flipped).
  // The result is that RTL strings containing punctuation marks are not
  // displayed properly. For example, the string "...ABC" (where A, B and C are
  // Hebrew characters) is displayed as "ABC..." which is incorrect.
  //
  // In order to overcome this problem, we mark the localized Hebrew strings as
  // RTL strings explicitly (using the appropriate Unicode formatting) so that
  // Windows displays the text correctly regardless of the HWND hierarchy.
  base::i18n::AdjustStringForLocaleDirection(&label_);

  if (native_wrapper_)
    native_wrapper_->UpdateLabel();

  // Update the accessible name whenever the label changes.
  SetAccessibleName(WideToUTF16Hack(label));
  PreferredSizeChanged();
}

void NativeButtonBase::SetIsDefault(bool is_default) {
  if (is_default == is_default_)
    return;
  is_default_ = is_default;
  if (is_default_)
    AddAccelerator(Accelerator(ui::VKEY_RETURN, false, false, false));
  else
    RemoveAccelerator(Accelerator(ui::VKEY_RETURN, false, false, false));
  if (native_wrapper_)
    native_wrapper_->UpdateDefault();
  PreferredSizeChanged();
}

void NativeButtonBase::SetNeedElevation(bool need_elevation) {
  need_elevation_ = need_elevation;
  if (native_wrapper_)
    native_wrapper_->UpdateLabel();
  PreferredSizeChanged();
}

void NativeButtonBase::ButtonPressed() {
  RequestFocus();

  // TODO(beng): obtain mouse event flags for native buttons someday.
#if defined(OS_WIN)
  DWORD pos = GetMessagePos();
  POINTS points = MAKEPOINTS(pos);
  gfx::Point cursor_point(points.x, points.y);
#elif defined(OS_LINUX)
  gfx::Point cursor_point = Screen::GetCursorScreenPoint();
#endif

  views::MouseEvent event(ui::ET_MOUSE_RELEASED,
                          cursor_point.x(), cursor_point.y(),
                          ui::EF_LEFT_BUTTON_DOWN);
  NotifyClick(event);
}

////////////////////////////////////////////////////////////////////////////////
// NativeButtonBase, View overrides:

gfx::Size NativeButtonBase::GetPreferredSize() {
  if (!native_wrapper_)
    return gfx::Size();

  gfx::Size sz = native_wrapper_->GetView()->GetPreferredSize();

  // Add in the border size. (Do this before clamping the minimum size in case
  // that clamping causes an increase in size that would include the borders.
  gfx::Insets border = GetInsets();
  sz.set_width(sz.width() + border.left() + border.right());
  sz.set_height(sz.height() + border.top() + border.bottom());

#if defined(OS_WIN)
  // Clamp the size returned to at least the minimum size.
  if (!ignore_minimum_size_) {
    gfx::PlatformFontWin* platform_font =
        static_cast<gfx::PlatformFontWin*>(font_.platform_font());
    sz.set_width(std::max(
        sz.width(),
        platform_font->horizontal_dlus_to_pixels(kMinWidthDLUs)));
    sz.set_height(std::max(
        sz.height(),
        platform_font->vertical_dlus_to_pixels(kMinHeightDLUs)));
  }
  // GTK returns a meaningful preferred size so that we don't need to adjust
  // the preferred size as we do on windows.
#endif

  return sz;
}

void NativeButtonBase::Layout() {
  if (native_wrapper_) {
    native_wrapper_->GetView()->SetBounds(0, 0, width(), height());
    native_wrapper_->GetView()->Layout();
  }
}

void NativeButtonBase::OnEnabledChanged() {
  Button::OnEnabledChanged();
  if (native_wrapper_)
    native_wrapper_->UpdateEnabled();
}

void NativeButtonBase::ViewHierarchyChanged(bool is_add, View* parent,
                                         View* child) {
  if (is_add && !native_wrapper_ && GetWidget()) {
    // The native wrapper's lifetime will be managed by the view hierarchy after
    // we call AddChildView.
    native_wrapper_ = CreateWrapper();
    UpdateAllStates();
    AddChildView(native_wrapper_->GetView());
  }
}

std::string NativeButtonBase::GetClassName() const {
  return kViewClassName;
}

bool NativeButtonBase::AcceleratorPressed(const Accelerator& accelerator) {
  if (IsEnabled()) {
#if defined(OS_WIN)
    DWORD pos = GetMessagePos();
    POINTS points = MAKEPOINTS(pos);
    gfx::Point cursor_point(points.x, points.y);
#elif defined(OS_LINUX)
    gfx::Point cursor_point = Screen::GetCursorScreenPoint();
#endif
    views::MouseEvent event(ui::ET_MOUSE_RELEASED,
                            cursor_point.x(), cursor_point.y(),
                            ui::EF_LEFT_BUTTON_DOWN);
    NotifyClick(event);
    return true;
  }
  return false;
}

void NativeButtonBase::OnFocus() {
  // Forward the focus to the wrapper.
  if (native_wrapper_)
    native_wrapper_->SetFocus();
  else
    Button::OnFocus();  // Will focus the RootView window (so we still get
                        // keyboard messages).
}

void NativeButtonBase::OnPaintFocusBorder(gfx::Canvas* canvas) {
  if (NativeViewHost::kRenderNativeControlFocus)
    View::OnPaintFocusBorder(canvas);
}

////////////////////////////////////////////////////////////////////////////////
// NativeButtonBase, protected:

NativeButtonWrapper* NativeButtonBase::CreateWrapper() {
  return NativeButtonWrapper::CreateNativeButtonWrapper(this);
}

void NativeButtonBase::InitBorder() {
  set_border(Border::CreateEmptyBorder(0, kButtonBorderHWidth, 0,
                                       kButtonBorderHWidth));
}

////////////////////////////////////////////////////////////////////////////////
// NativeButtonBase, private:
void NativeButtonBase::UpdateAllStates() {
  native_wrapper_->UpdateLabel();
  native_wrapper_->UpdateFont();
  native_wrapper_->UpdateEnabled();
  native_wrapper_->UpdateDefault();
  native_wrapper_->UpdateChecked();
  native_wrapper_->UpdateAccessibleName();
}

#if defined(TOUCH_UI)
////////////////////////////////////////////////////////////////////////////////
// NativeButton, public:

NativeButton::NativeButton(ButtonListener* listener, const std::wstring& label)
    : TextButton(listener, label), is_default_(false) {
  set_alignment(TextButton::ALIGN_CENTER);
  SetNormalHasBorder(true);
  set_focusable(true);
}

void NativeButton::SetLabel(const std::wstring& label) {
  SetText(label);
}

void NativeButton::set_font(const gfx::Font& font) {
  SetFont(font);
}

void NativeButton::SetIsDefault(bool default_button) {
  is_default_ = default_button;
}

bool NativeButton::is_default() const {
  return is_default_;
}

void NativeButton::set_ignore_minimum_size(bool) {
    // TODO(saintlou): ignoring for now
}
#else
////////////////////////////////////////////////////////////////////////////////
// NativeButton, public:

NativeButton::NativeButton(ButtonListener* listener)
    : NativeButtonBase(listener) {
}

NativeButton::NativeButton(ButtonListener* listener, const std::wstring& label)
    : NativeButtonBase(listener, label) {
}

NativeButton::~NativeButton() {
}
#endif

}  // namespace views
<commit_msg>Fix touch compile after some button cleanup (r88149).<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "views/controls/button/native_button.h"

#include "base/i18n/rtl.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "views/controls/native/native_view_host.h"

#if defined(OS_WIN)
#include "ui/gfx/platform_font_win.h"
#elif defined(OS_LINUX)
#include <gdk/gdkkeysyms.h>
#include "views/screen.h"
#endif

namespace views {

#if defined(OS_WIN)
// The min size in DLUs comes from
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwue/html/ch14e.asp
static const int kMinWidthDLUs = 50;
static const int kMinHeightDLUs = 14;

// Horizontal padding (on each side).
static const int kButtonBorderHWidth = 8;
#else
// Horizontal padding (on each side).
static const int kButtonBorderHWidth = 0;
#endif

// static
const char NativeButtonBase::kViewClassName[] = "views/NativeButtonBase";

////////////////////////////////////////////////////////////////////////////////
// NativeButtonBase, public:

NativeButtonBase::NativeButtonBase(ButtonListener* listener)
    : Button(listener),
      native_wrapper_(NULL),
      is_default_(false),
      need_elevation_(false),
      ignore_minimum_size_(false) {
  InitBorder();
  set_focusable(true);
}

NativeButtonBase::NativeButtonBase(ButtonListener* listener,
                                   const std::wstring& label)
    : Button(listener),
      native_wrapper_(NULL),
      is_default_(false),
      need_elevation_(false),
      ignore_minimum_size_(false) {
  SetLabel(label);  // SetLabel takes care of label layout in RTL UI.
  InitBorder();
  set_focusable(true);
}

NativeButtonBase::~NativeButtonBase() {
}

void NativeButtonBase::SetLabel(const std::wstring& label) {
  label_ = WideToUTF16Hack(label);

  // Even though we create a flipped HWND for a native button when the locale
  // is right-to-left, Windows does not render text for the button using a
  // right-to-left context (perhaps because the parent HWND is not flipped).
  // The result is that RTL strings containing punctuation marks are not
  // displayed properly. For example, the string "...ABC" (where A, B and C are
  // Hebrew characters) is displayed as "ABC..." which is incorrect.
  //
  // In order to overcome this problem, we mark the localized Hebrew strings as
  // RTL strings explicitly (using the appropriate Unicode formatting) so that
  // Windows displays the text correctly regardless of the HWND hierarchy.
  base::i18n::AdjustStringForLocaleDirection(&label_);

  if (native_wrapper_)
    native_wrapper_->UpdateLabel();

  // Update the accessible name whenever the label changes.
  SetAccessibleName(WideToUTF16Hack(label));
  PreferredSizeChanged();
}

void NativeButtonBase::SetIsDefault(bool is_default) {
  if (is_default == is_default_)
    return;
  is_default_ = is_default;
  if (is_default_)
    AddAccelerator(Accelerator(ui::VKEY_RETURN, false, false, false));
  else
    RemoveAccelerator(Accelerator(ui::VKEY_RETURN, false, false, false));
  if (native_wrapper_)
    native_wrapper_->UpdateDefault();
  PreferredSizeChanged();
}

void NativeButtonBase::SetNeedElevation(bool need_elevation) {
  need_elevation_ = need_elevation;
  if (native_wrapper_)
    native_wrapper_->UpdateLabel();
  PreferredSizeChanged();
}

void NativeButtonBase::ButtonPressed() {
  RequestFocus();

  // TODO(beng): obtain mouse event flags for native buttons someday.
#if defined(OS_WIN)
  DWORD pos = GetMessagePos();
  POINTS points = MAKEPOINTS(pos);
  gfx::Point cursor_point(points.x, points.y);
#elif defined(OS_LINUX)
  gfx::Point cursor_point = Screen::GetCursorScreenPoint();
#endif

  views::MouseEvent event(ui::ET_MOUSE_RELEASED,
                          cursor_point.x(), cursor_point.y(),
                          ui::EF_LEFT_BUTTON_DOWN);
  NotifyClick(event);
}

////////////////////////////////////////////////////////////////////////////////
// NativeButtonBase, View overrides:

gfx::Size NativeButtonBase::GetPreferredSize() {
  if (!native_wrapper_)
    return gfx::Size();

  gfx::Size sz = native_wrapper_->GetView()->GetPreferredSize();

  // Add in the border size. (Do this before clamping the minimum size in case
  // that clamping causes an increase in size that would include the borders.
  gfx::Insets border = GetInsets();
  sz.set_width(sz.width() + border.left() + border.right());
  sz.set_height(sz.height() + border.top() + border.bottom());

#if defined(OS_WIN)
  // Clamp the size returned to at least the minimum size.
  if (!ignore_minimum_size_) {
    gfx::PlatformFontWin* platform_font =
        static_cast<gfx::PlatformFontWin*>(font_.platform_font());
    sz.set_width(std::max(
        sz.width(),
        platform_font->horizontal_dlus_to_pixels(kMinWidthDLUs)));
    sz.set_height(std::max(
        sz.height(),
        platform_font->vertical_dlus_to_pixels(kMinHeightDLUs)));
  }
  // GTK returns a meaningful preferred size so that we don't need to adjust
  // the preferred size as we do on windows.
#endif

  return sz;
}

void NativeButtonBase::Layout() {
  if (native_wrapper_) {
    native_wrapper_->GetView()->SetBounds(0, 0, width(), height());
    native_wrapper_->GetView()->Layout();
  }
}

void NativeButtonBase::OnEnabledChanged() {
  Button::OnEnabledChanged();
  if (native_wrapper_)
    native_wrapper_->UpdateEnabled();
}

void NativeButtonBase::ViewHierarchyChanged(bool is_add, View* parent,
                                         View* child) {
  if (is_add && !native_wrapper_ && GetWidget()) {
    // The native wrapper's lifetime will be managed by the view hierarchy after
    // we call AddChildView.
    native_wrapper_ = CreateWrapper();
    UpdateAllStates();
    AddChildView(native_wrapper_->GetView());
  }
}

std::string NativeButtonBase::GetClassName() const {
  return kViewClassName;
}

bool NativeButtonBase::AcceleratorPressed(const Accelerator& accelerator) {
  if (IsEnabled()) {
#if defined(OS_WIN)
    DWORD pos = GetMessagePos();
    POINTS points = MAKEPOINTS(pos);
    gfx::Point cursor_point(points.x, points.y);
#elif defined(OS_LINUX)
    gfx::Point cursor_point = Screen::GetCursorScreenPoint();
#endif
    views::MouseEvent event(ui::ET_MOUSE_RELEASED,
                            cursor_point.x(), cursor_point.y(),
                            ui::EF_LEFT_BUTTON_DOWN);
    NotifyClick(event);
    return true;
  }
  return false;
}

void NativeButtonBase::OnFocus() {
  // Forward the focus to the wrapper.
  if (native_wrapper_)
    native_wrapper_->SetFocus();
  else
    Button::OnFocus();  // Will focus the RootView window (so we still get
                        // keyboard messages).
}

void NativeButtonBase::OnPaintFocusBorder(gfx::Canvas* canvas) {
  if (NativeViewHost::kRenderNativeControlFocus)
    View::OnPaintFocusBorder(canvas);
}

////////////////////////////////////////////////////////////////////////////////
// NativeButtonBase, protected:

NativeButtonWrapper* NativeButtonBase::CreateWrapper() {
  return NativeButtonWrapper::CreateNativeButtonWrapper(this);
}

void NativeButtonBase::InitBorder() {
  set_border(Border::CreateEmptyBorder(0, kButtonBorderHWidth, 0,
                                       kButtonBorderHWidth));
}

////////////////////////////////////////////////////////////////////////////////
// NativeButtonBase, private:
void NativeButtonBase::UpdateAllStates() {
  native_wrapper_->UpdateLabel();
  native_wrapper_->UpdateFont();
  native_wrapper_->UpdateEnabled();
  native_wrapper_->UpdateDefault();
  native_wrapper_->UpdateChecked();
  native_wrapper_->UpdateAccessibleName();
}

#if defined(TOUCH_UI)
////////////////////////////////////////////////////////////////////////////////
// NativeButton, public:

NativeButton::NativeButton(ButtonListener* listener, const std::wstring& label)
    : TextButton(listener, label), is_default_(false) {
  set_alignment(TextButton::ALIGN_CENTER);
  static_cast<TextButtonBorder*>(border())->copy_normal_set_to_hot_set();
  set_focusable(true);
}

void NativeButton::SetLabel(const std::wstring& label) {
  SetText(label);
}

void NativeButton::set_font(const gfx::Font& font) {
  SetFont(font);
}

void NativeButton::SetIsDefault(bool default_button) {
  is_default_ = default_button;
}

bool NativeButton::is_default() const {
  return is_default_;
}

void NativeButton::set_ignore_minimum_size(bool) {
    // TODO(saintlou): ignoring for now
}
#else
////////////////////////////////////////////////////////////////////////////////
// NativeButton, public:

NativeButton::NativeButton(ButtonListener* listener)
    : NativeButtonBase(listener) {
}

NativeButton::NativeButton(ButtonListener* listener, const std::wstring& label)
    : NativeButtonBase(listener, label) {
}

NativeButton::~NativeButton() {
}
#endif

}  // namespace views
<|endoftext|>


<commit_before>#include "main.h"
#include "im.h"
#include "jzon.h"
#include <opencv2/gpu/gpu.hpp>

using namespace eigengo::akka;

Main::Main(const std::string queue, const std::string exchange, const std::string routingKey) :
RabbitRpcServer::RabbitRpcServer(queue, exchange, routingKey) {

}

std::string Main::handleMessage(const AmqpClient::BasicMessage::ptr_t message, const AmqpClient::Channel::ptr_t channel) {
	ImageMessage imageMessage(message);

	Jzon::Object responseJson;
	try {
		Jzon::Array coinsJson;
		//Jzon::Array facesJson;
		auto imageData = imageMessage.headImage();
		auto imageMat = cv::imdecode(cv::Mat(imageData), 1);
		// ponies & unicorns
		auto coins = coinCounter.count(imageMat);

		for (auto i = coins.begin(); i != coins.end(); ++i) {
			/*
			Jzon::Object faceJson;
			faceJson.Add("left", face.left);
			faceJson.Add("top", face.top);
			faceJson.Add("width", face.width);
			faceJson.Add("height", face.height);
			facesJson.Add(faceJson);
			*/
			Jzon::Object coinJson;
			coinJson.Add("center", i->center);
			coinJson.Add("radius", i->radius);
			coinsJson.Add(coinJson);
		}
		//responseJson.Add("faces", facesJson);
		responseJson.Add("coins", coinsJson);
		responseJson.Add("succeeded", true);
	} catch (std::exception &e) {
		// bantha poodoo!
		std::cerr << e.what() << std::endl;
		responseJson.Add("succeeded", false);
	} catch (...) {
		// bantha poodoo!
		responseJson.Add("succeeded", false);
	}
	Jzon::Writer writer(responseJson, Jzon::NoFormat);
	writer.Write();

	return writer.GetResult();
}

void Main::inThreadInit() {
	using namespace cv::gpu;
	int deviceCount = getCudaEnabledDeviceCount();
	if (deviceCount > 0) {
		setDevice(0);
	}
}

int main(int argc, char** argv) {
	Main main("sogx.recog.queue", "sogx.exchange", "sogx.recog.key");
	main.runAndJoin(8);
	return 0;
}<commit_msg>Error handling<commit_after>#include "main.h"
#include "im.h"
#include "jzon.h"
#include <opencv2/gpu/gpu.hpp>

using namespace eigengo::akka;

Main::Main(const std::string queue, const std::string exchange, const std::string routingKey) :
RabbitRpcServer::RabbitRpcServer(queue, exchange, routingKey) {

}

std::string Main::handleMessage(const AmqpClient::BasicMessage::ptr_t message, const AmqpClient::Channel::ptr_t channel) {
	Jzon::Object responseJson;
	try {
		ImageMessage imageMessage(message);

		Jzon::Array coinsJson;
		//Jzon::Array facesJson;
		auto imageData = imageMessage.headImage();
		auto imageMat = cv::imdecode(cv::Mat(imageData), 1);
		// ponies & unicorns
		auto coins = coinCounter.count(imageMat);

		for (auto i = coins.begin(); i != coins.end(); ++i) {
			/*
			Jzon::Object faceJson;
			faceJson.Add("left", face.left);
			faceJson.Add("top", face.top);
			faceJson.Add("width", face.width);
			faceJson.Add("height", face.height);
			facesJson.Add(faceJson);
			*/
			Jzon::Object coinJson;
			coinJson.Add("center", i->center);
			coinJson.Add("radius", i->radius);
			coinsJson.Add(coinJson);
		}
		//responseJson.Add("faces", facesJson);
		responseJson.Add("coins", coinsJson);
		responseJson.Add("succeeded", true);
	} catch (std::exception &e) {
		// bantha poodoo!
		std::cerr << e.what() << std::endl;
		responseJson.Add("succeeded", false);
	} catch (...) {
		// bantha poodoo!
		responseJson.Add("succeeded", false);
	}
	Jzon::Writer writer(responseJson, Jzon::NoFormat);
	writer.Write();

	return writer.GetResult();
}

void Main::inThreadInit() {
	using namespace cv::gpu;
	int deviceCount = getCudaEnabledDeviceCount();
	if (deviceCount > 0) {
		setDevice(0);
	}
}

int main(int argc, char** argv) {
	Main main("sogx.recog.queue", "sogx.exchange", "sogx.recog.key");
	main.runAndJoin(8);
	return 0;
}<|endoftext|>


<commit_before>#include "../../local/include/gtest/gtest.h"

#include <vector>

// uncomment to use threads
//#define THREADED

#ifdef THREADED

// Tron
//#define NUM_CORES 4
// Clue
#define NUM_CORES 12

#include <thread>
#include <future>

#endif  // THREADED

#include "genetic.h"
#include "genetic_circuit.h"
#include "circuit.h"
#include "utility.h"

TEST(InnocuousAttempt, XOR) {
  BooleanTable expected_o = {{false},
                             {true}
                             {false},
                             {true}};
  BooleanTable expected_o = {{false},
                             {true}
                             {true},
                             {false}};

  std::mt19937 rand(std::random_device{}());
  // std::minstd_rand0 rand(std::random_device{}());
  GeneticCircuit* c = new GeneticCircuit(2, 1, &rand);
  BooleanTable answer = c->evaluateAllInputs();
  int i = 0;

  // #ifdef THREADED
  // std::vector<std::future<BooleanTable>> boolean_table_futures;
  // #endif THREADED

  while ((answer != expected_o) || (answer != expected_o_bar)) {
    // #ifdef THREADED
    // for (int i = 0; i < (NUM_CORES - 1); ++i) {
    //   boolean_table_futures.push_back(
    //       std::async(std::launch::async, , points));
    // }
    // #endif THREADED

    // std::vector<Path> paths;  // vector of possible paths
    // // Calculate a path on main thread while waiting for other threads
    // // If we're doing more than 1 set, do NUM_SETS random path calculations
    // on
    // // main thread
    // for (int i = 0; i < NUM_SETS; i++) {
    //   paths.push_back(FindRandomPath(points));
    // }

    // // Get Paths from threads
    // for (auto& pathfuture : pathfutures) {
    //   paths.push_back(pathfuture.get());
    // }

    delete c;
    c = new GeneticCircuit(2, 1, &rand);
    std::cerr << "Iteration: " + std::to_string(++i) << std::endl;
    // std::cerr << *c << std::endl;
    answer = c->evaluateAllInputs();
  }
}

TEST(InnocuousAttempt, FullAdder) {
  BooleanTable expected_o = {{false, false},
                             {false, true},
                             {false, true},
                             {true, false},
                             {false, true},
                             {true, false},
                             {true, false},
                             {true, true}};
  BooleanTable expected_o_bar = {{false, false},
                                 {true, false},
                                 {true, false},
                                 {false, true},
                                 {true, false},
                                 {false, true},
                                 {false, true},
                                 {true, true}};
  std::mt19937 rand(std::random_device{}());
  // std::minstd_rand0 rand(std::random_device{}());
  GeneticCircuit* c = new GeneticCircuit(3, 2, &rand);
  BooleanTable answer = c->evaluateAllInputs();
  int i = 0;

  // #ifdef THREADED
  // std::vector<std::future<BooleanTable>> boolean_table_futures;
  // #endif THREADED

  while ((answer != expected_o) || (answer != expected_o_bar)) {
    // #ifdef THREADED
    // for (int i = 0; i < (NUM_CORES - 1); ++i) {
    //   boolean_table_futures.push_back(
    //       std::async(std::launch::async, , points));
    // }
    // #endif THREADED

    // std::vector<Path> paths;  // vector of possible paths
    // // Calculate a path on main thread while waiting for other threads
    // // If we're doing more than 1 set, do NUM_SETS random path calculations
    // on
    // // main thread
    // for (int i = 0; i < NUM_SETS; i++) {
    //   paths.push_back(FindRandomPath(points));
    // }

    // // Get Paths from threads
    // for (auto& pathfuture : pathfutures) {
    //   paths.push_back(pathfuture.get());
    // }

    delete c;
    c = new GeneticCircuit(3, 2, &rand);
    std::cerr << "Iteration: " + std::to_string(++i) << std::endl;
    // std::cerr << *c << std::endl;
    answer = c->evaluateAllInputs();
  }
}

// TEST(InnocuousAttempt, InvertInputs) {
//   BooleanTable expected_o = {{true, true, true},
//                              {true, true, false},
//                              {true, false, true},
//                              {true, false, false},
//                              {false, true, true},
//                              {false, true, false},
//                              {false, false, true},
//                              {false, false, false}};
//   std::mt19937 rand(std::random_device{}());
//   // std::minstd_rand0 rand(std::random_device{}());
//   GeneticCircuit* c = new GeneticCircuit(3, 3, &rand);
//   while (c->evaluateAllInputs() != expected_o) {
//     delete c;
//     c = new GeneticCircuit(3, 3, &rand);
//     std::cerr << *c << std::endl;
//   }
// }
<commit_msg>fix missing commas<commit_after>#include "../../local/include/gtest/gtest.h"

#include <vector>

// uncomment to use threads
//#define THREADED

#ifdef THREADED

// Tron
//#define NUM_CORES 4
// Clue
#define NUM_CORES 12

#include <thread>
#include <future>

#endif  // THREADED

#include "genetic.h"
#include "genetic_circuit.h"
#include "circuit.h"
#include "utility.h"

TEST(InnocuousAttempt, XOR) {
  BooleanTable expected_o = {{false},
                             {true},
                             {false},
                             {true}};
  BooleanTable expected_o = {{false},
                             {true},
                             {true},
                             {false}};

  std::mt19937 rand(std::random_device{}());
  // std::minstd_rand0 rand(std::random_device{}());
  GeneticCircuit* c = new GeneticCircuit(2, 1, &rand);
  BooleanTable answer = c->evaluateAllInputs();
  int i = 0;

  // #ifdef THREADED
  // std::vector<std::future<BooleanTable>> boolean_table_futures;
  // #endif THREADED

  while ((answer != expected_o) || (answer != expected_o_bar)) {
    // #ifdef THREADED
    // for (int i = 0; i < (NUM_CORES - 1); ++i) {
    //   boolean_table_futures.push_back(
    //       std::async(std::launch::async, , points));
    // }
    // #endif THREADED

    // std::vector<Path> paths;  // vector of possible paths
    // // Calculate a path on main thread while waiting for other threads
    // // If we're doing more than 1 set, do NUM_SETS random path calculations
    // on
    // // main thread
    // for (int i = 0; i < NUM_SETS; i++) {
    //   paths.push_back(FindRandomPath(points));
    // }

    // // Get Paths from threads
    // for (auto& pathfuture : pathfutures) {
    //   paths.push_back(pathfuture.get());
    // }

    delete c;
    c = new GeneticCircuit(2, 1, &rand);
    std::cerr << "Iteration: " + std::to_string(++i) << std::endl;
    // std::cerr << *c << std::endl;
    answer = c->evaluateAllInputs();
  }
}

TEST(InnocuousAttempt, FullAdder) {
  BooleanTable expected_o = {{false, false},
                             {false, true},
                             {false, true},
                             {true, false},
                             {false, true},
                             {true, false},
                             {true, false},
                             {true, true}};
  BooleanTable expected_o_bar = {{false, false},
                                 {true, false},
                                 {true, false},
                                 {false, true},
                                 {true, false},
                                 {false, true},
                                 {false, true},
                                 {true, true}};
  std::mt19937 rand(std::random_device{}());
  // std::minstd_rand0 rand(std::random_device{}());
  GeneticCircuit* c = new GeneticCircuit(3, 2, &rand);
  BooleanTable answer = c->evaluateAllInputs();
  int i = 0;

  // #ifdef THREADED
  // std::vector<std::future<BooleanTable>> boolean_table_futures;
  // #endif THREADED

  while ((answer != expected_o) || (answer != expected_o_bar)) {
    // #ifdef THREADED
    // for (int i = 0; i < (NUM_CORES - 1); ++i) {
    //   boolean_table_futures.push_back(
    //       std::async(std::launch::async, , points));
    // }
    // #endif THREADED

    // std::vector<Path> paths;  // vector of possible paths
    // // Calculate a path on main thread while waiting for other threads
    // // If we're doing more than 1 set, do NUM_SETS random path calculations
    // on
    // // main thread
    // for (int i = 0; i < NUM_SETS; i++) {
    //   paths.push_back(FindRandomPath(points));
    // }

    // // Get Paths from threads
    // for (auto& pathfuture : pathfutures) {
    //   paths.push_back(pathfuture.get());
    // }

    delete c;
    c = new GeneticCircuit(3, 2, &rand);
    std::cerr << "Iteration: " + std::to_string(++i) << std::endl;
    // std::cerr << *c << std::endl;
    answer = c->evaluateAllInputs();
  }
}

// TEST(InnocuousAttempt, InvertInputs) {
//   BooleanTable expected_o = {{true, true, true},
//                              {true, true, false},
//                              {true, false, true},
//                              {true, false, false},
//                              {false, true, true},
//                              {false, true, false},
//                              {false, false, true},
//                              {false, false, false}};
//   std::mt19937 rand(std::random_device{}());
//   // std::minstd_rand0 rand(std::random_device{}());
//   GeneticCircuit* c = new GeneticCircuit(3, 3, &rand);
//   while (c->evaluateAllInputs() != expected_o) {
//     delete c;
//     c = new GeneticCircuit(3, 3, &rand);
//     std::cerr << *c << std::endl;
//   }
// }
<|endoftext|>


<commit_before>/*
 * EMULAB-COPYRIGHT
 * Copyright (c) 2003, 2004 University of Utah and the Flux Group.
 * All rights reserved.
 */

/*
 *
 */
#include <stdio.h>
#include <ctype.h>
#include <netdb.h>
#include <unistd.h>
#include <time.h>
#include <math.h>
#include <paths.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "config.h"
#include "event.h"
#include "tbdefs.h"
#include "log.h"
#include <map>
#include <string>
#include <iostream>

static int debug = 0;
static event_handle_t localhandle;
static event_handle_t bosshandle;
static std::map<std::string, event_subscription_t> exptmap;
static char nodeidstr[BUFSIZ], ipaddr[32];
;

void
usage(char *progname)
{
    fprintf(stderr, "Usage: %s [-s server] [-p port] -n pnodeid -l local_elvin_port\n", progname);
    exit(-1);
}

static void
callback(event_handle_t handle,
	 event_notification_t notification, void *data);

static void
expt_callback(event_handle_t handle,
	 event_notification_t notification, void *data);

static void
sched_callback(event_handle_t handle,
	       event_notification_t notification, void *data);

static void subscribe_callback(event_handle_t handle,  int result,
			       event_subscription_t es, void *data);

static void schedule_updateevent();

int
main(int argc, char **argv)
{
	address_tuple_t		tuple;
	char			*progname;
	char			*server = NULL;
	char			*port = NULL, *lport = NULL;
	char			*myeid = NULL;
	char			*pnodeid = NULL;
	char			buf[BUFSIZ];
	char			hostname[MAXHOSTNAMELEN];
	struct hostent		*he;
	int			c;
	struct in_addr		myip;
	FILE			*fp;

	progname = argv[0];

	while ((c = getopt(argc, argv, "ds:p:e:n:l:")) != -1) {
		switch (c) {
		case 'd':
			debug++;
			break;
		case 's':
			server = optarg;
			break;
		case 'p':
			port = optarg;
			break;
		case 'l':
			lport = optarg;
			break;
		case 'e':
			myeid = optarg;
			break;
		case 'n':
		        pnodeid = optarg;
                        break;
		default:
			usage(progname);
		}
	}
	argc -= optind;
	argv += optind;

	if (argc)
		usage(progname);

	if ((! pnodeid) || (! lport))
	   fatal("Must provide pnodeid and local elvin port");

	if (debug) {
	        loginit(0, 0);
        }

	/*
	 * Get our IP address. Thats how we name this host to the
	 * event System.
	 */
	if (gethostname(hostname, MAXHOSTNAMELEN) == -1) {
		fatal("could not get hostname: %s\n", strerror(errno));
	}
	if (! (he = gethostbyname(hostname))) {
		fatal("could not get IP address from hostname: %s", hostname);
	}
	memcpy((char *)&myip, he->h_addr, he->h_length);
	strcpy(ipaddr, inet_ntoa(myip));

	/*
	 * If server is not specified, then it defaults to EVENTSERVER.
	 * This allows the client to work on either users.emulab.net
	 * or on a client node.
	 */
	if (!server)
	  server = EVENTSERVER;

	/*
	 * Convert server/port to elvin thing.
	 *
	 * XXX This elvin string stuff should be moved down a layer.
	 */
	snprintf(buf, sizeof(buf), "elvin://%s%s%s",
		 server,
		 (port ? ":"  : ""),
		 (port ? port : ""));
	server = buf;

	/*
	 * Construct an address tuple for generating the event.
	 */
	tuple = address_tuple_alloc();
	if (tuple == NULL) {
		fatal("could not allocate an address tuple");
	}

	/* Register with the event system on boss */
	bosshandle = event_register(server, 0);
	if (bosshandle == NULL) {
		fatal("could not register with remote event system");
	}

	snprintf(buf, sizeof(buf), "elvin://localhost:%s",lport);

	/* Register with the event system on the local node */
	localhandle = event_register(buf, 0);
	if (localhandle == NULL) {
		fatal("could not register with local event system");
	}

	/*
	 * Create a subscription to pass to the remote server. We want
	 * all events for this node, or all events for the experiment
	 * if the node is unspecified (we want to avoid getting events
	 * that are directed at specific nodes that are not us!).
	 */
	snprintf(nodeidstr, sizeof(nodeidstr), "__%s_proxy", pnodeid);
	snprintf(buf, sizeof(buf), "%s,%s,%s",
                 TBDB_EVENTTYPE_UPDATE, TBDB_EVENTTYPE_CLEAR,
                 TBDB_EVENTTYPE_RELOAD);

	tuple->eventtype = buf;
	tuple->host = ipaddr;
	tuple->objname = nodeidstr;
	tuple->objtype = TBDB_OBJECTTYPE_EVPROXY;

	/* Subscribe to the test event: */
	if (! event_subscribe(bosshandle, callback, tuple,
			      (void *)"event received")) {
		fatal("could not subscribe to events on remote server");
        }

        /* Setup the global event passthru */
	address_tuple_free(tuple);
	tuple = address_tuple_alloc();

	snprintf(buf, sizeof(buf), "%s,%s",
                 ipaddr, ADDRESSTUPLE_ALL);

	tuple->host = buf;
	tuple->expt = TBDB_EVENTEXPT_NONE;

	if (! event_subscribe(bosshandle, expt_callback, tuple,
			      NULL)) {
		fatal("could not subscribe to events on remote server");
        }

        /*
         * Setup local elvind subscriptions:
         */
	address_tuple_free(tuple);
	tuple = address_tuple_alloc();

        tuple->host = ADDRESSTUPLE_ALL;
        tuple->scheduler = 1;

	if (! event_subscribe(localhandle, sched_callback, tuple,
			      NULL)) {
		fatal("could not subscribe to events on local server");
	}

        info("Successfully setup initial event subscriptions.\n");

	/*
	 * Stash the pid away.
	 */
	snprintf(buf, sizeof(buf), "%s/evproxy.pid", _PATH_VARRUN);
	fp = fopen(buf, "w");
	if (fp != NULL) {
		fprintf(fp, "%d\n", getpid());
		(void) fclose(fp);
	}

        /* Tell the schedulers on ops that we want a subscription update. */
	schedule_updateevent();

	/*
	 * Do this now, once we have had a chance to fail on the above
	 * event system calls.
	 */
	if (!debug) {
		daemon(0, 0);
		loginit(0, "/var/emulab/logs/evproxy.log");
	}

	/* Begin the event loop, waiting to receive event notifications */
        info("Entering main event loop.\n");
	event_main(bosshandle);

	/* Unregister with the remote event system: */
	if (event_unregister(bosshandle) == 0) {
		fatal("could not unregister with remote event system");
	}
	/* Unregister with the local event system: */
	if (event_unregister(localhandle) == 0) {
		fatal("could not unregister with local event system");
	}

	return 0;
}

/*
 * Handle incoming events from the remote server.
 */
static void
callback(event_handle_t handle, event_notification_t notification, void *data)
{
	char		eventtype[TBDB_FLEN_EVEVENTTYPE];
	char		objecttype[TBDB_FLEN_EVOBJTYPE];
	char		objectname[TBDB_FLEN_EVOBJNAME];
	char            expt[TBDB_FLEN_PID + TBDB_FLEN_EID + 1];

	event_notification_get_eventtype(handle,
					 notification, eventtype, sizeof(eventtype));
	event_notification_get_objtype(handle,
				       notification, objecttype, sizeof(objecttype));
	event_notification_get_objname(handle,
				       notification, objectname, sizeof(objectname));
	event_notification_get_expt(handle, notification, expt, sizeof(expt));

	if (debug) {
	  info("%s %s %s\n", eventtype, objecttype, objectname);
	}

	if (strcmp(objecttype,TBDB_OBJECTTYPE_EVPROXY) == 0) {

	  /* Add a new subcription request if a new expt is added on
	   * the plab node.
	   */

	  if (strcmp(eventtype,TBDB_EVENTTYPE_UPDATE) == 0) {

	    std::string key(expt);
	    std::map<std::string, event_subscription_t>::iterator member =
	      exptmap.find(key);

	    if(member == exptmap.end()) {

	      address_tuple_t tuple = address_tuple_alloc();
	      if (tuple == NULL) {
		fatal("could not allocate an address tuple");
	      }

	      tuple->expt = expt;

	      /* malloc data -- to be freed in subscribe_callback */
	      char *data = (char *) xmalloc(sizeof(expt));
	      strcpy(data, expt);

	      int retval = event_async_subscribe(bosshandle,
					  expt_callback, tuple, NULL,
					  subscribe_callback,
					  (void *) data, 1);
	      if (! retval) {
		error("could not subscribe to events on remote server.\n");
	      }

              info("Subscribing to experiment: %s\n", expt);

	      address_tuple_free(tuple);
	    }
	  }

	  /* Remove a old subcription whenever get a CLEAR message */

	  else if (strcmp(eventtype,TBDB_EVENTTYPE_CLEAR) == 0) {
	    std::string key(expt);

	    std::map<std::string, event_subscription_t>::iterator member =
	      exptmap.find(key);

	    if(member != exptmap.end()) {
	      event_subscription_t tmp = member->second;

	      /* remove the subscription */
	      int success = event_async_unsubscribe(handle, tmp);

	      if (!success) {
		error("not able to delete the subscription.\n");
		elvin_error_fprintf(stderr, handle->status);
	      } else {
		exptmap.erase(key);
                info("Unsubscribing from experiment: %s\n", expt);
	      }
	    }
	  }

	  /* reset all subscriptions if you get a RELOAD event */
	  else if (strcmp(eventtype,TBDB_EVENTTYPE_RELOAD) == 0) {

            info("RELOAD received.  Clearing experiment subscriptions "
                 "and scheduling an UPDATE.\n");

	    std::map<std::string, event_subscription_t>::iterator iter;

	    for(iter = exptmap.begin(); iter != exptmap.end(); iter++) {
	      /* remove the subscription */
	      std::string key = iter->first;
	      event_subscription_t tmp = iter->second;

	      int success = event_async_unsubscribe(handle, tmp);

	      if (!success) {
		error("not able to delete the subscription.\n");
		elvin_error_fprintf(stderr, handle->status);
	      }
	    }

	    exptmap.clear();
            schedule_updateevent();

	  }

	}
}

/*
 * Handle incoming experiment events from the remote server
 */
static void
expt_callback(event_handle_t handle, event_notification_t notification, void *data)
{
	char		objecttype[TBDB_FLEN_EVOBJTYPE];
        char		objectname[TBDB_FLEN_EVOBJNAME];
	char            expt[TBDB_FLEN_PID + TBDB_FLEN_EID + 1];

	event_notification_get_objtype(handle,
				       notification, objecttype, sizeof(objecttype));
        event_notification_get_objname(handle,
				       notification, objectname, sizeof(objectname));
        event_notification_get_expt(handle, notification, expt, sizeof(expt));

        if (debug) {
          info("Received event for %s: %s %s\n", expt, objecttype, objectname);
	}

	if (strcmp(objecttype,TBDB_OBJECTTYPE_EVPROXY) != 0) {
	  /*
           * Resend the notification to the local server.
           */
          if (! event_notify(localhandle, notification))
            error("Failed to deliver notification!\n");
	}

}

static void
sched_callback(event_handle_t handle,
	       event_notification_t notification,
	       void *data)
{
        if (! event_notify(bosshandle, notification))
		error("Failed to deliver scheduled notification!\n");

}

/* Callback functions for asysn event subscribe and ubnsubscribe */

void subscribe_callback(event_handle_t handle,  int result,
			event_subscription_t es, void *data) {
  if (result) {
    std::string key((char *)data);
    exptmap[key] = es;
    info("Subscription for %s added successfully.\n", (char *)data);
  } else {
    error("not able to delete the subscription.\n");
    elvin_error_fprintf(stderr, handle->status);
  }

  free(data);

}

void schedule_updateevent() {
  /* send a message to elvind on ops */
  address_tuple_t tuple = address_tuple_alloc();

  struct timeval now;
  gettimeofday(&now, NULL);

  if (tuple == NULL) {
    fatal("could not allocate an address tuple");
  }

  tuple->objtype = TBDB_OBJECTTYPE_EVPROXY;
  tuple->objname = nodeidstr;
  tuple->eventtype = TBDB_EVENTTYPE_UPDATE;
  tuple->host = ipaddr;

  event_notification_t notification =
    event_notification_alloc(bosshandle, tuple);

  if (notification == NULL) {
    fatal("could not allocate notification\n");
  }

  if (event_schedule(bosshandle, notification, &now) == 0) {
    error("could not schedule update event.\n");
  }

  info("Scheduled remote UPDATE event.\n");

  event_notification_free(bosshandle, notification);

  address_tuple_free(tuple);

}
<commit_msg><commit_after>/*
 * EMULAB-COPYRIGHT
 * Copyright (c) 2003, 2004 University of Utah and the Flux Group.
 * All rights reserved.
 */

/*
 *
 */
#include <stdio.h>
#include <ctype.h>
#include <netdb.h>
#include <unistd.h>
#include <time.h>
#include <math.h>
#include <paths.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "config.h"
#include "event.h"
#include "tbdefs.h"
#include "log.h"
#include <map>
#include <string>
#include <iostream>

static int debug = 0;
static event_handle_t localhandle;
static event_handle_t bosshandle;
static std::map<std::string, event_subscription_t> exptmap;
static char nodeidstr[BUFSIZ], ipaddr[32];
;

void
usage(char *progname)
{
    fprintf(stderr, "Usage: %s [-s server] [-p port] -n pnodeid -l local_elvin_port\n", progname);
    exit(-1);
}

static void
callback(event_handle_t handle,
	 event_notification_t notification, void *data);

static void
expt_callback(event_handle_t handle,
	 event_notification_t notification, void *data);

static void
sched_callback(event_handle_t handle,
	       event_notification_t notification, void *data);

static void subscribe_callback(event_handle_t handle,  int result,
			       event_subscription_t es, void *data);

static void async_callback(event_handle_t handle,  int result,
			   event_subscription_t es, void *data);

static void schedule_updateevent();

int
main(int argc, char **argv)
{
	address_tuple_t		tuple;
	char			*progname;
	char			*server = NULL;
	char			*port = NULL, *lport = NULL;
	char			*myeid = NULL;
	char			*pnodeid = NULL;
	char			buf[BUFSIZ];
	char			hostname[MAXHOSTNAMELEN];
	struct hostent		*he;
	int			c;
	struct in_addr		myip;
	FILE			*fp;

	progname = argv[0];

	while ((c = getopt(argc, argv, "ds:p:e:n:l:")) != -1) {
		switch (c) {
		case 'd':
			debug++;
			break;
		case 's':
			server = optarg;
			break;
		case 'p':
			port = optarg;
			break;
		case 'l':
			lport = optarg;
			break;
		case 'e':
			myeid = optarg;
			break;
		case 'n':
		        pnodeid = optarg;
                        break;
		default:
			usage(progname);
		}
	}
	argc -= optind;
	argv += optind;

	if (argc)
		usage(progname);

	if ((! pnodeid) || (! lport))
	   fatal("Must provide pnodeid and local elvin port");

	if (debug) {
	        loginit(0, 0);
        }

	/*
	 * Get our IP address. Thats how we name this host to the
	 * event System.
	 */
	if (gethostname(hostname, MAXHOSTNAMELEN) == -1) {
		fatal("could not get hostname: %s\n", strerror(errno));
	}
	if (! (he = gethostbyname(hostname))) {
		fatal("could not get IP address from hostname: %s", hostname);
	}
	memcpy((char *)&myip, he->h_addr, he->h_length);
	strcpy(ipaddr, inet_ntoa(myip));

	/*
	 * If server is not specified, then it defaults to EVENTSERVER.
	 * This allows the client to work on either users.emulab.net
	 * or on a client node.
	 */
	if (!server)
	  server = EVENTSERVER;

	/*
	 * Convert server/port to elvin thing.
	 *
	 * XXX This elvin string stuff should be moved down a layer.
	 */
	snprintf(buf, sizeof(buf), "elvin://%s%s%s",
		 server,
		 (port ? ":"  : ""),
		 (port ? port : ""));
	server = buf;

	/*
	 * Construct an address tuple for generating the event.
	 */
	tuple = address_tuple_alloc();
	if (tuple == NULL) {
		fatal("could not allocate an address tuple");
	}

	/* Register with the event system on boss */
	bosshandle = event_register(server, 0);
	if (bosshandle == NULL) {
		fatal("could not register with remote event system");
	}

	snprintf(buf, sizeof(buf), "elvin://localhost:%s",lport);

	/* Register with the event system on the local node */
	localhandle = event_register(buf, 0);
	if (localhandle == NULL) {
		fatal("could not register with local event system");
	}

	/*
	 * Create a subscription to pass to the remote server. We want
	 * all events for this node, or all events for the experiment
	 * if the node is unspecified (we want to avoid getting events
	 * that are directed at specific nodes that are not us!).
	 */
	snprintf(nodeidstr, sizeof(nodeidstr), "__%s_proxy", pnodeid);
	snprintf(buf, sizeof(buf), "%s,%s,%s",
                 TBDB_EVENTTYPE_UPDATE, TBDB_EVENTTYPE_CLEAR,
                 TBDB_EVENTTYPE_RELOAD);

	tuple->eventtype = buf;
	tuple->host = ipaddr;
	tuple->objname = nodeidstr;
	tuple->objtype = TBDB_OBJECTTYPE_EVPROXY;

	/* Subscribe to the test event: */
	if (! event_subscribe(bosshandle, callback, tuple,
			      (void *)"event received")) {
		fatal("could not subscribe to events on remote server");
        }

        /* Setup the global event passthru */
	address_tuple_free(tuple);
	tuple = address_tuple_alloc();

	snprintf(buf, sizeof(buf), "%s,%s",
                 ipaddr, ADDRESSTUPLE_ALL);

	tuple->host = buf;
	tuple->expt = TBDB_EVENTEXPT_NONE;

	if (! event_subscribe(bosshandle, expt_callback, tuple,
			      NULL)) {
		fatal("could not subscribe to events on remote server");
        }

        /*
         * Setup local elvind subscriptions:
         */
	address_tuple_free(tuple);
	tuple = address_tuple_alloc();

        tuple->host = ADDRESSTUPLE_ALL;
        tuple->scheduler = 1;

	if (! event_subscribe(localhandle, sched_callback, tuple,
			      NULL)) {
		fatal("could not subscribe to events on local server");
	}

        info("Successfully setup initial event subscriptions.\n");

	/*
	 * Stash the pid away.
	 */
	snprintf(buf, sizeof(buf), "%s/evproxy.pid", _PATH_VARRUN);
	fp = fopen(buf, "w");
	if (fp != NULL) {
		fprintf(fp, "%d\n", getpid());
		(void) fclose(fp);
	}

        /* Tell the schedulers on ops that we want a subscription update. */
	schedule_updateevent();

	/*
	 * Do this now, once we have had a chance to fail on the above
	 * event system calls.
	 */
	if (!debug) {
		daemon(0, 0);
		loginit(0, "/var/emulab/logs/evproxy.log");
	}

	/* Begin the event loop, waiting to receive event notifications */
        info("Entering main event loop.\n");
	event_main(bosshandle);

	/* Unregister with the remote event system: */
	if (event_unregister(bosshandle) == 0) {
		fatal("could not unregister with remote event system");
	}
	/* Unregister with the local event system: */
	if (event_unregister(localhandle) == 0) {
		fatal("could not unregister with local event system");
	}

	return 0;
}

/*
 * Handle incoming events from the remote server.
 */
static void
callback(event_handle_t handle, event_notification_t notification, void *data)
{
	char		eventtype[TBDB_FLEN_EVEVENTTYPE];
	char		objecttype[TBDB_FLEN_EVOBJTYPE];
	char		objectname[TBDB_FLEN_EVOBJNAME];
	char            expt[TBDB_FLEN_PID + TBDB_FLEN_EID + 1];

	event_notification_get_eventtype(handle,
					 notification, eventtype, sizeof(eventtype));
	event_notification_get_objtype(handle,
				       notification, objecttype, sizeof(objecttype));
	event_notification_get_objname(handle,
				       notification, objectname, sizeof(objectname));
	event_notification_get_expt(handle, notification, expt, sizeof(expt));

	if (debug) {
	  info("%s %s %s\n", eventtype, objecttype, objectname);
	}

	if (strcmp(objecttype,TBDB_OBJECTTYPE_EVPROXY) == 0) {

	  /* Add a new subcription request if a new expt is added on
	   * the plab node.
	   */

	  if (strcmp(eventtype,TBDB_EVENTTYPE_UPDATE) == 0) {

	    std::string key(expt);
	    std::map<std::string, event_subscription_t>::iterator member =
	      exptmap.find(key);

	    if(member == exptmap.end()) {

	      address_tuple_t tuple = address_tuple_alloc();
	      if (tuple == NULL) {
		fatal("could not allocate an address tuple");
	      }

	      tuple->expt = expt;
	      tuple->scheduler = 2;

	      /* malloc data -- to be freed in subscribe_callback */
	      char *data = (char *) xmalloc(sizeof(expt));
	      strcpy(data, expt);

	      int retval = event_async_subscribe(bosshandle,
					  expt_callback, tuple, NULL,
					  subscribe_callback,
					  (void *) data, 1);
	      if (! retval) {
		error("could not subscribe to events on remote server.\n");
	      }

	      tuple->scheduler = 0;

	      retval = event_async_subscribe(bosshandle,
					  expt_callback, tuple, NULL,
					  async_callback,
					  NULL, 1);
	      if (! retval) {
		error("could not subscribe to events on remote server.\n");
	      }

              info("Subscribing to experiment: %s\n", expt);

	      address_tuple_free(tuple);
	    }
	  }

	  /* Remove a old subcription whenever get a CLEAR message */

	  else if (strcmp(eventtype,TBDB_EVENTTYPE_CLEAR) == 0) {
	    std::string key(expt);

	    std::map<std::string, event_subscription_t>::iterator member =
	      exptmap.find(key);

	    if(member != exptmap.end()) {
	      event_subscription_t tmp = member->second;

	      /* remove the subscription */
	      int success = event_async_unsubscribe(handle, tmp);

	      if (!success) {
		error("not able to delete the subscription.\n");
		elvin_error_fprintf(stderr, handle->status);
	      } else {
		exptmap.erase(key);
                info("Unsubscribing from experiment: %s\n", expt);
	      }
	    }
	  }

	  /* reset all subscriptions if you get a RELOAD event */
	  else if (strcmp(eventtype,TBDB_EVENTTYPE_RELOAD) == 0) {

            info("RELOAD received.  Clearing experiment subscriptions "
                 "and scheduling an UPDATE.\n");

	    std::map<std::string, event_subscription_t>::iterator iter;

	    for(iter = exptmap.begin(); iter != exptmap.end(); iter++) {
	      /* remove the subscription */
	      std::string key = iter->first;
	      event_subscription_t tmp = iter->second;

	      int success = event_async_unsubscribe(handle, tmp);

	      if (!success) {
		error("not able to delete the subscription.\n");
		elvin_error_fprintf(stderr, handle->status);
	      }
	    }

	    exptmap.clear();
            schedule_updateevent();

	  }

	  /* pass thru EVPROXY events to plab-scheduler */
	  if (! event_notify(localhandle, notification))
            error("Failed to deliver notification!\n");

	}
}

/*
 * Handle incoming experiment events from the remote server
 */
static void
expt_callback(event_handle_t handle, event_notification_t notification, void *data)
{
	char		objecttype[TBDB_FLEN_EVOBJTYPE];
        char		objectname[TBDB_FLEN_EVOBJNAME];
	char            expt[TBDB_FLEN_PID + TBDB_FLEN_EID + 1];
	int		plabsched = 0;

	event_notification_get_objtype(handle,
				       notification, objecttype, sizeof(objecttype));
        event_notification_get_objname(handle,
				       notification, objectname, sizeof(objectname));
        event_notification_get_expt(handle, notification, expt, sizeof(expt));

        if (debug) {
          info("Received event for %s: %s %s\n", expt, objecttype, objectname);
	}

	if (strcmp(objecttype,TBDB_OBJECTTYPE_EVPROXY) != 0) {
	  /*
           * Filter <plabsched,1> events, and for rest resend the notification
	   * to the local elvind server.
           */
	  int ret = event_notification_get_int32(handle, notification,
						 TBDB_PLABSCHED, &plabsched);

	  if ((!ret) || (plabsched != 1)) {

	    if (! event_notify(localhandle, notification))
	      error("Failed to deliver notification!\n");
	  }
	}
}

static void
sched_callback(event_handle_t handle,
	       event_notification_t notification,
	       void *data)
{
        if (! event_notify(bosshandle, notification))
		error("Failed to deliver scheduled notification!\n");

}

/* Callback functions for asysn event subscribe */

void subscribe_callback(event_handle_t handle,  int result,
			event_subscription_t es, void *data) {
  if (result) {
    std::string key((char *)data);
    exptmap[key] = es;
    info("Subscription for %s added successfully.\n", (char *)data);
  } else {
    error("not able to add the subscription.\n");
    elvin_error_fprintf(stderr, handle->status);
  }

  free(data);

}

/* Callback functions for async event subscribe/unsubscribe */

void async_callback(event_handle_t handle,  int result,
			event_subscription_t es, void *data) {
  if (!result) {
    error("Error in async callback\n");
    elvin_error_fprintf(stderr, handle->status);
  }

}

void schedule_updateevent() {
  /* send a message to elvind on ops */
  address_tuple_t tuple = address_tuple_alloc();

  struct timeval now;
  gettimeofday(&now, NULL);

  if (tuple == NULL) {
    fatal("could not allocate an address tuple");
  }

  tuple->objtype = TBDB_OBJECTTYPE_EVPROXY;
  tuple->objname = nodeidstr;
  tuple->eventtype = TBDB_EVENTTYPE_UPDATE;
  tuple->host = ipaddr;

  event_notification_t notification =
    event_notification_alloc(bosshandle, tuple);

  if (notification == NULL) {
    fatal("could not allocate notification\n");
  }

  if (event_schedule(bosshandle, notification, &now) == 0) {
    error("could not schedule update event.\n");
  }

  info("Scheduled remote UPDATE event.\n");

  event_notification_free(bosshandle, notification);

  address_tuple_free(tuple);

}
<|endoftext|>


<commit_before>#include "ofApp.h"
#include "iostream.h"

void useStream(IOStream &stream) {
    ((ofApp *) ofGetAppPtr())->useIStream(stream);
    ((ofApp *) ofGetAppPtr())->useOStream(stream);
}

void useStream(IOStreamVector &stream) {
    ((ofApp *) ofGetAppPtr())->useIStream(stream);
    ((ofApp *) ofGetAppPtr())->useOStream(stream);
}

void ASCIISerialStream::onReceive(uint32_t label) {
    serial_->writeByte(label + '0');
    serial_->writeByte('\n');
}

void ASCIISerialStream::onReceive(vector<double> data) {
    for (int i = 0; i < data.size(); i++) {
        string s = to_string(data[i]);
        if (i > 0) serial_->writeByte('\t');
        for (int j = 0; j < s.size(); j++) serial_->writeByte(s[j]);
    }
    if (data.size() > 0) serial_->writeByte('\n');
}

void ASCIISerialStream::parseSerial(vector<unsigned char> &buffer) {
    auto newline = find(buffer.begin(), buffer.end(), '\n');
    if (newline != buffer.end()) {
        string s(buffer.begin(), newline);

        buffer.erase(newline);
        buffer.erase(buffer.begin(), newline);

        if (data_ready_callback_ != nullptr) {
            istringstream iss(s);
            vector<double> data;
            double d;

            while (iss >> d) data.push_back(d);

            if (data.size() > 0) {
                data = normalize(data);

                GRT::MatrixDouble matrix;
                matrix.push_back(data);

                data_ready_callback_(matrix);
            }
        }
    }
}

void BinaryIntArraySerialStream::onReceive(uint32_t label) {
    serial_->writeByte(label + '0');
    serial_->writeByte('\n');
}

void BinaryIntArraySerialStream::onReceive(vector<double> data) {
    for (int i = 0; i < data.size(); i++) {
        string s = to_string(data[i]);
        if (i > 0) serial_->writeByte('\t');
        for (int j = 0; j < s.size(); j++) serial_->writeByte(s[j]);
    }
    if (data.size() > 0) serial_->writeByte('\n');
}

void BinaryIntArraySerialStream::parseSerial(vector<unsigned char> &buffer) {
    auto start = std::find(buffer.begin(), buffer.end(), 0); // look for packet start
    if (start != buffer.end()) {
        buffer.erase(buffer.begin(), start); // advance to start of packet
        if (buffer.size() >= 3) { // 0, LSB(n), MSB(n)
            unsigned char checksum = 0;
            int LSB = buffer[1]; checksum += LSB;
            int MSB = buffer[2]; checksum += MSB;
            int n = ((MSB & 0x7F) << 7) | (LSB & 0x7F);
            if (buffer.size() >= 4 + 2 * n) {
                vector<double> vals;
                //std::cout << "Got array of " << n << " bytes: " << buffer.size();
                for (int j = 3; j < (3 + 2 * n);) {
                    LSB = buffer[j++]; checksum += LSB;
                    MSB = buffer[j++]; checksum += MSB;
                    int val = ((MSB & 0x7F) << 7) | (LSB & 0x7F);
                    //std::cout << val << " ";
                    vals.push_back(val);
                }
                //std::cout << "(" << (checksum | 0x80) << " <> " << buffer[3 + 2 * n] << ")" << std::endl;
                if ((checksum | 0x80) != buffer[3 + 2 * n]) {
                    ofLog(OF_LOG_WARNING) << "Invalid checksum, discarding serial packet.";
                } else if (n != getNumInputDimensions()) {
                    ofLog(OF_LOG_WARNING) << "Serial packet contains " << n <<
                        " dimensions. Expected " << getNumInputDimensions();
                } else {
                    GRT::MatrixDouble data(1, n);
                    for (int i = 0; i < getNumInputDimensions(); i++) {
                        int b = vals[i];
                        data[0][i] = (normalizer_ != nullptr) ? normalizer_(b) : b;
                    }
                    if (data_ready_callback_ != nullptr) {
                        data_ready_callback_(data);
                    }

                }

                buffer.erase(buffer.begin(), buffer.begin() + (4 + 2 * n));
            }
        }
    }
}<commit_msg>Don't erase twice in the same vector.<commit_after>#include "ofApp.h"
#include "iostream.h"

void useStream(IOStream &stream) {
    ((ofApp *) ofGetAppPtr())->useIStream(stream);
    ((ofApp *) ofGetAppPtr())->useOStream(stream);
}

void useStream(IOStreamVector &stream) {
    ((ofApp *) ofGetAppPtr())->useIStream(stream);
    ((ofApp *) ofGetAppPtr())->useOStream(stream);
}

void ASCIISerialStream::onReceive(uint32_t label) {
    serial_->writeByte(label + '0');
    serial_->writeByte('\n');
}

void ASCIISerialStream::onReceive(vector<double> data) {
    for (int i = 0; i < data.size(); i++) {
        string s = to_string(data[i]);
        if (i > 0) serial_->writeByte('\t');
        for (int j = 0; j < s.size(); j++) serial_->writeByte(s[j]);
    }
    if (data.size() > 0) serial_->writeByte('\n');
}

void ASCIISerialStream::parseSerial(vector<unsigned char> &buffer) {
    auto newline = find(buffer.begin(), buffer.end(), '\n');
    if (newline != buffer.end()) {
        string s(buffer.begin(), newline);

        buffer.erase(buffer.begin(), ++newline);

        if (data_ready_callback_ != nullptr) {
            istringstream iss(s);
            vector<double> data;
            double d;

            while (iss >> d) data.push_back(d);

            if (data.size() > 0) {
                data = normalize(data);

                GRT::MatrixDouble matrix;
                matrix.push_back(data);

                data_ready_callback_(matrix);
            }
        }
    }
}

void BinaryIntArraySerialStream::onReceive(uint32_t label) {
    serial_->writeByte(label + '0');
    serial_->writeByte('\n');
}

void BinaryIntArraySerialStream::onReceive(vector<double> data) {
    for (int i = 0; i < data.size(); i++) {
        string s = to_string(data[i]);
        if (i > 0) serial_->writeByte('\t');
        for (int j = 0; j < s.size(); j++) serial_->writeByte(s[j]);
    }
    if (data.size() > 0) serial_->writeByte('\n');
}

void BinaryIntArraySerialStream::parseSerial(vector<unsigned char> &buffer) {
    auto start = std::find(buffer.begin(), buffer.end(), 0); // look for packet start
    if (start != buffer.end()) {
        buffer.erase(buffer.begin(), start); // advance to start of packet
        if (buffer.size() >= 3) { // 0, LSB(n), MSB(n)
            unsigned char checksum = 0;
            int LSB = buffer[1]; checksum += LSB;
            int MSB = buffer[2]; checksum += MSB;
            int n = ((MSB & 0x7F) << 7) | (LSB & 0x7F);
            if (buffer.size() >= 4 + 2 * n) {
                vector<double> vals;
                //std::cout << "Got array of " << n << " bytes: " << buffer.size();
                for (int j = 3; j < (3 + 2 * n);) {
                    LSB = buffer[j++]; checksum += LSB;
                    MSB = buffer[j++]; checksum += MSB;
                    int val = ((MSB & 0x7F) << 7) | (LSB & 0x7F);
                    //std::cout << val << " ";
                    vals.push_back(val);
                }
                //std::cout << "(" << (checksum | 0x80) << " <> " << buffer[3 + 2 * n] << ")" << std::endl;
                if ((checksum | 0x80) != buffer[3 + 2 * n]) {
                    ofLog(OF_LOG_WARNING) << "Invalid checksum, discarding serial packet.";
                } else if (n != getNumInputDimensions()) {
                    ofLog(OF_LOG_WARNING) << "Serial packet contains " << n <<
                        " dimensions. Expected " << getNumInputDimensions();
                } else {
                    GRT::MatrixDouble data(1, n);
                    for (int i = 0; i < getNumInputDimensions(); i++) {
                        int b = vals[i];
                        data[0][i] = (normalizer_ != nullptr) ? normalizer_(b) : b;
                    }
                    if (data_ready_callback_ != nullptr) {
                        data_ready_callback_(data);
                    }

                }

                buffer.erase(buffer.begin(), buffer.begin() + (4 + 2 * n));
            }
        }
    }
}<|endoftext|>


<commit_before>#include "stdafx.h"

#include "Performance.h"
#include <fvec.h>

namespace GameServer
{
    namespace Extension
    {
        using namespace ATF;

        constexpr double PiToAngle(float value)
        {
            return ((double)(value)*65535.0) / (2.0 * 3.1415926535);
        }

        void CPerformance::load()
        {
            auto& core = CATFCore::get_instance();
            core.set_hook(&ATF::Global::GetSqrt, &CPerformance::GetSqrt);
            core.set_hook(&ATF::Global::Get3DSqrt, &CPerformance::Get3DSqrt);
            core.set_hook((float(*)(float* Pos, float* Tar))&ATF::Global::GetYAngle, &CPerformance::GetYAngle);
            core.set_hook(&ATF::Global::GetDist, &CPerformance::GetDist);
        }

        void CPerformance::unload()
        {
            auto& core = CATFCore::get_instance();
            core.unset_hook(&ATF::Global::GetSqrt);
            core.unset_hook(&ATF::Global::Get3DSqrt);
            core.unset_hook((float(*)(float* Pos, float* Tar))&ATF::Global::GetYAngle);
            core.unset_hook(&ATF::Global::GetDist);
        }

        ModuleName_t CPerformance::get_name()
        {
            static const ModuleName_t name = "system_Performance";
            return name;
        }

        float WINAPIV CPerformance::GetSqrt(
            float* fPos,
            float* fTar,
            ATF::Global::Info::GetSqrt667_ptr next)
        {
            UNREFERENCED_PARAMETER(next);
            const F32vec4 vecTar = F32vec4(0.f, fTar[2], 0.f, fTar[0]);
            const F32vec4 vecPos = F32vec4(0.f, fPos[2], 0.f, fPos[0]);
            const F32vec4 diff = vecTar - vecPos;
            const F32vec4 diff_pow = diff * diff;

            return sqrt(F32vec4(add_horizontal(diff_pow)))[0];
        }
        float WINAPIV CPerformance::Get3DSqrt(
            float * fPos,
            float * fTar,
            ATF::Global::Info::Get3DSqrt435_ptr next)
        {
            UNREFERENCED_PARAMETER(next);
            const F32vec4 vecTar = F32vec4(0.f, fTar[2], fTar[1], fTar[0]);
            const F32vec4 vecPos = F32vec4(0.f, fPos[2], fPos[1], fPos[0]);
            const F32vec4 diff = vecTar - vecPos;
            const F32vec4 diff_pow = diff * diff;

            return sqrt(F32vec4(add_horizontal(diff_pow)))[0];
        }

        float WINAPIV CPerformance::GetYAngle(
            float * fPos,
            float * fTar,
            ATF::Global::Info::GetYAngle700_ptr next)
        {
            const F32vec4 vecTar = F32vec4(0.f, fTar[2], 0.f, fTar[0]);
            const F32vec4 vecPos = F32vec4(0.f, fPos[2], 0.f, fPos[0]);
            const F32vec4 diff = vecTar - vecPos;
            const F32vec4 diff_pow = diff * diff;

            const double Sqrt = sqrt(F32vec4(add_horizontal(diff_pow)))[0];
            if (Sqrt == 0.f)
                return 0.f;

            const double Acos = acos(diff[2] / Sqrt);

            if (diff[0] > 0.f)
                return (float)(PiToAngle(Acos) + 32768);
            else
                return (float)(PiToAngle(-Acos) + 32768);
        }

        float WINAPIV CPerformance::GetDist(
            const float* fPos,
            const float* fTar,
            ATF::Global::Info::GetDist498_ptr next)
        {
            UNREFERENCED_PARAMETER(next);
            const F32vec4 vecTar = F32vec4(0.f, fTar[2], fTar[1], fTar[0]);
            const F32vec4 vecPos = F32vec4(0.f, fPos[2], fPos[1], fPos[0]);
            const F32vec4 diff = vecTar - vecPos;
            const F32vec4 diff_pow = diff * diff;

            return sqrt(F32vec4(add_horizontal(diff_pow)))[0];
        }
    }
}<commit_msg>fixed warning<commit_after>#include "stdafx.h"

#include "Performance.h"
#include <fvec.h>

namespace GameServer
{
    namespace Extension
    {
        using namespace ATF;

        constexpr double PiToAngle(float value)
        {
            return ((double)(value)*65535.0) / (2.0 * 3.1415926535);
        }

        void CPerformance::load()
        {
            auto& core = CATFCore::get_instance();
            core.set_hook(&ATF::Global::GetSqrt, &CPerformance::GetSqrt);
            core.set_hook(&ATF::Global::Get3DSqrt, &CPerformance::Get3DSqrt);
            core.set_hook((float(*)(float* Pos, float* Tar))&ATF::Global::GetYAngle, &CPerformance::GetYAngle);
            core.set_hook(&ATF::Global::GetDist, &CPerformance::GetDist);
        }

        void CPerformance::unload()
        {
            auto& core = CATFCore::get_instance();
            core.unset_hook(&ATF::Global::GetSqrt);
            core.unset_hook(&ATF::Global::Get3DSqrt);
            core.unset_hook((float(*)(float* Pos, float* Tar))&ATF::Global::GetYAngle);
            core.unset_hook(&ATF::Global::GetDist);
        }

        ModuleName_t CPerformance::get_name()
        {
            static const ModuleName_t name = "system_Performance";
            return name;
        }

        float WINAPIV CPerformance::GetSqrt(
            float* fPos,
            float* fTar,
            ATF::Global::Info::GetSqrt667_ptr next)
        {
            UNREFERENCED_PARAMETER(next);
            const F32vec4 vecTar = F32vec4(0.f, fTar[2], 0.f, fTar[0]);
            const F32vec4 vecPos = F32vec4(0.f, fPos[2], 0.f, fPos[0]);
            const F32vec4 diff = vecTar - vecPos;
            const F32vec4 diff_pow = diff * diff;

            return sqrt(F32vec4(add_horizontal(diff_pow)))[0];
        }
        float WINAPIV CPerformance::Get3DSqrt(
            float * fPos,
            float * fTar,
            ATF::Global::Info::Get3DSqrt435_ptr next)
        {
            UNREFERENCED_PARAMETER(next);
            const F32vec4 vecTar = F32vec4(0.f, fTar[2], fTar[1], fTar[0]);
            const F32vec4 vecPos = F32vec4(0.f, fPos[2], fPos[1], fPos[0]);
            const F32vec4 diff = vecTar - vecPos;
            const F32vec4 diff_pow = diff * diff;

            return sqrt(F32vec4(add_horizontal(diff_pow)))[0];
        }

        float WINAPIV CPerformance::GetYAngle(
            float * fPos,
            float * fTar,
            ATF::Global::Info::GetYAngle700_ptr next)
        {
            UNREFERENCED_PARAMETER(next);
            const F32vec4 vecTar = F32vec4(0.f, fTar[2], 0.f, fTar[0]);
            const F32vec4 vecPos = F32vec4(0.f, fPos[2], 0.f, fPos[0]);
            const F32vec4 diff = vecTar - vecPos;
            const F32vec4 diff_pow = diff * diff;

            const double Sqrt = sqrt(F32vec4(add_horizontal(diff_pow)))[0];
            if (Sqrt == 0.f)
                return 0.f;

            const double Acos = acos(diff[2] / Sqrt);

            if (diff[0] > 0.f)
                return (float)(PiToAngle(Acos) + 32768);
            else
                return (float)(PiToAngle(-Acos) + 32768);
        }

        float WINAPIV CPerformance::GetDist(
            const float* fPos,
            const float* fTar,
            ATF::Global::Info::GetDist498_ptr next)
        {
            UNREFERENCED_PARAMETER(next);
            const F32vec4 vecTar = F32vec4(0.f, fTar[2], fTar[1], fTar[0]);
            const F32vec4 vecPos = F32vec4(0.f, fPos[2], fPos[1], fPos[0]);
            const F32vec4 diff = vecTar - vecPos;
            const F32vec4 diff_pow = diff * diff;

            return sqrt(F32vec4(add_horizontal(diff_pow)))[0];
        }
    }
}<|endoftext|>


<commit_before>// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - OpenGL Renderer"
// For conditions of distribution and use, see copyright notice in Config.hpp

#pragma once

#ifndef NAZARA_OPENGLRENDERER_EGLCONTEXTWIN32_HPP
#define NAZARA_OPENGLRENDERER_EGLCONTEXTWIN32_HPP

#include <Nazara/Prerequisites.hpp>
#include <Nazara/OpenGLRenderer/Wrapper/EGL/EGLContextBase.hpp>

namespace Nz::GL
{
	class EGLContextX11 final : public EGLContextBase
	{
		public:
			using EGLContextBase::EGLContextBase;
			EGLContextX11(const EGLContextX11&) = delete;
			EGLContextX11(EGLContextX11&&) = delete;
			~EGLContextX11() = default;

			bool Create(const ContextParams& params, WindowHandle window, const EGLContextBase* shareContext = nullptr) override;
			void Destroy() override;

			EGLContextX11& operator=(const EGLContextX11&) = delete;
			EGLContextX11& operator=(EGLContextX11&&) = delete;
	};
}

#include <Nazara/OpenGLRenderer/Wrapper/Linux/EGLContextX11.inl>

#endif
<commit_msg>Fix Linux compilation<commit_after>// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - OpenGL Renderer"
// For conditions of distribution and use, see copyright notice in Config.hpp

#pragma once

#ifndef NAZARA_OPENGLRENDERER_EGLCONTEXTWIN32_HPP
#define NAZARA_OPENGLRENDERER_EGLCONTEXTWIN32_HPP

#include <Nazara/Prerequisites.hpp>
#include <Nazara/OpenGLRenderer/Wrapper/EGL/EGLContextBase.hpp>

namespace Nz::GL
{
	class EGLContextX11 final : public EGLContextBase
	{
		public:
			using EGLContextBase::EGLContextBase;
			EGLContextX11(const EGLContextX11&) = delete;
			EGLContextX11(EGLContextX11&&) = delete;
			~EGLContextX11() = default;

			bool Create(const ContextParams& params, WindowHandle window, const EGLContextBase* shareContext = nullptr) override;

			EGLContextX11& operator=(const EGLContextX11&) = delete;
			EGLContextX11& operator=(EGLContextX11&&) = delete;
	};
}

#include <Nazara/OpenGLRenderer/Wrapper/Linux/EGLContextX11.inl>

#endif
<|endoftext|>


<commit_before>// Copyright 2020 Google LLC
//
// 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
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iree/compiler/Conversion/CodegenUtils/MatmulCodegenStrategy.h"
#include "mlir/IR/Builders.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassRegistry.h"

namespace mlir {
namespace iree_compiler {

static llvm::cl::opt<int> l1TileSize(
    "iree-codegen-linalg-to-llvm-matmul-l1-tile-size",
    llvm::cl::desc("Specify the size of L1 tile for matmul vector lowering"),
    llvm::cl::init(4));

static llvm::cl::opt<int> l2TileSize(
    "iree-codegen-linalg-to-llvm-matmul-l2-tile-size",
    llvm::cl::desc("Specify the size of L2 tile for matmul vector lowering"),
    llvm::cl::init(32));

static llvm::cl::opt<int> l3TileSize(
    "iree-codegen-linalg-to-llvm-matmul-l3-tile-size",
    llvm::cl::desc("Specify the size of L3 tile for matmul vector lowering"),
    llvm::cl::init(64));

static llvm::cl::opt<bool> unrollVectorTransfer(
    "iree-codegen-linalg-to-llvm-matmul-unroll-vector-transfer",
    llvm::cl::desc("If true vector transfers operation loop get unrolled."),
    llvm::cl::init(true));

static llvm::cl::opt<std::string> vectorOpLowering(
    "iree-codegen-linalg-to-llvm-matmul-vector-op-lowerig",
    llvm::cl::desc(
        "Select the vector operation for lowering linalg.matmul, options : "
        "{'outer_product', 'vector_contract', 'matrix_internsics'}"),
    llvm::cl::init("outer_product"));

namespace {
struct MatMulTileAndVectorizePass
    : PassWrapper<MatMulTileAndVectorizePass, FunctionPass> {
  void getDependentDialects(DialectRegistry &registry) const override {
    registry.insert<AffineDialect, scf::SCFDialect, vector::VectorDialect>();
  }

  void runOnFunction() override;
};
}  // namespace

void MatMulTileAndVectorizePass::runOnFunction() {
  FuncOp fn = getFunction();
  MatmulCodegenStrategy strategy;
  strategy
      .tile<linalg::MatmulOp>(linalg::LinalgTilingOptions().setTileSizes(
          {l3TileSize, l3TileSize, l3TileSize}))
      .tile<linalg::MatmulOp>(linalg::LinalgTilingOptions().setTileSizes(
          {l2TileSize, l2TileSize, l2TileSize}))
      .tile<linalg::MatmulOp>(linalg::LinalgTilingOptions().setTileSizes(
          {l1TileSize, l1TileSize, l1TileSize}))
      .vectorize<linalg::MatmulOp>()
      .setVectorTransferToSCFOptions(
          VectorTransferToSCFOptions().setUnroll(unrollVectorTransfer));
  if (vectorOpLowering == "outer_product") {
    strategy.setVectorTransformsOptions(
        vector::VectorTransformsOptions().setVectorTransformsOptions(
            vector::VectorContractLowering::OuterProduct));
  } else if (vectorOpLowering == "vector_contract") {
    strategy.setVectorTransformsOptions(
        vector::VectorTransformsOptions().setVectorTransformsOptions(
            vector::VectorContractLowering::OuterProduct));
  } else if (vectorOpLowering == "matrix_internsics") {
    strategy.setVectorTransformsOptions(
        vector::VectorTransformsOptions().setVectorTransformsOptions(
            vector::VectorContractLowering::OuterProduct));
  } else {
    signalPassFailure();
  }
  strategy.setDefaultCPULowering();
  strategy.transform(fn);
}

std::unique_ptr<FunctionPass> createMatMulTileAndVectorizePass() {
  return std::make_unique<MatMulTileAndVectorizePass>();
}

static PassRegistration<MatMulTileAndVectorizePass> pass(
    "iree-codegen-linalg-to-llvm-matmul-vectorization-pass",
    "Tile and vectorize linalg.matmul operation",
    [] { return std::make_unique<MatMulTileAndVectorizePass>(); });

}  // namespace iree_compiler
}  // namespace mlir
<commit_msg>Add an option to only apply L1 level tiling for matmulOp (#3049)<commit_after>// Copyright 2020 Google LLC
//
// 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
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iree/compiler/Conversion/CodegenUtils/MatmulCodegenStrategy.h"
#include "mlir/IR/Builders.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassRegistry.h"

namespace mlir {
namespace iree_compiler {

static llvm::cl::opt<bool> useL1TilesOnly(
    "iree-codegen-linalg-to-llvm-matmul-use-l1-tiles-only",
    llvm::cl::desc("If specified only L1 tiling applies, tiling for reduction "
                   "dim is set l1-tile-size, other dimension are tiled by "
                   "at most l1-reigster-max-tile-size"),
    llvm::cl::init(false));

static llvm::cl::opt<int> l1RegisterMaxTileSize(
    "iree-codegen-linalg-to-llvm-matmul-l1-register-max-tile-size",
    llvm::cl::desc(
        "Max tile size for M & N dimensions when use-l1-tiles-only is set"),
    llvm::cl::init(8));

static llvm::cl::opt<int> l1TileSize(
    "iree-codegen-linalg-to-llvm-matmul-l1-tile-size",
    llvm::cl::desc("Specify the size of L1 tile for matmul vector lowering"),
    llvm::cl::init(4));

static llvm::cl::opt<int> l2TileSize(
    "iree-codegen-linalg-to-llvm-matmul-l2-tile-size",
    llvm::cl::desc("Specify the size of L2 tile for matmul vector lowering"),
    llvm::cl::init(32));

static llvm::cl::opt<int> l3TileSize(
    "iree-codegen-linalg-to-llvm-matmul-l3-tile-size",
    llvm::cl::desc("Specify the size of L3 tile for matmul vector lowering"),
    llvm::cl::init(64));

static llvm::cl::opt<bool> unrollVectorTransfer(
    "iree-codegen-linalg-to-llvm-matmul-unroll-vector-transfer",
    llvm::cl::desc("If true vector transfers operation loop get unrolled."),
    llvm::cl::init(true));

static llvm::cl::opt<std::string> vectorOpLowering(
    "iree-codegen-linalg-to-llvm-matmul-vector-op-lowerig",
    llvm::cl::desc(
        "Select the vector operation for lowering linalg.matmul, options : "
        "{'outer_product', 'vector_contract', 'matrix_internsics'}"),
    llvm::cl::init("outer_product"));

namespace {
struct MatMulTileAndVectorizePass
    : PassWrapper<MatMulTileAndVectorizePass, FunctionPass> {
  void getDependentDialects(DialectRegistry &registry) const override {
    registry.insert<AffineDialect, scf::SCFDialect, vector::VectorDialect>();
  }

  void runOnFunction() override;
};
}  // namespace

void MatMulTileAndVectorizePass::runOnFunction() {
  FuncOp fn = getFunction();
  MatmulCodegenStrategy strategy;

  if (useL1TilesOnly) {
    auto matmulOps = llvm::to_vector<1>(fn.getOps<linalg::MatmulOp>());
    if (matmulOps.size() != 1) return;

    auto lhsShapeType =
        matmulOps[0].getInput(0).getType().dyn_cast_or_null<ShapedType>();
    auto rhsShapeType =
        matmulOps[0].getInput(1).getType().dyn_cast_or_null<ShapedType>();

    if (!lhsShapeType || !rhsShapeType) return;

    auto lhsShape = lhsShapeType.getShape();
    auto rhsShape = rhsShapeType.getShape();

    int M = lhsShape[0], N = rhsShape[1];
    auto tileDim = [](int dim, int maxSize) -> int {
      for (int i = maxSize; i > 0; --i) {
        if (dim % i == 0) return i;
      }
      return 1;
    };
    strategy.tile<linalg::MatmulOp>(linalg::LinalgTilingOptions().setTileSizes(
        {tileDim(M, l1RegisterMaxTileSize), tileDim(N, l1RegisterMaxTileSize),
         l1TileSize}));
  } else {
    strategy
        .tile<linalg::MatmulOp>(linalg::LinalgTilingOptions().setTileSizes(
            {l3TileSize, l3TileSize, l3TileSize}))
        .tile<linalg::MatmulOp>(linalg::LinalgTilingOptions().setTileSizes(
            {l2TileSize, l2TileSize, l2TileSize}))
        .tile<linalg::MatmulOp>(linalg::LinalgTilingOptions().setTileSizes(
            {l1TileSize, l1TileSize, l1TileSize}));
  }
  strategy.vectorize<linalg::MatmulOp>().setVectorTransferToSCFOptions(
      VectorTransferToSCFOptions().setUnroll(unrollVectorTransfer));
  if (vectorOpLowering == "outer_product") {
    strategy.setVectorTransformsOptions(
        vector::VectorTransformsOptions().setVectorTransformsOptions(
            vector::VectorContractLowering::OuterProduct));
  } else if (vectorOpLowering == "vector_contract") {
    strategy.setVectorTransformsOptions(
        vector::VectorTransformsOptions().setVectorTransformsOptions(
            vector::VectorContractLowering::OuterProduct));
  } else if (vectorOpLowering == "matrix_internsics") {
    strategy.setVectorTransformsOptions(
        vector::VectorTransformsOptions().setVectorTransformsOptions(
            vector::VectorContractLowering::OuterProduct));
  } else {
    signalPassFailure();
  }
  strategy.setDefaultCPULowering();
  strategy.transform(fn);
}

std::unique_ptr<FunctionPass> createMatMulTileAndVectorizePass() {
  return std::make_unique<MatMulTileAndVectorizePass>();
}

static PassRegistration<MatMulTileAndVectorizePass> pass(
    "iree-codegen-linalg-to-llvm-matmul-vectorization-pass",
    "Tile and vectorize linalg.matmul operation",
    [] { return std::make_unique<MatMulTileAndVectorizePass>(); });

}  // namespace iree_compiler
}  // namespace mlir
<|endoftext|>


<commit_before>// Make sure we don't report a leak nor hang.
// RUN: %clangxx_asan -O3 %s -o %t && %t
#include <malloc.h>
int *p = (int*)valloc(1 << 20);
int main() { }
<commit_msg>[ASan] fix assign_large_valloc_to_global.cc to use the correct header for valloc() on OSX.<commit_after>// Make sure we don't report a leak nor hang.
// RUN: %clangxx_asan -O3 %s -o %t && %t
#if defined(__APPLE__)
#include <stdlib.h>
#else
#include <malloc.h>
#endif
int *p = (int*)valloc(1 << 20);
int main() { }
<|endoftext|>