<commit_before>#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <math.h>
#include <vector>
#include <map>

#include "../../qbAPI/src/qbmove_communications.h"

#define STIFFNESS 0.4
#define HAND_CLOSURE 18000
#define QBMOVE_FILE "../../../qbadmin/conf_files/qbmove.conf"

std::map<int, std::vector<short int>> cube_pos;
std::map<int, short int> hand_pos;

double tick2rad(short int meas)
{
	return (double(meas)) * (2.0 * M_PI) / 32768.0;
}

short int compute_cube_motor_position(double eq, double stiff, short int& th1, short int& th2)
{
	th1 = (short int)((eq + stiff) * 32768.0 / (2* M_PI));
	th2 = (short int)((eq - stiff) * 32768.0 / (2* M_PI));
}

short int compute_hand_motor_position(double eq, short int& th1)
{
	th1 = (short int)(eq*HAND_CLOSURE);
}

void activate(comm_settings* cs, int id)
{
	commActivate(cs, id, 1);
	usleep(1000);
}

void deactivate(comm_settings* cs, int id)
{
	commActivate(cs, id, 0);
	usleep(1000);
}

int main(int argc, char **argv)
{
        // here set serial port and your device id(s)

	std::string serial_port  = "/dev/ttyUSB0";
	std::vector<int> cube_id = {15}; // = {1,2,3,4};
	std::vector<int> hand_id;       // = {5};

	FILE* file;
	file = fopen(QBMOVE_FILE, "w+");
	if (file == NULL)
	{
	    std::cout<<"ERROR: Cannot open qbmove.conf"<<std::endl;
	}
	fprintf(file,"serialport %s\n", serial_port.c_str());
	fclose(file);

	std::cout<<"Opened serial port: "<<serial_port<<std::endl;

	int us_sleep = 10000; // ~ 100 Hz
	short int inputs[2];
	short int measurements[3];

	comm_settings comm_settings_t;

	openRS485(&comm_settings_t, serial_port.c_str(), 2000000);
	usleep(10000);

	std::cout<<std::endl;
	std::cout<<"QB Device Handler"<<std::endl;

	if(cube_id.size()>0)
	{
	    std::cout<<" - Cubes ("<<cube_id.size()<<") = ";

	    for(auto id:cube_id)
	    {
		    cube_pos[id] = {0,0};
		    activate(&comm_settings_t,id);
		    std::cout<<id<<", ";
	    }
	}

	if(hand_id.size()>0)
	{
	    std::cout<<std::endl<<" - Hands ("<<hand_id.size()<<") = ";
	    for(auto id:hand_id)
	    {
		    hand_pos[id]=0;
		    activate(&comm_settings_t,id);
		    std::cout<<id<<", ";
	    }
	}

	std::cout<<std::endl<<std::endl;

	int count=0;

	while(1)
	{
		for(auto id:cube_id)
		{
			double cube_data=sin(count*0.01);
			count++;

		        compute_cube_motor_position(cube_data,STIFFNESS,cube_pos.at(id).at(0),cube_pos.at(id).at(1));

			inputs[0] = cube_pos[id].at(0);
			inputs[1] = cube_pos[id].at(1);

			commSetInputs(&comm_settings_t, id, inputs);
			usleep(100);
			commGetMeasurements(&comm_settings_t, id, measurements);
			usleep(100);
		}

		for(auto id:hand_id)
		{
		        double hand_data=sin(count*0.01);
			count++;

		        compute_hand_motor_position(hand_data,hand_pos[id]);

			inputs[0] = hand_pos[id];
			inputs[1] = 0;

			commSetInputs(&comm_settings_t, id, inputs);
			usleep(100);
			commGetMeasurements(&comm_settings_t, id, measurements);
			usleep(100);
		}

		usleep(us_sleep);

		if(count > 1000) break;
	}

	for(auto id:cube_id)
		deactivate(&comm_settings_t,id);
	for(auto id:hand_id)
		deactivate(&comm_settings_t,id);

	closeRS485(&comm_settings_t);
	usleep(1000);

	std::cout<<"Exiting..."<<std::endl;

	return 0;
}<commit_msg>qbdevice_handler example updated<commit_after>#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <math.h>
#include <vector>
#include <map>

#include "../../qbAPI/src/qbmove_communications.h"

#define STIFFNESS 0.4
#define HAND_CLOSURE 18000
#define QBMOVE_FILE "../../../qbadmin/conf_files/qbmove.conf"

std::map<int, std::vector<short int>> cube_pos;
std::map<int, short int> hand_pos;

double tick2rad(short int meas)
{
	return (double(meas)) * (2.0 * M_PI) / 32768.0;
}

short int compute_cube_motor_position(double eq, double stiff, short int& th1, short int& th2)
{
	th1 = (short int)((eq + stiff) * 32768.0 / (2* M_PI));
	th2 = (short int)((eq - stiff) * 32768.0 / (2* M_PI));
}

short int compute_hand_motor_position(double eq, short int& th1)
{
	th1 = (short int)(eq*HAND_CLOSURE);
}

void activate(comm_settings* cs, int id)
{
	commActivate(cs, id, 1);
	usleep(1000);
}

void deactivate(comm_settings* cs, int id)
{
	commActivate(cs, id, 0);
	usleep(1000);
}

int main(int argc, char **argv)
{
        // here set serial port and your device id(s)

	std::string serial_port  = "/dev/ttyUSB0";
	std::vector<int> cube_id = {15}; // = {1,2,3,4};
	std::vector<int> hand_id;       // = {5};

	FILE* file;
	file = fopen(QBMOVE_FILE, "w+");
	if (file == NULL)
	{
	    std::cout<<"ERROR: Cannot open qbmove.conf"<<std::endl;
	}
	fprintf(file,"serialport %s\n", serial_port.c_str());
	fclose(file);

	std::cout<<std::endl<<"Opened serial port: "<<serial_port<<std::endl;

	int us_sleep = 10000; // ~ 100 Hz
	short int inputs[2];
	short int measurements[3];

	comm_settings comm_settings_t;

	closeRS485(&comm_settings_t);
	usleep(1000);
	openRS485(&comm_settings_t, serial_port.c_str(), 2000000);
	usleep(10000);

	std::cout<<std::endl;
	std::cout<<"QB Device Handler"<<std::endl;

	if(cube_id.size()>0)
	{
	    std::cout<<" - Cubes ("<<cube_id.size()<<") = ";

	    for(auto id:cube_id)
	    {
		    cube_pos[id] = {0,0};
		    activate(&comm_settings_t,id);
		    std::cout<<id<<", ";
	    }
	}

	if(hand_id.size()>0)
	{
	    std::cout<<std::endl<<" - Hands ("<<hand_id.size()<<") = ";
	    for(auto id:hand_id)
	    {
		    hand_pos[id]=0;
		    activate(&comm_settings_t,id);
		    std::cout<<id<<", ";
	    }
	}

	std::cout<<std::endl<<std::endl;

	int count=0;

	while(1)
	{
		for(auto id:cube_id)
		{
			double cube_data=sin(count*0.01);
			count++;

		        compute_cube_motor_position(cube_data,STIFFNESS,cube_pos.at(id).at(0),cube_pos.at(id).at(1));

			inputs[0] = cube_pos[id].at(0);
			inputs[1] = cube_pos[id].at(1);

			commSetInputs(&comm_settings_t, id, inputs);
			usleep(100);
			commGetMeasurements(&comm_settings_t, id, measurements);
			usleep(100);
		}

		for(auto id:hand_id)
		{
		        double hand_data=sin(count*0.01);
			count++;

		        compute_hand_motor_position(hand_data,hand_pos[id]);

			inputs[0] = hand_pos[id];
			inputs[1] = 0;

			commSetInputs(&comm_settings_t, id, inputs);
			usleep(100);
			commGetMeasurements(&comm_settings_t, id, measurements);
			usleep(100);
		}

		usleep(us_sleep);

		if(count > 1000) break;
	}

	for(auto id:cube_id)
		deactivate(&comm_settings_t,id);
	for(auto id:hand_id)
		deactivate(&comm_settings_t,id);

	closeRS485(&comm_settings_t);
	usleep(1000);

	std::cout<<"Exiting..."<<std::endl<<std::endl;

	return 0;
}<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsoftkeystack.h"
#include "qsoftkeystack_p.h"
#include "qapplication.h"
#include "qmainwindow.h"

QSoftKeyStackPrivate::QSoftKeyStackPrivate()
{

}

QSoftKeyStackPrivate::~QSoftKeyStackPrivate()
{

}

void QSoftKeyStackPrivate::push(QSoftKeyAction *softKey)
{
    QSoftkeySet softKeySet;
    softKeySet.append(softKey);
    softKeyStack.push(softKeySet);
    setNativeSoftKeys();

}
void QSoftKeyStackPrivate::push(const QList<QSoftKeyAction*> &softkeys)
{
    QSoftkeySet softKeySet(softkeys);
    softKeyStack.push(softKeySet);
    setNativeSoftKeys();
}

void QSoftKeyStackPrivate::pop()
{
    softKeyStack.pop();
    setNativeSoftKeys();
}

const QSoftkeySet& QSoftKeyStackPrivate::top()
{
    return softKeyStack.top();
}

QSoftKeyStack::QSoftKeyStack(QWidget *parent)
    : QObject(*new QSoftKeyStackPrivate, parent)
{
    connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), SLOT(handleFocusChanged(QWidget*, QWidget*)));
}

QSoftKeyStack::~QSoftKeyStack()
{
}

void QSoftKeyStack::push(QSoftKeyAction *softKey)
{
    Q_D(QSoftKeyStack);
    d->push(softKey);
}

void QSoftKeyStack::push(const QList<QSoftKeyAction*> &softKeys)
{
    Q_D(QSoftKeyStack);
    d->push(softKeys);
}

void QSoftKeyStack::pop()
{
    Q_D(QSoftKeyStack);
    d->pop();
}

const QSoftkeySet& QSoftKeyStack::top()
{
    Q_D(QSoftKeyStack);
    return d->top();
}

void QSoftKeyStack::handleFocusChanged(QWidget *old, QWidget *now)
{
    if (!now)
        return;
    QWidget *w = qApp->activeWindow();
    QMainWindow *mainWindow = qobject_cast<QMainWindow*>(w);
    QSoftKeyStack* softKeyStack = mainWindow->softKeyStack();
    if (old)
        softKeyStack->pop();

    Qt::ContextMenuPolicy policy = now->contextMenuPolicy();
    if (policy != Qt::NoContextMenu && policy != Qt::PreventContextMenu ) {
        QList<QSoftKeyAction*> actionList;
        QSoftKeyAction* menu = new QSoftKeyAction(QSoftKeyAction::Menu, QString("Menu"), now);
        QSoftKeyAction* contextMenu = new QSoftKeyAction(QSoftKeyAction::ContextMenu, QString("ContextMenu"), now);
        actionList.append(menu);
        actionList.append(contextMenu);
        softKeyStack->push(actionList);
        }

/*    if (!now)
        return;
    bool nowInOurMainWindow = false;
    const QMainWindow *ourMainWindow = qobject_cast<const QMainWindow*>(parent());
    Q_ASSERT(ourMainWindow);

    // "ourMainWindow" in parent chain of "now"? Isn't there a helper in Qt for this?
    QWidget *nowParent = now;
    while (nowParent = nowParent->parentWidget()) {
        if (nowParent == ourMainWindow) {
            nowInOurMainWindow = true;
            break;
        }
    }

    if (!nowInOurMainWindow)
        return;

    QList<QAction*> actions = now->actions();
    // Do something with these actions.
*/
}

