<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbWrapperQtWidgetFloatParameter.h"

namespace otb
{
namespace Wrapper
{

QtWidgetFloatParameter::QtWidgetFloatParameter(FloatParameter* floatParam, QtWidgetModel* m)
: QtWidgetParameterBase(floatParam, m),
  m_FloatParam(floatParam)
{
}

QtWidgetFloatParameter::~QtWidgetFloatParameter()
{
}

void QtWidgetFloatParameter::DoUpdateGUI()
{
  // TODO : search for a better solution
  m_QDoubleSpinBox->setRange(m_FloatParam->GetMinimumValue(),
                             m_FloatParam->GetMaximumValue());

  bool signalsBlocked = m_QDoubleSpinBox->blockSignals( true );

  if (m_FloatParam->HasValue())
    {
    m_QDoubleSpinBox->setValue(m_FloatParam->GetValue());
    }
  m_QDoubleSpinBox->blockSignals( signalsBlocked );

  QFont font = m_QDoubleSpinBox->font();
  if (m_FloatParam->HasUserValue())
    {
    font.setBold(true);
    }
  else
    {
    font.setBold(false);
    }
  m_QDoubleSpinBox->setFont(font);
}

void QtWidgetFloatParameter::DoCreateWidget()
{
  m_QHBoxLayout = new QHBoxLayout;
  m_QHBoxLayout->setSpacing(0);
  m_QHBoxLayout->setContentsMargins(0, 0, 0, 0);

  m_QDoubleSpinBox = new QDoubleSpinBox;
  m_QDoubleSpinBox->setDecimals(5);
  m_QDoubleSpinBox->setSingleStep(0.1);
  m_QDoubleSpinBox->setRange(m_FloatParam->GetMinimumValue(), m_FloatParam->GetMaximumValue());
  m_QDoubleSpinBox->setToolTip(m_FloatParam->GetDescription());

  connect( m_QDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(SetValue(double)) );
  connect( m_QDoubleSpinBox, SIGNAL(valueChanged(double)), GetModel(), SLOT(NotifyUpdate()) );
  connect( GetModel(), SIGNAL(UpdateGui()), this, SLOT(UpdateGUI() ) );

  m_QHBoxLayout->addWidget(m_QDoubleSpinBox);
  m_QHBoxLayout->addStretch();

  this->setLayout(m_QHBoxLayout);
}

void QtWidgetFloatParameter::SetValue(double value)
{
  m_FloatParam->SetValue( static_cast<float>(value) );
  m_FloatParam->SetUserValue(true);
}

}
}
<commit_msg>ENH: turning AutomaticValue to Off when a UserValue is set<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbWrapperQtWidgetFloatParameter.h"

namespace otb
{
namespace Wrapper
{

QtWidgetFloatParameter::QtWidgetFloatParameter(FloatParameter* floatParam, QtWidgetModel* m)
: QtWidgetParameterBase(floatParam, m),
  m_FloatParam(floatParam)
{
}

QtWidgetFloatParameter::~QtWidgetFloatParameter()
{
}

void QtWidgetFloatParameter::DoUpdateGUI()
{
  // TODO : search for a better solution
  m_QDoubleSpinBox->setRange(m_FloatParam->GetMinimumValue(),
                             m_FloatParam->GetMaximumValue());

  bool signalsBlocked = m_QDoubleSpinBox->blockSignals( true );

  if (m_FloatParam->HasValue())
    {
    m_QDoubleSpinBox->setValue(m_FloatParam->GetValue());
    }
  m_QDoubleSpinBox->blockSignals( signalsBlocked );

  QFont font = m_QDoubleSpinBox->font();
  if (m_FloatParam->HasUserValue())
    {
    font.setBold(true);
    }
  else
    {
    font.setBold(false);
    }
  m_QDoubleSpinBox->setFont(font);
}

void QtWidgetFloatParameter::DoCreateWidget()
{
  m_QHBoxLayout = new QHBoxLayout;
  m_QHBoxLayout->setSpacing(0);
  m_QHBoxLayout->setContentsMargins(0, 0, 0, 0);

  m_QDoubleSpinBox = new QDoubleSpinBox;
  m_QDoubleSpinBox->setDecimals(5);
  m_QDoubleSpinBox->setSingleStep(0.1);
  m_QDoubleSpinBox->setRange(m_FloatParam->GetMinimumValue(), m_FloatParam->GetMaximumValue());
  m_QDoubleSpinBox->setToolTip(m_FloatParam->GetDescription());

  connect( m_QDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(SetValue(double)) );
  connect( m_QDoubleSpinBox, SIGNAL(valueChanged(double)), GetModel(), SLOT(NotifyUpdate()) );
  connect( GetModel(), SIGNAL(UpdateGui()), this, SLOT(UpdateGUI() ) );

  m_QHBoxLayout->addWidget(m_QDoubleSpinBox);
  m_QHBoxLayout->addStretch();

  this->setLayout(m_QHBoxLayout);
}

void QtWidgetFloatParameter::SetValue(double value)
{
  m_FloatParam->SetValue( static_cast<float>(value) );
  m_FloatParam->SetUserValue(true);
  m_FloatParam->SetAutomaticValue(false);
}

}
}
<|endoftext|>


<commit_before>/**
 ** \file object/object-class.cc
 ** \brief Creation of the URBI object object.
 */

//#define ENABLE_DEBUG_TRACES

#include <boost/bind.hpp>

#include <libport/compiler.hh>
#include <libport/containers.hh>
#include <libport/escape.hh>
#include <libport/foreach.hh>
#include <libport/tokenizer.hh>

#include <kernel/uconnection.hh>

#include <object/cxx-primitive.hh>
#include <object/float.hh>
#include <object/global.hh>
#include <object/list.hh>
#include <object/object.hh>
#include <object/object.hh>
#include <object/string.hh>

#include <runner/call.hh>
#include <runner/runner.hh>

namespace object
{
  rObject object_class;

  /*--------------------.
  | Object primitives.  |
  `--------------------*/

  static rObject
  object_class_clone (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 0);

    return args[0]->clone();
  }

  static rObject
  object_class_init (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 0);
    return args[0];
  }

  /// Send dumped self on the connection.
  /// args[1], if present, can be the tag to use.
  static rObject
  object_class_dump (runner::Runner& r, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1, 2);

    // Second argument is max depth.
    int depth_max = 0;
    if (args.size() >= 2)
    {
      type_check(args[1], Float::proto);
      const rFloat& arg1 = args[1]->as<Float>();
      try
      {
	depth_max = libport::ufloat_to_int(arg1->value_get());
      }
      catch (libport::bad_numeric_cast& ue)
      {
	throw BadInteger(arg1->value_get(), SYMBOL(dump));
      }
    }

    // Third argument is the tag name.
    std::string tag;
    if (args.size() >= 3)
    {
      const rString& arg2 = args[2].unsafe_cast<String>();
      assert(arg2);
      tag = arg2->value_get();
    }

    std::ostringstream os;
    args[0]->dump(os, r, depth_max);
    //for now our best choice is to dump line by line in "system" messages.
    const std::string stream = os.str();
    boost::tokenizer< boost::char_separator<char> > tok =
      libport::make_tokenizer(stream, "\n");
    const std::string system_header("*** ");
    foreach(const std::string& line, tok)
      r.send_message(tag, system_header+line);
    return void_class;
  }

  /// Return the address of an object as a number, mostly
  /// for debugging purpose.
  static rObject
  object_class_uid (runner::Runner&, objects_type& args)
  {
    static boost::format uid("0x%x");
    check_arg_count(args.size() - 1, 0);
    return
      new String(str(uid % reinterpret_cast<long long>(args[0].get())));
  }

  /// Structural equality
  static rObject
  object_class_EQ_EQ(runner::Runner& r, objects_type& args)
  {
    // Unless overridden, structural equality is physical equality.
    check_arg_count(args.size() - 1, 1);
    return urbi_call(r, args[0], SYMBOL(EQ_EQ_EQ), args[1]);
  }

  /// Physical equality
  static rObject
  object_class_EQ_EQ_EQ(runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1);
    return to_boolean(args[0] == args[1]);
  }

  static rObject
  object_class_apply(runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1);
    type_check(args[1], List::proto);
    const rList& arg1 = args[1]->as<List>();
    if (arg1->value_get ().size () != 1 || arg1->value_get().front() != args[0])
      throw PrimitiveError(SYMBOL(apply), "first argument must be [this]");
    return arg1->value_get().front();
  }

  static rObject
  object_class_callMessage (runner::Runner& r, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1);
    // We need to set the 'code' slot: make a copy of the call message.
    rObject call_message = args[1]->clone();
    const rObject& message = call_message->slot_get(SYMBOL(message));
    type_check(message, String::proto);
    const libport::Symbol msg = libport::Symbol(message->as<String>()->value_get());
    const rObject& target = args[0];
    const rObject& code = target->slot_get(msg);
    call_message->slot_update(r, SYMBOL(code), code);
    call_message->slot_update(r, SYMBOL(target), target);
    // FIXME: Sanity checks on the call message are probably required
    return r.apply_call_message(code, msg, call_message);
  }

  /*---------.
  | Protos.  |
  `---------*/

  /// Adding or removing protos. \a Verb is "add" or "remove".
