<commit_before>/*
* Author: Manash Kumar Mandal
* Modified Library introduced in Arduino Playground which does not work
* This works perfectly
* LICENSE: MIT
*/

#include "SerialPort.hpp"

SerialPort::SerialPort(const char *portName)
{
    this->connected = false;

    this->handler = CreateFileA(static_cast<LPCSTR>(portName),
                                GENERIC_READ | GENERIC_WRITE,
                                0,
                                NULL,
                                OPEN_EXISTING,
                                FILE_ATTRIBUTE_NORMAL,
                                NULL);
    if (this->handler == INVALID_HANDLE_VALUE)
    {
        if (GetLastError() == ERROR_FILE_NOT_FOUND)
        {
            std::cerr << "ERROR: Handle was not attached.Reason : " << portName << " not available\n";
        }
        else
        {
            std::cerr << "ERROR!!!\n";
        }
    }
    else
    {
        DCB dcbSerialParameters = {0};

        if (!GetCommState(this->handler, &dcbSerialParameters))
        {
            std::cerr << "Failed to get current serial parameters\n";
        }
        else
        {
            dcbSerialParameters.BaudRate = CBR_9600;
            dcbSerialParameters.ByteSize = 8;
            dcbSerialParameters.StopBits = ONESTOPBIT;
            dcbSerialParameters.Parity = NOPARITY;
            dcbSerialParameters.fDtrControl = DTR_CONTROL_ENABLE;

            if (!SetCommState(handler, &dcbSerialParameters))
            {
                std::cout << "ALERT: could not set serial port parameters\n";
            }
            else
            {
                this->connected = true;
                PurgeComm(this->handler, PURGE_RXCLEAR | PURGE_TXCLEAR);
                Sleep(ARDUINO_WAIT_TIME);
            }
        }
    }
}

SerialPort::~SerialPort()
{
    if (this->connected)
    {
        this->connected = false;
        CloseHandle(this->handler);
    }
}

int SerialPort::readSerialPort(char *buffer, unsigned int buf_size)
{
    DWORD bytesRead{};
    unsigned int toRead = 0;

    ClearCommError(this->handler, &this->errors, &this->status);

    if (this->status.cbInQue > 0)
    {
        if (this->status.cbInQue > buf_size)
        {
            toRead = buf_size;
        }
        else
        {
            toRead = this->status.cbInQue;
        }
    }

    memset(buffer, 0, buf_size);

    if (ReadFile(this->handler, buffer, toRead, &bytesRead, NULL))
    {
        return bytesRead;
    }

    return 0;
}

bool SerialPort::writeSerialPort(char *buffer, unsigned int buf_size)
{
    DWORD bytesSend;

    if (!WriteFile(this->handler, (void*) buffer, buf_size, &bytesSend, 0))
    {
        ClearCommError(this->handler, &this->errors, &this->status);
        return false;
    }

    return true;
}

bool SerialPort::isConnected()
{
    if (!ClearCommError(this->handler, &this->errors, &this->status))
    {
        this->connected = false;
    }

    return this->connected;
}

void SerialPort::closeSerial()
{
    CloseHandle(this->handler);
}
<commit_msg>Added some comments about usage<commit_after>/*
* Author: Manash Kumar Mandal
* Modified Library introduced in Arduino Playground which does not work
* This works perfectly
* LICENSE: MIT
*/

#include "SerialPort.hpp"

SerialPort::SerialPort(const char *portName)
{
    this->connected = false;

    this->handler = CreateFileA(static_cast<LPCSTR>(portName),
                                GENERIC_READ | GENERIC_WRITE,
                                0,
                                NULL,
                                OPEN_EXISTING,
                                FILE_ATTRIBUTE_NORMAL,
                                NULL);
    if (this->handler == INVALID_HANDLE_VALUE)
    {
        if (GetLastError() == ERROR_FILE_NOT_FOUND)
        {
            std::cerr << "ERROR: Handle was not attached.Reason : " << portName << " not available\n";
        }
        else
        {
            std::cerr << "ERROR!!!\n";
        }
    }
    else
    {
        DCB dcbSerialParameters = {0};

        if (!GetCommState(this->handler, &dcbSerialParameters))
        {
            std::cerr << "Failed to get current serial parameters\n";
        }
        else
        {
            dcbSerialParameters.BaudRate = CBR_9600;
            dcbSerialParameters.ByteSize = 8;
            dcbSerialParameters.StopBits = ONESTOPBIT;
            dcbSerialParameters.Parity = NOPARITY;
            dcbSerialParameters.fDtrControl = DTR_CONTROL_ENABLE;

            if (!SetCommState(handler, &dcbSerialParameters))
            {
                std::cout << "ALERT: could not set serial port parameters\n";
            }
            else
            {
                this->connected = true;
                PurgeComm(this->handler, PURGE_RXCLEAR | PURGE_TXCLEAR);
                Sleep(ARDUINO_WAIT_TIME);
            }
        }
    }
}

SerialPort::~SerialPort()
{
    if (this->connected)
    {
        this->connected = false;
        CloseHandle(this->handler);
    }
}

// Reading bytes from serial port to buffer;
// returns read bytes count, or if error occurs, returns 0
int SerialPort::readSerialPort(char *buffer, unsigned int buf_size)
{
    DWORD bytesRead{};
    unsigned int toRead = 0;

    ClearCommError(this->handler, &this->errors, &this->status);

    if (this->status.cbInQue > 0)
    {
        if (this->status.cbInQue > buf_size)
        {
            toRead = buf_size;
        }
        else
        {
            toRead = this->status.cbInQue;
        }
    }

    memset(buffer, 0, buf_size);

    if (ReadFile(this->handler, buffer, toRead, &bytesRead, NULL))
    {
        return bytesRead;
    }

    return 0;
}

// Sending provided buffer to serial port;
// returns true if succeed, false if not
bool SerialPort::writeSerialPort(char *buffer, unsigned int buf_size)
{
    DWORD bytesSend;

    if (!WriteFile(this->handler, (void*) buffer, buf_size, &bytesSend, 0))
    {
        ClearCommError(this->handler, &this->errors, &this->status);
        return false;
    }

    return true;
}

// Checking if serial port is connected
bool SerialPort::isConnected()
{
    if (!ClearCommError(this->handler, &this->errors, &this->status))
    {
        this->connected = false;
    }

    return this->connected;
}

void SerialPort::closeSerial()
{
    CloseHandle(this->handler);
}
<|endoftext|>


<commit_before>#include "dsa_common.h"

#include "requester.h"

#include "core/session.h"

namespace dsa {

Requester::Requester(Session &session) : _session(session) {}

void Requester::close_impl() { _incoming_streams.clear(); }

int32_t Requester::next_rid() {
  while (_incoming_streams.find(++_next_rid) != _incoming_streams.end()) {
    // find next available get_rid;
  }
  if (_next_rid == 0) {
    // rid can't be 0, do it again;
    return next_rid();
  }
  return _next_rid;
}

void Requester::receive_message(MessageRef &&message) {
  auto search = _incoming_streams.find(message->get_rid());
  if (search != _incoming_streams.end()) {
    auto &stream = search->second;
    stream->receive_message(std::move(message));
  }
}
ref_<IncomingSubscribeStream> Requester::subscribe(
    const std::string &path, IncomingSubscribeStream::Callback &&callback,
    const SubscribeOptions &options) {
  uint32_t rid = next_rid();
  auto stream = make_ref_<IncomingSubscribeStream>(
      _session.get_ref(), Path(path), rid, std::move(callback));
  _incoming_streams[rid] = stream;

  stream->subscribe(options);

  return stream;
}

ref_<IncomingListStream> Requester::list(
    const std::string &path, IncomingListStream::Callback &&callback,
    const ListOptions &options) {
  uint32_t rid = next_rid();
  auto stream = make_ref_<IncomingListStream>(_session.get_ref(), Path(path),
                                              rid, std::move(callback));
  _incoming_streams[rid] = stream;

  stream->list(options);

  return stream;
}

ref_<IncomingInvokeStream> Requester::invoke(
    const std::string &path, IncomingInvokeStream::Callback &&callback,
    ref_<const InvokeRequestMessage> &&message) {
  uint32_t rid = next_rid();
  auto stream = make_ref_<IncomingInvokeStream>(_session.get_ref(), Path(path),
                                                rid, std::move(callback));
  _incoming_streams[rid] = stream;

  stream->invoke(std::move(message));

  return stream;
}

ref_<IncomingSetStream> Requester::set(
    const std::string &path, IncomingSetStream::Callback &&callback,
    ref_<const SetRequestMessage> &&message) {
  uint32_t rid = next_rid();
  auto stream = make_ref_<IncomingSetStream>(_session.get_ref(), Path(path),
                                             rid, std::move(callback));
  _incoming_streams[rid] = stream;

  stream->set(std::move(message));

  return stream;
}

bool Requester::remove_stream(uint32_t rid){
  auto search = _incoming_streams.find(rid);
  if (search != _incoming_streams.end()) {
    auto &stream = search->second;
    stream->close();
    _incoming_streams.erase(search);
  }
}
}
<commit_msg>fix compile error<commit_after>#include "dsa_common.h"

#include "requester.h"

#include "core/session.h"

namespace dsa {

Requester::Requester(Session &session) : _session(session) {}

void Requester::close_impl() { _incoming_streams.clear(); }

int32_t Requester::next_rid() {
  while (_incoming_streams.find(++_next_rid) != _incoming_streams.end()) {
    // find next available get_rid;
  }
  if (_next_rid == 0) {
    // rid can't be 0, do it again;
    return next_rid();
  }
  return _next_rid;
}

void Requester::receive_message(MessageRef &&message) {
  auto search = _incoming_streams.find(message->get_rid());
  if (search != _incoming_streams.end()) {
    auto &stream = search->second;
    stream->receive_message(std::move(message));
  }
}
ref_<IncomingSubscribeStream> Requester::subscribe(
    const std::string &path, IncomingSubscribeStream::Callback &&callback,
    const SubscribeOptions &options) {
  uint32_t rid = next_rid();
  auto stream = make_ref_<IncomingSubscribeStream>(
      _session.get_ref(), Path(path), rid, std::move(callback));
  _incoming_streams[rid] = stream;

  stream->subscribe(options);

  return stream;
}

ref_<IncomingListStream> Requester::list(
    const std::string &path, IncomingListStream::Callback &&callback,
    const ListOptions &options) {
  uint32_t rid = next_rid();
  auto stream = make_ref_<IncomingListStream>(_session.get_ref(), Path(path),
                                              rid, std::move(callback));
  _incoming_streams[rid] = stream;

  stream->list(options);

  return stream;
}

ref_<IncomingInvokeStream> Requester::invoke(
    const std::string &path, IncomingInvokeStream::Callback &&callback,
    ref_<const InvokeRequestMessage> &&message) {
  uint32_t rid = next_rid();
  auto stream = make_ref_<IncomingInvokeStream>(_session.get_ref(), Path(path),
                                                rid, std::move(callback));
  _incoming_streams[rid] = stream;

  stream->invoke(std::move(message));

  return stream;
}

ref_<IncomingSetStream> Requester::set(
    const std::string &path, IncomingSetStream::Callback &&callback,
    ref_<const SetRequestMessage> &&message) {
  uint32_t rid = next_rid();
  auto stream = make_ref_<IncomingSetStream>(_session.get_ref(), Path(path),
                                             rid, std::move(callback));
  _incoming_streams[rid] = stream;

  stream->set(std::move(message));

  return stream;
}

bool Requester::remove_stream(uint32_t rid){
  auto search = _incoming_streams.find(rid);
  if (search != _incoming_streams.end()) {
    auto &stream = search->second;
    stream->close();
    _incoming_streams.erase(search);
    return true;
  }
  return false;
}
}
<|endoftext|>