void QSoftKeyStack::handleSoftKeyPress(int command)
{
    Q_D(QSoftKeyStack);
    d->handleSoftKeyPress(command);
}
<commit_msg>experiment with QMainWindow<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsoftkeystack.h"
#include "qsoftkeystack_p.h"
#include "qapplication.h"
#include "qmainwindow.h"

QSoftKeyStackPrivate::QSoftKeyStackPrivate()
{

}

QSoftKeyStackPrivate::~QSoftKeyStackPrivate()
{

}

void QSoftKeyStackPrivate::push(QSoftKeyAction *softKey)
{
    QSoftkeySet softKeySet;
    softKeySet.append(softKey);
    softKeyStack.push(softKeySet);
    setNativeSoftKeys();

}
void QSoftKeyStackPrivate::push(const QList<QSoftKeyAction*> &softkeys)
{
    QSoftkeySet softKeySet(softkeys);
    softKeyStack.push(softKeySet);
    setNativeSoftKeys();
}

void QSoftKeyStackPrivate::pop()
{
    softKeyStack.pop();
    setNativeSoftKeys();
}

const QSoftkeySet& QSoftKeyStackPrivate::top()
{
    return softKeyStack.top();
}

QSoftKeyStack::QSoftKeyStack(QWidget *parent)
    : QObject(*new QSoftKeyStackPrivate, parent)
{
    connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), SLOT(handleFocusChanged(QWidget*, QWidget*)));
}

QSoftKeyStack::~QSoftKeyStack()
{
}

void QSoftKeyStack::push(QSoftKeyAction *softKey)
{
    Q_D(QSoftKeyStack);
    d->push(softKey);
}

void QSoftKeyStack::push(const QList<QSoftKeyAction*> &softKeys)
{
    Q_D(QSoftKeyStack);
    d->push(softKeys);
}

void QSoftKeyStack::pop()
{
    Q_D(QSoftKeyStack);
    d->pop();
}

const QSoftkeySet& QSoftKeyStack::top()
{
    Q_D(QSoftKeyStack);
    return d->top();
}

void QSoftKeyStack::handleFocusChanged(QWidget *old, QWidget *now)
{
    if (!now)
        return;
    QWidget *w = qApp->activeWindow();
    QMainWindow *mainWindow = qobject_cast<QMainWindow*>(w);
    if( !mainWindow)
        return;
    QSoftKeyStack* softKeyStack = mainWindow->softKeyStack();
    if (old)
        softKeyStack->pop();

    Qt::ContextMenuPolicy policy = now->contextMenuPolicy();
    if (policy != Qt::NoContextMenu && policy != Qt::PreventContextMenu ) {
        QList<QSoftKeyAction*> actionList;
        QSoftKeyAction* menu = new QSoftKeyAction(QSoftKeyAction::Menu, QString("Menu"), now);
        QSoftKeyAction* contextMenu = new QSoftKeyAction(QSoftKeyAction::ContextMenu, QString("ContextMenu"), now);
        actionList.append(menu);
        actionList.append(contextMenu);
        softKeyStack->push(actionList);
        }

/*    if (!now)
        return;
    bool nowInOurMainWindow = false;
    const QMainWindow *ourMainWindow = qobject_cast<const QMainWindow*>(parent());
    Q_ASSERT(ourMainWindow);

    // "ourMainWindow" in parent chain of "now"? Isn't there a helper in Qt for this?
    QWidget *nowParent = now;
    while (nowParent = nowParent->parentWidget()) {
        if (nowParent == ourMainWindow) {
            nowInOurMainWindow = true;
            break;
        }
    }

    if (!nowInOurMainWindow)
        return;

    QList<QAction*> actions = now->actions();
    // Do something with these actions.
*/
}

void QSoftKeyStack::handleSoftKeyPress(int command)
{
    Q_D(QSoftKeyStack);
    d->handleSoftKeyPress(command);
}
<|endoftext|>


<commit_before>#include <CL/cl.hpp>
#include <iostream>
#include "Image.h"
#include "Strategy.h"
#include "LabelData.h"
#include <chrono>
#include <sys/stat.h>

template <class T> void fail(T message, cl_int err = 0) {
  std::cerr << message;
  if (err) {
    std::cerr << " ERR #: " << err;
  }
  std::cerr << std::endl;
  exit(-1);
}

cl::Context load_context() {
  cl_int err;

  // Create the context. Iterates through the platforms and picks the first
  // one with a GPU, then creates a context from that.
  cl::Context context = cl::Context(CL_DEVICE_TYPE_GPU, NULL, NULL, NULL, &err);
  if (err) {
    // Fall back to CPU
    context = cl::Context(CL_DEVICE_TYPE_CPU, NULL, NULL, NULL, &err);
  }
  if (err) {
    fail("Couldn't find a platform/device.", err);
  }
  return context;
}

std::vector<cl::Device> load_devices(cl::Context *context) {
  std::vector<cl::Device> devices = context->getInfo<CL_CONTEXT_DEVICES>();
  if (devices.size() == 0) {
    fail("Found no devices");
  }
  return devices;
}

bool equivalent_result(LabelData *a, LabelData *b){ return true; } //TODO

bool valid_result(LabelData *l) { return true; } //TODO

bool rgb_above_100(unsigned char r, unsigned char g, unsigned char b,
                   unsigned char) {
  if (r > 100 && g > 100 && b > 100) {
    return true;
  }
  return false;
}

RGBA max_if_nonzero(LabelData::label_type in){
  RGBA out;
  if (in) {
    out.r = out.g = out.b = out.a = 255;
  } else {
    out.r = out.g = out.b = out.a = 0;
  }
  return out;
}

int main(int argc, const char *argv[]) {
  cl::Context context = load_context();
  std::vector<cl::Device> devices = load_devices(&context);

  if (argc != 2) {
    std::cerr << "Usage: " << argv[0] << " filename" << std::endl;
    return 0;
  }
  iml::Image rgba_image(argv[1]);
  if (!rgba_image) {
    fail("Image not loaded correctly, aborting.");
  }

  {
    int err = mkdir("out", 0777);
    if (err && err != EEXIST) {
      fail("Couldn't creat output directory 'out'.");
    }
  }

  LabelData input(&rgba_image, rgb_above_100);
  LabelData correct(input);
  LabelData output(input);

  std::vector<Strategy*> strats;
  strats.push_back(new IdStrategy);
  // TODO: Put a known good one in front
  {
    auto &strat = strats[0];
    strat->prepare_gpu(&context, &devices, &input);
    strat->execute(&correct);
    strat->clean_gpu();
  }

  for (auto *strat : strats) {
    strat->prepare_gpu(&context, &devices, &input);
    auto start = std::chrono::high_resolution_clock::now();
    strat->execute(&output);
    auto end = std::chrono::high_resolution_clock::now();
    strat->clean_gpu();
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
                  .count();
    std::cout << argv[1] << " -- " << strat->name() << ": " << ms << " ms."
              << std::endl;
    if (!valid_result(&output)) {
      std::cerr << "Strategy returned an invalid labeling" << std::endl;
    }
    if (!equivalent_result(&input, &output)) {
      std::cerr << "Strategy returned an unexpected labeling." << std::endl;
    }

    //Write to file
    iml::Image out(output.width, output.height);
    output.copy_to_image(out.data, max_if_nonzero);
    std::string outname = "out/" + strat->name() + ".png";
    iml::writepng(outname, &out);
  }
}
<commit_msg>Correct error checked<commit_after>#include <CL/cl.hpp>
#include <iostream>
#include "Image.h"
#include "Strategy.h"
#include "LabelData.h"
#include <chrono>
#include <sys/stat.h>

template <class T> void fail(T message, cl_int err = 0) {
  std::cerr << message;
  if (err) {
    std::cerr << " ERR #: " << err;
  }
  std::cerr << std::endl;
  exit(-1);
}

cl::Context load_context() {
  cl_int err;

  // Create the context. Iterates through the platforms and picks the first
  // one with a GPU, then creates a context from that.
  cl::Context context = cl::Context(CL_DEVICE_TYPE_GPU, NULL, NULL, NULL, &err);
  if (err) {
    // Fall back to CPU
    context = cl::Context(CL_DEVICE_TYPE_CPU, NULL, NULL, NULL, &err);
  }
  if (err) {
    fail("Couldn't find a platform/device.", err);
  }
  return context;
}

std::vector<cl::Device> load_devices(cl::Context *context) {
  std::vector<cl::Device> devices = context->getInfo<CL_CONTEXT_DEVICES>();
  if (devices.size() == 0) {
    fail("Found no devices");
  }
  return devices;
}

bool equivalent_result(LabelData *a, LabelData *b){ return true; } //TODO

bool valid_result(LabelData *l) { return true; } //TODO

bool rgb_above_100(unsigned char r, unsigned char g, unsigned char b,
                   unsigned char) {
  if (r > 100 && g > 100 && b > 100) {
    return true;
  }
  return false;
}

RGBA max_if_nonzero(LabelData::label_type in){
  RGBA out;
  if (in) {
    out.r = out.g = out.b = out.a = 255;
  } else {
    out.r = out.g = out.b = out.a = 0;
  }
  return out;
}