#define CHANGE_PARENTS(Verb)                                            \
  static rObject                                                        \
  object_class_ ## Verb ## Proto (runner::Runner&,                      \
                                  objects_type& args)                   \
  {									\
    check_arg_count(args.size() - 1, 1);                                \
    args[0]->proto_ ## Verb (args[1]);					\
    return args[0];							\
  }

  /// Add a proto.
  CHANGE_PARENTS(add);
  /// Remove a proto.
  CHANGE_PARENTS(remove);
#undef CHANGE_PARENTS

  /// Get protos' list.
  static rObject
  object_class_protos (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 0);
    return args[0]->urbi_protos_get ();
  }

  /// Recursively get protos list

  static bool
  proto_add(List::value_type& protos, const rObject& proto)
  {
    protos.push_back(proto);
    return false;
  }

  static rObject
  object_class_allProtos(runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 0);
    List::value_type res;
    for_all_protos(args[0], boost::bind(&proto_add, boost::ref(res), _1));
    return new List(res);
  }

  /*--------.
  | Slots.  |
  `--------*/

  template <typename F>
  static inline void for_all_slot_names(const rObject& o, F f)
  {
    for (Object::slots_implem::iterator slot = o->slots_get().begin(o.get());
         slot != o->slots_get().end(o.get());
         ++slot)
      f(slot->first.second);
  }

  static void
  add_as_rString(List::value_type& l, libport::Symbol slot_name)
  {
    l.push_back(new String(slot_name));
  }

  /// List of slot names.
  static rObject
  object_class_slotNames (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 0);
    const rObject& obj = args[0];

    List::value_type l;
    for_all_slot_names(obj, boost::bind(&add_as_rString, boost::ref(l), _1));
    return new List(l);
  }

  /// Recursive list of slot names.

  static void
  maybe_add(std::vector<libport::Symbol>& control, List::value_type& l,
	    libport::Symbol slot_name)
  {
    if (!libport::has(control, slot_name))
    {
      control.push_back(slot_name);
      l.push_back(new String(slot_name));
    }
  }

  static rObject
  object_class_allSlotNames(runner::Runner& r, objects_type& args)
  {
    check_arg_count(args.size() - 1, 0);
    std::vector<libport::Symbol> slot_names;
    List::value_type res;
    objects_type protos = object_class_allProtos(r, args)->as<List>()->value_get();
    foreach (const rObject& proto, protos)
    {
      for_all_slot_names(proto, boost::bind(&maybe_add,
					    boost::ref(slot_names),
					    boost::ref(res),
					    _1));
    }
    return new List(res);
  }

  /// Get a slot content.
  static rObject
  object_class_getSlot (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1);
    const rObject& obj = args[0];
    const rString& arg1 = args[1].unsafe_cast<String>();
    assert(arg1);
    return obj->slot_get(libport::Symbol(arg1->value_get()));
  }

  // self.getLazyLocalSlot(SLOT-NAME, DEFAULT-VALUE, CREATE?).
  static rObject
  object_class_getLazyLocalSlot (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 3);

    const rString& arg1 = args[1].unsafe_cast<String>();
    assert(arg1);
    const Object::key_type& slot_name = libport::Symbol(arg1->value_get());

    // If the slot already exists, return its content.
    if (rObject slot = args[0]->own_slot_get (slot_name))
      return slot;

    // The slot doesn't exist. Should we create it?
    if (is_true (args[3], SYMBOL(getLazyLocalSlot)))
      args[0]->slot_set (slot_name, args[2]);

    // Return the default value for this slot.
    return args[2];
  }

  /// Remove a slot.
  static rObject
  object_class_removeSlot (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1);
    const rObject& obj = args[0];
    const rString& arg1 = args[1].unsafe_cast<String>();
    assert(arg1);
    obj->slot_remove(libport::Symbol(arg1->value_get()));
    return obj;
  }

   /// Locate a slot.
  static rObject
  object_class_locateSlot (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1);
    const rString& arg1 = args[1].unsafe_cast<String>();
    assert(arg1);

    rObject o = args[0]->slot_locate(libport::Symbol(arg1->value_get()));
    return o ? o : nil_class;
  }

  static rObject
  object_class_setSlot (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 2);
    const rString& arg1 = args[1].unsafe_cast<String>();
    assert(arg1);
    args[0]->slot_set(libport::Symbol(arg1->value_get()), args[2]);
    return args[2];
  }

  static rObject
  object_class_createSlot (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1);
    const rString& arg1 = args[1].unsafe_cast<String>();
    assert(arg1);
    args[0]->slot_set(libport::Symbol(arg1->value_get()), void_class);
    return void_class;
  }

  static rObject
  object_class_updateSlot (runner::Runner& r, objects_type& args)
  {
    check_arg_count(args.size() - 1, 2);
    const rString& arg1 = args[1].unsafe_cast<String>();
    assert(arg1);
    return args[0]->slot_update(r, libport::Symbol(arg1->value_get()), args[2]);
  }

  static bool
  object_class_isA(rObject self, rObject proto)
  {
    return is_a(self, proto);
  }

  void
  object_class_initialize ()
  {
    object_class->slot_set(SYMBOL(isA),
                           make_primitive(object_class_isA, SYMBOL(isA)));

    /// \a Call gives the name of the C++ function, and \a Name that in Urbi.
#define DECLARE(Name)				\
    DECLARE_PRIMITIVE(object, Name)

    DECLARE(addProto);
    DECLARE(allProtos);
    DECLARE(allSlotNames);
    DECLARE(apply);
    DECLARE(callMessage);
    DECLARE(clone);
    DECLARE(dump);
    DECLARE(getLazyLocalSlot);
    DECLARE(getSlot);
    DECLARE(init);
    DECLARE(locateSlot);
    DECLARE(EQ_EQ_EQ);
    DECLARE(protos);
    DECLARE(removeProto);
    DECLARE(removeSlot);
    DECLARE(EQ_EQ);
    DECLARE(setSlot);
    DECLARE(createSlot);
    DECLARE(slotNames);
    DECLARE(uid);
    DECLARE(updateSlot);
#undef DECLARE

#define DECLARE(Name, Code)                     \
    object_class->slot_set(SYMBOL(Name), make_primitive(Code, SYMBOL(Name)))

    DECLARE(getProperty, &Object::property_get);
    DECLARE(hasProperty, &Object::property_has);
    DECLARE(hasSlot, &Object::slot_has);
    DECLARE(setProperty, &Object::property_set);
    DECLARE(removeProperty, &Object::property_remove);
#undef DECLARE
  }

}; // namespace object
<commit_msg>Formatting changes.<commit_after>/**
 ** \file object/object-class.cc
 ** \brief Creation of the URBI object object.
 */

//#define ENABLE_DEBUG_TRACES

#include <boost/bind.hpp>

#include <libport/compiler.hh>
#include <libport/containers.hh>
#include <libport/escape.hh>
#include <libport/foreach.hh>
#include <libport/tokenizer.hh>

#include <kernel/uconnection.hh>

#include <object/cxx-primitive.hh>
#include <object/float.hh>
#include <object/global.hh>
#include <object/list.hh>
#include <object/object.hh>
#include <object/object.hh>
#include <object/string.hh>

#include <runner/call.hh>
#include <runner/runner.hh>

namespace object
{
  rObject object_class;

  /*--------------------.
  | Object primitives.  |
  `--------------------*/

  static rObject
  object_class_clone (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 0);