<commit_before>#include "instrumentation/builder/instrument_builder.hpp"

#include <deal.II/lac/vector.h>
#include <deal.II/base/mpi.h>
#include <deal.II/base/conditional_ostream.h>

#include "calculator/fourier/fourier_transform_fftw.h"
#include "instrumentation/basic_instrument.h"
#include "instrumentation/instrument.h"
#include "instrumentation/converter/calculator/vector_subtractor.h"
#include "instrumentation/converter/multi_converter.hpp"
#include "instrumentation/converter/factory.h"
#include "instrumentation/outstream/factory.h"
#include "utility/colors.h"

namespace bart::convergence {
struct Status;
} // namespace bart::convergence

namespace bart::instrumentation::builder {

namespace  {

using ConditionalOstream = dealii::ConditionalOStream;
using ConditionalOstreamPtr = std::unique_ptr<ConditionalOstream>;
using ConvergenceStatus = convergence::Status;
using ConvergenceInstrument = InstrumentI<convergence::Status>;
using ConverterName = instrumentation::converter::ConverterName;
using DealiiVector = dealii::Vector<double>;
using IntDoublePair = std::pair<int, double>;
using OutstreamName = outstream::OutstreamName;
using StringInstrument = InstrumentI<std::string>;
using StringColorPair = std::pair<std::string, utility::Color>;

auto GetConditionalOstream = []() {
  return outstream::OutstreamIFactory<std::string, ConditionalOstreamPtr>::get()
    .GetConstructor(OutstreamName::kToConditionalOstream)(
        std::make_unique<ConditionalOstream>(
            std::cout,
            dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0));
};

} // namespace

// Convergence Status ==========================================================

template <>
auto InstrumentBuilder::BuildInstrument<ConvergenceStatus>(
    const InstrumentName name) -> std::unique_ptr<ConvergenceInstrument> {
  switch (name) {
    case InstrumentName::kConvergenceStatusToConditionalOstream: {
      return std::make_unique<Instrument<ConvergenceStatus, std::string>>(
          converter::ConverterIFactory<ConvergenceStatus, std::string>::get()
              .GetConstructor(ConverterName::kConvergenceToString)(),
          GetConditionalOstream());
    }
    default:
    AssertThrow(false,
                dealii::ExcMessage("Bad instrument name passed to builder"))
  }
}

// DEALII VECTOR ===============================================================

template <>
auto InstrumentBuilder::BuildInstrument<DealiiVector>(
    const InstrumentName name,
    const DealiiVector error,
    const std::string filename)
-> std::unique_ptr<InstrumentI<DealiiVector>> {
  switch (name) {
    case InstrumentName::kFourierOfErrorToFile: {
      using ComplexVector = std::vector<std::complex<double>>;
      using IntComplexVectorPair = std::pair<int, ComplexVector>;
      using AbsoluteValue = instrumentation::converter::calculator::AbsoluteValue;
      using FourierCalculator = calculator::fourier::FourierTransformI;
      using FourierCalculatorFFTW = calculator::fourier::FourierTransformFFTW;
      using Normalized = calculator::fourier::Normalized;
      using FirstStageConverter = instrumentation::converter::MultiConverter<DealiiVector, DealiiVector, ComplexVector>;

      auto vector_subtractor_ptr =
          converter::ConverterIFactory<DealiiVector, DealiiVector, DealiiVector, AbsoluteValue>::get()
          .GetConstructor(ConverterName::kCalculatorVectorSubtractor)
              (error, AbsoluteValue(false));
      auto dealii_to_complex_vector_converter_ptr =
          converter::ConverterIFactory<DealiiVector, ComplexVector>::get()
          .GetConstructor(ConverterName::kDealiiToComplexVector)();
      auto fourier_transform_calculator = std::make_unique<FourierCalculatorFFTW>(error.size());
      auto fourier_calculator_ptr =
          converter::ConverterIFactory<ComplexVector, ComplexVector, std::unique_ptr<FourierCalculator>, Normalized>::get()
              .GetConstructor(ConverterName::kFourierTransform)
                  (std::move(fourier_transform_calculator), Normalized(true));
      auto pair_incrementer_ptr =
               converter::ConverterIFactory<ComplexVector, std::pair<int, ComplexVector>>::get()
                   .GetConstructor(converter::ConverterName::kPairIncrementer)();
      auto pair_to_string_ptr =
          converter::ConverterIFactory<IntComplexVectorPair, std::string>::get()
              .GetConstructor(converter::ConverterName::kIntVectorComplexPairToString)();

      auto full_converter = std::move(vector_subtractor_ptr) +
          std::move(dealii_to_complex_vector_converter_ptr) +
          std::move(fourier_calculator_ptr) +
          std::move(pair_incrementer_ptr) +
          std::move(pair_to_string_ptr);

      return std::make_unique<Instrument<DealiiVector, std::string>>(
          std::move(full_converter),
          outstream::OutstreamIFactory<std::string, std::unique_ptr<std::ostream>>::get()
              .GetConstructor(OutstreamName::kToOstream)(
                  std::make_unique<std::ofstream>(filename)));
    }
    default:
    AssertThrow(false,
                dealii::ExcMessage("Bad instrument name passed to builder"))
  }
}

// INT-DOUBLE-PAIR =============================================================
template <>
auto InstrumentBuilder::BuildInstrument<IntDoublePair>(
    const InstrumentName name, const std::string filename)
-> std::unique_ptr<InstrumentI<IntDoublePair> > {
  switch (name) {
    case InstrumentName::kIntDoublePairToFile: {
      return std::make_unique<Instrument<IntDoublePair, std::string>>(
          converter::ConverterIFactory<IntDoublePair, std::string>::get()
              .GetConstructor(ConverterName::kIntDoublePairToString)(),
          outstream::OutstreamIFactory<std::string, std::unique_ptr<std::ostream>>::get()
              .GetConstructor(OutstreamName::kToOstream)(
                  std::make_unique<std::ofstream>(filename)));
    }
    default:
    AssertThrow(false,
                dealii::ExcMessage("Bad instrument name passed to builder"))
  }
}

// STRING-COLOR-PAIR ===========================================================

template<>
std::unique_ptr<InstrumentI<StringColorPair>> InstrumentBuilder::BuildInstrument(
    const InstrumentName name) {

  switch (name) {
    case InstrumentName::kColorStatusToConditionalOstream: {
      return std::make_unique<Instrument<StringColorPair, std::string>>(
          converter::ConverterIFactory<StringColorPair, std::string>::get()
              .GetConstructor(converter::ConverterName::kStringColorPairToString)(),
          outstream::OutstreamIFactory<std::string, ConditionalOstreamPtr>::get()
              .GetConstructor(outstream::OutstreamName::kToConditionalOstream)(
                  std::make_unique<ConditionalOstream>(
                      std::cout,
                      dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)));
    }
    default:
      AssertThrow(false,
                  dealii::ExcMessage("Bad instrument name passed to builder"))
  }
}

// STRING ======================================================================
template <>
auto InstrumentBuilder::BuildInstrument(const InstrumentName name)
-> std::unique_ptr<StringInstrument> {
  switch (name) {
    case InstrumentName::kStringToConditionalOstream: {
      return std::make_unique<BasicInstrument<std::string>>(
          outstream::OutstreamIFactory<std::string, ConditionalOstreamPtr>::get()
              .GetConstructor(outstream::OutstreamName::kToConditionalOstream)(
                  std::make_unique<ConditionalOstream>(
                      std::cout,
                      dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)));
    };
    default:
    AssertThrow(false,
                dealii::ExcMessage("Bad instrument name passed to builder"))
  }
}

} // namespace bart::instrumentation::builder
<commit_msg>Explicitly made unique ptrs to filestreams in builder for instruments that output to a file.<commit_after>#include "instrumentation/builder/instrument_builder.hpp"

#include <deal.II/lac/vector.h>
#include <deal.II/base/mpi.h>
#include <deal.II/base/conditional_ostream.h>

#include "calculator/fourier/fourier_transform_fftw.h"
#include "instrumentation/basic_instrument.h"
#include "instrumentation/instrument.h"
#include "instrumentation/converter/calculator/vector_subtractor.h"
#include "instrumentation/converter/multi_converter.hpp"
#include "instrumentation/converter/factory.h"
#include "instrumentation/outstream/factory.h"
#include "utility/colors.h"

namespace bart::convergence {
struct Status;
} // namespace bart::convergence