int main(int argc, const char *argv[]) {
  cl::Context context = load_context();
  std::vector<cl::Device> devices = load_devices(&context);

  if (argc != 2) {
    std::cerr << "Usage: " << argv[0] << " filename" << std::endl;
    return 0;
  }
  iml::Image rgba_image(argv[1]);
  if (!rgba_image) {
    fail("Image not loaded correctly, aborting.");
  }

  {
    int err = mkdir("out", 0777);
    if (err && errno != EEXIST) {
      fail("Couldn't creat output directory 'out'.");
    }
  }

  LabelData input(&rgba_image, rgb_above_100);
  LabelData correct(input);
  LabelData output(input);

  std::vector<Strategy*> strats;
  strats.push_back(new IdStrategy);
  // TODO: Put a known good one in front
  {
    auto &strat = strats[0];
    strat->prepare_gpu(&context, &devices, &input);
    strat->execute(&correct);
    strat->clean_gpu();
  }

  for (auto *strat : strats) {
    strat->prepare_gpu(&context, &devices, &input);
    auto start = std::chrono::high_resolution_clock::now();
    strat->execute(&output);
    auto end = std::chrono::high_resolution_clock::now();
    strat->clean_gpu();
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
                  .count();
    std::cout << argv[1] << " -- " << strat->name() << ": " << ms << " ms."
              << std::endl;
    if (!valid_result(&output)) {
      std::cerr << "Strategy returned an invalid labeling" << std::endl;
    }
    if (!equivalent_result(&input, &output)) {
      std::cerr << "Strategy returned an unexpected labeling." << std::endl;
    }

    //Write to file
    iml::Image out(output.width, output.height);
    output.copy_to_image(out.data, max_if_nonzero);
    std::string outname = "out/" + strat->name() + ".png";
    iml::writepng(outname, &out);
  }
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

#include "cling/Interpreter/DynamicLibraryManager.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/InvocationOptions.h"
#include "cling/Utils/Paths.h"
#include "cling/Utils/Platform.h"
#include "cling/Utils/Output.h"

#include "llvm/BinaryFormat/Magic.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/Path.h"

#include <system_error>
#include <sys/stat.h>

namespace cling {
  DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts)
    : m_Opts(Opts) {
    const llvm::SmallVector<const char*, 10> kSysLibraryEnv = {
      "LD_LIBRARY_PATH",
  #if __APPLE__
      "DYLD_LIBRARY_PATH",
      "DYLD_FALLBACK_LIBRARY_PATH",
      /*
      "DYLD_VERSIONED_LIBRARY_PATH",
      "DYLD_FRAMEWORK_PATH",
      "DYLD_FALLBACK_FRAMEWORK_PATH",
      "DYLD_VERSIONED_FRAMEWORK_PATH",
      */
  #elif defined(_WIN32)
      "PATH",
  #endif
    };

    // Behaviour is to not add paths that don't exist...In an interpreted env
    // does this make sense? Path could pop into existance at any time.
    for (const char* Var : kSysLibraryEnv) {
      if (Opts.Verbose())
        cling::log() << "Adding library paths from '" << Var << "':\n";
      if (const char* Env = ::getenv(Var)) {
        llvm::SmallVector<llvm::StringRef, 10> CurPaths;
        SplitPaths(Env, CurPaths, utils::kPruneNonExistant, platform::kEnvDelim,
                   Opts.Verbose());
        for (const auto& Path : CurPaths)
          m_SearchPaths.push_back({Path.str(), /*IsUser*/true});
      }
    }

    llvm::SmallVector<std::string, 64> SysPaths;
    platform::GetSystemLibraryPaths(SysPaths);

    for (const std::string& P : SysPaths)
      m_SearchPaths.push_back({P, /*IsUser*/false});

    // This will currently be the last path searched, should it be pushed to
    // the front of the line, or even to the front of user paths?
    m_SearchPaths.push_back({".", /*IsUser*/true});
  }

  std::string
  DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const {
    llvm::SmallVector<SearchPathInfo, 128> Paths;
    for (const std::string &P : m_Opts.LibSearchPath)
      Paths.push_back({P, /*IsUser*/true});

    Paths.append(m_SearchPaths.begin(), m_SearchPaths.end());

    llvm::SmallString<512> ThisPath;
    for (const SearchPathInfo& Info : Paths) {
      ThisPath = Info.Path;
      llvm::sys::path::append(ThisPath, libStem);
      bool exists;
      if (isSharedLibrary(ThisPath.str(), &exists))
        return ThisPath.str();
      if (exists)
        return "";
    }
    return "";
  }

  std::string
  DynamicLibraryManager::lookupLibMaybeAddExt(llvm::StringRef libStem) const {
    using namespace llvm::sys;

    std::string foundDyLib = lookupLibInPaths(libStem);

    if (foundDyLib.empty()) {
      // Add DyLib extension:
      llvm::SmallString<512> filenameWithExt(libStem);
#if defined(LLVM_ON_UNIX)
#ifdef __APPLE__
      llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;
#endif
      static const char* DyLibExt = ".so";
#elif defined(_WIN32)
      static const char* DyLibExt = ".dll";
#else
# error "Unsupported platform."
#endif
      filenameWithExt += DyLibExt;
      foundDyLib = lookupLibInPaths(filenameWithExt);
#ifdef __APPLE__
      if (foundDyLib.empty()) {
        filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());
        filenameWithExt += ".dylib";
        foundDyLib = lookupLibInPaths(filenameWithExt);
      }
#endif
    }

    if (foundDyLib.empty())
      return std::string();

    // get canonical path name and check if already loaded
    const std::string Path = platform::NormalizePath(foundDyLib);
    if (Path.empty()) {
      cling::errs() << "cling::DynamicLibraryManager::lookupLibMaybeAddExt(): "
        "error getting real (canonical) path of library " << foundDyLib << '\n';
      return foundDyLib;
    }
    return Path;
  }

  std::string DynamicLibraryManager::normalizePath(llvm::StringRef path) {
    // Make the path canonical if the file exists.
    const std::string Path = path.str();
    struct stat buffer;
    if (::stat(Path.c_str(), &buffer) != 0)
      return std::string();

    const std::string NPath = platform::NormalizePath(Path);
    if (NPath.empty())
      cling::log() << "Could not normalize: '" << Path << "'";
    return NPath;
  }

  std::string
  DynamicLibraryManager::lookupLibrary(llvm::StringRef libStem) const {
    // If it is an absolute path, don't try iterate over the paths.
    if (llvm::sys::path::is_absolute(libStem)) {
      if (isSharedLibrary(libStem))
        return normalizePath(libStem);
      else
        return std::string();
    }

    std::string foundName = lookupLibMaybeAddExt(libStem);
    if (foundName.empty() && !libStem.startswith("lib")) {
      // try with "lib" prefix:
      foundName = lookupLibMaybeAddExt("lib" + libStem.str());
    }

    if (!foundName.empty() && isSharedLibrary(foundName))
      return platform::NormalizePath(foundName);

    return std::string();
  }

  DynamicLibraryManager::LoadLibResult
  DynamicLibraryManager::loadLibrary(const std::string& libStem,
                                     bool permanent, bool resolved) {
    std::string lResolved;
    const std::string& canonicalLoadedLib = resolved ? libStem : lResolved;
    if (!resolved) {
      lResolved = lookupLibrary(libStem);
      if (lResolved.empty())
        return kLoadLibNotFound;
    }

    if (m_LoadedLibraries.find(canonicalLoadedLib) != m_LoadedLibraries.end())
      return kLoadLibAlreadyLoaded;

    // TODO: !permanent case

    std::string errMsg;
    DyLibHandle dyLibHandle = platform::DLOpen(canonicalLoadedLib, &errMsg);
    if (!dyLibHandle) {
      // We emit callback to LibraryLoadingFailed when we get error with error message.
      if (InterpreterCallbacks* C = getCallbacks()) {
        if (C->LibraryLoadingFailed(errMsg, libStem, permanent, resolved))
          return kLoadLibSuccess;
      }

      cling::errs() << "cling::DynamicLibraryManager::loadLibrary(): " << errMsg
                    << '\n';
      return kLoadLibLoadError;
    }
    else if (InterpreterCallbacks* C = getCallbacks())
      C->LibraryLoaded(dyLibHandle, canonicalLoadedLib);

    std::pair<DyLibs::iterator, bool> insRes
      = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,
                                                            canonicalLoadedLib));
    if (!insRes.second)
      return kLoadLibAlreadyLoaded;
    m_LoadedLibraries.insert(canonicalLoadedLib);
    return kLoadLibSuccess;
  }

  void DynamicLibraryManager::unloadLibrary(llvm::StringRef libStem) {
    std::string canonicalLoadedLib = lookupLibrary(libStem);
    if (!isLibraryLoaded(canonicalLoadedLib))
      return;

    DyLibHandle dyLibHandle = 0;
    for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end();
         I != E; ++I) {
      if (I->second == canonicalLoadedLib) {
        dyLibHandle = I->first;
        break;
      }
    }

    // TODO: !permanent case

    std::string errMsg;
    platform::DLClose(dyLibHandle, &errMsg);
    if (!errMsg.empty()) {
      cling::errs() << "cling::DynamicLibraryManager::unloadLibrary(): "
                    << errMsg << '\n';
    }

    if (InterpreterCallbacks* C = getCallbacks())
      C->LibraryUnloaded(dyLibHandle, canonicalLoadedLib);

    m_DyLibs.erase(dyLibHandle);
    m_LoadedLibraries.erase(canonicalLoadedLib);
  }

  bool DynamicLibraryManager::isLibraryLoaded(llvm::StringRef fullPath) const {
    std::string canonPath = normalizePath(fullPath);
    if (m_LoadedLibraries.find(canonPath) != m_LoadedLibraries.end())
      return true;
    return false;
  }

  void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {
    llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));
  }

  bool DynamicLibraryManager::isSharedLibrary(llvm::StringRef libFullPath,
                                              bool* exists /*=0*/) {
    using namespace llvm;
    file_magic Magic;
    const std::error_code Error = identify_magic(libFullPath, Magic);
    if (exists)
      *exists = !Error;

    return !Error &&
#ifdef __APPLE__
      (Magic == file_magic::macho_fixed_virtual_memory_shared_lib
       || Magic == file_magic::macho_dynamically_linked_shared_lib
       || Magic == file_magic::macho_dynamically_linked_shared_lib_stub
       || Magic == file_magic::macho_universal_binary)
#elif defined(LLVM_ON_UNIX)
#ifdef __CYGWIN__
      (Magic == file_magic::pecoff_executable)
#else
      (Magic == file_magic::elf_shared_object)
#endif
#elif defined(_WIN32)
      (Magic == file_magic::pecoff_executable
       || platform::IsDLL(libFullPath.str()))
#else
# error "Unsupported platform."
#endif
      ;
  }

} // end namespace cling
<commit_msg>[cling] Skip non-regular files to find dylibs:<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

#include "cling/Interpreter/DynamicLibraryManager.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/InvocationOptions.h"
#include "cling/Utils/Paths.h"
#include "cling/Utils/Platform.h"
#include "cling/Utils/Output.h"

#include "llvm/BinaryFormat/Magic.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/Path.h"

#include <system_error>
#include <sys/stat.h>

