<commit_before>/*
 * compile both driver code and kernel code with nvcc, as in:
 * 			nvcc simple.c simple.cu
 */
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <vector>
#include <cmath>
#include <ctime>
using namespace std;

extern "C" void gpu_sobel(int **source_array, int **result_array, int src_rows,
                          int src_column_size);

#pragma pack(1)
typedef struct {
  char id[2];
  int file_size;
  int reserved;
  int offset;
} header_type;

#pragma pack(1)
typedef struct {
  int header_size;
  int width;
  int height;
  unsigned short int color_planes;
  unsigned short int color_depth;
  unsigned int compression;
  int image_size;
  int xresolution;
  int yresolution;
  int num_colors;
  int num_important_colors;
} information_type;

int main(int argc, char *argv[]) {
  header_type header;
  information_type information;
  string imageFileName, newImageFileName;
  unsigned char tempData[3];
  int row, col, row_bytes, padding;

  // prepare files
  // cout << "Original imagefile? ";
  imageFileName = argv[1];
  ifstream imageFile;
  imageFile.open(imageFileName.c_str(), ios::binary);
  if (!imageFile) {
    cerr << "file not found" << endl;
    exit(-1);
  }
  newImageFileName = argv[2];
  ofstream newImageFile;
  newImageFile.open(newImageFileName.c_str(), ios::binary);

  // read file header
  imageFile.read((char *)&header, sizeof(header_type));
  if (header.id[0] != 'B' || header.id[1] != 'M') {
    cerr << "Does not appear to be a .bmp file.  Goodbye." << endl;
    exit(-1);
  }
  // read/compute image information
  imageFile.read((char *)&information, sizeof(information_type));
  row_bytes = information.width * 3;
  padding = row_bytes % 4;
  if (padding)
    padding = 4 - padding;

  // extract image data, initialize vectors
  int rows = information.height + 2;
  int column_size = information.width + 2;
  int src_size = rows * column_size;
  int **data = (int **)malloc(src_size * sizeof(int *));
  for (row = 1; row <= information.height; row++) {
    data[row] = (int *)malloc(column_size * sizeof(int));
    for (col = 0; col <= information.width; col++) {
      if (col == 0) {
        data[row][0] = 0;
      } else {
        imageFile.read((char *)tempData, 3 * sizeof(unsigned char));
        data[row][col] = ((int)tempData[0]);
      }
    }
    // pad last column
    data[row][col + 1] = 0;
    if (padding)
      imageFile.read((char *)tempData, padding * sizeof(unsigned char));
  }

  // pad first & last row
  int last_row = rows - 1;
  data[0] = (int *)malloc(column_size * sizeof(int));
  data[last_row] = (int *)malloc(column_size * sizeof(int));
  for (col = 0; col < column_size; col++) {
    data[0][col] = 0;
    data[rows - 1][col] = 0;
  }
  std::cout << imageFileName << std::endl
            << "columns (x): " << information.width
            << " rows (y): " << information.height << std::endl;

  int size = information.width * information.height;
  int **newData = (int **)malloc(size * sizeof(int *));
  // linear-ize source array
  int dest_size = information.width * information.height;
  int *l_source_array = 0;
  l_source_array = new int[src_size];
  for (row = 0; row < src_rows; row++) {
    for (col = 0; col < src_column_size; col++) {
      l_source_array[row * src_column_size + col] = data[row][col];
    }
  }
  int *l_result_array = 0;
  l_result_array = new int[size];
  clock_t gpu_start = clock();
  gpu_sobel(l_source_array, l_result_array, rows, column_size);
  clock_t gpu_stop = clock();
  double elapsed_gpu = double(gpu_stop - gpu_start) / (CLOCKS_PER_SEC / 1000);

  std::cout << "GPU Time Taken (msec): " << elapsed_gpu << std::endl;

  // de-linearize result array
  int **newData = (int **)malloc(dest_size * sizeof(int *));
  for (row = 0; row < result_rows; row++) {
    newData[row] = new int[result_column_size];
    for (col = 0; col < result_column_size; col++) {
      newData[row][col] = l_result_array[(row * result_column_size) + col];
    }
  }

  // write header to new image file
  newImageFile.write((char *)&header, sizeof(header_type));
  newImageFile.write((char *)&information, sizeof(information_type));

  // write new image data to new image file
  for (row = 0; row < information.height; row++) {
    for (col = 0; col < information.width; col++) {
      tempData[0] = (unsigned char)newData[row][col];
      tempData[1] = (unsigned char)newData[row][col];
      tempData[2] = (unsigned char)newData[row][col];
      newImageFile.write((char *)tempData, 3 * sizeof(unsigned char));
    }
    if (padding) {
      tempData[0] = 0;
      tempData[1] = 0;
      tempData[2] = 0;
      newImageFile.write((char *)tempData, padding * sizeof(unsigned char));
    }
  }
  cout << newImageFileName << " done." << endl;
  imageFile.close();
  newImageFile.close();

  return 0;
}
<commit_msg>fix compile<commit_after>/*
 * compile both driver code and kernel code with nvcc, as in:
 * 			nvcc simple.c simple.cu
 */
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <vector>
#include <cmath>
#include <ctime>
using namespace std;

extern "C" void gpu_sobel(int *l_source_array, int *l_result_array,
                          int src_rows, int src_column_size);

#pragma pack(1)
typedef struct {
  char id[2];
  int file_size;
  int reserved;
  int offset;
} header_type;

#pragma pack(1)
typedef struct {
  int header_size;
  int width;
  int height;
  unsigned short int color_planes;
  unsigned short int color_depth;
  unsigned int compression;
  int image_size;
  int xresolution;
  int yresolution;
  int num_colors;
  int num_important_colors;
} information_type;

int main(int argc, char *argv[]) {
  header_type header;
  information_type information;
  string imageFileName, newImageFileName;
  unsigned char tempData[3];
  int row, col, row_bytes, padding;

  // prepare files
  // cout << "Original imagefile? ";
  imageFileName = argv[1];
  ifstream imageFile;
  imageFile.open(imageFileName.c_str(), ios::binary);
  if (!imageFile) {
    cerr << "file not found" << endl;
    exit(-1);
  }
  newImageFileName = argv[2];
  ofstream newImageFile;
  newImageFile.open(newImageFileName.c_str(), ios::binary);

  // read file header
  imageFile.read((char *)&header, sizeof(header_type));
  if (header.id[0] != 'B' || header.id[1] != 'M') {
    cerr << "Does not appear to be a .bmp file.  Goodbye." << endl;
    exit(-1);
  }
  // read/compute image information
  imageFile.read((char *)&information, sizeof(information_type));
  row_bytes = information.width * 3;
  padding = row_bytes % 4;
  if (padding)
    padding = 4 - padding;

  // extract image data, initialize vectors
  int rows = information.height + 2;
  int column_size = information.width + 2;
  int src_size = rows * column_size;
  int **data = (int **)malloc(src_size * sizeof(int *));
  for (row = 1; row <= information.height; row++) {
    data[row] = (int *)malloc(column_size * sizeof(int));
    for (col = 0; col <= information.width; col++) {
      if (col == 0) {
        data[row][0] = 0;
      } else {
        imageFile.read((char *)tempData, 3 * sizeof(unsigned char));
        data[row][col] = ((int)tempData[0]);
      }
    }
    // pad last column
    data[row][col + 1] = 0;
    if (padding)
      imageFile.read((char *)tempData, padding * sizeof(unsigned char));
  }

  // pad first & last row
  int last_row = rows - 1;
  data[0] = (int *)malloc(column_size * sizeof(int));
  data[last_row] = (int *)malloc(column_size * sizeof(int));
  for (col = 0; col < column_size; col++) {
    data[0][col] = 0;
    data[rows - 1][col] = 0;
  }
  std::cout << imageFileName << std::endl
            << "columns (x): " << information.width
            << " rows (y): " << information.height << std::endl;

  int size = information.width * information.height;
  int **newData = (int **)malloc(size * sizeof(int *));
  // linear-ize source array
  int dest_size = information.width * information.height;
  int *l_source_array = 0;
  l_source_array = new int[src_size];
  for (row = 0; row < src_rows; row++) {
    for (col = 0; col < src_column_size; col++) {
      l_source_array[row * src_column_size + col] = data[row][col];
    }
  }
  int *l_result_array = 0;
  l_result_array = new int[size];
  clock_t gpu_start = clock();
  gpu_sobel(l_source_array, l_result_array, rows, column_size);
  clock_t gpu_stop = clock();
  double elapsed_gpu = double(gpu_stop - gpu_start) / (CLOCKS_PER_SEC / 1000);

  std::cout << "GPU Time Taken (msec): " << elapsed_gpu << std::endl;

  int result_rows = information.height;
  int result_column_size = information.width;
  // de-linearize result array
  int **newData = (int **)malloc(dest_size * sizeof(int *));
  for (row = 0; row < result_rows; row++) {
    newData[row] = new int[result_column_size];
    for (col = 0; col < result_column_size; col++) {
      newData[row][col] = l_result_array[(row * result_column_size) + col];
    }
  }

  // write header to new image file
  newImageFile.write((char *)&header, sizeof(header_type));
  newImageFile.write((char *)&information, sizeof(information_type));

  // write new image data to new image file
  for (row = 0; row < information.height; row++) {
    for (col = 0; col < information.width; col++) {
      tempData[0] = (unsigned char)newData[row][col];
      tempData[1] = (unsigned char)newData[row][col];
      tempData[2] = (unsigned char)newData[row][col];
      newImageFile.write((char *)tempData, 3 * sizeof(unsigned char));
    }
    if (padding) {
      tempData[0] = 0;
      tempData[1] = 0;
      tempData[2] = 0;
      newImageFile.write((char *)tempData, padding * sizeof(unsigned char));
    }
  }
  cout << newImageFileName << " done." << endl;
  imageFile.close();
  newImageFile.close();

  return 0;
}
<|endoftext|>


<commit_before>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */
#include "slidercontainer.h"

#include <DuiButton>
#include <DuiLinearLayoutPolicy>
#include <DuiLabel>
#include <DuiLayout>
#include <DuiSlider>

#undef DEBUG
#include "../debug.h"

SliderContainer::SliderContainer (DuiWidget *parent) :
        DuiContainer (parent),
        PSMAutoButton (NULL),
        PSMSlider (0),
        sliderValue (-1)
{
    SYS_DEBUG ("");

    setHeaderVisible (false);
    setLayout ();
}

SliderContainer::~SliderContainer ()
{
    SYS_DEBUG ("Destroying %p", this);
}

void
SliderContainer::retranslate ()
{
    SYS_DEBUG ("");
    //% "Auto activate power save"
    textLabel->setText (qtTrId ("qtn_ener_autops"));
}

void SliderContainer::setLayout()
{
    SYS_DEBUG ("");

    DuiLayout *layout = new DuiLayout;
    layout_policy =
        new DuiLinearLayoutPolicy (layout, Qt::Vertical);

    DuiLayout *hlayout = new DuiLayout;
    DuiLinearLayoutPolicy *hpolicy =
        new DuiLinearLayoutPolicy (hlayout, Qt::Horizontal);

    // battery label
    textLabel = new DuiLabel;
    textLabel->setObjectName ("batteryLabel");
    retranslate ();

    hpolicy->addItem (textLabel, Qt::AlignLeft);

    // PSMAutoButton
    PSMAutoButton = new DuiButton;
    connect (PSMAutoButton, SIGNAL (toggled (bool)),
             this, SLOT (PSMAutoButtonToggled (bool)));
    PSMAutoButton->setCheckable (true);
    PSMAutoButton->setViewType (DuiButton::switchType);
    // PSMAutoButton->setObjectName ("PSMAutoButton");

    hpolicy->addItem (PSMAutoButton, Qt::AlignRight);

    layout_policy->addItem (hlayout);

    centralWidget ()->setLayout (layout);
}

