<commit_before>#include <avro/BinaryEncoder.hh>
#include <avro/Compiler.hh>
#include <avro/Decoder.hh>
#include <avro/Encoder.hh>
#include <avro/Generic.hh>
#include <avro/Specific.hh>
#include <avro/Symbol.hh>
#include <avro/ValidSchema.hh>
#include <avro/buffer/Buffer.hh>
#include <avro/buffer/BufferStream.hh>
#include <avro/json/JsonEncoder.hh>
#include <node.h>
#include <node_buffer.h>
#include <v8.h>

using namespace std;
using namespace v8;

Persistent<ObjectTemplate> avroSchemaTemplate;

Handle<ObjectTemplate> MakeAvroSchemaTemplate() {
  HandleScope handle_scope;
  Handle<ObjectTemplate> result = ObjectTemplate::New();
  result->SetInternalFieldCount(1);
  return handle_scope.Close(result);
}

/*
  Wraps a parsed schema in a V8 schema object.
*/
Handle<Object> WrapAvroSchema(avro::ValidSchema *schema) {
  HandleScope handle_scope;
  if (avroSchemaTemplate.IsEmpty()) {
    Handle<ObjectTemplate> rawTemplate = MakeAvroSchemaTemplate();
    avroSchemaTemplate = Persistent<ObjectTemplate>::New(rawTemplate);
  }
  Handle<ObjectTemplate> templ = avroSchemaTemplate;
  Handle<Object> result = templ->NewInstance();
  Handle<External> schemaPtr = External::New(schema);
  result->SetInternalField(0, schemaPtr);
  return handle_scope.Close(result);
}

/*
  Extracts the wrapped schema from a V8 schema object.
*/
avro::ValidSchema *UnwrapAvroSchema(Handle<Object> obj) {
  Handle<External> field = Handle<External>::Cast(obj->GetInternalField(0));
  void* ptr = field->Value();
  return static_cast<avro::ValidSchema*>(ptr);
}

/*
  Takes a JSON schema as input and returns a V8 schema object.
*/
static Handle<Value> ParseAvroSchema(const Arguments& args) {
  HandleScope scope;

  if (args.Length() != 1) {
    ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
    return scope.Close(Undefined());
  }

  Handle<Value> schemaString = args[0];

  if (!schemaString->IsString()) {
    ThrowException(Exception::TypeError(String::New("Schema must be a string")));
    return scope.Close(Undefined());
  }

  String::Utf8Value schemaUtf8Value(schemaString);
  uint8_t *schemaBytes = (uint8_t *) *schemaUtf8Value;

  avro::ValidSchema *schema =
    new avro::ValidSchema(avro::compileJsonSchemaFromMemory(schemaBytes, schemaUtf8Value.length()));

  return WrapAvroSchema(schema);
}

/*
  Takes two arguments, an Avro schema as a JSON string, and an Avro
  value as a JSON string, and returns a buffer containing the encoded
  data.
*/
static Handle<Value> JsonStringToAvroBuffer(const Arguments& args) {
  HandleScope scope;

  // Check arguments

  if (args.Length() != 2) {
    ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
    return scope.Close(Undefined());
  }

  Handle<Object> schemaObject = args[0]->ToObject();
  Handle<Value> jsonString = args[1];

  if (!jsonString->IsString()) {
    ThrowException(Exception::TypeError(String::New("JSON must be a string")));
    return scope.Close(Undefined());
  }

  // Get schema

  avro::ValidSchema schema = *UnwrapAvroSchema(schemaObject);

  // Decode JSON from string

  String::Utf8Value jsonUtf8Value(jsonString);
  uint8_t *jsonBytes = (uint8_t *) *jsonUtf8Value;
  auto_ptr<avro::InputStream> in = avro::memoryInputStream(jsonBytes, jsonUtf8Value.length());
  avro::DecoderPtr decoder = avro::jsonDecoder(schema);
  decoder->init(*in);
  avro::GenericDatum datum(schema);
  avro::decode(*decoder, datum);

  // Encode datum to output stream backed by stringstream

  stringstream ss(stringstream::out);
  auto_ptr<avro::OutputStream> out = avro::ostreamOutputStream(ss);
  avro::EncoderPtr encoder = avro::binaryEncoder();
  encoder->init(*out);
  avro::encode(*encoder, datum);
  encoder->flush();
  out->flush();
  string s = ss.str();

  // Copy data to buffer and return it

  avro::BinaryEncoder *binaryEncoder = (avro::BinaryEncoder *) &(*encoder);
  avro::StreamWriter &sw = binaryEncoder->getStreamWriter();

  Handle<Value> buffer = node::Buffer::New((char *) s.data(), sw.getBytesWritten())->handle_;
  return scope.Close(buffer);
}

/*
  Takes two arguments, an Avro schema as a JSON string, and a buffer
  containing encoded data, and returns a JSON string containing the
  decoded Avro value.
*/
static Handle<Value> AvroBufferToJsonString(const Arguments& args) {
  HandleScope scope;

  // Check arguments

  if (args.Length() != 2) {
    ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
    return scope.Close(Undefined());
  }

  Handle<Object> schemaObject = args[0]->ToObject();
  Handle<Value> avroBuffer = args[1];

  if (!node::Buffer::HasInstance(avroBuffer)) {
    ThrowException(Exception::TypeError(String::New("Not a buffer")));
    return scope.Close(Undefined());
  }

  // Get schema

  avro::ValidSchema schema = *UnwrapAvroSchema(schemaObject);

  // Decode data from buffer

  auto_ptr<avro::InputStream> in =
    avro::memoryInputStream((uint8_t *) node::Buffer::Data(avroBuffer->ToObject()),
                            node::Buffer::Length(avroBuffer->ToObject()));
  avro::DecoderPtr decoder = avro::binaryDecoder();
  decoder->init(*in);
  avro::GenericDatum datum(schema);
  avro::decode(*decoder, datum);

  // Encode data to JSON

  stringstream ss(stringstream::out);
  auto_ptr<avro::OutputStream> out = avro::ostreamOutputStream(ss);
  avro::EncoderPtr encoder = avro::jsonEncoder(schema);
  encoder->init(*out);
  avro::encode(*encoder, datum);
  encoder->flush();
  out->flush();
  string s = ss.str();

  avro::parsing::JsonEncoder<avro::parsing::SimpleParser<avro::parsing::JsonHandler> >  *jsonEncoder =
    (avro::parsing::JsonEncoder<avro::parsing::SimpleParser<avro::parsing::JsonHandler> > *) &(*encoder);
  avro::StreamWriter &sw = jsonEncoder->getStreamWriter();

  return scope.Close(String::New((char *) s.data(), sw.getBytesWritten()));
}

void init(Handle<Object> target) {
  target->Set(String::NewSymbol("jsonStringToAvroBuffer"),
              FunctionTemplate::New(JsonStringToAvroBuffer)->GetFunction());
  target->Set(String::NewSymbol("avroBufferToJsonString"),
              FunctionTemplate::New(AvroBufferToJsonString)->GetFunction());
  target->Set(String::NewSymbol("parseSchema"),
              FunctionTemplate::New(ParseAvroSchema)->GetFunction());
}

NODE_MODULE(avro, init)
<commit_msg>Return result of v8::ThrowException instead of undefined, as the V8 sample code does.<commit_after>#include <avro/BinaryEncoder.hh>
#include <avro/Compiler.hh>
#include <avro/Decoder.hh>
#include <avro/Encoder.hh>
#include <avro/Generic.hh>
#include <avro/Specific.hh>
#include <avro/Symbol.hh>
#include <avro/ValidSchema.hh>
#include <avro/buffer/Buffer.hh>
#include <avro/buffer/BufferStream.hh>
#include <avro/json/JsonEncoder.hh>
#include <node.h>
#include <node_buffer.h>
#include <v8.h>

using namespace std;
using namespace v8;

Persistent<ObjectTemplate> avroSchemaTemplate;

Handle<ObjectTemplate> MakeAvroSchemaTemplate() {
  HandleScope handle_scope;
  Handle<ObjectTemplate> result = ObjectTemplate::New();
  result->SetInternalFieldCount(1);
  return handle_scope.Close(result);
}

/*
  Wraps a parsed schema in a V8 schema object.
*/
Handle<Object> WrapAvroSchema(avro::ValidSchema *schema) {
  HandleScope handle_scope;
  if (avroSchemaTemplate.IsEmpty()) {
    Handle<ObjectTemplate> rawTemplate = MakeAvroSchemaTemplate();
    avroSchemaTemplate = Persistent<ObjectTemplate>::New(rawTemplate);
  }
  Handle<ObjectTemplate> templ = avroSchemaTemplate;
  Handle<Object> result = templ->NewInstance();
  Handle<External> schemaPtr = External::New(schema);
  result->SetInternalField(0, schemaPtr);
  return handle_scope.Close(result);
}

/*
  Extracts the wrapped schema from a V8 schema object.
*/
avro::ValidSchema *UnwrapAvroSchema(Handle<Object> obj) {
  Handle<External> field = Handle<External>::Cast(obj->GetInternalField(0));
  void* ptr = field->Value();
  return static_cast<avro::ValidSchema*>(ptr);
}

/*
  Takes a JSON schema as input and returns a V8 schema object.
*/
static Handle<Value> ParseAvroSchema(const Arguments& args) {
  HandleScope scope;

  if (args.Length() != 1) {
    return ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
  }

  Handle<Value> schemaString = args[0];

  if (!schemaString->IsString()) {
    return ThrowException(Exception::TypeError(String::New("Schema must be a string")));
  }

  String::Utf8Value schemaUtf8Value(schemaString);
  uint8_t *schemaBytes = (uint8_t *) *schemaUtf8Value;

  avro::ValidSchema *schema =
    new avro::ValidSchema(avro::compileJsonSchemaFromMemory(schemaBytes, schemaUtf8Value.length()));

  return WrapAvroSchema(schema);
}

/*
  Takes two arguments, an Avro schema as a JSON string, and an Avro
  value as a JSON string, and returns a buffer containing the encoded
  data.
*/
static Handle<Value> JsonStringToAvroBuffer(const Arguments& args) {
  HandleScope scope;

  // Check arguments

  if (args.Length() != 2) {
    return ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
  }

  Handle<Object> schemaObject = args[0]->ToObject();
  Handle<Value> jsonString = args[1];

  if (!jsonString->IsString()) {
    return ThrowException(Exception::TypeError(String::New("JSON must be a string")));
  }

  // Get schema

  avro::ValidSchema schema = *UnwrapAvroSchema(schemaObject);

  // Decode JSON from string

  String::Utf8Value jsonUtf8Value(jsonString);
  uint8_t *jsonBytes = (uint8_t *) *jsonUtf8Value;
  auto_ptr<avro::InputStream> in = avro::memoryInputStream(jsonBytes, jsonUtf8Value.length());
  avro::DecoderPtr decoder = avro::jsonDecoder(schema);
  decoder->init(*in);
  avro::GenericDatum datum(schema);
  avro::decode(*decoder, datum);

  // Encode datum to output stream backed by stringstream

  stringstream ss(stringstream::out);
  auto_ptr<avro::OutputStream> out = avro::ostreamOutputStream(ss);
  avro::EncoderPtr encoder = avro::binaryEncoder();
  encoder->init(*out);
  avro::encode(*encoder, datum);
  encoder->flush();
  out->flush();
  string s = ss.str();

  // Copy data to buffer and return it

  avro::BinaryEncoder *binaryEncoder = (avro::BinaryEncoder *) &(*encoder);
  avro::StreamWriter &sw = binaryEncoder->getStreamWriter();

  Handle<Value> buffer = node::Buffer::New((char *) s.data(), sw.getBytesWritten())->handle_;
  return scope.Close(buffer);
}

