text:
// Copyright 2016 Alex Silva Torres
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "simple-object.h"

#include <string>
#include <boost/variant.hpp>

#include "obj-type.h"
#include "object-factory.h"

namespace shpp {
namespace internal {

ObjectPtr NullObject::ObjBool() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(false);
}

ObjectPtr NullObject::Equal(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (obj->type() == ObjectType::NIL) {
    return obj_factory.NewBool(true);
  } else {
    return obj_factory.NewBool(false);
  }
}

ObjectPtr NullObject::NotEqual(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (obj->type() == ObjectType::NIL) {
    return obj_factory.NewBool(false);
  } else {
    return obj_factory.NewBool(true);
  }
}

ObjectPtr NullObject::And(ObjectPtr /*obj*/) {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(false);
}

ObjectPtr NullObject::Or(ObjectPtr obj) {
  return obj->ObjBool();
}

ObjectPtr NullObject::Not() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(true);
}

ObjectPtr BoolObject::ObjBool() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(value_);
}

ObjectPtr BoolObject::ObjCmd() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewString(value_?"true":"false");
}

ObjectPtr BoolObject::Equal(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (obj->type() == ObjectType::BOOL) {
    bool value = static_cast<const BoolObject&>(*obj).value_;
    return obj_factory.NewBool(value_ == value);
  } else {
    ObjectPtr obj_bool = obj->ObjBool();
    bool value = static_cast<const BoolObject&>(*obj_bool).value_;
    return obj_factory.NewBool(value_ == value);
  }
}

ObjectPtr BoolObject::NotEqual(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (obj->type() == ObjectType::BOOL) {
    bool value = static_cast<const BoolObject&>(*obj).value_;
    return obj_factory.NewBool(value_ != value);
  } else {
    ObjectPtr obj_bool = obj->ObjBool();
    bool value = static_cast<const BoolObject&>(*obj_bool).value_;
    return obj_factory.NewBool(value_ != value);
  }
}

ObjectPtr BoolObject::And(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (value_ == false) {
    return obj_factory.NewBool(false);
  }

  if (obj->type() == ObjectType::BOOL) {
    bool value = static_cast<const BoolObject&>(*obj).value_;
    ObjectFactory obj_factory(symbol_table_stack());
    return obj_factory.NewBool(value);
  } else {
    ObjectPtr obj_bool = obj->ObjBool();
    bool value = static_cast<const BoolObject&>(*obj_bool).value_;
    ObjectFactory obj_factory(symbol_table_stack());
    return obj_factory.NewBool(value);
  }
}

ObjectPtr BoolObject::Or(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (value_ == true) {
    return obj_factory.NewBool(true);
  }

  if (obj->type() == ObjectType::BOOL) {
    bool value = static_cast<const BoolObject&>(*obj).value_;
    ObjectFactory obj_factory(symbol_table_stack());
    return obj_factory.NewBool(value);
  } else {
    ObjectPtr obj_bool = obj->ObjBool();
    bool value = static_cast<const BoolObject&>(*obj_bool).value_;
    ObjectFactory obj_factory(symbol_table_stack());
    return obj_factory.NewBool(value);
  }
}

ObjectPtr BoolObject::Not() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(!value_);
}

////////////////////////////////////////////////////////////////////////////////
/// Int Object
////////////////////////////////////////////////////////////////////////////////