namespace bart::instrumentation::builder {

namespace  {

using ConditionalOstream = dealii::ConditionalOStream;
using ConditionalOstreamPtr = std::unique_ptr<ConditionalOstream>;
using ConvergenceStatus = convergence::Status;
using ConvergenceInstrument = InstrumentI<convergence::Status>;
using ConverterName = instrumentation::converter::ConverterName;
using DealiiVector = dealii::Vector<double>;
using IntDoublePair = std::pair<int, double>;
using OutstreamName = outstream::OutstreamName;
using StringInstrument = InstrumentI<std::string>;
using StringColorPair = std::pair<std::string, utility::Color>;

auto GetConditionalOstream = []() {
  return outstream::OutstreamIFactory<std::string, ConditionalOstreamPtr>::get()
    .GetConstructor(OutstreamName::kToConditionalOstream)(
        std::make_unique<ConditionalOstream>(
            std::cout,
            dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0));
};

} // namespace

// Convergence Status ==========================================================

template <>
auto InstrumentBuilder::BuildInstrument<ConvergenceStatus>(
    const InstrumentName name) -> std::unique_ptr<ConvergenceInstrument> {
  switch (name) {
    case InstrumentName::kConvergenceStatusToConditionalOstream: {
      return std::make_unique<Instrument<ConvergenceStatus, std::string>>(
          converter::ConverterIFactory<ConvergenceStatus, std::string>::get()
              .GetConstructor(ConverterName::kConvergenceToString)(),
          GetConditionalOstream());
    }
    default:
    AssertThrow(false,
                dealii::ExcMessage("Bad instrument name passed to builder"))
  }
}

// DEALII VECTOR ===============================================================

template <>
auto InstrumentBuilder::BuildInstrument<DealiiVector>(
    const InstrumentName name,
    const DealiiVector error,
    const std::string filename)
-> std::unique_ptr<InstrumentI<DealiiVector>> {
  switch (name) {
    case InstrumentName::kFourierOfErrorToFile: {
      using ComplexVector = std::vector<std::complex<double>>;
      using IntComplexVectorPair = std::pair<int, ComplexVector>;
      using AbsoluteValue = instrumentation::converter::calculator::AbsoluteValue;
      using FourierCalculator = calculator::fourier::FourierTransformI;
      using FourierCalculatorFFTW = calculator::fourier::FourierTransformFFTW;
      using Normalized = calculator::fourier::Normalized;
      using FirstStageConverter = instrumentation::converter::MultiConverter<DealiiVector, DealiiVector, ComplexVector>;

      auto vector_subtractor_ptr =
          converter::ConverterIFactory<DealiiVector, DealiiVector, DealiiVector, AbsoluteValue>::get()
          .GetConstructor(ConverterName::kCalculatorVectorSubtractor)
              (error, AbsoluteValue(false));
      auto dealii_to_complex_vector_converter_ptr =
          converter::ConverterIFactory<DealiiVector, ComplexVector>::get()
          .GetConstructor(ConverterName::kDealiiToComplexVector)();
      auto fourier_transform_calculator = std::make_unique<FourierCalculatorFFTW>(error.size());
      auto fourier_calculator_ptr =
          converter::ConverterIFactory<ComplexVector, ComplexVector, std::unique_ptr<FourierCalculator>, Normalized>::get()
              .GetConstructor(ConverterName::kFourierTransform)
                  (std::move(fourier_transform_calculator), Normalized(true));
      auto pair_incrementer_ptr =
               converter::ConverterIFactory<ComplexVector, std::pair<int, ComplexVector>>::get()
                   .GetConstructor(converter::ConverterName::kPairIncrementer)();
      auto pair_to_string_ptr =
          converter::ConverterIFactory<IntComplexVectorPair, std::string>::get()
              .GetConstructor(converter::ConverterName::kIntVectorComplexPairToString)();

      auto full_converter = std::move(vector_subtractor_ptr) +
          std::move(dealii_to_complex_vector_converter_ptr) +
          std::move(fourier_calculator_ptr) +
          std::move(pair_incrementer_ptr) +
          std::move(pair_to_string_ptr);

      std::unique_ptr<std::ostream> file_stream = std::make_unique<std::ofstream>(filename);
      return std::make_unique<Instrument<DealiiVector, std::string>>(
          std::move(full_converter),
          outstream::OutstreamIFactory<std::string, std::unique_ptr<std::ostream>>::get()
              .GetConstructor(OutstreamName::kToOstream)
                  (std::move(file_stream)));
    }
    default:
    AssertThrow(false,
                dealii::ExcMessage("Bad instrument name passed to builder"))
  }
}

// INT-DOUBLE-PAIR =============================================================
template <>
auto InstrumentBuilder::BuildInstrument<IntDoublePair>(
    const InstrumentName name, const std::string filename)
-> std::unique_ptr<InstrumentI<IntDoublePair> > {
  switch (name) {
    case InstrumentName::kIntDoublePairToFile: {
      std::unique_ptr<std::ostream> file_stream = std::make_unique<std::ofstream>(filename);
      return std::make_unique<Instrument<IntDoublePair, std::string>>(
          converter::ConverterIFactory<IntDoublePair, std::string>::get()
              .GetConstructor(ConverterName::kIntDoublePairToString)(),
          outstream::OutstreamIFactory<std::string, std::unique_ptr<std::ostream>>::get()
              .GetConstructor(OutstreamName::kToOstream)(
                  std::move(file_stream)));
    }
    default:
    AssertThrow(false,
                dealii::ExcMessage("Bad instrument name passed to builder"))
  }
}

// STRING-COLOR-PAIR ===========================================================

template<>
std::unique_ptr<InstrumentI<StringColorPair>> InstrumentBuilder::BuildInstrument(
    const InstrumentName name) {

  switch (name) {
    case InstrumentName::kColorStatusToConditionalOstream: {
      return std::make_unique<Instrument<StringColorPair, std::string>>(
          converter::ConverterIFactory<StringColorPair, std::string>::get()
              .GetConstructor(converter::ConverterName::kStringColorPairToString)(),
          outstream::OutstreamIFactory<std::string, ConditionalOstreamPtr>::get()
              .GetConstructor(outstream::OutstreamName::kToConditionalOstream)(
                  std::make_unique<ConditionalOstream>(
                      std::cout,
                      dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)));
    }
    default:
      AssertThrow(false,
                  dealii::ExcMessage("Bad instrument name passed to builder"))
  }
}

// STRING ======================================================================
template <>
auto InstrumentBuilder::BuildInstrument(const InstrumentName name)
-> std::unique_ptr<StringInstrument> {
  switch (name) {
    case InstrumentName::kStringToConditionalOstream: {
      return std::make_unique<BasicInstrument<std::string>>(
          outstream::OutstreamIFactory<std::string, ConditionalOstreamPtr>::get()
              .GetConstructor(outstream::OutstreamName::kToConditionalOstream)(
                  std::make_unique<ConditionalOstream>(
                      std::cout,
                      dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)));
    };
    default:
    AssertThrow(false,
                dealii::ExcMessage("Bad instrument name passed to builder"))
  }
}

} // namespace bart::instrumentation::builder
<|endoftext|>


<commit_before>#include <cassert>
#include <algorithm>
#include <iostream>
#include <mutex>
#include <thread>
#include <agency/executor_array.hpp>

int main()
{
  using namespace agency;

  using outer_executor_type = this_thread::parallel_executor;
  using inner_executor_type = concurrent_executor;

  {
    // test executor_array async_execute()
    using executor_type = executor_array<inner_executor_type, outer_executor_type>;
    using traits = agency::executor_traits<executor_type>;
    using shape_type = typename traits::shape_type;
    using index_type = typename traits::index_type;

    executor_type exec(2);

    auto shape = exec.make_shape(3,5);

    std::mutex mut;
    auto f = exec.async_execute([=,&mut](const index_type& idx, int& outer_shared, int& inner_shared)
    {
      mut.lock();
      std::cout << "Hello from agent " << idx << std::endl;
      mut.unlock();

      return 13 + outer_shared + inner_shared;
    },
    [](shape_type shape)
    {
      return traits::container<int>(shape);
    },
    shape,
    []{ return 7; },
    []{ return 42; });

    // sleep for a bit
    mut.lock();
    std::cout << "main thread sleeping for a bit..." << std::endl;
    mut.unlock();

    std::this_thread::sleep_for(std::chrono::seconds(3));

    mut.lock();
    std::cout << "main thread woke up" << std::endl;
    mut.unlock();

    auto results = f.get();

    assert(results.size() == agency::detail::shape_size(shape));
    assert(std::all_of(results.begin(), results.end(), [](int x){ return x == 13 + 7 + 42; }));
  }

  {
    // test executor_array async_execute()
    using executor_type = executor_array<inner_executor_type, outer_executor_type>;
    using traits = agency::executor_traits<executor_type>;
    using shape_type = typename traits::shape_type;
    using index_type = typename traits::index_type;

    executor_type exec(2);

    auto past = traits::make_ready_future<int>(exec,1);

    auto shape = exec.make_shape(3,5);

    auto f = exec.then_execute([](const index_type& idx, int& past, int& outer_shared, int& inner_shared)
    {
      return 13 + past + outer_shared + inner_shared;
    },
    [](shape_type shape)
    {
      return traits::container<int>(shape);
    },
    shape,
    past,
    []{ return 7; },
    []{ return 42; });

    auto results = f.get();

    assert(results.size() == agency::detail::shape_size(shape));
    assert(std::all_of(results.begin(), results.end(), [](int x){ return x == 13 + 1 + 7 + 42; }));
  }

  {
    // test flattened executor_array
    using executor_array_type = executor_array<inner_executor_type, outer_executor_type>;
    using executor_type = flattened_executor<executor_array_type>;

    using traits = agency::executor_traits<executor_type>;
    using shape_type = typename traits::shape_type;
    using index_type = typename traits::index_type;

    executor_array_type exec_array(2);
    executor_type exec{exec_array};

    shape_type shape = 10;

    auto f = traits::async_execute(exec, [](const index_type& idx, int& shared)
    {
      return 13 + shared;
    },
    [](shape_type shape)
    {
      return traits::container<int>(shape);
    },
    shape,
    []{ return 7; });

    auto results = f.get();

    assert(results.size() == agency::detail::shape_size(shape));
    assert(std::all_of(results.begin(), results.end(), [](int x){ return x == 13 + 7; }));
  }

  std::cout << "OK" << std::endl;

  return 0;
}

<commit_msg>Reenable disabled tests<commit_after>#include <cassert>
#include <algorithm>
#include <iostream>
#include <mutex>
#include <thread>
#include <agency/executor_array.hpp>

int main()
{
  using namespace agency;

  using inner_executor_type = concurrent_executor;

  {
    // test executor_array async_execute()
    using executor_type = executor_array<inner_executor_type>;
    using traits = agency::executor_traits<executor_type>;
    using shape_type = typename traits::shape_type;
    using index_type = typename traits::index_type;

    executor_type exec(2);

    auto shape = exec.make_shape(3,5);

    std::mutex mut;
    auto f = traits::async_execute(exec, [=,&mut](const index_type& idx, int& outer_shared, int& inner_shared)
    {
      mut.lock();
      std::cout << "Hello from agent " << idx << std::endl;
      mut.unlock();

      return 13 + outer_shared + inner_shared;
    },
    [](shape_type shape)
    {
      return traits::container<int>(shape);
    },
    shape,
    []{ return 7; },
    []{ return 42; });

    // sleep for a bit
    mut.lock();
    std::cout << "main thread sleeping for a bit..." << std::endl;
    mut.unlock();

    std::this_thread::sleep_for(std::chrono::seconds(1));

    mut.lock();
    std::cout << "main thread woke up" << std::endl;
    mut.unlock();

    auto results = f.get();

    assert(results.size() == agency::detail::shape_size(shape));
    assert(std::all_of(results.begin(), results.end(), [](int x){ return x == 13 + 7 + 42; }));
  }

  {
    // test executor_array then_execute()
    using executor_type = executor_array<inner_executor_type>;
    using traits = agency::executor_traits<executor_type>;
    using shape_type = typename traits::shape_type;
    using index_type = typename traits::index_type;

    executor_type exec(2);

    auto past = traits::make_ready_future<int>(exec,1);

    auto shape = exec.make_shape(3,5);

    std::mutex mut;
    auto f = traits::then_execute(exec, [=,&mut](const index_type& idx, int& past, int& outer_shared, int& inner_shared)
    {
      mut.lock();
      std::cout << "Hello from agent " << idx << std::endl;
      mut.unlock();

      return 13 + past + outer_shared + inner_shared;
    },
    [](shape_type shape)
    {
      return traits::container<int>(shape);
    },
    shape,
    past,
    []{ return 7; },
    []{ return 42; });

    // sleep for a bit
    mut.lock();
    std::cout << "main thread sleeping for a bit..." << std::endl;
    mut.unlock();

    std::this_thread::sleep_for(std::chrono::seconds(1));

    mut.lock();
    std::cout << "main thread woke up" << std::endl;
    mut.unlock();

    auto results = f.get();

    assert(results.size() == agency::detail::shape_size(shape));
    assert(std::all_of(results.begin(), results.end(), [](int x){ return x == 13 + 1 + 7 + 42; }));
  }

  {
    // test flattened executor_array
    using executor_array_type = executor_array<inner_executor_type>;
    using executor_type = flattened_executor<executor_array_type>;

    using traits = agency::executor_traits<executor_type>;
    using shape_type = typename traits::shape_type;
    using index_type = typename traits::index_type;

    executor_array_type exec_array(2);
    executor_type exec{exec_array};

    shape_type shape = 10;

    auto f = traits::async_execute(exec, [](const index_type& idx, int& shared)
    {
      return 13 + shared;
    },
    [](shape_type shape)
    {
      return traits::container<int>(shape);
    },
    shape,
    []{ return 7; });

    auto results = f.get();

    assert(results.size() == agency::detail::shape_size(shape));
    assert(std::all_of(results.begin(), results.end(), [](int x){ return x == 13 + 7; }));
  }

  std::cout << "OK" << std::endl;

  return 0;
}

<|endoftext|>