void
SliderContainer::initSlider (
        const QStringList &values)
{
    SYS_DEBUG ("");
    sliderValues = QStringList (values);

    if (PSMSlider == 0)
        return;

    PSMSlider->setRange (0, sliderValues.size () - 1);
    PSMSlider->setOrientation (Qt::Horizontal);
    PSMSlider->setHandleLabelVisible (true);

    if (sliderValue > 0)
        sliderValueChanged (sliderValue);

    connect (PSMSlider, SIGNAL (valueChanged (int)),
             this, SLOT (sliderValueChanged (int)));
}

void SliderContainer::updateSlider (const QString &value)
{
    SYS_DEBUG ("value = %s", SYS_STR (value));

    // Store the actual value for later
    // (eg for the case when slider isn't ready yet...)
    sliderValue = sliderValues.indexOf (value);

    // Slider not yet created:
    if (PSMSlider == 0)
        return;

    PSMSlider->setValue (sliderValue);
    //^ in case this is the first call, we need to set the value
    PSMSlider->setHandleLabel (QString ("%1%").arg (value));
}

void SliderContainer::sliderValueChanged (int value)
{
    SYS_DEBUG ("");

    sliderValue = value;
    updateSlider (sliderValues.at (value));
    emit PSMThresholdValueChanged (sliderValues.at (value));
}

void SliderContainer::toggleSliderExistence (bool toggle)
{
    SYS_DEBUG ("");
    if (toggle) {
        if ((layout_policy->count () < 2) && (PSMSlider == 0))
        {
            PSMSlider = new DuiSlider;
            initSlider (sliderValues);
            layout_policy->addItem (PSMSlider);
        }
    } else {
        if ((PSMSlider) && (layout_policy->count () > 1))
        {
            layout_policy->removeItem (PSMSlider);
            delete PSMSlider;
            PSMSlider = 0;
        }
    }
}

void SliderContainer::initPSMAutoButton (bool toggle)
{
    PSMAutoButton->setChecked (toggle);
    toggleSliderExistence (toggle);
}

void SliderContainer::PSMAutoDisabled ()
{
    SYS_DEBUG ("");
    PSMAutoButton->blockSignals (true);
    initPSMAutoButton (false);
    PSMAutoButton->blockSignals (false);
}

void SliderContainer::PSMAutoButtonToggled (bool toggle)
{
    SYS_DEBUG ("toggle = %s", SYS_BOOL (toggle));

    toggleSliderExistence (toggle);
    emit PSMAutoToggled (toggle);
}

<commit_msg>Batteryapplet code fix.<commit_after>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */
#include "slidercontainer.h"

#include <DuiButton>
#include <DuiLinearLayoutPolicy>
#include <DuiLabel>
#include <DuiLayout>
#include <DuiSlider>

#define DEBUG
#include "../debug.h"

SliderContainer::SliderContainer (DuiWidget *parent) :
        DuiContainer (parent),
        PSMAutoButton (NULL),
        PSMSlider (0),
        sliderValue (-1)
{
    SYS_DEBUG ("");

    setHeaderVisible (false);
    setLayout ();
}

SliderContainer::~SliderContainer ()
{
    SYS_DEBUG ("Destroying %p", this);
}

void
SliderContainer::retranslate ()
{
    SYS_DEBUG ("");
    //% "Auto activate power save"
    textLabel->setText (qtTrId ("qtn_ener_autops"));
}

void SliderContainer::setLayout()
{
    SYS_DEBUG ("");

    DuiLayout *layout = new DuiLayout;
    layout_policy =
        new DuiLinearLayoutPolicy (layout, Qt::Vertical);

    DuiLayout *hlayout = new DuiLayout;
    DuiLinearLayoutPolicy *hpolicy =
        new DuiLinearLayoutPolicy (hlayout, Qt::Horizontal);

    // battery label
    textLabel = new DuiLabel;
    textLabel->setObjectName ("batteryLabel");
    retranslate ();

    hpolicy->addItem (textLabel, Qt::AlignLeft);

    // PSMAutoButton
    PSMAutoButton = new DuiButton;
    connect (PSMAutoButton, SIGNAL (toggled (bool)),
             this, SLOT (PSMAutoButtonToggled (bool)));
    PSMAutoButton->setCheckable (true);
    PSMAutoButton->setViewType (DuiButton::switchType);
    // PSMAutoButton->setObjectName ("PSMAutoButton");

    hpolicy->addItem (PSMAutoButton, Qt::AlignRight);

    layout_policy->addItem (hlayout);

    centralWidget ()->setLayout (layout);
}

void
SliderContainer::initSlider (
        const QStringList &values)
{
    SYS_DEBUG ("");
    sliderValues = QStringList (values);

    if (PSMSlider == 0)
        return;

    PSMSlider->setRange (0, sliderValues.size () - 1);
    PSMSlider->setOrientation (Qt::Horizontal);
    PSMSlider->setHandleLabelVisible (true);
}

void SliderContainer::updateSlider (const QString &value)
{
    SYS_DEBUG ("value = %s", SYS_STR (value));

    // Store the actual value for later
    // (eg for the case when slider isn't ready yet...)
    sliderValue = sliderValues.indexOf (value);

    // Slider not yet created:
    if (PSMSlider == 0)
        return;

    PSMSlider->setValue (sliderValue);
    //^ in case this is the first call, we need to set the value
    PSMSlider->setHandleLabel (QString ("%1%").arg (value));
}

void SliderContainer::sliderValueChanged (int value)
{
    SYS_DEBUG ("*** slider = %p", PSMSlider);

    sliderValue = value;
    SYS_DEBUG ("*** value  = %d", value);

    updateSlider (sliderValues.at (value));
    emit PSMThresholdValueChanged (sliderValues.at (value));
}

void SliderContainer::toggleSliderExistence (bool toggle)
{
    SYS_DEBUG ("");
    if (toggle) {
        if ((layout_policy->count () < 2) && (PSMSlider == 0)) {
            PSMSlider = new DuiSlider;
            SYS_DEBUG ("Connecting %p->valueChanged", PSMSlider);
            initSlider (sliderValues);
            connect (PSMSlider, SIGNAL (valueChanged (int)),
                    this, SLOT (sliderValueChanged (int)));
            layout_policy->addItem (PSMSlider);
        }
    } else {
        if ((PSMSlider) && (layout_policy->count () > 1)) {
            layout_policy->removeItem (PSMSlider);
            delete PSMSlider;
            PSMSlider = 0;
        }
    }
}

void SliderContainer::initPSMAutoButton (bool toggle)
{
    PSMAutoButton->setChecked (toggle);
    toggleSliderExistence (toggle);
}

void SliderContainer::PSMAutoDisabled ()
{
    SYS_DEBUG ("");
    PSMAutoButton->blockSignals (true);
    initPSMAutoButton (false);
    PSMAutoButton->blockSignals (false);
}

void SliderContainer::PSMAutoButtonToggled (bool toggle)
{
    SYS_DEBUG ("toggle = %s", SYS_BOOL (toggle));

    toggleSliderExistence (toggle);
    emit PSMAutoToggled (toggle);
}

<|endoftext|>


<commit_before>#ifndef ELEKTRA_KDBVALUE_HPP
#define ELEKTRA_KDBVALUE_HPP

#ifdef HAVE_KDBCONFIG_H
#include <kdbconfig.h>
#endif

#include <set>
#include <map>
#include <string>
#include <vector>
#include <memory>
#include <cassert>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <functional>
#include <unordered_map>

#include <kdbproposal.h>
#include <keyset.hpp>

namespace kdb
{

// some widely used interfaces

class Layer
{
public:
	virtual std::string id() const = 0;
	virtual std::string operator()() const = 0;
};

class Observer
{
public:
	virtual ~Observer() = 0;
	virtual void update() const = 0;

	typedef std::reference_wrapper<Observer> reference;
};

bool operator <(Observer const & lhs, Observer const & rhs)
{
	return &lhs < &rhs;
}

inline Observer::~Observer()
{}

// Default Policies for Value

class NoContext
{
//TODO: define interface
};

/**
 * @brief simply lookup without spec
 */
template<typename T>
class DefaultGetPolicy
{
public:
	typedef T type;
	static type get(KeySet &ks, Key const& spec)
	{
		Key found = ks.lookup(spec.getName(), 0);
		type val = type{};
		if (found)
		{
			val = found.get<type>();
#if DEBUG && VERBOSE
		std::cout << "got name: " << m_spec.getName() << " to " << m_cache << std::endl;
#endif
		}
		else
		{
			val = spec.getMeta<type>("default");
#if DEBUG && VERBOSE
		std::cout << "got default name: " << m_spec.getName() << " to " << m_cache << std::endl;
#endif
		}

		return val;
	}
};

/**
 * @brief Implements update when key is not found.
 *
 * The new value always can be written out
 */
template<typename T>
class DefaultSetPolicy
{
public:
	typedef T type;
	static Key set(KeySet &ks, Key const& spec)
	{
		kdb::Key found = ks.lookup(spec.getName(), 0);

		if(!found)
		{
			kdb::Key k("user/"+spec.getName(), KEY_END);
			ks.append(k);
			found = k;
		}

		return found;
	}
};

template<typename T>
class DefaultWritePolicy
{
public:
	typedef T type;
	static const bool allowed = true;
};

template<typename T>
class ReadOnlyPolicy
{
public:
	typedef T type;
	static const bool allowed = false;
};

class DefaultObserverPolicy
{
public:
	typedef double type;
};

class NoLockPolicy
{
public:
	typedef char type;
	void lock() {}
	void unlock() {}
};

/**
 * This technique with the PolicySelector and Discriminator is taken
 * from the book  "C++ Templates - The Complete Guide"
 * by David Vandevoorde and Nicolai M. Josuttis, Addison-Wesley, 2002
 * in Chapter 16 Templates and Inheritance: Named Template Arguments
 *
 * The technique allows users of the class Value to use any number
 * and order of policies as desired.
 */
template <typename Base, int D>
class Discriminator : public Base
{
};

template < typename Setter1,
	   typename Setter2,
	   typename Setter3,
	   typename Setter4,
	   typename Setter5,
	   typename Setter6
	 >
class PolicySelector : public Discriminator<Setter1,1>,
		       public Discriminator<Setter2,2>,
		       public Discriminator<Setter3,3>,
		       public Discriminator<Setter4,4>,
		       public Discriminator<Setter5,5>,
		       public Discriminator<Setter6,6>
{
};

template<typename T>
class DefaultPolicies
{
public:
	typedef DefaultGetPolicy<T> GetPolicy;
	typedef DefaultSetPolicy<T> SetPolicy;
	typedef NoContext ContextPolicy;
	typedef DefaultWritePolicy<T> WritePolicy;
	typedef DefaultObserverPolicy ObserverPolicy;
	typedef NoLockPolicy LockPolicy;
};

template<typename T>
class DefaultPolicyArgs : virtual public DefaultPolicies<T>
{
};

// class templates to override the default policy values

/// Needed by the user to set one of the policies
///
/// @tparam Policy
template <typename Policy>
class GetPolicyIs : virtual public DefaultPolicies<typename Policy::type>
{
public:
	typedef Policy GetPolicy;
};

/// Needed by the user to set one of the policies
///
/// @tparam Policy
template <typename Policy>
class SetPolicyIs : virtual public DefaultPolicies<typename Policy::type>
{
public:
	typedef Policy SetPolicy;
};

/// Needed by the user to set one of the policies
///
/// @tparam Policy
template <typename Policy>
class ContextPolicyIs : virtual public DefaultPolicies<typename Policy::type>
{
public:
	typedef Policy Context;
};

/// Needed by the user to set one of the policies
///
/// @tparam Policy
template <typename Policy>
class WritePolicyIs : virtual public DefaultPolicies<typename Policy::type>
{
public:
	typedef Policy WritePolicy;
};

/// Needed by the user to set one of the policies
///
/// @tparam Policy
template <typename Policy>
class ObserverPolicyIs : virtual public DefaultPolicies<typename Policy::type>
{
public:
	typedef Policy ObserverPolicy;
};

/// Needed by the user to set one of the policies
///
/// @tparam Policy
template <typename Policy>
class LockPolicyIs : virtual public DefaultPolicies<typename Policy::type>
{
public:
	typedef Policy LockPolicy;
};

// standard types

template<typename T,
	typename PolicySetter1 = DefaultPolicyArgs<T>,
	typename PolicySetter2 = DefaultPolicyArgs<T>,
	typename PolicySetter3 = DefaultPolicyArgs<T>,
	typename PolicySetter4 = DefaultPolicyArgs<T>,
	typename PolicySetter5 = DefaultPolicyArgs<T>,
	typename PolicySetter6 = DefaultPolicyArgs<T>
	>
class Value :
	public Observer
{
public:
	typedef T type;

	typedef PolicySelector<
		PolicySetter1,
		PolicySetter2,
		PolicySetter3,
		PolicySetter4,
		PolicySetter5,
		PolicySetter6
		>
		Policies;

	// not to be constructed yourself
	Value<T, PolicySetter1, PolicySetter2, PolicySetter3,
		PolicySetter4, PolicySetter5, PolicySetter6>
		(KeySet & ks, typename Policies::ContextPolicy & context_, kdb::Key spec) :
		m_cache(),
		m_ks(ks),
		m_context(context_),
		m_spec(spec)
	{
		assert(m_spec.getName()[0] == '/');
		m_spec.setMeta("name", m_spec.getName());
		ckdb::elektraKeySetName(*m_spec,
				m_context.evaluate(m_spec.getName()).c_str(),
				KEY_CASCADING_NAME);
		syncCache();  // read what we have in our context
		m_context.attachByName(m_spec.getMeta<std::string>("name"), *this);
	}

	Value<T, PolicySetter1, PolicySetter2, PolicySetter3,
		PolicySetter4, PolicySetter5, PolicySetter6>
		(Value<T> const & other, KeySet & ks) :
		m_cache(other.m_cache),
		m_ks(ks),
		m_context(other.m_context),
		m_spec(other.m_spec)
	{
		assert(m_spec.getName()[0] == '/');
		// cache already in sync
		// attach copy, too:
		m_context.attachByName(m_spec.getMeta<std::string>("name"), *this);
	}

	typedef Value<T, PolicySetter1, PolicySetter2, PolicySetter3,
		PolicySetter4, PolicySetter5, PolicySetter6> CV;

	CV const & operator= (type n)
	{
		static_assert(Policies::WritePolicy::allowed, "read only contextual value");
		m_cache = n;

		return *this;
	}

	type operator ++()
	{
		static_assert(Policies::WritePolicy::allowed, "read only contextual value");
		return ++m_cache;
	}

	type operator ++(int)
	{
		static_assert(Policies::WritePolicy::allowed, "read only contextual value");
		return m_cache++;
	}

	operator type() const
	{
			return m_cache;
	}

	bool operator == (CV const & other) const
	{
		return m_cache == other.m_cache ;
	}

	type getDefault() const
	{
		return m_spec.getMeta<type>("default");
	}

	/// We allow manipulation of context for const
	/// objects
	typename Policies::ContextPolicy & context() const
	{
		return const_cast<typename Policies::ContextPolicy&>(m_context);
	}

	Key const& getSpec() const
	{
		return m_spec;
	}

	// keyset to cache
	void syncCache() const
	{
		m_cache = Policies::GetPolicy::get(m_ks, m_spec);
		// Policies::GetPolicy::get(this);
	}

	// cache to keyset
	void syncKeySet() const
	{
#if DEBUG && VERBOSE
		std::cout << "set name: " << m_spec.getName() << " to " << m_cache << std::endl;
#endif
		kdb::Key found = Policies::SetPolicy::set(m_ks, m_spec);
		if (found)
		{
			found.set<type>(m_cache);
		}
		// Policies::SetPolicy::set(this);
	}

private:
	virtual void update() const
	{
		// Policies::UpdatePolicy::update(this);
		typename Policies::LockPolicy lock;
		lock.lock();

		std::string evaluated_name = m_context.evaluate(m_spec.getMeta<std::string>("name"));
#if DEBUG && VERBOSE
		std::cout << "update " << evaluated_name << " from " << m_spec.getName() << std::endl;
#endif
		if (evaluated_name != m_spec.getName())
		{
			syncKeySet(); // flush out what currently is in cache
			ckdb::elektraKeySetName(*m_spec,
					evaluated_name.c_str(),
					KEY_CASCADING_NAME);
			syncCache();  // read what we have under new context
		}
		lock.unlock();
	}

private:
	mutable type m_cache;
	KeySet & m_ks;
	typename Policies::ContextPolicy & m_context;
	mutable Key m_spec;
	mutable Key m_key;
};

}