ObjectPtr IntObject::OperationObj(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      int r = OperationArit(value_, int_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewInt(r);
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      float r = OperationArit(value_, real_obj.value(), op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr IntObject::OperationObjInt(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      int r = OperationArit(value_, int_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewInt(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr IntObject::Not() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(false);
}

ObjectPtr IntObject::ObjReal() {
  float v = static_cast<float>(value_);

  ObjectFactory obj_factory(symbol_table_stack());
  ObjectPtr obj_real(obj_factory.NewReal(v));

  return obj_real;
}

ObjectPtr IntObject::ObjCmd() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewString(std::to_string(value_));
}

ObjectPtr IntObject::ObjString() {
  std::string v = std::to_string(value_);

  ObjectFactory obj_factory(symbol_table_stack());
  ObjectPtr obj_str(obj_factory.NewString(v));

  return obj_str;
}

ObjectPtr IntObject::OperationObjComp(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      bool r = OperationComp(value_, int_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(r);
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      bool r = OperationComp(value_, real_obj.value(), op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(r);
    } break;

    default: {
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(false);
    }
  }
}

ObjectPtr IntObject::Copy() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewInt(value_);
}

ObjectPtr IntObject::ObjBool() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(true);
}

ObjectPtr IntObject::Add(ObjectPtr obj) {
  return OperationObj(obj, 0);
}

ObjectPtr IntObject::Sub(ObjectPtr obj) {
  return OperationObj(obj, 1);
}

ObjectPtr IntObject::Mult(ObjectPtr obj) {
  return OperationObj(obj, 2);
}

ObjectPtr IntObject::Div(ObjectPtr obj) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      float b = int_obj.value();

      if (b == 0) {
        throw RunTimeError(RunTimeError::ErrorCode::ZERO_DIV,
                           boost::format("zero div indetermined"));
      }

      float r = static_cast<float>(value_)/ b;
      ObjectFactory obj_factory(symbol_table_stack());
      if ((value_% int_obj.value_) != 0) {
        return obj_factory.NewReal(r);
      } else {
        return obj_factory.NewInt(static_cast<int>(r));
      }
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      float b = real_obj.value();

      if (b == static_cast<float>(0)) {
        throw RunTimeError(RunTimeError::ErrorCode::ZERO_DIV,
                           boost::format("zero div indetermined"));
      }

      float r = static_cast<float>(value_)/ b;
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr IntObject::DivMod(ObjectPtr obj) {
  return OperationObjInt(obj, 4);
}

ObjectPtr IntObject::RightShift(ObjectPtr obj) {
  return OperationObjInt(obj, 5);
}

ObjectPtr IntObject::LeftShift(ObjectPtr obj) {
  return OperationObjInt(obj, 6);
}

ObjectPtr IntObject::Lesser(ObjectPtr obj) {
  return OperationObjComp(obj, 0);
}

ObjectPtr IntObject::Greater(ObjectPtr obj) {
  return OperationObjComp(obj, 1);
}

ObjectPtr IntObject::LessEqual(ObjectPtr obj) {
  return OperationObjComp(obj, 2);
}

ObjectPtr IntObject::GreatEqual(ObjectPtr obj) {
  return OperationObjComp(obj, 3);
}

ObjectPtr IntObject::Equal(ObjectPtr obj) {
  return OperationObjComp(obj, 4);
}

ObjectPtr IntObject::NotEqual(ObjectPtr obj) {
  if (obj->type() != ObjectType::INT && obj->type() != ObjectType::REAL) {
    ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(true);
  }

  return OperationObjComp(obj, 5);
}

ObjectPtr IntObject::BitAnd(ObjectPtr obj) {
  return OperationObjInt(obj, 7);
}

ObjectPtr IntObject::BitOr(ObjectPtr obj) {
  return OperationObjInt(obj, 8);
}

ObjectPtr IntObject::BitXor(ObjectPtr obj) {
  return OperationObjInt(obj, 9);
}

ObjectPtr IntObject::BitNot() {
  int r = ~value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewInt(r);
}

ObjectPtr IntObject::UnaryAdd() {
  int r = +value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewInt(r);
}

ObjectPtr IntObject::UnarySub() {
  int r = -value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewInt(r);
}

////////////////////////////////////////////////////////////////////////////////
/// Real Object
////////////////////////////////////////////////////////////////////////////////
ObjectPtr RealObject::OperationObj(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      float r = OperationArit(value_, static_cast<float>(int_obj.value()), op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(r);
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      float r = OperationArit(value_, real_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr RealObject::Not() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(false);
}

ObjectPtr RealObject::ObjInt() {
  int v = static_cast<int>(value_);

  ObjectFactory obj_factory(symbol_table_stack());
  ObjectPtr obj_int(obj_factory.NewReal(v));
  return obj_int;
}

ObjectPtr RealObject::ObjString() {
  std::string v = std::to_string(value_);

  ObjectFactory obj_factory(symbol_table_stack());
  ObjectPtr obj_str(obj_factory.NewString(v));

  return obj_str;
}

ObjectPtr RealObject::ObjCmd() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewString(std::to_string(value_));
}

ObjectPtr RealObject::OperationObjComp(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      bool r = OperationComp(value_, static_cast<float>(int_obj.value()), op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(r);
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      bool r = OperationComp(value_, real_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr RealObject::Copy() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewReal(value_);
}

ObjectPtr RealObject::ObjBool() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(true);
}

ObjectPtr RealObject::Add(ObjectPtr obj) {
  return OperationObj(obj, 0);
}

ObjectPtr RealObject::Sub(ObjectPtr obj) {
  return OperationObj(obj, 1);
}

ObjectPtr RealObject::Mult(ObjectPtr obj) {
  return OperationObj(obj, 2);
}

ObjectPtr RealObject::Div(ObjectPtr obj) {
  return OperationObj(obj, 3);
}

ObjectPtr RealObject::Lesser(ObjectPtr obj) {
  return OperationObjComp(obj, 0);
}

ObjectPtr RealObject::Greater(ObjectPtr obj) {
  return OperationObjComp(obj, 1);
}

ObjectPtr RealObject::LessEqual(ObjectPtr obj) {
  return OperationObjComp(obj, 2);
}

ObjectPtr RealObject::GreatEqual(ObjectPtr obj) {
  return OperationObjComp(obj, 3);
}

ObjectPtr RealObject::Equal(ObjectPtr obj) {
  return OperationObjComp(obj, 4);
}

ObjectPtr RealObject::NotEqual(ObjectPtr obj) {
  if (obj->type() != ObjectType::INT && obj->type() != ObjectType::REAL) {
    ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(true);
  }

  return OperationObjComp(obj, 5);
}

ObjectPtr RealObject::UnaryAdd() {
  float r = +value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewReal(r);
}

ObjectPtr RealObject::UnarySub() {
  float r = -value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewReal(r);
}

}
}

max_stars_repo_name: aminya/shell-plus-plus

max_issues_repo_name: aminya/shell-plus-plus

max_forks_repo_name: aminya/shell-plus-plus


text:
#include "stdafx.h"
#include <catch.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/variant.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <boost/fusion/include/io.hpp>

#include <iostream>
#include <list>
#include <map>

namespace x3 = boost::spirit::x3;

namespace client {
namespace ast
{
///////////////////////////////////////////////////////////////////////////
//  The AST
///////////////////////////////////////////////////////////////////////////
struct nil {};
struct signed_;
struct expression;

struct operand : x3::variant<
	nil
	, unsigned int
	, x3::forward_ast<signed_>
	, x3::forward_ast<expression>
>
{
	using base_type::base_type;
	using base_type::operator=;
};

struct signed_
{
	char sign;
	operand operand_;
};

struct operation
{
	char operator_;
	operand operand_;
};

struct expression
{
	operand first;
	std::list<operation> rest;
};

// print function for debugging
inline std::ostream& operator<<(std::ostream& out, nil) { out << "nil"; return out; }
} // ast
} // client

BOOST_FUSION_ADAPT_STRUCT(client::ast::signed_,
	sign, operand_
)

BOOST_FUSION_ADAPT_STRUCT(client::ast::operation,
	operator_, operand_
)

BOOST_FUSION_ADAPT_STRUCT(client::ast::expression,
	first, rest
)

namespace client
{
///////////////////////////////////////////////////////////////////////////
//  The Virtual Machine
///////////////////////////////////////////////////////////////////////////
enum byte_code
{
	op_neg,     //  negate the top stack entry
	op_add,     //  add top two stack entries
	op_sub,     //  subtract top two stack entries
	op_mul,     //  multiply top two stack entries
	op_div,     //  divide top two stack entries
	op_int,     //  push constant integer into the stack
};

class vmachine
{
public:

	vmachine(unsigned stackSize = 4096)
		: stack(stackSize)
		, stack_ptr(stack.begin())
	{
	}

	int top() const { return stack_ptr[-1]; };
	void execute(std::vector<int> const& code);

private:
	std::vector<int> stack;
	std::vector<int>::iterator stack_ptr;
};

void vmachine::execute(std::vector<int> const& code)
{
	std::vector<int>::const_iterator pc = code.begin();
	stack_ptr = stack.begin();

	while (pc != code.end())
	{
		switch (*pc++)
		{
		case op_neg:
			stack_ptr[-1] = -stack_ptr[-1];
			break;

		case op_add:
			--stack_ptr;
			stack_ptr[-1] += stack_ptr[0];
			break;

		case op_sub:
			--stack_ptr;
			stack_ptr[-1] -= stack_ptr[0];
			break;

		case op_mul:
			--stack_ptr;
			stack_ptr[-1] *= stack_ptr[0];
			break;

		case op_div:
			--stack_ptr;
			stack_ptr[-1] /= stack_ptr[0];
			break;

		case op_int:
			*stack_ptr++ = *pc++;
			break;
		}
	}
}

///////////////////////////////////////////////////////////////////////////
//  The Compiler
///////////////////////////////////////////////////////////////////////////
struct compiler
{
	typedef void result_type;

	std::vector<int>& code;
	compiler(std::vector<int>& code)
		: code(code) {}

	void operator()(ast::nil) const { BOOST_ASSERT(0); }
	void operator()(unsigned int n) const
	{
		code.push_back(op_int);
		code.push_back(n);
	}

	void operator()(ast::operation const& x) const
	{
		boost::apply_visitor(*this, x.operand_);
		switch (x.operator_)
		{
		case '+': code.push_back(op_add); break;
		case '-': code.push_back(op_sub); break;
		case '*': code.push_back(op_mul); break;
		case '/': code.push_back(op_div); break;
		default: BOOST_ASSERT(0); break;
		}
	}

	void operator()(ast::signed_ const& x) const
	{
		boost::apply_visitor(*this, x.operand_);
		switch (x.sign)
		{
		case '-': code.push_back(op_neg); break;
		case '+': break;
		default: BOOST_ASSERT(0); break;
		}
	}

	void operator()(ast::expression const& x) const
	{
		boost::apply_visitor(*this, x.first);
		for (ast::operation const& oper : x.rest)
		{
			(*this)(oper);
		}
	}
};

///////////////////////////////////////////////////////////////////////////////
//  The calculator grammar
///////////////////////////////////////////////////////////////////////////////
namespace calculator_grammar
{
using x3::uint_;
using x3::char_;

struct expression_class;
struct term_class;
struct factor_class;

x3::rule<expression_class, ast::expression> const expression("expression");
x3::rule<term_class, ast::expression> const term("term");
x3::rule<factor_class, ast::operand> const factor("factor");

auto const expression_def =
term
>> *((char_('+') > term)
	| (char_('-') > term)
	)
	;

auto const term_def =
factor
>> *((char_('*') > factor)
	| (char_('/') > factor)
	)
	;

auto const factor_def =
uint_
| '(' > expression > ')'
| (char_('-') > factor)
| (char_('+') > factor)
;

BOOST_SPIRIT_DEFINE(
	expression
	, term
	, factor
);

struct expression_class
{
	//  Our error handler
	template <typename Iterator, typename Exception, typename Context>
	x3::error_handler_result
		on_error(Iterator&, Iterator const& last, Exception const& x, Context const& context)
	{
		std::cout
			<< "Error! Expecting: "
			<< x.which()
			<< " here: \""
			<< std::string(x.where(), last)
			<< "\""
			<< std::endl
			;
		return x3::error_handler_result::fail;
	}
};

auto calculator = expression;
}

using calculator_grammar::calculator;
}

TEST_CASE("calculator example")
{
	//
	// learn to parse value expressions
	// a large example
	// - variable / expression
	// - vm to calculate
	//

	SECTION("run parser")
	{
		typedef std::string::const_iterator iterator_type;
		typedef client::ast::expression ast_expression;
		typedef client::compiler compiler;

		std::string str = "3 * 2 + 1";

		client::vmachine mach;              // Our virtual machine
		std::vector<int> code;              // Our VM code
		auto& calc = client::calculator;    // Our grammar
		ast_expression expression;          // Our program (AST)
		compiler compile(code);             // Compiles the program

		iterator_type iter = str.begin();
		iterator_type const end = str.end();
		boost::spirit::x3::ascii::space_type space;
		bool r = phrase_parse(iter, end, calc, space, expression);

		CHECK(r);
		CHECK(iter == end);

		compile(expression); // code generation

		mach.execute(code);  // execute
	}
}

ext: cpp

max_stars_repo_name: laxtools/article

max_issues_repo_name: laxtools/article

max_forks_repo_name: laxtools/article


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

#include "DuplicateClasses.h"

#include "Trace.h"
#include <boost/algorithm/string/predicate.hpp>
#include <vector>

namespace dup_classes {

// Global allowlist for duplicated classes
std::vector<std::string> g_dup_class_allowlist{
    "Lcom/facebook/soloader/MergedSoMapping;", "Ljunit/framework/TestSuite;",
    // Java 8 desugaring classes generated by D8. See this link for more info:
    // https://r8.googlesource.com/r8/+/refs/heads/d8-1.5/src/main/java/com/
    //   android/tools/r8/utils/ProgramClassCollection.java#72
    "L$r8$java8methods$utility", "Ljava/util/stream/Stream$-"};

// Read allowed duplicate class list from config.
void read_dup_class_allowlist(const JsonWrapper& json_cfg) {
  std::vector<std::string> dups;
  json_cfg.get("dup_class_allowlist", {}, dups);
  for (const auto& name : dups) {
    g_dup_class_allowlist.emplace_back(name);
  }

  TRACE(MAIN, 1, "dup_class_allowlist: { ");
  for (const auto& allowlist_name : g_dup_class_allowlist) {
    TRACE(MAIN, 1, "  %s", allowlist_name.c_str());
  }
  TRACE(MAIN, 1, "}");
}

// Return true if the cls is among one of the known allowed duplicated
// classes.
bool is_known_dup(DexClass* cls) {
  return std::find_if(g_dup_class_allowlist.begin(),
                      g_dup_class_allowlist.end(),
                      [cls](const std::string& name) {
                        return boost::starts_with(cls->get_name()->str(), name);
                      }) != g_dup_class_allowlist.end();
}

} // namespace dup_classes

max_stars_repo_name: ivanmurashko/redex

max_issues_repo_name: ivanmurashko/redex

max_forks_repo_name: ivanmurashko/redex


text:
// Copyright 2004-present Facebook. All Rights Reserved.

#include <fstream>

#include <boost/algorithm/string/trim.hpp>
#include <boost/lexical_cast.hpp>

#include <osquery/core.h>
#include <osquery/database.h>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include <osquery/tables.h>

namespace osquery {
namespace tables {

const std::string kKernelSyscallAddrModifiedPath = "/sys/kernel/camb/syscall_addr_modified";
const std::string kKernelTextHashPath = "/sys/kernel/camb/text_segment_hash";

QueryData genKernelIntegrity(QueryContext &context) {
  QueryData results;
  Row r;
  std::string content;
  std::string text_segment_hash;
  std::string syscall_addr_modified;

  // Get an integral value, 0 or 1, for whether a syscall table pointer is modified.
  auto f1 = osquery::readFile(kKernelSyscallAddrModifiedPath, content);
  if (f1.ok()) {
    boost::trim(content);
    syscall_addr_modified = content;
  } else {
    VLOG(1) << "Cannot read file: " << kKernelSyscallAddrModifiedPath;
    return results;
  }

  // Get the hash value for the kernel's .text memory segment
  auto f2 = osquery::readFile(kKernelTextHashPath, content);
  if (f2.ok()) {
    boost::trim(content);
    text_segment_hash = content;
  } else {
    VLOG(1) << "Cannot read file: " << kKernelTextHashPath;
    return results;
  }

  r["sycall_addr_modified"] = syscall_addr_modified;
  r["text_segment_hash"] = text_segment_hash;
  results.push_back(r);

  return results;
}
}
}

max_stars_repo_name: majacQ/osquery

max_issues_repo_name: majacQ/osquery

max_forks_repo_name: majacQ/osquery


text:
/*
// Copyright 2018 University of Liege
//
// 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.
//
// Authors:
// - Adrien Crovato
*/

//// Field variables computation
// Compute variables (velocity, speed of sound, density, mach number) in the field
//
// I/O:
// - Minf: freestream Mach number
// - vInf: freestream velocity vector
// - bPan: (network of) body panels (structure)
// - fPan: field panels (structure)
// - sp: sub-panel (structure)
// - b2fAIC: body to field AIC (structure)
// - f2fAIC: field to field AIC (structure)
// - spAIC: body to field AIC for subpanels (structure)

#include <iostream>
#include <Eigen/Dense>
#include "compute_fVars.h"
#include "interp_ctv.h"
#include "interp_sp.h"

#define GAMMA 1.4
#define NV 4 // number of vertices

using namespace std;
using namespace Eigen;

void compute_fVars(double Minf, Vector3d &vInf, Network &bPan, Field &fPan, Subpanel &sp,
                       Body_AIC &b2fAIC, Field2field_AIC &f2fAIC, Subpanel_AIC &spAIC) {

    //// Initialization
    // Temporary variables
    MatrixXd vSing; // corner interpolated singularities
    vSing.resize(NV,2);
    MatrixXd sInterp; // sub-panel interoplated singularities
    sInterp.resize(sp.NS,2);

    //// Potential
    // Perturbation potential
    fPan.phi = b2fAIC.B * bPan.tau + b2fAIC.A * bPan.mu + f2fAIC.C * fPan.sigma;

    // Perturbation potential (with sub-paneling technique)
    // TODO Subpaneling induces small assymmetry. Check why?
    for (int jj = 0; jj < sp.sI.size(); jj++) {
        int j = sp.sI[jj]; // panel global index
        int n = j % bPan.nC_; // panel chordwise index
        int m = j / bPan.nC_; // panel spanwise index
        // Interpolation of singularities from centers to vertices
        vSing = interp_ctv(j, n, m, bPan);
        // Interpolation of singularities from vertices to sub-panel
        sInterp = interp_sp(j, bPan, sp,
                            vSing(0,0), vSing(1,0), vSing(2,0), vSing(3,0),
                            vSing(0,1), vSing(1,1), vSing(2,1), vSing(3,1));

        for (int ii = 0; ii < sp.fI[jj].size(); ii++) {
            int i = sp.fI[jj][ii]; // cell index
            // Velocity induces by each sub-panel
            for (int k = 0; k < sp.NS; k++) {
                fPan.phi(i) += spAIC.A[jj](ii,k) * sInterp(k,0) + spAIC.B[jj](ii,k) * sInterp(k,1);
            }
        }
    }

    //// Velocity
    // Perturbation velocity
    for (int i = 0; i < fPan.nE; i++) {
        int f = fPan.eIdx(i);

        // X-derivative
        double fb=0, ff=0;
        if (fPan.fbdMap(f,0) && fPan.fwdMap(f,0))
            fb = (fPan.phi(f) - fPan.phi(f - 1)) / fPan.deltaX;
        if (fPan.fbdMap(f,1) && fPan.fwdMap(f,1))
            ff = (fPan.phi(f + 1) - fPan.phi(f)) / fPan.deltaX;
        if (fPan.fbdMap(f,0) && fPan.fwdMap(f,0) && fPan.fbdMap(f,1) && fPan.fwdMap(f,1))
            fPan.U(f,0) = 0.5*(fb+ff);
        else
            fPan.U(f,0) = fb+ff;

        // Y-derivative
        fb=0; ff=0;
        if (fPan.fbdMap(f,2) && fPan.fwdMap(f,2))
            fb = (fPan.phi(f) - fPan.phi(f - fPan.nX*fPan.nZ)) / fPan.deltaY;
        if (fPan.fbdMap(f,3) && fPan.fwdMap(f,3))
            ff = (fPan.phi(f + fPan.nX*fPan.nZ) - fPan.phi(f)) / fPan.deltaY;
        if (fPan.fbdMap(f,2) && fPan.fwdMap(f,2) && fPan.fbdMap(f,3) && fPan.fwdMap(f,3))
            fPan.U(f,1) = 0.5*(fb+ff);
        else
            fPan.U(f,1) = fb+ff;

        // Z-derivative
        fb=0; ff=0;
        if (fPan.fbdMap(f,4) && fPan.fwdMap(f,4))
            fb = (fPan.phi(f) - fPan.phi(f - fPan.nX)) / fPan.deltaZ;
        if (fPan.fbdMap(f,5) && fPan.fwdMap(f,5))
            ff = (fPan.phi(f + fPan.nX) - fPan.phi(f)) / fPan.deltaZ;
        if (fPan.fbdMap(f,4) && fPan.fwdMap(f,4) && fPan.fbdMap(f,5) && fPan.fwdMap(f,5))
            fPan.U(f,2) = 0.5*(fb+ff);
        else
            fPan.U(f,2) = fb+ff;
    }
    // Freestream component
    for (int i = 0; i < fPan.nE; ++i) {
        fPan.U.row(fPan.eIdx(i)) += vInf.transpose();
    }

    //// Thermodynamic variables
    for (int i = 0; i < fPan.nE; ++i) {
        int f = fPan.eIdx(i);
        // Speed of sound
        fPan.a(f) = sqrt(
                1/(Minf * Minf) + (GAMMA - 1) / 2 - (GAMMA - 1) / 2 * fPan.U.row(f).dot(fPan.U.row(f)));
        // Mach number
        fPan.M(f) = fPan.U.row(f).norm() / fPan.a(f);
        // Density
        fPan.rho(f) = pow(
                1 + (GAMMA - 1) / 2 * Minf * Minf * (1 - fPan.U.row(f).dot(fPan.U.row(f))),
                1 / (GAMMA - 1));
    }
}

max_stars_repo_name: acrovato/aero

max_issues_repo_name: acrovato/aero

max_forks_repo_name: acrovato/aero


text:
/*    Copyright (c) 2010-2019, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN

#include <limits>
#include <string>
#include <thread>

#include <boost/make_shared.hpp>
#include <boost/test/unit_test.hpp>

#include "tudat/simulation/simulation.h"

namespace tudat
{
namespace unit_tests
{

BOOST_AUTO_TEST_SUITE( test_gauss_propagator )

// Test Gauss propagator for point mass central body.
BOOST_AUTO_TEST_CASE( testGaussPopagatorForPointMassCentralBodies )
{
    for( int propagatorType = 0; propagatorType < 2; propagatorType++ )
    {
        // Test simulation for different central body cases
        //    for( unsigned int simulationCase = 1; simulationCase < 2; simulationCase++ )
        //    {
        //Using declarations.
        using namespace tudat::interpolators;
        using namespace tudat::numerical_integrators;
        using namespace tudat::spice_interface;
        using namespace tudat::simulation_setup;
        using namespace tudat::basic_astrodynamics;
        using namespace tudat::orbital_element_conversions;
        using namespace tudat::propagators;

        //Load spice kernels.
        spice_interface::loadStandardSpiceKernels( );

        // Define bodies in simulation.
        unsigned int totalNumberOfBodies = 7;
        std::vector< std::string > bodyNames;
        bodyNames.resize( totalNumberOfBodies );
        bodyNames[ 0 ] = "Earth";
        bodyNames[ 1 ] = "Mars";
        bodyNames[ 2 ] = "Sun";
        bodyNames[ 3 ] = "Venus";
        bodyNames[ 4 ] = "Moon";
        bodyNames[ 5 ] = "Mercury";
        bodyNames[ 6 ] = "Jupiter";

        double initialEphemerisTime = 1.0E7;
        double finalEphemerisTime = 2.0E7;
        double maximumTimeStep = 250.0;
        double buffer = 5.0 * maximumTimeStep;

        // Create bodies needed in simulation
        BodyListSettings bodySettings =
                getDefaultBodySettings( bodyNames, initialEphemerisTime - buffer , finalEphemerisTime + buffer,
                                         "SSB", "J2000" );

        SystemOfBodies bodies = createSystemOfBodies( bodySettings );

        // Set accelerations between bodies that are to be taken into account.
        SelectedAccelerationMap accelerationMap;
        std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfEarth;
        accelerationsOfEarth[ "Sun" ].push_back( std::make_shared< AccelerationSettings >( point_mass_gravity ) );
        accelerationsOfEarth[ "Moon" ].push_back( std::make_shared< AccelerationSettings >( point_mass_gravity ) );
        accelerationsOfEarth[ "Jupiter" ].push_back( std::make_shared< AccelerationSettings >( point_mass_gravity ) );
        accelerationMap[ "Earth" ] = accelerationsOfEarth;

        std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfMars;
        accelerationsOfMars[ "Sun" ].push_back( std::make_shared< AccelerationSettings >( point_mass_gravity ) );
        accelerationsOfMars[ "Venus" ].push_back( std::make_shared< AccelerationSettings >( point_mass_gravity ) );
        accelerationsOfMars[ "Jupiter" ].push_back( std::make_shared< AccelerationSettings >( point_mass_gravity ) );
        accelerationMap[ "Mars" ] = accelerationsOfMars;

        std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfVenus;
        accelerationsOfVenus[ "Sun" ].push_back( std::make_shared< AccelerationSettings >( point_mass_gravity ) );
        accelerationsOfVenus[ "Mars" ].push_back( std::make_shared< AccelerationSettings >( point_mass_gravity ) );
        accelerationsOfVenus[ "Jupiter" ].push_back( std::make_shared< AccelerationSettings >( point_mass_gravity ) );
        accelerationMap[ "Venus" ] = accelerationsOfVenus;

        // Propagate Earth, Mars and Moon
        std::vector< std::string > bodiesToPropagate;
        bodiesToPropagate.push_back( "Earth" );
        bodiesToPropagate.push_back( "Mars" );
        bodiesToPropagate.push_back( "Venus" );

        unsigned int numberOfNumericalBodies = bodiesToPropagate.size( );

        // Define central bodies: all Sun for simulationCase = 0, Earth and Mars: Sun, Moon: Earth for simulationCase = 1
        std::vector< std::string > centralBodies;
        std::map< std::string, std::string > centralBodyMap;
        centralBodies.resize( numberOfNumericalBodies );
        for( unsigned int i = 0; i < numberOfNumericalBodies; i++ )
        {
            centralBodies[ i ] = "Sun";
            //        if( i == 2 )
            //        {
            //            centralBodies[ i ] = "Earth";
            //        }
            //        else
            {
                centralBodies[ i ] = "Sun";
            }
            centralBodyMap[ bodiesToPropagate[ i ] ] = centralBodies[ i ];
        }

        // Get initial states for bodies.
        Eigen::VectorXd systemInitialState = Eigen::VectorXd( bodiesToPropagate.size( ) * 6 );
        for( unsigned int i = 0; i < numberOfNumericalBodies ; i++ )
        {
            systemInitialState.segment( i * 6 , 6 ) =
                    bodies.at( bodiesToPropagate[ i ] )->getStateInBaseFrameFromEphemeris( initialEphemerisTime ) -
                    bodies.at( centralBodies[ i ] )->getStateInBaseFrameFromEphemeris( initialEphemerisTime );
        }

        // Avoid degradation of performance in Kepler element conversions
        Eigen::Vector6d earthInitialKeplerElements =
                convertCartesianToKeplerianElements(
                    Eigen::Vector6d( systemInitialState.segment( 0, 6 ) ), bodies.at( "Earth" )->getGravityFieldModel( )->getGravitationalParameter( ) +
                    bodies.at( "Sun" )->getGravityFieldModel( )->getGravitationalParameter( ) );

        earthInitialKeplerElements( 2 ) = mathematical_constants::PI - earthInitialKeplerElements( 2 );
        earthInitialKeplerElements( 4 ) = earthInitialKeplerElements( 4 ) - 0.4;
        systemInitialState.segment( 0, 6 ) =
                convertKeplerianToCartesianElements(
                    earthInitialKeplerElements, bodies.at( "Earth" )->getGravityFieldModel( )->getGravitationalParameter( ) +
                    bodies.at( "Sun" )->getGravityFieldModel( )->getGravitationalParameter( ) );

        // Create acceleratiuon models.
        AccelerationMap accelerationModelMap = createAccelerationModelsMap(
                    bodies, accelerationMap, centralBodyMap );

        // Create integrator settings.
        std::shared_ptr< IntegratorSettings< > > integratorSettings =
                std::make_shared< IntegratorSettings< > >
                ( rungeKutta4,
                  initialEphemerisTime, 250.0 );

        // Create propagation settings (Cowell)
        std::shared_ptr< TranslationalStatePropagatorSettings< double > > propagatorSettings =
                std::make_shared< TranslationalStatePropagatorSettings< double > >
                ( centralBodies, accelerationModelMap, bodiesToPropagate, systemInitialState, finalEphemerisTime );

        // Propagate orbit with Cowell method
        SingleArcDynamicsSimulator< double > dynamicsSimulator2(
                    bodies, integratorSettings, propagatorSettings, true, false, true );

        // Define ephemeris interrogation settings.
        double initialTestTime = initialEphemerisTime;
        double finalTestTime = finalEphemerisTime;
        double testTimeStep = 1000.0;

        // Get resutls of Cowell integration at given times.
        double currentTestTime = initialTestTime;
        std::map< double, Eigen::Matrix< double, 18, 1 > > cowellIntegrationResults;
        bodies.at( "Earth" )->recomputeStateOnNextCall( );
        bodies.at( "Mars" )->recomputeStateOnNextCall( );
        bodies.at( "Venus" )->recomputeStateOnNextCall( );

        while( currentTestTime < finalTestTime )
        {
            cowellIntegrationResults[ currentTestTime ].segment( 0, 6 ) =
                    bodies.at( "Earth" )->getStateInBaseFrameFromEphemeris( currentTestTime );
            cowellIntegrationResults[ currentTestTime ].segment( 6, 6 ) =
                    bodies.at( "Mars" )->getStateInBaseFrameFromEphemeris( currentTestTime );
            cowellIntegrationResults[ currentTestTime ].segment( 12, 6 ) =
                    bodies.at( "Venus" )->getStateInBaseFrameFromEphemeris( currentTestTime );

            currentTestTime += testTimeStep;
        }

        TranslationalPropagatorType translationalPropagatorType = undefined_translational_propagator;
        if( propagatorType == 0 )
        {
            translationalPropagatorType = gauss_modified_equinoctial;
        }
        else
        {
            translationalPropagatorType = gauss_keplerian;
        }

        // Create propagation settings (Gauss)
        propagatorSettings = std::make_shared< TranslationalStatePropagatorSettings< double > >
                ( centralBodies, accelerationModelMap, bodiesToPropagate, systemInitialState, finalEphemerisTime, translationalPropagatorType );

        // Propagate orbit with Gauss method
        SingleArcDynamicsSimulator< double > dynamicsSimulator(
                    bodies, integratorSettings, propagatorSettings, true, false, true );

        // Get resutls of Gauss integration at given times.
        currentTestTime = initialTestTime;
        std::map< double, Eigen::Matrix< double, 18, 1 > > gaussIntegrationResults;
        while( currentTestTime < finalTestTime )
        {
            gaussIntegrationResults[ currentTestTime ].segment( 0, 6 ) =
                    bodies.at( "Earth" )->getStateInBaseFrameFromEphemeris( currentTestTime );
            gaussIntegrationResults[ currentTestTime ].segment( 6, 6 ) =
                    bodies.at( "Mars" )->getStateInBaseFrameFromEphemeris( currentTestTime );
            gaussIntegrationResults[ currentTestTime ].segment( 12, 6 ) =
                    bodies.at( "Venus" )->getStateInBaseFrameFromEphemeris( currentTestTime );
            currentTestTime += testTimeStep;
        }

        // Compare results of Cowell and Gauss propagations
        std::map< double, Eigen::Matrix< double, 18, 1 > >::iterator gaussIterator = gaussIntegrationResults.begin( );
        Eigen::Vector6d currentCartesianState, currentKeplerianStateDifference;
        std::map< double, Eigen::Matrix< double, 18, 1 > >::iterator cowellIterator = cowellIntegrationResults.begin( );
        for( unsigned int i = 0; i < gaussIntegrationResults.size( ); i++ )
        {

            for( int j= 0; j< 3; j++ )
            {
                BOOST_CHECK_SMALL( ( gaussIterator->second - cowellIterator->second ).segment( j, 1 )( 0 ), 0.05 );
            }

            for( int j = 6; j < 9; j++ )
            {
                BOOST_CHECK_SMALL( ( gaussIterator->second - cowellIterator->second ).segment( j, 1 )( 0 ), 0.05 );
            }

            for( int j = 12; j < 15; j++ )
            {
                BOOST_CHECK_SMALL( ( gaussIterator->second - cowellIterator->second ).segment( j, 1 )( 0 ), 0.075 );
            }

            for( int j = 3; j < 6; j++ )
            {
                BOOST_CHECK_SMALL( ( gaussIterator->second - cowellIterator->second ).segment( j, 1 )( 0 ), 1.0E-8 );
            }

            for( int j = 9; j < 12; j++ )
            {
                BOOST_CHECK_SMALL( ( gaussIterator->second - cowellIterator->second ).segment( j, 1 )( 0 ), 1.0E-8 );

            }

            for( int j = 15; j < 18; j++ )
            {
                BOOST_CHECK_SMALL( ( gaussIterator->second - cowellIterator->second ).segment( j, 1 )( 0 ), 1.0E-6 );
            }
            gaussIterator++;
            cowellIterator++;
        }
    }
}

// Test Gauss propagator for point mass, and spherical harmonics central body.
BOOST_AUTO_TEST_CASE( testGaussPopagatorForSphericalHarmonicCentralBodies )
{
    using namespace tudat;
    using namespace simulation_setup;
    using namespace propagators;
    using namespace numerical_integrators;
    using namespace orbital_element_conversions;
    using namespace basic_mathematics;
    using namespace gravitation;
    using namespace numerical_integrators;

    // Load Spice kernels.
    spice_interface::loadStandardSpiceKernels( );

    // Set simulation time settings.
    const double simulationStartEpoch = 0.0;
    const double simulationEndEpoch = tudat::physical_constants::JULIAN_DAY;

    for( int propagatorType = 0; propagatorType < 2; propagatorType++ )
    {
        TranslationalPropagatorType translationalPropagatorType;
        if( propagatorType == 0 )
        {
            translationalPropagatorType = gauss_modified_equinoctial;
        }
        else
        {
            translationalPropagatorType = gauss_keplerian;
        }
        for( unsigned int simulationCase = 0; simulationCase < 4; simulationCase++ )
        {
            std::cout << "Simulation case : " << simulationCase << std::endl << std::endl;

            // Define body settings for simulation.
            std::vector< std::string > bodiesToCreate;
            bodiesToCreate.push_back( "Sun" );
            bodiesToCreate.push_back( "Earth" );
            bodiesToCreate.push_back( "Moon" );
            bodiesToCreate.push_back( "Mars" );
            bodiesToCreate.push_back( "Venus" );

            // Create body objects.
            BodyListSettings bodySettings =
                    getDefaultBodySettings( bodiesToCreate, simulationStartEpoch - 300.0, simulationEndEpoch + 300.0,
                                            "SSB", "J2000" );
            for( unsigned int i = 0; i < bodiesToCreate.size( ); i++ )
            {
                bodySettings.at( bodiesToCreate.at( i ) )->ephemerisSettings->resetFrameOrientation( "J2000" );
                bodySettings.at( bodiesToCreate.at( i ) )->rotationModelSettings->resetOriginalFrame( "J2000" );
            }
            SystemOfBodies bodies = createSystemOfBodies( bodySettings );

            // Create spacecraft object.
            bodies.createEmptyBody( "Vehicle" );
            bodies.at( "Vehicle" )->setConstantBodyMass( 400.0 );
            std::shared_ptr< RadiationPressureInterfaceSettings > vehicleRadiationPressureSettings =
                    std::make_shared< CannonBallRadiationPressureInterfaceSettings >(
                        "Sun", 4.0, 1.2, std::vector< std::string >{ "Earth" } );
            bodies.at( "Vehicle" )->setRadiationPressureInterface(
                        "Sun", createRadiationPressureInterface(
                            vehicleRadiationPressureSettings, "Vehicle", bodies ) );

            // Define propagator settings variables.
            SelectedAccelerationMap accelerationMap;
            std::vector< std::string > bodiesToPropagate;
            std::vector< std::string > centralBodies;

            // Define propagation settings.
            std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationsOfVehicle;

            // Use only central gravity for Earth
            if( simulationCase < 2 )
            {
                accelerationsOfVehicle[ "Earth" ].push_back( std::make_shared< AccelerationSettings >(
                                                                 basic_astrodynamics::point_mass_gravity ) );
            }
            // Use spherical harmonics for Earth
            else
            {
                accelerationsOfVehicle[ "Earth" ].push_back(
                            std::make_shared< SphericalHarmonicAccelerationSettings >( 5, 5 ) );

            }

            // Use perturbations other than Earth gravity
            if( simulationCase % 2 == 0 )
            {
                accelerationsOfVehicle[ "Sun" ].push_back( std::make_shared< AccelerationSettings >(
                                                               basic_astrodynamics::point_mass_gravity ) );
                accelerationsOfVehicle[ "Moon" ].push_back( std::make_shared< AccelerationSettings >(
                                                                basic_astrodynamics::point_mass_gravity ) );
                accelerationsOfVehicle[ "Mars" ].push_back( std::make_shared< AccelerationSettings >(
                                                                basic_astrodynamics::point_mass_gravity ) );
                accelerationsOfVehicle[ "Venus" ].push_back( std::make_shared< AccelerationSettings >(
                                                                 basic_astrodynamics::point_mass_gravity ) );
                accelerationsOfVehicle[ "Sun" ].push_back( std::make_shared< AccelerationSettings >(
                                                               basic_astrodynamics::cannon_ball_radiation_pressure ) );
            }
            accelerationMap[ "Vehicle" ] = accelerationsOfVehicle;
            bodiesToPropagate.push_back( "Vehicle" );
            centralBodies.push_back( "Earth" );
            basic_astrodynamics::AccelerationMap accelerationModelMap = createAccelerationModelsMap(
                        bodies, accelerationMap, bodiesToPropagate, centralBodies );

            // Set Keplerian elements for Vehicle.
            Eigen::Vector6d vehicleInitialStateInKeplerianElements;
            vehicleInitialStateInKeplerianElements( semiMajorAxisIndex ) = 8000.0E3;
            vehicleInitialStateInKeplerianElements( eccentricityIndex ) = 0.1;
            vehicleInitialStateInKeplerianElements( inclinationIndex ) = unit_conversions::convertDegreesToRadians( 85.3 );
            vehicleInitialStateInKeplerianElements( argumentOfPeriapsisIndex )
                    = unit_conversions::convertDegreesToRadians( 235.7 );
            vehicleInitialStateInKeplerianElements( longitudeOfAscendingNodeIndex )
                    = unit_conversions::convertDegreesToRadians( 23.4 );
            vehicleInitialStateInKeplerianElements( trueAnomalyIndex ) = unit_conversions::convertDegreesToRadians( 139.87 );

            double earthGravitationalParameter = bodies.at( "Earth" )->getGravityFieldModel( )->getGravitationalParameter( );
            const Eigen::Vector6d vehicleInitialState = convertKeplerianToCartesianElements(
                        vehicleInitialStateInKeplerianElements, earthGravitationalParameter );

            // Define propagator settings (Cowell)
            std::shared_ptr< TranslationalStatePropagatorSettings< double > > propagatorSettings =
                    std::make_shared< TranslationalStatePropagatorSettings< double > >
                    ( centralBodies, accelerationModelMap, bodiesToPropagate, vehicleInitialState, simulationEndEpoch );

            // Define integrator settings.
            const double fixedStepSize = 5.0;
            std::shared_ptr< IntegratorSettings< > > integratorSettings =
                    std::make_shared< IntegratorSettings< > >
                    ( rungeKutta4, 0.0, fixedStepSize );

            // Propagate orbit with Cowell method
            SingleArcDynamicsSimulator< double > dynamicsSimulator2(
                        bodies, integratorSettings, propagatorSettings, true, false, true );

            // Define ephemeris interrogation settings.
            double initialTestTime = simulationStartEpoch;
            double finalTestTime = simulationEndEpoch - 10.0 * fixedStepSize;
            double testTimeStep = 1.0E4;

            // Get resutls of Cowell integration at given times.
            double currentTestTime = initialTestTime;
            std::map< double, Eigen::Matrix< double, 6, 1 > > cowellIntegrationResults;
            while( currentTestTime < finalTestTime )
            {
                cowellIntegrationResults[ currentTestTime ].segment( 0, 6 ) =
                        bodies.at( "Vehicle" )->getEphemeris( )->getCartesianState( currentTestTime );

                currentTestTime += testTimeStep;
            }

            // Create propagation settings (Gauss)
            propagatorSettings = std::make_shared< TranslationalStatePropagatorSettings< double > >
                    ( centralBodies, accelerationModelMap, bodiesToPropagate, vehicleInitialState, simulationEndEpoch, translationalPropagatorType );

            // Propagate orbit with Gauss method
            SingleArcDynamicsSimulator< double > dynamicsSimulator(
                        bodies, integratorSettings, propagatorSettings, true, false, true );

            // Get resutls of Gauss integration at given times.
            currentTestTime = initialTestTime;
            std::map< double, Eigen::Matrix< double, 6, 1 > > gaussIntegrationResults;
            while( currentTestTime < finalTestTime )
            {
                gaussIntegrationResults[ currentTestTime ].segment( 0, 6 ) =
                        bodies.at( "Vehicle" )->getEphemeris( )->getCartesianState( currentTestTime );
                currentTestTime += testTimeStep;
            }

            // Compare results of Cowell and Gauss propagations
            std::map< double, Eigen::Matrix< double, 6, 1 > >::iterator gaussIterator = gaussIntegrationResults.begin( );
            std::map< double, Eigen::Matrix< double, 6, 1 > >::iterator cowellIterator = cowellIntegrationResults.begin( );
            for( unsigned int i = 0; i < gaussIntegrationResults.size( ); i++ )
            {
                for( int j= 0; j< 3; j++ )
                {
                    BOOST_CHECK_SMALL( ( gaussIterator->second - cowellIterator->second )( j ), 0.02 );
                }

                for( int j = 3; j < 6; j++ )
                {
                    BOOST_CHECK_SMALL( ( gaussIterator->second - cowellIterator->second )( j ), 1.0E-5 );

                }
                gaussIterator++;
                cowellIterator++;
            }
        }
    }
}
BOOST_AUTO_TEST_SUITE_END( )

}

}


text:
/**
 * Copyright (C) 2016 Turi
 * All rights reserved.
 *
 * This software may be modified and distributed under the terms
 * of the BSD license. See the LICENSE file for details.
 */
#include <fstream>
#include <fileio/fs_utils.hpp>
#include <fileio/temp_files.hpp>
#include <fileio/fileio_constants.hpp>
#include <process/process_util.hpp>
#include <boost/filesystem.hpp>

#if BOOST_VERSION <= 105600 && defined(_WIN32)
#define BOOST_INTERPROCESS_WIN32_PRIMITIVES_HPP
#include "boost_alt_winapi.h"
#endif
#include <boost/interprocess/shared_memory_object.hpp>
namespace graphlab {
namespace shmipc {

namespace fs = boost::filesystem;

struct raii_deleter {
  raii_deleter(const std::string& shmname,
               const std::string& tagfile)
      :m_shmname(shmname), m_tagfilename(tagfile) {
  }
  ~raii_deleter() {
    // failed deletion is ok
    try {
      boost::interprocess::shared_memory_object::remove(m_shmname.c_str());
    } catch (...) { }

    // failed deletion is ok
    try {
      fileio::delete_path(m_tagfilename);
    } catch (...) { }
  }
  std::string m_shmname;
  std::string m_tagfilename;
};

/**
 * Return [TMPDIR]/glshm_[userid]
 */
static fs::path shared_memory_tagfile_path() {
  auto temp = fileio::get_system_temp_directory();
  fs::path path = temp;
  path /= "glshm_" + get_system_user_name();
  if (!fs::is_directory(path)) fs::create_directories(path);
  return path;
}

void garbage_collect() {
  auto taglist =
      fileio::get_directory_listing(shared_memory_tagfile_path().generic_string());

  // enumerate all files in [TMPDIR]/glshm_[userid]
  // Each file contains a pid in it.
  for (auto& file: taglist) {
    auto shmname = fileio::get_filename(file.first);
    std::ifstream fin(file.first.c_str());
    size_t pid = 0;
    fin >> pid;
    if (pid != 0 && is_process_running(pid) == false) {
      // use the raii deleter's destructor to delete the shared memory and the
      // tag file
      raii_deleter(shmname, file.first);
    }
  }
}

std::shared_ptr<raii_deleter>
register_shared_memory_name(std::string m_name) {
  garbage_collect();

  // tag file is located as [system temp directory]/glshm_[userid]/[shmname]
  // tag file contains a PID in it.
  auto tagfile = (shared_memory_tagfile_path() / m_name).generic_string();
  std::ofstream fout(tagfile);
  fout << get_my_pid();
  fout.close();
  return std::make_shared<raii_deleter>(m_name, tagfile);
}

} // shmipc
} // graphlab

max_stars_repo_name: venkattgg/venkey

max_issues_repo_name: venkattgg/venkey

max_forks_repo_name: venkattgg/venkey


text:
// Copyright (c) 2014, Guilherme Balena Versiani <guibv@yahoo.com>
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef MESSAGE_ATTRIBUTE_DETAIL_ENDPOINT_HPP
#define MESSAGE_ATTRIBUTE_DETAIL_ENDPOINT_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <message/detail/config.hpp>

#include <boost/asio/ip/address.hpp>

#include <message/detail/push_options.hpp>

namespace stun {
namespace detail {

struct endpoint {
#pragma pack(push, 1)
  struct impl_type {
    uint8_t unused;
    uint8_t family; // IPv4 = 1, IPv6 = 2
    uint16_t port;
    union {
      uint8_t v4[4];
      uint8_t v6[16];
    } addr;
  };
#pragma pack(pop)
  typedef boost::asio::ip::address address_type;

  class decoder {
   public:
    MESSAGE_DECL decoder(const uint8_t* data, size_t data_len);
    MESSAGE_DECL bool valid() const;
    MESSAGE_DECL address_type address() const;
    MESSAGE_DECL uint16_t port() const;
   private:
    const impl_type* data_;
    size_t data_len_;
  };

  class encoder {
   public:
    MESSAGE_DECL encoder(uint8_t* data);
    MESSAGE_DECL void set_address(const address_type &address);
    MESSAGE_DECL void set_port(uint16_t port);
   private:
    impl_type* data_;
  };

  MESSAGE_DECL static size_t size_of(uint8_t family);
  MESSAGE_DECL static size_t size_of(const address_type &address);
};

} // namespace detail
} // namespace stun

#include <message/detail/pop_options.hpp>

#if defined(MESSAGE_HEADER_ONLY)
#include <message/detail/impl/endpoint.ipp>
#endif // defined(MESSAGE_HEADER_ONLY)

#endif // MESSAGE_ATTRIBUTE_DETAIL_ENDPOINT_HPP

ext: hpp

max_stars_repo_name: guibv/turnover

max_issues_repo_name: guibv/turnover

max_forks_repo_name: guibv/turnover


text:
#include <sstream>
#include <iostream>
#include <vector>
#include <limits>

#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>

#include "filelib.h"
#include "stringlib.h"
#include "weights.h"
#include "hg_io.h"
#include "kbest.h"
#include "viterbi.h"
#include "ns.h"
#include "ns_docscorer.h"
#include "candidate_set.h"

using namespace std;
namespace po = boost::program_options;

void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
  po::options_description opts("Configuration options");
  opts.add_options()
        ("reference,r",po::value<vector<string> >(), "[REQD] Reference translation (tokenized text)")
        ("weights,w",po::value<string>(), "[REQD] Weights files from current iterations")
        ("input,i",po::value<string>()->default_value("-"), "Input file to map (- is STDIN)")
        ("evaluation_metric,m",po::value<string>()->default_value("IBM_BLEU"), "Evaluation metric (ibm_bleu, koehn_bleu, nist_bleu, ter, meteor, etc.)")
        ("kbest_repository,R",po::value<string>(), "Accumulate k-best lists from previous iterations (parameter is path to repository)")
        ("kbest_size,k",po::value<unsigned>()->default_value(500u), "Top k-hypotheses to extract")
        ("cccp_iterations,I", po::value<unsigned>()->default_value(10u), "CCCP iterations (T')")
        ("ssd_iterations,J", po::value<unsigned>()->default_value(5u), "Stochastic subgradient iterations (T'')")
        ("eta", po::value<double>()->default_value(1e-4), "Step size")
        ("regularization_strength,C", po::value<double>()->default_value(1.0), "L2 regularization strength")
        ("alpha,a", po::value<double>()->default_value(10.0), "Cost scale (alpha); alpha * [1-metric(y,y')]")
        ("help,h", "Help");
  po::options_description dcmdline_options;
  dcmdline_options.add(opts);
  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
  bool flag = false;
  if (!conf->count("reference")) {
    cerr << "Please specify one or more references using -r <REF.TXT>\n";
    flag = true;
  }
  if (!conf->count("weights")) {
    cerr << "Please specify weights using -w <WEIGHTS.TXT>\n";
    flag = true;
  }
  if (flag || conf->count("help")) {
    cerr << dcmdline_options << endl;
    exit(1);
  }
}

struct GainFunction {
  explicit GainFunction(const EvaluationMetric* m) : metric(m) {}
  float operator()(const SufficientStats& eval_feats) const {
    float g = metric->ComputeScore(eval_feats);
    if (!metric->IsErrorMetric()) g = 1 - g;
    return g;
  }
  const EvaluationMetric* metric;
};

template <typename GainFunc>
void CostAugmentedSearch(const GainFunc& gain,
                         const training::CandidateSet& cs,
                         const SparseVector<double>& w,
                         double alpha,
                         SparseVector<double>* fmap) {
  unsigned best_i = 0;
  double best = -numeric_limits<double>::infinity();
  for (unsigned i = 0; i < cs.size(); ++i) {
    double s = cs[i].fmap.dot(w) + alpha * gain(cs[i].eval_feats);
    if (s > best) {
      best = s;
      best_i = i;
    }
  }
  *fmap = cs[best_i].fmap;
}

// runs lines 4--15 of rampion algorithm
int main(int argc, char** argv) {
  po::variables_map conf;
  InitCommandLine(argc, argv, &conf);
  const string evaluation_metric = conf["evaluation_metric"].as<string>();

  EvaluationMetric* metric = EvaluationMetric::Instance(evaluation_metric);
  DocumentScorer ds(metric, conf["reference"].as<vector<string> >());
  cerr << "Loaded " << ds.size() << " references for scoring with " << evaluation_metric << endl;
  double goodsign = -1;
  double badsign = -goodsign;

  Hypergraph hg;
  string last_file;
  ReadFile in_read(conf["input"].as<string>());
  string kbest_repo;
  if (conf.count("kbest_repository")) {
    kbest_repo = conf["kbest_repository"].as<string>();
    MkDirP(kbest_repo);
  }
  istream &in=*in_read.stream();
  const unsigned kbest_size = conf["kbest_size"].as<unsigned>();
  const unsigned tp = conf["cccp_iterations"].as<unsigned>();
  const unsigned tpp = conf["ssd_iterations"].as<unsigned>();
  const double eta = conf["eta"].as<double>();
  const double reg = conf["regularization_strength"].as<double>();
  const double alpha = conf["alpha"].as<double>();
  SparseVector<weight_t> weights;
  {
    vector<weight_t> vweights;
    const string weightsf = conf["weights"].as<string>();
    Weights::InitFromFile(weightsf, &vweights);
    Weights::InitSparseVector(vweights, &weights);
  }
  string line, file;
  vector<training::CandidateSet> kis;
  cerr << "Loading hypergraphs...\n";
  while(getline(in, line)) {
    istringstream is(line);
    int sent_id;
    kis.resize(kis.size() + 1);
    training::CandidateSet& curkbest = kis.back();
    string kbest_file;
    if (kbest_repo.size()) {
      ostringstream os;
      os << kbest_repo << "/kbest." << sent_id << ".txt.gz";
      kbest_file = os.str();
      if (FileExists(kbest_file))
        curkbest.ReadFromFile(kbest_file);
    }
    is >> file >> sent_id;
    ReadFile rf(file);
    if (kis.size() % 5 == 0) { cerr << '.'; }
    if (kis.size() % 200 == 0) { cerr << " [" << kis.size() << "]\n"; }
    HypergraphIO::ReadFromJSON(rf.stream(), &hg);
    hg.Reweight(weights);
    curkbest.AddKBestCandidates(hg, kbest_size, ds[sent_id]);
    if (kbest_file.size())
      curkbest.WriteToFile(kbest_file);
  }
  cerr << "\nHypergraphs loaded.\n";

  vector<SparseVector<weight_t> > goals(kis.size());  // f(x_i,y+,h+)
  SparseVector<weight_t> fear;  // f(x,y-,h-)
  const GainFunction gain(metric);
  for (unsigned iterp = 1; iterp <= tp; ++iterp) {
    cerr << "CCCP Iteration " << iterp << endl;
    for (unsigned i = 0; i < goals.size(); ++i)
      CostAugmentedSearch(gain, kis[i], weights, goodsign * alpha, &goals[i]);
    for (unsigned iterpp = 1; iterpp <= tpp; ++iterpp) {
      cerr << "  SSD Iteration " << iterpp << endl;
      for (unsigned i = 0; i < goals.size(); ++i) {
        CostAugmentedSearch(gain, kis[i], weights, badsign * alpha, &fear);
        weights -= weights * (eta * reg / goals.size());
        weights += (goals[i] - fear) * eta;
      }
    }
  }
  vector<weight_t> w;
  weights.init_vector(&w);
  Weights::WriteToFile("-", w);
  return 0;
}

ext: cc

max_stars_repo_name: kho/cdec

max_issues_repo_name: kho/cdec

max_forks_repo_name: kho/cdec


text:
//  Copyright (c) 2006, Giovanni P. Deretta
//
//  This code may be used under either of the following two licences:
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
//  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE. OF SUCH DAMAGE.
//
//  Or:
//
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_COROUTINE_CONTEXT_IMPL_HPP_20060810
#define BOOST_COROUTINE_CONTEXT_IMPL_HPP_20060810
/*
 * Currently asio can, in some cases. call copy constructors and
 * operator= from different threads, even if in the
 * one-thread-per-service model. (i.e. from the resolver thread)
 * This will be corrected in future versions, but for now
 * we will play it safe and use an atomic count. The overhead shouldn't
 * be big.
 */
#define BOOST_COROUTINE_USE_ATOMIC_COUNT

#ifdef BOOST_COROUTINE_USE_ATOMIC_COUNT
#  include <boost/detail/atomic_count.hpp>
#endif
#include <cstddef>
#include <algorithm> //for swap
#include <boost/coroutine/detail/swap_context.hpp> //for swap hints
#include <boost/intrusive_ptr.hpp>
#include <boost/coroutine/exception.hpp>
#include <boost/coroutine/detail/noreturn.hpp>
namespace boost { namespace coroutines { namespace detail {

  const std::ptrdiff_t default_stack_size = -1;

  template<typename ContextImpl>
  class context_base : public ContextImpl {
  public:

    typedef ContextImpl context_impl;
    typedef context_base<context_impl> type;
    typedef boost::intrusive_ptr<type> pointer;
    typedef void deleter_type(const type*);

    template<typename Derived>
	context_base(Derived& derived,
		     std::ptrdiff_t stack_size) :
      context_impl(derived, stack_size),
      m_counter(0),
      m_deleter(&deleter<Derived>),
      m_state(ctx_ready),
      m_exit_state(ctx_exit_not_requested),
      m_exit_status(ctx_not_exited),
      m_wait_counter(0),
      m_operation_counter(0),
      m_type_info(0) {}

    friend
    void intrusive_ptr_add_ref(type * ctx) {
      ctx->acquire();
    }

    friend
    void intrusive_ptr_release(type * ctx) {
      ctx->release();
    }

    bool unique() const {
      return count() == 1;
    }

    std::size_t count() const {
      return m_counter;
    }

    void acquire() const {
      ++m_counter;
    }

    void release() const {
      BOOST_ASSERT(m_counter);
      if(--m_counter == 0) {
	m_deleter(this);
      }
    }

    void count_down() throw() {
      BOOST_ASSERT(m_operation_counter) ;
      --m_operation_counter;
    }

    void count_up() throw() {
      ++m_operation_counter;
    }

    // return true if there are operations pending.
    int pending() const {
      return m_operation_counter;
    }

    /*
     * A signal may occur only when a context is
     * not running (is delivered sinchrononously).
     * This means that state MUST NOT be busy.
     * It may be ready or waiting.
     * returns 'ready()'.
     * Nothrow.
     */
    bool signal () throw() {
      BOOST_ASSERT(!running() && !exited());
      BOOST_ASSERT(m_wait_counter) ;

      --m_wait_counter;
      if(!m_wait_counter && m_state == ctx_waiting)
	m_state = ctx_ready;
      return ready();
    }

    /*
     * Wake up a waiting context.
     * Similar to invoke(), but *does not
     * throw* if the coroutine exited normally
     * or entered the wait state.
     * It *does throw* if the coroutine
     * exited abnormally.
     * Return: false if invoke() would have thrown,
     *         true otherwise.
     *
     */
    bool wake_up() {
      BOOST_ASSERT(ready());
      do_invoke();
      // TODO: could use a binary 'or' here to eliminate
      // shortcut evaluation (and a branch), but maybe the compiler is
      // smart enough to do it anyway as there are no side effects.
      if(m_exit_status || m_state == ctx_waiting) {
	if(m_state == ctx_waiting)
	  return false;
	if(m_exit_status == ctx_exited_return)
	  return true;
	if(m_exit_status == ctx_exited_abnormally) {
	std::type_info const * tinfo =0;
	std::swap(m_type_info, tinfo);
	throw abnormal_exit(tinfo?*tinfo: typeid(unknown_exception_tag));
	} else if(m_exit_status == ctx_exited_exit)
	  return false;
	else {
	  BOOST_ASSERT(0 && "unkonw exit status");
	}
      }
      return true;
    }
    /*
     * Returns true if the context is runnable.
     */
    bool ready() const {
      return m_state == ctx_ready;
    }

    /*
     * Returns true if the context is in wait
     * state.
     */
    bool waiting() const {
      return m_state == ctx_waiting;
    }

    bool running() const {
      return m_state == ctx_running;
    }

    bool exited() const {
      return m_state == ctx_exited;
    }

    // Resume coroutine.
    // Pre:  The coroutine must be ready.
    // Post: The coroutine relinquished control. It might be ready, waiting
    //       or exited.
    // Throws:- 'waiting' if the coroutine entered the wait state,
    //        - 'coroutine_exited' if the coroutine exited by an uncaught
    //          'exit_exception'.
    //        - 'abnormal_exit' if the coroutine was exited by another
    //          uncaught exception.
    // Note, it guarantees that the coroutine is resumed. Can throw only
    // on return.
    void invoke() {
      BOOST_ASSERT(ready());
      do_invoke();
      // TODO: could use a bynary or here to eliminate
      // shortcut evaluation (and a branch), but maybe the compiler is
      // smart enough to do it anyway as there are no side effects.
      if(m_exit_status || m_state == ctx_waiting) {
	if(m_state == ctx_waiting)
	  throw waiting();
	if(m_exit_status == ctx_exited_return)
	  return;
	if(m_exit_status == ctx_exited_abnormally) {
	std::type_info const * tinfo =0;
	std::swap(m_type_info, tinfo);
	throw abnormal_exit(tinfo?*tinfo: typeid(unknown_exception_tag));
	} else if(m_exit_status == ctx_exited_exit)
	  throw coroutine_exited();
      	else {
	  BOOST_ASSERT(0 && "unkonw exit status");
	}
      }
    }

    // Put coroutine in ready state and relinquish control
    // to caller until resumed again.
    // Pre:  Coroutine is running.
    //       Exit not pending.
    //       Operations not pending.
    // Post: Coroutine is running.
    // Throws: exit_exception, if exit is pending *after* it has been
    //         resumed.
    void yield() {
      BOOST_ASSERT(m_exit_state < ctx_exit_signaled); //prevent infinite loops
      BOOST_ASSERT(running());
      BOOST_ASSERT(!pending());

      m_state = ctx_ready;
      do_yield();

      BOOST_ASSERT(running());
      check_exit_state();
    }

    //
    // If n > 0, put the coroutine in the wait state
    // then relinquish control to caller.
    // If n = 0 do nothing.
    // The coroutine will remain in the wait state until
    // is signaled 'n' times.
    // Pre:  0 <= n < pending()
    //       Coroutine is running.
    //       Exit not pending.
    // Post: Coroutine is running.
    //       The coroutine has been signaled 'n' times unless an exit
    //        has been signaled.
    // Throws: exit_exception.
    // FIXME: currently there is a BIG problem. A coroutine cannot
    // be exited as long as there are futures pending.
    // The exit_exception would cause the future to be destroyed and
    // an assertion to be generated. Removing an assertion is not a
    // solution because we would leak the coroutine impl. The callback
    // bound to the future in fact hold a refrence to it. If the coroutine
    // is exited the callback cannot be called.
    void wait(int n) {
      BOOST_ASSERT(!(n<0));
      BOOST_ASSERT(m_exit_state < ctx_exit_signaled); //prevent infinite loop
      BOOST_ASSERT(running());
      BOOST_ASSERT(!(pending() < n));

      if(n == 0) return;
      m_wait_counter = n;

      m_state = ctx_waiting;
      do_yield();

      BOOST_ASSERT(m_state == ctx_running);
      check_exit_state();
      BOOST_ASSERT(m_wait_counter == 0);
    }

    // Throws: exit_exception.
    void yield_to(context_base& to) {
      BOOST_ASSERT(m_exit_state < ctx_exit_signaled); //prevent infinite loops
      BOOST_ASSERT(m_state == ctx_running);
      BOOST_ASSERT(to.ready());
      BOOST_ASSERT(!to.pending());

      std::swap(m_caller, to.m_caller);
      std::swap(m_state, to.m_state);
      swap_context(*this, to, detail::yield_to_hint());

      BOOST_ASSERT(m_state == ctx_running);
      check_exit_state();
    }

    // Cause this coroutine to exit.
    // Can only be called on a ready coroutine.
    // Cannot be called if there are pending operations.
    // It follws that cannot be called from 'this'.
    // Nothrow.
    void exit() throw(){
      BOOST_ASSERT(!pending());
      BOOST_ASSERT(ready()) ;
      if(m_exit_state < ctx_exit_pending)
	m_exit_state = ctx_exit_pending;
      do_invoke();
      BOOST_ASSERT(exited()); //at this point the coroutine MUST have exited.
    }

    // Always throw exit_exception.
    // Never returns from standard control flow.
    BOOST_COROUTINE_NORETURN(void exit_self()) {
      BOOST_ASSERT(!pending());
      BOOST_ASSERT(running());
      m_exit_state = ctx_exit_pending;
      throw exit_exception();
    }

    // Nothrow.
    ~context_base() throw() {
      BOOST_ASSERT(!running());
      try {
	if(!exited())
	  exit();
	BOOST_ASSERT(exited());
      } catch(...) {}
    }

  protected:
    // global coroutine state
    enum context_state {
      ctx_running,  // context running.
      ctx_ready,    // context at yield point.
      ctx_waiting,     // context waiting for events.
      ctx_exited    // context is finished.
    };

    // exit request state
    enum context_exit_state {
      ctx_exit_not_requested,  // exit not requested.
      ctx_exit_pending,   // exit requested.
      ctx_exit_signaled,  // exit request delivered.
    };

    // exit status
    enum context_exit_status {
      ctx_not_exited,
      ctx_exited_return,  // process exited by return.
      ctx_exited_exit,    // process exited by exit().
      ctx_exited_abnormally // process exited uncleanly.
    };

    // Cause the coroutine to exit if
    // a exit request is pending.
    // Throws: exit_exception if an exit request is pending.
    void check_exit_state() {
      BOOST_ASSERT(running());
      if(!m_exit_state) return;
      throw exit_exception();
    }

    // Nothrow.
    void do_return(context_exit_status status, std::type_info const* info) throw() {
      BOOST_ASSERT(status != ctx_not_exited);
      BOOST_ASSERT(m_state == ctx_running);
      m_type_info = info;
      m_state = ctx_exited;
      m_exit_status = status;
      do_yield();
    }

  private:

    // Nothrow.
    void do_yield() throw() {
      swap_context(*this, m_caller, detail::yield_hint());
    }

    // Nothrow.
    void do_invoke() throw (){
      BOOST_ASSERT(ready() || waiting());
      m_state = ctx_running;
      swap_context(m_caller, *this, detail::invoke_hint());
    }

    template<typename ActualCtx>
    static void deleter (const type* ctx){
      delete static_cast<ActualCtx*>(const_cast<type*>(ctx));
    }

    typedef typename context_impl::context_impl_base ctx_type;
    ctx_type m_caller;
    mutable
#ifndef BOOST_COROUTINE_USE_ATOMIC_COUNT
    std::size_t
#else
    boost::detail::atomic_count
#endif
    m_counter;
    deleter_type * m_deleter;
    context_state m_state;
    context_exit_state m_exit_state;
    context_exit_status m_exit_status;
    int m_wait_counter;
    int m_operation_counter;

    // This is used to generate a meaningful exception trace.
    std::type_info const* m_type_info;
  };

} } }
#endif

max_stars_repo_name: erikfrey/coroutine

max_issues_repo_name: erikfrey/coroutine

max_forks_repo_name: erikfrey/coroutine


text:
#ifndef __C_AUTOM8_DEVICE_MODEL_HPP__
#define __C_AUTOM8_DEVICE_MODEL_HPP__

#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <autom8/device/device_factory.hpp>
#include <sqlite3.h>
#include <sigslot/sigslot.h>

namespace autom8 {
    class device_model {
    public:
        device_model(device_factory_ptr factory);
        virtual ~device_model();

        sigslot::signal1<device_ptr> device_added;
        sigslot::signal1<database_id> device_removed;
        sigslot::signal1<database_id> device_updated;

        virtual device_ptr add(
            device_type type,
            const std::string& address,
            const std::string& label,
            const std::vector<std::string>& groups);

        virtual bool remove(device_ptr device);
        virtual bool remove(database_id id);

        virtual bool update(device_ptr device);
        virtual bool update(
            database_id id,
            device_type type,
            const std::string& address,
            const std::string& label,
            const std::vector<std::string>& groups);

        virtual int all_devices(device_list& target);
        virtual device_ptr find_by_address(const std::string& address);

    protected:
        void create_tables();
        sqlite3* connection() { return connection_; }
        device_factory_ptr factory() { return factory_; }

        virtual void on_device_added(device_ptr new_device);
        virtual void on_device_removed(database_id old_device_id);
        virtual void on_device_updated(database_id id);

        bool remove_groups(database_id id);
        void get_groups(database_id id, std::vector<std::string>& groups);
        bool set_groups(database_id id, const std::vector<std::string>& groups);

    private:
        device_factory_ptr factory_;
        std::string device_table_name_, groups_table_name_;
        sqlite3* connection_;
        boost::mutex connection_mutex_;
    };

    typedef boost::shared_ptr<device_model> device_model_ptr;
}

#endif


text:
#pragma once
#ifndef OPTIMIZE_HPP
#define OPTIMIZE_HPP

// c++ libraries
#include <iosfwd>
// eigen libraries
#include <Eigen/Dense>
//serialization
#include "src/mem/serialize.hpp"

namespace Opt{

#ifndef OPT_PRINT_FUNC
#define OPT_PRINT_FUNC 0
#endif

#ifndef OPT_PRINT_DATA
#define OPT_PRINT_DATA 0
#endif

//***************************************************
// optimization method
//***************************************************

class Algo{
public:
	enum Type{
		UNKNOWN=0,
		SGD=1,
		SDM=2,
		NAG=3,
		ADAGRAD=4,
		ADADELTA=5,
		RMSPROP=6,
		ADAM=7,
		NADAM=8,
		AMSGRAD=9,
		BFGS=10,
		RPROP=11,
		CG=12,
	};
	//constructor
	Algo():t_(Type::UNKNOWN){}
	Algo(Type t):t_(t){}
	//operators
	operator Type()const{return t_;}
	//member functions
	static Algo read(const char* str);
	static const char* name(const Algo& algo);
private:
	Type t_;
	//prevent automatic conversion for other built-in types
	//template<typename T> operator T() const;
};
std::ostream& operator<<(std::ostream& out, const Algo& algo);

//***************************************************
// stopping criterion
//***************************************************

class Stop{
public:
	enum Type{
		UNKNOWN=0,
		FABS=1,
		FREL=2,
		XABS=3,
		XREL=4
	};
	//constructor
	Stop():t_(Type::UNKNOWN){}
	Stop(Type t):t_(t){}
	//operators
	operator Type()const{return t_;}
	//member functions
	static Stop read(const char* str);
	static const char* name(const Stop& stop);
private:
	Type t_;
	//prevent automatic conversion for other built-in types
	//template<typename T> operator T() const;
};
std::ostream& operator<<(std::ostream& out, const Stop& stop);

//***************************************************
// decay method
//***************************************************

class Decay{
public:
	enum Type{
		UNKNOWN=0,
		CONST=1,
		EXP=2,
		SQRT=3,
		INV=4,
		POW=5,
		STEP=6
	};
	//constructor
	Decay():t_(Type::UNKNOWN){}
	Decay(Type t):t_(t){}
	//operators
	operator Type()const{return t_;}
	//member functions
	static Decay read(const char* str);
	static const char* name(const Decay& decay);
private:
	Type t_;
	//prevent automatic conversion for other built-in types
	//template<typename T> operator T() const;
};
std::ostream& operator<<(std::ostream& out, const Decay& decay);

//***************************************************
// loss function
//***************************************************

struct Loss{
public:
	enum Type{
		UNKNOWN=0,
		MSE=1,
		MAE=2,
		HUBER=3
	};
	//constructor
	Loss():t_(Type::UNKNOWN){}
	Loss(Type t):t_(t){}
	//operators
	operator Type()const{return t_;}
	//member functions
	static Loss read(const char* str);
	static const char* name(const Loss& loss);
	//error
	static double error(Loss loss, const Eigen::VectorXd& value, const Eigen::VectorXd& target);
	static double error(Loss loss, const Eigen::VectorXd& value, const Eigen::VectorXd& target, Eigen::VectorXd& grad);
private:
	Type t_;
	//prevent automatic conversion for other built-in types
	//template<typename T> operator T() const;
};
std::ostream& operator<<(std::ostream& out, const Loss& loss);

//***************************************************
// Data
//***************************************************

class Data{
private:
	//count
		int nPrint_;//print data every n steps
		int nWrite_;//write data every n steps
		int step_;//current step
		int count_;//current count
	//stopping
		int max_;//max steps
		double tol_;//stop tolerance
	//status
		double val_,valOld_;//current, old value
		double dv_,dp_;//change in value, p
	//algorithm
		Algo algo_;//optimization algorithm
		Stop stop_;//the type of value determining the end condition
	//parameters
		int dim_;//dimension of problem
		Eigen::VectorXd p_,pOld_;//current, old parameters
		Eigen::VectorXd g_,gOld_;//current, old gradients
public:
	//==== constructors/destructors ====
	Data(){defaults();}
	Data(int dim){defaults();init(dim);}
	~Data(){}

	//==== operators ====
	friend std::ostream& operator<<(std::ostream& out, const Data& data);

	//==== access ====
	//status
		double& val(){return val_;}
		const double& val()const{return val_;}
		double& valOld(){return valOld_;}
		const double& valOld()const{return valOld_;}
		double& dv(){return dv_;}
		const double& dv()const{return dv_;}
		double& dp(){return dp_;}
		const double& dp()const{return dp_;}
	//count
		int& nPrint(){return nPrint_;}
		const int& nPrint()const{return nPrint_;}
		int& nWrite(){return nWrite_;}
		const int& nWrite()const{return nWrite_;}
		int& step(){return step_;}
		const int& step()const{return step_;}
		int& count(){return count_;}
		const int& count()const{return count_;}
	//stopping
		double& tol(){return tol_;}
		const double& tol()const{return tol_;}
		int& max(){return max_;}
		const int& max()const{return max_;}
	//parameters
		int& dim(){return dim_;}
		const int& dim()const{return dim_;}
		Eigen::VectorXd& p(){return p_;}
		const Eigen::VectorXd& p()const{return p_;}
		Eigen::VectorXd& pOld(){return pOld_;}
		const Eigen::VectorXd& pOld()const{return pOld_;}
		Eigen::VectorXd& g(){return g_;}
		const Eigen::VectorXd& g()const{return g_;}
		Eigen::VectorXd& gOld(){return gOld_;}
		const Eigen::VectorXd& gOld()const{return gOld_;}
	//algorithm
		Algo& algo(){return algo_;}
		const Algo& algo()const{return algo_;}
		Stop& stop(){return stop_;}
		const Stop& stop()const{return stop_;}

	//==== member functions ====
	void defaults();
	void clear(){defaults();}
	void init(int dim);
};

//***************************************************
// Model
//***************************************************

class Model{
protected:
	int dim_;//dimension of the problem
	int period_;//period of decay
	Algo algo_;//optimization algorithm
	Decay decay_;//decay schedule
	double alpha_;//step decay constant
	double gamma_;//gradient step size
	double lambda_;//regularization parameter
	double power_;//step decay power
	double mix_;//mixing parameter
public:
	//==== constructors/destructors ====
	Model(){defaults();}
	virtual ~Model(){}

	//==== operators ====
	friend std::ostream& operator<<(std::ostream& out, const Model& model);

	//==== access ====
	int& dim(){return dim_;}
	const int& dim()const{return dim_;}
	int& period(){return period_;}
	const int& period()const{return period_;}
	Algo& algo(){return algo_;}
	const Algo& algo()const{return algo_;}
	Decay& decay(){return decay_;}
	const Decay& decay()const{return decay_;}
	double& alpha(){return alpha_;}
	const double& alpha()const{return alpha_;}
	double& gamma(){return gamma_;}
	const double& gamma()const{return gamma_;}
	double& lambda(){return lambda_;}
	const double& lambda()const{return lambda_;}
	double& power(){return power_;}
	const double& power()const{return power_;}
	double& mix(){return mix_;}
	const double& mix()const{return mix_;}

	//==== member functions ====
	void defaults();
	void clear();
	void update_step(int step);

	//==== virtual functions ====
	virtual void step(Data& d)=0;
	virtual void init(int dim);

	//==== static functions ====
	static std::ostream& print(std::ostream& out, const Model* model);
};

//steepest-desccent
class SGD final: public Model{
public:
	//constructors/destructors
	SGD(){defaults();}
	SGD(int dim){init(dim);}
	~SGD(){}
	//member functions
	void step(Data& d);
	void defaults();
	void init(int dim);
	//operators
	friend std::ostream& operator<<(std::ostream& out, const SGD& sgd);
};

//steepest-descent + momentum
class SDM final: public Model{
private:
	double eta_;//mixing term
	Eigen::VectorXd dx_;//change in parameters
public:
	//constructors/destructors
	SDM(){defaults();}
	SDM(int dim){init(dim);}
	~SDM(){}
	//access
	double& eta(){return eta_;}
	const double& eta()const{return eta_;}
	Eigen::VectorXd& dx(){return dx_;}
	const Eigen::VectorXd& dx()const{return dx_;}
	//member functions
	void step(Data& d);
	void defaults();
	void init(int dim);
	//operators
	friend std::ostream& operator<<(std::ostream& out, const SDM& sdm);
};

//nesterov accelerated gradient
class NAG final: public Model{
private:
	double eta_;//mixing term
	Eigen::VectorXd dx_;
public:
	//constructors/destructors
	NAG(){defaults();}
	NAG(int dim){init(dim);}
	~NAG(){}
	//access
	double& eta(){return eta_;}
	const double& eta()const{return eta_;}
	Eigen::VectorXd& dx(){return dx_;}
	const Eigen::VectorXd& dx()const{return dx_;}
	//member functions
	void step(Data& d);
	void defaults();
	void init(int dim);
	//operators
	friend std::ostream& operator<<(std::ostream& out, const NAG& nag);
};

//adagrad
class ADAGRAD final: public Model{
private:
	static const double eps_;//small term to prevent divergence
	Eigen::VectorXd mgrad2_;//avg of square of gradient
public:
	//constructors/destructors
	ADAGRAD(){defaults();}
	ADAGRAD(int dim){init(dim);}
	~ADAGRAD(){}
	//access
	Eigen::VectorXd& mgrad2(){return mgrad2_;}
	const Eigen::VectorXd& mgrad2()const{return mgrad2_;}
	//member functions
	void step(Data& d);
	void defaults();
	void init(int dim);
	//operators
	friend std::ostream& operator<<(std::ostream& out, const ADAGRAD& adagrad);
};

//adadelta
class ADADELTA final: public Model{
private:
	static const double eps_;//small term to prevent divergence
	double eta_;//mixing fraction
	Eigen::VectorXd mgrad2_;//avg of square of gradient
	Eigen::VectorXd mdx2_;//avg of square of dx
	Eigen::VectorXd dx_;//change in x
public:
	//constructors/destructors
	ADADELTA(){defaults();}
	ADADELTA(int dim){init(dim);}
	~ADADELTA(){}
	//access
	double& eta(){return eta_;}
	const double& eta()const{return eta_;}
	Eigen::VectorXd& mgrad2(){return mgrad2_;}
	const Eigen::VectorXd& mgrad2()const{return mgrad2_;}
	Eigen::VectorXd& mdx2(){return mdx2_;}
	const Eigen::VectorXd& mdx2()const{return mdx2_;}
	Eigen::VectorXd& dx(){return dx_;}
	const Eigen::VectorXd& dx()const{return dx_;}
	//member functions
	void step(Data& d);
	void defaults();
	void init(int dim);
	//operators
	friend std::ostream& operator<<(std::ostream& out, const ADADELTA& adadelta);
};

//rmsprop
class RMSPROP final: public Model{
private:
	static const double eps_;//small term to prevent divergence
	Eigen::VectorXd mgrad2_;//avg of square of gradient
public:
	//constructors/destructors
	RMSPROP(){defaults();}
	RMSPROP(int dim){init(dim);}
	~RMSPROP(){}
	//access
	Eigen::VectorXd& mgrad2(){return mgrad2_;}
	const Eigen::VectorXd& mgrad2()const{return mgrad2_;}
	//member functions
	void step(Data& d);
	void defaults();
	void init(int dim);
	//operators
	friend std::ostream& operator<<(std::ostream& out, const RMSPROP& rmsprop);
};

//adam
class ADAM final: public Model{
private:
	static const double eps_;//small term to prevent divergence
	static const double beta1_;
	static const double beta2_;
	double beta1i_;//power w.r.t i
	double beta2i_;//power w.r.t i
	Eigen::VectorXd mgrad_;//avg of gradient
	Eigen::VectorXd mgrad2_;//avg of square of gradient
public:
	//constructors/destructors
	ADAM(){defaults();}
	ADAM(int dim){init(dim);}
	~ADAM(){}
	//access
	double& beta1i(){return beta1i_;}
	const double& beta1i()const{return beta1i_;}
	double& beta2i(){return beta2i_;}
	const double& beta2i()const{return beta2i_;}
	Eigen::VectorXd& mgrad(){return mgrad_;}
	const Eigen::VectorXd& mgrad()const{return mgrad_;}
	Eigen::VectorXd& mgrad2(){return mgrad2_;}
	const Eigen::VectorXd& mgrad2()const{return mgrad2_;}
	//member functions
	void step(Data& d);
	void defaults();
	void init(int dim);
	//operators
	friend std::ostream& operator<<(std::ostream& out, const ADAM& adam);
};

//nadam
class NADAM final: public Model{
private:
	static const double eps_;//small term to prevent divergence
	static const double beta1_;
	static const double beta2_;
	double beta1i_;//power w.r.t i
	double beta2i_;//power w.r.t i
	Eigen::VectorXd mgrad_;//avg of gradient
	Eigen::VectorXd mgrad2_;//avg of square of gradient
public:
	//constructors/destructors
	NADAM(){defaults();}
	NADAM(int dim){init(dim);}
	~NADAM(){}
	//access
	double& beta1i(){return beta1i_;}
	const double& beta1i()const{return beta1i_;}
	double& beta2i(){return beta2i_;}
	const double& beta2i()const{return beta2i_;}
	Eigen::VectorXd& mgrad(){return mgrad_;}
	const Eigen::VectorXd& mgrad()const{return mgrad_;}
	Eigen::VectorXd& mgrad2(){return mgrad2_;}
	const Eigen::VectorXd& mgrad2()const{return mgrad2_;}
	//member functions
	void step(Data& d);
	void defaults();
	void init(int dim);
	//operators
	friend std::ostream& operator<<(std::ostream& out, const NADAM& nadam);
};

//amsgrad
class AMSGRAD final: public Model{
private:
	static const double eps_;//small term to prevent divergence
	static const double beta1_;
	static const double beta2_;
	double beta1i_;//power w.r.t i
	double beta2i_;//power w.r.t i
	Eigen::VectorXd mgrad_;//avg of gradient
	Eigen::VectorXd mgrad2_;//avg of square of gradient
	Eigen::VectorXd mgrad2m_;
public:
	//constructors/destructors
	AMSGRAD(){defaults();}
	AMSGRAD(int dim){init(dim);}
	~AMSGRAD(){}
	//access
	double& beta1i(){return beta1i_;}
	const double& beta1i()const{return beta1i_;}
	double& beta2i(){return beta2i_;}
	const double& beta2i()const{return beta2i_;}
	Eigen::VectorXd& mgrad(){return mgrad_;}
	const Eigen::VectorXd& mgrad()const{return mgrad_;}
	Eigen::VectorXd& mgrad2(){return mgrad2_;}
	const Eigen::VectorXd& mgrad2()const{return mgrad2_;}
	Eigen::VectorXd& mgrad2m(){return mgrad2m_;}
	const Eigen::VectorXd& mgrad2m()const{return mgrad2m_;}
	//member functions
	void step(Data& d);
	void defaults();
	void init(int dim);
	//operators
	friend std::ostream& operator<<(std::ostream& out, const AMSGRAD& amsgrad);
};

//bfgs
class BFGS final: public Model{
private:
	Eigen::MatrixXd B_,BOld_;
	Eigen::VectorXd s_,y_;
public:
	//constructors/destructors
	BFGS(){defaults();}
	BFGS(int dim){init(dim);}
	~BFGS(){}
	//member functions
	void step(Data& d);
	void defaults();
	void init(int dim);
	//operators
	friend std::ostream& operator<<(std::ostream& out, const BFGS& bfgs);
};

//rprop
class RPROP final: public Model{
private:
	static const double etaP;
	static const double etaM;
	static const double deltaMax;
	static const double deltaMin;
	Eigen::VectorXd delta_;
	Eigen::VectorXd dx_;
public:
	//constructors/destructors
	RPROP(){defaults();}
	RPROP(int dim){init(dim);}
	~RPROP(){}
	//access
	Eigen::VectorXd& delta(){return delta_;}
	const Eigen::VectorXd& delta()const{return delta_;}
	Eigen::VectorXd& dx(){return dx_;}
	const Eigen::VectorXd& dx()const{return dx_;}
	//member functions
	void step(Data& d);
	void defaults();
	void init(int dim);
	//operators
	friend std::ostream& operator<<(std::ostream& out, const RPROP& rprop);
};
/*
	Christian Igel and Michael Hüsken.
		Improving the Rprop Learning Algorithm.
		Second International Symposium on Neural Computation
		(NC 2000), pp. 115-121, ICSC Academic Press, 2000
	Christian Igel and Michael Hüsken.
		Empirical Evaluation of the Improved Rprop Learning Algorithm.
		Neurocomputing 50:105-123, 2003
*/

//cg
class CG final: public Model{
private:
	static const double eps_;//small term to prevent divergence
	Eigen::VectorXd cgd_;//cg direction
public:
	//constructors/destructors
	CG(){defaults();}
	CG(int dim){init(dim);}
	~CG(){}
	//access
	Eigen::VectorXd& cgd(){return cgd_;}
	const Eigen::VectorXd& cgd()const{return cgd_;}
	//member functions
	void step(Data& d);
	void defaults();
	void init(int dim);
	//operators
	friend std::ostream& operator<<(std::ostream& out, const CG& cg);
};

//read from file

Model& read(Model& model, const char* file);
Data& read(Data& data, const char* file);
SGD& read(SGD& sdg, const char* file);
SDM& read(SDM& sdm, const char* file);
NAG& read(NAG& nag, const char* file);
ADAGRAD& read(ADAGRAD& adagrad, const char* file);
ADADELTA& read(ADADELTA& adadelta, const char* file);
RMSPROP& read(RMSPROP& rmsprop, const char* file);
ADAM& read(ADAM& adam, const char* file);
NADAM& read(NADAM& nadam, const char* file);
BFGS& read(BFGS& bfgs, const char* file);
RPROP& read(RPROP& rprop, const char* file);

//read from file pointer

Model& read(Model& model, FILE* reader);
Data& read(Data& data, FILE* reader);
SGD& read(SGD& sdg, FILE* reader);
SDM& read(SDM& sdm, FILE* reader);
NAG& read(NAG& nag, FILE* reader);
ADAGRAD& read(ADAGRAD& adagrad, FILE* reader);
ADADELTA& read(ADADELTA& adadelta, FILE* reader);
RMSPROP& read(RMSPROP& rmsprop, FILE* reader);
ADAM& read(ADAM& adam, FILE* reader);
NADAM& read(NADAM& nadam, FILE* reader);
BFGS& read(BFGS& bfgs, FILE* reader);
RPROP& read(RPROP& rprop, FILE* reader);

//opterators - comparison

bool operator==(const SGD& obj1, const SGD& obj2);
bool operator==(const SDM& obj1, const SDM& obj2);
bool operator==(const NAG& obj1, const NAG& obj2);
bool operator==(const ADAGRAD& obj1, const ADAGRAD& obj2);
bool operator==(const ADADELTA& obj1, const ADADELTA& obj2);
bool operator==(const RMSPROP& obj1, const RMSPROP& obj2);
bool operator==(const ADAM& obj1, const ADAM& obj2);
bool operator==(const NADAM& obj1, const NADAM& obj2);
bool operator==(const BFGS& obj1, const BFGS& obj2);
bool operator==(const RPROP& obj1, const RPROP& obj2);

}

namespace serialize{

	//**********************************************
	// byte measures
	//**********************************************

	template <> int nbytes(const Opt::Data& obj);
	template <> int nbytes(const Opt::Model& obj);
	template <> int nbytes(const Opt::SGD& obj);
	template <> int nbytes(const Opt::SDM& obj);
	template <> int nbytes(const Opt::NAG& obj);
	template <> int nbytes(const Opt::ADAGRAD& obj);
	template <> int nbytes(const Opt::ADADELTA& obj);
	template <> int nbytes(const Opt::RMSPROP& obj);
	template <> int nbytes(const Opt::ADAM& obj);
	template <> int nbytes(const Opt::NADAM& obj);
	template <> int nbytes(const Opt::AMSGRAD& obj);
	template <> int nbytes(const Opt::BFGS& obj);
	template <> int nbytes(const Opt::RPROP& obj);
	template <> int nbytes(const Opt::CG& obj);

	//**********************************************
	// packing
	//**********************************************

	template <> int pack(const Opt::Data& obj, char* arr);
	template <> int pack(const Opt::Model& obj, char* arr);
	template <> int pack(const Opt::SGD& obj, char* arr);
	template <> int pack(const Opt::SDM& obj, char* arr);
	template <> int pack(const Opt::NAG& obj, char* arr);
	template <> int pack(const Opt::ADAGRAD& obj, char* arr);
	template <> int pack(const Opt::ADADELTA& obj, char* arr);
	template <> int pack(const Opt::RMSPROP& obj, char* arr);
	template <> int pack(const Opt::ADAM& obj, char* arr);
	template <> int pack(const Opt::NADAM& obj, char* arr);
	template <> int pack(const Opt::AMSGRAD& obj, char* arr);
	template <> int pack(const Opt::BFGS& obj, char* arr);
	template <> int pack(const Opt::RPROP& obj, char* arr);
	template <> int pack(const Opt::CG& obj, char* arr);

	//**********************************************
	// unpacking
	//**********************************************

	template <> int unpack(Opt::Data& obj, const char* arr);
	template <> int unpack(Opt::Model& obj, const char* arr);
	template <> int unpack(Opt::SGD& obj, const char* arr);
	template <> int unpack(Opt::SDM& obj, const char* arr);
	template <> int unpack(Opt::NAG& obj, const char* arr);
	template <> int unpack(Opt::ADAGRAD& obj, const char* arr);
	template <> int unpack(Opt::ADADELTA& obj, const char* arr);
	template <> int unpack(Opt::RMSPROP& obj, const char* arr);
	template <> int unpack(Opt::ADAM& obj, const char* arr);
	template <> int unpack(Opt::NADAM& obj, const char* arr);
	template <> int unpack(Opt::AMSGRAD& obj, const char* arr);
	template <> int unpack(Opt::BFGS& obj, const char* arr);
	template <> int unpack(Opt::RPROP& obj, const char* arr);
	template <> int unpack(Opt::CG& obj, const char* arr);

}

#endif

max_stars_repo_name: markdellostritto/AtomNN

max_issues_repo_name: markdellostritto/AtomNN

max_forks_repo_name: markdellostritto/AtomNN