    return args[0]->clone();
  }

  static rObject
  object_class_init (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 0);
    return args[0];
  }

  /// Send dumped self on the connection.
  /// args[1], if present, can be the tag to use.
  static rObject
  object_class_dump (runner::Runner& r, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1, 2);

    // Second argument is max depth.
    int depth_max = 0;
    if (args.size() >= 2)
    {
      type_check(args[1], Float::proto);
      const rFloat& arg1 = args[1]->as<Float>();
      try
      {
	depth_max = libport::ufloat_to_int(arg1->value_get());
      }
      catch (libport::bad_numeric_cast& ue)
      {
	throw BadInteger(arg1->value_get(), SYMBOL(dump));
      }
    }

    // Third argument is the tag name.
    std::string tag;
    if (args.size() >= 3)
    {
      const rString& arg2 = args[2].unsafe_cast<String>();
      assert(arg2);
      tag = arg2->value_get();
    }

    std::ostringstream os;
    args[0]->dump(os, r, depth_max);
    //for now our best choice is to dump line by line in "system" messages.
    const std::string stream = os.str();
    boost::tokenizer< boost::char_separator<char> > tok =
      libport::make_tokenizer(stream, "\n");
    const std::string system_header("*** ");
    foreach(const std::string& line, tok)
      r.send_message(tag, system_header+line);
    return void_class;
  }

  /// Return the address of an object as a number, mostly
  /// for debugging purpose.
  static rObject
  object_class_uid (runner::Runner&, objects_type& args)
  {
    static boost::format uid("0x%x");
    check_arg_count(args.size() - 1, 0);
    return
      new String(str(uid % reinterpret_cast<long long>(args[0].get())));
  }

  /// Structural equality
  static rObject
  object_class_EQ_EQ(runner::Runner& r, objects_type& args)
  {
    // Unless overridden, structural equality is physical equality.
    check_arg_count(args.size() - 1, 1);
    return urbi_call(r, args[0], SYMBOL(EQ_EQ_EQ), args[1]);
  }

  /// Physical equality
  static rObject
  object_class_EQ_EQ_EQ(runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1);
    return to_boolean(args[0] == args[1]);
  }

  static rObject
  object_class_apply(runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1);
    type_check(args[1], List::proto);
    const rList& arg1 = args[1]->as<List>();
    if (arg1->value_get ().size () != 1
        || arg1->value_get().front() != args[0])
      throw PrimitiveError(SYMBOL(apply), "first argument must be [this]");
    return arg1->value_get().front();
  }

  static rObject
  object_class_callMessage (runner::Runner& r, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1);
    // We need to set the 'code' slot: make a copy of the call message.
    rObject call_message = args[1]->clone();
    const rObject& message = call_message->slot_get(SYMBOL(message));
    type_check(message, String::proto);
    const libport::Symbol msg(message->as<String>()->value_get());
    const rObject& target = args[0];
    const rObject& code = target->slot_get(msg);
    call_message->slot_update(r, SYMBOL(code), code);
    call_message->slot_update(r, SYMBOL(target), target);
    // FIXME: Sanity checks on the call message are probably required
    return r.apply_call_message(code, msg, call_message);
  }

  /*---------.
  | Protos.  |
  `---------*/

  /// Adding or removing protos. \a Verb is "add" or "remove".
#define CHANGE_PARENTS(Verb)                                            \
  static rObject                                                        \
  object_class_ ## Verb ## Proto (runner::Runner&,                      \
                                  objects_type& args)                   \
  {									\
    check_arg_count(args.size() - 1, 1);                                \
    args[0]->proto_ ## Verb (args[1]);					\
    return args[0];							\
  }

  /// Add a proto.
  CHANGE_PARENTS(add);
  /// Remove a proto.
  CHANGE_PARENTS(remove);
#undef CHANGE_PARENTS

  /// Get protos' list.
  static rObject
  object_class_protos (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 0);
    return args[0]->urbi_protos_get ();
  }

  /// Recursively get protos list

  static bool
  proto_add(List::value_type& protos, const rObject& proto)
  {
    protos.push_back(proto);
    return false;
  }

  static rObject
  object_class_allProtos(runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 0);
    List::value_type res;
    for_all_protos(args[0], boost::bind(&proto_add, boost::ref(res), _1));
    return new List(res);
  }

  /*--------.
  | Slots.  |
  `--------*/

  template <typename F>
  static inline void for_all_slot_names(const rObject& o, F f)
  {
    for (Object::slots_implem::iterator slot = o->slots_get().begin(o.get());
         slot != o->slots_get().end(o.get());
         ++slot)
      f(slot->first.second);
  }

  static void
  add_as_rString(List::value_type& l, libport::Symbol slot_name)
  {
    l.push_back(new String(slot_name));
  }

  /// List of slot names.
  static rObject
  object_class_slotNames (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 0);
    const rObject& obj = args[0];

    List::value_type l;
    for_all_slot_names(obj, boost::bind(&add_as_rString, boost::ref(l), _1));
    return new List(l);
  }

  /// Recursive list of slot names.

  static void
  maybe_add(std::vector<libport::Symbol>& control, List::value_type& l,
	    libport::Symbol slot_name)
  {
    if (!libport::has(control, slot_name))
    {
      control.push_back(slot_name);
      l.push_back(new String(slot_name));
    }
  }

  static rObject
  object_class_allSlotNames(runner::Runner& r, objects_type& args)
  {
    check_arg_count(args.size() - 1, 0);
    std::vector<libport::Symbol> slot_names;
    List::value_type res;
    objects_type protos =
      object_class_allProtos(r, args)->as<List>()->value_get();
    foreach (const rObject& proto, protos)
    {
      for_all_slot_names(proto, boost::bind(&maybe_add,
					    boost::ref(slot_names),
					    boost::ref(res),
					    _1));
    }
    return new List(res);
  }

  /// Get a slot content.
  static rObject
  object_class_getSlot (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1);
    const rObject& obj = args[0];
    const rString& arg1 = args[1].unsafe_cast<String>();
    assert(arg1);
    return obj->slot_get(libport::Symbol(arg1->value_get()));
  }

  // self.getLazyLocalSlot(SLOT-NAME, DEFAULT-VALUE, CREATE?).
  static rObject
  object_class_getLazyLocalSlot (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 3);

    const rString& arg1 = args[1].unsafe_cast<String>();
    assert(arg1);
    const Object::key_type& slot_name = libport::Symbol(arg1->value_get());

    // If the slot already exists, return its content.
    if (rObject slot = args[0]->own_slot_get (slot_name))
      return slot;

    // The slot doesn't exist. Should we create it?
    if (is_true (args[3], SYMBOL(getLazyLocalSlot)))
      args[0]->slot_set (slot_name, args[2]);

    // Return the default value for this slot.
    return args[2];
  }

  /// Remove a slot.
  static rObject
  object_class_removeSlot (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1);
    const rObject& obj = args[0];
    const rString& arg1 = args[1].unsafe_cast<String>();
    assert(arg1);
    obj->slot_remove(libport::Symbol(arg1->value_get()));
    return obj;
  }

   /// Locate a slot.
  static rObject
  object_class_locateSlot (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1);
    const rString& arg1 = args[1].unsafe_cast<String>();
    assert(arg1);

    rObject o = args[0]->slot_locate(libport::Symbol(arg1->value_get()));
    return o ? o : nil_class;
  }

  static rObject
  object_class_setSlot (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 2);
    const rString& arg1 = args[1].unsafe_cast<String>();
    assert(arg1);
    args[0]->slot_set(libport::Symbol(arg1->value_get()), args[2]);
    return args[2];
  }

  static rObject
  object_class_createSlot (runner::Runner&, objects_type& args)
  {
    check_arg_count(args.size() - 1, 1);
    const rString& arg1 = args[1].unsafe_cast<String>();
    assert(arg1);
    args[0]->slot_set(libport::Symbol(arg1->value_get()), void_class);
    return void_class;
  }

  static rObject
  object_class_updateSlot (runner::Runner& r, objects_type& args)
  {
    check_arg_count(args.size() - 1, 2);
    const rString& arg1 = args[1].unsafe_cast<String>();
    assert(arg1);
    return args[0]->slot_update(r, libport::Symbol(arg1->value_get()), args[2]);
  }

  static bool
  object_class_isA(rObject self, rObject proto)
  {
    return is_a(self, proto);
  }

  void
  object_class_initialize ()
  {
    object_class->slot_set(SYMBOL(isA),
                           make_primitive(object_class_isA, SYMBOL(isA)));

    /// \a Call gives the name of the C++ function, and \a Name that in Urbi.
#define DECLARE(Name)				\
    DECLARE_PRIMITIVE(object, Name)

    DECLARE(addProto);
    DECLARE(allProtos);
    DECLARE(allSlotNames);
    DECLARE(apply);
    DECLARE(callMessage);
    DECLARE(clone);
    DECLARE(dump);
    DECLARE(getLazyLocalSlot);
    DECLARE(getSlot);
    DECLARE(init);
    DECLARE(locateSlot);
    DECLARE(EQ_EQ_EQ);
    DECLARE(protos);
    DECLARE(removeProto);
    DECLARE(removeSlot);
    DECLARE(EQ_EQ);
    DECLARE(setSlot);
    DECLARE(createSlot);
    DECLARE(slotNames);
    DECLARE(uid);
    DECLARE(updateSlot);
#undef DECLARE

#define DECLARE(Name, Code)                     \
    object_class->slot_set(SYMBOL(Name), make_primitive(Code, SYMBOL(Name)))

    DECLARE(getProperty, &Object::property_get);
    DECLARE(hasProperty, &Object::property_has);
    DECLARE(hasSlot, &Object::slot_has);
    DECLARE(setProperty, &Object::property_set);
    DECLARE(removeProperty, &Object::property_remove);
#undef DECLARE
  }

}; // namespace object
<|endoftext|>