<commit_before>/*
 * GwtFileHandler.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include <core/gwt/GwtFileHandler.hpp>

#include <boost/regex.hpp>
#include <boost/algorithm/string/predicate.hpp>

#include <core/FilePath.hpp>
#include <core/RegexUtils.hpp>
#include <core/text/TemplateFilter.hpp>
#include <core/system/System.hpp>
#include <core/http/Request.hpp>
#include <core/http/Response.hpp>

namespace rstudio {
namespace core {
namespace gwt {

namespace {

void handleFileRequest(const std::string& wwwLocalPath,
                       const std::string& baseUri,
                       core::http::UriFilterFunction mainPageFilter,
                       const std::string& initJs,
                       const std::string& gwtPrefix,
                       bool useEmulatedStack,
                       const std::string& frameOptions,
                       const http::Request& request,
                       http::Response* pResponse)
{
   // get the uri and strip the query string
   std::string uri = request.uri();
   std::size_t pos = uri.find("?");
   if (pos != std::string::npos)
      uri.erase(pos);

   // request for one-character short of root location redirects to root
   if (uri == baseUri.substr(0, baseUri.size()-1))
   {
      pResponse->setMovedPermanently(request, baseUri);
      return;
   }

   // request for a URI not within our location scope
   if (uri.find(baseUri) != 0)
   {
      pResponse->setNotFoundError(request.uri());
      return;
   }

   // auto-append index.htm to request for root location
   const char * const kIndexFile = "index.htm";
   if (uri == baseUri)
      uri += kIndexFile;

   // if this is main page and we have a filter then then give it a crack
   // at the request
   std::string mainPage = baseUri + kIndexFile;
   if (uri == mainPage)
   {
      // run filter if we have one
      if (mainPageFilter)
      {
         // if the filter returns false it means we should stop processing
         if (!mainPageFilter(request, pResponse))
            return ;
      }

      // apply browser compatibility headers
      pResponse->setBrowserCompatible(request);
   }

   // get the requested file
   std::string relativePath = uri.substr(baseUri.length());
   FilePath filePath = http::util::requestedFile(wwwLocalPath, relativePath);
   if (filePath.empty())
   {
      pResponse->setNotFoundError(request.uri());
      return;
   }

   // case: files designated to be cached "forever"
   if (regex_utils::match(uri, boost::regex(".*\\.cache\\..*")))
   {
      pResponse->setCacheForeverHeaders();
      pResponse->setFile(filePath, request);
   }

   // case: files designated to never be cached
   else if (regex_utils::match(uri, boost::regex(".*\\.nocache\\..*")))
   {
      pResponse->setNoCacheHeaders();
      pResponse->setFile(filePath, request);
   }
   // case: main page -- don't cache and dynamically set compiler stack mode
   else if (uri == mainPage)
   {
      // check for emulated stack
      std::map<std::string,std::string> vars;
      useEmulatedStack = useEmulatedStack ||
                         (request.queryParamValue("emulatedStack") == "1");
      vars["compiler_stack_mode"] = useEmulatedStack ? "emulated" : "native";

      // check for initJs
      if (!initJs.empty())
         vars["head_tags"] = "<script>" + initJs + "</script>";
      else
         vars["head_tags"] = std::string();

      // gwt prefix
      vars["gwt_prefix"] = gwtPrefix;

      // don't allow main page to be framed by other domains (clickjacking
      // defense)
      pResponse->setFrameOptionHeaders(frameOptions);

      // return the page
      pResponse->setNoCacheHeaders();
      pResponse->setFile(filePath, request, text::TemplateFilter(vars));
   }

   // case: normal cacheable file
   else
   {
      // since these are application components we force revalidation
      pResponse->setCacheWithRevalidationHeaders();
      pResponse->setCacheableFile(filePath, request);
   }

}

} // anonymous namespace

http::UriHandlerFunction fileHandlerFunction(
                                       const std::string& wwwLocalPath,
                                       const std::string& baseUri,
                                       http::UriFilterFunction mainPageFilter,
                                       const std::string& initJs,
                                       const std::string& gwtPrefix,
                                       bool useEmulatedStack,
                                       const std::string& frameOptions)
{
   return boost::bind(handleFileRequest,
                      wwwLocalPath,
                      baseUri,
                      mainPageFilter,
                      initJs,
                      gwtPrefix,
                      useEmulatedStack,
                      frameOptions,
                      _1,
                      _2);
}

} // namespace gwt
} // namespace core
} // namespace rstudio

<commit_msg>deny directory listings in GWT file handler (fixes #1561)<commit_after>/*
 * GwtFileHandler.cpp
 *
 * Copyright (C) 2009-17 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include <core/gwt/GwtFileHandler.hpp>

#include <boost/regex.hpp>
#include <boost/algorithm/string/predicate.hpp>

#include <core/FilePath.hpp>
#include <core/RegexUtils.hpp>
#include <core/text/TemplateFilter.hpp>
#include <core/system/System.hpp>
#include <core/http/Request.hpp>
#include <core/http/Response.hpp>

namespace rstudio {
namespace core {
namespace gwt {

namespace {

void handleFileRequest(const std::string& wwwLocalPath,
                       const std::string& baseUri,
                       core::http::UriFilterFunction mainPageFilter,
                       const std::string& initJs,
                       const std::string& gwtPrefix,
                       bool useEmulatedStack,
                       const std::string& frameOptions,
                       const http::Request& request,
                       http::Response* pResponse)
{
   // get the uri and strip the query string
   std::string uri = request.uri();
   std::size_t pos = uri.find("?");
   if (pos != std::string::npos)
      uri.erase(pos);

   // request for one-character short of root location redirects to root
   if (uri == baseUri.substr(0, baseUri.size()-1))
   {
      pResponse->setMovedPermanently(request, baseUri);
      return;
   }

   // request for a URI not within our location scope
   if (uri.find(baseUri) != 0)
   {
      pResponse->setNotFoundError(request.uri());
      return;
   }

   // auto-append index.htm to request for root location
   const char * const kIndexFile = "index.htm";
   if (uri == baseUri)
      uri += kIndexFile;

   // if this is main page and we have a filter then then give it a crack
   // at the request
   std::string mainPage = baseUri + kIndexFile;
   if (uri == mainPage)
   {
      // run filter if we have one
      if (mainPageFilter)
      {
         // if the filter returns false it means we should stop processing
         if (!mainPageFilter(request, pResponse))
            return ;
      }

      // apply browser compatibility headers
      pResponse->setBrowserCompatible(request);
   }

   // get the requested file
   std::string relativePath = uri.substr(baseUri.length());
   FilePath filePath = http::util::requestedFile(wwwLocalPath, relativePath);
   if (filePath.empty())
   {
      pResponse->setNotFoundError(request.uri());
      return;
   }
   else if (filePath.isDirectory())
   {
      // deny directory listings
      pResponse->setError(http::status::Forbidden, "Forbidden");
      return;
   }

   // case: files designated to be cached "forever"
   if (regex_utils::match(uri, boost::regex(".*\\.cache\\..*")))
   {
      pResponse->setCacheForeverHeaders();
      pResponse->setFile(filePath, request);
   }

   // case: files designated to never be cached
   else if (regex_utils::match(uri, boost::regex(".*\\.nocache\\..*")))
   {
      pResponse->setNoCacheHeaders();
      pResponse->setFile(filePath, request);
   }
   // case: main page -- don't cache and dynamically set compiler stack mode
   else if (uri == mainPage)
   {
      // check for emulated stack
      std::map<std::string,std::string> vars;
      useEmulatedStack = useEmulatedStack ||
                         (request.queryParamValue("emulatedStack") == "1");
      vars["compiler_stack_mode"] = useEmulatedStack ? "emulated" : "native";

      // check for initJs
      if (!initJs.empty())
         vars["head_tags"] = "<script>" + initJs + "</script>";
      else
         vars["head_tags"] = std::string();

      // gwt prefix
      vars["gwt_prefix"] = gwtPrefix;

      // don't allow main page to be framed by other domains (clickjacking
      // defense)
      pResponse->setFrameOptionHeaders(frameOptions);

      // return the page
      pResponse->setNoCacheHeaders();
      pResponse->setFile(filePath, request, text::TemplateFilter(vars));
   }

   // case: normal cacheable file
   else
   {
      // since these are application components we force revalidation
      pResponse->setCacheWithRevalidationHeaders();
      pResponse->setCacheableFile(filePath, request);
   }

}

} // anonymous namespace

http::UriHandlerFunction fileHandlerFunction(
                                       const std::string& wwwLocalPath,
                                       const std::string& baseUri,
                                       http::UriFilterFunction mainPageFilter,
                                       const std::string& initJs,
                                       const std::string& gwtPrefix,
                                       bool useEmulatedStack,
                                       const std::string& frameOptions)
{
   return boost::bind(handleFileRequest,
                      wwwLocalPath,
                      baseUri,
                      mainPageFilter,
                      initJs,
                      gwtPrefix,
                      useEmulatedStack,
                      frameOptions,
                      _1,
                      _2);
}

} // namespace gwt
} // namespace core
} // namespace rstudio

<|endoftext|>


<commit_before>/*
 * Event.cpp
 *
 * Copyright (C) 2006 - 2007 by Universitaet Stuttgart (VIS).
 * Alle Rechte vorbehalten.
 */

#include "vislib/Event.h"

#ifndef _WIN32
#include <climits>
#endif /* !_WIN32 */

#include "vislib/assert.h"
#include "vislib/error.h"
#include "vislib/IllegalParamException.h"
#include "vislib/SystemException.h"
#include "vislib/Trace.h"
#include "vislib/UnsupportedOperationException.h"

/*
 * vislib::sys::Event::TIMEOUT_INFINITE
 */
#ifdef _WIN32
const DWORD vislib::sys::Event::TIMEOUT_INFINITE = INFINITE;
#else /* _WIN32 */
const DWORD vislib::sys::Event::TIMEOUT_INFINITE = UINT_MAX;
#endif /* _WIN32 */

/*
 * vislib::sys::Event::Event
 */
vislib::sys::Event::Event(const bool isManualReset,
                          const bool isInitiallySignaled)
#ifndef _WIN32
        : isManualReset(isManualReset),
        semaphore(isInitiallySignaled ? 1 : 0, 1)
#endif /* _WIN32 */
{
#ifdef _WIN32
    this->handle = ::CreateEventA(NULL, isManualReset ? TRUE : FALSE, FALSE,
        NULL);
    ASSERT(this->handle != NULL);
#endif /* _WIN32 */
}

/*
 * vislib::sys::Event::Event
 */
vislib::sys::Event::Event(const char *name, const bool isManualReset,
        const bool isInitiallySignaled, bool *outIsNew)
#ifndef _WIN32
        : isManualReset(isManualReset),
        semaphore(name, isInitiallySignaled ? 1 : 0, 1, outIsNew)
#endif /* _WIN32 */
{
#ifdef _WIN32
    if (outIsNew != NULL) {
        *outIsNew = false;
    }

    /* Try to open existing event first. */
    if ((this->handle = ::OpenEventA(SYNCHRONIZE | EVENT_MODIFY_STATE,
            FALSE, name)) == NULL) {
        this->handle = ::CreateEventA(NULL, isManualReset ? TRUE : FALSE, FALSE,
            name);
        if (outIsNew != NULL) {
            *outIsNew = true;
        }
    }
    ASSERT(this->handle != NULL);
#endif /* _WIN32 */
}

/*
 * vislib::sys::Event::Event
 */
vislib::sys::Event::Event(const wchar_t *name, const bool isManualReset,
        const bool isInitiallySignaled, bool *outIsNew)
#ifndef _WIN32
        : isManualReset(isManualReset),
        semaphore(name, isInitiallySignaled ? 1 : 0, 1, outIsNew)
#endif /* _WIN32 */
{
#ifdef _WIN32
    if (outIsNew != NULL) {
        *outIsNew = false;
    }

    /* Try to open existing event first. */
    if ((this->handle = ::OpenEventW(SYNCHRONIZE | EVENT_MODIFY_STATE,
            FALSE, name)) == NULL) {
        this->handle = ::CreateEventW(NULL, isManualReset ? TRUE : FALSE, FALSE,
            name);
        if (outIsNew != NULL) {
            *outIsNew = true;
        }
    }
    ASSERT(this->handle != NULL);
#endif /* _WIN32 */
}