namespace cling {
  DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts)
    : m_Opts(Opts) {
    const llvm::SmallVector<const char*, 10> kSysLibraryEnv = {
      "LD_LIBRARY_PATH",
  #if __APPLE__
      "DYLD_LIBRARY_PATH",
      "DYLD_FALLBACK_LIBRARY_PATH",
      /*
      "DYLD_VERSIONED_LIBRARY_PATH",
      "DYLD_FRAMEWORK_PATH",
      "DYLD_FALLBACK_FRAMEWORK_PATH",
      "DYLD_VERSIONED_FRAMEWORK_PATH",
      */
  #elif defined(_WIN32)
      "PATH",
  #endif
    };

    // Behaviour is to not add paths that don't exist...In an interpreted env
    // does this make sense? Path could pop into existance at any time.
    for (const char* Var : kSysLibraryEnv) {
      if (Opts.Verbose())
        cling::log() << "Adding library paths from '" << Var << "':\n";
      if (const char* Env = ::getenv(Var)) {
        llvm::SmallVector<llvm::StringRef, 10> CurPaths;
        SplitPaths(Env, CurPaths, utils::kPruneNonExistant, platform::kEnvDelim,
                   Opts.Verbose());
        for (const auto& Path : CurPaths)
          m_SearchPaths.push_back({Path.str(), /*IsUser*/true});
      }
    }

    llvm::SmallVector<std::string, 64> SysPaths;
    platform::GetSystemLibraryPaths(SysPaths);

    for (const std::string& P : SysPaths)
      m_SearchPaths.push_back({P, /*IsUser*/false});

    // This will currently be the last path searched, should it be pushed to
    // the front of the line, or even to the front of user paths?
    m_SearchPaths.push_back({".", /*IsUser*/true});
  }

  std::string
  DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const {
    llvm::SmallVector<SearchPathInfo, 128> Paths;
    for (const std::string &P : m_Opts.LibSearchPath)
      Paths.push_back({P, /*IsUser*/true});

    Paths.append(m_SearchPaths.begin(), m_SearchPaths.end());

    llvm::SmallString<512> ThisPath;
    for (const SearchPathInfo& Info : Paths) {
      ThisPath = Info.Path;
      llvm::sys::path::append(ThisPath, libStem);
      bool exists;
      if (isSharedLibrary(ThisPath.str(), &exists))
        return ThisPath.str();
      if (exists)
        return "";
    }
    return "";
  }

  std::string
  DynamicLibraryManager::lookupLibMaybeAddExt(llvm::StringRef libStem) const {
    using namespace llvm::sys;

    std::string foundDyLib = lookupLibInPaths(libStem);

    if (foundDyLib.empty()) {
      // Add DyLib extension:
      llvm::SmallString<512> filenameWithExt(libStem);
#if defined(LLVM_ON_UNIX)
#ifdef __APPLE__
      llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;
#endif
      static const char* DyLibExt = ".so";
#elif defined(_WIN32)
      static const char* DyLibExt = ".dll";
#else
# error "Unsupported platform."
#endif
      filenameWithExt += DyLibExt;
      foundDyLib = lookupLibInPaths(filenameWithExt);
#ifdef __APPLE__
      if (foundDyLib.empty()) {
        filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());
        filenameWithExt += ".dylib";
        foundDyLib = lookupLibInPaths(filenameWithExt);
      }
#endif
    }

    if (foundDyLib.empty())
      return std::string();

    // get canonical path name and check if already loaded
    const std::string Path = platform::NormalizePath(foundDyLib);
    if (Path.empty()) {
      cling::errs() << "cling::DynamicLibraryManager::lookupLibMaybeAddExt(): "
        "error getting real (canonical) path of library " << foundDyLib << '\n';
      return foundDyLib;
    }
    return Path;
  }

  std::string DynamicLibraryManager::normalizePath(llvm::StringRef path) {
    // Make the path canonical if the file exists.
    const std::string Path = path.str();
    struct stat buffer;
    if (::stat(Path.c_str(), &buffer) != 0)
      return std::string();

    const std::string NPath = platform::NormalizePath(Path);
    if (NPath.empty())
      cling::log() << "Could not normalize: '" << Path << "'";
    return NPath;
  }

  std::string
  DynamicLibraryManager::lookupLibrary(llvm::StringRef libStem) const {
    // If it is an absolute path, don't try iterate over the paths.
    if (llvm::sys::path::is_absolute(libStem)) {
      if (isSharedLibrary(libStem))
        return normalizePath(libStem);
      else
        return std::string();
    }

    std::string foundName = lookupLibMaybeAddExt(libStem);
    if (foundName.empty() && !libStem.startswith("lib")) {
      // try with "lib" prefix:
      foundName = lookupLibMaybeAddExt("lib" + libStem.str());
    }

    if (!foundName.empty() && isSharedLibrary(foundName))
      return platform::NormalizePath(foundName);

    return std::string();
  }

  DynamicLibraryManager::LoadLibResult
  DynamicLibraryManager::loadLibrary(const std::string& libStem,
                                     bool permanent, bool resolved) {
    std::string lResolved;
    const std::string& canonicalLoadedLib = resolved ? libStem : lResolved;
    if (!resolved) {
      lResolved = lookupLibrary(libStem);
      if (lResolved.empty())
        return kLoadLibNotFound;
    }

    if (m_LoadedLibraries.find(canonicalLoadedLib) != m_LoadedLibraries.end())
      return kLoadLibAlreadyLoaded;

    // TODO: !permanent case

    std::string errMsg;
    DyLibHandle dyLibHandle = platform::DLOpen(canonicalLoadedLib, &errMsg);
    if (!dyLibHandle) {
      // We emit callback to LibraryLoadingFailed when we get error with error message.
      if (InterpreterCallbacks* C = getCallbacks()) {
        if (C->LibraryLoadingFailed(errMsg, libStem, permanent, resolved))
          return kLoadLibSuccess;
      }

      cling::errs() << "cling::DynamicLibraryManager::loadLibrary(): " << errMsg
                    << '\n';
      return kLoadLibLoadError;
    }
    else if (InterpreterCallbacks* C = getCallbacks())
      C->LibraryLoaded(dyLibHandle, canonicalLoadedLib);

    std::pair<DyLibs::iterator, bool> insRes
      = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,
                                                            canonicalLoadedLib));
    if (!insRes.second)
      return kLoadLibAlreadyLoaded;
    m_LoadedLibraries.insert(canonicalLoadedLib);
    return kLoadLibSuccess;
  }

  void DynamicLibraryManager::unloadLibrary(llvm::StringRef libStem) {
    std::string canonicalLoadedLib = lookupLibrary(libStem);
    if (!isLibraryLoaded(canonicalLoadedLib))
      return;

    DyLibHandle dyLibHandle = 0;
    for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end();
         I != E; ++I) {
      if (I->second == canonicalLoadedLib) {
        dyLibHandle = I->first;
        break;
      }
    }

    // TODO: !permanent case

    std::string errMsg;
    platform::DLClose(dyLibHandle, &errMsg);
    if (!errMsg.empty()) {
      cling::errs() << "cling::DynamicLibraryManager::unloadLibrary(): "
                    << errMsg << '\n';
    }

    if (InterpreterCallbacks* C = getCallbacks())
      C->LibraryUnloaded(dyLibHandle, canonicalLoadedLib);

    m_DyLibs.erase(dyLibHandle);
    m_LoadedLibraries.erase(canonicalLoadedLib);
  }

  bool DynamicLibraryManager::isLibraryLoaded(llvm::StringRef fullPath) const {
    std::string canonPath = normalizePath(fullPath);
    if (m_LoadedLibraries.find(canonPath) != m_LoadedLibraries.end())
      return true;
    return false;
  }

  void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {
    llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));
  }

  bool DynamicLibraryManager::isSharedLibrary(llvm::StringRef libFullPath,
                                              bool* exists /*=0*/) {
    using namespace llvm;
    auto filetype = sys::fs::get_file_type(libFullPath, /*Follow*/ true);
    if (filetype != sys::fs::file_type::regular_file) {
      if (exists) {
        // get_file_type returns status_error also in case of file_not_found.
        *exists = filetype != sys::fs::file_type::status_error;
      }
      return false;
    }

    file_magic Magic;
    const std::error_code Error = identify_magic(libFullPath, Magic);
    if (exists)
      *exists = !Error;

    return !Error &&
#ifdef __APPLE__
      (Magic == file_magic::macho_fixed_virtual_memory_shared_lib
       || Magic == file_magic::macho_dynamically_linked_shared_lib
       || Magic == file_magic::macho_dynamically_linked_shared_lib_stub
       || Magic == file_magic::macho_universal_binary)
#elif defined(LLVM_ON_UNIX)
#ifdef __CYGWIN__
      (Magic == file_magic::pecoff_executable)
#else
      (Magic == file_magic::elf_shared_object)
#endif
#elif defined(_WIN32)
      (Magic == file_magic::pecoff_executable
       || platform::IsDLL(libFullPath.str()))
#else
# error "Unsupported platform."
#endif
      ;
  }

} // end namespace cling
<|endoftext|>


<commit_before>#include <cassert>
#include <var>
#include <map>
#include <fstream>

using namespace std;

var getString()
{
    cout << "In getString()" << endl;
    var str;
    str = "An example string with spaces.";
    return str;
}

void useString(var s)
{
    cout << "Using: " << s << endl;
}

int main(int argc, char** argv)
{
    // Copy the command line
    var arg(argc, argv);

    // Check that one and two level indexing works
    cout << "Arg: " << arg << endl;
    cout << "Arg[0]: " << arg[0] << endl;
    cout << "Arg[0][0]: " << arg[0][0] << endl;

    // Check that operator == works
    if (arg[0][0] == '.')
        cout << "It's a dot" << endl;
    else
        cout << "It's not a dot" << endl;

    // Check that index() finds (or not) an element
    if (arg.index("-f").defined())
        cout << "There's a -f" << endl;
    else
        cout << "There's no -f" << endl;

    // Basic numerical tests
    var s, w, x, y, z, dummy;
    w = 'w';
    x = 2;
    y = 3.14;
    z = y.cos();
    s = "Hello!";

    cout << "Var size is " << sizeof(var) << endl;
    cout << w << endl;
    cout << x << endl;
    cout << y << endl;
    cout << z << endl;
    cout << s << endl;
    cout << s.at(0) << endl;
    cout << s[0] << endl;

    // Numerical overloads
    x += 2;
    y += 3.14f;
    x.push(2);
    y -= 1;
    cout << x << endl;
    cout << y << endl;

    // Reference the same object & reference counting
    var a = s;
    cout << "a is: " << a << endl;
    a = "New string";

    // String comparison
    var n = "New string";
    if (a == n)
        cout << "equal" << endl;
    else
        cout << "not equal" << endl;

    // Pass a string into a function, it's still valid outside
    cout << "Calling getString()" << endl;
    var b = getString();
    cout << "b is: " << b << endl;
    useString(b);
    cout << "b is: " << b << endl;

    // Basic string split
    var sp;
    sp = b.split("n");
    cout << "sp is: " << sp << endl;

    // Basic string insert
    a.insert("ddd", 1);
    cout << "a is: " << a << endl;

    // Shifting of command line
    arg.insert("insert", 1);
    cout << "arg is: " << arg << endl;
    arg.remove(0);
    cout << "arg is: " << arg << endl;
    var as = arg.shift();
    cout << "arg is: " << arg << " shifted: " << as << endl;

    // Join the command line args
    cout << "Joining: " << arg << endl;
    cout << "Joined: " << arg.join("-") << endl;

    // Sort the command line args
    cout << arg.sort() << endl;

    // Check that we can act as a std::map key (just needs operator<)
    map<var, int> map;
    map["One"] = 1;
    map["Two"] = 2;
    map["Three"] = 3;
    cout << map.count("Zero") << endl;
    cout << map.count("One") << endl;

    // Read a small file
    var f;
    var t;
    ifstream is("tests.txt", ifstream::in);
    if (is.fail())
        cout << "Open failed" << endl;
    while (f.getline(is).defined())
    {
        cout << f << endl;
        t.push(f.copy());
    }
    cout << t << endl;

    // Shallow copy
    var c1 = arg;
    c1.push("extra");
    cout << c1 << endl;
    cout << arg << endl;
    var c2 = arg.copy();
    c2.pop();
    cout << c2 << endl;
    cout << arg << endl;

    // Modify an array using operator[]
    int xxa[] = {1,2,3,4,5};
    var xa(5, xxa);
    cout << "xa is " << xa << endl;
    xa[1] = xa[0];
    xa[2] += xa[1];
    xa[3] = 7;
    xa[4] += 7;
    cout << "xa is " << xa << endl;

    // set() on an array broadcasts over the array
    xa.set(2);
    cout << "xa is " << xa << endl;

    // Array of vars just by assigning indeces
    var arr;
    arr[1] = "Hi!";
    cout << arr << endl;

    // Array indexed by var
    var vmap;
    vmap["one"] = 1;
    vmap["two"] = 2;
    vmap["three"] = 3;
    cout << "vmap[0] is " << vmap[0] << endl;
    cout << "vmap[1] is " << vmap[1] << endl;
    cout << "vmap[\"three\"] is " << vmap["three"] << endl;
    cout << "vmap is " << vmap << endl;

    // Init from variable argument list
    var ai(5, 5,4,3,2,1);
    cout << "ai is: " << ai << endl;

    // Read a text file via a dynamic library
    var txt;
    txt.read("tests.txt", "txt");
    cout << "Loaded: " << txt << endl;

    return 0;
}
<commit_msg>Tensor tests<commit_after>#include <cassert>
#include <var>
#include <map>
#include <fstream>

using namespace std;

var getString()
{
    cout << "In getString()" << endl;
    var str;
    str = "An example string with spaces.";
    return str;
}

void useString(var s)
{
    cout << "Using: " << s << endl;
}