<commit_before>// MathLib.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <unittest.h>
#include <neuralnet.h>

int _tmain(int /*argc*/, _TCHAR* /*argv[]*/)
{
	//test change
	run_tests();

	return 0;
}
<commit_msg>Small cleanup<commit_after>// MathLib.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <unittest.h>

int _tmain(int /*argc*/, _TCHAR* /*argv[]*/)
{
	//test change
	run_tests();

	return 0;
}
<|endoftext|>


<commit_before>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"

using namespace MathLib;

#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO

/*
*/
#define ACTOR_BASE_IFPS             (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP            89.9f
#define ACTOR_BASE_COLLISIONS       4

/*
*/
CActorBase::CActorBase()
{
	m_vUp = vec3(0.0f, 0.0f, 1.0f);
	m_pObject = new CObjectDummy();
	m_pDummy = new CBodyDummy();
	m_pShape = new CShapeCapsule(1.0f, 1.0f);

	m_nFlush = 0;
	m_vPosition = Vec3_zero;
	m_vVelocity = Vec3_zero;
	m_fPhiAngle = 0.0f;			//倾斜角		二维平面坐标系中，直线向Y周延伸的方向与X轴正向之间的夹角
	m_fThetaAngle = 0.0f;			//方位角，正北方那条线与当前线条按照顺时针走过的角度

	for (int i = 0; i < NUM_STATES; i++)
	{
		m_pStates[i] = 0;
		m_pTimes[i] = 0.0f;
	}
	m_pDummy->SetEnabled(1);
	m_pObject->SetBody(NULL);
	m_pObject->SetBody(m_pDummy);
	m_pShape->SetBody(NULL);
	m_pShape->SetBody(m_pDummy);

	m_pObject->SetWorldTransform(Get_Body_Transform());
	m_pShape->SetRestitution(0.0f);
	m_pShape->SetCollisionMask(2);

	SetEnabled(1);
	SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
	SetCollision(1);
	SetCollisionRadius(0.3f);
	SetCollisionHeight(1.0f);
	SetFriction(2.0f);
	SetMinVelocity(2.0f);
	SetMaxVelocity(4.0f);
	SetAcceleration(8.0f);
	SetDamping(8.0f);
	SetJumping(1.5f);

	SetGround(0);
	SetCeiling(0);
}

CActorBase::~CActorBase()
{
	m_pDummy->SetObject(NULL);
	delete m_pObject;
	delete m_pDummy;
}

void CActorBase::SetEnabled(int enable)
{
	m_nEnable = enable;
	m_pDummy->SetEnabled(m_nEnable);
}

int CActorBase::IsEnabled() const
{
	return m_nEnable;
}
void CActorBase::Update(float ifps)
{
	if (!m_nEnable)
	{
		return;
	}

	// impulse
	vec3 impulse = vec3_zero;

	// ortho basis
	vec3 tangent, binormal;
	OrthoBasis(m_vUp, tangent, binormal);

	// current basis
	vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
	vec3 y = Normalize(Cross(m_vUp, x));
	vec3 z = Normalize(Cross(x, y));

	handle states
	Update_States(1, ifps);

	// old velocity
	float x_velocity = Dot(x, m_vVelocity);
	float y_velocity = Dot(y, m_vVelocity);
	float z_velocity = Dot(z, m_vVelocity);
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"

using namespace MathLib;

#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO

/*
*/
#define ACTOR_BASE_IFPS             (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP            89.9f
#define ACTOR_BASE_COLLISIONS       4

/*
*/
CActorBase::CActorBase()
{
	m_vUp = vec3(0.0f, 0.0f, 1.0f);
	m_pObject = new CObjectDummy();
	m_pDummy = new CBodyDummy();
	m_pShape = new CShapeCapsule(1.0f, 1.0f);

	m_nFlush = 0;
	m_vPosition = Vec3_zero;
	m_vVelocity = Vec3_zero;
	m_fPhiAngle = 0.0f;			//倾斜角		二维平面坐标系中，直线向Y周延伸的方向与X轴正向之间的夹角
	m_fThetaAngle = 0.0f;			//方位角，正北方那条线与当前线条按照顺时针走过的角度

	for (int i = 0; i < NUM_STATES; i++)
	{
		m_pStates[i] = 0;
		m_pTimes[i] = 0.0f;
	}
	m_pDummy->SetEnabled(1);
	m_pObject->SetBody(NULL);
	m_pObject->SetBody(m_pDummy);
	m_pShape->SetBody(NULL);
	m_pShape->SetBody(m_pDummy);

	m_pObject->SetWorldTransform(Get_Body_Transform());
	m_pShape->SetRestitution(0.0f);
	m_pShape->SetCollisionMask(2);

	SetEnabled(1);
	SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
	SetCollision(1);
	SetCollisionRadius(0.3f);
	SetCollisionHeight(1.0f);
	SetFriction(2.0f);
	SetMinVelocity(2.0f);
	SetMaxVelocity(4.0f);
	SetAcceleration(8.0f);
	SetDamping(8.0f);
	SetJumping(1.5f);

	SetGround(0);
	SetCeiling(0);
}

CActorBase::~CActorBase()
{
	m_pDummy->SetObject(NULL);
	delete m_pObject;
	delete m_pDummy;
}

void CActorBase::SetEnabled(int enable)
{
	m_nEnable = enable;
	m_pDummy->SetEnabled(m_nEnable);
}

int CActorBase::IsEnabled() const
{
	return m_nEnable;
}
void CActorBase::Update(float ifps)
{
	if (!m_nEnable)
	{
		return;
	}

	// impulse
	vec3 impulse = vec3_zero;

	// ortho basis
	vec3 tangent, binormal;
	OrthoBasis(m_vUp, tangent, binormal);

	// current basis
	vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
	vec3 y = Normalize(Cross(m_vUp, x));
	vec3 z = Normalize(Cross(x, y));

	handle states
	Update_States(1, ifps);

	// old velocity
	float x_velocity = Dot(x, m_vVelocity);
	float y_velocity = Dot(y, m_vVelocity);
	float z_velocity = Dot(z, m_vVelocity);
	// movement
	if (m_pStates[STATE_FORWARD]) impulse += x;
	if (m_pStates[STATE_BACKWARD]) impulse -= x;
	if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
	if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
	impulse.normalize();

}<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// 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
//
//     https://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.
//
// -----------------------------------------------------------------------------
// File: robots_main.cc
// -----------------------------------------------------------------------------
//
// Simple binary to assess whether a URL is accessible to a user-agent according
// to records found in a local robots.txt file, based on Google's robots.txt
// parsing and matching algorithms.
// Usage:
//     robots_main <local_path_to_robotstxt> <user_agent> <url>
// Arguments:
// local_path_to_robotstxt: local path to a file containing robots.txt records.
//   For example: /home/users/username/robots.txt
// user_agent: a token to be matched against records in the robots.txt.
//   For example: Googlebot
// url: a url to be matched against records in the robots.txt. The URL must be
// %-encoded according to RFC3986.
//   For example: https://example.com/accessible/url.html
// Returns: Prints a sentence with verdict about whether 'user_agent' is allowed
// to access 'url' based on records in 'local_path_to_robotstxt'.
//
#include <fstream>
#include <iostream>

#include "robots.h"

bool LoadFile(const std::string& filename, std::string* result) {
  std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate);
  if (file.is_open()) {
    size_t size = file.tellg();
    std::vector<char> buffer(size);
    file.seekg (0, std::ios::beg);
    file.read(buffer.data(), size);
    file.close();
    if (!file) return false;  // file reading error (failbit or badbit).
    result->assign(buffer.begin(), buffer.end());
    return true;
  }
  return false;
}

void ShowHelp(int argc, char** argv) {
    std::cerr << "Shows whether the given user_agent and URI combination"
              << " is allowed or disallowed by the given robots.txt file. "
              << std::endl << std::endl;
    std::cerr << "Usage: " << std::endl << "  " << argv[0]
              << " <robots.txt filename> <user_agent> <URI>"
              << std::endl << std::endl;
    std::cerr << "The URI must be %-encoded according to RFC3986."
              << std::endl << std::endl;
    std::cerr << "Example: " << std::endl
              << "  " << argv[0] << " robots.txt FooBot http://example.com/foo"
              << std::endl;
}