/*
  Takes two arguments, an Avro schema as a JSON string, and a buffer
  containing encoded data, and returns a JSON string containing the
  decoded Avro value.
*/
static Handle<Value> AvroBufferToJsonString(const Arguments& args) {
  HandleScope scope;

  // Check arguments

  if (args.Length() != 2) {
    return ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
  }

  Handle<Object> schemaObject = args[0]->ToObject();
  Handle<Value> avroBuffer = args[1];

  if (!node::Buffer::HasInstance(avroBuffer)) {
    return ThrowException(Exception::TypeError(String::New("Not a buffer")));
  }

  // Get schema

  avro::ValidSchema schema = *UnwrapAvroSchema(schemaObject);

  // Decode data from buffer

  auto_ptr<avro::InputStream> in =
    avro::memoryInputStream((uint8_t *) node::Buffer::Data(avroBuffer->ToObject()),
                            node::Buffer::Length(avroBuffer->ToObject()));
  avro::DecoderPtr decoder = avro::binaryDecoder();
  decoder->init(*in);
  avro::GenericDatum datum(schema);
  avro::decode(*decoder, datum);

  // Encode data to JSON

  stringstream ss(stringstream::out);
  auto_ptr<avro::OutputStream> out = avro::ostreamOutputStream(ss);
  avro::EncoderPtr encoder = avro::jsonEncoder(schema);
  encoder->init(*out);
  avro::encode(*encoder, datum);
  encoder->flush();
  out->flush();
  string s = ss.str();

  avro::parsing::JsonEncoder<avro::parsing::SimpleParser<avro::parsing::JsonHandler> >  *jsonEncoder =
    (avro::parsing::JsonEncoder<avro::parsing::SimpleParser<avro::parsing::JsonHandler> > *) &(*encoder);
  avro::StreamWriter &sw = jsonEncoder->getStreamWriter();

  return scope.Close(String::New((char *) s.data(), sw.getBytesWritten()));
}

void init(Handle<Object> target) {
  target->Set(String::NewSymbol("jsonStringToAvroBuffer"),
              FunctionTemplate::New(JsonStringToAvroBuffer)->GetFunction());
  target->Set(String::NewSymbol("avroBufferToJsonString"),
              FunctionTemplate::New(AvroBufferToJsonString)->GetFunction());
  target->Set(String::NewSymbol("parseSchema"),
              FunctionTemplate::New(ParseAvroSchema)->GetFunction());
}

NODE_MODULE(avro, init)
<|endoftext|>


<commit_before>#include "CTransition.hpp"

namespace urde
{

CTransition::CTransition(CInputStream& in)
{
}

}
<commit_msg>Implement CTransition constructor<commit_after>#include "CTransition.hpp"

namespace urde
{

CTransition::CTransition(CInputStream& in)
    : x0_id(in.readUint32Big())
    , x4_animA(in.readUint32Big())
    , x8_animB(in.readUint32Big())
    , xc_trans(CMetaTransFactory::CreateMetaTrans(in))
{
}

}
<|endoftext|>


<commit_before>#include <dbt/dbtPlateform.h>
#include <lib/endianness.h>
#include <isa/vexISA.h>

unsigned int getInitCode(DBTPlateform *platform, int start, unsigned int startAddress){

	int cycle = start;
	writeInt(platform->vliwBinaries, cycle*16+0, assembleIInstruction(VEX_CALL, 0, 0));
	writeInt(platform->vliwBinaries, cycle*16+4, 0); //OLD : assembleIInstruction(VEX_MOVI,0xffff,29)
	writeInt(platform->vliwBinaries, cycle*16+8, 0);
	writeInt(platform->vliwBinaries, cycle*16+12, 0);

	cycle++;
	writeInt(platform->vliwBinaries, cycle*16+0, 0);
	writeInt(platform->vliwBinaries, cycle*16+4, 0);
	writeInt(platform->vliwBinaries, cycle*16+8, 0);
	writeInt(platform->vliwBinaries, cycle*16+12, 0);

	cycle++;
	writeInt(platform->vliwBinaries, cycle*16+0, assembleIInstruction(VEX_STOP, 0, 0));
	writeInt(platform->vliwBinaries, cycle*16+4, 0);		//STOP
	writeInt(platform->vliwBinaries, cycle*16+8, 0);
	writeInt(platform->vliwBinaries, cycle*16+12, 0);

	cycle++;
	writeInt(platform->vliwBinaries, cycle*16+0, 0);
	writeInt(platform->vliwBinaries, cycle*16+4, 0);
	writeInt(platform->vliwBinaries, cycle*16+8, 0);
	writeInt(platform->vliwBinaries, cycle*16+12, 0);

	cycle++;
	return cycle;

}
<commit_msg>Modified init code so that it work correctly when issue width is greater then 5.<commit_after>#include <dbt/dbtPlateform.h>
#include <lib/endianness.h>
#include <isa/vexISA.h>

unsigned int getInitCode(DBTPlateform *platform, int start, unsigned int startAddress){
	char offset = (platform->vliwInitialIssueWidth>4) ? 2:1;
	int cycle = start;
	writeInt(platform->vliwBinaries, cycle*16+0, assembleIInstruction(VEX_CALL, 63, 0));
	writeInt(platform->vliwBinaries, cycle*16+4, 0); //OLD : assembleIInstruction(VEX_MOVI,0xffff,29)
	writeInt(platform->vliwBinaries, cycle*16+8, 0);
	writeInt(platform->vliwBinaries, cycle*16+12, 0);

	cycle+=offset;
	writeInt(platform->vliwBinaries, cycle*16+0, 0);
	writeInt(platform->vliwBinaries, cycle*16+4, 0);
	writeInt(platform->vliwBinaries, cycle*16+8, 0);
	writeInt(platform->vliwBinaries, cycle*16+12, 0);

	cycle+=offset;
	writeInt(platform->vliwBinaries, cycle*16+0, assembleIInstruction(VEX_STOP, 0, 0));
	writeInt(platform->vliwBinaries, cycle*16+4, 0);		//STOP
	writeInt(platform->vliwBinaries, cycle*16+8, 0);
	writeInt(platform->vliwBinaries, cycle*16+12, 0);

	cycle+=offset;
	writeInt(platform->vliwBinaries, cycle*16+0, 0);
	writeInt(platform->vliwBinaries, cycle*16+4, 0);
	writeInt(platform->vliwBinaries, cycle*16+8, 0);
	writeInt(platform->vliwBinaries, cycle*16+12, 0);

	cycle+=offset;
	return cycle;

}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

#pragma once
#ifndef NET_TCP_RTTM_HPP
#define NET_TCP_RTTM_HPP

#include <cassert>
#include <chrono>
#include <cmath>
#include <debug>

namespace net {
namespace tcp {

// [RFC 6298]
// Round Trip Time Measurer
struct RTTM {
  using timestamp_t = double;
  using duration_t = double;

  // clock granularity
  //static constexpr duration_t CLOCK_G = hw::PIT::frequency().count() / 1000;
  static constexpr duration_t CLOCK_G = 0.0011;

  static constexpr double K = 4.0;

  static constexpr double alpha = 1.0/8;
  static constexpr double beta = 1.0/4;

  timestamp_t t; // tick when measure is started

  duration_t SRTT; // smoothed round-trip time
  duration_t RTTVAR; // round-trip time variation
  duration_t RTO; // retransmission timeout

  bool active;

  RTTM()
    : t(0), SRTT(1.0), RTTVAR(1.0), RTO(1.0), active(false)
  {}

  void start();

  void stop(bool first = false);

  auto rto_ms() const
  { return std::chrono::milliseconds{static_cast<unsigned long>(RTO * 1000)}; }

  /*
    When the first RTT measurement R is made, the host MUST set

    SRTT <- R
    RTTVAR <- R/2
    RTO <- SRTT + max (G, K*RTTVAR)

    where K = 4.
  */
  void first_rtt_measurement(duration_t R) {
    SRTT = R;
    RTTVAR = R/2;
    update_rto();
  }

  /*
    When a subsequent RTT measurement R' is made, a host MUST set

    RTTVAR <- (1 - beta) * RTTVAR + beta * |SRTT - R'|
    SRTT <- (1 - alpha) * SRTT + alpha * R'

    The value of SRTT used in the update to RTTVAR is its value
    before updating SRTT itself using the second assignment.  That
    is, updating RTTVAR and SRTT MUST be computed in the above
    order.

    The above SHOULD be computed using alpha=1/8 and beta=1/4 (as
    suggested in [JK88]).

    After the computation, a host MUST update
    RTO <- SRTT + max (G, K*RTTVAR)
  */
  void sub_rtt_measurement(duration_t R) {
    RTTVAR = (1 - beta) * RTTVAR + beta * std::abs(SRTT-R);
    SRTT = (1 - alpha) * SRTT + alpha * R;
    update_rto();
  }

  void update_rto() {
    RTO = std::max(SRTT + std::max(CLOCK_G, K * RTTVAR), 1.0);
    debug2("<TCP::Connection::RTO> RTO updated: %ums\n",
      (uint32_t)(RTO * 1000));
  }
}; // < struct RTTM

} // < namespace tcp
} // < namespace net

#endif // < NET_TCP_RTTM_HPP
<commit_msg>tcp/rttm.hpp - Missing #include <algorithm> for std::max calls<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

#pragma once
#ifndef NET_TCP_RTTM_HPP
#define NET_TCP_RTTM_HPP

#include <cassert>
#include <chrono>
#include <cmath>
#include <algorithm>
#include <debug>

namespace net {
namespace tcp {

// [RFC 6298]
// Round Trip Time Measurer
struct RTTM {
  using timestamp_t = double;
  using duration_t = double;

  // clock granularity
  //static constexpr duration_t CLOCK_G = hw::PIT::frequency().count() / 1000;
  static constexpr duration_t CLOCK_G = 0.0011;

  static constexpr double K = 4.0;

  static constexpr double alpha = 1.0/8;
  static constexpr double beta = 1.0/4;

  timestamp_t t; // tick when measure is started

  duration_t SRTT; // smoothed round-trip time
  duration_t RTTVAR; // round-trip time variation
  duration_t RTO; // retransmission timeout

  bool active;

  RTTM()
    : t(0), SRTT(1.0), RTTVAR(1.0), RTO(1.0), active(false)
  {}

  void start();

  void stop(bool first = false);

  auto rto_ms() const
  { return std::chrono::milliseconds{static_cast<unsigned long>(RTO * 1000)}; }

  /*
    When the first RTT measurement R is made, the host MUST set

    SRTT <- R
    RTTVAR <- R/2
    RTO <- SRTT + max (G, K*RTTVAR)

    where K = 4.
  */
  void first_rtt_measurement(duration_t R) {
    SRTT = R;
    RTTVAR = R/2;
    update_rto();
  }

  /*
    When a subsequent RTT measurement R' is made, a host MUST set

    RTTVAR <- (1 - beta) * RTTVAR + beta * |SRTT - R'|
    SRTT <- (1 - alpha) * SRTT + alpha * R'

    The value of SRTT used in the update to RTTVAR is its value
    before updating SRTT itself using the second assignment.  That
    is, updating RTTVAR and SRTT MUST be computed in the above
    order.

    The above SHOULD be computed using alpha=1/8 and beta=1/4 (as
    suggested in [JK88]).

    After the computation, a host MUST update
    RTO <- SRTT + max (G, K*RTTVAR)
  */
  void sub_rtt_measurement(duration_t R) {
    RTTVAR = (1 - beta) * RTTVAR + beta * std::abs(SRTT-R);
    SRTT = (1 - alpha) * SRTT + alpha * R;
    update_rto();
  }

  void update_rto() {
    RTO = std::max(SRTT + std::max(CLOCK_G, K * RTTVAR), 1.0);
    debug2("<TCP::Connection::RTO> RTO updated: %ums\n",
      (uint32_t)(RTO * 1000));
  }
}; // < struct RTTM

} // < namespace tcp
} // < namespace net

#endif // < NET_TCP_RTTM_HPP
<|endoftext|>


<commit_before>// vim: tabstop=3 expandtab shiftwidth=4 softtabstop=4

#include <catch.hpp>
#include <moar_rulez.hpp>

using moar_rulez::execute;
using moar_rulez::success;
using moar_rulez::fail;
using moar_rulez::running;
using moar_rulez::eq;
using moar_rulez::ne;
using moar_rulez::gt;
using moar_rulez::lt;
using moar_rulez::State;
using moar_rulez::make_rule;
using moar_rulez::set;