/*
 * vislib::sys::Event::~Event
 */
vislib::sys::Event::~Event(void) {
#ifdef _WIN32
    ::CloseHandle(this->handle);

#else /* _WIN32 */
    /* Nothing to do. */

#endif /* _WIN32 */
}

/*
 * vislib::sys::Event::Reset
 */
void vislib::sys::Event::Reset(void) {
#ifdef _WIN32
    if (!::ResetEvent(this->handle)) {
        throw SystemException(__FILE__, __LINE__);
    }

#else /* _WIN32 */
    VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Reset\n");

    this->semaphore.TryLock();
    ASSERT(!this->semaphore.TryLock());

#endif /* _WIN32 */
}

/*
 * vislib::sys::Event::Set
 */
void vislib::sys::Event::Set(void) {
#ifdef _WIN32
    if (!::SetEvent(this->handle)) {
        throw SystemException(__FILE__, __LINE__);
    }

#else /* _WIN32 */
    VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Set\n");

    this->semaphore.TryLock();
    this->semaphore.Unlock();

#endif /* _WIN32 */
}

/*
 * vislib::sys::Event::Wait
 */
bool vislib::sys::Event::Wait(const DWORD timeout) {
#ifdef _WIN32
    switch (::WaitForSingleObject(this->handle, timeout)) {

        case WAIT_OBJECT_0:
            /* falls through. */
        case WAIT_ABANDONED:
            return true;
            /* Unreachable. */

        case WAIT_TIMEOUT:
            return false;
            /* Unreachable. */

        default:
            throw SystemException(__FILE__, __LINE__);
            /* Unreachable. */
    }

#else /* _WIN32 */
    VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Wait\n");
    bool retval = false;

    if (timeout == TIMEOUT_INFINITE) {
        this->semaphore.Lock();
        retval = true;

    } else {
        retval = this->semaphore.TryLock(timeout);
    }

    if (retval && this->isManualReset) {
        VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Wait signal again\n");
        this->semaphore.Unlock();
    }

    return retval;
#endif /* _WIN32 */
}

/*
 * vislib::sys::Event::Event
 */
vislib::sys::Event::Event(const Event& rhs) {
    throw UnsupportedOperationException("vislib::sys::Event::Event",
        __FILE__, __LINE__);
}

/*
 * vislib::sys::Event::operator =
 */
vislib::sys::Event& vislib::sys::Event::operator =(const Event& rhs) {
    if (this != &rhs) {
        throw IllegalParamException("rhs", __FILE__, __LINE__);
    }

    return *this;
}
<commit_msg>Event has been fixed and works as intended<commit_after>/*
 * Event.cpp
 *
 * Copyright (C) 2006 - 2007 by Universitaet Stuttgart (VIS).
 * Alle Rechte vorbehalten.
 */

#include "vislib/Event.h"

#ifndef _WIN32
#include <climits>
#endif /* !_WIN32 */

#include "vislib/assert.h"
#include "vislib/error.h"
#include "vislib/IllegalParamException.h"
#include "vislib/SystemException.h"
#include "vislib/Trace.h"
#include "vislib/UnsupportedOperationException.h"

/*
 * vislib::sys::Event::TIMEOUT_INFINITE
 */
#ifdef _WIN32
const DWORD vislib::sys::Event::TIMEOUT_INFINITE = INFINITE;
#else /* _WIN32 */
const DWORD vislib::sys::Event::TIMEOUT_INFINITE = UINT_MAX;
#endif /* _WIN32 */

/*
 * vislib::sys::Event::Event
 */
vislib::sys::Event::Event(const bool isManualReset,
                          const bool isInitiallySignaled)
#ifndef _WIN32
        : isManualReset(isManualReset),
        semaphore(isInitiallySignaled ? 1 : 0, 1)
#endif /* _WIN32 */
{
#ifdef _WIN32
    this->handle = ::CreateEventA(NULL, isManualReset ? TRUE : FALSE,
        isInitiallySignaled ? TRUE : FALSE,
        NULL);
    ASSERT(this->handle != NULL);
#endif /* _WIN32 */
}

/*
 * vislib::sys::Event::Event
 */
vislib::sys::Event::Event(const char *name, const bool isManualReset,
        const bool isInitiallySignaled, bool *outIsNew)
#ifndef _WIN32
        : isManualReset(isManualReset),
        semaphore(name, isInitiallySignaled ? 1 : 0, 1, outIsNew)
#endif /* _WIN32 */
{
#ifdef _WIN32
    if (outIsNew != NULL) {
        *outIsNew = false;
    }

    /* Try to open existing event first. */
    if ((this->handle = ::OpenEventA(SYNCHRONIZE | EVENT_MODIFY_STATE,
            FALSE, name)) == NULL) {
        this->handle = ::CreateEventA(NULL, isManualReset ? TRUE : FALSE,
            isInitiallySignaled ? TRUE : FALSE,
            name);
        if (outIsNew != NULL) {
            *outIsNew = true;
        }
    }
    ASSERT(this->handle != NULL);
#endif /* _WIN32 */
}

/*
 * vislib::sys::Event::Event
 */
vislib::sys::Event::Event(const wchar_t *name, const bool isManualReset,
        const bool isInitiallySignaled, bool *outIsNew)
#ifndef _WIN32
        : isManualReset(isManualReset),
        semaphore(name, isInitiallySignaled ? 1 : 0, 1, outIsNew)
#endif /* _WIN32 */
{
#ifdef _WIN32
    if (outIsNew != NULL) {
        *outIsNew = false;
    }

    /* Try to open existing event first. */
    if ((this->handle = ::OpenEventW(SYNCHRONIZE | EVENT_MODIFY_STATE,
            FALSE, name)) == NULL) {
        this->handle = ::CreateEventW(NULL, isManualReset ? TRUE : FALSE,
            isInitiallySignaled ? TRUE : FALSE,
            name);
        if (outIsNew != NULL) {
            *outIsNew = true;
        }
    }
    ASSERT(this->handle != NULL);
#endif /* _WIN32 */
}

/*
 * vislib::sys::Event::~Event
 */
vislib::sys::Event::~Event(void) {
#ifdef _WIN32
    ::CloseHandle(this->handle);

#else /* _WIN32 */
    /* Nothing to do. */

#endif /* _WIN32 */
}

/*
 * vislib::sys::Event::Reset
 */
void vislib::sys::Event::Reset(void) {
#ifdef _WIN32
    if (!::ResetEvent(this->handle)) {
        throw SystemException(__FILE__, __LINE__);
    }

#else /* _WIN32 */
    VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Reset\n");

    this->semaphore.TryLock();
    ASSERT(!this->semaphore.TryLock());

#endif /* _WIN32 */
}

/*
 * vislib::sys::Event::Set
 */
void vislib::sys::Event::Set(void) {
#ifdef _WIN32
    if (!::SetEvent(this->handle)) {
        throw SystemException(__FILE__, __LINE__);
    }

#else /* _WIN32 */
    VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Set\n");

    this->semaphore.TryLock();
    this->semaphore.Unlock();

#endif /* _WIN32 */
}

/*
 * vislib::sys::Event::Wait
 */
bool vislib::sys::Event::Wait(const DWORD timeout) {
#ifdef _WIN32
    switch (::WaitForSingleObject(this->handle, timeout)) {

        case WAIT_OBJECT_0:
            /* falls through. */
        case WAIT_ABANDONED:
            return true;
            /* Unreachable. */

        case WAIT_TIMEOUT:
            return false;
            /* Unreachable. */

        default:
            throw SystemException(__FILE__, __LINE__);
            /* Unreachable. */
    }

#else /* _WIN32 */
    VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Wait\n");
    bool retval = false;

    if (timeout == TIMEOUT_INFINITE) {
        this->semaphore.Lock();
        retval = true;

    } else {
        retval = this->semaphore.TryLock(timeout);
    }

    if (retval && this->isManualReset) {
        VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Wait signal again\n");
        this->semaphore.Unlock();
    }

    return retval;
#endif /* _WIN32 */
}

/*
 * vislib::sys::Event::Event
 */
vislib::sys::Event::Event(const Event& rhs) {
    throw UnsupportedOperationException("vislib::sys::Event::Event",
        __FILE__, __LINE__);
}

/*
 * vislib::sys::Event::operator =
 */
vislib::sys::Event& vislib::sys::Event::operator =(const Event& rhs) {
    if (this != &rhs) {
        throw IllegalParamException("rhs", __FILE__, __LINE__);
    }

    return *this;
}
<|endoftext|>


<commit_before>// This file is part of the ustl library, an STL implementation.
//
// Copyright (C) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
//
// ualgobase.cc
//
// Copy and fill optimizations are here.
//

#ifndef NDEBUG	// Optimized code here. asserts slow it down, and are checked elsewhere.
#define NDEBUG
#endif

#include "ualgobase.h"

#if __i386__