int main(int argc, char** argv) {
  std::string filename = argc >= 2 ? argv[1] : "";
  if (filename == "-h" || filename == "-help" || filename == "--help") {
    ShowHelp(argc, argv);
    return 0;
  }
  if (argc != 4) {
    std::cerr << "Invalid amount of arguments. Showing help."
              << std::endl << std::endl;
    ShowHelp(argc, argv);
    return 1;
  }
  std::string robots_content;
  if (!(LoadFile(filename, &robots_content))) {
    std::cerr << "failed to read file \"" << filename << "\"" << std::endl;
    return 1;
  }

  std::string user_agent = argv[2];
  std::vector<std::string> user_agents(1, user_agent);
  googlebot::RobotsMatcher matcher;
  std::string url = argv[3];
  bool allowed = matcher.AllowedByRobots(robots_content, &user_agents, url);

  std::cout << "user-agent '" << user_agent << "' with URI '" << argv[3]
            << "': " << (allowed ? "ALLOWED" : "DISALLOWED") << std::endl;
  if (robots_content.empty()) {
    std::cout << "notice: robots file is empty so all user-agents are allowed"
              << std::endl;
  }
}
<commit_msg>Remove whitespace in method call<commit_after>// Copyright 2019 Google LLC
//
// 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
//
//     https://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.
//
// -----------------------------------------------------------------------------
// File: robots_main.cc
// -----------------------------------------------------------------------------
//
// Simple binary to assess whether a URL is accessible to a user-agent according
// to records found in a local robots.txt file, based on Google's robots.txt
// parsing and matching algorithms.
// Usage:
//     robots_main <local_path_to_robotstxt> <user_agent> <url>
// Arguments:
// local_path_to_robotstxt: local path to a file containing robots.txt records.
//   For example: /home/users/username/robots.txt
// user_agent: a token to be matched against records in the robots.txt.
//   For example: Googlebot
// url: a url to be matched against records in the robots.txt. The URL must be
// %-encoded according to RFC3986.
//   For example: https://example.com/accessible/url.html
// Returns: Prints a sentence with verdict about whether 'user_agent' is allowed
// to access 'url' based on records in 'local_path_to_robotstxt'.
//
#include <fstream>
#include <iostream>

#include "robots.h"

bool LoadFile(const std::string& filename, std::string* result) {
  std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate);
  if (file.is_open()) {
    size_t size = file.tellg();
    std::vector<char> buffer(size);
    file.seekg(0, std::ios::beg);
    file.read(buffer.data(), size);
    file.close();
    if (!file) return false;  // file reading error (failbit or badbit).
    result->assign(buffer.begin(), buffer.end());
    return true;
  }
  return false;
}

void ShowHelp(int argc, char** argv) {
    std::cerr << "Shows whether the given user_agent and URI combination"
              << " is allowed or disallowed by the given robots.txt file. "
              << std::endl << std::endl;
    std::cerr << "Usage: " << std::endl << "  " << argv[0]
              << " <robots.txt filename> <user_agent> <URI>"
              << std::endl << std::endl;
    std::cerr << "The URI must be %-encoded according to RFC3986."
              << std::endl << std::endl;
    std::cerr << "Example: " << std::endl
              << "  " << argv[0] << " robots.txt FooBot http://example.com/foo"
              << std::endl;
}

int main(int argc, char** argv) {
  std::string filename = argc >= 2 ? argv[1] : "";
  if (filename == "-h" || filename == "-help" || filename == "--help") {
    ShowHelp(argc, argv);
    return 0;
  }
  if (argc != 4) {
    std::cerr << "Invalid amount of arguments. Showing help."
              << std::endl << std::endl;
    ShowHelp(argc, argv);
    return 1;
  }
  std::string robots_content;
  if (!(LoadFile(filename, &robots_content))) {
    std::cerr << "failed to read file \"" << filename << "\"" << std::endl;
    return 1;
  }

  std::string user_agent = argv[2];
  std::vector<std::string> user_agents(1, user_agent);
  googlebot::RobotsMatcher matcher;
  std::string url = argv[3];
  bool allowed = matcher.AllowedByRobots(robots_content, &user_agents, url);

  std::cout << "user-agent '" << user_agent << "' with URI '" << argv[3]
            << "': " << (allowed ? "ALLOWED" : "DISALLOWED") << std::endl;
  if (robots_content.empty()) {
    std::cout << "notice: robots file is empty so all user-agents are allowed"
              << std::endl;
  }
}
<|endoftext|>


<commit_before>//
// Created by michael on 16.02.16.
//

#include <Story/SimpleStoryTemplate.h>

using namespace weave;
using namespace std;

StoryTemplateResult SimpleStoryTemplate::CreateStory(const EntityMap &requiredEntities, const WeaverGraph &,
                                                     const WorldModel &worldModel,
                                                     shared_ptr<RandomStream> randomStream) const {
    auto entities = getValidEntities(requiredEntities, worldModel, randomStream);
    if (entities.empty()) {
        Logger::Fatal("Invalid template call, not all required entities were found!");
    }

    TokenToEntityMap tokenEntityMap;
    StoryTemplateResult result;
    for (uint64_t i = 1; i <= GetRequiredEntities().size(); i++) {
        auto entity = entities[0];
        tokenEntityMap[to_string(i)] = {entity->GetId()};

        if (conditions.count(StoryCondition::OncePerEntity)) {
            MetaData markedData;
            markedData.SetValue(key, 1);
            result.worldActions.emplace_back(WorldActionType::UPDATE, entity, markedData);
        }
    }

    result.tokenMap = createTokenMapping(tokenEntityMap);
    result.rawText = rawText;
    return result;
}

bool SimpleStoryTemplate::IsValid(const EntityMap &requiredEntities, const WeaverGraph &,
                                  const WorldModel &worldModel) const {
    return getValidEntities(requiredEntities, worldModel, make_shared<RandomStream>()).size() > 0;
}

vector<shared_ptr<WorldEntity>> SimpleStoryTemplate::getValidEntities(const EntityMap &entityMap,
                                                                      const WorldModel &worldModel,
                                                                      shared_ptr<RandomStream> randomStream) const {
    vector<shared_ptr<WorldEntity>> result;
    for (string type : GetRequiredEntities()) {
        vector<shared_ptr<WorldEntity>> validEntities;
        auto mapIter = entityMap.find(type);
        if (mapIter == entityMap.end()) {
            return validEntities;
        }

        for (shared_ptr<WorldEntity> entity : mapIter->second) {
            ID id = entity->GetId();
            MetaData metaData = worldModel.GetMetaData(id);

            // check the "once per entity" condition
            if (conditions.count(StoryCondition::OncePerEntity) && metaData.HasValue(key)) {
                continue;
            }

            // check the "without property" condition
            auto iter = conditions.find(StoryCondition::WithoutProperty);
            if (iter != conditions.end() && !iter->second.empty() && metaData.HasValue(iter->second[0])) {
                continue;
            }

            // check the "with property" condition
            iter = conditions.find(StoryCondition::WithProperty);
            if (iter != conditions.end() && !iter->second.empty() && !metaData.HasValue(iter->second[0])) {
                continue;
            }

            // check the "greater than" condition
            iter = conditions.find(StoryCondition::GreaterThan);
            if (iter != conditions.end() && iter->second.size() == 2) {
                string property = iter->second[0];
                int value = atoi(iter->second[1].c_str());
                if (!metaData.HasValue(property) || metaData.GetValue(property) <= value) {
                    continue;
                }
            }

            // check the "smaller than" condition
            iter = conditions.find(StoryCondition::SmallerThan);
            if (iter != conditions.end() && iter->second.size() == 2) {
                string property = iter->second[0];
                int value = atoi(iter->second[1].c_str());
                if (!metaData.HasValue(property) || metaData.GetValue(property) >= value) {
                    continue;
                }
            }
            validEntities.push_back(entity);
        }
        if (validEntities.empty()) {
            return validEntities;
        }
        result.push_back(validEntities[randomStream->GetRandomIndex(validEntities.size())]);
    }
    return result;
}
<commit_msg>fixed a bug when a story requires multiple entities<commit_after>//
// Created by michael on 16.02.16.
//

#include <Story/SimpleStoryTemplate.h>

using namespace weave;
using namespace std;