SCENARIO("All rules should work independently") {

  GIVEN("constants") {
    CHECK( success == execute(success) );
    CHECK( fail	   == execute(fail) );
    CHECK( running == execute(running) );
  }
  GIVEN("operator&&") {
    CHECK( success == execute(success && success) );
    CHECK( fail    == execute(success && fail) );
    CHECK( fail    == execute(fail && success) );
    CHECK( fail    == execute(fail && fail) );
    CHECK( fail    == execute(fail && running) );
    CHECK( running == execute(running && fail) );
    CHECK( running == execute(success && running) );
    CHECK( running == execute(running && success) );
    CHECK( running == execute(running && running) );
  }
  GIVEN("operator||") {
    CHECK( success == execute(success || success) );
    CHECK( success == execute(success || fail) );
    CHECK( success == execute(fail || success) );
    CHECK( success == execute(success || running) );
    CHECK( running == execute(running || success) );
    CHECK( fail    == execute(fail || fail) );
    CHECK( running == execute(fail || running) );
    CHECK( running == execute(running || fail) );
    CHECK( running == execute(running || running) );
  }

  GIVEN("operator~") {
    CHECK( success == execute(~fail) );
    CHECK( fail    == execute(~success) );
    CHECK( running == execute(~running) );
  }

  GIVEN("eq") {
    auto eqvar = 5;
    CHECK( success == execute(eq(eqvar,5)) );
    CHECK( fail    == execute(eq(eqvar,7)) );
  }
  GIVEN("ne") {
    auto nevar = 4;
    CHECK( fail    == execute(ne(nevar,4)) );
    CHECK( success == execute(ne(nevar,2)) );
    CHECK( success == execute(~eq(nevar,2)) ); // same as above
  }
  GIVEN("gt") {
    auto gtvar = 4;
    CHECK( fail    == execute(gt(gtvar,4)) );
    CHECK( fail    == execute(gt(gtvar,5)) );
    CHECK( success == execute(gt(gtvar,2)) );
  }
  GIVEN("lt") {
    auto ltvar = 4;
    CHECK( fail    == execute(lt(ltvar,4)) );
    CHECK( success == execute(lt(ltvar,5)) );
    CHECK( fail    == execute(lt(ltvar,2)) );
  }
  GIVEN("set") {
    auto setvar = 0;
    CHECK( success == execute(set(setvar,42)) );
    CHECK( 42 == setvar );
  }
}

SCENARIO("Example: A dude tries to open a door") {
  auto door_open     = false;
  auto door_locked   = true;
  auto failed        = false;
  auto dude_has_key  = true;
  auto dude_position = 0;
  constexpr auto door_position = 100;

  const auto move_dude = make_rule([&]{
    dude_position += 1;
    return State::Success;
  });

  const auto unlock_door = make_rule([&]{
      if(dude_position != door_position || !dude_has_key) return State::Fail;
      door_locked = false;
      return State::Success;
  });

  const auto open_door = make_rule([&]{
      if(dude_position != door_position || door_locked) return State::Fail;
      door_open = true;
      return State::Success;
  });

  const auto try_open =
    eq(dude_position, door_position)
    && (unlock_door || set(failed,true))
    && open_door;

  const auto rules =
    try_open
    || move_dude;

  const auto run = [&]{
    while( door_locked && !failed ) execute(rules);
  };

  GIVEN("the dude has no key") {
    dude_has_key = false;
    run();
    CHECK( false == door_open );
    CHECK( true  == failed );
  }
  GIVEN("the dude has a key") {
    dude_has_key = true;
    run();
    CHECK( true  == door_open );
    CHECK( false == failed );
  }
}
<commit_msg>Added tests for static rules<commit_after>// vim: tabstop=3 expandtab shiftwidth=4 softtabstop=4

#include <catch.hpp>
#include <moar_rulez.hpp>

using moar_rulez::execute;
using moar_rulez::success;
using moar_rulez::fail;
using moar_rulez::running;
using moar_rulez::eq;
using moar_rulez::ne;
using moar_rulez::gt;
using moar_rulez::lt;
using moar_rulez::State;
using moar_rulez::make_rule;
using moar_rulez::set;

SCENARIO("All rules should work independently") {

  GIVEN("constants") {
    CHECK( success == execute(success) );
    CHECK( fail	   == execute(fail) );
    CHECK( running == execute(running) );
  }
  GIVEN("operator&&") {
    CHECK( success == execute(success && success) );
    CHECK( fail    == execute(success && fail) );
    CHECK( fail    == execute(fail && success) );
    CHECK( fail    == execute(fail && fail) );
    CHECK( fail    == execute(fail && running) );
    CHECK( running == execute(running && fail) );
    CHECK( running == execute(success && running) );
    CHECK( running == execute(running && success) );
    CHECK( running == execute(running && running) );
  }
  GIVEN("operator||") {
    CHECK( success == execute(success || success) );
    CHECK( success == execute(success || fail) );
    CHECK( success == execute(fail || success) );
    CHECK( success == execute(success || running) );
    CHECK( running == execute(running || success) );
    CHECK( fail    == execute(fail || fail) );
    CHECK( running == execute(fail || running) );
    CHECK( running == execute(running || fail) );
    CHECK( running == execute(running || running) );
  }

  GIVEN("operator~") {
    CHECK( success == execute(~fail) );
    CHECK( fail    == execute(~success) );
    CHECK( running == execute(~running) );
  }

  GIVEN("eq") {
    const auto eqvar = 5;
    CHECK( success == execute(eq(eqvar,5)) );
    CHECK( fail    == execute(eq(eqvar,7)) );
    CHECK( success == execute(eq<5>(eqvar)) );
    CHECK( fail    == execute(eq<7>(eqvar)) );
  }
  GIVEN("ne") {
    const auto nevar = 4;
    CHECK( success == execute(ne(nevar,2)) );
    CHECK( fail    == execute(ne(nevar,4)) );
    CHECK( success == execute(ne<2>(nevar)) );
    CHECK( fail    == execute(ne<4>(nevar)) );
  }
  GIVEN("gt") {
    const auto gtvar = 4;
    CHECK( success == execute(gt(gtvar,2)) );
    CHECK( fail    == execute(gt(gtvar,4)) );
    CHECK( fail    == execute(gt(gtvar,5)) );
    CHECK( success == execute(gt<2>(gtvar)) );
    CHECK( fail    == execute(gt<4>(gtvar)) );
    CHECK( fail    == execute(gt<5>(gtvar)) );
  }
  GIVEN("lt") {
    const auto ltvar = 4;
    CHECK( success == execute(lt(ltvar,5)) );
    CHECK( fail    == execute(lt(ltvar,4)) );
    CHECK( fail    == execute(lt(ltvar,2)) );
    CHECK( success == execute(lt<5>(ltvar)) );
    CHECK( fail    == execute(lt<4>(ltvar)) );
    CHECK( fail    == execute(lt<2>(ltvar)) );
  }
  GIVEN("set") {
    auto setvar = 0;
    CHECK( success == execute(set(setvar,42)) );
    CHECK( 42 == setvar );
    CHECK( success == execute(set<43>(setvar)) );
    CHECK( 43 == setvar );
  }
}

SCENARIO("Example: A dude tries to open a door") {
  auto door_open     = false;
  auto door_locked   = true;
  auto failed        = false;
  auto dude_has_key  = true;
  auto dude_position = 0;
  constexpr auto door_position = 100;

  const auto move_dude = make_rule([&]{
    dude_position += 1;
    return State::Success;
  });

  const auto unlock_door = make_rule([&]{
      if(dude_position != door_position || !dude_has_key) return State::Fail;
      door_locked = false;
      return State::Success;
  });

  const auto open_door = make_rule([&]{
      if(dude_position != door_position || door_locked) return State::Fail;
      door_open = true;
      return State::Success;
  });

  const auto try_open =
    eq(dude_position, door_position)
    && (unlock_door || set(failed,true))
    && open_door;

  const auto rules =
    try_open
    || move_dude;

  const auto run = [&]{
    while( door_locked && !failed ) execute(rules);
  };

  GIVEN("the dude has no key") {
    dude_has_key = false;
    run();
    CHECK( false == door_open );
    CHECK( true  == failed );
  }
  GIVEN("the dude has a key") {
    dude_has_key = true;
    run();
    CHECK( true  == door_open );
    CHECK( false == failed );
  }
}
<|endoftext|>


<commit_before>// vim: tabstop=3 expandtab shiftwidth=4 softtabstop=4

#include <catch.hpp>
#include <moar_rulez.hpp>

using moar_rulez::execute;
using moar_rulez::success;
using moar_rulez::fail;
using moar_rulez::running;
using moar_rulez::eq;
using moar_rulez::ne;
using moar_rulez::gt;
using moar_rulez::lt;
using moar_rulez::State;
using moar_rulez::make_rule;
using moar_rulez::set;

SCENARIO("All rules should work independently") {

  GIVEN("constants") {
    CHECK( success == execute(success) );
    CHECK( fail	   == execute(fail) );
    CHECK( running == execute(running) );
  }
  GIVEN("operator&&") {
    CHECK( success == execute(success && success) );
    CHECK( fail    == execute(success && fail) );
    CHECK( fail    == execute(fail && success) );
    CHECK( fail    == execute(fail && fail) );
    CHECK( fail    == execute(fail && running) );
    CHECK( running == execute(running && fail) );
    CHECK( running == execute(success && running) );
    CHECK( running == execute(running && success) );
    CHECK( running == execute(running && running) );
  }
  GIVEN("operator||") {
    CHECK( success == execute(success || success) );
    CHECK( success == execute(success || fail) );
    CHECK( success == execute(fail || success) );
    CHECK( success == execute(success || running) );
    CHECK( running == execute(running || success) );
    CHECK( fail    == execute(fail || fail) );
    CHECK( running == execute(fail || running) );
    CHECK( running == execute(running || fail) );
    CHECK( running == execute(running || running) );
  }

  GIVEN("operator~") {
    CHECK( success == execute(~fail) );
    CHECK( fail    == execute(~success) );
    CHECK( running == execute(~running) );
  }

  GIVEN("eq") {
    const auto eqvar = 5;
    CHECK( success == execute(eq(eqvar,5)) );
    CHECK( fail    == execute(eq(eqvar,7)) );
    CHECK( success == execute(eq<5>(eqvar)) );
    CHECK( fail    == execute(eq<7>(eqvar)) );
  }
  GIVEN("ne") {
    const auto nevar = 4;
    CHECK( success == execute(ne(nevar,2)) );
    CHECK( fail    == execute(ne(nevar,4)) );
    CHECK( success == execute(ne<2>(nevar)) );
    CHECK( fail    == execute(ne<4>(nevar)) );
  }
  GIVEN("gt") {
    const auto gtvar = 4;
    CHECK( success == execute(gt(gtvar,2)) );
    CHECK( fail    == execute(gt(gtvar,4)) );
    CHECK( fail    == execute(gt(gtvar,5)) );
    CHECK( success == execute(gt<2>(gtvar)) );
    CHECK( fail    == execute(gt<4>(gtvar)) );
    CHECK( fail    == execute(gt<5>(gtvar)) );
  }
  GIVEN("lt") {
    const auto ltvar = 4;
    CHECK( success == execute(lt(ltvar,5)) );
    CHECK( fail    == execute(lt(ltvar,4)) );
    CHECK( fail    == execute(lt(ltvar,2)) );
    CHECK( success == execute(lt<5>(ltvar)) );
    CHECK( fail    == execute(lt<4>(ltvar)) );
    CHECK( fail    == execute(lt<2>(ltvar)) );
  }
  GIVEN("set") {
    auto setvar = 0;
    CHECK( success == execute(set(setvar,42)) );
    CHECK( 42 == setvar );
    CHECK( success == execute(set<43>(setvar)) );
    CHECK( 43 == setvar );
  }
}