namespace ustl {

//----------------------------------------------------------------------
// Copy functions
//----------------------------------------------------------------------

#if __GNUC__ >= 3
static inline void movsb_dir_up (void) __attribute__((always_inline));
static inline void movsb_dir_down (void) __attribute__((always_inline));
static inline void movsb (const void*& src, size_t nBytes, void*& dest) __attribute__((always_inline));
static inline void movsd (const void*& src, size_t nWords, void*& dest) __attribute__((always_inline));
#endif

static inline void movsb_dir_up (void) { asm volatile ("cld"); }
static inline void movsb_dir_down (void) { asm volatile ("std"); }

static inline void movsb (const void*& src, size_t nBytes, void*& dest)
{
    asm volatile ("rep;\n\tmovsb"
	: "=&S"(src), "=&D"(dest), "=&c"(nBytes)
	: "0"(src), "1"(dest), "2"(nBytes)
	: "memory");
}

static inline void movsd (const void*& src, size_t nWords, void*& dest)
{
    asm volatile ("rep;\n\tmovsl"
	: "=&S"(src), "=&D"(dest), "=&c"(nWords)
	: "0"(src), "1"(dest), "2"(nWords)
	: "memory");
}

template <typename T> inline void stosv (T*&, size_t, T) {}
template <> inline void stosv (uint8_t*& p, size_t n, uint8_t v)
{ asm volatile ("rep;\n\tstosb" : "=&D"(p), "=c"(n) : "0"(p), "1"(n), "a"(v) : "memory"); }
template <> inline void stosv (uint16_t*& p, size_t n, uint16_t v)
{ asm volatile ("rep;\n\tstosw" : "=&D"(p), "=c"(n) : "0"(p), "1"(n), "a"(v) : "memory"); }
template <> inline void stosv (uint32_t*& p, size_t n, uint32_t v)
{ asm volatile ("rep;\n\tstosl" : "=&D"(p), "=c"(n) : "0"(p), "1"(n), "a"(v) : "memory"); }

#if CPU_HAS_MMX
#define MMX_ALIGN	16U	// Data must be aligned on this grain
#define MMX_BS		32U	// Assembly routines copy data this many bytes at a time.

static inline void simd_block_copy (const void* src, void* dest) __attribute__((always_inline));
static inline void simd_block_store (uint8_t* dest) __attribute__((always_inline));
static inline void simd_block_cleanup (void) __attribute__((always_inline));

static inline void simd_block_copy (const void* src, void* dest)
{
    #if CPU_HAS_SSE
    asm volatile (
	"movaps (%%esi), %%xmm0		\n\t"
	"movaps 16(%%esi), %%xmm1	\n\t"
	"movntps %%xmm0, (%%edi)	\n\t"
	"movntps %%xmm1, 16(%%edi)"
	: : "S"(src), "D"(dest)
	: "memory", "xmm0", "xmm1");
    #else
    asm volatile (
	"movq (%%esi), %%mm0	\n\t"
	"movq 8(%%esi), %%mm1	\n\t"
	"movq 16(%%esi), %%mm2	\n\t"
	"movq 24(%%esi), %%mm3	\n\t"
	"movq %%mm0, (%%edi)	\n\t"
	"movq %%mm1, 8(%%edi)	\n\t"
	"movq %%mm2, 16(%%edi)	\n\t"
	"movq %%mm3, 24(%%edi)"
	: : "S"(src), "D"(dest)
	: "memory", "mm0", "mm1", "mm2", "mm3", "st", "st(1)", "st(2)", "st(3)");
    #endif
}

static inline void simd_block_store (uint8_t* dest)
{
    #if CPU_HAS_SSE
    asm volatile (
	"movntq %%mm0, %0\n\t"
	"movntq %%mm0, %1\n\t"
	"movntq %%mm0, %2\n\t"
	"movntq %%mm0, %3"
	: "=m"(dest[0]), "=m"(dest[8]), "=m"(dest[16]), "=m"(dest[24])::);
    #else
    asm volatile (
	"movq %%mm0, %0	\n\t"
	"movq %%mm0, %1	\n\t"
	"movq %%mm0, %2	\n\t"
	"movq %%mm0, %3"
	: "=m"(dest[0]), "=m"(dest[8]), "=m"(dest[16]), "=m"(dest[24])::);
    #endif
}

static inline void simd_block_cleanup (void)
{
    #if !CPU_HAS_SSE
	simd::reset_mmx();
    #endif
    asm volatile ("sfence");
}

/// The fastest optimized raw memory copy.
void copy_n_fast (const void* src, size_t nBytes, void* dest)
{
    movsb_dir_up();
    size_t nHeadBytes = Align(uintptr_t(src), MMX_ALIGN) - uintptr_t(src);
    nHeadBytes = min (nHeadBytes, nBytes);
    movsb (src, nHeadBytes, dest);
    nBytes -= nHeadBytes;
    if (!(uintptr_t(dest) % MMX_ALIGN)) {
	const size_t nMiddleBlocks = nBytes / MMX_BS;
	for (uoff_t i = 0; i < nMiddleBlocks; ++ i) {
	    prefetch (advance (src, 512), 0, 0);
	    simd_block_copy (src, dest);
	    src = advance (src, MMX_BS);
	    dest = advance (dest, MMX_BS);
	}
	simd_block_cleanup();
	nBytes %= MMX_BS;
    }
    movsb (src, nBytes, dest);
}
#endif // CPU_HAS_MMX

/// The fastest optimized backwards raw memory copy.
void copy_n_backward_fast (const void* first, const void* last, void* result)
{
    prefetch (first, 0, 0);
    prefetch (result, 1, 0);
    size_t nBytes (distance (first, last));
    movsb_dir_down();
    size_t nHeadBytes = uintptr_t(last) % 4;
    last = advance (last, -1);
    result = advance (result, -1);
    movsb (last, nHeadBytes, result);
    nBytes -= nHeadBytes;
    if (uintptr_t(result) % 4 == 3) {
	const size_t nMiddleBlocks = nBytes / 4;
	last = advance (last, -3);
	result = advance (result, -3);
	movsd (last, nMiddleBlocks, result);
	nBytes %= 4;
    }
    movsb (last, nBytes, result);
    movsb_dir_up();
}
#endif // __i386__

//----------------------------------------------------------------------
// Fill functions
//----------------------------------------------------------------------

#if CPU_HAS_MMX
template <typename T> inline void build_block (T) {}
template <> inline void build_block (uint8_t v)
{
    asm volatile (
	"movd %0, %%mm0\n\tpunpcklbw %%mm0, %%mm0\n\tpshufw $0, %%mm0, %%mm0"
	: : "g"(uint32_t(v)) : "mm0");
}
template <> inline void build_block (uint16_t v)
{
    asm volatile (
	"movd %0, %%mm0\n\tpshufw $0, %%mm0, %%mm0"
	: : "g"(uint32_t(v)) : "mm0");
}
template <> inline void build_block (uint32_t v)
{
    asm volatile (
	"movd %0, %%mm0\n\tpunpckldq %%mm0, %%mm0"
	: : "g"(uint32_t(v)) : "mm0");
}

static inline void simd_block_fill_loop (uint8_t*& dest, size_t count)
{
    prefetch (advance (dest, 512), 1, 0);
    for (uoff_t i = 0; i < count; ++ i, dest += MMX_BS)
	simd_block_store (dest);
    simd_block_cleanup();
    simd::reset_mmx();
}

template <typename T>
inline void fill_n_fast (T* dest, size_t count, T v)
{
    size_t nHead = Align(uintptr_t(dest), MMX_ALIGN) - uintptr_t(dest) / sizeof(T);
    nHead = min (nHead, count);
    stosv (dest, nHead, v);
    count -= nHead;
    build_block (v);
    simd_block_fill_loop ((uint8_t*&) dest, count * sizeof(T) / MMX_BS);
    count %= MMX_BS;
    stosv (dest, count, v);
}

void fill_n8_fast (uint8_t* dest, size_t count, uint8_t v)
    { fill_n_fast (dest, count, v); }
void fill_n16_fast (uint16_t* dest, size_t count, uint16_t v)
    { fill_n_fast (dest, count, v); }
void fill_n32_fast (uint32_t* dest, size_t count, uint32_t v)
    { fill_n_fast (dest, count, v); }
#else
void fill_n8_fast (uint8_t* dest, size_t count, uint8_t v) { memset (dest, v, count); }
void fill_n16_fast (uint16_t* dest, size_t count, uint16_t v) { stosv (dest, count, v); }
void fill_n32_fast (uint32_t* dest, size_t count, uint32_t v) { stosv (dest, count, v); }
#endif // CPU_HAS_MMX

} // namespace ustl

<commit_msg>Removed ::) ending from asm blocks; gcc 3.3 can't compile it.<commit_after>// This file is part of the ustl library, an STL implementation.
//
// Copyright (C) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
//
// ualgobase.cc
//
// Copy and fill optimizations are here.
//

#ifndef NDEBUG	// Optimized code here. asserts slow it down, and are checked elsewhere.
#define NDEBUG
#endif

#include "ualgobase.h"

#if __i386__

namespace ustl {

//----------------------------------------------------------------------
// Copy functions
//----------------------------------------------------------------------

#if __GNUC__ >= 3
static inline void movsb_dir_up (void) __attribute__((always_inline));
static inline void movsb_dir_down (void) __attribute__((always_inline));
static inline void movsb (const void*& src, size_t nBytes, void*& dest) __attribute__((always_inline));
static inline void movsd (const void*& src, size_t nWords, void*& dest) __attribute__((always_inline));
#endif

static inline void movsb_dir_up (void) { asm volatile ("cld"); }
static inline void movsb_dir_down (void) { asm volatile ("std"); }

static inline void movsb (const void*& src, size_t nBytes, void*& dest)
{
    asm volatile ("rep;\n\tmovsb"
	: "=&S"(src), "=&D"(dest), "=&c"(nBytes)
	: "0"(src), "1"(dest), "2"(nBytes)
	: "memory");
}

static inline void movsd (const void*& src, size_t nWords, void*& dest)
{
    asm volatile ("rep;\n\tmovsl"
	: "=&S"(src), "=&D"(dest), "=&c"(nWords)
	: "0"(src), "1"(dest), "2"(nWords)
	: "memory");
}

template <typename T> inline void stosv (T*&, size_t, T) {}
template <> inline void stosv (uint8_t*& p, size_t n, uint8_t v)
{ asm volatile ("rep;\n\tstosb" : "=&D"(p), "=c"(n) : "0"(p), "1"(n), "a"(v) : "memory"); }
template <> inline void stosv (uint16_t*& p, size_t n, uint16_t v)
{ asm volatile ("rep;\n\tstosw" : "=&D"(p), "=c"(n) : "0"(p), "1"(n), "a"(v) : "memory"); }
template <> inline void stosv (uint32_t*& p, size_t n, uint32_t v)
{ asm volatile ("rep;\n\tstosl" : "=&D"(p), "=c"(n) : "0"(p), "1"(n), "a"(v) : "memory"); }

#if CPU_HAS_MMX
#define MMX_ALIGN	16U	// Data must be aligned on this grain
#define MMX_BS		32U	// Assembly routines copy data this many bytes at a time.

static inline void simd_block_copy (const void* src, void* dest) __attribute__((always_inline));
static inline void simd_block_store (uint8_t* dest) __attribute__((always_inline));
static inline void simd_block_cleanup (void) __attribute__((always_inline));

static inline void simd_block_copy (const void* src, void* dest)
{
    #if CPU_HAS_SSE
    asm volatile (
	"movaps (%%esi), %%xmm0		\n\t"
	"movaps 16(%%esi), %%xmm1	\n\t"
	"movntps %%xmm0, (%%edi)	\n\t"
	"movntps %%xmm1, 16(%%edi)"
	: : "S"(src), "D"(dest)
	: "memory", "xmm0", "xmm1");
    #else
    asm volatile (
	"movq (%%esi), %%mm0	\n\t"
	"movq 8(%%esi), %%mm1	\n\t"
	"movq 16(%%esi), %%mm2	\n\t"
	"movq 24(%%esi), %%mm3	\n\t"
	"movq %%mm0, (%%edi)	\n\t"
	"movq %%mm1, 8(%%edi)	\n\t"
	"movq %%mm2, 16(%%edi)	\n\t"
	"movq %%mm3, 24(%%edi)"
	: : "S"(src), "D"(dest)
	: "memory", "mm0", "mm1", "mm2", "mm3", "st", "st(1)", "st(2)", "st(3)");
    #endif
}

static inline void simd_block_store (uint8_t* dest)
{
    #if CPU_HAS_SSE
    asm volatile (
	"movntq %%mm0, %0\n\t"
	"movntq %%mm0, %1\n\t"
	"movntq %%mm0, %2\n\t"
	"movntq %%mm0, %3"
	: "=m"(dest[0]), "=m"(dest[8]), "=m"(dest[16]), "=m"(dest[24]));
    #else
    asm volatile (
	"movq %%mm0, %0	\n\t"
	"movq %%mm0, %1	\n\t"
	"movq %%mm0, %2	\n\t"
	"movq %%mm0, %3"
	: "=m"(dest[0]), "=m"(dest[8]), "=m"(dest[16]), "=m"(dest[24]));
    #endif
}

static inline void simd_block_cleanup (void)
{
    #if !CPU_HAS_SSE
	simd::reset_mmx();
    #endif
    asm volatile ("sfence");
}

/// The fastest optimized raw memory copy.
void copy_n_fast (const void* src, size_t nBytes, void* dest)
{
    movsb_dir_up();
    size_t nHeadBytes = Align(uintptr_t(src), MMX_ALIGN) - uintptr_t(src);
    nHeadBytes = min (nHeadBytes, nBytes);
    movsb (src, nHeadBytes, dest);
    nBytes -= nHeadBytes;
    if (!(uintptr_t(dest) % MMX_ALIGN)) {
	const size_t nMiddleBlocks = nBytes / MMX_BS;
	for (uoff_t i = 0; i < nMiddleBlocks; ++ i) {
	    prefetch (advance (src, 512), 0, 0);
	    simd_block_copy (src, dest);
	    src = advance (src, MMX_BS);
	    dest = advance (dest, MMX_BS);
	}
	simd_block_cleanup();
	nBytes %= MMX_BS;
    }
    movsb (src, nBytes, dest);
}
#endif // CPU_HAS_MMX

/// The fastest optimized backwards raw memory copy.
void copy_n_backward_fast (const void* first, const void* last, void* result)
{
    prefetch (first, 0, 0);
    prefetch (result, 1, 0);
    size_t nBytes (distance (first, last));
    movsb_dir_down();
    size_t nHeadBytes = uintptr_t(last) % 4;
    last = advance (last, -1);
    result = advance (result, -1);
    movsb (last, nHeadBytes, result);
    nBytes -= nHeadBytes;
    if (uintptr_t(result) % 4 == 3) {
	const size_t nMiddleBlocks = nBytes / 4;
	last = advance (last, -3);
	result = advance (result, -3);
	movsd (last, nMiddleBlocks, result);
	nBytes %= 4;
    }
    movsb (last, nBytes, result);
    movsb_dir_up();
}
#endif // __i386__

//----------------------------------------------------------------------
// Fill functions
//----------------------------------------------------------------------

#if CPU_HAS_MMX
template <typename T> inline void build_block (T) {}
template <> inline void build_block (uint8_t v)
{
    asm volatile (
	"movd %0, %%mm0\n\tpunpcklbw %%mm0, %%mm0\n\tpshufw $0, %%mm0, %%mm0"
	: : "g"(uint32_t(v)) : "mm0");
}
template <> inline void build_block (uint16_t v)
{
    asm volatile (
	"movd %0, %%mm0\n\tpshufw $0, %%mm0, %%mm0"
	: : "g"(uint32_t(v)) : "mm0");
}
template <> inline void build_block (uint32_t v)
{
    asm volatile (
	"movd %0, %%mm0\n\tpunpckldq %%mm0, %%mm0"
	: : "g"(uint32_t(v)) : "mm0");
}

static inline void simd_block_fill_loop (uint8_t*& dest, size_t count)
{
    prefetch (advance (dest, 512), 1, 0);
    for (uoff_t i = 0; i < count; ++ i, dest += MMX_BS)
	simd_block_store (dest);
    simd_block_cleanup();
    simd::reset_mmx();
}

template <typename T>
inline void fill_n_fast (T* dest, size_t count, T v)
{
    size_t nHead = Align(uintptr_t(dest), MMX_ALIGN) - uintptr_t(dest) / sizeof(T);
    nHead = min (nHead, count);
    stosv (dest, nHead, v);
    count -= nHead;
    build_block (v);
    simd_block_fill_loop ((uint8_t*&) dest, count * sizeof(T) / MMX_BS);
    count %= MMX_BS;
    stosv (dest, count, v);
}

void fill_n8_fast (uint8_t* dest, size_t count, uint8_t v)
    { fill_n_fast (dest, count, v); }
void fill_n16_fast (uint16_t* dest, size_t count, uint16_t v)
    { fill_n_fast (dest, count, v); }
void fill_n32_fast (uint32_t* dest, size_t count, uint32_t v)
    { fill_n_fast (dest, count, v); }
#else
void fill_n8_fast (uint8_t* dest, size_t count, uint8_t v) { memset (dest, v, count); }
void fill_n16_fast (uint16_t* dest, size_t count, uint16_t v) { stosv (dest, count, v); }
void fill_n32_fast (uint32_t* dest, size_t count, uint32_t v) { stosv (dest, count, v); }
#endif // CPU_HAS_MMX

} // namespace ustl

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004-2013 ZNC, see the NOTICE file for details.
 * Copyright (C) 2013 Rasmus Eskola <fruitiex@gmail.com>
 * based on sample.cpp sample module code
 *
 * 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 <znc/FileUtils.h>