int main(int argc, char** argv)
{
    // Copy the command line
    var arg(argc, argv);

    // Check that one and two level indexing works
    cout << "Arg: " << arg << endl;
    cout << "Arg[0]: " << arg[0] << endl;
    cout << "Arg[0][0]: " << arg[0][0] << endl;

    // Check that operator == works
    if (arg[0][0] == '.')
        cout << "It's a dot" << endl;
    else
        cout << "It's not a dot" << endl;

    // Check that index() finds (or not) an element
    if (arg.index("-f").defined())
        cout << "There's a -f" << endl;
    else
        cout << "There's no -f" << endl;

    // Basic numerical tests
    var s, w, x, y, z, dummy;
    w = 'w';
    x = 2;
    y = 3.14;
    z = y.cos();
    s = "Hello!";

    cout << "Var size is " << sizeof(var) << endl;
    cout << w << endl;
    cout << x << endl;
    cout << y << endl;
    cout << z << endl;
    cout << s << endl;
    cout << s.at(0) << endl;
    cout << s[0] << endl;

    // Numerical overloads
    x += 2;
    y += 3.14f;
    x.push(2);
    y -= 1;
    cout << x << endl;
    cout << y << endl;

    // Reference the same object & reference counting
    var a = s;
    cout << "a is: " << a << endl;
    a = "New string";

    // String comparison
    var n = "New string";
    if (a == n)
        cout << "equal" << endl;
    else
        cout << "not equal" << endl;

    // Pass a string into a function, it's still valid outside
    cout << "Calling getString()" << endl;
    var b = getString();
    cout << "b is: " << b << endl;
    useString(b);
    cout << "b is: " << b << endl;

    // Basic string split
    var sp;
    sp = b.split("n");
    cout << "sp is: " << sp << endl;

    // Basic string insert
    a.insert("ddd", 1);
    cout << "a is: " << a << endl;

    // Shifting of command line
    arg.insert("insert", 1);
    cout << "arg is: " << arg << endl;
    arg.remove(0);
    cout << "arg is: " << arg << endl;
    var as = arg.shift();
    cout << "arg is: " << arg << " shifted: " << as << endl;

    // Join the command line args
    cout << "Joining: " << arg << endl;
    cout << "Joined: " << arg.join("-") << endl;

    // Sort the command line args
    cout << arg.sort() << endl;

    // Check that we can act as a std::map key (just needs operator<)
    map<var, int> map;
    map["One"] = 1;
    map["Two"] = 2;
    map["Three"] = 3;
    cout << map.count("Zero") << endl;
    cout << map.count("One") << endl;

    // Read a small file
    var f;
    var t;
    ifstream is("tests.txt", ifstream::in);
    if (is.fail())
        cout << "Open failed" << endl;
    while (f.getline(is).defined())
    {
        cout << f << endl;
        t.push(f.copy());
    }
    cout << t << endl;

    // Shallow copy
    var c1 = arg;
    c1.push("extra");
    cout << c1 << endl;
    cout << arg << endl;
    var c2 = arg.copy();
    c2.pop();
    cout << c2 << endl;
    cout << arg << endl;

    // Modify an array using operator[]
    int xxa[] = {1,2,3,4,5};
    var xa(5, xxa);
    cout << "xa is " << xa << endl;
    xa[1] = xa[0];
    xa[2] += xa[1];
    xa[3] = 7;
    xa[4] += 7;
    cout << "xa is " << xa << endl;

    // set() on an array broadcasts over the array
    xa.set(2);
    cout << "xa is " << xa << endl;

    // Array of vars just by assigning indeces
    var arr;
    arr[1] = "Hi!";
    cout << arr << endl;

    // Array indexed by var
    var vmap;
    vmap["one"] = 1;
    vmap["two"] = 2;
    vmap["three"] = 3;
    cout << "vmap[0] is " << vmap[0] << endl;
    cout << "vmap[1] is " << vmap[1] << endl;
    cout << "vmap[\"three\"] is " << vmap["three"] << endl;
    cout << "vmap is " << vmap << endl;

    // Init from variable argument list
    var ai(5, 5,4,3,2,1);
    cout << "ai is: " << ai << endl;

    // Read a text file via a dynamic library
    var txt;
    txt.read("tests.txt", "txt");
    cout << "Loaded: " << txt << endl;

    // Tensors
    var ts = 0.0f;
    ts.resize(16);
    for (int i=0; i<16; i++)
        ts[i] = (float)i;
    var ten = ts.view(2, 4, 4);
    cout << ts << endl;
    cout << ten << endl;

    return 0;
}
<|endoftext|>


<commit_before>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#ifndef GUARD_MIOPEN_TENSOR_OPPS_HPP_
#define GUARD_MIOPEN_TENSOR_OPPS_HPP_

#include <miopen/common.hpp>
#include <miopen/datatype.hpp>
#include <miopen/handle.hpp>
#include <miopen/miopen.h>
#include <miopen/object.hpp>
#include <vector>

namespace miopen {

void ScaleTensor(
    Handle& handle, const TensorDescriptor& yDesc, Data_t y, const void* p_alpha, int offset = 0);

void SetTensor(
    Handle& handle, const TensorDescriptor& yDesc, Data_t y, const void* p_alpha, int offset = 0);

void OpTensor(Handle& handle,
              miopenTensorOp_t tensorOp,
              const void* alpha0,
              const TensorDescriptor& aTensorDesc,
              ConstData_t ATensor,
              const void* alpha1,
              const TensorDescriptor& bTensorDesc,
              ConstData_t BTensor,
              const void* beta,
              const TensorDescriptor& cTensorDesc,
              Data_t CTensor,
              size_t Aoffset = 0,
              size_t Boffset = 0,
              size_t Coffset = 0);

void CopyTensor(Handle& handle,
                const TensorDescriptor& srcDesc,
                ConstData_t src,
                const TensorDescriptor& dstDesc,
                Data_t dst,
                int srcOffset = 0,
                int dstOffset = 0);

} // namespace miopen
#endif // GUARD_MIOPEN_TENSOR_OPPS_HPP_
<commit_msg>tidy up<commit_after>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#ifndef GUARD_MIOPEN_TENSOR_OPPS_HPP_
#define GUARD_MIOPEN_TENSOR_OPPS_HPP_

#include <miopen/common.hpp>
#include <miopen/datatype.hpp>
#include <miopen/handle.hpp>
#include <miopen/miopen.h>
#include <miopen/object.hpp>
#include <vector>

namespace miopen {

void ScaleTensor(
    Handle& handle, const TensorDescriptor& yDesc, Data_t y, const void* alpha, int offset = 0);

void SetTensor(
    Handle& handle, const TensorDescriptor& yDesc, Data_t y, const void* alpha, int offset = 0);

void OpTensor(Handle& handle,
              miopenTensorOp_t tensorOp,
              const void* alpha0,
              const TensorDescriptor& aTensorDesc,
              ConstData_t ATensor,
              const void* alpha1,
              const TensorDescriptor& bTensorDesc,
              ConstData_t BTensor,
              const void* beta,
              const TensorDescriptor& cTensorDesc,
              Data_t CTensor,
              size_t Aoffset = 0,
              size_t Boffset = 0,
              size_t Coffset = 0);

void CopyTensor(Handle& handle,
                const TensorDescriptor& srcDesc,
                ConstData_t src,
                const TensorDescriptor& dstDesc,
                Data_t dst,
                int srcOffset = 0,
                int dstOffset = 0);

} // namespace miopen
#endif // GUARD_MIOPEN_TENSOR_OPPS_HPP_
<|endoftext|>


<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2017 Intel Corporation. All Rights Reserved.

#include <iostream>
#include <iomanip>
#include <map>
#include <utility>
#include <vector>
#include <librealsense2/rs.hpp>
#include <algorithm>
#include "../example.hpp"
#include "api_how_to.h"
#include "helper.h"

// Forward declaration of the create_sensor_actions which returns a collection of functions
//  and their description that operate on a device or sensor
using sensor_action = std::pair<std::function<void(rs2::device, rs2::sensor)>, std::string>;
std::vector<sensor_action> create_sensor_actions();

int main(int argc, char * argv[]) try
{
    //In this example we will go through a flow of selecting a device, then selecting one of its sensors,
    // and finally run some operations on that sensor

    //We will use the "how_to" class to make the code clear, expressive and encapsulate common actions inside a function

    std::vector<sensor_action> sensor_actions = create_sensor_actions();

    bool choose_a_device = true;
    while (choose_a_device)
    {
        print_separator();
        //First thing, let's choose a device:
        rs2::device dev = how_to::get_a_realsense_device();

        //Print the device's information
        how_to::print_device_information(dev);

        bool choose_a_sensor = true;
        while (choose_a_sensor)
        {
            print_separator();
            //Next, choose one of the device's sensors
            rs2::sensor sensor = how_to::get_a_sensor_from_a_device(dev);

            bool control_sensor = true;
            while (control_sensor)
            {
                print_separator();
                std::cout << "What would you like to do with the sensor?\n" << std::endl;
                int i = 0;
                for (auto&& action : sensor_actions)
                {
                    std::cout << i++ << " : " << action.second << std::endl;
                }
                uint32_t selected_action_index = helper::get_user_selection("Select an action: ");
                if (selected_action_index >= sensor_actions.size())
                {
                    throw std::out_of_range("Selected action index is out of range");
                }

                auto selected_action = sensor_actions[selected_action_index].first;

                bool repeat = true;
                while (repeat)
                {
                    print_separator();
                    selected_action(dev, sensor);
                    repeat = prompt_yes_no(sensor_actions[selected_action_index].second + " again?");
                }
                control_sensor = prompt_yes_no("Choose another action for this sensor?");
            }

            choose_a_sensor = prompt_yes_no("Choose another sensor?");
        }

        choose_a_device = prompt_yes_no("Choose another device?");
    }

    return EXIT_SUCCESS;
}
catch (const rs2::error & e)
{
    std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n    " << e.what() << std::endl;
    return EXIT_FAILURE;
}
catch (const std::exception & e)
{
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
}

void control_sensor_options(rs2::device device, rs2::sensor sensor)
{
    // The rs2::sensor allows you to control its properties such as Exposure, Brightness etc.
    rs2_option sensor_option = how_to::get_sensor_option(sensor);
    how_to::change_sensor_option(sensor, sensor_option);
}
void display_live_stream(rs2::device device, rs2::sensor sensor)
{
    // The rs2::sensor allows you to control its streams
    // We will first choose a single stream profile from the available profiles of the sensor
    rs2::stream_profile selected_profile = how_to::choose_a_streaming_profile(sensor);

    // Next, we will display the stream in a window
    how_to::start_streaming_a_profile(sensor, selected_profile);
}
void show_stream_intrinsics(rs2::device device, rs2::sensor sensor)
{
    rs2::stream_profile selected_profile = how_to::choose_a_streaming_profile(sensor);
    // The rs2::sensor allows you to control its properties such as Exposure, Brightness etc.
    how_to::get_field_of_view(selected_profile);
}
void show_extrinsics_between_streams(rs2::device device, rs2::sensor sensor)
{
    std::cout << "Please choose a sensor and then a stream that will be used as the origin of extrinsic transformation:\n" << std::endl;
    rs2::sensor from_sensor = how_to::get_a_sensor_from_a_device(device);
    rs2::stream_profile from = how_to::choose_a_streaming_profile(from_sensor);

    std::cout << "Please choose a sensor and then a stream that will be used as the target of extrinsic transformation::\n" << std::endl;
    rs2::sensor to_sensor = how_to::get_a_sensor_from_a_device(device);
    rs2::stream_profile to = how_to::choose_a_streaming_profile(to_sensor);
    // The rs2::sensor allows you to control its properties such as Exposure, Brightness etc.
    how_to::get_extrinsics(from, to);
}
std::vector<sensor_action> create_sensor_actions()
{
    //This function creates several functions ("sensor_action") that takes a device and a sensor,
    // and perform some specific action
    return std::vector<sensor_action> {
            std::make_pair(&control_sensor_options, "Control sensor's options"),
            std::make_pair(&display_live_stream, "Control sensor's streams"),
            std::make_pair(&show_stream_intrinsics, "Show stream intrinsics"),
            std::make_pair(&show_extrinsics_between_streams, "Display extrinsics")
    };
}
<commit_msg>Updated comments of sensor actions fruncions<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2017 Intel Corporation. All Rights Reserved.