SCENARIO("Complex sequences") {
  CHECK( success == execute(success && success || running) );
  CHECK( running == execute(success && success && running) );
  CHECK( success == execute(success && success || fail) );
  CHECK( fail    == execute(success && success && fail) );
  CHECK( success == execute(success || running && success) );
  CHECK( success == execute(success || running && running) );
  CHECK( success == execute(success || running || fail) );
  CHECK( success == execute(success || running && fail) );
  CHECK( running == execute(success && running && success) );
  CHECK( running == execute(success && running || running) );
  CHECK( running == execute(success && running || fail) );
  CHECK( success == execute(success || fail && success) );
  CHECK( success == execute(success || fail || running) );
  CHECK( success == execute(success || fail && running) );
  CHECK( success == execute(success || fail && fail) );
  CHECK( fail    == execute(success && fail && success) );
  CHECK( running == execute(success && fail || running) );
  CHECK( fail    == execute(success && fail && running) );
  CHECK( fail    == execute(success && fail || fail) );
  CHECK( running == execute(running || success && success) );
  CHECK( running == execute(running || success && running) );
  CHECK( running == execute(running || success || fail) );
  CHECK( running == execute(running || success && fail) );
  CHECK( running == execute(running && success || success) );
  CHECK( running == execute(running && success && running) );
  CHECK( running == execute(running && success || fail) );
  CHECK( running == execute(running && success && fail) );
  CHECK( running == execute(running && running || success) );
  CHECK( running == execute(running && running && success) );
  CHECK( running == execute(running && running || fail) );
  CHECK( running == execute(running && running && fail) );
  CHECK( running == execute(running || fail || success) );
  CHECK( running == execute(running || fail && success) );
  CHECK( running == execute(running || fail && running) );
  CHECK( running == execute(running || fail && fail) );
  CHECK( running == execute(running && fail || success) );
  CHECK( running == execute(running && fail && success) );
  CHECK( running == execute(running && fail && running) );
  CHECK( running == execute(running && fail || fail) );
}

SCENARIO("Example: A dude tries to open a door") {
  auto door_open     = false;
  auto door_locked   = true;
  auto failed        = false;
  auto dude_has_key  = true;
  auto dude_position = 0;
  constexpr auto door_position = 100;

  const auto move_dude = make_rule([&]{
    dude_position += 1;
    return State::Success;
  });

  const auto unlock_door = make_rule([&]{
      if(dude_position != door_position || !dude_has_key) return State::Fail;
      door_locked = false;
      return State::Success;
  });

  const auto open_door = make_rule([&]{
      if(dude_position != door_position || door_locked) return State::Fail;
      door_open = true;
      return State::Success;
  });

  const auto try_open =
    eq(dude_position, door_position)
    && (unlock_door || set(failed,true))
    && open_door;

  const auto rules =
    try_open
    || move_dude;

  const auto run = [&]{
    while( door_locked && !failed ) execute(rules);
  };

  GIVEN("the dude has no key") {
    dude_has_key = false;
    run();
    CHECK( false == door_open );
    CHECK( true  == failed );
  }
  GIVEN("the dude has a key") {
    dude_has_key = true;
    run();
    CHECK( true  == door_open );
    CHECK( false == failed );
  }
}
<commit_msg>Update moar_rulez.cpp<commit_after>// vim: tabstop=3 expandtab shiftwidth=4 softtabstop=4

#include <catch.hpp>
#include <moar_rulez.hpp>

using moar_rulez::execute;
using moar_rulez::success;
using moar_rulez::fail;
using moar_rulez::running;
using moar_rulez::eq;
using moar_rulez::ne;
using moar_rulez::gt;
using moar_rulez::lt;
using moar_rulez::State;
using moar_rulez::make_rule;
using moar_rulez::set;

SCENARIO("All rules should work independently") {

  GIVEN("constants") {
    CHECK( success == execute(success) );
    CHECK( fail	   == execute(fail) );
    CHECK( running == execute(running) );
  }
  GIVEN("operator&&") {
    CHECK( success == execute(success && success) );
    CHECK( fail    == execute(success && fail) );
    CHECK( fail    == execute(fail && success) );
    CHECK( fail    == execute(fail && fail) );
    CHECK( fail    == execute(fail && running) );
    CHECK( running == execute(running && fail) );
    CHECK( running == execute(success && running) );
    CHECK( running == execute(running && success) );
    CHECK( running == execute(running && running) );
  }
  GIVEN("operator||") {
    CHECK( success == execute(success || success) );
    CHECK( success == execute(success || fail) );
    CHECK( success == execute(fail || success) );
    CHECK( success == execute(success || running) );
    CHECK( running == execute(running || success) );
    CHECK( fail    == execute(fail || fail) );
    CHECK( running == execute(fail || running) );
    CHECK( running == execute(running || fail) );
    CHECK( running == execute(running || running) );
  }

  GIVEN("operator~") {
    CHECK( success == execute(~fail) );
    CHECK( fail    == execute(~success) );
    CHECK( running == execute(~running) );
  }

  GIVEN("eq") {
    const auto eqvar = 5;
    CHECK( success == execute(eq(eqvar,5)) );
    CHECK( fail    == execute(eq(eqvar,7)) );
    CHECK( success == execute(eq<5>(eqvar)) );
    CHECK( fail    == execute(eq<7>(eqvar)) );
  }
  GIVEN("ne") {
    const auto nevar = 4;
    CHECK( success == execute(ne(nevar,2)) );
    CHECK( fail    == execute(ne(nevar,4)) );
    CHECK( success == execute(ne<2>(nevar)) );
    CHECK( fail    == execute(ne<4>(nevar)) );
  }
  GIVEN("gt") {
    const auto gtvar = 4;
    CHECK( success == execute(gt(gtvar,2)) );
    CHECK( fail    == execute(gt(gtvar,4)) );
    CHECK( fail    == execute(gt(gtvar,5)) );
    CHECK( success == execute(gt<2>(gtvar)) );
    CHECK( fail    == execute(gt<4>(gtvar)) );
    CHECK( fail    == execute(gt<5>(gtvar)) );
  }
  GIVEN("lt") {
    const auto ltvar = 4;
    CHECK( success == execute(lt(ltvar,5)) );
    CHECK( fail    == execute(lt(ltvar,4)) );
    CHECK( fail    == execute(lt(ltvar,2)) );
    CHECK( success == execute(lt<5>(ltvar)) );
    CHECK( fail    == execute(lt<4>(ltvar)) );
    CHECK( fail    == execute(lt<2>(ltvar)) );
  }
  GIVEN("set") {
    auto setvar = 0;
    CHECK( success == execute(set(setvar,42)) );
    CHECK( 42 == setvar );
    CHECK( success == execute(set<43>(setvar)) );
    CHECK( 43 == setvar );
  }
}

SCENARIO("Complex sequences") {
  CHECK( success == execute(success && success || running) );
  CHECK( running == execute(success && success && running) );
  CHECK( success == execute(success && success || fail) );
  CHECK( fail    == execute(success && success && fail) );
  CHECK( success == execute(success || running && success) );
  CHECK( success == execute(success || running && running) );
  CHECK( success == execute(success || running || fail) );
  CHECK( success == execute(success || running && fail) );
  CHECK( running == execute(success && running && success) );
  CHECK( running == execute(success && running || running) );
  CHECK( running == execute(success && running || fail) );
  CHECK( success == execute(success || fail && success) );
  CHECK( success == execute(success || fail || running) );
  CHECK( success == execute(success || fail && running) );
  CHECK( success == execute(success || fail && fail) );
  CHECK( fail    == execute(success && fail && success) );
  CHECK( running == execute(success && fail || running) );
  CHECK( fail    == execute(success && fail && running) );
  CHECK( fail    == execute(success && fail || fail) );
  CHECK( running == execute(running || success && success) );
  CHECK( running == execute(running || success && running) );
  CHECK( running == execute(running || success || fail) );
  CHECK( running == execute(running || success && fail) );
  CHECK( running == execute(running && success || success) );
  CHECK( running == execute(running && success && running) );
  CHECK( running == execute(running && success || fail) );
  CHECK( running == execute(running && success && fail) );
  CHECK( running == execute(running && running || success) );
  CHECK( running == execute(running && running && success) );
  CHECK( running == execute(running && running || fail) );
  CHECK( running == execute(running && running && fail) );
  CHECK( running == execute(running || fail || success) );
  CHECK( running == execute(running || fail && success) );
  CHECK( running == execute(running || fail && running) );
  CHECK( running == execute(running || fail && fail) );
  CHECK( running == execute(running && fail || success) );
  CHECK( running == execute(running && fail && success) );
  CHECK( running == execute(running && fail && running) );
  CHECK( running == execute(running && fail || fail) );
  CHECK( success == execute(fail || success && success) );
  CHECK( success == execute(fail || success || running) );
  CHECK( running == execute(fail || success && running) );
  CHECK( fail    == execute(fail || success && fail) );
  CHECK( success == execute(fail && success || success) );
  CHECK( running == execute(fail && success || running) );
  CHECK( fail    == execute(fail && success && running) );
  CHECK( fail    == execute(fail && success && fail) );
  CHECK( running == execute(fail || running || success) );
  CHECK( running == execute(fail || running && success) );
  CHECK( running == execute(fail || running && running) );
  CHECK( running == execute(fail || running && fail) );
  CHECK( success == execute(fail && running || success) );
  CHECK( fail    == execute(fail && running && success) );
  CHECK( running == execute(fail && running || running) );
  CHECK( fail    == execute(fail && running && fail) );
  CHECK( success == execute(fail && fail || success) );
  CHECK( fail    == execute(fail && fail && success) );
  CHECK( running == execute(fail && fail || running) );
  CHECK( fail    == execute(fail && fail && running) );
}