StoryTemplateResult SimpleStoryTemplate::CreateStory(const EntityMap &requiredEntities, const WeaverGraph &,
                                                     const WorldModel &worldModel,
                                                     shared_ptr<RandomStream> randomStream) const {
    auto entities = getValidEntities(requiredEntities, worldModel, randomStream);
    if (entities.empty()) {
        Logger::Fatal("Invalid template call, not all required entities were found!");
    }

    TokenToEntityMap tokenEntityMap;
    StoryTemplateResult result;
    for (uint64_t i = 1; i <= GetRequiredEntities().size(); i++) {
        auto entity = entities[i - 1];
        tokenEntityMap[to_string(i)] = {entity->GetId()};

        if (conditions.count(StoryCondition::OncePerEntity)) {
            MetaData markedData;
            markedData.SetValue(key, 1);
            result.worldActions.emplace_back(WorldActionType::UPDATE, entity, markedData);
        }
    }

    result.tokenMap = createTokenMapping(tokenEntityMap);
    result.rawText = rawText;
    return result;
}

bool SimpleStoryTemplate::IsValid(const EntityMap &requiredEntities, const WeaverGraph &,
                                  const WorldModel &worldModel) const {
    return getValidEntities(requiredEntities, worldModel, make_shared<RandomStream>()).size() > 0;
}

vector<shared_ptr<WorldEntity>> SimpleStoryTemplate::getValidEntities(const EntityMap &entityMap,
                                                                      const WorldModel &worldModel,
                                                                      shared_ptr<RandomStream> randomStream) const {
    vector<shared_ptr<WorldEntity>> result;
    for (string type : GetRequiredEntities()) {
        vector<shared_ptr<WorldEntity>> validEntities;
        auto mapIter = entityMap.find(type);
        if (mapIter == entityMap.end()) {
            return validEntities;
        }

        for (shared_ptr<WorldEntity> entity : mapIter->second) {
            ID id = entity->GetId();
            MetaData metaData = worldModel.GetMetaData(id);

            // check the "once per entity" condition
            if (conditions.count(StoryCondition::OncePerEntity) && metaData.HasValue(key)) {
                continue;
            }

            // check the "without property" condition
            auto iter = conditions.find(StoryCondition::WithoutProperty);
            if (iter != conditions.end() && !iter->second.empty() && metaData.HasValue(iter->second[0])) {
                continue;
            }

            // check the "with property" condition
            iter = conditions.find(StoryCondition::WithProperty);
            if (iter != conditions.end() && !iter->second.empty() && !metaData.HasValue(iter->second[0])) {
                continue;
            }

            // check the "greater than" condition
            iter = conditions.find(StoryCondition::GreaterThan);
            if (iter != conditions.end() && iter->second.size() == 2) {
                string property = iter->second[0];
                int value = atoi(iter->second[1].c_str());
                if (!metaData.HasValue(property) || metaData.GetValue(property) <= value) {
                    continue;
                }
            }

            // check the "smaller than" condition
            iter = conditions.find(StoryCondition::SmallerThan);
            if (iter != conditions.end() && iter->second.size() == 2) {
                string property = iter->second[0];
                int value = atoi(iter->second[1].c_str());
                if (!metaData.HasValue(property) || metaData.GetValue(property) >= value) {
                    continue;
                }
            }
            validEntities.push_back(entity);
        }
        if (validEntities.empty()) {
            return validEntities;
        }
        result.push_back(validEntities[randomStream->GetRandomIndex(validEntities.size())]);
    }
    return result;
}
<|endoftext|>


<commit_before>#ifndef GUARD_session_hpp
#define GUARD_session_hpp

#include <sqlite3.h>
#include <iostream>

namespace phatbooks
{

class Session
{
public:
	/**
	 * Starts a Phatbooks user session.
	 * Initializes SQLite3 (but does not create database
	 * connection).
	 */
	Session();

	/**
	 * Ends a Phatbooks user session.
	 * Shuts down SQLite3. (It is assumed that there are no
	 * open connections at this point.)
	 */
	~Session();

private:

};

inline Session::Session()
{
	std::clog << "Creating session..." << std::endl;
	sqlite3_initialize();
	std::clog << "SQLite3 has been initialized." << std::endl;
}

inline Session::~Session()
{
	std::clog << "Destroying session..." << std::endl;
	sqlite3_shutdown();
	std::clog << "SQLite3 has been shut down." << std::endl;
}

}  // namespace phatbooks

#endif  // GUARD_session_hpp
<commit_msg>Made Session noncopyable.<commit_after>#ifndef GUARD_session_hpp
#define GUARD_session_hpp

#include <sqlite3.h>
#include <boost/utility.hpp>
#include <iostream>

namespace phatbooks
{

class Session
{
public:
	/**
	 * Starts a Phatbooks user session.
	 * Initializes SQLite3 (but does not create database
	 * connection).
	 */
	Session();

	/**
	 * Ends a Phatbooks user session.
	 * Shuts down SQLite3. (It is assumed that there are no
	 * open connections at this point.)
	 */
	~Session();

private:

};

inline Session::Session()
{
	std::clog << "Creating session..." << std::endl;
	sqlite3_initialize();
	std::clog << "SQLite3 has been initialized." << std::endl;
}

inline Session::~Session()
{
	std::clog << "Destroying session..." << std::endl;
	sqlite3_shutdown();
	std::clog << "SQLite3 has been shut down." << std::endl;
}

}  // namespace phatbooks

#endif  // GUARD_session_hpp
<|endoftext|>


<commit_before>#include "raptor_api.h"
#include "type/pb_converter.h"
#include "boost/date_time/posix_time/posix_time.hpp"
//#include "street_network/street_network_api.h"