#include <iostream>
#include <iomanip>
#include <map>
#include <utility>
#include <vector>
#include <librealsense2/rs.hpp>
#include <algorithm>
#include "../example.hpp"
#include "api_how_to.h"
#include "helper.h"

// Forward declaration of the create_sensor_actions which returns a collection of functions
//  and their description that operate on a device or sensor
using sensor_action = std::pair<std::function<void(rs2::device, rs2::sensor)>, std::string>;
std::vector<sensor_action> create_sensor_actions();

int main(int argc, char * argv[]) try
{
    //In this example we will go through a flow of selecting a device, then selecting one of its sensors,
    // and finally run some operations on that sensor

    //We will use the "how_to" class to make the code clear, expressive and encapsulate common actions inside a function

    std::vector<sensor_action> sensor_actions = create_sensor_actions();

    bool choose_a_device = true;
    while (choose_a_device)
    {
        print_separator();
        //First thing, let's choose a device:
        rs2::device dev = how_to::get_a_realsense_device();

        //Print the device's information
        how_to::print_device_information(dev);

        bool choose_a_sensor = true;
        while (choose_a_sensor)
        {
            print_separator();
            //Next, choose one of the device's sensors
            rs2::sensor sensor = how_to::get_a_sensor_from_a_device(dev);

            bool control_sensor = true;
            while (control_sensor)
            {
                print_separator();
                std::cout << "What would you like to do with the sensor?\n" << std::endl;
                int i = 0;
                for (auto&& action : sensor_actions)
                {
                    std::cout << i++ << " : " << action.second << std::endl;
                }
                uint32_t selected_action_index = helper::get_user_selection("Select an action: ");
                if (selected_action_index >= sensor_actions.size())
                {
                    throw std::out_of_range("Selected action index is out of range");
                }

                auto selected_action = sensor_actions[selected_action_index].first;

                bool repeat = true;
                while (repeat)
                {
                    print_separator();
                    selected_action(dev, sensor);
                    repeat = prompt_yes_no(sensor_actions[selected_action_index].second + " again?");
                }
                control_sensor = prompt_yes_no("Choose another action for this sensor?");
            }

            choose_a_sensor = prompt_yes_no("Choose another sensor?");
        }

        choose_a_device = prompt_yes_no("Choose another device?");
    }

    return EXIT_SUCCESS;
}
catch (const rs2::error & e)
{
    std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n    " << e.what() << std::endl;
    return EXIT_FAILURE;
}
catch (const std::exception & e)
{
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
}