SCENARIO("Example: A dude tries to open a door") {
  auto door_open     = false;
  auto door_locked   = true;
  auto failed        = false;
  auto dude_has_key  = true;
  auto dude_position = 0;
  constexpr auto door_position = 100;

  const auto move_dude = make_rule([&]{
    dude_position += 1;
    return State::Success;
  });

  const auto unlock_door = make_rule([&]{
      if(dude_position != door_position || !dude_has_key) return State::Fail;
      door_locked = false;
      return State::Success;
  });

  const auto open_door = make_rule([&]{
      if(dude_position != door_position || door_locked) return State::Fail;
      door_open = true;
      return State::Success;
  });

  const auto try_open =
    eq(dude_position, door_position)
    && (unlock_door || set(failed,true))
    && open_door;

  const auto rules =
    try_open
    || move_dude;

  const auto run = [&]{
    while( door_locked && !failed ) execute(rules);
  };

  GIVEN("the dude has no key") {
    dude_has_key = false;
    run();
    CHECK( false == door_open );
    CHECK( true  == failed );
  }
  GIVEN("the dude has a key") {
    dude_has_key = true;
    run();
    CHECK( true  == door_open );
    CHECK( false == failed );
  }
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "iowrapper.h"
#include "CLI11.hpp"
#include <QApplication>
#include <QCommandLineParser>
#include <QSurfaceFormat>
//TODO
#include <iostream>

using namespace Vipster;

int main(int argc, char *argv[])
{
    QSurfaceFormat format;
    format.setVersion(3,3);
    format.setSamples(8);
    format.setAlphaBufferSize(8);
    format.setProfile(QSurfaceFormat::CoreProfile);
    QSurfaceFormat::setDefaultFormat(format);
    QApplication qapp(argc, argv);
    QApplication::setApplicationName("Vipster");
    QApplication::setApplicationVersion("1.9a");

    // main parser + data-targets
    CLI::App app{"Vipster " + QApplication::applicationVersion().toStdString()};
    // TODO
    app.allow_extras(true);
    std::map<IOFmt, std::vector<std::string>> fmt_files{};
    std::map<CLI::Option*, IOFmt> fmt_opts{};
    for(auto& fmt: IOPlugins){
        // parser
        auto opt = app.add_option("--" + fmt.second->command,
                                  fmt_files[fmt.first],
                                  fmt.second->name);
        fmt_opts[opt] = fmt.first;
        opt->group("Parse files");
        opt->check(CLI::ExistingFile);
    }

    // conversion parser + data + options
    auto convert = app.add_subcommand("convert", "Directly convert a file");
    std::string fmt_group{"Available formats (r: parsing, w: writing)"};
    struct{
        std::vector<std::string> input;
        std::vector<std::string> output;
        std::vector<std::string> kpoints;
        std::string param;
        // TODO
//        std::unique_ptr<BaseConfig> config{};
    }conv_data;
    [[maybe_unused]]
    auto conv_kpoints = convert->add_option("-k", conv_data.kpoints,
        "Specify k-points (defaults to parsed mesh or gamma-point)");

    auto conv_param = convert->add_option("-p", conv_data.param,
        "Specify parameter set (defaults to parsed one, if present)");
    conv_param->expected(1);

    auto conv_in = convert->add_option("in", conv_data.input,
                                       "fmt and filename of input");
    conv_in->required(true);
    conv_in->expected(2);
    auto conv_out = convert->add_option("out", conv_data.output,
                                        "fmt and filename of output");
    conv_out->required(true);
    conv_out->expected(2);

    // do the parsing
    CLI11_PARSE(app, argc, argv);

    // execution
    if(app.got_subcommand(convert)){
        // TODO: as callback! should catch the throws
        IOFmt fmt_in, fmt_out;
        auto pos_in = IOCmdIn.find(conv_data.input[0]);
        if(pos_in == IOCmdIn.end()){
            throw CLI::ParseError("Invalid input format: "+conv_data.input[0], 1);
        }else{
            fmt_in = pos_in->second;
        }
        auto pos_out = IOCmdIn.find(conv_data.output[0]);
        if(pos_out == IOCmdOut.end()){
            throw CLI::ParseError("Invalid output format: "+conv_data.output[0], 1);
        }else{
            fmt_out = pos_out->second;
        }
        //TODO: c++17
        //auto [mol, fmt, param] = readFile(conv_data.input[1], fmt_in);
        auto data = readFile(conv_data.input[1], fmt_in);
        auto mol = std::move(data.mol);
        auto param = std::move(data.param);
        if(!conv_data.param.empty()){
            auto tmp = params.equal_range(fmt_in);
            auto pos_par = std::find_if(tmp.first, tmp.second,
                                        [&](const decltype(params)::value_type& p){
                                            return p.second->name == conv_data.param;
                                        });
            if(pos_par == params.end()){
                throw CLI::ParseError("Invalid parameter \""+conv_data.param+
                                      "\" for format "+conv_data.input[0], 1);
            }
            param = pos_par->second->copy();
        }
        if(!conv_data.kpoints.empty()){
            const auto& kpoints = conv_data.kpoints;
            const std::string kp_err = "KPoints should be one of:\n"
                                       "gamma\n"
                                       "mpg x y z sx sy sz\n"
                                       "";
            if(kpoints[0] == "gamma"){
                if(kpoints.size() > 1){
                    throw CLI::ParseError("gamma takes no arguments\n\n"+kp_err, 1);
                }
                mol.setKPoints(KPoints{KPointFmt::Gamma, {}, {}});
            }else if(kpoints[0] == "mpg"){
                const std::string mpg_err = "mpg takes three integer and three "
                                            "float arguments\n\n";
                if(kpoints.size() != 7){
                    throw CLI::ParseError(mpg_err+kp_err, 1);
                }
                try {
                    mol.setKPoints(KPoints{KPointFmt::MPG, {
                                       std::stoi(kpoints[1]),
                                       std::stoi(kpoints[2]),
                                       std::stoi(kpoints[3]),
                                       std::stof(kpoints[4]),
                                       std::stof(kpoints[5]),
                                       std::stof(kpoints[6]),
                                   }, {}});
                } catch (...) {
                    throw CLI::ParseError(mpg_err+kp_err, 1);
                }{}
            //TODO: discrete
            }else{
                throw CLI::ParseError("Invalid KPoint style\n"+kp_err, 1);
            }
        }
        writeFile(conv_data.output[1], fmt_out, mol, param.get());
    }else{
        std::vector<IO::Data> data{};
        // TODO: try to guess formats from app.remaining()
        for(const auto& file: app.remaining()){
            auto pos = file.find_last_of('.');
            if(pos != file.npos){
                std::string ext = file.substr(pos+1);
                auto pos = IOExt.find(ext);
                if(pos != IOExt.end()){
                    data.push_back(readFile(file, pos->second));
                }else{
                    throw CLI::ParseError(
                                "Could not deduce format of file "+file+
                                "\nPlease specify format explicitely", 1);
                }
            }else{
                throw CLI::ParseError(
                            "Could not deduce format of file "+file+
                            "\nPlease specify format explicitely", 1);
            }
        }
        // parse files
        for(auto& op_fmt: fmt_opts){
            for(const auto& fn: op_fmt.first->results()){
                data.push_back(readFile(fn, op_fmt.second));
            }
        }
        // launch GUI
        if(data.size()){
            MainWindow w{std::move(data)};
            w.show();
            return QApplication::exec();
        }else{
            MainWindow w{};
            w.show();
            return QApplication::exec();
        }
    }
}
<commit_msg>catch cli-exceptions via callbacks in CLI11_PARSE<commit_after>#include "mainwindow.h"
#include "iowrapper.h"
#include "CLI11.hpp"
#include <QApplication>
#include <QCommandLineParser>
#include <QSurfaceFormat>

using namespace Vipster;

int main(int argc, char *argv[])
{
    QSurfaceFormat format;
    format.setVersion(3,3);
    format.setSamples(8);
    format.setAlphaBufferSize(8);
    format.setProfile(QSurfaceFormat::CoreProfile);
    QSurfaceFormat::setDefaultFormat(format);
    QApplication qapp(argc, argv);
    QApplication::setApplicationName("Vipster");
    QApplication::setApplicationVersion("1.9a");

    // main parser + data-targets
    CLI::App app{"Vipster " + QApplication::applicationVersion().toStdString()};
    app.allow_extras(true);
    std::map<IOFmt, std::vector<std::string>> fmt_files{};
    std::map<CLI::Option*, IOFmt> fmt_opts{};
    for(auto& fmt: IOPlugins){
        // parser
        auto opt = app.add_option("--" + fmt.second->command,
                                  fmt_files[fmt.first],
                                  fmt.second->name);
        fmt_opts[opt] = fmt.first;
        opt->group("Parse files");
        opt->check(CLI::ExistingFile);
    }
    app.set_callback([&](){
        std::vector<IO::Data> data{};
        for(const auto& file: app.remaining()){
            auto pos = file.find_last_of('.');
            if(pos != file.npos){
                std::string ext = file.substr(pos+1);
                auto pos = IOExt.find(ext);
                if(pos != IOExt.end()){
                    data.push_back(readFile(file, pos->second));
                }else{
                    throw CLI::ParseError(
                                "Could not deduce format of file "+file+
                                "\nPlease specify format explicitely", 1);
                }
            }else{
                throw CLI::ParseError(
                            "Could not deduce format of file "+file+
                            "\nPlease specify format explicitely", 1);
            }
        }
        // parse files
        for(auto& op_fmt: fmt_opts){
            for(const auto& fn: op_fmt.first->results()){
                data.push_back(readFile(fn, op_fmt.second));
            }
        }
        // launch GUI
        if(data.size()){
            MainWindow w{std::move(data)};
            w.show();
            return QApplication::exec();
        }else{
            MainWindow w{};
            w.show();
            return QApplication::exec();
        }
    });

    // conversion parser + data + options
    auto convert = app.add_subcommand("convert", "Directly convert a file");
    std::string fmt_group{"Available formats (r: parsing, w: writing)"};
    struct{
        std::vector<std::string> input;
        std::vector<std::string> output;
        std::vector<std::string> kpoints;
        std::string param;
        // TODO
//        std::unique_ptr<BaseConfig> config{};
    }conv_data;
    [[maybe_unused]]
    auto conv_kpoints = convert->add_option("-k", conv_data.kpoints,
        "Specify k-points (defaults to parsed mesh or gamma-point)");

    auto conv_param = convert->add_option("-p", conv_data.param,
        "Specify parameter set (defaults to parsed one, if present)");
    conv_param->expected(1);

    auto conv_in = convert->add_option("in", conv_data.input,
                                       "fmt and filename of input");
    conv_in->required(true);
    conv_in->expected(2);
    auto conv_out = convert->add_option("out", conv_data.output,
                                        "fmt and filename of output");
    conv_out->required(true);
    conv_out->expected(2);

    convert->set_callback([&](){
        IOFmt fmt_in, fmt_out;
        auto pos_in = IOCmdIn.find(conv_data.input[0]);
        if(pos_in == IOCmdIn.end()){
            throw CLI::ParseError("Invalid input format: "+conv_data.input[0], 1);
        }else{
            fmt_in = pos_in->second;
        }
        auto pos_out = IOCmdIn.find(conv_data.output[0]);
        if(pos_out == IOCmdOut.end()){
            throw CLI::ParseError("Invalid output format: "+conv_data.output[0], 1);
        }else{
            fmt_out = pos_out->second;
        }
        //TODO: c++17
        //auto [mol, fmt, param] = readFile(conv_data.input[1], fmt_in);
        auto data = readFile(conv_data.input[1], fmt_in);
        auto mol = std::move(data.mol);
        auto param = std::move(data.param);
        if(!conv_data.param.empty()){
            auto tmp = params.equal_range(fmt_in);
            auto pos_par = std::find_if(tmp.first, tmp.second,
                                        [&](const decltype(params)::value_type& p){
                                            return p.second->name == conv_data.param;
                                        });
            if(pos_par == params.end()){
                throw CLI::ParseError("Invalid parameter \""+conv_data.param+
                                      "\" for format "+conv_data.input[0], 1);
            }
            param = pos_par->second->copy();
        }
        if(!conv_data.kpoints.empty()){
            const auto& kpoints = conv_data.kpoints;
            const std::string kp_err = "KPoints should be one of:\n"
                                       "gamma\n"
                                       "mpg x y z sx sy sz\n"
                                       "";
            if(kpoints[0] == "gamma"){
                if(kpoints.size() > 1){
                    throw CLI::ParseError("gamma takes no arguments\n\n"+kp_err, 1);
                }
                mol.setKPoints(KPoints{KPointFmt::Gamma, {}, {}});
            }else if(kpoints[0] == "mpg"){
                const std::string mpg_err = "mpg takes three integer and three "
                                            "float arguments\n\n";
                if(kpoints.size() != 7){
                    throw CLI::ParseError(mpg_err+kp_err, 1);
                }
                try {
                    mol.setKPoints(KPoints{KPointFmt::MPG, {
                                       std::stoi(kpoints[1]),
                                       std::stoi(kpoints[2]),
                                       std::stoi(kpoints[3]),
                                       std::stof(kpoints[4]),
                                       std::stof(kpoints[5]),
                                       std::stof(kpoints[6]),
                                   }, {}});
                } catch (...) {
                    throw CLI::ParseError(mpg_err+kp_err, 1);
                }{}
            //TODO: discrete
            }else{
                throw CLI::ParseError("Invalid KPoint style\n"+kp_err, 1);
            }
        }
        writeFile(conv_data.output[1], fmt_out, mol, param.get());
        throw CLI::Success();
    });

    // do the parsing
    CLI11_PARSE(app, argc, argv);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

// libsolv
extern "C" {
#include <solv/dataiterator.h>
}

#include "DependencyContainer.hpp"
#include "Dependency.hpp"
#include "../DependencySplitter.hpp"

namespace libdnf {

DependencyContainer::DependencyContainer(const DependencyContainer &src)
        : sack(src.sack)
{
    queue_init_clone(&this->queue, &queue);
}

DependencyContainer::DependencyContainer(DnfSack *sack)
        : sack(sack)
{
    queue_init(&queue);
}

DependencyContainer::DependencyContainer(DnfSack *sack, const Queue &queue)
        : sack(sack)
{
    queue_init_clone(&this->queue, &queue);
}

DependencyContainer::DependencyContainer(DnfSack *sack, Queue &&queue)
        : sack(sack), queue(queue)
{}

DependencyContainer::~DependencyContainer()
{
    queue_free(&queue);
}

DependencyContainer &DependencyContainer::operator=(DependencyContainer &&src) noexcept
{
    sack = src.sack;
    queue_init_clone(&queue, &src.queue);
    return *this;
}

bool DependencyContainer::operator!=(const DependencyContainer &r) const { return !(*this == r); }
bool DependencyContainer::operator==(const DependencyContainer &r) const
{
    if (queue.count != r.queue.count)
        return false;

    for (int i = 0; i < queue.count; i++) {
        if (queue.elements[i] != r.queue.elements[i]) {
            return false;
        }
    }

    return dnf_sack_get_pool(sack) == dnf_sack_get_pool(r.sack);
}

void DependencyContainer::add(Dependency *dependency)
{
    queue_push(&queue, dependency->getId());
}

void DependencyContainer::add(Id id)
{
    queue_push(&queue, id);
}

bool DependencyContainer::addReldepWithGlob(const char *reldepStr)
{
    DependencySplitter depSplitter;
    if(!depSplitter.parse(reldepStr))
        return false;
    Dataiterator di;
    Pool *pool = dnf_sack_get_pool(sack);

    dataiterator_init(&di, pool, 0, 0, 0, depSplitter.getNameCStr(),
                      SEARCH_STRING | SEARCH_GLOB);
    while (dataiterator_step(&di)) {
        Id id = Dependency::getReldepId(sack, di.kv.str, depSplitter.getEVRCStr(),
                                        depSplitter.getCmpType());
        add(id);
    }
    dataiterator_free(&di);
    return true;
}

bool DependencyContainer::addReldep(const char *reldepStr)
{
    try {
        Id id = Dependency::getReldepId(sack, reldepStr);
        add(id);
        return true;
    }
    catch (...) {
        return false;
    }
}

void DependencyContainer::extend(DependencyContainer *container)
{
    queue_insertn(&queue, 0, container->queue.count, container->queue.elements);
}

std::unique_ptr<Dependency> DependencyContainer::get(int index) const noexcept
{
    Id id = queue.elements[index];
    return std::unique_ptr<Dependency> (new Dependency(sack, id));
}

Dependency *DependencyContainer::getPtr(int index) const noexcept
{
    Id id = queue.elements[index];
    return new Dependency(sack, id);
}

int DependencyContainer::count() const noexcept { return queue.count; }
const Queue &DependencyContainer::getQueue() const noexcept { return queue; }

}
<commit_msg>Fix copy constructor of DependencyContainer<commit_after>/*
 * Copyright (C) 2018 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

// libsolv
extern "C" {
#include <solv/dataiterator.h>
}

#include "DependencyContainer.hpp"
#include "Dependency.hpp"
#include "../DependencySplitter.hpp"

namespace libdnf {

DependencyContainer::DependencyContainer(const DependencyContainer &src)
        : sack(src.sack)
{
    queue_init_clone(&queue, &src.queue);
}

DependencyContainer::DependencyContainer(DnfSack *sack)
        : sack(sack)
{
    queue_init(&queue);
}

DependencyContainer::DependencyContainer(DnfSack *sack, const Queue &queue)
        : sack(sack)
{
    queue_init_clone(&this->queue, &queue);
}

DependencyContainer::DependencyContainer(DnfSack *sack, Queue &&queue)
        : sack(sack), queue(queue)
{}

DependencyContainer::~DependencyContainer()
{
    queue_free(&queue);
}

DependencyContainer &DependencyContainer::operator=(DependencyContainer &&src) noexcept
{
    sack = src.sack;
    queue_init_clone(&queue, &src.queue);
    return *this;
}

bool DependencyContainer::operator!=(const DependencyContainer &r) const { return !(*this == r); }
bool DependencyContainer::operator==(const DependencyContainer &r) const
{
    if (queue.count != r.queue.count)
        return false;

    for (int i = 0; i < queue.count; i++) {
        if (queue.elements[i] != r.queue.elements[i]) {
            return false;
        }
    }

    return dnf_sack_get_pool(sack) == dnf_sack_get_pool(r.sack);
}

void DependencyContainer::add(Dependency *dependency)
{
    queue_push(&queue, dependency->getId());
}

void DependencyContainer::add(Id id)
{
    queue_push(&queue, id);
}

bool DependencyContainer::addReldepWithGlob(const char *reldepStr)
{
    DependencySplitter depSplitter;
    if(!depSplitter.parse(reldepStr))
        return false;
    Dataiterator di;
    Pool *pool = dnf_sack_get_pool(sack);

    dataiterator_init(&di, pool, 0, 0, 0, depSplitter.getNameCStr(),
                      SEARCH_STRING | SEARCH_GLOB);
    while (dataiterator_step(&di)) {
        Id id = Dependency::getReldepId(sack, di.kv.str, depSplitter.getEVRCStr(),
                                        depSplitter.getCmpType());
        add(id);
    }
    dataiterator_free(&di);
    return true;
}

bool DependencyContainer::addReldep(const char *reldepStr)
{
    try {
        Id id = Dependency::getReldepId(sack, reldepStr);
        add(id);
        return true;
    }
    catch (...) {
        return false;
    }
}

void DependencyContainer::extend(DependencyContainer *container)
{
    queue_insertn(&queue, 0, container->queue.count, container->queue.elements);
}

std::unique_ptr<Dependency> DependencyContainer::get(int index) const noexcept
{
    Id id = queue.elements[index];
    return std::unique_ptr<Dependency> (new Dependency(sack, id));
}

Dependency *DependencyContainer::getPtr(int index) const noexcept
{
    Id id = queue.elements[index];
    return new Dependency(sack, id);
}

int DependencyContainer::count() const noexcept { return queue.count; }
const Queue &DependencyContainer::getQueue() const noexcept { return queue; }

}
<|endoftext|>


<commit_before>#include "bson_decode.h"
#include "bson_encode.h"

namespace HPHP {

  // Global function for decoding bson
  static Array HHVM_FUNCTION(bson_decode, const String& bson) {
    return cbson_loads_from_string(bson);
  }

  static String HHVM_FUNCTION(bson_encode, const Variant& anything) {
    bson_t bson;
    bson_init(&bson);
    fillBSONWithArray(anything.toArray(), &bson);

    const char* output = (const char*) bson_get_data(&bson);
    return String(output, bson.len, CopyString);
  }
}
<commit_msg>changed include<commit_after>#include "bson_decode.h"
#include "contrib/bson_encode.h"

namespace HPHP {

  // Global function for decoding bson
  static Array HHVM_FUNCTION(bson_decode, const String& bson) {
    return cbson_loads_from_string(bson);
  }

  static String HHVM_FUNCTION(bson_encode, const Variant& anything) {
    bson_t bson;
    bson_init(&bson);
    fillBSONWithArray(anything.toArray(), &bson);

    const char* output = (const char*) bson_get_data(&bson);
    return String(output, bson.len, CopyString);
  }
}
<|endoftext|>


<commit_before><commit_msg>Resolves: #i124686# reuse already set font for interpreting...<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#pragma once

#ifndef _LIBQI_QI_ATOMIC_HPP_
#define _LIBQI_QI_ATOMIC_HPP_

#ifdef _MSC_VER
# include <windows.h>
#endif

#include <qi/config.hpp>

namespace qi
{
  template <typename T>
  class QI_API atomic
  {
  public:
    atomic()
      : _value(0)
    {
    }

    atomic(T value)
      : _value(value)
    {
    }

    /* prefix operators */
    T operator++();
    T operator--();

    T operator*()
    {
      return _value;
    }

  private:
    T _value;
  };

#ifdef __GNUC__
    template <typename T>
    T atomic<T>::operator++()
    {
      return __sync_add_and_fetch(&_value, 1);
    }

    template <typename T>
    T atomic<T>::operator--()
    {
      return __sync_sub_and_fetch(&_value, 1);
    }
#endif

#ifdef _MSC_VER
  template<>
  inline short atomic<short>::operator++()
  {
    return _InterlockedIncrement16(&_value);
  }

  template<>
  inline short atomic<short>::operator--()
  {
    return _InterlockedDecrement16(&_value);
  }

  template <>
  inline long atomic<long>::operator++()
  {
    return _InterlockedIncrement(&_value);
  }

  template <>
  inline long atomic<long>::operator--()
  {
    return _InterlockedDecrement(&_value);
  }
#endif
}