namespace navitia { namespace routing { namespace raptor {

std::string iso_string(const nt::Data & d, int date, int hour){
    boost::posix_time::ptime date_time(d.meta.production_date.begin() + boost::gregorian::days(date));
    date_time += boost::posix_time::seconds(hour);
    return boost::posix_time::to_iso_string(date_time);
}

pbnavitia::Response make_pathes(const std::vector<navitia::routing::Path> &paths, const nt::Data & d, streetnetwork::StreetNetwork & worker) {
    pbnavitia::Response pb_response;
    pb_response.set_requested_api(pbnavitia::PLANNER);

    auto temp = worker.get_direct_path();
    pbnavitia::Planner * planner = pb_response.mutable_planner();
    if(paths.size() > 0 || temp.path_items.size() > 0) {
        planner->set_response_type(pbnavitia::ITINERARY_FOUND);
        if(temp.path_items.size() > 0) {
            pbnavitia::Journey * pb_journey = planner->add_journey();
            pb_journey->set_duration(temp.length);
            fill_road_section(temp, d, pb_journey->add_section(), 1);
        }
        for(Path path : paths) {
            DateTime departure_time = DateTime::inf, arrival_time = DateTime::inf;
            pbnavitia::Journey * pb_journey = planner->add_journey();
            pb_journey->set_nb_transfers(path.nb_changes);
            pb_journey->set_requested_date_time(boost::posix_time::to_iso_string(path.request_time));

            // La marche à pied initiale si on avait donné une coordonnée
            if(path.items.size() > 0 && path.items.front().stop_points.size() > 0 && path.items.front().stop_points.size() > 0){
                const auto temp = worker.get_path(path.items.front().stop_points.front());
                if(temp.path_items.size() > 0) {
                    fill_road_section(temp , d, pb_journey->add_section(), 1);
                    departure_time = path.items.front().departure - temp.length/1.38;
                }
            }

            // La partie TC et correspondances
            for(PathItem & item : path.items){
                pbnavitia::Section * pb_section = pb_journey->add_section();
                if(item.type == public_transport){
                    pb_section->set_type(pbnavitia::PUBLIC_TRANSPORT);
                    if( item.vj_idx != type::invalid_idx){ // TODO : réfléchir si ça peut vraiment arriver
                        const type::VehicleJourney & vj = d.pt_data.vehicle_journeys[item.vj_idx];
                        const type::Route & route = d.pt_data.routes[vj.route_idx];
                        const type::Line & line = d.pt_data.lines[route.line_idx];
                        if(line.network_idx != type::invalid_idx)
                            pb_section->set_network(d.pt_data.networks[line.network_idx].name );
                        else
                            pb_section->set_network("");
                        if(vj.mode_idx != type::invalid_idx)
                            pb_section->set_mode(d.pt_data.modes[vj.mode_idx].name);
                        pb_section->set_code(line.code);
                        pb_section->set_headsign(vj.name);
                        pb_section->set_direction(route.name);
                        fill_pb_object(line.idx, d, pb_section->mutable_line());
                    }
                    for(size_t i=0;i<item.stop_points.size();++i){
                        pbnavitia::StopTime * stop_time = pb_section->add_stop_time();
                        auto arr_time = item.arrivals[i];
                        stop_time->set_arrival_date_time(iso_string(d, arr_time.date(), arr_time.hour()));
                        auto dep_time = item.departures[i];
                        stop_time->set_departure_date_time(iso_string(d, dep_time.date(), dep_time.hour()));
                        fill_pb_object(item.stop_points[i], d, stop_time->mutable_stop_point(), 1);
                    }

                    if(item.stop_points.size() >= 2) {
                        fill_pb_placemark(d.pt_data.stop_points[item.stop_points.front()], d, pb_section->mutable_origin());
                        fill_pb_placemark(d.pt_data.stop_points[item.stop_points.back()], d, pb_section->mutable_destination());
                    }
                }

                else {
                    pb_section->set_type(pbnavitia::TRANSFER);
                    pb_section->set_duration(item.departure - item.arrival);
                    fill_pb_placemark(d.pt_data.stop_points[item.stop_points.front()], d, pb_section->mutable_origin());
                    fill_pb_placemark(d.pt_data.stop_points[item.stop_points.back()], d, pb_section->mutable_destination());
                }
                pb_section->set_duration(item.arrival - item.departure);
                if(departure_time == DateTime::inf)
                    departure_time = item.departure;
                arrival_time = item.arrival;
                pb_journey->set_duration(arrival_time - departure_time);
            }

            // La marche à pied finale si on avait donné une coordonnée
            if(path.items.size() > 0 && path.items.back().stop_points.size() > 0 && path.items.back().stop_points.size()>0){
                auto temp = worker.get_path(path.items.back().stop_points.back(), true);
                if(temp.path_items.size() > 0) {
                    fill_road_section(temp, d, pb_journey->add_section(), 1);
                    arrival_time =  arrival_time + temp.length/1.38;
                }
            }
            pb_journey->set_departure_date_time(iso_string(d, departure_time.date(), departure_time.hour()));
            pb_journey->set_arrival_date_time(iso_string(d, arrival_time.date(), arrival_time.hour()));
        }
    } else {
        planner->set_response_type(pbnavitia::NO_SOLUTION);
    }

    return pb_response;
}

std::vector<std::pair<type::idx_t, double> > get_stop_points(const type::EntryPoint &ep, const type::Data & data, streetnetwork::StreetNetwork & worker, bool use_second = false){
    std::vector<std::pair<type::idx_t, double> > result;

    switch(ep.type) {
    case navitia::type::Type_e::eStopArea:
    {
        auto it = data.pt_data.stop_area_map.find(ep.external_code);
        if(it!= data.pt_data.stop_area_map.end()) {
            for(auto spidx : data.pt_data.stop_areas[it->second].stop_point_list) {
                result.push_back(std::make_pair(spidx, 0));
            }
        }
    } break;
    case type::Type_e::eStopPoint: {
        auto it = data.pt_data.stop_point_map.find(ep.external_code);
        if(it != data.pt_data.stop_point_map.end()){
            result.push_back(std::make_pair(data.pt_data.stop_points[it->second].idx, 0));
        }
    } break;
        // AA gestion des adresses
    case type::Type_e::eAddress:
    case type::Type_e::eCoord: {
        result = worker.find_nearest_stop_points(ep.coordinates, data.pt_data.stop_point_proximity_list, 1000, use_second);
    } break;
    default: break;
    }
    return result;
}

pbnavitia::Response make_response(RAPTOR &raptor, const type::EntryPoint &origin, const type::EntryPoint &destination,
                                  const std::vector<std::string> &datetimes_str, bool clockwise,
                                  std::multimap<std::string, std::string> forbidden,
                                  streetnetwork::StreetNetwork & worker) {
    pbnavitia::Response response;
    response.set_requested_api(pbnavitia::PLANNER);

    std::vector<boost::posix_time::ptime> datetimes;
    for(std::string datetime: datetimes_str){
        try {
            boost::posix_time::ptime ptime;
            ptime = boost::posix_time::from_iso_string(datetime);
            if(!raptor.data.meta.production_date.contains(ptime.date())) {
                response.mutable_planner()->set_response_type(pbnavitia::DATE_OUT_OF_BOUNDS);
                response.set_info("Example of invalid date: " + datetime);
                return response;
            }
            datetimes.push_back(ptime);
        } catch(...){
            response.set_error("Impossible to parse date " + datetime);
            return response;
        }
    }
    if(clockwise)
        std::sort(datetimes.begin(), datetimes.end(),
                  [](boost::posix_time::ptime dt1, boost::posix_time::ptime dt2){return dt1 > dt2;});
    else
        std::sort(datetimes.begin(), datetimes.end());

    worker.init();
    auto departures = get_stop_points(origin, raptor.data, worker);
    auto destinations = get_stop_points(destination, raptor.data, worker, true);
    if(departures.size() == 0 && destinations.size() == 0){
        response.mutable_planner()->set_response_type(pbnavitia::NO_ORIGIN_NOR_DESTINATION_POINT);
        return response;
    }

    if(departures.size() == 0){
        response.mutable_planner()->set_response_type(pbnavitia::NO_ORIGIN_POINT);
        return response;
    }

    if(destinations.size() == 0){
        response.mutable_planner()->set_response_type(pbnavitia::NO_DESTINATION_POINT);
        return response;
    }

    std::vector<Path> result;

    DateTime borne;
    if(!clockwise)
        borne = DateTime::min;
    else {
//        std::vector<DateTime> dts;
//        for(boost::posix_time::ptime datetime : datetimes){
//            int day = (datetime.date() - raptor.data.meta.production_date.begin()).days();
//            int time = datetime.time_of_day().total_seconds();
//            dts.push_back(DateTime(day, time));
//        }

//        return make_pathes(raptor.compute_all(departures, destinations, dts, borne), raptor.data, worker);
        borne = DateTime::inf;
    }

    for(boost::posix_time::ptime datetime : datetimes){
        std::vector<Path> tmp;
        int day = (datetime.date() - raptor.data.meta.production_date.begin()).days();
        int time = datetime.time_of_day().total_seconds();

        if(clockwise)
            tmp = raptor.compute_all(departures, destinations, DateTime(day, time), borne, forbidden);
        else
            tmp = raptor.compute_reverse_all(departures, destinations, DateTime(day, time), borne, forbidden);

        // Lorsqu'on demande qu'un seul horaire, on garde tous les résultas
        if(datetimes.size() == 1){
            result = tmp;
            for(auto & path : result){
                path.request_time = datetime;
            }
        } else if(tmp.size() > 0) {
            // Lorsqu'on demande plusieurs horaires, on garde que l'arrivée au plus tôt / départ au plus tard
            tmp.back().request_time = datetime;
            result.push_back(tmp.back());
            borne = tmp.back().items.back().arrival;
        } else // Lorsqu'on demande plusieurs horaires, et qu'il n'y a pas de résultat, on retourne un itinéraire vide
            result.push_back(Path());
    }
    if(clockwise)
        std::reverse(result.begin(), result.end());

    return make_pathes(result, raptor.data, worker);
}

}}}
<commit_msg>raptor api : Le stop_area est affiché dans origin/destination, plus dans chaque stoptime<commit_after>#include "raptor_api.h"
#include "type/pb_converter.h"
#include "boost/date_time/posix_time/posix_time.hpp"
//#include "street_network/street_network_api.h"