#endif
<commit_msg>broken<commit_after>#ifndef ELEKTRA_KDBVALUE_HPP
#define ELEKTRA_KDBVALUE_HPP

#ifdef HAVE_KDBCONFIG_H
#include <kdbconfig.h>
#endif

#include <set>
#include <map>
#include <string>
#include <vector>
#include <memory>
#include <cassert>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <functional>
#include <unordered_map>

#include <kdbproposal.h>
#include <keyset.hpp>

namespace kdb
{

// some widely used interfaces

class Layer
{
public:
	virtual std::string id() const = 0;
	virtual std::string operator()() const = 0;
};

class Observer
{
public:
	virtual ~Observer() = 0;
	virtual void update() const = 0;

	typedef std::reference_wrapper<Observer> reference;
};

bool operator <(Observer const & lhs, Observer const & rhs)
{
	return &lhs < &rhs;
}

inline Observer::~Observer()
{}

// Default Policies for Value

class NoContext
{
//TODO: define interface
};

/**
 * @brief simply lookup without spec
 */
class DefaultGetPolicy
{
public:
	static type get(KeySet &ks, Key const& spec)
	{
		Key found = ks.lookup(spec.getName(), 0);
		type val = type{};
		if (found)
		{
			val = found.get<type>();
#if DEBUG && VERBOSE
		std::cout << "got name: " << m_spec.getName() << " to " << m_cache << std::endl;
#endif
		}
		else
		{
			val = spec.getMeta<type>("default");
#if DEBUG && VERBOSE
		std::cout << "got default name: " << m_spec.getName() << " to " << m_cache << std::endl;
#endif
		}

		return val;
	}
};

/**
 * @brief Implements update when key is not found.
 *
 * The new value always can be written out
 */
class DefaultSetPolicy
{
public:
	static Key set(KeySet &ks, Key const& spec)
	{
		kdb::Key found = ks.lookup(spec.getName(), 0);

		if(!found)
		{
			kdb::Key k("user/"+spec.getName(), KEY_END);
			ks.append(k);
			found = k;
		}

		return found;
	}
};

class DefaultWritePolicy
{
public:
	static const bool allowed = true;
};

class ReadOnlyPolicy
{
public:
	static const bool allowed = false;
};

class DefaultObserverPolicy
{
public:
	typedef double type;
};

class NoLockPolicy
{
public:
	void lock() {}
	void unlock() {}
};

/**
 * This technique with the PolicySelector and Discriminator is taken
 * from the book  "C++ Templates - The Complete Guide"
 * by David Vandevoorde and Nicolai M. Josuttis, Addison-Wesley, 2002
 * in Chapter 16 Templates and Inheritance: Named Template Arguments
 *
 * The technique allows users of the class Value to use any number
 * and order of policies as desired.
 */
template <typename Base, int D>
class Discriminator : public Base
{
};

template < typename Setter1,
	   typename Setter2,
	   typename Setter3,
	   typename Setter4,
	   typename Setter5,
	   typename Setter6
	 >
class PolicySelector : public Discriminator<Setter1,1>,
		       public Discriminator<Setter2,2>,
		       public Discriminator<Setter3,3>,
		       public Discriminator<Setter4,4>,
		       public Discriminator<Setter5,5>,
		       public Discriminator<Setter6,6>
{
};

template<typename T>
class DefaultPolicies
{
public:
	typedef DefaultGetPolicy GetPolicy;
	typedef DefaultSetPolicy SetPolicy;
	typedef NoContext ContextPolicy;
	typedef DefaultWritePolicy WritePolicy;
	typedef DefaultObserverPolicy ObserverPolicy;
	typedef NoLockPolicy LockPolicy;
};

template<typename T>
class DefaultPolicyArgs : virtual public DefaultPolicies<T>
{
};

// class templates to override the default policy values

/// Needed by the user to set one of the policies
///
/// @tparam Policy
template <typename Policy>
class GetPolicyIs : virtual public DefaultPolicies<typename Policy::type>
{
public:
	typedef Policy GetPolicy;
};

/// Needed by the user to set one of the policies
///
/// @tparam Policy
template <typename Policy>
class SetPolicyIs : virtual public DefaultPolicies<typename Policy::type>
{
public:
	typedef Policy SetPolicy;
};

/// Needed by the user to set one of the policies
///
/// @tparam Policy
template <typename Policy>
class ContextPolicyIs : virtual public DefaultPolicies<typename Policy::type>
{
public:
	typedef Policy Context;
};

/// Needed by the user to set one of the policies
///
/// @tparam Policy
template <typename Policy>
class WritePolicyIs : virtual public DefaultPolicies<typename Policy::type>
{
public:
	typedef Policy WritePolicy;
};

/// Needed by the user to set one of the policies
///
/// @tparam Policy
template <typename Policy>
class ObserverPolicyIs : virtual public DefaultPolicies<typename Policy::type>
{
public:
	typedef Policy ObserverPolicy;
};

/// Needed by the user to set one of the policies
///
/// @tparam Policy
template <typename Policy>
class LockPolicyIs : virtual public DefaultPolicies<typename Policy::type>
{
public:
	typedef Policy LockPolicy;
};

// standard types

template<typename T,
	typename PolicySetter1 = DefaultPolicyArgs<T>,
	typename PolicySetter2 = DefaultPolicyArgs<T>,
	typename PolicySetter3 = DefaultPolicyArgs<T>,
	typename PolicySetter4 = DefaultPolicyArgs<T>,
	typename PolicySetter5 = DefaultPolicyArgs<T>,
	typename PolicySetter6 = DefaultPolicyArgs<T>
	>
class Value :
	public Observer
{
public:
	typedef T type;

	typedef PolicySelector<
		PolicySetter1,
		PolicySetter2,
		PolicySetter3,
		PolicySetter4,
		PolicySetter5,
		PolicySetter6
		>
		Policies;

	// not to be constructed yourself
	Value<T, PolicySetter1, PolicySetter2, PolicySetter3,
		PolicySetter4, PolicySetter5, PolicySetter6>
		(KeySet & ks, typename Policies::ContextPolicy & context_, kdb::Key spec) :
		m_cache(),
		m_ks(ks),
		m_context(context_),
		m_spec(spec)
	{
		assert(m_spec.getName()[0] == '/');
		m_spec.setMeta("name", m_spec.getName());
		ckdb::elektraKeySetName(*m_spec,
				m_context.evaluate(m_spec.getName()).c_str(),
				KEY_CASCADING_NAME);
		syncCache();  // read what we have in our context
		m_context.attachByName(m_spec.getMeta<std::string>("name"), *this);
	}

	Value<T, PolicySetter1, PolicySetter2, PolicySetter3,
		PolicySetter4, PolicySetter5, PolicySetter6>
		(Value<T> const & other, KeySet & ks) :
		m_cache(other.m_cache),
		m_ks(ks),
		m_context(other.m_context),
		m_spec(other.m_spec)
	{
		assert(m_spec.getName()[0] == '/');
		// cache already in sync
		// attach copy, too:
		m_context.attachByName(m_spec.getMeta<std::string>("name"), *this);
	}

	typedef Value<T, PolicySetter1, PolicySetter2, PolicySetter3,
		PolicySetter4, PolicySetter5, PolicySetter6> CV;

	CV const & operator= (type n)
	{
		static_assert(Policies::WritePolicy::allowed, "read only contextual value");
		m_cache = n;

		return *this;
	}

	type operator ++()
	{
		static_assert(Policies::WritePolicy::allowed, "read only contextual value");
		return ++m_cache;
	}

	type operator ++(int)
	{
		static_assert(Policies::WritePolicy::allowed, "read only contextual value");
		return m_cache++;
	}

	template < typename = typename std::enable_if< true >::type >
	operator type() const
	{
			return m_cache;
	}

	bool operator == (CV const & other) const
	{
		return m_cache == other.m_cache ;
	}

	type getDefault() const
	{
		return m_spec.getMeta<type>("default");
	}

	/// We allow manipulation of context for const
	/// objects
	typename Policies::ContextPolicy & context() const
	{
		return const_cast<typename Policies::ContextPolicy&>(m_context);
	}

	Key const& getSpec() const
	{
		return m_spec;
	}

	// keyset to cache
	void syncCache() const
	{
		m_cache = Policies::GetPolicy::get(m_ks, m_spec);
		// Policies::GetPolicy::get(this);
	}

	// cache to keyset
	void syncKeySet() const
	{
#if DEBUG && VERBOSE
		std::cout << "set name: " << m_spec.getName() << " to " << m_cache << std::endl;
#endif
		kdb::Key found = Policies::SetPolicy::set(m_ks, m_spec);
		if (found)
		{
			found.set<type>(m_cache);
		}
		// Policies::SetPolicy::set(this);
	}

private:
	virtual void update() const
	{
		// Policies::UpdatePolicy::update(this);
		typename Policies::LockPolicy lock;
		lock.lock();

		std::string evaluated_name = m_context.evaluate(m_spec.getMeta<std::string>("name"));
#if DEBUG && VERBOSE
		std::cout << "update " << evaluated_name << " from " << m_spec.getName() << std::endl;
#endif
		if (evaluated_name != m_spec.getName())
		{
			syncKeySet(); // flush out what currently is in cache
			ckdb::elektraKeySetName(*m_spec,
					evaluated_name.c_str(),
					KEY_CASCADING_NAME);
			syncCache();  // read what we have under new context
		}
		lock.unlock();
	}

private:
	mutable type m_cache;
	KeySet & m_ks;
	typename Policies::ContextPolicy & m_context;
	mutable Key m_spec;
	mutable Key m_key;
};

}