#endif // _LIBQI_QI_ATOMIC_HPP_
<commit_msg>Fix MSVC definitions.<commit_after>/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#pragma once

#ifndef _LIBQI_QI_ATOMIC_HPP_
#define _LIBQI_QI_ATOMIC_HPP_

#ifdef _MSC_VER
# include <windows.h>
# pragma intrinsic(_InterlockedIncrement16)
# pragma intrinsic(_InterlockedDecrement16)
# pragma intrinsic(_InterlockedIncrement)
# pragma intrinsic(_InterlockedDecrement)

extern "C" long __cdecl _InterlockedIncrement(long volatile *);
extern "C" long __cdecl _InterlockedDecrement(long volatile *);
extern "C" short __cdecl _InterlockedIncrement16(short volatile *);
extern "C" short __cdecl _InterlockedDecrement16(short volatile *);
#endif

#include <qi/config.hpp>

namespace qi
{
  template <typename T>
  class QI_API atomic
  {
  public:
    atomic()
      : _value(0)
    {
    }

    atomic(T value)
      : _value(value)
    {
    }

    /* prefix operators */
    T operator++();
    T operator--();

    T operator*()
    {
      return _value;
    }

  private:
    T _value;
  };

#ifdef __GNUC__
    template <typename T>
    T atomic<T>::operator++()
    {
      return __sync_add_and_fetch(&_value, 1);
    }

    template <typename T>
    T atomic<T>::operator--()
    {
      return __sync_sub_and_fetch(&_value, 1);
    }
#endif

#ifdef _MSC_VER
  template<>
  inline short atomic<short>::operator++()
  {
    return _InterlockedIncrement16(&_value);
  }

  template<>
  inline short atomic<short>::operator--()
  {
    return _InterlockedDecrement16(&_value);
  }

  template <>
  inline long atomic<long>::operator++()
  {
    return _InterlockedIncrement(&_value);
  }

  template <>
  inline long atomic<long>::operator--()
  {
    return _InterlockedDecrement(&_value);
  }
#endif
}

#endif // _LIBQI_QI_ATOMIC_HPP_
<|endoftext|>


<commit_before>
#include "rtkTestConfiguration.h"
#include "rtkThreeDCircularProjectionGeometryXMLFile.h"
#include "rtkRayBoxIntersectionImageFilter.h"
#include "rtkSheppLoganPhantomFilter.h"
#include "rtkDrawSheppLoganFilter.h"
#include "rtkConstantImageSource.h"

#ifdef USE_CUDA
#  include "rtkCudaForwardProjectionImageFilter.h"
#else
#  include "rtkJosephForwardProjectionImageFilter.h"
#endif

template<class TImage1, class TImage2>
#if FAST_TESTS_NO_CHECKS
void CheckImageQuality(typename TImage::Pointer itkNotUsed(recon), typename TImage::Pointer itkNotUsed(ref))
{
}
#else
void CheckImageQuality(typename TImage1::Pointer recon, typename TImage2::Pointer ref)
{
  typedef itk::ImageRegionConstIterator<TImage1> ImageIteratorType1;
  typedef itk::ImageRegionConstIterator<TImage2> ImageIteratorType2;
  ImageIteratorType1 itTest( recon, recon->GetBufferedRegion() );
  ImageIteratorType2 itRef( ref, ref->GetBufferedRegion() );

  typedef double ErrorType;
  ErrorType TestError = 0.;
  ErrorType EnerError = 0.;

  itTest.GoToBegin();
  itRef.GoToBegin();

  while( !itRef.IsAtEnd() )
    {
    typename TImage1::PixelType TestVal = itTest.Get();
    typename TImage2::PixelType RefVal = itRef.Get();

    if( TestVal != RefVal )
      {
      TestError += vcl_abs(RefVal - TestVal);
      EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
      }
    ++itTest;
    ++itRef;
    }
  // Error per Pixel
  ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
  // MSE
  ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "MSE = " << MSE << std::endl;
  // PSNR
  ErrorType PSNR = 20*log10(255.0) - 10*log10(MSE);
  std::cout << "PSNR = " << PSNR << "dB" << std::endl;
  // QI
  ErrorType QI = (255.0-ErrorPerPixel)/255.0;
  std::cout << "QI = " << QI << std::endl;

  // Checking results
  if (ErrorPerPixel > 1.28)
    {
    std::cerr << "Test Failed, Error per pixel not valid! "
              << ErrorPerPixel << " instead of 1.28" << std::endl;
    //exit( EXIT_FAILURE);
    }
  if (PSNR < 44.)
    {
    std::cerr << "Test Failed, PSNR not valid! "
              << PSNR << " instead of 44" << std::endl;
    //exit( EXIT_FAILURE);
    }
}
#endif