void control_sensor_options(rs2::device device, rs2::sensor sensor)
{
    // The rs2::sensor allows you to control its properties such as Exposure, Brightness etc.
    rs2_option sensor_option = how_to::get_sensor_option(sensor);
    how_to::change_sensor_option(sensor, sensor_option);
}
void display_live_stream(rs2::device device, rs2::sensor sensor)
{
    // The rs2::sensor allows you to control its streams
    // We will first choose a single stream profile from the available profiles of the sensor
    rs2::stream_profile selected_profile = how_to::choose_a_streaming_profile(sensor);

    // Next, we will display the stream in a window
    how_to::start_streaming_a_profile(sensor, selected_profile);
}
void show_stream_intrinsics(rs2::device device, rs2::sensor sensor)
{
    // Each stream has its own intrinsic information, first choose a stream, then display its intrinsics
    rs2::stream_profile selected_profile = how_to::choose_a_streaming_profile(sensor);
    how_to::get_field_of_view(selected_profile);
}
void show_extrinsics_between_streams(rs2::device device, rs2::sensor sensor)
{
    // A rs2::device can have its sensors and streams calibrated and provide the extrinsics between 2 streams.
    std::cout << "Please choose a sensor and then a stream that will be used as the origin of extrinsic transformation:\n" << std::endl;
    rs2::sensor from_sensor = how_to::get_a_sensor_from_a_device(device);
    rs2::stream_profile from = how_to::choose_a_streaming_profile(from_sensor);

    std::cout << "Please choose a sensor and then a stream that will be used as the target of extrinsic transformation::\n" << std::endl;
    rs2::sensor to_sensor = how_to::get_a_sensor_from_a_device(device);
    rs2::stream_profile to = how_to::choose_a_streaming_profile(to_sensor);

    how_to::get_extrinsics(from, to);
}
std::vector<sensor_action> create_sensor_actions()
{
    //This function creates several functions ("sensor_action") that takes a device and a sensor,
    // and perform some specific action
    return std::vector<sensor_action> {
            std::make_pair(&control_sensor_options, "Control sensor's options"),
            std::make_pair(&display_live_stream, "Control sensor's streams"),
            std::make_pair(&show_stream_intrinsics, "Show stream intrinsics"),
            std::make_pair(&show_extrinsics_between_streams, "Display extrinsics")
    };
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2017-2020 the rbfx project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/ResourceEvents.h>
#include <IconFontCppHeaders/IconsFontAwesome5.h>
#include <Toolbox/SystemUI/Widgets.h>
#include "BaseResourceTab.h"

namespace Urho3D
{

BaseResourceTab::BaseResourceTab(Context* context)
    : Tab(context)
{
    onTabContextMenu_.Subscribe(this, &BaseResourceTab::OnRenderContextMenu);

    SubscribeToEvent(E_RESOURCERENAMED, [&](StringHash, VariantMap& args) {
        using namespace ResourceRenamed;

        auto nameFrom = args[P_FROM].GetString();
        if (resourceName_ == nameFrom)
            SetResourceName(args[P_TO].GetString());
    });
    SubscribeToEvent(this, E_DOCUMENTMODIFIEDREQUEST, [this](StringHash, VariantMap&)
    {
        if (!modified_)
        {
            undo_->Add<UndoModifiedState>(this, true);
            modified_ = true;
        }
    });
    SubscribeToEvent(E_DOCUMENTMODIFIED, [this](StringHash, VariantMap& args) { modified_ = args[DocumentModified::P_MODIFIED].GetBool(); });
}

bool BaseResourceTab::LoadResource(const ea::string& resourcePath)
{
    if (!Tab::LoadResource(resourcePath))
        return false;

    if (resourcePath.empty())
        return false;

    if (IsModified() && pendingLoadResource_.empty())
    {
        pendingLoadResource_ = resourcePath;
        return false;
    }

    SetResourceName(resourcePath);
    modified_ = false;

    return true;
}

bool BaseResourceTab::SaveResource()
{
    if (!Tab::SaveResource())
        return false;

    if (resourceName_.empty())
        return false;

    // Mark tab as not modified.
    if (modified_)
    {
        undo_->Add<UndoModifiedState>(this, false);
        modified_ = false;
    }

    return true;
}

void BaseResourceTab::OnSaveUISettings(ImGuiTextBuffer* buf)
{
    Tab::OnSaveUISettings(buf);
    if (!resourceName_.empty())
        buf->appendf("Path=%s\n", resourceName_.c_str());
}

const char* BaseResourceTab::OnLoadUISettings(const char* name, const char* line)
{
    line = Tab::OnLoadUISettings(name, line);
    char path[1024];
    if (int scanned = sscanf(line, "Path=%s\n", path))
    {
        LoadResource(path);
        line += scanned;
    }
    return line;
}

void BaseResourceTab::SetResourceName(const ea::string& resourceName)
{
    resourceName_ = resourceName;
    if (!isUtility_)
        SetTitle(GetFileName(resourceName_));
}

void BaseResourceTab::Close()
{
    auto cache = GetSubsystem<ResourceCache>();
    cache->ReleaseResource(GetResourceType(), GetResourceName(), true);
    modified_ = false;
    resourceName_.clear();
}

bool BaseResourceTab::RenderWindowContent()
{
    if (wasOpen_ && !ui::IsPopupOpen("Save?"))
    {
        if ((!open_ && IsModified()) || !pendingLoadResource_.empty())
        {
            ui::OpenPopup("Save?");
            open_ = true;
        }
    }

    bool noCancel = true;
    if (ui::BeginPopupModal("Save?", &noCancel, ImGuiWindowFlags_NoDocking|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_Popup))
    {
        // Warn when closing a tab that was modified.
        if (!pendingLoadResource_.empty())
        {
            ui::Text(
                "Resource '%s' was modified. Would you like to save it before opening '%s'?",
                GetFileNameAndExtension(resourceName_).c_str(),
                GetFileNameAndExtension(pendingLoadResource_).c_str());

            bool save = ui::Button(ICON_FA_SAVE " Save & Open");
            ui::SameLine();
            bool open = save || ui::Button(ICON_FA_EXCLAMATION_TRIANGLE " Close & Open");

            if (save)
                SaveResource();

            if (open)
            {
                LoadResource(pendingLoadResource_);
                pendingLoadResource_.clear();
                ui::CloseCurrentPopup();
            }
        }
        else
        {
            ui::Text("Resource '%s' was modified. Would you like to save it before closing?",
                GetFileNameAndExtension(resourceName_).c_str());

            bool save = ui::Button(ICON_FA_SAVE " Save & Close");
            ui::SameLine();
            bool close = ui::Button(ICON_FA_EXCLAMATION_TRIANGLE " Close without saving");
            ui::SetHelpTooltip("Can not be undone!", KEY_UNKNOWN);

            if (save)
                SaveResource();

            if (save || close)
            {
                open_ = false;
                ui::CloseCurrentPopup();
            }
        }
        ui::SameLine();
        if (ui::Button(ICON_FA_TIMES " Cancel"))
        {
            pendingLoadResource_.clear();
            ui::CloseCurrentPopup();
        }
        ui::EndPopup();
    }
    else if (!pendingLoadResource_.empty())
    {
        // Click outside of popup.
        pendingLoadResource_.clear();
    }

    if (wasOpen_ && !open_)
        Close();

    return true;
}

void BaseResourceTab::OnRenderContextMenu()
{
    if (ui::MenuItem("Save"))
        SaveResource();

    ui::Separator();

    if (ui::MenuItem("Close"))
        open_ = false;
}

}
<commit_msg>Support scene filenames with spaces<commit_after>//
// Copyright (c) 2017-2020 the rbfx project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/ResourceEvents.h>
#include <IconFontCppHeaders/IconsFontAwesome5.h>
#include <Toolbox/SystemUI/Widgets.h>
#include "BaseResourceTab.h"

namespace Urho3D
{

BaseResourceTab::BaseResourceTab(Context* context)
    : Tab(context)
{
    onTabContextMenu_.Subscribe(this, &BaseResourceTab::OnRenderContextMenu);

    SubscribeToEvent(E_RESOURCERENAMED, [&](StringHash, VariantMap& args) {
        using namespace ResourceRenamed;

        auto nameFrom = args[P_FROM].GetString();
        if (resourceName_ == nameFrom)
            SetResourceName(args[P_TO].GetString());
    });
    SubscribeToEvent(this, E_DOCUMENTMODIFIEDREQUEST, [this](StringHash, VariantMap&)
    {
        if (!modified_)
        {
            undo_->Add<UndoModifiedState>(this, true);
            modified_ = true;
        }
    });
    SubscribeToEvent(E_DOCUMENTMODIFIED, [this](StringHash, VariantMap& args) { modified_ = args[DocumentModified::P_MODIFIED].GetBool(); });
}

bool BaseResourceTab::LoadResource(const ea::string& resourcePath)
{
    if (!Tab::LoadResource(resourcePath))
        return false;

    if (resourcePath.empty())
        return false;

    if (IsModified() && pendingLoadResource_.empty())
    {
        pendingLoadResource_ = resourcePath;
        return false;
    }

    SetResourceName(resourcePath);
    modified_ = false;

    return true;
}

bool BaseResourceTab::SaveResource()
{
    if (!Tab::SaveResource())
        return false;

    if (resourceName_.empty())
        return false;

    // Mark tab as not modified.
    if (modified_)
    {
        undo_->Add<UndoModifiedState>(this, false);
        modified_ = false;
    }

    return true;
}

void BaseResourceTab::OnSaveUISettings(ImGuiTextBuffer* buf)
{
    Tab::OnSaveUISettings(buf);
    if (!resourceName_.empty())
        buf->appendf("Path=%s\n", resourceName_.c_str());
}

const char* BaseResourceTab::OnLoadUISettings(const char* name, const char* line)
{
    line = Tab::OnLoadUISettings(name, line);
    char path[1024];
    if (int scanned = sscanf(line, "Path=%[^\n]\n", path))
    {
        LoadResource(path);
        line += scanned;
    }
    return line;
}

void BaseResourceTab::SetResourceName(const ea::string& resourceName)
{
    resourceName_ = resourceName;
    if (!isUtility_)
        SetTitle(GetFileName(resourceName_));
}

void BaseResourceTab::Close()
{
    auto cache = GetSubsystem<ResourceCache>();
    cache->ReleaseResource(GetResourceType(), GetResourceName(), true);
    modified_ = false;
    resourceName_.clear();
}

bool BaseResourceTab::RenderWindowContent()
{
    if (wasOpen_ && !ui::IsPopupOpen("Save?"))
    {
        if ((!open_ && IsModified()) || !pendingLoadResource_.empty())
        {
            ui::OpenPopup("Save?");
            open_ = true;
        }
    }

    bool noCancel = true;
    if (ui::BeginPopupModal("Save?", &noCancel, ImGuiWindowFlags_NoDocking|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_Popup))
    {
        // Warn when closing a tab that was modified.
        if (!pendingLoadResource_.empty())
        {
            ui::Text(
                "Resource '%s' was modified. Would you like to save it before opening '%s'?",
                GetFileNameAndExtension(resourceName_).c_str(),
                GetFileNameAndExtension(pendingLoadResource_).c_str());

            bool save = ui::Button(ICON_FA_SAVE " Save & Open");
            ui::SameLine();
            bool open = save || ui::Button(ICON_FA_EXCLAMATION_TRIANGLE " Close & Open");

            if (save)
                SaveResource();

            if (open)
            {
                LoadResource(pendingLoadResource_);
                pendingLoadResource_.clear();
                ui::CloseCurrentPopup();
            }
        }
        else
        {
            ui::Text("Resource '%s' was modified. Would you like to save it before closing?",
                GetFileNameAndExtension(resourceName_).c_str());

            bool save = ui::Button(ICON_FA_SAVE " Save & Close");
            ui::SameLine();
            bool close = ui::Button(ICON_FA_EXCLAMATION_TRIANGLE " Close without saving");
            ui::SetHelpTooltip("Can not be undone!", KEY_UNKNOWN);

            if (save)
                SaveResource();

            if (save || close)
            {
                open_ = false;
                ui::CloseCurrentPopup();
            }
        }
        ui::SameLine();
        if (ui::Button(ICON_FA_TIMES " Cancel"))
        {
            pendingLoadResource_.clear();
            ui::CloseCurrentPopup();
        }
        ui::EndPopup();
    }
    else if (!pendingLoadResource_.empty())
    {
        // Click outside of popup.
        pendingLoadResource_.clear();
    }

    if (wasOpen_ && !open_)
        Close();

    return true;
}

void BaseResourceTab::OnRenderContextMenu()
{
    if (ui::MenuItem("Save"))
        SaveResource();

    ui::Separator();

    if (ui::MenuItem("Close"))
        open_ = false;
}

}
<|endoftext|>


<commit_before>//
// Copyright (c) 2018 Rokas Kupstys
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include <IconFontCppHeaders/IconsFontAwesome5.h>
#include <Urho3D/Urho3DAll.h>
#include "ContentUtilities.h"

namespace Urho3D
{

const Vector<String> archiveExtensions_{".rar", ".zip", ".tar", ".gz", ".xz", ".7z", ".pak"};
const Vector<String> wordExtensions_{".doc", ".docx", ".odt"};
const Vector<String> codeExtensions_{".c", ".cpp", ".h", ".hpp", ".hxx", ".py", ".py3", ".js", ".cs"};
const Vector<String> imagesExtensions_{".png", ".jpg", ".jpeg", ".gif", ".ttf", ".dds", ".psd"};
const Vector<String> textExtensions_{".xml", ".json", ".txt", ".yml", ".scene", ".material", ".ui", ".uistyle", ".node", ".particle"};
const Vector<String> audioExtensions_{".waw", ".ogg", ".mp3"};

FileType GetFileType(const String& fileName)
{
    auto extension = GetExtension(fileName).ToLower();
    if (archiveExtensions_.Contains(extension))
        return FTYPE_ARCHIVE;
    if (wordExtensions_.Contains(extension))
        return FTYPE_WORD;
    if (codeExtensions_.Contains(extension))
        return FTYPE_CODE;
    if (imagesExtensions_.Contains(extension))
        return FTYPE_IMAGE;
    if (textExtensions_.Contains(extension))
        return FTYPE_TEXT;
    if (audioExtensions_.Contains(extension))
        return FTYPE_AUDIO;
    if (extension == "pdf")
        return FTYPE_PDF;
    return FTYPE_FILE;
}

String GetFileIcon(const String& fileName)
{
    switch (GetFileType(fileName))
    {
    case FTYPE_ARCHIVE:
        return ICON_FA_FILE_ARCHIVE;
    case FTYPE_WORD:
        return ICON_FA_FILE_WORD;
    case FTYPE_CODE:
        return ICON_FA_FILE_CODE;
    case FTYPE_IMAGE:
        return ICON_FA_FILE_IMAGE;
    case FTYPE_PDF:
        return ICON_FA_FILE_PDF;
    case FTYPE_VIDEO:
        return ICON_FA_FILE_VIDEO;
    case FTYPE_POWERPOINT:
        return ICON_FA_FILE_POWERPOINT;
    case FTYPE_TEXT:
        return ICON_FA_FILE_ALT;
    case FTYPE_FILM:
        return ICON_FA_FILE_VIDEO;
    case FTYPE_AUDIO:
        return ICON_FA_FILE_AUDIO;
    case FTYPE_EXCEL:
        return ICON_FA_FILE_EXCEL;
    default:
        return ICON_FA_FILE;
    }
}

ContentType GetContentType(const String& resourcePath)
{
    auto extension = GetExtension(resourcePath).ToLower();
    if (extension == ".xml")
    {
        auto systemUI = (SystemUI*)ui::GetIO().UserData;
        SharedPtr<XMLFile> xml(systemUI->GetCache()->GetResource<XMLFile>(resourcePath));
        if (xml.Null())
            return CTYPE_UNKNOWN;

        auto rootElementName = xml->GetRoot().GetName();
        if (rootElementName == "scene")
            return CTYPE_SCENE;
        if (rootElementName == "node")
            return CTYPE_SCENEOBJECT;
        if (rootElementName == "elements")
            return CTYPE_UISTYLE;
        if (rootElementName == "element")
            return CTYPE_UILAYOUT;
        if (rootElementName == "material")
            return CTYPE_MATERIAL;
        if (rootElementName == "particleeffect")
            return CTYPE_PARTICLE;
        if (rootElementName == "renderpath")
            return CTYPE_RENDERPATH;
        if (rootElementName == "texture")
            return CTYPE_TEXTUREXML;
    }

    if (extension == ".mdl")
        return CTYPE_MODEL;
    if (extension == ".ani")
        return CTYPE_ANIMATION;
    if (extension == ".scene")
        return CTYPE_SCENE;
    if (extension == ".ui")
        return CTYPE_UILAYOUT;
    if (extension == ".style")
        return CTYPE_UISTYLE;
    if (extension == ".material")
        return CTYPE_MATERIAL;
    if (extension == ".particle")
        return CTYPE_PARTICLE;
    if (extension == ".node")
        return CTYPE_SCENEOBJECT;
    if (audioExtensions_.Contains(extension))
        return CTYPE_SOUND;
    if (imagesExtensions_.Contains(extension))
        return CTYPE_TEXTURE;

    return CTYPE_UNKNOWN;
}

}
<commit_msg>Toolbox: Use explicit includes.<commit_after>//
// Copyright (c) 2018 Rokas Kupstys
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/XMLFile.h>
#include <Urho3D/SystemUI/SystemUI.h>
#include <IconFontCppHeaders/IconsFontAwesome5.h>
#include "ContentUtilities.h"

namespace Urho3D
{

const Vector<String> archiveExtensions_{".rar", ".zip", ".tar", ".gz", ".xz", ".7z", ".pak"};
const Vector<String> wordExtensions_{".doc", ".docx", ".odt"};
const Vector<String> codeExtensions_{".c", ".cpp", ".h", ".hpp", ".hxx", ".py", ".py3", ".js", ".cs"};
const Vector<String> imagesExtensions_{".png", ".jpg", ".jpeg", ".gif", ".ttf", ".dds", ".psd"};
const Vector<String> textExtensions_{".xml", ".json", ".txt", ".yml", ".scene", ".material", ".ui", ".uistyle", ".node", ".particle"};
const Vector<String> audioExtensions_{".waw", ".ogg", ".mp3"};

FileType GetFileType(const String& fileName)
{
    auto extension = GetExtension(fileName).ToLower();
    if (archiveExtensions_.Contains(extension))
        return FTYPE_ARCHIVE;
    if (wordExtensions_.Contains(extension))
        return FTYPE_WORD;
    if (codeExtensions_.Contains(extension))
        return FTYPE_CODE;
    if (imagesExtensions_.Contains(extension))
        return FTYPE_IMAGE;
    if (textExtensions_.Contains(extension))
        return FTYPE_TEXT;
    if (audioExtensions_.Contains(extension))
        return FTYPE_AUDIO;
    if (extension == "pdf")
        return FTYPE_PDF;
    return FTYPE_FILE;
}

String GetFileIcon(const String& fileName)
{
    switch (GetFileType(fileName))
    {
    case FTYPE_ARCHIVE:
        return ICON_FA_FILE_ARCHIVE;
    case FTYPE_WORD:
        return ICON_FA_FILE_WORD;
    case FTYPE_CODE:
        return ICON_FA_FILE_CODE;
    case FTYPE_IMAGE:
        return ICON_FA_FILE_IMAGE;
    case FTYPE_PDF:
        return ICON_FA_FILE_PDF;
    case FTYPE_VIDEO:
        return ICON_FA_FILE_VIDEO;
    case FTYPE_POWERPOINT:
        return ICON_FA_FILE_POWERPOINT;
    case FTYPE_TEXT:
        return ICON_FA_FILE_ALT;
    case FTYPE_FILM:
        return ICON_FA_FILE_VIDEO;
    case FTYPE_AUDIO:
        return ICON_FA_FILE_AUDIO;
    case FTYPE_EXCEL:
        return ICON_FA_FILE_EXCEL;
    default:
        return ICON_FA_FILE;
    }
}

ContentType GetContentType(const String& resourcePath)
{
    auto extension = GetExtension(resourcePath).ToLower();
    if (extension == ".xml")
    {
        auto systemUI = (SystemUI*)ui::GetIO().UserData;
        SharedPtr<XMLFile> xml(systemUI->GetCache()->GetResource<XMLFile>(resourcePath));
        if (xml.Null())
            return CTYPE_UNKNOWN;

        auto rootElementName = xml->GetRoot().GetName();
        if (rootElementName == "scene")
            return CTYPE_SCENE;
        if (rootElementName == "node")
            return CTYPE_SCENEOBJECT;
        if (rootElementName == "elements")
            return CTYPE_UISTYLE;
        if (rootElementName == "element")
            return CTYPE_UILAYOUT;
        if (rootElementName == "material")
            return CTYPE_MATERIAL;
        if (rootElementName == "particleeffect")
            return CTYPE_PARTICLE;
        if (rootElementName == "renderpath")
            return CTYPE_RENDERPATH;
        if (rootElementName == "texture")
            return CTYPE_TEXTUREXML;
    }

    if (extension == ".mdl")
        return CTYPE_MODEL;
    if (extension == ".ani")
        return CTYPE_ANIMATION;
    if (extension == ".scene")
        return CTYPE_SCENE;
    if (extension == ".ui")
        return CTYPE_UILAYOUT;
    if (extension == ".style")
        return CTYPE_UISTYLE;
    if (extension == ".material")
        return CTYPE_MATERIAL;
    if (extension == ".particle")
        return CTYPE_PARTICLE;
    if (extension == ".node")
        return CTYPE_SCENEOBJECT;
    if (audioExtensions_.Contains(extension))
        return CTYPE_SOUND;
    if (imagesExtensions_.Contains(extension))
        return CTYPE_TEXTURE;

    return CTYPE_UNKNOWN;
}

}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2004-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include "fboss/agent/platforms/wedge/WedgePlatform.h"

#include <folly/Memory.h>
#include <folly/Subprocess.h>
#include <glog/logging.h>
#include "fboss/lib/usb/UsbError.h"
#include "fboss/lib/usb/WedgeI2CBus.h"
#include "fboss/agent/SwSwitch.h"
#include "fboss/agent/SysError.h"
#include "fboss/agent/hw/bcm/BcmAPI.h"
#include "fboss/agent/hw/bcm/BcmSwitch.h"
#include "fboss/agent/platforms/wedge/WedgePort.h"

#include <future>

DEFINE_string(volatile_state_dir, "/dev/shm/fboss",
              "Directory for storing volatile state");
DEFINE_string(persistent_state_dir, "/var/facebook/fboss",
              "Directory for storing persistent state");
DEFINE_string(mac, "",
              "The local MAC address for this switch");
DEFINE_string(mgmt_if, "eth0",
              "name of management interface");

using folly::MacAddress;
using std::make_unique;
using folly::Subprocess;
using std::string;

namespace {
constexpr auto kNumWedge40Qsfps = 16;
}

namespace facebook { namespace fboss {

WedgePlatform::WedgePlatform(std::unique_ptr<WedgeProductInfo> productInfo)
    : productInfo_(std::move(productInfo)) {}

void WedgePlatform::init() {
  auto config = loadConfig();
  BcmAPI::init(config);
  initLocalMac();
  auto mode = getMode();
  bool isLc = mode == WedgePlatformMode::LC ||
    mode == WedgePlatformMode::GALAXY_LC;
  hw_.reset(new BcmSwitch(this, isLc ? BcmSwitch::HALF_HASH :
        BcmSwitch::FULL_HASH));
}

WedgePlatform::~WedgePlatform() {}

WedgePlatform::InitPortMap WedgePlatform::initPorts() {
  portMapping_ = createPortMapping();

  InitPortMap mapping;
  for (const auto& kv: *portMapping_) {
    opennsl_port_t id = kv.first;
    mapping[id] = kv.second.get();
  }
  return mapping;
}

HwSwitch* WedgePlatform::getHwSwitch() const {
  return hw_.get();
}

MacAddress WedgePlatform::getLocalMac() const {
  return localMac_;
}

string WedgePlatform::getVolatileStateDir() const {
  return FLAGS_volatile_state_dir;
}

string WedgePlatform::getPersistentStateDir() const {
  return FLAGS_persistent_state_dir;
}

void WedgePlatform::onUnitAttach(int unit) {}

void WedgePlatform::getProductInfo(ProductInfo& info) {
  productInfo_->getInfo(info);
}

WedgePlatformMode WedgePlatform::getMode() const {
  return productInfo_->getMode();
}

void WedgePlatform::initLocalMac() {
  if (!FLAGS_mac.empty()) {
    localMac_ = MacAddress(FLAGS_mac);
    return;
  }

  // TODO(t4543375): Get the base MAC address from the BMC.
  //
  // For now, we take the MAC address from eth0, and enable the
  // "locally administered" bit.  This MAC should be unique, and it's fine for
  // us to use a locally administered address for now.
  std::vector<std::string> cmd{"/sbin/ip", "address", "ls", FLAGS_mgmt_if};
  Subprocess p(cmd, Subprocess::pipeStdout());
  auto out = p.communicate();
  p.waitChecked();
  auto idx = out.first.find("link/ether ");
  if (idx == std::string::npos) {
    throw std::runtime_error("unable to determine local mac address");
  }
  MacAddress eth0Mac(out.first.substr(idx + 11, 17));
  localMac_ = MacAddress::fromHBO(eth0Mac.u64HBO() | 0x0000020000000000);
}

std::unique_ptr<BaseWedgeI2CBus> WedgePlatform::getI2CBus() {
  return make_unique<WedgeI2CBus>();
}

TransceiverIdxThrift WedgePlatform::getPortMapping(PortID portId) const {
  auto info = TransceiverIdxThrift();
  auto port = getPort(portId);

  auto transceiver = port->getTransceiverID();
  if (transceiver) {
    info.transceiverId = static_cast<int32_t>(*transceiver);
    info.__isset.transceiverId = true;
  }
  auto channel = port->getChannel();
  if (channel) {
    info.channelId = static_cast<int32_t>(*channel);
    info.__isset.channelId = true;
  }
  return info;
}

WedgePort* WedgePlatform::getPort(PortID id) const {
  return portMapping_->getPort(id);
}
WedgePort* WedgePlatform::getPort(TransceiverID id) const {
  return portMapping_->getPort(id);
}

}} // facebook::fboss
<commit_msg>Replace Subprocess::pipe* syntax sugar with Subprocess::Options().pipe*<commit_after>/*
 *  Copyright (c) 2004-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include "fboss/agent/platforms/wedge/WedgePlatform.h"

#include <folly/Memory.h>
#include <folly/Subprocess.h>
#include <glog/logging.h>
#include "fboss/lib/usb/UsbError.h"
#include "fboss/lib/usb/WedgeI2CBus.h"
#include "fboss/agent/SwSwitch.h"
#include "fboss/agent/SysError.h"
#include "fboss/agent/hw/bcm/BcmAPI.h"
#include "fboss/agent/hw/bcm/BcmSwitch.h"
#include "fboss/agent/platforms/wedge/WedgePort.h"

#include <future>

DEFINE_string(volatile_state_dir, "/dev/shm/fboss",
              "Directory for storing volatile state");
DEFINE_string(persistent_state_dir, "/var/facebook/fboss",
              "Directory for storing persistent state");
DEFINE_string(mac, "",
              "The local MAC address for this switch");
DEFINE_string(mgmt_if, "eth0",
              "name of management interface");

using folly::MacAddress;
using std::make_unique;
using folly::Subprocess;
using std::string;

namespace {
constexpr auto kNumWedge40Qsfps = 16;
}

namespace facebook { namespace fboss {

WedgePlatform::WedgePlatform(std::unique_ptr<WedgeProductInfo> productInfo)
    : productInfo_(std::move(productInfo)) {}

void WedgePlatform::init() {
  auto config = loadConfig();
  BcmAPI::init(config);
  initLocalMac();
  auto mode = getMode();
  bool isLc = mode == WedgePlatformMode::LC ||
    mode == WedgePlatformMode::GALAXY_LC;
  hw_.reset(new BcmSwitch(this, isLc ? BcmSwitch::HALF_HASH :
        BcmSwitch::FULL_HASH));
}

WedgePlatform::~WedgePlatform() {}

WedgePlatform::InitPortMap WedgePlatform::initPorts() {
  portMapping_ = createPortMapping();

  InitPortMap mapping;
  for (const auto& kv: *portMapping_) {
    opennsl_port_t id = kv.first;
    mapping[id] = kv.second.get();
  }
  return mapping;
}

HwSwitch* WedgePlatform::getHwSwitch() const {
  return hw_.get();
}

MacAddress WedgePlatform::getLocalMac() const {
  return localMac_;
}

string WedgePlatform::getVolatileStateDir() const {
  return FLAGS_volatile_state_dir;
}

string WedgePlatform::getPersistentStateDir() const {
  return FLAGS_persistent_state_dir;
}

void WedgePlatform::onUnitAttach(int unit) {}

void WedgePlatform::getProductInfo(ProductInfo& info) {
  productInfo_->getInfo(info);
}

WedgePlatformMode WedgePlatform::getMode() const {
  return productInfo_->getMode();
}

void WedgePlatform::initLocalMac() {
  if (!FLAGS_mac.empty()) {
    localMac_ = MacAddress(FLAGS_mac);
    return;
  }

  // TODO(t4543375): Get the base MAC address from the BMC.
  //
  // For now, we take the MAC address from eth0, and enable the
  // "locally administered" bit.  This MAC should be unique, and it's fine for
  // us to use a locally administered address for now.
  std::vector<std::string> cmd{"/sbin/ip", "address", "ls", FLAGS_mgmt_if};
  Subprocess p(cmd, Subprocess::Options().pipeStdout());
  auto out = p.communicate();
  p.waitChecked();
  auto idx = out.first.find("link/ether ");
  if (idx == std::string::npos) {
    throw std::runtime_error("unable to determine local mac address");
  }
  MacAddress eth0Mac(out.first.substr(idx + 11, 17));
  localMac_ = MacAddress::fromHBO(eth0Mac.u64HBO() | 0x0000020000000000);
}

std::unique_ptr<BaseWedgeI2CBus> WedgePlatform::getI2CBus() {
  return make_unique<WedgeI2CBus>();
}

TransceiverIdxThrift WedgePlatform::getPortMapping(PortID portId) const {
  auto info = TransceiverIdxThrift();
  auto port = getPort(portId);

  auto transceiver = port->getTransceiverID();
  if (transceiver) {
    info.transceiverId = static_cast<int32_t>(*transceiver);
    info.__isset.transceiverId = true;
  }
  auto channel = port->getChannel();
  if (channel) {
    info.channelId = static_cast<int32_t>(*channel);
    info.__isset.channelId = true;
  }
  return info;
}

WedgePort* WedgePlatform::getPort(PortID id) const {
  return portMapping_->getPort(id);
}
WedgePort* WedgePlatform::getPort(TransceiverID id) const {
  return portMapping_->getPort(id);
}

}} // facebook::fboss
<|endoftext|>