#include <znc/Client.h>
#include <znc/Chan.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Modules.h>
#include <dirent.h>
#include <vector>
#include <algorithm>

class CBacklogMod : public CModule {
public:
	MODCONSTRUCTOR(CBacklogMod) {}

	virtual bool OnLoad(const CString& sArgs, CString& sMessage);
	virtual ~CBacklogMod();
	virtual void OnModCommand(const CString& sCommand);

private:
	CString			LogPath;
};

bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) {
	LogPath = sArgs;

	if(LogPath.empty()) {
		LogPath = GetNV("LogPath");
		if(LogPath.empty()) {
			// TODO: guess logpath?
			PutModule("LogPath is empty, set it with the LogPath command");
			PutModule("Usage: LogPath <path> (use keywords $USER, $NETWORK, $WINDOW)");
		}
	} else {
		SetNV("LogPath", LogPath);
		PutModule("LogPath set to: " + LogPath);
	}
	return true;
}

CBacklogMod::~CBacklogMod() {
}

void CBacklogMod::OnModCommand(const CString& sCommand) {
	if (sCommand.Token(0).CaseCmp("help") == 0) {
		// TODO: proper help text, look how AddHelpCommand() does it in other ZNC code
		PutModule("Help");
		return;
	}
	else if (sCommand.Token(0).CaseCmp("logpath") == 0) {
		LogPath = sCommand.Token(1, true);

		if(LogPath.empty()) {
			PutModule("Usage: LogPath <path> (use keywords $USER, $NETWORK, $WINDOW)");
			PutModule("Current LogPath is set to: " + GetNV("LogPath"));
			return;
		}

		SetNV("LogPath", LogPath);
		PutModule("LogPath set to: " + LogPath);
		return;
	}

	// TODO: handle these differently depending on how the module was loaded
	CString User = (m_pUser ? m_pUser->GetUserName() : "UNKNOWN");
	CString Network = (m_pNetwork ? m_pNetwork->GetName() : "znc");
	CString Channel = sCommand.Token(0);

	int printedLines = 0;
	int reqLines = sCommand.Token(1).ToInt();
	if(reqLines <= 0) {
		reqLines = 150;
	}

	CString Path = LogPath.substr(); // make copy
	Path.Replace("$NETWORK", Network);
	Path.Replace("$WINDOW", Channel);
	Path.Replace("$USER", User);

	CString DirPath = Path.substr(0, Path.find_last_of("/"));
	CString FilePath;

	std::vector<CString> FileList;
	std::vector<CString> LinesToPrint;

	// gather list of all log files for requested channel/window
	DIR *dir;
	struct dirent *ent;
	if ((dir = opendir (DirPath.c_str())) != NULL) {
		while ((ent = readdir (dir)) != NULL) {
			FilePath = DirPath + "/" + ent->d_name;
			//PutModule("DEBUG: " + FilePath + " " + Path);
			if(FilePath.StrCmp(Path, Path.find_last_of("*")) == 0) {
				FileList.push_back(FilePath);
			}
		}
		closedir (dir);
	} else {
		PutModule("Could not list directory " + DirPath + ": " + strerror(errno));
		return;
	}

	std::sort(FileList.begin(), FileList.end());

	// loop through list of log files one by one starting from most recent...
	for (std::vector<CString>::reverse_iterator it = FileList.rbegin(); it != FileList.rend(); ++it) {
		CFile LogFile(*it);
		CString Line;
		std::vector<CString> Lines;

		if (LogFile.Open()) {
			while (LogFile.ReadLine(Line)) {
				// store lines from file into Lines
				Lines.push_back(Line);
			}
		} else {
			PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno));
			continue;
		}

		LogFile.Close();

		// loop through Lines in reverse order, push to LinesToPrint
		for (std::vector<CString>::reverse_iterator itl = Lines.rbegin(); itl != Lines.rend(); ++itl) {
			LinesToPrint.push_back(*itl);
			printedLines++;

			if(printedLines >= reqLines) {
				break;
			}
		}

		if(printedLines >= reqLines) {
			break;
		}
	}

	// now actually print
	for (std::vector<CString>::reverse_iterator it = LinesToPrint.rbegin(); it != LinesToPrint.rend(); ++it) {
		PutModule(*it);
	}

	if(printedLines == 0) {
		PutModule("No log files found for window " + Channel + " in " + DirPath + "/");
	}
}

template<> void TModInfo<CBacklogMod>(CModInfo& Info) {
	Info.AddType(CModInfo::NetworkModule);
	Info.AddType(CModInfo::GlobalModule);
	Info.SetWikiPage("backlog");
	Info.SetArgsHelpText("Takes as optional argument (and if given, sets) the log path, use keywords: $USER, $NETWORK and $WINDOW");
	Info.SetHasArgs(true);
}

NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.")
<commit_msg>WIP: print message log into correct window, currently does not work if that window is not joined<commit_after>/*
 * Copyright (C) 2004-2013 ZNC, see the NOTICE file for details.
 * Copyright (C) 2013 Rasmus Eskola <fruitiex@gmail.com>
 * based on sample.cpp sample module code
 *
 * 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 <znc/FileUtils.h>
#include <znc/Client.h>
#include <znc/Chan.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Modules.h>
#include <dirent.h>
#include <vector>
#include <algorithm>

class CBacklogMod : public CModule {
public:
	MODCONSTRUCTOR(CBacklogMod) {}

	virtual bool OnLoad(const CString& sArgs, CString& sMessage);
	virtual ~CBacklogMod();
	virtual void OnModCommand(const CString& sCommand);

private:
	CString			LogPath;
};

bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) {
	LogPath = sArgs;

	if(LogPath.empty()) {
		LogPath = GetNV("LogPath");
		if(LogPath.empty()) {
			// TODO: guess logpath?
			PutModule("LogPath is empty, set it with the LogPath command");
			PutModule("Usage: LogPath <path> (use keywords $USER, $NETWORK, $WINDOW)");
		}
	} else {
		SetNV("LogPath", LogPath);
		PutModule("LogPath set to: " + LogPath);
	}
	return true;
}

CBacklogMod::~CBacklogMod() {
}

void CBacklogMod::OnModCommand(const CString& sCommand) {
	if (sCommand.Token(0).CaseCmp("help") == 0) {
		// TODO: proper help text, look how AddHelpCommand() does it in other ZNC code
		PutModule("Help");
		return;
	}
	else if (sCommand.Token(0).CaseCmp("logpath") == 0) {
		LogPath = sCommand.Token(1, true);

		if(LogPath.empty()) {
			PutModule("Usage: LogPath <path> (use keywords $USER, $NETWORK, $WINDOW)");
			PutModule("Current LogPath is set to: " + GetNV("LogPath"));
			return;
		}

		SetNV("LogPath", LogPath);
		PutModule("LogPath set to: " + LogPath);
		return;
	}

	// TODO: handle these differently depending on how the module was loaded
	CString User = (m_pUser ? m_pUser->GetUserName() : "UNKNOWN");
	CString Network = (m_pNetwork ? m_pNetwork->GetName() : "znc");
	CString Channel = sCommand.Token(0);

	int printedLines = 0;
	int reqLines = sCommand.Token(1).ToInt();
	if(reqLines <= 0) {
		reqLines = 150;
	}

	CString Path = LogPath.substr(); // make copy
	Path.Replace("$NETWORK", Network);
	Path.Replace("$WINDOW", Channel);
	Path.Replace("$USER", User);

	CString DirPath = Path.substr(0, Path.find_last_of("/"));
	CString FilePath;

	std::vector<CString> FileList;
	std::vector<CString> LinesToPrint;

	// gather list of all log files for requested channel/window
	DIR *dir;
	struct dirent *ent;
	if ((dir = opendir (DirPath.c_str())) != NULL) {
		while ((ent = readdir (dir)) != NULL) {
			FilePath = DirPath + "/" + ent->d_name;
			//PutModule("DEBUG: " + FilePath + " " + Path);
			if(FilePath.StrCmp(Path, Path.find_last_of("*")) == 0) {
				FileList.push_back(FilePath);
			}
		}
		closedir (dir);
	} else {
		PutModule("Could not list directory " + DirPath + ": " + strerror(errno));
		return;
	}

	std::sort(FileList.begin(), FileList.end());

	// loop through list of log files one by one starting from most recent...
	for (std::vector<CString>::reverse_iterator it = FileList.rbegin(); it != FileList.rend(); ++it) {
		CFile LogFile(*it);
		CString Line;
		std::vector<CString> Lines;

		if (LogFile.Open()) {
			while (LogFile.ReadLine(Line)) {
				// store lines from file into Lines
				Lines.push_back(Line);
			}
		} else {
			PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno));
			continue;
		}

		LogFile.Close();

		// loop through Lines in reverse order, push to LinesToPrint
		for (std::vector<CString>::reverse_iterator itl = Lines.rbegin(); itl != Lines.rend(); ++itl) {
			LinesToPrint.push_back(*itl);
			printedLines++;

			if(printedLines >= reqLines) {
				break;
			}
		}

		if(printedLines >= reqLines) {
			break;
		}
	}

	// now actually print
	for (std::vector<CString>::reverse_iterator it = LinesToPrint.rbegin(); it != LinesToPrint.rend(); ++it) {
		// if(channel has been joined) {
			CString Nick = "foo";
			m_pNetwork->PutUser(":" + Nick + "!znc@znc.in PRIVMSG " + Channel + " :" + *it, GetClient());
		// } else {
		//	PutModule(*it);
		// }
	}

	if(printedLines == 0) {
		PutModule("No log files found for window " + Channel + " in " + DirPath + "/");
	}
}

template<> void TModInfo<CBacklogMod>(CModInfo& Info) {
	Info.AddType(CModInfo::NetworkModule);
	Info.AddType(CModInfo::GlobalModule);
	Info.SetWikiPage("backlog");
	Info.SetArgsHelpText("Takes as optional argument (and if given, sets) the log path, use keywords: $USER, $NETWORK and $WINDOW");
	Info.SetHasArgs(true);
}

NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.")
<|endoftext|>


<commit_before>#include "UserCode/diall/interface/anaBaseTask.h"

#include "TClass.h"
#include "TDirectory.h"

ClassImp(anaBaseTask)

anaBaseTask::anaBaseTask(const char *name, const char *title)
:TTask(name,title),
  fEventObjects(0),
  fInitOutput(0),
  fDir(0x0),
  fOutput(0),
  fEvtName(""),
  fHiEvent(),
  fTriggerMapName(""),
  fTriggerMap(),
  fTriggerList(0),
  fCollSel(0),
  fHBHENoise(0),
  fCentMin(-999),
  fCentMax(999),
  fPFJet80(0),
  fPhoton30(0),
  fPhoton30Excl(0),
  fTrk24(0),
  fTrk45(0)
{

}

//----------------------------------------------------------
void anaBaseTask::Exec(Option_t * /*option*/)
{
  if(!fInitOutput) CreateOutputObjects();

  //Get event properties
  if(!fHiEvent && !fEvtName.IsNull()) {
     fHiEvent = dynamic_cast<hiEventContainer*>(fEventObjects->FindObject(fEvtName.Data()));
     if(!fHiEvent) {
       Printf("%s: !!WARNING: Couldn't locate %s branch",GetName(),fEvtName.Data());
       return;
     }
  }

  //Get trigger map
  if(!fTriggerMap && !fTriggerMapName.IsNull()) {
    fTriggerMap = dynamic_cast<triggerMap*>(fEventObjects->FindObject(fTriggerMapName.Data()));
    if(!fTriggerMap) {
      Printf("%s: !!WARNING: Couldn't locate %s branch",GetName(),fTriggerMapName.Data());
      return;
    }
  }

  //if(!SelectEvent()) return;
}