int main(int , char** )
{
  const unsigned int Dimension = 3;
  typedef float                                    OutputPixelType;

#ifdef USE_CUDA
  typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
#else
  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
#endif

  typedef itk::Image< OutputPixelType, Dimension > OutputImageType2;

  typedef itk::Vector<double, 3>                   VectorType;
#if FAST_TESTS_NO_CHECKS
  const unsigned int NumberOfProjectionImages = 3;
#else
  const unsigned int NumberOfProjectionImages = 45;
#endif

  // Constant image sources
  typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
  ConstantImageSourceType::PointType origin;
  ConstantImageSourceType::SizeType size;
  ConstantImageSourceType::SpacingType spacing;

  // The test projects a volume filled with ones. The forward projector should
  // then return the intersection of the ray with the box and it is compared
  // with the analytical intersection of a box with a ray.

  // Create Joseph Forward Projector volume input.
  const ConstantImageSourceType::Pointer volInput = ConstantImageSourceType::New();
  origin[0] = -126;
  origin[1] = -126;
  origin[2] = -126;
#if FAST_TESTS_NO_CHECKS
  size[0] = 2;
  size[1] = 2;
  size[2] = 2;
  spacing[0] = 252.;
  spacing[1] = 252.;
  spacing[2] = 252.;
#else
  size[0] = 64;
  size[1] = 64;
  size[2] = 64;
  spacing[0] = 4.;
  spacing[1] = 4.;
  spacing[2] = 4.;
#endif
  volInput->SetOrigin( origin );
  volInput->SetSpacing( spacing );
  volInput->SetSize( size );
  volInput->SetConstant( 1. );
  volInput->UpdateOutputInformation();

  // Initialization Volume, it is used in the Joseph Forward Projector and in the
  // Ray Box Intersection Filter in order to initialize the stack of projections.
  const ConstantImageSourceType::Pointer projInput = ConstantImageSourceType::New();
  size[2] = NumberOfProjectionImages;
  projInput->SetOrigin( origin );
  projInput->SetSpacing( spacing );
  projInput->SetSize( size );
  projInput->SetConstant( 0. );
  projInput->Update();

  // Joseph Forward Projection filter
#ifdef USE_CUDA
  typedef rtk::CudaForwardProjectionImageFilter JFPType;
#else
  typedef rtk::JosephForwardProjectionImageFilter<OutputImageType, OutputImageType> JFPType;
#endif
  JFPType::Pointer jfp = JFPType::New();
  jfp->InPlaceOff();
  jfp->SetInput( projInput->GetOutput() );
  jfp->SetInput( 1, volInput->GetOutput() );

  // Ray Box Intersection filter (reference)
  typedef rtk::RayBoxIntersectionImageFilter<OutputImageType2, OutputImageType2> RBIType;
  RBIType::Pointer rbi = RBIType::New();
  rbi->InPlaceOff();
  rbi->SetInput( projInput->GetOutput() );
  VectorType boxMin, boxMax;
  boxMin[0] = -126.0;
  boxMin[1] = -126.0;
  boxMin[2] = -126.0;
  boxMax[0] =  126.0;
  boxMax[1] =  126.0;
  boxMax[2] =   47.6;
  rbi->SetBoxMin(boxMin);
  rbi->SetBoxMax(boxMax);

  std::cout << "\n\n****** Case 1: inner ray source ******" << std::endl;
  // The circle is divided in 4 quarters
  for(int q=0; q<4; q++) {
    // Geometry
    typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
    GeometryType::Pointer geometry = GeometryType::New();
    for(unsigned int i=0; i<NumberOfProjectionImages;i++)
      {
      const double angle = -45. + i*2.;
      geometry->AddProjection(47.6 / vcl_cos(angle*itk::Math::pi/180.), 1000., q*90+angle);
      }

    if(q==0) {
      rbi->SetGeometry( geometry );
      rbi->Update();
    }

    jfp->SetGeometry(geometry);
    jfp->Update();

    CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput());
    std::cout << "\n\nTest of quarter #" << q << " PASSED! " << std::endl;
  }

  std::cout << "\n\n****** Case 2: outer ray source ******" << std::endl;
  boxMax[2] = 126.0;
  rbi->SetBoxMax(boxMax);

  // Geometry
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer geometry = GeometryType::New();
  for(unsigned int i=0; i<NumberOfProjectionImages; i++)
    geometry->AddProjection(500., 1000., i*8.);

  rbi->SetGeometry( geometry );
  rbi->Update();

  jfp->SetGeometry( geometry );
  jfp->Update();

  CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

  std::cout << "\n\n****** Case 3: Shepp-Logan, outer ray source ******" << std::endl;

  // Create Shepp Logan reference projections
  typedef rtk::SheppLoganPhantomFilter<OutputImageType2, OutputImageType2> SLPType;
  SLPType::Pointer slp = SLPType::New();
  slp->InPlaceOff();
  slp->SetInput( projInput->GetOutput() );
  slp->SetGeometry(geometry);
  slp->Update();

  // Create a Shepp Logan reference volume (finer resolution)
  origin.Fill(-127);
  size.Fill(128);
  spacing.Fill(2.);
  volInput->SetOrigin( origin );
  volInput->SetSpacing( spacing );
  volInput->SetSize( size );
  volInput->SetConstant( 0. );

  typedef rtk::DrawSheppLoganFilter<OutputImageType2, OutputImageType> DSLType;
  DSLType::Pointer dsl = DSLType::New();
  dsl->InPlaceOff();
  dsl->SetInput( volInput->GetOutput() );
  dsl->Update();

  // Forward projection
  jfp->SetInput( 1, dsl->GetOutput() );
  jfp->Update();

  CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

  std::cout << "\n\n****** Case 4: Shepp-Logan, inner ray source ******" << std::endl;
  geometry = GeometryType::New();
  for(unsigned int i=0; i<NumberOfProjectionImages; i++)
    geometry->AddProjection(120., 1000., i*8.);

  slp->SetGeometry(geometry);
  slp->Update();

  jfp->SetGeometry( geometry );
  jfp->Update();

  CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

  return EXIT_SUCCESS;
}
<commit_msg>Fixed compilation error (wrong copy pasting)<commit_after>
#include "rtkTestConfiguration.h"
#include "rtkThreeDCircularProjectionGeometryXMLFile.h"
#include "rtkRayBoxIntersectionImageFilter.h"
#include "rtkSheppLoganPhantomFilter.h"
#include "rtkDrawSheppLoganFilter.h"
#include "rtkConstantImageSource.h"

#ifdef USE_CUDA
#  include "rtkCudaForwardProjectionImageFilter.h"
#else
#  include "rtkJosephForwardProjectionImageFilter.h"
#endif

template<class TImage1, class TImage2>
#if FAST_TESTS_NO_CHECKS
void CheckImageQuality(typename TImage1::Pointer itkNotUsed(recon), typename TImage2::Pointer itkNotUsed(ref))
{
}
#else
void CheckImageQuality(typename TImage1::Pointer recon, typename TImage2::Pointer ref)
{
  typedef itk::ImageRegionConstIterator<TImage1> ImageIteratorType1;
  typedef itk::ImageRegionConstIterator<TImage2> ImageIteratorType2;
  ImageIteratorType1 itTest( recon, recon->GetBufferedRegion() );
  ImageIteratorType2 itRef( ref, ref->GetBufferedRegion() );

  typedef double ErrorType;
  ErrorType TestError = 0.;
  ErrorType EnerError = 0.;

  itTest.GoToBegin();
  itRef.GoToBegin();

  while( !itRef.IsAtEnd() )
    {
    typename TImage1::PixelType TestVal = itTest.Get();
    typename TImage2::PixelType RefVal = itRef.Get();

    if( TestVal != RefVal )
      {
      TestError += vcl_abs(RefVal - TestVal);
      EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
      }
    ++itTest;
    ++itRef;
    }
  // Error per Pixel
  ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
  // MSE
  ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "MSE = " << MSE << std::endl;
  // PSNR
  ErrorType PSNR = 20*log10(255.0) - 10*log10(MSE);
  std::cout << "PSNR = " << PSNR << "dB" << std::endl;
  // QI
  ErrorType QI = (255.0-ErrorPerPixel)/255.0;
  std::cout << "QI = " << QI << std::endl;

  // Checking results
  if (ErrorPerPixel > 1.28)
    {
    std::cerr << "Test Failed, Error per pixel not valid! "
              << ErrorPerPixel << " instead of 1.28" << std::endl;
    //exit( EXIT_FAILURE);
    }
  if (PSNR < 44.)
    {
    std::cerr << "Test Failed, PSNR not valid! "
              << PSNR << " instead of 44" << std::endl;
    //exit( EXIT_FAILURE);
    }
}
#endif

int main(int , char** )
{
  const unsigned int Dimension = 3;
  typedef float                                    OutputPixelType;

#ifdef USE_CUDA
  typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
#else
  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
#endif

  typedef itk::Image< OutputPixelType, Dimension > OutputImageType2;

  typedef itk::Vector<double, 3>                   VectorType;
#if FAST_TESTS_NO_CHECKS
  const unsigned int NumberOfProjectionImages = 3;
#else
  const unsigned int NumberOfProjectionImages = 45;
#endif

  // Constant image sources
  typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
  ConstantImageSourceType::PointType origin;
  ConstantImageSourceType::SizeType size;
  ConstantImageSourceType::SpacingType spacing;

  // The test projects a volume filled with ones. The forward projector should
  // then return the intersection of the ray with the box and it is compared
  // with the analytical intersection of a box with a ray.

  // Create Joseph Forward Projector volume input.
  const ConstantImageSourceType::Pointer volInput = ConstantImageSourceType::New();
  origin[0] = -126;
  origin[1] = -126;
  origin[2] = -126;
#if FAST_TESTS_NO_CHECKS
  size[0] = 2;
  size[1] = 2;
  size[2] = 2;
  spacing[0] = 252.;
  spacing[1] = 252.;
  spacing[2] = 252.;
#else
  size[0] = 64;
  size[1] = 64;
  size[2] = 64;
  spacing[0] = 4.;
  spacing[1] = 4.;
  spacing[2] = 4.;
#endif
  volInput->SetOrigin( origin );
  volInput->SetSpacing( spacing );
  volInput->SetSize( size );
  volInput->SetConstant( 1. );
  volInput->UpdateOutputInformation();

  // Initialization Volume, it is used in the Joseph Forward Projector and in the
  // Ray Box Intersection Filter in order to initialize the stack of projections.
  const ConstantImageSourceType::Pointer projInput = ConstantImageSourceType::New();
  size[2] = NumberOfProjectionImages;
  projInput->SetOrigin( origin );
  projInput->SetSpacing( spacing );
  projInput->SetSize( size );
  projInput->SetConstant( 0. );
  projInput->Update();

  // Joseph Forward Projection filter
#ifdef USE_CUDA
  typedef rtk::CudaForwardProjectionImageFilter JFPType;
#else
  typedef rtk::JosephForwardProjectionImageFilter<OutputImageType, OutputImageType> JFPType;
#endif
  JFPType::Pointer jfp = JFPType::New();
  jfp->InPlaceOff();
  jfp->SetInput( projInput->GetOutput() );
  jfp->SetInput( 1, volInput->GetOutput() );

  // Ray Box Intersection filter (reference)
  typedef rtk::RayBoxIntersectionImageFilter<OutputImageType2, OutputImageType2> RBIType;
  RBIType::Pointer rbi = RBIType::New();
  rbi->InPlaceOff();
  rbi->SetInput( projInput->GetOutput() );
  VectorType boxMin, boxMax;
  boxMin[0] = -126.0;
  boxMin[1] = -126.0;
  boxMin[2] = -126.0;
  boxMax[0] =  126.0;
  boxMax[1] =  126.0;
  boxMax[2] =   47.6;
  rbi->SetBoxMin(boxMin);
  rbi->SetBoxMax(boxMax);

  std::cout << "\n\n****** Case 1: inner ray source ******" << std::endl;
  // The circle is divided in 4 quarters
  for(int q=0; q<4; q++) {
    // Geometry
    typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
    GeometryType::Pointer geometry = GeometryType::New();
    for(unsigned int i=0; i<NumberOfProjectionImages;i++)
      {
      const double angle = -45. + i*2.;
      geometry->AddProjection(47.6 / vcl_cos(angle*itk::Math::pi/180.), 1000., q*90+angle);
      }

    if(q==0) {
      rbi->SetGeometry( geometry );
      rbi->Update();
    }

    jfp->SetGeometry(geometry);
    jfp->Update();

    CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput());
    std::cout << "\n\nTest of quarter #" << q << " PASSED! " << std::endl;
  }

  std::cout << "\n\n****** Case 2: outer ray source ******" << std::endl;
  boxMax[2] = 126.0;
  rbi->SetBoxMax(boxMax);

  // Geometry
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer geometry = GeometryType::New();
  for(unsigned int i=0; i<NumberOfProjectionImages; i++)
    geometry->AddProjection(500., 1000., i*8.);

  rbi->SetGeometry( geometry );
  rbi->Update();

  jfp->SetGeometry( geometry );
  jfp->Update();

  CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

  std::cout << "\n\n****** Case 3: Shepp-Logan, outer ray source ******" << std::endl;

  // Create Shepp Logan reference projections
  typedef rtk::SheppLoganPhantomFilter<OutputImageType2, OutputImageType2> SLPType;
  SLPType::Pointer slp = SLPType::New();
  slp->InPlaceOff();
  slp->SetInput( projInput->GetOutput() );
  slp->SetGeometry(geometry);
  slp->Update();

  // Create a Shepp Logan reference volume (finer resolution)
  origin.Fill(-127);
  size.Fill(128);
  spacing.Fill(2.);
  volInput->SetOrigin( origin );
  volInput->SetSpacing( spacing );
  volInput->SetSize( size );
  volInput->SetConstant( 0. );

  typedef rtk::DrawSheppLoganFilter<OutputImageType2, OutputImageType> DSLType;
  DSLType::Pointer dsl = DSLType::New();
  dsl->InPlaceOff();
  dsl->SetInput( volInput->GetOutput() );
  dsl->Update();

  // Forward projection
  jfp->SetInput( 1, dsl->GetOutput() );
  jfp->Update();

  CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

  std::cout << "\n\n****** Case 4: Shepp-Logan, inner ray source ******" << std::endl;
  geometry = GeometryType::New();
  for(unsigned int i=0; i<NumberOfProjectionImages; i++)
    geometry->AddProjection(120., 1000., i*8.);

  slp->SetGeometry(geometry);
  slp->Update();

  jfp->SetGeometry( geometry );
  jfp->Update();

  CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include "vast/system/default_configuration.hpp"