#endif
<|endoftext|>


<commit_before>#include <boost/program_options.hpp>
#include <iostream>
#include <string>

#include "config.h"
#include "uptane/secondaryfactory.h"
#include "uptane/secondaryinterface.h"

#include "ipsecondarydiscovery.h"
#include "ipuptaneconnection.h"
#include "ipuptaneconnectionsplitter.h"
#include "logging.h"

namespace po = boost::program_options;

int main(int argc, char **argv) {
  po::options_description desc("aktualizr_info command line options");
  // clang-format off
  desc.add_options()
    ("help,h", "print usage")
    ("config,c", po::value<std::string>(), "toml configuration file");
  // clang-format on

  try {
    logger_init();
    logger_set_threshold(boost::log::trivial::info);
    po::variables_map vm;
    po::basic_parsed_options<char> parsed_options = po::command_line_parser(argc, argv).options(desc).run();
    po::store(parsed_options, vm);
    po::notify(vm);
    if (vm.count("help") != 0) {
      std::cout << desc << '\n';
      exit(EXIT_SUCCESS);
    }

    std::string sota_config_file = "/usr/lib/sota/sota.toml";
    if (vm.count("config") != 0) {
      sota_config_file = vm["config"].as<std::string>();
    } else if (boost::filesystem::exists("/tmp/aktualizr_config_path")) {
      sota_config_file = Utils::readFile("/tmp/aktualizr_config_path");
    }

    boost::filesystem::path sota_config_path(sota_config_file);
    if (false == boost::filesystem::exists(sota_config_path)) {
      std::cout << "configuration file " << boost::filesystem::absolute(sota_config_path) << " not found. Exiting."
                << std::endl;
      exit(EXIT_FAILURE);
    }
    Config config(sota_config_path.string());

    IpSecondaryDiscovery ip_uptane_discovery{config.network};
    auto discovered = ip_uptane_discovery.discover();
    LOG_INFO << "Discovering finished";
    LOG_INFO << "Found " << discovered.size() << " devices";
    if (discovered.size()) {
      LOG_INFO << "Trying to connect with founded devices and get public key";
      IpUptaneConnection ip_uptane_connection(config.network.ipuptane_port);
      IpUptaneConnectionSplitter ip_uptane_splitter(ip_uptane_connection);

      std::vector<Uptane::SecondaryConfig>::const_iterator it;
      for (it = discovered.begin(); it != discovered.end(); ++it) {
        boost::shared_ptr<Uptane::SecondaryInterface> sec = Uptane::SecondaryFactory::makeSecondary(*it);
        if (it->secondary_type == Uptane::kIpUptane) {
          dynamic_cast<Uptane::IpUptaneSecondary *>(&(*sec))->connect(&ip_uptane_splitter);
          auto public_key = sec->getPublicKey();
          LOG_INFO << "Got public key from secondary: " << public_key.second;
        }
      }
      exit(EXIT_SUCCESS);
    }
    LOG_INFO << "Exiting";

  } catch (const po::error &o) {
    std::cout << o.what() << std::endl;
    std::cout << desc;
    return EXIT_FAILURE;
  }
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<commit_msg>fix utils according new changes<commit_after>#include <boost/program_options.hpp>
#include <iostream>
#include <string>

#include "config.h"
#include "uptane/secondaryfactory.h"
#include "uptane/secondaryinterface.h"

#include "ipsecondarydiscovery.h"
#include "ipuptaneconnection.h"
#include "ipuptaneconnectionsplitter.h"
#include "logging.h"

namespace po = boost::program_options;

int main(int argc, char **argv) {
  po::options_description desc("aktualizr_info command line options");
  // clang-format off
  desc.add_options()
    ("help,h", "print usage")
    ("config,c", po::value<std::string>(), "toml configuration file");
  // clang-format on

  try {
    logger_init();
    logger_set_threshold(boost::log::trivial::info);
    po::variables_map vm;
    po::basic_parsed_options<char> parsed_options = po::command_line_parser(argc, argv).options(desc).run();
    po::store(parsed_options, vm);
    po::notify(vm);
    if (vm.count("help") != 0) {
      std::cout << desc << '\n';
      exit(EXIT_SUCCESS);
    }

    std::string sota_config_file = "/usr/lib/sota/sota.toml";
    if (vm.count("config") != 0) {
      sota_config_file = vm["config"].as<std::string>();
    } else if (boost::filesystem::exists("/tmp/aktualizr_config_path")) {
      sota_config_file = Utils::readFile("/tmp/aktualizr_config_path");
    }

    boost::filesystem::path sota_config_path(sota_config_file);
    if (false == boost::filesystem::exists(sota_config_path)) {
      std::cout << "configuration file " << boost::filesystem::absolute(sota_config_path) << " not found. Exiting."
                << std::endl;
      exit(EXIT_FAILURE);
    }
    Config config(sota_config_path.string());

    IpSecondaryDiscovery ip_uptane_discovery{config.network};
    auto discovered = ip_uptane_discovery.discover();
    LOG_INFO << "Discovering finished";
    LOG_INFO << "Found " << discovered.size() << " devices";
    if (discovered.size()) {
      LOG_INFO << "Trying to connect with founded devices and get public key";
      IpUptaneConnection ip_uptane_connection(config.network.ipuptane_port);
      IpUptaneConnectionSplitter ip_uptane_splitter(ip_uptane_connection);

      std::vector<Uptane::SecondaryConfig>::const_iterator it;
      for (it = discovered.begin(); it != discovered.end(); ++it) {
        boost::shared_ptr<Uptane::SecondaryInterface> sec = Uptane::SecondaryFactory::makeSecondary(*it);
        if (it->secondary_type == Uptane::kIpUptane) {
          ip_uptane_splitter.registerSecondary(*dynamic_cast<Uptane::IpUptaneSecondary *>(&(*sec)));
          auto public_key = sec->getPublicKey();
          LOG_INFO << "Got public key from secondary: " << public_key.second;
        }
      }
      exit(EXIT_SUCCESS);
    }
    LOG_INFO << "Exiting";

  } catch (const po::error &o) {
    std::cout << o.what() << std::endl;
    std::cout << desc;
    return EXIT_FAILURE;
  }
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<|endoftext|>


<commit_before>/*

Copyright 2015-2019 Igor Petrovic

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

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

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

*/

#include "interface/display/Config.h"
#include "interface/digital/output/leds/Constants.h"
#include "Layout.h"

///
/// \brief Helper macro for easier entry and exit from system block.
/// Important: ::init must called before trying to use this macro.
///
#define SYSTEM_BLOCK_ENTER(code)                                                                    \
    {                                                                                \
        setStartAddress(0);                                                                         \
        LESSDB::setLayout(dbLayout, DB_BLOCKS + 1);                                                 \
        code                                                                                \
            LESSDB::setLayout(&dbLayout[1], DB_BLOCKS);                                             \
        setStartAddress(systemBlockUsage + ((totalMemoryUsage - systemBlockUsage) * activePreset)); \
    }

///
/// \brief Initializes database.
///
bool Database::init()
{
    setStartAddress(0);

    if (!LESSDB::setLayout(dbLayout, DB_BLOCKS + 1))
        return false;

    totalMemoryUsage = LESSDB::currentDBusage();
    systemBlockUsage = dbLayout[1].address;

    if (!isSignatureValid())
    {
        factoryReset(LESSDB::factoryResetType_t::full);
    }
    else
    {
        if (getPresetPreserveState())
        {
            SYSTEM_BLOCK_ENTER(
                activePreset = read(0, dbSection_system_settings, systemGlobal_ActivePreset);)
        }
        else
        {
            activePreset = 0;
        }

        setPreset(activePreset);
    }

    return true;
}

///
/// \brief Performs factory reset of data in database.
/// @param [in] type Factory reset type. See LESSDB::factoryResetType_t enumeration.
///
void Database::factoryReset(LESSDB::factoryResetType_t type)
{
    SYSTEM_BLOCK_ENTER(
        if (type == LESSDB::factoryResetType_t::full)
            clear();

        setDbUID(getDbUID());)

    for (int i = 0; i < getSupportedPresets(); i++)
    {
        setPreset(i);
        initData(type);
        writeCustomValues();
    }

    setPreset(0);
}

///
/// \brief Used to set new database layout (preset).
/// @param [in] preset  New preset to set.
/// \returns False if specified preset isn't supported, true otherwise.
///
bool Database::setPreset(uint8_t preset)
{
    if (preset >= getSupportedPresets())
        return false;

    activePreset = preset;

    SYSTEM_BLOCK_ENTER(
        update(0, dbSection_system_settings, systemGlobal_ActivePreset, preset);)

    if (presetChangeHandler != nullptr)
        presetChangeHandler(preset);

    return true;
}

///
/// \brief Retrieves currently active preset.
///
uint8_t Database::getPreset()
{
    return activePreset;
}

///
/// \brief Writes custom values to specific indexes which can't be generalized within database section.
///
void Database::writeCustomValues()
{
#ifdef DISPLAY_SUPPORTED
    update(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventTime, MIN_MESSAGE_RETENTION_TIME);
#endif
}

///
/// \brief Retrieves number of presets possible to store in database.
/// Preset is simply another database layout copy.
///
uint8_t Database::getSupportedPresets()
{
    return (dbSize() - systemBlockUsage) / (totalMemoryUsage - systemBlockUsage);
}

///
/// \brief Enables or disables preservation of preset setting.
/// If preservation is enabled, configured preset will be loaded on board power on.
/// Otherwise, first preset will be loaded instead.
///
void Database::setPresetPreserveState(bool state)
{
    SYSTEM_BLOCK_ENTER(
        update(0, dbSection_system_settings, systemGlobal_presetPreserve, state);)
}

///
/// \brief Checks if preset preservation setting is enabled or disabled.
/// \returns True if preset preservation is enabled, false otherwise.
///
bool Database::getPresetPreserveState()
{
    bool returnValue;

    SYSTEM_BLOCK_ENTER(
        returnValue = read(0, dbSection_system_settings, systemGlobal_presetPreserve);)

    return returnValue;
}

///
/// \brief Checks if database has been already initialized by checking DB_BLOCK_ID.
/// \returns True if valid, false otherwise.
///
bool Database::isSignatureValid()
{
    uint16_t signature;

    SYSTEM_BLOCK_ENTER(
        signature = read(0, dbSection_system_uid, 0);)

    return getDbUID() == signature;
}

///
/// \brief Calculates unique database ID.
/// UID is calculated by appending number of parameters and their types for all
/// sections and all blocks.
///
uint16_t Database::getDbUID()
{
///
/// \brief Magic value with which calculated signature is XORed.
///
#define DB_UID_BASE 0x1701

    uint16_t signature = 0;

    SYSTEM_BLOCK_ENTER(
        //get unique database signature based on its blocks/sections
        for (int i = 0; i < DB_BLOCKS + 1; i++) {
            for (int j = 0; j < dbLayout[i].numberOfSections; j++)
            {
                signature += dbLayout[i].section[i].numberOfParameters;
                signature += static_cast<uint16_t>(dbLayout[i].section[i].parameterType);
            }
        })

    return signature ^ DB_UID_BASE;
}

///
/// \brief Updates unique database UID.
/// UID is written to first two database locations.
/// @param [in] uid Database UID to set.
///
void Database::setDbUID(uint16_t uid)
{
    SYSTEM_BLOCK_ENTER(
        update(0, dbSection_system_uid, 0, uid);)
}

///
/// \brief Sets callback used to indicate that the preset has been changed.
///
void Database::setPresetChangeHandler(void (*presetChangeHandler)(uint8_t preset))
{
    this->presetChangeHandler = presetChangeHandler;
}<commit_msg>don't enter in system block when performing db clearing and UID setting<commit_after>/*

Copyright 2015-2019 Igor Petrovic

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

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

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

*/

#include "interface/display/Config.h"
#include "interface/digital/output/leds/Constants.h"
#include "Layout.h"

///
/// \brief Helper macro for easier entry and exit from system block.
/// Important: ::init must called before trying to use this macro.
///
#define SYSTEM_BLOCK_ENTER(code)                                                                    \
    {                                                                                \
        setStartAddress(0);                                                                         \
        LESSDB::setLayout(dbLayout, DB_BLOCKS + 1);                                                 \
        code                                                                                \
            LESSDB::setLayout(&dbLayout[1], DB_BLOCKS);                                             \
        setStartAddress(systemBlockUsage + ((totalMemoryUsage - systemBlockUsage) * activePreset)); \
    }

///
/// \brief Initializes database.
///
bool Database::init()
{
    setStartAddress(0);

    if (!LESSDB::setLayout(dbLayout, DB_BLOCKS + 1))
        return false;

    totalMemoryUsage = LESSDB::currentDBusage();
    systemBlockUsage = dbLayout[1].address;

    if (!isSignatureValid())
    {
        factoryReset(LESSDB::factoryResetType_t::full);
    }
    else
    {
        if (getPresetPreserveState())
        {
            SYSTEM_BLOCK_ENTER(
                activePreset = read(0, dbSection_system_settings, systemGlobal_ActivePreset);)
        }
        else
        {
            activePreset = 0;
        }

        setPreset(activePreset);
    }

    return true;
}

///
/// \brief Performs factory reset of data in database.
/// @param [in] type Factory reset type. See LESSDB::factoryResetType_t enumeration.
///
void Database::factoryReset(LESSDB::factoryResetType_t type)
{
    if (type == LESSDB::factoryResetType_t::full)
        clear();

    setDbUID(getDbUID());

    for (int i = 0; i < getSupportedPresets(); i++)
    {
        setPreset(i);
        initData(type);
        writeCustomValues();
    }

    setPreset(0);
}

///
/// \brief Used to set new database layout (preset).
/// @param [in] preset  New preset to set.
/// \returns False if specified preset isn't supported, true otherwise.
///
bool Database::setPreset(uint8_t preset)
{
    if (preset >= getSupportedPresets())
        return false;

    activePreset = preset;

    SYSTEM_BLOCK_ENTER(
        update(0, dbSection_system_settings, systemGlobal_ActivePreset, preset);)

    if (presetChangeHandler != nullptr)
        presetChangeHandler(preset);

    return true;
}

///
/// \brief Retrieves currently active preset.
///
uint8_t Database::getPreset()
{
    return activePreset;
}

///
/// \brief Writes custom values to specific indexes which can't be generalized within database section.
///
void Database::writeCustomValues()
{
#ifdef DISPLAY_SUPPORTED
    update(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventTime, MIN_MESSAGE_RETENTION_TIME);
#endif
}

///
/// \brief Retrieves number of presets possible to store in database.
/// Preset is simply another database layout copy.
///
uint8_t Database::getSupportedPresets()
{
    return (dbSize() - systemBlockUsage) / (totalMemoryUsage - systemBlockUsage);
}

///
/// \brief Enables or disables preservation of preset setting.
/// If preservation is enabled, configured preset will be loaded on board power on.
/// Otherwise, first preset will be loaded instead.
///
void Database::setPresetPreserveState(bool state)
{
    SYSTEM_BLOCK_ENTER(
        update(0, dbSection_system_settings, systemGlobal_presetPreserve, state);)
}

///
/// \brief Checks if preset preservation setting is enabled or disabled.
/// \returns True if preset preservation is enabled, false otherwise.
///
bool Database::getPresetPreserveState()
{
    bool returnValue;

    SYSTEM_BLOCK_ENTER(
        returnValue = read(0, dbSection_system_settings, systemGlobal_presetPreserve);)

    return returnValue;
}

///
/// \brief Checks if database has been already initialized by checking DB_BLOCK_ID.
/// \returns True if valid, false otherwise.
///
bool Database::isSignatureValid()
{
    uint16_t signature;

    SYSTEM_BLOCK_ENTER(
        signature = read(0, dbSection_system_uid, 0);)

    return getDbUID() == signature;
}

///
/// \brief Calculates unique database ID.
/// UID is calculated by appending number of parameters and their types for all
/// sections and all blocks.
///
uint16_t Database::getDbUID()
{
///
/// \brief Magic value with which calculated signature is XORed.
///
#define DB_UID_BASE 0x1701

    uint16_t signature = 0;

    SYSTEM_BLOCK_ENTER(
        //get unique database signature based on its blocks/sections
        for (int i = 0; i < DB_BLOCKS + 1; i++) {
            for (int j = 0; j < dbLayout[i].numberOfSections; j++)
            {
                signature += dbLayout[i].section[i].numberOfParameters;
                signature += static_cast<uint16_t>(dbLayout[i].section[i].parameterType);
            }
        })

    return signature ^ DB_UID_BASE;
}

///
/// \brief Updates unique database UID.
/// UID is written to first two database locations.
/// @param [in] uid Database UID to set.
///
void Database::setDbUID(uint16_t uid)
{
    SYSTEM_BLOCK_ENTER(
        update(0, dbSection_system_uid, 0, uid);)
}

///
/// \brief Sets callback used to indicate that the preset has been changed.
///
void Database::setPresetChangeHandler(void (*presetChangeHandler)(uint8_t preset))
{
    this->presetChangeHandler = presetChangeHandler;
}<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 *
 * table_factory.cpp
 * file description
 *
 * Copyright(c) 2015, CMU
 *
 *-------------------------------------------------------------------------
 */

#include "backend/bridge/bridge.h"
#include "backend/storage/table_factory.h"

#include "backend/common/exception.h"
#include "backend/common/logger.h"
#include "backend/index/index.h"
#include "backend/catalog/manager.h"
#include "backend/storage/data_table.h"

#include <mutex>

namespace nstore {
namespace storage {

DataTable* TableFactory::GetDataTable(oid_t database_oid,
                                      catalog::Schema* schema,
                                      std::string table_name,
                                      size_t tuples_per_tilegroup_count) {
    // create a new backend
    // FIXME: We need a better way of managing these. Why not just embed it in
    //        directly inside of the table object?
    AbstractBackend* backend = new VMBackend();

    DataTable *table =  new DataTable(schema, backend, table_name,
                                      tuples_per_tilegroup_count);
    table->database_id = database_oid;

    // Check if we need this table in the catalog
    if(database_oid != INVALID_OID){
        oid_t table_oid = GetRelationOidFromRelationName(table_name.c_str());
        catalog::Manager::GetInstance().SetLocation( database_oid, table_oid, table);
    }

    return table;

}

bool TableFactory::DropDataTable(oid_t database_oid, std::string table_name){

    oid_t table_oid = GetRelationOidFromRelationName(table_name.c_str());
<<<<<<< HEAD
    DataTable* table =  (nstore::storage::DataTable *)catalog::Manager::GetInstance().GetLocation(table_oid);
=======

    DataTable* table =  (DataTable*) catalog::Manager::GetInstance().GetLocation(database_oid, table_oid);
>>>>>>> 8b8be2c272b32b778bbc257a4ae6c461c6861428

    if(table == nullptr)
      return false;

    delete table;
    return true;
}

} // End storage namespace
} // End nstore namespace

<commit_msg>Resolve conflict<commit_after>/*-------------------------------------------------------------------------
 *
 * table_factory.cpp
 * file description
 *
 * Copyright(c) 2015, CMU
 *
 *-------------------------------------------------------------------------
 */

#include "backend/bridge/bridge.h"
#include "backend/storage/table_factory.h"

#include "backend/common/exception.h"
#include "backend/common/logger.h"
#include "backend/index/index.h"
#include "backend/catalog/manager.h"
#include "backend/storage/data_table.h"

#include <mutex>

namespace nstore {
namespace storage {

DataTable* TableFactory::GetDataTable(oid_t database_oid,
                                      catalog::Schema* schema,
                                      std::string table_name,
                                      size_t tuples_per_tilegroup_count) {
    // create a new backend
    // FIXME: We need a better way of managing these. Why not just embed it in
    //        directly inside of the table object?
    AbstractBackend* backend = new VMBackend();

    DataTable *table =  new DataTable(schema, backend, table_name,
                                      tuples_per_tilegroup_count);
    table->database_id = database_oid;

    // Check if we need this table in the catalog
    if(database_oid != INVALID_OID){
        oid_t table_oid = GetRelationOidFromRelationName(table_name.c_str());
        catalog::Manager::GetInstance().SetLocation( database_oid, table_oid, table);
    }

    return table;

}

bool TableFactory::DropDataTable(oid_t database_oid, std::string table_name){

    oid_t table_oid = GetRelationOidFromRelationName(table_name.c_str());

    DataTable* table =  (DataTable*) catalog::Manager::GetInstance().GetLocation(database_oid, table_oid);

    if(table == nullptr)
      return false;

    delete table;
    return true;
}

} // End storage namespace
} // End nstore namespace

<|endoftext|>


<commit_before>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "ViewShadowNode.h"
#include <react/renderer/components/view/primitives.h>

namespace facebook {
namespace react {

char const ViewComponentName[] = "View";

ViewShadowNode::ViewShadowNode(
    ShadowNodeFragment const &fragment,
    ShadowNodeFamily::Shared const &family,
    ShadowNodeTraits traits)
    : ConcreteViewShadowNode(fragment, family, traits) {
  initialize();
}

ViewShadowNode::ViewShadowNode(
    ShadowNode const &sourceShadowNode,
    ShadowNodeFragment const &fragment)
    : ConcreteViewShadowNode(sourceShadowNode, fragment) {
  initialize();
}

void ViewShadowNode::initialize() noexcept {
  auto &viewProps = static_cast<ViewProps const &>(*props_);

  bool formsStackingContext = !viewProps.collapsable ||
      viewProps.pointerEvents == PointerEventsMode::None ||
      !viewProps.nativeId.empty() || viewProps.accessible ||
      viewProps.opacity != 1.0 || viewProps.transform != Transform{} ||
      viewProps.elevation != 0 ||
      (viewProps.zIndex.has_value() &&
       viewProps.yogaStyle.positionType() != YGPositionTypeStatic) ||
      viewProps.yogaStyle.display() == YGDisplayNone ||
      viewProps.getClipsContentToBounds() ||
      isColorMeaningful(viewProps.shadowColor) ||
      viewProps.accessibilityElementsHidden ||
      viewProps.importantForAccessibility != ImportantForAccessibility::Auto ||
      viewProps.removeClippedSubviews;

  bool formsView = isColorMeaningful(viewProps.backgroundColor) ||
      isColorMeaningful(viewProps.foregroundColor) ||
      !(viewProps.yogaStyle.border() == YGStyle::Edges{}) ||
      !viewProps.testId.empty();

  formsView = formsView || formsStackingContext;

  if (formsView) {
    traits_.set(ShadowNodeTraits::Trait::FormsView);
  } else {
    traits_.unset(ShadowNodeTraits::Trait::FormsView);
  }

  if (formsStackingContext) {
    traits_.set(ShadowNodeTraits::Trait::FormsStackingContext);
  } else {
    traits_.unset(ShadowNodeTraits::Trait::FormsStackingContext);
  }
}

} // namespace react
} // namespace facebook
<commit_msg>Do not flatten view if prop accessibilityViewIsModal is true<commit_after>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "ViewShadowNode.h"
#include <react/renderer/components/view/primitives.h>

namespace facebook {
namespace react {

char const ViewComponentName[] = "View";

ViewShadowNode::ViewShadowNode(
    ShadowNodeFragment const &fragment,
    ShadowNodeFamily::Shared const &family,
    ShadowNodeTraits traits)
    : ConcreteViewShadowNode(fragment, family, traits) {
  initialize();
}

ViewShadowNode::ViewShadowNode(
    ShadowNode const &sourceShadowNode,
    ShadowNodeFragment const &fragment)
    : ConcreteViewShadowNode(sourceShadowNode, fragment) {
  initialize();
}

void ViewShadowNode::initialize() noexcept {
  auto &viewProps = static_cast<ViewProps const &>(*props_);

  bool formsStackingContext = !viewProps.collapsable ||
      viewProps.pointerEvents == PointerEventsMode::None ||
      !viewProps.nativeId.empty() || viewProps.accessible ||
      viewProps.opacity != 1.0 || viewProps.transform != Transform{} ||
      viewProps.elevation != 0 ||
      (viewProps.zIndex.has_value() &&
       viewProps.yogaStyle.positionType() != YGPositionTypeStatic) ||
      viewProps.yogaStyle.display() == YGDisplayNone ||
      viewProps.getClipsContentToBounds() ||
      isColorMeaningful(viewProps.shadowColor) ||
      viewProps.accessibilityElementsHidden ||
      viewProps.accessibilityViewIsModal ||
      viewProps.importantForAccessibility != ImportantForAccessibility::Auto ||
      viewProps.removeClippedSubviews;

  bool formsView = isColorMeaningful(viewProps.backgroundColor) ||
      isColorMeaningful(viewProps.foregroundColor) ||
      !(viewProps.yogaStyle.border() == YGStyle::Edges{}) ||
      !viewProps.testId.empty();

  formsView = formsView || formsStackingContext;

  if (formsView) {
    traits_.set(ShadowNodeTraits::Trait::FormsView);
  } else {
    traits_.unset(ShadowNodeTraits::Trait::FormsView);
  }

  if (formsStackingContext) {
    traits_.set(ShadowNodeTraits::Trait::FormsStackingContext);
  } else {
    traits_.unset(ShadowNodeTraits::Trait::FormsStackingContext);
  }
}

} // namespace react
} // namespace facebook
<|endoftext|>


<commit_before>//
// Created by iskakoff on 19/07/16.
//
#include <iostream>
#include <iomanip>

#include <edlib/EDParams.h>
#include <edlib/HDF5Utils.h>
#include <edlib/ChiLoc.h>
#include "edlib/Hamiltonian.h"
#include "edlib/GreensFunction.h"
#include "edlib/StateDescription.h"

int main(int argc, const char ** argv) {
#ifdef USE_MPI
  MPI_Init(&argc, (char ***) &argv);
  alps::mpi::communicator comm;
#endif
  alps::params params(argc, argv);
  EDLib::define_parameters(params);
  if(params.help_requested(std::cout)) {
    exit(0);
  }
  alps::hdf5::archive ar(params["OUTPUT_FILE"], alps::hdf5::archive::WRITE);
#ifdef USE_MPI
  if(comm.rank())
    ar.close();
#endif
  try {
#ifdef USE_MPI
    EDLib::SRSSIAMHamiltonian ham(params, comm);
#else
    EDLib::SRSSIAMHamiltonian ham(params);
#endif
    ham.diag();
    EDLib::hdf5::save_eigen_pairs(ham, ar, "results");
    EDLib::gf::GreensFunction < EDLib::SRSSIAMHamiltonian, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> greensFunction(params, ham,alps::gf::statistics::statistics_type::FERMIONIC);
    greensFunction.compute();
    greensFunction.save(ar, "results");
    EDLib::gf::ChiLoc<EDLib::SRSSIAMHamiltonian, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> susc(params, ham, alps::gf::statistics::statistics_type::BOSONIC);
    susc.compute();
    susc.save(ar, "results");
    susc.compute<EDLib::gf::NOperator<double> >();
    susc.save(ar, "results");
  } catch (std::exception & e) {
#ifdef USE_MPI
    if(comm.rank() == 0) std::cerr<<e.what();
#else
    std::cerr<<e.what();
#endif
  }
#ifdef USE_MPI
  if(!comm.rank())
#endif
  ar.close();
#ifdef USE_MPI
  MPI_Finalize();
#endif
  return 0;
}
<commit_msg>Update Anderson.cpp<commit_after>//
// Created by iskakoff on 19/07/16.
//
#include <iostream>

#include <edlib/EDParams.h>
#include "edlib/Hamiltonian.h"
#include "edlib/SzSymmetry.h"
#include "edlib/SOCRSStorage.h"
#include "edlib/CRSStorage.h"
#include "edlib/HubbardModel.h"
#include "edlib/GreensFunction.h"
#include "edlib/ChiLoc.h"
#include "edlib/HDF5Utils.h"
#include "edlib/SpinResolvedStorage.h"
#include "edlib/StateDescription.h"
#include "edlib/MeshFactory.h"

int main(int argc, const char ** argv) {
#ifdef USE_MPI
  MPI_Init(&argc, (char ***) &argv);
  alps::mpi::communicator comm;
#endif
  alps::params params(argc, argv);
  EDLib::define_parameters(params);
  if(params.help_requested(std::cout)) {
    exit(0);
  }
  alps::hdf5::archive ar(params["OUTPUT_FILE"], alps::hdf5::archive::WRITE);
#ifdef USE_MPI
  if(comm.rank())
    ar.close();
#endif
  try {
#ifdef USE_MPI
    EDLib::SRSSIAMHamiltonian ham(params, comm);
#else
    EDLib::SRSSIAMHamiltonian ham(params);
#endif
    ham.diag();
    EDLib::hdf5::save_eigen_pairs(ham, ar, "results");
    EDLib::gf::GreensFunction < EDLib::SRSSIAMHamiltonian, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> greensFunction(params, ham,alps::gf::statistics::statistics_type::FERMIONIC);
    greensFunction.compute();
    greensFunction.save(ar, "results");
    EDLib::gf::ChiLoc<EDLib::SRSSIAMHamiltonian, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> susc(params, ham, alps::gf::statistics::statistics_type::BOSONIC);
    susc.compute();
    susc.save(ar, "results");
    susc.compute<EDLib::gf::NOperator<double> >();
    susc.save(ar, "results");
  } catch (std::exception & e) {
#ifdef USE_MPI
    if(comm.rank() == 0) std::cerr<<e.what();
#else
    std::cerr<<e.what();
#endif
  }
#ifdef USE_MPI
  if(!comm.rank())
#endif
  ar.close();
#ifdef USE_MPI
  MPI_Finalize();
#endif
  return 0;
}
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

#include <proton/connection.hpp>
#include <proton/connection_options.hpp>
#include <proton/container.hpp>
#include <proton/default_container.hpp>
#include <proton/delivery.hpp>
#include <proton/link.hpp>
#include <proton/listener.hpp>
#include <proton/message.hpp>
#include <proton/message_id.hpp>
#include <proton/messaging_handler.hpp>
#include <proton/thread_safe.hpp>
#include <proton/tracker.hpp>
#include <proton/value.hpp>
#include <proton/receiver_options.hpp>

#include <assert.h>
#include <chrono>
#include <iostream>
#include <sstream>

long now() {
    return std::chrono::duration_cast<std::chrono::milliseconds>
        (std::chrono::system_clock::now().time_since_epoch()).count();
}

void eprint(std::string message) {
    std::cerr << "quiver-arrow: error: " << message << std::endl;
}

struct handler : public proton::messaging_handler {
    std::string connection_mode;
    std::string channel_mode;
    std::string operation;
    std::string id;
    std::string host;
    std::string port;
    std::string path;
    int messages;
    int body_size;
    int credit_window;

    proton::listener listener;
    proton::binary body;

    int sent = 0;
    int received = 0;
    int accepted = 0;

    void on_container_start(proton::container& c) override {
        std::string domain = host + ":" + port;

        proton::connection_options opts;
        opts.sasl_allowed_mechs("ANONYMOUS");

        if (connection_mode == "client") {
            c.connect(domain, opts);
        } else if (connection_mode == "server") {
            listener = c.listen(domain, opts);
        } else {
            throw std::exception();
        }

        body = std::string(body_size, 'x');
    }

    void on_connection_open(proton::connection& c) override {
        if (channel_mode == "active") {
            if (operation == "send") {
                c.open_sender(path);
            } else if (operation == "receive") {
                proton::receiver_options opts;
                opts.credit_window(credit_window);

                c.open_receiver(path, opts);
            } else {
                throw std::exception();
            }
        }
    }

    void on_sendable(proton::sender& s) override {
        assert (operation == "send");

        while (s.credit() && sent < messages) {
            int id = sent + 1;
            long stime = now();

            proton::message m(body);
            m.id(id);
            m.properties().put("SendTime", stime);

            s.send(m);
            sent++;

            std::cout << id << "," << stime << "\n";
        }
    }

    void on_tracker_accept(proton::tracker& t) override {
        accepted++;

        if (accepted == messages) {
            t.connection().close();

            if (connection_mode == "server") {
                listener.stop();
            }
        }
    }

    void on_message(proton::delivery& d, proton::message& m) override {
        assert (operation == "receive");

        if (received == messages) {
            return;
        }

        received++;

        proton::message_id id = m.id();
        proton::scalar stime = m.properties().get("SendTime");
        long rtime = now();

        std::cout << id << "," << stime << "," << rtime << "\n";

        if (received == messages) {
            d.connection().close();

            if (connection_mode == "server") {
                listener.stop();
            }
        }
    }
};

int main(int argc, char** argv) {
    handler h;

    h.connection_mode = argv[1];
    h.channel_mode = argv[2];
    h.operation = argv[3];
    h.id = argv[4];
    h.host = argv[5];
    h.port = argv[6];
    h.path = argv[7];
    h.messages = std::atoi(argv[8]);
    h.body_size = std::atoi(argv[9]);
    h.credit_window = std::atoi(argv[10]);

    try {
        proton::default_container(h, h.id).run();
    } catch (const std::exception& e) {
        eprint(e.what());
        return 1;
    }

    return 0;
}
<commit_msg>More literate<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

#include <proton/connection.hpp>
#include <proton/connection_options.hpp>
#include <proton/container.hpp>
#include <proton/default_container.hpp>
#include <proton/delivery.hpp>
#include <proton/link.hpp>
#include <proton/listener.hpp>
#include <proton/message.hpp>
#include <proton/message_id.hpp>
#include <proton/messaging_handler.hpp>
#include <proton/thread_safe.hpp>
#include <proton/tracker.hpp>
#include <proton/value.hpp>
#include <proton/receiver_options.hpp>

#include <assert.h>
#include <chrono>
#include <iostream>
#include <sstream>

long now() {
    return std::chrono::duration_cast<std::chrono::milliseconds>
        (std::chrono::system_clock::now().time_since_epoch()).count();
}

void eprint(std::string message) {
    std::cerr << "quiver-arrow: error: " << message << std::endl;
}

struct handler : public proton::messaging_handler {
    std::string connection_mode;
    std::string channel_mode;
    std::string operation;
    std::string id;
    std::string host;
    std::string port;
    std::string path;
    int messages;
    int body_size;
    int credit_window;

    proton::listener listener;
    proton::binary body;

    int sent = 0;
    int received = 0;
    int accepted = 0;

    void on_container_start(proton::container& c) override {
        std::string domain = host + ":" + port;

        proton::connection_options opts;
        opts.sasl_allowed_mechs("ANONYMOUS");

        if (connection_mode == "client") {
            c.connect(domain, opts);
        } else if (connection_mode == "server") {
            listener = c.listen(domain, opts);
        } else {
            throw std::exception();
        }

        body = std::string(body_size, 'x');
    }

    void on_connection_open(proton::connection& c) override {
        if (channel_mode == "active") {
            if (operation == "send") {
                c.open_sender(path);
            } else if (operation == "receive") {
                proton::receiver_options opts;
                opts.credit_window(credit_window);

                c.open_receiver(path, opts);
            } else {
                throw std::exception();
            }
        }
    }

    void on_sendable(proton::sender& s) override {
        assert (operation == "send");

        while (s.credit() > 0 && sent < messages) {
            int id = sent + 1;
            long stime = now();

            proton::message m(body);
            m.id(id);
            m.properties().put("SendTime", stime);

            s.send(m);
            sent++;

            std::cout << id << "," << stime << "\n";
        }
    }

    void on_tracker_accept(proton::tracker& t) override {
        accepted++;

        if (accepted == messages) {
            t.connection().close();

            if (connection_mode == "server") {
                listener.stop();
            }
        }
    }

    void on_message(proton::delivery& d, proton::message& m) override {
        assert (operation == "receive");

        if (received == messages) {
            return;
        }

        received++;

        proton::message_id id = m.id();
        proton::scalar stime = m.properties().get("SendTime");
        long rtime = now();

        std::cout << id << "," << stime << "," << rtime << "\n";

        if (received == messages) {
            d.connection().close();

            if (connection_mode == "server") {
                listener.stop();
            }
        }
    }
};

int main(int argc, char** argv) {
    handler h;

    h.connection_mode = argv[1];
    h.channel_mode = argv[2];
    h.operation = argv[3];
    h.id = argv[4];
    h.host = argv[5];
    h.port = argv[6];
    h.path = argv[7];
    h.messages = std::atoi(argv[8]);
    h.body_size = std::atoi(argv[9]);
    h.credit_window = std::atoi(argv[10]);

    try {
        proton::default_container(h, h.id).run();
    } catch (const std::exception& e) {
        eprint(e.what());
        return 1;
    }

    return 0;
}
<|endoftext|>


<commit_before>#ifndef VIENNAGRID_ELEMENT_KEY_HPP
#define VIENNAGRID_ELEMENT_KEY_HPP

/* =======================================================================
   Copyright (c) 2011-2012, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at
                 Josef Weinbub                    weinbub@iue.tuwien.ac.at

   (A list of additional contributors can be found in the PDF manual)

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#include <map>
#include <iostream>
#include <algorithm>

#include "viennagrid/forwards.hpp"
#include "viennagrid/element/element.hpp"
#include "viennagrid/topology/point.hpp"

#include "viennagrid/storage/container.hpp"
#include "viennagrid/storage/hidden_key_map.hpp"

/** @file element_key.hpp
    @brief Provides a key that uniquely identifies n-cells
*/

namespace viennagrid
{

  /** @brief A key type that uniquely identifies an element by its vertices */
  //template <typename ConfigType, typename ElementType>
  template <typename element_type, typename id_type>
  class element_key
  {
      typedef typename element_type::tag            ElementTag;
      //typedef typename ElementKeyStorageType<ConfigType, ElementType>::result_type  StorageType;
    public:
      element_key( const element_type & el2) : vertex_ids(topology::bndcells<ElementTag, 0>::num)
      {
            //typedef typename element_type::vertex_container_type vertex_container_type;
            typedef typename viennagrid::result_of::const_ncell_range< element_type, 0 >::type vertex_range;
            typedef typename viennagrid::result_of::const_iterator< vertex_range >::type const_iterator;
            //typedef typename vertex_container_type::const_iterator const_iterator;
            //typedef typename vertex_container_type::const_hook_iterator const_hook_iterator;

        //typedef typename result_of::const_ncell_range<element_type, 0>::type       VertexConstRange;
        //typedef typename result_of::iterator<VertexConstRange>::type          VertexConstIterator;
        long i = 0;
        vertex_range & vertices_el2 = ncells<0>(el2);
        for (const_iterator vit = vertices_el2.begin();
             vit != vertices_el2.end();
             ++vit, ++i)
          vertex_ids[i] = static_cast<id_type>( (*vit).id() );
        //sort it:
        std::sort(vertex_ids.begin(), vertex_ids.end());
      }

      element_key( const element_key & ek2) : vertex_ids(ek2.vertex_ids.size())
      {
        //std::cout << "Copy constructor ElementKey " << this << std::endl;
        for (typename std::vector<id_type>::size_type i=0; i<ek2.vertex_ids.size(); ++i)
          vertex_ids[i] = ek2.vertex_ids[i];
      }

      bool operator < (element_key const & epc2) const
      {
        for (long i=0; i<topology::bndcells<ElementTag, 0>::num; ++i)
        {
          if ( vertex_ids[i] > epc2.vertex_ids[i] )
            return false;
          else if ( vertex_ids[i] < epc2.vertex_ids[i] )
            return true;
        }
        return false;
      }

      void print() const
      {
        for (typename std::vector<id_type>::const_iterator vit = vertex_ids.begin();
              vit != vertex_ids.end();
              ++vit)
          std::cout << *vit << " ";
        std::cout << std::endl;
      }

    private:
        // TODO: statt std::vector abhängig vom element_type
      std::vector< id_type > vertex_ids;
  };
}

namespace viennagrid
{
    namespace storage
    {
        template<typename id_type>
        struct element_key_tag {};

        namespace result_of
        {
            template<typename element_type, typename id_type>
            struct hidden_key_map_key_type_from_tag<element_type, element_key_tag<id_type> >
            {
                typedef element_key<element_type, id_type> type;
            };

        }
    }

}

#endif
<commit_msg>element_key now only has 1 template argument (id is not necessary)<commit_after>#ifndef VIENNAGRID_ELEMENT_KEY_HPP
#define VIENNAGRID_ELEMENT_KEY_HPP

/* =======================================================================
   Copyright (c) 2011-2012, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at
                 Josef Weinbub                    weinbub@iue.tuwien.ac.at

   (A list of additional contributors can be found in the PDF manual)

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#include <map>
#include <iostream>
#include <algorithm>

#include "viennagrid/forwards.hpp"
#include "viennagrid/element/element.hpp"
#include "viennagrid/topology/point.hpp"

#include "viennagrid/storage/container.hpp"
#include "viennagrid/storage/hidden_key_map.hpp"

/** @file element_key.hpp
    @brief Provides a key that uniquely identifies n-cells
*/

namespace viennagrid
{

  /** @brief A key type that uniquely identifies an element by its vertices */
  //template <typename ConfigType, typename ElementType>
  template <typename element_type>
  class element_key
  {
      typedef typename element_type::tag            ElementTag;
      typedef typename viennagrid::result_of::ncell< element_type, 0 >::type vertex_type;
      typedef typename vertex_type::id_type id_type;
      //typedef typename viennagrid::storage::result_of::id<vertex_type, id_tag>::type id_type;

      //typedef typename ElementKeyStorageType<ConfigType, ElementType>::result_type  StorageType;
    public:

      element_key( const element_type & el2) : vertex_ids(topology::bndcells<ElementTag, 0>::num)
      {
            //typedef typename element_type::vertex_container_type vertex_container_type;
            typedef typename viennagrid::result_of::const_ncell_range< element_type, 0 >::type vertex_range;
            typedef typename viennagrid::result_of::const_iterator< vertex_range >::type const_iterator;
            //typedef typename vertex_container_type::const_iterator const_iterator;
            //typedef typename vertex_container_type::const_hook_iterator const_hook_iterator;

        //typedef typename result_of::const_ncell_range<element_type, 0>::type       VertexConstRange;
        //typedef typename result_of::iterator<VertexConstRange>::type          VertexConstIterator;
        long i = 0;
        vertex_range & vertices_el2 = ncells<0>(el2);
        for (const_iterator vit = vertices_el2.begin();
             vit != vertices_el2.end();
             ++vit, ++i)
          vertex_ids[i] = static_cast<id_type>( (*vit).id() );
        //sort it:
        std::sort(vertex_ids.begin(), vertex_ids.end());
      }

      element_key( const element_key & ek2) : vertex_ids(ek2.vertex_ids.size())
      {
        //std::cout << "Copy constructor ElementKey " << this << std::endl;
        for (typename std::vector<id_type>::size_type i=0; i<ek2.vertex_ids.size(); ++i)
          vertex_ids[i] = ek2.vertex_ids[i];
      }

      bool operator < (element_key const & epc2) const
      {
        for (long i=0; i<topology::bndcells<ElementTag, 0>::num; ++i)
        {
          if ( vertex_ids[i] > epc2.vertex_ids[i] )
            return false;
          else if ( vertex_ids[i] < epc2.vertex_ids[i] )
            return true;
        }
        return false;
      }

      void print() const
      {
        for (typename std::vector<id_type>::const_iterator vit = vertex_ids.begin();
              vit != vertex_ids.end();
              ++vit)
          std::cout << *vit << " ";
        std::cout << std::endl;
      }

    private:
        // TODO: statt std::vector abhängig vom element_type
      std::vector< id_type > vertex_ids;
  };
}

namespace viennagrid
{
    namespace storage
    {
        struct element_key_tag {};

        namespace result_of
        {
            template<typename element_type>
            struct hidden_key_map_key_type_from_tag<element_type, element_key_tag>
            {
                typedef element_key<element_type> type;
            };

        }
    }

}

#endif
<|endoftext|>


<commit_before>///////
#include <bela/base.hpp>
#include <bela/escapeargv.hpp>
#include <bela/picker.hpp>
#include <windowsx.h> // box help
#include <vector>
#include "appui.hpp"

bool Execute(wchar_t *command) {
  PROCESS_INFORMATION pi;
  STARTUPINFOW si;
  ZeroMemory(&si, sizeof(si));
  ZeroMemory(&pi, sizeof(pi));
  si.cb = sizeof(si);
  si.dwFlags = STARTF_USESHOWWINDOW;
  si.wShowWindow = SW_SHOW;
#if defined(_M_IX86) || defined(_M_ARM)
  //// Only x86,ARM on Windows 64/ARM64
  clangbuilder::FsRedirection fsRedirection;
#endif
  if (CreateProcessW(nullptr, command, NULL, NULL, FALSE,
                     CREATE_NEW_CONSOLE | NORMAL_PRIORITY_CLASS, NULL, NULL,
                     &si, &pi) != TRUE) {
    return false;
  }
  CloseHandle(pi.hThread);
  CloseHandle(pi.hProcess);
  return true;
}

bool MainWindow::InitializeElemets() {
  // TODO initialize target
  tables.Targets = {L"x86", L"x64", L"ARM", L"ARM64"};
  tables.Configurations = {L"Release", L"MinSizeRel", L"RelWithDebInfo",
                           L"Debug"};
  tables.AddEngine(L"Ninja - MSVC", L"Ninja")
      .AddEngine(L"Ninja - Clang", L"NinjaIterate")
      .AddEngine(L"MSBuild - MSVC", L"MSBuild")
      .AddEngine(L"Ninja - Bootstrap", L"NinjaBootstrap");
  tables.Branches = {L"Mainline", L"Stable", L"Release"};
  return search.Execute(root, settings.EnterpriseWDK());
}

LRESULT MainWindow::OnBuildNow(WORD wNotifyCode, WORD wID, HWND hWndCtl,
                               BOOL &bHandled) {
  auto pwshexe = settings.PwshExePath();
  if (pwshexe.empty()) {
    bela::BelaMessageBox(m_hWnd, L"Unable to find installed powershell",
                         L"Please check if powershell is installed correctly",
                         nullptr, bela::mbs_t::FATAL);

    return S_FALSE;
  }

  auto vsindex_ = ComboBox_GetCurSel(hvsbox.hWnd);
  if (vsindex_ < 0 || search.Size() <= (size_t)vsindex_) {
    return S_FALSE;
  }
  auto archindex_ = ComboBox_GetCurSel(htargetbox.hWnd);
  if (archindex_ < 0 || tables.Targets.size() <= archindex_) {
    return S_FALSE;
  }

  auto flavor_ = ComboBox_GetCurSel(hconfigbox.hWnd);
  if (flavor_ < 0 || tables.Configurations.size() <= flavor_) {
    return S_FALSE;
  }

  auto be = ComboBox_GetCurSel(hbuildbox.hWnd);
  if (be < 0 || tables.Engines.size() <= be) {
    return S_FALSE;
  }

  auto bs = ComboBox_GetCurSel(hbranchbox.hWnd);
  if (bs < 0 || tables.Branches.size() <= bs) {
    return S_FALSE;
  }

  bela::EscapeArgv ea;
  if (!settings.Terminal().empty()) {
    ea.Assign(settings.Terminal());
  }
  ea.Append(pwshexe)
      .Append(L"-NoLogo")
      .Append(L"-NoExit")
      .Append(L"-File")
      .Append(targetFile)
      .Append(L"-InstanceId")
      .Append(search.InstanceId(vsindex_))
      .Append(L"-InstallationVersion")
      .Append(search.InstallVersion(vsindex_))
      .Append(L"-Arch")
      .Append(tables.Targets[archindex_])
      .Append(L"-Flavor")
      .Append(tables.Configurations[flavor_])
      .Append(L"-Engine")
      .Append(tables.Engines[be].Value)
      .Append(L"-Branch")
      .Append(tables.Branches[bs]);

  if ((be == 1 || be == 3) && Button_GetCheck(hlibcxx.hWnd) == BST_CHECKED) {
    ea.Append(L"-Libcxx");
  }

  if (Button_GetCheck(hlto.hWnd) == BST_CHECKED) {
    ea.Append(L"-LTO");
  }

  if (Button_GetCheck(hcpack.hWnd) == BST_CHECKED) {
    ea.Append(L"-Package");
  }

  if (Button_GetCheck(hlldb.hWnd) == BST_CHECKED) {
    ea.Append(L"-LLDB");
  }

  if (Button_GetCheck(hcleanenv.hWnd) == BST_CHECKED) {
    ea.Append(L"-ClearEnv");
  }
  if (!Execute(ea.data())) {
    auto ec = bela::make_system_error_code();
    bela::BelaMessageBox(m_hWnd, L"CreateProcess failed", ec.message.data(),
                         nullptr, bela::mbs_t::FATAL);
  }
  return S_OK;
}

LRESULT MainWindow::OnStartupEnv(WORD wNotifyCode, WORD wID, HWND hWndCtl,
                                 BOOL &bHandled) {

  auto pwshexe = settings.PwshExePath();
  if (pwshexe.empty()) {
    bela::BelaMessageBox(m_hWnd, L"Unable to find installed powershell",
                         L"Please check if powershell is installed correctly",
                         nullptr, bela::mbs_t::FATAL);
    return S_FALSE;
  }

  auto vsindex_ = ComboBox_GetCurSel(hvsbox.hWnd);
  if (vsindex_ < 0 || search.Size() <= (size_t)vsindex_) {
    return S_FALSE;
  }
  auto archindex_ = ComboBox_GetCurSel(htargetbox.hWnd);
  if (archindex_ < 0 || tables.Targets.size() <= archindex_) {
    return S_FALSE;
  }

  bela::EscapeArgv ea;
  if (!settings.Terminal().empty()) {
    ea.Assign(settings.Terminal());
  }
  ea.Append(pwshexe)
      .Append(L"-NoLogo")
      .Append(L"-NoExit")
      .Append(L"-File")
      .Append(targetFile)
      .Append(L"-Environment")
      .Append(L"-InstanceId")
      .Append(search.InstanceId(vsindex_))
      .Append(L"-InstallationVersion")
      .Append(search.InstallVersion(vsindex_))
      .Append(L"-Arch")
      .Append(tables.Targets[archindex_]);
  if (Button_GetCheck(hcleanenv.hWnd) == BST_CHECKED) {
    ea.Append(L"-ClearEnv");
  }
  if (!Execute(ea.data())) {
    auto ec = bela::make_system_error_code();
    bela::BelaMessageBox(m_hWnd, L"CreateProcess failed", ec.message.data(),
                         nullptr, bela::mbs_t::FATAL);
  }
  return S_OK;
}
<commit_msg>[clangbuilder] avoid windows terminal incorrect parse subcommand<commit_after>///////
#include <bela/base.hpp>
#include <bela/escapeargv.hpp>
#include <bela/picker.hpp>
#include <windowsx.h> // box help
#include <vector>
#include <filesystem>
#include "appui.hpp"

bool Execute(wchar_t *command, const wchar_t *cwd) {
  PROCESS_INFORMATION pi;
  STARTUPINFOW si;
  SecureZeroMemory(&si, sizeof(si));
  SecureZeroMemory(&pi, sizeof(pi));
  si.cb = sizeof(si);
#if defined(_M_IX86) || defined(_M_ARM)
  //// Only x86,ARM on Windows 64/ARM64
  clangbuilder::FsRedirection fsRedirection;
#endif
  if (CreateProcessW(nullptr, command, nullptr, nullptr, FALSE, CREATE_UNICODE_ENVIRONMENT, nullptr,
                     cwd, &si, &pi) != TRUE) {
    auto ec = bela::make_system_error_code();
    bela::BelaMessageBox(nullptr, L"unable open Windows Terminal", ec.data(), nullptr,
                         bela::mbs_t::FATAL);
    return false;
  }
  CloseHandle(pi.hThread);
  CloseHandle(pi.hProcess);
  return true;
}

bool MainWindow::InitializeElemets() {
  // TODO initialize target
  tables.Targets = {L"x86", L"x64", L"ARM", L"ARM64"};
  tables.Configurations = {L"Release", L"MinSizeRel", L"RelWithDebInfo", L"Debug"};
  tables.AddEngine(L"Ninja - MSVC", L"Ninja")
      .AddEngine(L"Ninja - Clang", L"NinjaIterate")
      .AddEngine(L"MSBuild - MSVC", L"MSBuild")
      .AddEngine(L"Ninja - Bootstrap", L"NinjaBootstrap");
  tables.Branches = {L"Mainline", L"Stable", L"Release"};
  return search.Execute(root, settings.EnterpriseWDK());
}

LRESULT MainWindow::OnBuildNow(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL &bHandled) {
  auto pwshexe = settings.PwshExePath();
  if (pwshexe.empty()) {
    bela::BelaMessageBox(m_hWnd, L"Unable to find installed powershell",
                         L"Please check if powershell is installed correctly", nullptr,
                         bela::mbs_t::FATAL);

    return S_FALSE;
  }

  auto vsindex_ = ComboBox_GetCurSel(hvsbox.hWnd);
  if (vsindex_ < 0 || search.Size() <= (size_t)vsindex_) {
    return S_FALSE;
  }
  auto archindex_ = ComboBox_GetCurSel(htargetbox.hWnd);
  if (archindex_ < 0 || tables.Targets.size() <= archindex_) {
    return S_FALSE;
  }

  auto flavor_ = ComboBox_GetCurSel(hconfigbox.hWnd);
  if (flavor_ < 0 || tables.Configurations.size() <= flavor_) {
    return S_FALSE;
  }

  auto be = ComboBox_GetCurSel(hbuildbox.hWnd);
  if (be < 0 || tables.Engines.size() <= be) {
    return S_FALSE;
  }

  auto bs = ComboBox_GetCurSel(hbranchbox.hWnd);
  if (bs < 0 || tables.Branches.size() <= bs) {
    return S_FALSE;
  }
  auto cwd = std::filesystem::path(targetFile).parent_path().wstring();
  bela::EscapeArgv ea;
  if (settings.UseWindowsTerminal()) {
    ea.Assign(settings.Terminal()).Append(L"--startingDirectory").Append(cwd).Append(L"--");
  }
  ea.Append(pwshexe)
      .Append(L"-NoLogo")
      .Append(L"-NoExit")
      .Append(L"-File")
      .Append(targetFile)
      .Append(L"-InstanceId")
      .Append(search.InstanceId(vsindex_))
      .Append(L"-InstallationVersion")
      .Append(search.InstallVersion(vsindex_))
      .Append(L"-Arch")
      .Append(tables.Targets[archindex_])
      .Append(L"-Flavor")
      .Append(tables.Configurations[flavor_])
      .Append(L"-Engine")
      .Append(tables.Engines[be].Value)
      .Append(L"-Branch")
      .Append(tables.Branches[bs]);

  if ((be == 1 || be == 3) && Button_GetCheck(hlibcxx.hWnd) == BST_CHECKED) {
    ea.Append(L"-Libcxx");
  }

  if (Button_GetCheck(hlto.hWnd) == BST_CHECKED) {
    ea.Append(L"-LTO");
  }

  if (Button_GetCheck(hcpack.hWnd) == BST_CHECKED) {
    ea.Append(L"-Package");
  }

  if (Button_GetCheck(hlldb.hWnd) == BST_CHECKED) {
    ea.Append(L"-LLDB");
  }

  if (Button_GetCheck(hcleanenv.hWnd) == BST_CHECKED) {
    ea.Append(L"-ClearEnv");
  }
  if (!Execute(ea.data(), cwd.data())) {
    auto ec = bela::make_system_error_code();
    bela::BelaMessageBox(m_hWnd, L"CreateProcess failed", ec.message.data(), nullptr,
                         bela::mbs_t::FATAL);
  }
  return S_OK;
}

LRESULT MainWindow::OnStartupEnv(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL &bHandled) {

  auto pwshexe = settings.PwshExePath();
  if (pwshexe.empty()) {
    bela::BelaMessageBox(m_hWnd, L"Unable to find installed powershell",
                         L"Please check if powershell is installed correctly", nullptr,
                         bela::mbs_t::FATAL);
    return S_FALSE;
  }

  auto vsindex_ = ComboBox_GetCurSel(hvsbox.hWnd);
  if (vsindex_ < 0 || search.Size() <= (size_t)vsindex_) {
    return S_FALSE;
  }
  auto archindex_ = ComboBox_GetCurSel(htargetbox.hWnd);
  if (archindex_ < 0 || tables.Targets.size() <= archindex_) {
    return S_FALSE;
  }

  bela::EscapeArgv ea;
  auto cwd = std::filesystem::path(targetFile).parent_path().wstring();
  if (settings.UseWindowsTerminal()) {
    ea.Assign(settings.Terminal()).Append(L"--startingDirectory").Append(cwd).Append(L"--");
  }
  ea.Append(pwshexe)
      .Append(L"-NoLogo")
      .Append(L"-NoExit")
      .Append(L"-File")
      .Append(targetFile)
      .Append(L"-Environment")
      .Append(L"-InstanceId")
      .Append(search.InstanceId(vsindex_))
      .Append(L"-InstallationVersion")
      .Append(search.InstallVersion(vsindex_))
      .Append(L"-Arch")
      .Append(tables.Targets[archindex_]);
  if (Button_GetCheck(hcleanenv.hWnd) == BST_CHECKED) {
    ea.Append(L"-ClearEnv");
  }
  if (!Execute(ea.data(), cwd.data())) {
    auto ec = bela::make_system_error_code();
    bela::BelaMessageBox(m_hWnd, L"CreateProcess failed", ec.message.data(), nullptr,
                         bela::mbs_t::FATAL);
  }
  return S_OK;
}
<|endoftext|>