//----------------------------------------------------------
void anaBaseTask::CreateOutputObjects() {

  if(!fDir) {
    TString dirName = GetName();
    fDir = new TDirectory(dirName.Data(),dirName.Data());
  }
  fDir->cd();
  if(!fOutput) fOutput = new TList();
  if(!fOutput) {
    Printf("%s: There is a problem. fOutput does not exist",GetName());
    return;
  }
  fOutput->SetName(GetName());

  fInitOutput = kTRUE;
}

//----------------------------------------------------------
Bool_t anaBaseTask::CheckInheritance(TClonesArray *c, TString clsName) {

  //check if inheritance is to expected type
  TString objname(c->GetClass()->GetName());
  TClass cls(objname);
  if (!cls.InheritsFrom(clsName)) {
    Printf("%s: Objects of type %s are not inherited from %s!",
           GetName(), cls.GetName(), clsName.Data());
    return kFALSE;
  }
  return kTRUE;
}

//----------------------------------------------------------
bool anaBaseTask::SelectEvent() const {
  //
  //pcollision, hbhenoise
  //triggers

  bool accept = true;

  if(fHiEvent) {
    if(fCollSel && !fHiEvent->GetColl()) accept = false;
    //  printf("accept 1 %d %d %d\n", accept, fCollSel, !fHiEvent->GetColl()); }
    if(fHBHENoise && !fHiEvent->GetHBHENoise()) accept = false;
    //  printf("accept 2 %d %d %d\n", accept, fHBHENoise, !fHiEvent->GetHBHENoise()); }
    if(fCentMin>-1) {
      double cent = fHiEvent->GetCentrality();
      if(cent<fCentMin && cent>fCentMax) accept = false;
//	printf("accept 3 %d %f %d\n", accept, cent, !fHiEvent->GetCentrality()); }
    }

    if(fPFJet80 && !fHiEvent->GetPFJet80()) { accept = false;
  //    printf("accept 4 %d %d %d\n", accept, fPFJet80, !fHiEvent->GetPFJet80() );
    }
    if(fPhoton30 && !fHiEvent->GetPhoton30()) { accept = false;
    //  printf("accept 5 %d %d %d\n", accept, fPhoton30, !fHiEvent->GetPhoton30() );
    }
    if(fTrk24 && !fHiEvent->GetTrk24()) accept = false;
     // printf("accept 6 %d %d %d\n", accept, fTrk24, !fHiEvent->GetTrk24()); }
    if(fTrk45 && !fHiEvent->GetTrk45()) { accept = false;
     // printf("accept 7 %d %d %d\n", accept, fTrk45, !fHiEvent->GetTrk45() );
    }

    //special for express stream
    if(fPhoton30Excl && fHiEvent->GetPhoton30()) { accept = false;
 //     printf("accept 8 %d %d %d\n", accept, fPhoton30Excl, !fHiEvent->GetPhoton30() );
    }
  }

  if(fTriggerMap && accept) {
    bool passTrig = false;
    for(std::vector<std::string>::const_iterator s = fTriggerList.begin(); s != fTriggerList.end(); ++s) {
       int fire = fTriggerMap->TriggerFired(*s);
       if(fire>0) passTrig = true;
    }
    accept = passTrig;
  }

  return accept;
}
<commit_msg>add vz selection to base task<commit_after>#include "UserCode/diall/interface/anaBaseTask.h"

#include "TClass.h"
#include "TDirectory.h"

ClassImp(anaBaseTask)

anaBaseTask::anaBaseTask(const char *name, const char *title)
:TTask(name,title),
  fEventObjects(0),
  fInitOutput(0),
  fDir(0x0),
  fOutput(0),
  fEvtName(""),
  fHiEvent(),
  fTriggerMapName(""),
  fTriggerMap(),
  fTriggerList(0),
  fCollSel(0),
  fHBHENoise(0),
  fCentMin(-999),
  fCentMax(999),
  fPFJet80(0),
  fPhoton30(0),
  fPhoton30Excl(0),
  fTrk24(0),
  fTrk45(0)
{

}

//----------------------------------------------------------
void anaBaseTask::Exec(Option_t * /*option*/)
{
  if(!fInitOutput) CreateOutputObjects();

  //Get event properties
  if(!fHiEvent && !fEvtName.IsNull()) {
     fHiEvent = dynamic_cast<hiEventContainer*>(fEventObjects->FindObject(fEvtName.Data()));
     if(!fHiEvent) {
       Printf("%s: !!WARNING: Couldn't locate %s branch",GetName(),fEvtName.Data());
       return;
     }
  }

  //Get trigger map
  if(!fTriggerMap && !fTriggerMapName.IsNull()) {
    fTriggerMap = dynamic_cast<triggerMap*>(fEventObjects->FindObject(fTriggerMapName.Data()));
    if(!fTriggerMap) {
      Printf("%s: !!WARNING: Couldn't locate %s branch",GetName(),fTriggerMapName.Data());
      return;
    }
  }

  //if(!SelectEvent()) return;
}

//----------------------------------------------------------
void anaBaseTask::CreateOutputObjects() {

  if(!fDir) {
    TString dirName = GetName();
    fDir = new TDirectory(dirName.Data(),dirName.Data());
  }
  fDir->cd();
  if(!fOutput) fOutput = new TList();
  if(!fOutput) {
    Printf("%s: There is a problem. fOutput does not exist",GetName());
    return;
  }
  fOutput->SetName(GetName());

  fInitOutput = kTRUE;
}

//----------------------------------------------------------
Bool_t anaBaseTask::CheckInheritance(TClonesArray *c, TString clsName) {

  //check if inheritance is to expected type
  TString objname(c->GetClass()->GetName());
  TClass cls(objname);
  if (!cls.InheritsFrom(clsName)) {
    Printf("%s: Objects of type %s are not inherited from %s!",
           GetName(), cls.GetName(), clsName.Data());
    return kFALSE;
  }
  return kTRUE;
}

//----------------------------------------------------------
bool anaBaseTask::SelectEvent() const {
  //
  //pcollision, hbhenoise
  //triggers

  bool accept = true;

  if(fHiEvent) {
    if(std::abs(fHiEvent->GetVz())>15.) accept = false;
    if(fCollSel && !fHiEvent->GetColl()) accept = false;
    //  printf("accept 1 %d %d %d\n", accept, fCollSel, !fHiEvent->GetColl()); }
    if(fHBHENoise && !fHiEvent->GetHBHENoise()) accept = false;
    //  printf("accept 2 %d %d %d\n", accept, fHBHENoise, !fHiEvent->GetHBHENoise()); }
    if(fCentMin>-1) {
      double cent = fHiEvent->GetCentrality();
      if(cent<fCentMin && cent>fCentMax) accept = false;
//	printf("accept 3 %d %f %d\n", accept, cent, !fHiEvent->GetCentrality()); }
    }

    if(fPFJet80 && !fHiEvent->GetPFJet80()) { accept = false;
  //    printf("accept 4 %d %d %d\n", accept, fPFJet80, !fHiEvent->GetPFJet80() );
    }
    if(fPhoton30 && !fHiEvent->GetPhoton30()) { accept = false;
    //  printf("accept 5 %d %d %d\n", accept, fPhoton30, !fHiEvent->GetPhoton30() );
    }
    if(fTrk24 && !fHiEvent->GetTrk24()) accept = false;
     // printf("accept 6 %d %d %d\n", accept, fTrk24, !fHiEvent->GetTrk24()); }
    if(fTrk45 && !fHiEvent->GetTrk45()) { accept = false;
     // printf("accept 7 %d %d %d\n", accept, fTrk45, !fHiEvent->GetTrk45() );
    }

    //special for express stream
    if(fPhoton30Excl && fHiEvent->GetPhoton30()) { accept = false;
 //     printf("accept 8 %d %d %d\n", accept, fPhoton30Excl, !fHiEvent->GetPhoton30() );
    }
  }

  if(fTriggerMap && accept) {
    bool passTrig = false;
    for(std::vector<std::string>::const_iterator s = fTriggerList.begin(); s != fTriggerList.end(); ++s) {
       int fire = fTriggerMap->TriggerFired(*s);
       if(fire>0) passTrig = true;
    }
    accept = passTrig;
  }

  return accept;
}
<|endoftext|>