#include <caf/defaults.hpp>
#include <caf/timestamp.hpp>

#include "vast/defaults.hpp"
#include "vast/detail/system.hpp"
#include "vast/error.hpp"
#include "vast/filesystem.hpp"
#include "vast/system/application.hpp"

namespace vast::system {

path make_log_dirname() {
  auto dir_name = caf::deep_to_string(caf::make_timestamp());
  dir_name += '#';
  dir_name += std::to_string(detail::process_id());
  return path{"log"} / dir_name;
}

default_configuration::default_configuration(std::string application_name)
  : application_name{std::move(application_name)} {
  // Tweak default logging options.
  set("logger.component-blacklist",
      caf::make_config_value_list(caf::atom("caf"), caf::atom("caf_flow")));
  set("logger.console-verbosity", caf::atom("INFO"));
  set("logger.console", caf::atom("COLORED"));
  set("logger.file-verbosity", caf::atom("DEBUG"));
  // Allow VAST clusters to form a mesh.
  set("middleman.enable-automatic-connections", true);
}

caf::expected<path>
default_configuration::setup_log_file(const path& base_dir) {
  auto log_dir = base_dir / make_log_dirname();
  // Create the log directory first, which we need to create the symlink
  // afterwards.
  if (!exists(log_dir))
    if (auto res = mkdir(log_dir); !res)
      return res.error();
  // Create user-friendly symlink to current log directory.
  auto link_dir = log_dir.chop(-1) / "current";
  if (exists(link_dir))
    if (!rm(link_dir))
      return make_error(ec::filesystem_error, "cannot remove log symlink");
  create_symlink(log_dir.trim(-1), link_dir);
  return log_dir / application_name + ".log";
}

// Parses the options from the root command and adds them to the global
// configuration.
caf::error default_configuration::merge_root_options(system::application& app) {
  // Delegate to the root command for argument parsing.
  caf::settings options;
  app.root.options.parse(options, command_line.begin(), command_line.end());
  // Move everything into the system-wide options, but use "vast" as category
  // instead of the default "global" category.
  content["vast"].as_dictionary().insert(options.begin(), options.end());
  auto default_fn = caf::defaults::logger::file_name;
  if (caf::get_or(*this, "logger.file-name", default_fn) == default_fn) {
    path dir = get_or(*this, "vast.directory", defaults::command::directory);
    if (auto log_file = setup_log_file(dir.complete()); !log_file) {
      std::cerr << "failed to setup log file: " << to_string(log_file.error())
                << std::endl;
      return log_file.error();
    } else {
      set("logger.file-name", log_file->str());
    }
  }
  return caf::none;
}

} // namespace vast::system
<commit_msg>Fix merge_root_options<commit_after>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include "vast/system/default_configuration.hpp"

#include <caf/defaults.hpp>
#include <caf/timestamp.hpp>

#include "vast/defaults.hpp"
#include "vast/detail/system.hpp"
#include "vast/error.hpp"
#include "vast/filesystem.hpp"
#include "vast/system/application.hpp"

namespace vast::system {

path make_log_dirname() {
  auto dir_name = caf::deep_to_string(caf::make_timestamp());
  dir_name += '#';
  dir_name += std::to_string(detail::process_id());
  return path{"log"} / dir_name;
}

default_configuration::default_configuration(std::string application_name)
  : application_name{std::move(application_name)} {
  // Tweak default logging options.
  set("logger.component-blacklist",
      caf::make_config_value_list(caf::atom("caf"), caf::atom("caf_flow")));
  set("logger.console-verbosity", caf::atom("INFO"));
  set("logger.console", caf::atom("COLORED"));
  set("logger.file-verbosity", caf::atom("DEBUG"));
  // Allow VAST clusters to form a mesh.
  set("middleman.enable-automatic-connections", true);
}

caf::expected<path>
default_configuration::setup_log_file(const path& base_dir) {
  auto log_dir = base_dir / make_log_dirname();
  // Create the log directory first, which we need to create the symlink
  // afterwards.
  if (!exists(log_dir))
    if (auto res = mkdir(log_dir); !res)
      return res.error();
  // Create user-friendly symlink to current log directory.
  auto link_dir = log_dir.chop(-1) / "current";
  if (exists(link_dir))
    if (!rm(link_dir))
      return make_error(ec::filesystem_error, "cannot remove log symlink");
  create_symlink(log_dir.trim(-1), link_dir);
  return log_dir / application_name + ".log";
}

// Parses the options from the root command and adds them to the global
// configuration.
caf::error default_configuration::merge_root_options(system::application& app) {
  // Delegate to the root command for argument parsing.
  caf::settings options;
  app.root.options.parse(options, command_line.begin(), command_line.end());
  // Move everything into the system-wide options, but use "vast" as category
  // instead of the default "global" category.
  auto& vast_section = content["vast"].as_dictionary();
  for (auto& [key, value] : options)
    vast_section.insert_or_assign(key, value);
  auto default_fn = caf::defaults::logger::file_name;
  if (caf::get_or(*this, "logger.file-name", default_fn) == default_fn) {
    path dir = get_or(*this, "vast.directory", defaults::command::directory);
    if (auto log_file = setup_log_file(dir.complete()); !log_file) {
      std::cerr << "failed to setup log file: " << to_string(log_file.error())
                << std::endl;
      return log_file.error();
    } else {
      set("logger.file-name", log_file->str());
    }
  }
  return caf::none;
}

} // namespace vast::system
<|endoftext|>


<commit_before>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#pragma once

#include "vast/concept/parseable/core.hpp"
#include "vast/concept/parseable/numeric/integral.hpp"
#include "vast/port.hpp"

namespace vast {

struct port_type_parser : parser<port_type_parser> {
  using attribute = port::port_type;

  template <class Iterator>
  bool parse(Iterator& f, const Iterator& l, unused_type) const {
    using namespace parsers;
    using namespace parser_literals;
    auto p = ("?"_p | "tcp" | "udp" | "icmp");
    return p(f, l, unused);
  }

  template <class Iterator>
  bool parse(Iterator& f, const Iterator& l, port::port_type& x) const {
    using namespace parsers;
    using namespace parser_literals;
    auto p = (
      "?"_p->*[] { return port::unknown; } | "tcp"_p->*[] { return port::tcp; }
      | "udp"_p->*[] { return port::udp; }
      | "icmp"_p->*[] { return port::icmp; });
    return p(f, l, x);
  }
};

template <>
struct parser_registry<port::port_type> {
  using type = port_type_parser;
};

namespace parsers {

auto const port_type = port_type_parser{};

} // namespace parsers

struct port_parser : parser<port_parser> {
  using attribute = port;

  template <class Iterator, class Attribute>
  bool parse(Iterator& f, const Iterator& l, Attribute& x) const {
    using namespace parsers;
    using namespace parser_literals;
    auto p = u16 >> '/' >> parsers::port_type;
    if constexpr (std::is_same_v<Attribute, unused_type>) {
      return p(f, l, unused);
    } else {
      port::number_type n;
      port::port_type t;
      if (!p(f, l, n, t))
        return false;
      x = {n, t};
      return true;
    }
  }
};

template <>
struct parser_registry<port> {
  using type = port_parser;
};

namespace parsers {

auto const port = port_parser{};

} // namespace parsers

} // namespace vast
<commit_msg>Disable clang-format for parser dsl<commit_after>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#pragma once

#include "vast/concept/parseable/core.hpp"
#include "vast/concept/parseable/numeric/integral.hpp"
#include "vast/port.hpp"

namespace vast {

struct port_type_parser : parser<port_type_parser> {
  using attribute = port::port_type;

  template <class Iterator>
  bool parse(Iterator& f, const Iterator& l, unused_type) const {
    using namespace parsers;
    using namespace parser_literals;
    auto p = ("?"_p | "tcp" | "udp" | "icmp");
    return p(f, l, unused);
  }

  template <class Iterator>
  bool parse(Iterator& f, const Iterator& l, port::port_type& x) const {
    using namespace parsers;
    using namespace parser_literals;
    // clang-format off
    auto p
      = ( "?"_p ->* [] { return port::unknown; }
         | "tcp"_p ->* [] { return port::tcp; }
         | "udp"_p ->* [] { return port::udp; }
         | "icmp"_p ->* [] { return port::icmp; }
         )
      ;
    // clang-format on
    return p(f, l, x);
  }
};

template <>
struct parser_registry<port::port_type> {
  using type = port_type_parser;
};

namespace parsers {

auto const port_type = port_type_parser{};

} // namespace parsers

struct port_parser : parser<port_parser> {
  using attribute = port;

  template <class Iterator, class Attribute>
  bool parse(Iterator& f, const Iterator& l, Attribute& x) const {
    using namespace parsers;
    using namespace parser_literals;
    auto p = u16 >> '/' >> parsers::port_type;
    if constexpr (std::is_same_v<Attribute, unused_type>) {
      return p(f, l, unused);
    } else {
      port::number_type n;
      port::port_type t;
      if (!p(f, l, n, t))
        return false;
      x = {n, t};
      return true;
    }
  }
};

template <>
struct parser_registry<port> {
  using type = port_parser;
};

namespace parsers {

auto const port = port_parser{};

} // namespace parsers

} // namespace vast
<|endoftext|>