namespace navitia { namespace routing { namespace raptor {

std::string iso_string(const nt::Data & d, int date, int hour){
    boost::posix_time::ptime date_time(d.meta.production_date.begin() + boost::gregorian::days(date));
    date_time += boost::posix_time::seconds(hour);
    return boost::posix_time::to_iso_string(date_time);
}

pbnavitia::Response make_pathes(const std::vector<navitia::routing::Path> &paths, const nt::Data & d, streetnetwork::StreetNetwork & worker) {
    pbnavitia::Response pb_response;
    pb_response.set_requested_api(pbnavitia::PLANNER);

    auto temp = worker.get_direct_path();
    pbnavitia::Planner * planner = pb_response.mutable_planner();
    if(paths.size() > 0 || temp.path_items.size() > 0) {
        planner->set_response_type(pbnavitia::ITINERARY_FOUND);
        if(temp.path_items.size() > 0) {
            pbnavitia::Journey * pb_journey = planner->add_journey();
            pb_journey->set_duration(temp.length);
            fill_road_section(temp, d, pb_journey->add_section(), 1);
        }
        for(Path path : paths) {
            DateTime departure_time = DateTime::inf, arrival_time = DateTime::inf;
            pbnavitia::Journey * pb_journey = planner->add_journey();
            pb_journey->set_nb_transfers(path.nb_changes);
            pb_journey->set_requested_date_time(boost::posix_time::to_iso_string(path.request_time));

            // La marche à pied initiale si on avait donné une coordonnée
            if(path.items.size() > 0 && path.items.front().stop_points.size() > 0 && path.items.front().stop_points.size() > 0){
                const auto temp = worker.get_path(path.items.front().stop_points.front());
                if(temp.path_items.size() > 0) {
                    fill_road_section(temp , d, pb_journey->add_section(), 1);
                    departure_time = path.items.front().departure - temp.length/1.38;
                }
            }

            // La partie TC et correspondances
            for(PathItem & item : path.items){
                pbnavitia::Section * pb_section = pb_journey->add_section();
                if(item.type == public_transport){
                    pb_section->set_type(pbnavitia::PUBLIC_TRANSPORT);
                    if( item.vj_idx != type::invalid_idx){ // TODO : réfléchir si ça peut vraiment arriver
                        const type::VehicleJourney & vj = d.pt_data.vehicle_journeys[item.vj_idx];
                        const type::Route & route = d.pt_data.routes[vj.route_idx];
                        const type::Line & line = d.pt_data.lines[route.line_idx];
                        if(line.network_idx != type::invalid_idx)
                            pb_section->set_network(d.pt_data.networks[line.network_idx].name );
                        else
                            pb_section->set_network("");
                        if(vj.mode_idx != type::invalid_idx)
                            pb_section->set_mode(d.pt_data.modes[vj.mode_idx].name);
                        pb_section->set_code(line.code);
                        pb_section->set_headsign(vj.name);
                        pb_section->set_direction(route.name);
                        fill_pb_object(line.idx, d, pb_section->mutable_line());
                    }
                    for(size_t i=0;i<item.stop_points.size();++i){
                        pbnavitia::StopTime * stop_time = pb_section->add_stop_time();
                        auto arr_time = item.arrivals[i];
                        stop_time->set_arrival_date_time(iso_string(d, arr_time.date(), arr_time.hour()));
                        auto dep_time = item.departures[i];
                        stop_time->set_departure_date_time(iso_string(d, dep_time.date(), dep_time.hour()));
                        fill_pb_object(item.stop_points[i], d, stop_time->mutable_stop_point(), 0);
                    }

                    if(item.stop_points.size() >= 2) {
                        fill_pb_placemark(d.pt_data.stop_points[item.stop_points.front()], d, pb_section->mutable_origin(), 1);
                        fill_pb_placemark(d.pt_data.stop_points[item.stop_points.back()], d, pb_section->mutable_destination(), 1);
                    }
                }

                else {
                    pb_section->set_type(pbnavitia::TRANSFER);
                    pb_section->set_duration(item.departure - item.arrival);
                    fill_pb_placemark(d.pt_data.stop_points[item.stop_points.front()], d, pb_section->mutable_origin(), 1);
                    fill_pb_placemark(d.pt_data.stop_points[item.stop_points.back()], d, pb_section->mutable_destination(), 1);
                }
                pb_section->set_duration(item.arrival - item.departure);
                if(departure_time == DateTime::inf)
                    departure_time = item.departure;
                arrival_time = item.arrival;
                pb_journey->set_duration(arrival_time - departure_time);
            }

            // La marche à pied finale si on avait donné une coordonnée
            if(path.items.size() > 0 && path.items.back().stop_points.size() > 0 && path.items.back().stop_points.size()>0){
                auto temp = worker.get_path(path.items.back().stop_points.back(), true);
                if(temp.path_items.size() > 0) {
                    fill_road_section(temp, d, pb_journey->add_section(), 1);
                    arrival_time =  arrival_time + temp.length/1.38;
                }
            }
            pb_journey->set_departure_date_time(iso_string(d, departure_time.date(), departure_time.hour()));
            pb_journey->set_arrival_date_time(iso_string(d, arrival_time.date(), arrival_time.hour()));
        }
    } else {
        planner->set_response_type(pbnavitia::NO_SOLUTION);
    }

    return pb_response;
}

std::vector<std::pair<type::idx_t, double> > get_stop_points(const type::EntryPoint &ep, const type::Data & data, streetnetwork::StreetNetwork & worker, bool use_second = false){
    std::vector<std::pair<type::idx_t, double> > result;

    switch(ep.type) {
    case navitia::type::Type_e::eStopArea:
    {
        auto it = data.pt_data.stop_area_map.find(ep.external_code);
        if(it!= data.pt_data.stop_area_map.end()) {
            for(auto spidx : data.pt_data.stop_areas[it->second].stop_point_list) {
                result.push_back(std::make_pair(spidx, 0));
            }
        }
    } break;
    case type::Type_e::eStopPoint: {
        auto it = data.pt_data.stop_point_map.find(ep.external_code);
        if(it != data.pt_data.stop_point_map.end()){
            result.push_back(std::make_pair(data.pt_data.stop_points[it->second].idx, 0));
        }
    } break;
        // AA gestion des adresses
    case type::Type_e::eAddress:
    case type::Type_e::eCoord: {
        result = worker.find_nearest_stop_points(ep.coordinates, data.pt_data.stop_point_proximity_list, 1000, use_second);
    } break;
    default: break;
    }
    return result;
}

pbnavitia::Response make_response(RAPTOR &raptor, const type::EntryPoint &origin, const type::EntryPoint &destination,
                                  const std::vector<std::string> &datetimes_str, bool clockwise,
                                  std::multimap<std::string, std::string> forbidden,
                                  streetnetwork::StreetNetwork & worker) {
    pbnavitia::Response response;
    response.set_requested_api(pbnavitia::PLANNER);

    std::vector<boost::posix_time::ptime> datetimes;
    for(std::string datetime: datetimes_str){
        try {
            boost::posix_time::ptime ptime;
            ptime = boost::posix_time::from_iso_string(datetime);
            if(!raptor.data.meta.production_date.contains(ptime.date())) {
                response.mutable_planner()->set_response_type(pbnavitia::DATE_OUT_OF_BOUNDS);
                response.set_info("Example of invalid date: " + datetime);
                return response;
            }
            datetimes.push_back(ptime);
        } catch(...){
            response.set_error("Impossible to parse date " + datetime);
            return response;
        }
    }
    if(clockwise)
        std::sort(datetimes.begin(), datetimes.end(),
                  [](boost::posix_time::ptime dt1, boost::posix_time::ptime dt2){return dt1 > dt2;});
    else
        std::sort(datetimes.begin(), datetimes.end());

    worker.init();
    auto departures = get_stop_points(origin, raptor.data, worker);
    auto destinations = get_stop_points(destination, raptor.data, worker, true);
    if(departures.size() == 0 && destinations.size() == 0){
        response.mutable_planner()->set_response_type(pbnavitia::NO_ORIGIN_NOR_DESTINATION_POINT);
        return response;
    }

    if(departures.size() == 0){
        response.mutable_planner()->set_response_type(pbnavitia::NO_ORIGIN_POINT);
        return response;
    }

    if(destinations.size() == 0){
        response.mutable_planner()->set_response_type(pbnavitia::NO_DESTINATION_POINT);
        return response;
    }

    std::vector<Path> result;

    DateTime borne;
    if(!clockwise)
        borne = DateTime::min;
    else {
//        std::vector<DateTime> dts;
//        for(boost::posix_time::ptime datetime : datetimes){
//            int day = (datetime.date() - raptor.data.meta.production_date.begin()).days();
//            int time = datetime.time_of_day().total_seconds();
//            dts.push_back(DateTime(day, time));
//        }

//        return make_pathes(raptor.compute_all(departures, destinations, dts, borne), raptor.data, worker);
        borne = DateTime::inf;
    }

    for(boost::posix_time::ptime datetime : datetimes){
        std::vector<Path> tmp;
        int day = (datetime.date() - raptor.data.meta.production_date.begin()).days();
        int time = datetime.time_of_day().total_seconds();

        if(clockwise)
            tmp = raptor.compute_all(departures, destinations, DateTime(day, time), borne, forbidden);
        else
            tmp = raptor.compute_reverse_all(departures, destinations, DateTime(day, time), borne, forbidden);

        // Lorsqu'on demande qu'un seul horaire, on garde tous les résultas
        if(datetimes.size() == 1){
            result = tmp;
            for(auto & path : result){
                path.request_time = datetime;
            }
        } else if(tmp.size() > 0) {
            // Lorsqu'on demande plusieurs horaires, on garde que l'arrivée au plus tôt / départ au plus tard
            tmp.back().request_time = datetime;
            result.push_back(tmp.back());
            borne = tmp.back().items.back().arrival;
        } else // Lorsqu'on demande plusieurs horaires, et qu'il n'y a pas de résultat, on retourne un itinéraire vide
            result.push_back(Path());
    }
    if(clockwise)
        std::reverse(result.begin(), result.end());

    return make_pathes(result, raptor.data, worker);
}

}}}
<|endoftext|>