<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <sstream>
// Boost
#include <boost/make_shared.hpp>
// StdAir
#include <stdair/basic/BasChronometer.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>
// AirSched
#include <airsched/basic/BasConst_AIRSCHED_Service.hpp>
#include <airsched/factory/FacAIRSCHEDServiceContext.hpp>
#include <airsched/command/Simulator.hpp>
#include <airsched/command/ScheduleParser.hpp>
#include <airsched/command/OnDParser.hpp>
#include <airsched/command/SegmentPathProvider.hpp>
#include <airsched/command/InventoryGenerator.hpp>
#include <airsched/service/AIRSCHED_ServiceContext.hpp>
#include <airsched/AIRSCHED_Service.hpp>

namespace AIRSCHED {

  // ////////////////////////////////////////////////////////////////////
  AIRSCHED_Service::AIRSCHED_Service() : _airschedServiceContext (NULL) {
    assert (false);
  }

  // ////////////////////////////////////////////////////////////////////
  AIRSCHED_Service::AIRSCHED_Service (const AIRSCHED_Service& iService)
    : _airschedServiceContext (NULL) {
    assert (false);
  }

  // ////////////////////////////////////////////////////////////////////
  AIRSCHED_Service::AIRSCHED_Service (const stdair::BasLogParams& iLogParams)
    : _airschedServiceContext (NULL) {

    // Initialise the STDAIR service handler
    stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
      initStdAirService (iLogParams);

    // Initialise the service context
    initServiceContext();

    // Add the StdAir service context to the AirSched service context
    // \note AirSched owns the STDAIR service resources here.
    const bool ownStdairService = true;
    addStdAirService (lSTDAIR_Service_ptr, ownStdairService);

    // Initialise the (remaining of the) context
    initAirschedService();
  }

  // ////////////////////////////////////////////////////////////////////
  AIRSCHED_Service::AIRSCHED_Service (const stdair::BasLogParams& iLogParams,
                                      const stdair::BasDBParams& iDBParams)
    : _airschedServiceContext (NULL) {

    // Initialise the STDAIR service handler
    stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
      initStdAirService (iLogParams, iDBParams);

    // Initialise the STDAIR service handler
    stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
      initStdAirService (iLogParams);

    // Initialise the service context
    initServiceContext();

    // Add the StdAir service context to the AirSched service context
    // \note AirSched owns the STDAIR service resources here.
    const bool ownStdairService = true;
    addStdAirService (lSTDAIR_Service_ptr, ownStdairService);

    // Initialise the (remaining of the) context
    initAirschedService();
  }

  // ////////////////////////////////////////////////////////////////////
  AIRSCHED_Service::
  AIRSCHED_Service (stdair::STDAIR_ServicePtr_T ioSTDAIRServicePtr)
    : _airschedServiceContext (NULL) {

    // Initialise the service context
    initServiceContext();

    // Add the StdAir service context to the AirSched service context.
    // \note AirSched does not own the STDAIR service resources here.
    const bool doesNotOwnStdairService = false;
    addStdAirService (ioSTDAIRServicePtr, doesNotOwnStdairService);

    // Initialise the context
    initAirschedService();
  }

  // ////////////////////////////////////////////////////////////////////
  AIRSCHED_Service::~AIRSCHED_Service() {
    // Delete/Clean all the objects from memory
    finalise();
  }

  // ////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::finalise() {
    assert (_airschedServiceContext != NULL);
    // Reset the (Boost.)Smart pointer pointing on the STDAIR_Service object.
    _airschedServiceContext->reset();
  }

  // //////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::initServiceContext() {
    // Initialise the service context
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      FacAIRSCHEDServiceContext::instance().create();
    _airschedServiceContext = &lAIRSCHED_ServiceContext;
  }

  // ////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::
  addStdAirService (stdair::STDAIR_ServicePtr_T ioSTDAIR_Service_ptr,
                    const bool iOwnStdairService) {

    // Retrieve the AirSched service context
    assert (_airschedServiceContext != NULL);
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;

    // Store the STDAIR service object within the (AirSched) service context
    lAIRSCHED_ServiceContext.setSTDAIR_Service (ioSTDAIR_Service_ptr,
                                                iOwnStdairService);
  }

  // //////////////////////////////////////////////////////////////////////
  stdair::STDAIR_ServicePtr_T AIRSCHED_Service::
  initStdAirService (const stdair::BasLogParams& iLogParams) {

    /**
     * Initialise the STDAIR service handler.
     *
     * \note The (Boost.)Smart Pointer keeps track of the references
     *       on the Service object, and deletes that object when it is
     *       no longer referenced (e.g., at the end of the process).
     */
    stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
      boost::make_shared<stdair::STDAIR_Service> (iLogParams);

    return lSTDAIR_Service_ptr;
  }

  // //////////////////////////////////////////////////////////////////////
  stdair::STDAIR_ServicePtr_T AIRSCHED_Service::
  initStdAirService (const stdair::BasLogParams& iLogParams,
                     const stdair::BasDBParams& iDBParams) {

    /**
     * Initialise the STDAIR service handler.
     *
     * \note The (Boost.)Smart Pointer keeps track of the references
     *       on the Service object, and deletes that object when it is
     *       no longer referenced (e.g., at the end of the process).
     */
    stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
      boost::make_shared<stdair::STDAIR_Service> (iLogParams, iDBParams);

    return lSTDAIR_Service_ptr;
  }

  // ////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::initAirschedService() {
    // Do nothing at this stage. A sample BOM tree may be built by
    // calling the buildSampleBom() method
  }

  // ////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::
  parseAndLoad (const stdair::Filename_T& iScheduleInputFilename) {

    // Retrieve the BOM root object.
    assert (_airschedServiceContext != NULL);
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();
    stdair::BomRoot& lBomRoot = lSTDAIR_Service.getBomRoot();

    // Parse the schedule input file, and generate the Inventories
    stdair::BasChronometer lINVGeneration; lINVGeneration.start();
    ScheduleParser::generateInventories (iScheduleInputFilename, lBomRoot);
    const double lGenerationMeasure = lINVGeneration.elapsed();

    // DEBUG
    STDAIR_LOG_DEBUG ("Inventory generation time: " << lGenerationMeasure);
  }

  // ////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::
  parseAndLoad (const stdair::Filename_T& iScheduleInputFilename,
                const stdair::Filename_T& iODInputFilename) {

    // First, build the airline inventories from the schedule file
    parseAndLoad (iScheduleInputFilename);

    // Retrieve the BOM tree root
    assert (_airschedServiceContext != NULL);
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();
    stdair::BomRoot& lBomRoot = lSTDAIR_Service.getBomRoot();

    // Parse the O&D input file, and generate the O&D periods
    stdair::BasChronometer lOnDGeneration; lOnDGeneration.start();
    OnDParser::generateOnDPeriods (iODInputFilename, lBomRoot);
    const double lGenerationMeasure = lOnDGeneration.elapsed();

    // DEBUG
    STDAIR_LOG_DEBUG ("O&D generation time: " << lGenerationMeasure);
  }

  // //////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::buildSampleBom() {

    // Retrieve the AirSched service context
    if (_airschedServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The AirSched service has "
                                                    "not been initialised");
    }
    assert (_airschedServiceContext != NULL);

    // Retrieve the STDAIR service object from the (AirSched) service context
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM building to the dedicated service
    lSTDAIR_Service.buildSampleBom();
  }

  // ////////////////////////////////////////////////////////////////////
  std::string AIRSCHED_Service::
  jsonExport (const stdair::AirlineCode_T& iAirlineCode,
              const stdair::FlightNumber_T& iFlightNumber,
              const stdair::Date_T& iDepartureDate) const {

    // Retrieve the AirSched service context
    if (_airschedServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The AirSched service "
                                                    "has not been initialised");
    }
    assert (_airschedServiceContext != NULL);

    // Retrieve the StdAir service object from the (AirSched) service context
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();

    // Delegate the JSON export to the dedicated service
    return lSTDAIR_Service.jsonExport (iAirlineCode, iFlightNumber,
                                       iDepartureDate);
  }

  // //////////////////////////////////////////////////////////////////////
  std::string AIRSCHED_Service::csvDisplay() const {

    // Retrieve the AirSched service context
    if (_airschedServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The AirSched service has "
                                                    "not been initialised");
    }
    assert (_airschedServiceContext != NULL);

    // Retrieve the STDAIR service object from the (AirSched) service context
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM building to the dedicated service
    return lSTDAIR_Service.csvDisplay();
  }

  // ////////////////////////////////////////////////////////////////////
  std::string AIRSCHED_Service::
  csvDisplay (const stdair::AirlineCode_T& iAirlineCode,
              const stdair::FlightNumber_T& iFlightNumber,
              const stdair::Date_T& iDepartureDate) const {

    // Retrieve the AirSched service context
    if (_airschedServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The AirSched service has "
                                                    "not been initialised");
    }
    assert (_airschedServiceContext != NULL);

    // Retrieve the STDAIR service object from the (AirSched) service context
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM display to the dedicated service
    return lSTDAIR_Service.csvDisplay (iAirlineCode, iFlightNumber,
                                       iDepartureDate);
  }

  // ////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::simulate() {

    // Retrieve the AirSched service context
    if (_airschedServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The AirSched service has "
                                                    "not been initialised");
    }
    assert (_airschedServiceContext != NULL);

    // Retrieve the BOM tree root
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();
    stdair::BomRoot& lBomRoot = lSTDAIR_Service.getBomRoot();

    // Call the underlying Use Case (command)
    stdair::BasChronometer lSimulateChronometer; lSimulateChronometer.start();
    Simulator::simulate (lBomRoot);
    const double lSimulateMeasure = lSimulateChronometer.elapsed();

    // DEBUG
    STDAIR_LOG_DEBUG ("Simulation: " << lSimulateMeasure << " - "
                      << lAIRSCHED_ServiceContext.display());
  }

  // ////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::
  buildSegmentPathList (stdair::TravelSolutionList_T& ioTravelSolutionList,
			const stdair::BookingRequestStruct& iBookingRequest) {

    if (_airschedServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The AirSched service has "
                                                    "not been initialised");
    }
    assert (_airschedServiceContext != NULL);

    // Retrieve the BOM tree root
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();
    stdair::BomRoot& lBomRoot = lSTDAIR_Service.getBomRoot();

    // Delegate the call to the dedicated command
    stdair::BasChronometer lBuildChronometer; lBuildChronometer.start();
    SegmentPathProvider::buildSegmentPathList (ioTravelSolutionList,
					       lBomRoot, iBookingRequest);
    const double lBuildMeasure = lBuildChronometer.elapsed();

    // DEBUG
    STDAIR_LOG_DEBUG ("Segment-path build: " << lBuildMeasure << " - "
                      << lAIRSCHED_ServiceContext.display());
  }

}
<commit_msg>[Dev] Fixed a merge issue.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <sstream>
// Boost
#include <boost/make_shared.hpp>
// StdAir
#include <stdair/basic/BasChronometer.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>
// AirSched
#include <airsched/basic/BasConst_AIRSCHED_Service.hpp>
#include <airsched/factory/FacAIRSCHEDServiceContext.hpp>
#include <airsched/command/Simulator.hpp>
#include <airsched/command/ScheduleParser.hpp>
#include <airsched/command/OnDParser.hpp>
#include <airsched/command/SegmentPathProvider.hpp>
#include <airsched/command/InventoryGenerator.hpp>
#include <airsched/service/AIRSCHED_ServiceContext.hpp>
#include <airsched/AIRSCHED_Service.hpp>

namespace AIRSCHED {

  // ////////////////////////////////////////////////////////////////////
  AIRSCHED_Service::AIRSCHED_Service() : _airschedServiceContext (NULL) {
    assert (false);
  }

  // ////////////////////////////////////////////////////////////////////
  AIRSCHED_Service::AIRSCHED_Service (const AIRSCHED_Service& iService)
    : _airschedServiceContext (NULL) {
    assert (false);
  }

  // ////////////////////////////////////////////////////////////////////
  AIRSCHED_Service::AIRSCHED_Service (const stdair::BasLogParams& iLogParams)
    : _airschedServiceContext (NULL) {

    // Initialise the STDAIR service handler
    stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
      initStdAirService (iLogParams);

    // Initialise the service context
    initServiceContext();

    // Add the StdAir service context to the AirSched service context
    // \note AirSched owns the STDAIR service resources here.
    const bool ownStdairService = true;
    addStdAirService (lSTDAIR_Service_ptr, ownStdairService);

    // Initialise the (remaining of the) context
    initAirschedService();
  }

  // ////////////////////////////////////////////////////////////////////
  AIRSCHED_Service::AIRSCHED_Service (const stdair::BasLogParams& iLogParams,
                                      const stdair::BasDBParams& iDBParams)
    : _airschedServiceContext (NULL) {

    // Initialise the STDAIR service handler
    stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
      initStdAirService (iLogParams, iDBParams);

    // Initialise the service context
    initServiceContext();

    // Add the StdAir service context to the AirSched service context
    // \note AirSched owns the STDAIR service resources here.
    const bool ownStdairService = true;
    addStdAirService (lSTDAIR_Service_ptr, ownStdairService);

    // Initialise the (remaining of the) context
    initAirschedService();
  }

  // ////////////////////////////////////////////////////////////////////
  AIRSCHED_Service::
  AIRSCHED_Service (stdair::STDAIR_ServicePtr_T ioSTDAIRServicePtr)
    : _airschedServiceContext (NULL) {

    // Initialise the service context
    initServiceContext();

    // Add the StdAir service context to the AirSched service context.
    // \note AirSched does not own the STDAIR service resources here.
    const bool doesNotOwnStdairService = false;
    addStdAirService (ioSTDAIRServicePtr, doesNotOwnStdairService);

    // Initialise the context
    initAirschedService();
  }

  // ////////////////////////////////////////////////////////////////////
  AIRSCHED_Service::~AIRSCHED_Service() {
    // Delete/Clean all the objects from memory
    finalise();
  }

  // ////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::finalise() {
    assert (_airschedServiceContext != NULL);
    // Reset the (Boost.)Smart pointer pointing on the STDAIR_Service object.
    _airschedServiceContext->reset();
  }

  // //////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::initServiceContext() {
    // Initialise the service context
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      FacAIRSCHEDServiceContext::instance().create();
    _airschedServiceContext = &lAIRSCHED_ServiceContext;
  }

  // ////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::
  addStdAirService (stdair::STDAIR_ServicePtr_T ioSTDAIR_Service_ptr,
                    const bool iOwnStdairService) {

    // Retrieve the AirSched service context
    assert (_airschedServiceContext != NULL);
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;

    // Store the STDAIR service object within the (AirSched) service context
    lAIRSCHED_ServiceContext.setSTDAIR_Service (ioSTDAIR_Service_ptr,
                                                iOwnStdairService);
  }

  // //////////////////////////////////////////////////////////////////////
  stdair::STDAIR_ServicePtr_T AIRSCHED_Service::
  initStdAirService (const stdair::BasLogParams& iLogParams) {

    /**
     * Initialise the STDAIR service handler.
     *
     * \note The (Boost.)Smart Pointer keeps track of the references
     *       on the Service object, and deletes that object when it is
     *       no longer referenced (e.g., at the end of the process).
     */
    stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
      boost::make_shared<stdair::STDAIR_Service> (iLogParams);

    return lSTDAIR_Service_ptr;
  }

  // //////////////////////////////////////////////////////////////////////
  stdair::STDAIR_ServicePtr_T AIRSCHED_Service::
  initStdAirService (const stdair::BasLogParams& iLogParams,
                     const stdair::BasDBParams& iDBParams) {

    /**
     * Initialise the STDAIR service handler.
     *
     * \note The (Boost.)Smart Pointer keeps track of the references
     *       on the Service object, and deletes that object when it is
     *       no longer referenced (e.g., at the end of the process).
     */
    stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
      boost::make_shared<stdair::STDAIR_Service> (iLogParams, iDBParams);

    return lSTDAIR_Service_ptr;
  }

  // ////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::initAirschedService() {
    // Do nothing at this stage. A sample BOM tree may be built by
    // calling the buildSampleBom() method
  }

  // ////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::
  parseAndLoad (const stdair::Filename_T& iScheduleInputFilename) {

    // Retrieve the BOM root object.
    assert (_airschedServiceContext != NULL);
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();
    stdair::BomRoot& lBomRoot = lSTDAIR_Service.getBomRoot();

    // Parse the schedule input file, and generate the Inventories
    stdair::BasChronometer lINVGeneration; lINVGeneration.start();
    ScheduleParser::generateInventories (iScheduleInputFilename, lBomRoot);
    const double lGenerationMeasure = lINVGeneration.elapsed();

    // DEBUG
    STDAIR_LOG_DEBUG ("Inventory generation time: " << lGenerationMeasure);
  }

  // ////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::
  parseAndLoad (const stdair::Filename_T& iScheduleInputFilename,
                const stdair::Filename_T& iODInputFilename) {

    // First, build the airline inventories from the schedule file
    parseAndLoad (iScheduleInputFilename);

    // Retrieve the BOM tree root
    assert (_airschedServiceContext != NULL);
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();
    stdair::BomRoot& lBomRoot = lSTDAIR_Service.getBomRoot();

    // Parse the O&D input file, and generate the O&D periods
    stdair::BasChronometer lOnDGeneration; lOnDGeneration.start();
    OnDParser::generateOnDPeriods (iODInputFilename, lBomRoot);
    const double lGenerationMeasure = lOnDGeneration.elapsed();

    // DEBUG
    STDAIR_LOG_DEBUG ("O&D generation time: " << lGenerationMeasure);
  }

  // //////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::buildSampleBom() {

    // Retrieve the AirSched service context
    if (_airschedServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The AirSched service has "
                                                    "not been initialised");
    }
    assert (_airschedServiceContext != NULL);

    // Retrieve the STDAIR service object from the (AirSched) service context
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM building to the dedicated service
    lSTDAIR_Service.buildSampleBom();
  }

  // ////////////////////////////////////////////////////////////////////
  std::string AIRSCHED_Service::
  jsonExport (const stdair::AirlineCode_T& iAirlineCode,
              const stdair::FlightNumber_T& iFlightNumber,
              const stdair::Date_T& iDepartureDate) const {

    // Retrieve the AirSched service context
    if (_airschedServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The AirSched service "
                                                    "has not been initialised");
    }
    assert (_airschedServiceContext != NULL);

    // Retrieve the StdAir service object from the (AirSched) service context
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();

    // Delegate the JSON export to the dedicated service
    return lSTDAIR_Service.jsonExport (iAirlineCode, iFlightNumber,
                                       iDepartureDate);
  }

  // //////////////////////////////////////////////////////////////////////
  std::string AIRSCHED_Service::csvDisplay() const {

    // Retrieve the AirSched service context
    if (_airschedServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The AirSched service has "
                                                    "not been initialised");
    }
    assert (_airschedServiceContext != NULL);

    // Retrieve the STDAIR service object from the (AirSched) service context
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM building to the dedicated service
    return lSTDAIR_Service.csvDisplay();
  }

  // ////////////////////////////////////////////////////////////////////
  std::string AIRSCHED_Service::
  csvDisplay (const stdair::AirlineCode_T& iAirlineCode,
              const stdair::FlightNumber_T& iFlightNumber,
              const stdair::Date_T& iDepartureDate) const {

    // Retrieve the AirSched service context
    if (_airschedServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The AirSched service has "
                                                    "not been initialised");
    }
    assert (_airschedServiceContext != NULL);

    // Retrieve the STDAIR service object from the (AirSched) service context
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM display to the dedicated service
    return lSTDAIR_Service.csvDisplay (iAirlineCode, iFlightNumber,
                                       iDepartureDate);
  }

  // ////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::simulate() {

    // Retrieve the AirSched service context
    if (_airschedServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The AirSched service has "
                                                    "not been initialised");
    }
    assert (_airschedServiceContext != NULL);

    // Retrieve the BOM tree root
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();
    stdair::BomRoot& lBomRoot = lSTDAIR_Service.getBomRoot();

    // Call the underlying Use Case (command)
    stdair::BasChronometer lSimulateChronometer; lSimulateChronometer.start();
    Simulator::simulate (lBomRoot);
    const double lSimulateMeasure = lSimulateChronometer.elapsed();

    // DEBUG
    STDAIR_LOG_DEBUG ("Simulation: " << lSimulateMeasure << " - "
                      << lAIRSCHED_ServiceContext.display());
  }

  // ////////////////////////////////////////////////////////////////////
  void AIRSCHED_Service::
  buildSegmentPathList (stdair::TravelSolutionList_T& ioTravelSolutionList,
			const stdair::BookingRequestStruct& iBookingRequest) {

    if (_airschedServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The AirSched service has "
                                                    "not been initialised");
    }
    assert (_airschedServiceContext != NULL);

    // Retrieve the BOM tree root
    AIRSCHED_ServiceContext& lAIRSCHED_ServiceContext =
      *_airschedServiceContext;
    stdair::STDAIR_Service& lSTDAIR_Service =
      lAIRSCHED_ServiceContext.getSTDAIR_Service();
    stdair::BomRoot& lBomRoot = lSTDAIR_Service.getBomRoot();

    // Delegate the call to the dedicated command
    stdair::BasChronometer lBuildChronometer; lBuildChronometer.start();
    SegmentPathProvider::buildSegmentPathList (ioTravelSolutionList,
					       lBomRoot, iBookingRequest);
    const double lBuildMeasure = lBuildChronometer.elapsed();

    // DEBUG
    STDAIR_LOG_DEBUG ("Segment-path build: " << lBuildMeasure << " - "
                      << lAIRSCHED_ServiceContext.display());
  }

}
<|endoftext|>


<commit_before>#include "HPACK.h"
#include "hpack_table.h"
#include "gtest/gtest.h"
#include <string.h>
#include "picojson/picojson.h"
#include <fstream>
#include <iostream>
#include <iterator>

TEST(encode_intTest, NormalTest) {
    uint8_t dst[10];
    uint8_t expect[][5] = {
        {0x01, 0x00},
        {0x0f, 0x01},
        //{0x1f, 0xa1, 0x8d, 0xb7, 0x01},
    };
    uint64_t len = encode_int(dst, 1, 1);
    EXPECT_EQ(2, len);
    EXPECT_TRUE(0 == std::memcmp(dst, expect[0], len));
    len = encode_int(dst, 16, 4);
    EXPECT_EQ(2, len);
    EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));
    /*
      len = encode_int(dst, 3000000, 5);
      EXPECT_EQ(5, len);
      EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));
    */
}

TEST(decode_intTest, NormalTest) {
    uint32_t dst = 0;
    uint8_t data[][5] = {
        {0x01, 0x00},
        {0x0f, 0x01},
    };
    EXPECT_EQ(1, decode_int(data[0], 1));
    EXPECT_EQ(16, decode_int(data[1], 4));
}

const static std::string TestCases[] = {
    "hpack-test-case/haskell-http2-naive/",
    "hpack-test-case/haskell-http2-naive-huffman/",
    "hpack-test-case/haskell-http2-static/",
    "hpack-test-case/haskell-http2-static-huffman/",
    "hpack-test-case/haskell-http2-linear/",
    "hpack-test-case/haskell-http2-linear-huffman/",
};

const static std::string out_tmp_file = "filename.txt";

bool
read_json_files(std::vector<std::string> &jsons, const std::string testcase) {
    std::string call_str = "ls " + testcase + " > " + out_tmp_file;
    int len = call_str.length();
    char call[70];
    memcpy(call, call_str.c_str(), len+1);
    system(call);
    std::ifstream fnames(out_tmp_file);
    if (fnames.fail()) {
        std::cerr  << "fail to open" << out_tmp_file << std::endl;
        return false;
    }

    std::string field;
    while (std::getline(fnames, field)) {
        jsons.push_back(field);
    }

    return true;
}

bool
read_json_as_pico(picojson::value& v, const std::string path) {
    std::ifstream ifs(path);

    if (ifs.fail()) {
        std::cerr  << "fail to open" << std::endl;
        return false;
    }
    std::string str((std::istreambuf_iterator<char>(ifs)),
                    std::istreambuf_iterator<char>());
    std::string err = picojson::parse(v, str);
    if (! err.empty()) {
        std::cerr << err << std::endl;
        return false;
    }
    return true;
}

bool
read_header_wire(std::vector<header>& ans_headers, std::string& wire, picojson::array::iterator it_seqno) {
    picojson::object obj_in = it_seqno->get<picojson::object>();
    wire = obj_in["wire"].to_str();
    picojson::array json_headers = obj_in["headers"].get<picojson::array>();
    picojson::array::iterator it_headers;

    for (it_headers = json_headers.begin(); it_headers != json_headers.end(); it_headers++) {
        picojson::object content = it_headers->get<picojson::object>();
        picojson::object::iterator it = content.begin();
        ans_headers.push_back(header(it->first, it->second.to_str()));
    }
    return true;
}

bool
wire2byte(uint8_t *wire_byte, const std::string wire) {
    int len = wire.length();
    for (int i = 0; i < len; i += 2) {
        *(wire_byte+i/2) = (uint8_t)std::stoi(wire.substr(i, 2).c_str(), nullptr, 16);
    }
    return true;
}

void
detect_testcase_type(bool &from_header, bool &from_static,
                     bool &is_huffman,const std::string testcase) {
    from_header = std::string::npos != testcase.find("linear", 0);
    from_static = from_header || std::string::npos != testcase.find("static", 0);
    is_huffman = std::string::npos != testcase.find("huffman", 0);
}

void
print_wire_byte(const uint8_t* expect, uint64_t e_len, const uint8_t* actual, uint64_t a_len) {
    std::cout << "Expect" << std::endl;
    for (int i = 0; i < e_len; i++) {
        printf("%02x", *(expect+i));
    }
    std::cout << std::endl;
    std::cout << "Actual" << std::endl;
    for (int i = 0; i < a_len; i++) {
        printf("%02x", *(actual+i));
    }
    std::cout << std::endl << std::endl;
}

TEST(encodeTest, NormalTest) {
    for (const std::string testcase : TestCases) {
        std::vector<std::string> jsons;
        bool err = read_json_files(jsons, testcase);
        if (!err) {
        }

        bool from_header, from_static, is_huffman;
        detect_testcase_type(from_header, from_static, is_huffman, testcase);
        std::cout << testcase << " " << from_header << from_static << is_huffman << std::endl;

        Table* table = new Table();
        for (std::string json_file : jsons) {
            picojson::value v;
            err = read_json_as_pico(v, testcase + json_file);
            if (!err) {
            }

            picojson::object obj = v.get<picojson::object>();
            picojson::array arr = obj["cases"].get<picojson::array>();
            picojson::array::iterator it_seqno = arr.begin();
            for (int seqno; it_seqno != arr.end(); seqno++, it_seqno++) {
                std::string wire;
                std::vector<header> ans_headers;
                err = read_header_wire(ans_headers, wire, it_seqno);
                if (!err) {
                }

                uint8_t dst[20000];
                int64_t len = hpack_encode(dst, ans_headers,from_static,
                                           from_header, is_huffman, table, -1);

                uint8_t *wire_byte = new uint8_t[wire.length()/2];
                err = wire2byte(wire_byte, wire);
                if (!err) {
                }

                int wire_assert = std::memcmp(dst, wire_byte, len);
                if (wire_assert != 0) {
                    std::cout << testcase << json_file << "  seqno: " << seqno << std::endl;
                    print_wire_byte(wire_byte, wire.length()/2, dst, len);
                }
                ASSERT_EQ(wire.length()/2, len);
                ASSERT_TRUE(0 == wire_assert);
                delete [] wire_byte;
            }
        }
        delete table;
    }
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<commit_msg>fix initialization bug<commit_after>#include "HPACK.h"
#include "hpack_table.h"
#include "gtest/gtest.h"
#include <string.h>
#include "picojson/picojson.h"
#include <fstream>
#include <iostream>
#include <iterator>

TEST(encode_intTest, NormalTest) {
    uint8_t dst[10];
    uint8_t expect[][5] = {
        {0x01, 0x00},
        {0x0f, 0x01},
        //{0x1f, 0xa1, 0x8d, 0xb7, 0x01},
    };
    uint64_t len = encode_int(dst, 1, 1);
    EXPECT_EQ(2, len);
    EXPECT_TRUE(0 == std::memcmp(dst, expect[0], len));
    len = encode_int(dst, 16, 4);
    EXPECT_EQ(2, len);
    EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));
    /*
      len = encode_int(dst, 3000000, 5);
      EXPECT_EQ(5, len);
      EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));
    */
}

TEST(decode_intTest, NormalTest) {
    uint32_t dst = 0;
    uint8_t data[][5] = {
        {0x01, 0x00},
        {0x0f, 0x01},
    };
    EXPECT_EQ(1, decode_int(data[0], 1));
    EXPECT_EQ(16, decode_int(data[1], 4));
}

const static std::string TestCases[] = {
    "hpack-test-case/haskell-http2-naive/",
    "hpack-test-case/haskell-http2-naive-huffman/",
    "hpack-test-case/haskell-http2-static/",
    "hpack-test-case/haskell-http2-static-huffman/",
    "hpack-test-case/haskell-http2-linear/",
    "hpack-test-case/haskell-http2-linear-huffman/",
};

const static std::string out_tmp_file = "filename.txt";

bool
read_json_files(std::vector<std::string> &jsons, const std::string testcase) {
    std::string call_str = "ls " + testcase + " > " + out_tmp_file;
    int len = call_str.length();
    char call[70];
    memcpy(call, call_str.c_str(), len+1);
    system(call);
    std::ifstream fnames(out_tmp_file);
    if (fnames.fail()) {
        std::cerr  << "fail to open" << out_tmp_file << std::endl;
        return false;
    }

    std::string field;
    while (std::getline(fnames, field)) {
        jsons.push_back(field);
    }

    return true;
}

bool
read_json_as_pico(picojson::value& v, const std::string path) {
    std::ifstream ifs(path);

    if (ifs.fail()) {
        std::cerr  << "fail to open" << std::endl;
        return false;
    }
    std::string str((std::istreambuf_iterator<char>(ifs)),
                    std::istreambuf_iterator<char>());
    std::string err = picojson::parse(v, str);
    if (! err.empty()) {
        std::cerr << err << std::endl;
        return false;
    }
    return true;
}

bool
read_header_wire(std::vector<header>& ans_headers, std::string& wire, picojson::array::iterator it_seqno) {
    picojson::object obj_in = it_seqno->get<picojson::object>();
    wire = obj_in["wire"].to_str();
    picojson::array json_headers = obj_in["headers"].get<picojson::array>();
    picojson::array::iterator it_headers;

    for (it_headers = json_headers.begin(); it_headers != json_headers.end(); it_headers++) {
        picojson::object content = it_headers->get<picojson::object>();
        picojson::object::iterator it = content.begin();
        ans_headers.push_back(header(it->first, it->second.to_str()));
    }
    return true;
}

bool
wire2byte(uint8_t *wire_byte, const std::string wire) {
    int len = wire.length();
    for (int i = 0; i < len; i += 2) {
        *(wire_byte+i/2) = (uint8_t)std::stoi(wire.substr(i, 2).c_str(), nullptr, 16);
    }
    return true;
}

void
detect_testcase_type(bool &from_header, bool &from_static,
                     bool &is_huffman,const std::string testcase) {
    from_header = std::string::npos != testcase.find("linear", 0);
    from_static = from_header || std::string::npos != testcase.find("static", 0);
    is_huffman = std::string::npos != testcase.find("huffman", 0);
}

void
print_wire_byte(const uint8_t* expect, uint64_t e_len, const uint8_t* actual, uint64_t a_len) {
    std::cout << "Expect" << std::endl;
    for (int i = 0; i < e_len; i++) {
        printf("%02x", *(expect+i));
    }
    std::cout << std::endl;
    std::cout << "Actual" << std::endl;
    for (int i = 0; i < a_len; i++) {
        printf("%02x", *(actual+i));
    }
    std::cout << std::endl << std::endl;
}

TEST(encodeTest, NormalTest) {
    for (const std::string testcase : TestCases) {
        std::vector<std::string> jsons;
        bool err = read_json_files(jsons, testcase);
        if (!err) {
        }

        bool from_header, from_static, is_huffman;
        detect_testcase_type(from_header, from_static, is_huffman, testcase);
        std::cout << testcase << " " << from_header << from_static << is_huffman << std::endl;

        Table* table = new Table();
        for (std::string json_file : jsons) {
            picojson::value v;
            err = read_json_as_pico(v, testcase + json_file);
            if (!err) {
            }

            picojson::object obj = v.get<picojson::object>();
            picojson::array arr = obj["cases"].get<picojson::array>();
            picojson::array::iterator it_seqno = arr.begin();
            for (int seqno = 0; it_seqno != arr.end(); seqno++, it_seqno++) {
                std::string wire;
                std::vector<header> ans_headers;
                err = read_header_wire(ans_headers, wire, it_seqno);
                if (!err) {
                }

                uint8_t dst[20000];
                int64_t len = hpack_encode(dst, ans_headers,from_static,
                                           from_header, is_huffman, table, -1);

                uint8_t *wire_byte = new uint8_t[wire.length()/2];
                err = wire2byte(wire_byte, wire);
                if (!err) {
                }

                int wire_assert = std::memcmp(dst, wire_byte, len);
                if (wire_assert != 0) {
                    std::cout << testcase << json_file << "  seqno: " << seqno << std::endl;
                    print_wire_byte(wire_byte, wire.length()/2, dst, len);
                }
                ASSERT_EQ(wire.length()/2, len);
                ASSERT_TRUE(0 == wire_assert);
                delete [] wire_byte;
            }
        }
        delete table;
    }
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#include "atomic.hh"
#include "percpu.hh"

template<class T>
struct vptr64 {
  typedef u128 __inttype;
  typedef T __ptrtype;
  __inttype _a;

  T ptr() const { return (T) iptr(); }
  u64 iptr() const { return _a & 0xffffffffffffffffULL; }
  u64 v() const { return _a >> 64; }

  vptr64(T p, u64 v) : _a((((u128)v)<<64) | (u64) p) {}
  vptr64(u128 a) : _a(a) {}
};

template<class T>
struct vptr48 {
  typedef u64 __inttype;
  typedef T __ptrtype;
  __inttype _a;

  T ptr() const {
    u64 i = iptr();
    if (i & (1ULL << 47))
      i += 0xffffULL << 48;
    return (T) i;
  }
  u64 iptr() const { return _a & 0xffffffffffffULL; }
  u16 v() const { return _a >> 48; }

  vptr48(T p, u16 v) : _a((((u64)v)<<48) | (((u64)p) & 0xffffffffffffULL)) {}
  vptr48(u64 a) : _a(a) {}
};

template<class VPTR>
class versioned {
 private:
  std::atomic<typename VPTR::__inttype> _a;

 public:
  VPTR load() { return VPTR(_a.load()); }
  bool compare_exchange(const VPTR &expected, typename VPTR::__ptrtype desired) {
    VPTR n(desired, expected.v());
    return cmpxch(&_a, expected._a, n._a);
  }
};

struct run {
  struct run *next;
};

struct kmem {
  char name[MAXNAME];
  u64 size;
  u64 ninit;
  versioned<vptr48<run*>> freelist;
  std::atomic<u64> nfree;

  run* alloc(const char* name);
  void free(run* r);
};

enum {
  slab_stack,
  slab_perf,
  slab_kshared,
  slab_wq,
  slab_userwq,
  slab_type_max
};

extern percpu<kmem, percpu_safety::internal> kmems;
<commit_msg>Implement an allocator class using kalloc<commit_after>#pragma once

#include "atomic.hh"
#include "percpu.hh"

#include <typeinfo>
#include <memory>

template<class T>
struct vptr64 {
  typedef u128 __inttype;
  typedef T __ptrtype;
  __inttype _a;

  T ptr() const { return (T) iptr(); }
  u64 iptr() const { return _a & 0xffffffffffffffffULL; }
  u64 v() const { return _a >> 64; }

  vptr64(T p, u64 v) : _a((((u128)v)<<64) | (u64) p) {}
  vptr64(u128 a) : _a(a) {}
};

template<class T>
struct vptr48 {
  typedef u64 __inttype;
  typedef T __ptrtype;
  __inttype _a;

  T ptr() const {
    u64 i = iptr();
    if (i & (1ULL << 47))
      i += 0xffffULL << 48;
    return (T) i;
  }
  u64 iptr() const { return _a & 0xffffffffffffULL; }
  u16 v() const { return _a >> 48; }

  vptr48(T p, u16 v) : _a((((u64)v)<<48) | (((u64)p) & 0xffffffffffffULL)) {}
  vptr48(u64 a) : _a(a) {}
};

template<class VPTR>
class versioned {
 private:
  std::atomic<typename VPTR::__inttype> _a;

 public:
  VPTR load() { return VPTR(_a.load()); }
  bool compare_exchange(const VPTR &expected, typename VPTR::__ptrtype desired) {
    VPTR n(desired, expected.v());
    return cmpxch(&_a, expected._a, n._a);
  }
};

struct run {
  struct run *next;
};

struct kmem {
  char name[MAXNAME];
  u64 size;
  u64 ninit;
  versioned<vptr48<run*>> freelist;
  std::atomic<u64> nfree;

  run* alloc(const char* name);
  void free(run* r);
};

enum {
  slab_stack,
  slab_perf,
  slab_kshared,
  slab_wq,
  slab_userwq,
  slab_type_max
};

extern percpu<kmem, percpu_safety::internal> kmems;

// std allocator

template<class T>
class allocator_base
{
public:
  typedef std::size_t size_type;
  typedef ptrdiff_t difference_type;
  typedef T* pointer;
  typedef const T* const_pointer;
  typedef T& reference;
  typedef const T& const_reference;
  typedef T value_type;

  pointer
  address(reference x) const noexcept
  {
    return std::addressof(x);
  }

  const_pointer
  address(const_reference x) const noexcept
  {
    return std::addressof(x);
  }

  template<class U, class... Args>
  void
  construct(U* p, Args&&... args)
  {
    ::new((void *)p) U(std::forward<Args>(args)...);
  }

  template <class U>
  void
  destroy(U* p)
  {
    p->~U();
  }
};

// Standard allocator that uses the kernel page allocator.  This
// satisfies both the standard Allocator requirement as well as the
// ZAllocator requirement.
template<class T>
class kalloc_allocator : public allocator_base<T>
{
public:
  template <class U> struct rebind { typedef kalloc_allocator<U> other; };

  kalloc_allocator() = default;
  kalloc_allocator(const kalloc_allocator&) = default;
  template<class U> kalloc_allocator(const kalloc_allocator<U>&) noexcept { }

  T*
  allocate(std::size_t n, const void *hint = 0)
  {
    if (n * sizeof(T) != PGSIZE)
      panic("%s cannot allocate %zu bytes", __PRETTY_FUNCTION__, n * sizeof(T));
    return (T*)kalloc(typeid(T).name());
  }

  void
  deallocate(T* p, std::size_t n)
  {
    if (n * sizeof(T) != PGSIZE)
      panic("%s cannot deallocate %zu bytes", __PRETTY_FUNCTION__,
            n * sizeof(T));
    kfree(p);
  }

  std::size_t
  max_size() const noexcept
  {
    return PGSIZE;
  }

  // ZAllocator methods

  T*
  default_allocate()
  {
    if (sizeof(T) != PGSIZE)
      panic("%s cannot allocate %zu bytes", __PRETTY_FUNCTION__, sizeof(T));

    if (std::has_trivial_default_constructor<T>::value) {
      // A trivial default constructor will zero-initialize
      // everything, so we can short-circuit this by allocating a zero
      // page.
      return (T*)zalloc(typeid(T).name());
    }

    // Fall back to usual allocation and default construction
    T *p = allocate(1);
    try {
      // Unqualified lookup doesn't find declarations in dependent
      // bases.  Hence "this->".
      this->construct(p);
    } catch (...) {
      deallocate(p, 1);
      throw;
    }
    return p;
  }
};
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "res_LegendPosition.hxx"
#include "ChartModelHelper.hxx"
#include "macros.hxx"
#include "LegendHelper.hxx"
#include "ChartModel.hxx"

#include <svtools/controldims.hrc>
#include <com/sun/star/chart2/LegendPosition.hpp>
#include <com/sun/star/chart/ChartLegendExpansion.hpp>

//itemset stuff
#include "chartview/ChartSfxItemIds.hxx"
#include <svl/intitem.hxx>
#include <svl/eitem.hxx>

namespace chart
{

using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;

LegendPositionResources::LegendPositionResources(VclBuilderContainer& rParent)
    : m_xCC() //unused in this scenario
    , m_pCbxShow( NULL ) //unused in this scenario, assumed to be visible
{
    rParent.get(m_pRbtLeft, "left");
    rParent.get(m_pRbtRight, "right");
    rParent.get(m_pRbtTop, "top");
    rParent.get(m_pRbtBottom, "bottom");
    impl_setRadioButtonToggleHdl();
}

LegendPositionResources::LegendPositionResources(VclBuilderContainer& rParent,
    const uno::Reference< uno::XComponentContext >& xCC)
    : m_xCC(xCC)
{
    rParent.get(m_pCbxShow, "show");
    rParent.get(m_pRbtLeft, "left");
    rParent.get(m_pRbtRight, "right");
    rParent.get(m_pRbtTop, "top");
    rParent.get(m_pRbtBottom, "bottom");

    m_pCbxShow->SetToggleHdl( LINK( this, LegendPositionResources, PositionEnableHdl ) );
    impl_setRadioButtonToggleHdl();
}

void LegendPositionResources::impl_setRadioButtonToggleHdl()
{
    m_pRbtLeft->SetToggleHdl( LINK( this, LegendPositionResources, PositionChangeHdl ) );
    m_pRbtTop->SetToggleHdl( LINK( this, LegendPositionResources, PositionChangeHdl ) );
    m_pRbtRight->SetToggleHdl( LINK( this, LegendPositionResources, PositionChangeHdl ) );
    m_pRbtBottom->SetToggleHdl( LINK( this, LegendPositionResources, PositionChangeHdl ) );
}

LegendPositionResources::~LegendPositionResources()
{
}

void LegendPositionResources::writeToResources( const uno::Reference< frame::XModel >& xChartModel )
{
    try
    {
        uno::Reference< XDiagram > xDiagram = ChartModelHelper::findDiagram( xChartModel );
        uno::Reference< beans::XPropertySet > xProp( xDiagram->getLegend(), uno::UNO_QUERY );
        if( xProp.is() )
        {
            //show
            bool bShowLegend = false;
            xProp->getPropertyValue( "Show" ) >>= bShowLegend;
            if (m_pCbxShow)
                m_pCbxShow->Check( bShowLegend );
            PositionEnableHdl(0);

            //position
            chart2::LegendPosition ePos;
            xProp->getPropertyValue( "AnchorPosition" )  >>= ePos;
            switch( ePos )
            {
                case chart2::LegendPosition_LINE_START:
                    m_pRbtLeft->Check();
                    break;
                case chart2::LegendPosition_LINE_END:
                    m_pRbtRight->Check();
                    break;
                case chart2::LegendPosition_PAGE_START:
                    m_pRbtTop->Check();
                    break;
                case chart2::LegendPosition_PAGE_END:
                    m_pRbtBottom->Check();
                    break;

                case chart2::LegendPosition_CUSTOM:
                default:
                    m_pRbtRight->Check();
                    break;
            }
        }
    }
    catch( const uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
}

void LegendPositionResources::writeToModel( const ::com::sun::star::uno::Reference< frame::XModel >& xChartModel ) const
{
    try
    {
        bool bShowLegend = m_pCbxShow && m_pCbxShow->IsChecked();
        ChartModel* pModel = dynamic_cast<ChartModel*>(xChartModel.get());
        uno::Reference< beans::XPropertySet > xProp( LegendHelper::getLegend( *pModel,m_xCC,bShowLegend ), uno::UNO_QUERY );
        if( xProp.is() )
        {
            //show
            xProp->setPropertyValue( "Show" , uno::makeAny( bShowLegend ));

            //position
            chart2::LegendPosition eNewPos;
            ::com::sun::star::chart::ChartLegendExpansion eExp = ::com::sun::star::chart::ChartLegendExpansion_HIGH;

            if( m_pRbtLeft->IsChecked() )
                eNewPos = chart2::LegendPosition_LINE_START;
            else if( m_pRbtRight->IsChecked() )
            {
                eNewPos = chart2::LegendPosition_LINE_END;
            }
            else if( m_pRbtTop->IsChecked() )
            {
                eNewPos = chart2::LegendPosition_PAGE_START;
                eExp = ::com::sun::star::chart::ChartLegendExpansion_WIDE;
            }
            else if( m_pRbtBottom->IsChecked() )
            {
                eNewPos = chart2::LegendPosition_PAGE_END;
                eExp = ::com::sun::star::chart::ChartLegendExpansion_WIDE;
            }

            xProp->setPropertyValue( "AnchorPosition" , uno::makeAny( eNewPos ));
            xProp->setPropertyValue( "Expansion" , uno::makeAny( eExp ));
            xProp->setPropertyValue( "RelativePosition" , uno::Any());
        }
    }
    catch( const uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
}

IMPL_LINK_NOARG(LegendPositionResources, PositionEnableHdl)
{
    bool bEnable = m_pCbxShow ? m_pCbxShow->IsChecked() : true;

    m_pRbtLeft->Enable( bEnable );
    m_pRbtTop->Enable( bEnable );
    m_pRbtRight->Enable( bEnable );
    m_pRbtBottom->Enable( bEnable );

    m_aChangeLink.Call(NULL);

    return 0;
}

void LegendPositionResources::initFromItemSet( const SfxItemSet& rInAttrs )
{
    const SfxPoolItem* pPoolItem = NULL;
    if( rInAttrs.GetItemState( SCHATTR_LEGEND_POS, true, &pPoolItem ) == SFX_ITEM_SET )
    {
        sal_Int32 nLegendPosition = ((const SfxInt32Item*)pPoolItem)->GetValue();
        switch( nLegendPosition )
        {
            case chart2::LegendPosition_LINE_START:
                m_pRbtLeft->Check(true);
                break;
            case chart2::LegendPosition_PAGE_START:
                m_pRbtTop->Check(true);
                break;
            case chart2::LegendPosition_LINE_END:
                m_pRbtRight->Check(true);
                break;
            case chart2::LegendPosition_PAGE_END:
                m_pRbtBottom->Check(true);
                break;
            default:
                break;
        }
    }

    if( m_pCbxShow && rInAttrs.GetItemState( SCHATTR_LEGEND_SHOW, true, &pPoolItem ) == SFX_ITEM_SET )
    {
        bool bShow = static_cast< const SfxBoolItem * >( pPoolItem )->GetValue();
        m_pCbxShow->Check(bShow);
    }
}

void LegendPositionResources::writeToItemSet( SfxItemSet& rOutAttrs ) const
{
    sal_Int32 nLegendPosition = chart2::LegendPosition_CUSTOM;
    if( m_pRbtLeft->IsChecked() )
        nLegendPosition = chart2::LegendPosition_LINE_START;
    else if( m_pRbtTop->IsChecked() )
        nLegendPosition = chart2::LegendPosition_PAGE_START;
    else if( m_pRbtRight->IsChecked() )
        nLegendPosition = chart2::LegendPosition_LINE_END;
    else if( m_pRbtBottom->IsChecked() )
        nLegendPosition = chart2::LegendPosition_PAGE_END;
    rOutAttrs.Put(SfxInt32Item(SCHATTR_LEGEND_POS, nLegendPosition ));

    rOutAttrs.Put( SfxBoolItem(SCHATTR_LEGEND_SHOW, m_pCbxShow ? m_pCbxShow->IsChecked() : true) );
}

IMPL_LINK( LegendPositionResources, PositionChangeHdl, RadioButton*, pRadio )
{
    //for each radio click ther are coming two change events
    //first uncheck of previous button -> ignore that call
    //the second call gives the check of the new button
    if( pRadio && pRadio->IsChecked() )
        m_aChangeLink.Call(NULL);
    return 0;
}

void LegendPositionResources::SetChangeHdl( const Link& rLink )
{
    m_aChangeLink = rLink;
}

} //namespace chart

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#1158119 Unchecked dynamic_cast<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "res_LegendPosition.hxx"
#include "ChartModelHelper.hxx"
#include "macros.hxx"
#include "LegendHelper.hxx"
#include "ChartModel.hxx"

#include <svtools/controldims.hrc>
#include <com/sun/star/chart2/LegendPosition.hpp>
#include <com/sun/star/chart/ChartLegendExpansion.hpp>

//itemset stuff
#include "chartview/ChartSfxItemIds.hxx"
#include <svl/intitem.hxx>
#include <svl/eitem.hxx>

namespace chart
{

using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;

LegendPositionResources::LegendPositionResources(VclBuilderContainer& rParent)
    : m_xCC() //unused in this scenario
    , m_pCbxShow( NULL ) //unused in this scenario, assumed to be visible
{
    rParent.get(m_pRbtLeft, "left");
    rParent.get(m_pRbtRight, "right");
    rParent.get(m_pRbtTop, "top");
    rParent.get(m_pRbtBottom, "bottom");
    impl_setRadioButtonToggleHdl();
}

LegendPositionResources::LegendPositionResources(VclBuilderContainer& rParent,
    const uno::Reference< uno::XComponentContext >& xCC)
    : m_xCC(xCC)
{
    rParent.get(m_pCbxShow, "show");
    rParent.get(m_pRbtLeft, "left");
    rParent.get(m_pRbtRight, "right");
    rParent.get(m_pRbtTop, "top");
    rParent.get(m_pRbtBottom, "bottom");

    m_pCbxShow->SetToggleHdl( LINK( this, LegendPositionResources, PositionEnableHdl ) );
    impl_setRadioButtonToggleHdl();
}

void LegendPositionResources::impl_setRadioButtonToggleHdl()
{
    m_pRbtLeft->SetToggleHdl( LINK( this, LegendPositionResources, PositionChangeHdl ) );
    m_pRbtTop->SetToggleHdl( LINK( this, LegendPositionResources, PositionChangeHdl ) );
    m_pRbtRight->SetToggleHdl( LINK( this, LegendPositionResources, PositionChangeHdl ) );
    m_pRbtBottom->SetToggleHdl( LINK( this, LegendPositionResources, PositionChangeHdl ) );
}

LegendPositionResources::~LegendPositionResources()
{
}

void LegendPositionResources::writeToResources( const uno::Reference< frame::XModel >& xChartModel )
{
    try
    {
        uno::Reference< XDiagram > xDiagram = ChartModelHelper::findDiagram( xChartModel );
        uno::Reference< beans::XPropertySet > xProp( xDiagram->getLegend(), uno::UNO_QUERY );
        if( xProp.is() )
        {
            //show
            bool bShowLegend = false;
            xProp->getPropertyValue( "Show" ) >>= bShowLegend;
            if (m_pCbxShow)
                m_pCbxShow->Check( bShowLegend );
            PositionEnableHdl(0);

            //position
            chart2::LegendPosition ePos;
            xProp->getPropertyValue( "AnchorPosition" )  >>= ePos;
            switch( ePos )
            {
                case chart2::LegendPosition_LINE_START:
                    m_pRbtLeft->Check();
                    break;
                case chart2::LegendPosition_LINE_END:
                    m_pRbtRight->Check();
                    break;
                case chart2::LegendPosition_PAGE_START:
                    m_pRbtTop->Check();
                    break;
                case chart2::LegendPosition_PAGE_END:
                    m_pRbtBottom->Check();
                    break;

                case chart2::LegendPosition_CUSTOM:
                default:
                    m_pRbtRight->Check();
                    break;
            }
        }
    }
    catch( const uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
}

void LegendPositionResources::writeToModel( const ::com::sun::star::uno::Reference< frame::XModel >& xChartModel ) const
{
    try
    {
        bool bShowLegend = m_pCbxShow && m_pCbxShow->IsChecked();
        ChartModel& rModel = dynamic_cast<ChartModel&>(*xChartModel.get());
        uno::Reference< beans::XPropertySet > xProp(LegendHelper::getLegend(rModel, m_xCC, bShowLegend), uno::UNO_QUERY);
        if( xProp.is() )
        {
            //show
            xProp->setPropertyValue( "Show" , uno::makeAny( bShowLegend ));

            //position
            chart2::LegendPosition eNewPos;
            ::com::sun::star::chart::ChartLegendExpansion eExp = ::com::sun::star::chart::ChartLegendExpansion_HIGH;

            if( m_pRbtLeft->IsChecked() )
                eNewPos = chart2::LegendPosition_LINE_START;
            else if( m_pRbtRight->IsChecked() )
            {
                eNewPos = chart2::LegendPosition_LINE_END;
            }
            else if( m_pRbtTop->IsChecked() )
            {
                eNewPos = chart2::LegendPosition_PAGE_START;
                eExp = ::com::sun::star::chart::ChartLegendExpansion_WIDE;
            }
            else if( m_pRbtBottom->IsChecked() )
            {
                eNewPos = chart2::LegendPosition_PAGE_END;
                eExp = ::com::sun::star::chart::ChartLegendExpansion_WIDE;
            }

            xProp->setPropertyValue( "AnchorPosition" , uno::makeAny( eNewPos ));
            xProp->setPropertyValue( "Expansion" , uno::makeAny( eExp ));
            xProp->setPropertyValue( "RelativePosition" , uno::Any());
        }
    }
    catch( const uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
}

IMPL_LINK_NOARG(LegendPositionResources, PositionEnableHdl)
{
    bool bEnable = m_pCbxShow ? m_pCbxShow->IsChecked() : true;

    m_pRbtLeft->Enable( bEnable );
    m_pRbtTop->Enable( bEnable );
    m_pRbtRight->Enable( bEnable );
    m_pRbtBottom->Enable( bEnable );

    m_aChangeLink.Call(NULL);

    return 0;
}

void LegendPositionResources::initFromItemSet( const SfxItemSet& rInAttrs )
{
    const SfxPoolItem* pPoolItem = NULL;
    if( rInAttrs.GetItemState( SCHATTR_LEGEND_POS, true, &pPoolItem ) == SFX_ITEM_SET )
    {
        sal_Int32 nLegendPosition = ((const SfxInt32Item*)pPoolItem)->GetValue();
        switch( nLegendPosition )
        {
            case chart2::LegendPosition_LINE_START:
                m_pRbtLeft->Check(true);
                break;
            case chart2::LegendPosition_PAGE_START:
                m_pRbtTop->Check(true);
                break;
            case chart2::LegendPosition_LINE_END:
                m_pRbtRight->Check(true);
                break;
            case chart2::LegendPosition_PAGE_END:
                m_pRbtBottom->Check(true);
                break;
            default:
                break;
        }
    }

    if( m_pCbxShow && rInAttrs.GetItemState( SCHATTR_LEGEND_SHOW, true, &pPoolItem ) == SFX_ITEM_SET )
    {
        bool bShow = static_cast< const SfxBoolItem * >( pPoolItem )->GetValue();
        m_pCbxShow->Check(bShow);
    }
}

void LegendPositionResources::writeToItemSet( SfxItemSet& rOutAttrs ) const
{
    sal_Int32 nLegendPosition = chart2::LegendPosition_CUSTOM;
    if( m_pRbtLeft->IsChecked() )
        nLegendPosition = chart2::LegendPosition_LINE_START;
    else if( m_pRbtTop->IsChecked() )
        nLegendPosition = chart2::LegendPosition_PAGE_START;
    else if( m_pRbtRight->IsChecked() )
        nLegendPosition = chart2::LegendPosition_LINE_END;
    else if( m_pRbtBottom->IsChecked() )
        nLegendPosition = chart2::LegendPosition_PAGE_END;
    rOutAttrs.Put(SfxInt32Item(SCHATTR_LEGEND_POS, nLegendPosition ));

    rOutAttrs.Put( SfxBoolItem(SCHATTR_LEGEND_SHOW, m_pCbxShow ? m_pCbxShow->IsChecked() : true) );
}

IMPL_LINK( LegendPositionResources, PositionChangeHdl, RadioButton*, pRadio )
{
    //for each radio click ther are coming two change events
    //first uncheck of previous button -> ignore that call
    //the second call gives the check of the new button
    if( pRadio && pRadio->IsChecked() )
        m_aChangeLink.Call(NULL);
    return 0;
}

void LegendPositionResources::SetChangeHdl( const Link& rLink )
{
    m_aChangeLink = rLink;
}

} //namespace chart

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "supervisor.hpp"

#include <string>
#include <iostream>
#include <map>

#include "family.hpp"
#include "eventdispatcher.hpp"
#include "config.hpp"

#include "daemonize.h"

#include <unistd.h>
#include <iostream>

Supervisor super;

Family * Supervisor::create_family(const std::string & name)
{
	Family * f = new Family(name);
	m_fams[f->name()] = f;
	return f;
}

void Supervisor::autostart()
{
	std::map<std::string, Family *>::iterator it;
	for(it = m_fams.begin(); it != m_fams.end(); it++) {
		it->second->autostart();
	}
}

void Supervisor::shutdown()
{
	std::map<std::string, Family *>::iterator it;
	for(it = m_fams.begin(); it != m_fams.end(); it++) {
		it->second->stop();
	}
}

bool Supervisor::configure(const std::string & var, const std::string & value)
{
	if(var == "logdir") {
		m_logdir = value;
		return true;
	} else if(var == "background") {
		m_background = Config::to_bool(value);
	}
	return false;
}

ConfTarget * Supervisor::confcontext(const std::string & ctx, bool brackets)
{
	std::map<std::string, Family *>::iterator it;
	it = m_fams.find(ctx);
	if(it == m_fams.end() && brackets) {
		return create_family(ctx);
	}
	if(it != m_fams.end())
		return it->second;
	return NULL;
}

int main(int argc, char * argv[])
{
	const char * conffile = "supervisor.conf";
	int daemon = 0;
	int ch;
	while ((ch = getopt(argc, argv, "?hc:D")) != -1) {
		switch (ch) {
			case 'c':
				conffile = optarg;
				break;
			case 'D':
				daemon++;
				break;
			case 'h':
			case '?':
			default:
				std::cout << "Usage: " << argv[0] << " [-h] [-D] [-c /path/to/supervisor.conf]" << std::endl;
				return 0;
		}
	}
	argc -= optind;
	argv += optind;

	config.default_context(&super);
	if(!config.read_file(conffile)) {
		std::cerr << "Can not open config file " << conffile << std::endl;
		return -1;
	}
	if(super.background() || daemon) {
		daemonize();
	}
	super.autostart();
	return disp.run();
}

<commit_msg>'background' config file option fixed<commit_after>#include "supervisor.hpp"

#include <string>
#include <iostream>
#include <map>

#include "family.hpp"
#include "eventdispatcher.hpp"
#include "config.hpp"

#include "daemonize.h"

#include <unistd.h>
#include <iostream>

Supervisor super;

Family * Supervisor::create_family(const std::string & name)
{
	Family * f = new Family(name);
	m_fams[f->name()] = f;
	return f;
}

void Supervisor::autostart()
{
	std::map<std::string, Family *>::iterator it;
	for(it = m_fams.begin(); it != m_fams.end(); it++) {
		it->second->autostart();
	}
}

void Supervisor::shutdown()
{
	std::map<std::string, Family *>::iterator it;
	for(it = m_fams.begin(); it != m_fams.end(); it++) {
		it->second->stop();
	}
}

bool Supervisor::configure(const std::string & var, const std::string & value)
{
	if(var == "logdir") {
		m_logdir = value;
		return true;
	} else if(var == "background") {
		m_background = Config::to_bool(value);
		return true;
	}
	return false;
}

ConfTarget * Supervisor::confcontext(const std::string & ctx, bool brackets)
{
	std::map<std::string, Family *>::iterator it;
	it = m_fams.find(ctx);
	if(it == m_fams.end() && brackets) {
		return create_family(ctx);
	}
	if(it != m_fams.end())
		return it->second;
	return NULL;
}

int main(int argc, char * argv[])
{
	const char * conffile = "supervisor.conf";
	int daemon = 0;
	int ch;
	while ((ch = getopt(argc, argv, "?hc:D")) != -1) {
		switch (ch) {
			case 'c':
				conffile = optarg;
				break;
			case 'D':
				daemon++;
				break;
			case 'h':
			case '?':
			default:
				std::cout << "Usage: " << argv[0] << " [-h] [-D] [-c /path/to/supervisor.conf]" << std::endl;
				return 0;
		}
	}
	argc -= optind;
	argv += optind;

	config.default_context(&super);
	if(!config.read_file(conffile)) {
		std::cerr << "Can not open config file " << conffile << std::endl;
		return -1;
	}
	if(super.background() || daemon) {
		daemonize();
	}
	super.autostart();
	return disp.run();
}

<|endoftext|>


<commit_before><commit_msg>ATO-83: Temporary commit<commit_after><|endoftext|>


<commit_before><commit_msg>GARFIELD +1 test is OK, if long double only<commit_after><|endoftext|>


<commit_before>/* Joey Button
 *
 *
 */

#include <stdio.h>
#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;

const char *win = "video";

void drawCircle( Mat img, Point center )
{
 int thickness = -1;
 int lineType = 8;

 circle( img,
         center,
         32.0,
         Scalar( 0, 0, 255 ),
         thickness,
         lineType );
}

int main()
{
    int cam = 0; // default camera
    VideoCapture cap(cam);
    if (!cap.isOpened()) {
	fprintf(stderr, "cannot open camera %d\n", cam);
	exit(1);
    }

    //namedWindow(win);
    namedWindow(win, 1);
    Mat frame, screen;
    Point pt;

    while (1) {
        cap >> frame;
        cvtColor(frame, screen, CV_LOAD_IMAGE_COLOR);

        pt.x = 500;
        pt.y = 500;

        //This will zero out the entire image, and draw a red circle
        Mat BGRChannels[3];
        split(screen,BGRChannels);                                  // split the BGR channesl
        BGRChannels[1]=Mat::zeros(screen.rows,screen.cols,CV_8UC1); // removing Green channel
        BGRChannels[0]=Mat::zeros(screen.rows,screen.cols,CV_8UC1); // removing Green channel
        BGRChannels[2]=Mat::zeros(screen.rows,screen.cols,CV_8UC1); // removing Green channel
        merge(BGRChannels,3,screen);

        drawCircle(screen,pt);

                            // pack the image

        imshow(win, screen);
        if (waitKey(30) >= 0) // wait up to 30 msec
	    break;
    }

    return 0;
}

/*
    Mat BGRChannels[3];
    split(screen,BGRChannels); // split the BGR channesl
    BGRChannels[1]=Mat::zeros(screen.rows,screen.cols,CV_8UC1);// removing Green channel
    merge(BGRChannels,3,screen); // pack the image

    waitKey(0);
*/
<commit_msg>Here is the ball with gravity<commit_after>/* Joey Button
 *
 *
 */

#include <stdio.h>
#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;

const char *win = "video";

void drawCircle( Mat img, Point center )
{
 int thickness = -1;
 int lineType = 8;

 circle( img,
         center,
         32.0,
         Scalar( 0, 0, 255 ),
         thickness,
         lineType );
}

int main()
{
    int cam = 0; // default camera
    VideoCapture cap(cam);
    if (!cap.isOpened()) {
	fprintf(stderr, "cannot open camera %d\n", cam);
	exit(1);
    }

    //namedWindow(win);
    namedWindow(win, 1);
    Mat frame, screen;
    Point pt;
    pt.x = 500;
    pt.y = 0;
    int momentumY = 10;
    int momentumX = 0;

    while (1) {
        cap >> frame;
        cvtColor(frame, screen, CV_LOAD_IMAGE_COLOR);

        pt.x += momentumX;
        pt.y += momentumY;

        if(pt.y<990){
          momentumY += 1;
        }else {
          momentumY = -(momentumY/2);
        }
        if (momentumY*momentumY <= 49 && pt.y > 990){
          momentumY =0;
        }

        //This will zero out the entire image, and draw a red circle

        Mat BGRChannels[3];
        split(screen,BGRChannels);                                  // split the BGR channesl
        BGRChannels[1]=Mat::zeros(screen.rows,screen.cols,CV_8UC1); // removing Green channel
        BGRChannels[0]=Mat::zeros(screen.rows,screen.cols,CV_8UC1); // removing Green channel
        BGRChannels[2]=Mat::zeros(screen.rows,screen.cols,CV_8UC1); // removing Green channel
        merge(BGRChannels,3,screen);

        drawCircle(screen,pt);

                            // pack the image

        imshow(win, screen);
        if (waitKey(30) >= 0) // wait up to 30 msec
	    break;
    }

    return 0;
}

/*
    Mat BGRChannels[3];
    split(screen,BGRChannels); // split the BGR channesl
    BGRChannels[1]=Mat::zeros(screen.rows,screen.cols,CV_8UC1);// removing Green channel
    merge(BGRChannels,3,screen); // pack the image

    waitKey(0);
*/
<|endoftext|>


<commit_before>/*
 * Summary: Exceptions for the C++ interface
 *
 * Copy: See Copyright for the status of this software.
 *
 */

/**
 * @file
 * @brief Exception declarations
 */

#ifndef LIBMEMACHED_EXCEPTION_HPP
#define LIBMEMACHED_EXCEPTION_HPP

#include <stdexcept>

namespace memcache
{
  class Exception : public std::runtime_error
  {
  public:
    Exception(const std::string& msg, bool in_errno)
      :
        std::runtime_error(msg),
        errno(in_errno)
    {}

    Exception(const char *msg, bool in_errno)
      :
        std::runtime_error(msg),
        errno(in_errno) {}

    virtual ~Exception() throw() {}

    int getErrno() const
    {
      return errno;
    }

  private:
    int errno;
  };

  class Warning : public Exception
  {
  public:
    Warning(const std::string& msg, bool errno) : Exception(msg, errno) {}
    Warning(const char *msg, bool errno) : Exception(msg, errno) {}
  };

  class Error : public Exception
  {
  public:
    Error(const std::string& msg, bool errno) : Exception(msg, errno) {}
    Error(const char *msg, bool errno) : Exception(msg, errno) {}
    virtual ~Error() throw() {}
  };

} /* namespace libmemcached */

#endif /* LIBMEMACHED_EXCEPTION_HPP */
<commit_msg>Correcting mistake I made in exceptions header file.<commit_after>/*
 * Summary: Exceptions for the C++ interface
 *
 * Copy: See Copyright for the status of this software.
 *
 */

/**
 * @file
 * @brief Exception declarations
 */

#ifndef LIBMEMACHED_EXCEPTION_HPP
#define LIBMEMACHED_EXCEPTION_HPP

#include <stdexcept>

namespace memcache
{
  class Exception : public std::runtime_error
  {
  public:
    Exception(const std::string& msg, bool in_errno)
      :
        std::runtime_error(msg),
        errno(in_errno)
    {}

    Exception(const char *msg, bool in_errno)
      :
        std::runtime_error(msg),
        errno(in_errno) {}

    virtual ~Exception() throw() {}

    int getErrno() const
    {
      return errno;
    }

  private:
    int errno;
  };

  class Warning : public Exception
  {
  public:
    Warning(const std::string& msg, bool in_errno) : Exception(msg, in_errno) {}
    Warning(const char *msg, bool in_errno) : Exception(msg, in_errno) {}
  };

  class Error : public Exception
  {
  public:
    Error(const std::string& msg, bool in_errno) : Exception(msg, in_errno) {}
    Error(const char *msg, bool in_errno) : Exception(msg, in_errno) {}
    virtual ~Error() throw() {}
  };

} /* namespace libmemcached */

#endif /* LIBMEMACHED_EXCEPTION_HPP */
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Roman Votyakov
 */

#include <shogun/lib/config.h>

#ifdef HAVE_EIGEN3

#include <shogun/classifier/GaussianProcessBinaryClassification.h>
#include <shogun/mathematics/eigen3.h>

using namespace shogun;
using namespace Eigen;

CGaussianProcessBinaryClassification::CGaussianProcessBinaryClassification()
	: CGaussianProcessMachine()
{
}

CGaussianProcessBinaryClassification::CGaussianProcessBinaryClassification(CInferenceMethod* method)
	: CGaussianProcessMachine(method)
{
	// set labels
	m_labels=method->get_labels();
}

CGaussianProcessBinaryClassification::~CGaussianProcessBinaryClassification()
{
}

CBinaryLabels* CGaussianProcessBinaryClassification::apply_binary(CFeatures* data)
{
	// check whether given combination of inference method and
	// likelihood function supports classification
	REQUIRE(m_method, "Inference method must be attached\n")
	CLikelihoodModel* lik=m_method->get_model();
	REQUIRE(m_method->supports_binary(), "%s with %s doesn't support classification\n",
			m_method->get_name(), lik->get_name())
	SG_UNREF(lik);

	// if regression data equals to NULL, then apply classification on
	// training features
	if (!data)
		data=m_method->get_features();
	else
		SG_REF(data);

	CBinaryLabels* result=new CBinaryLabels(get_mean_vector(data));
	SG_UNREF(data);

	return result;
}

bool CGaussianProcessBinaryClassification::train_machine(CFeatures* data)
{
	// check whether given combination of inference method and
	// likelihood function supports classification
	REQUIRE(m_method, "Inference method must be attached\n")
	CLikelihoodModel* lik=m_method->get_model();
	REQUIRE(m_method->supports_binary(), "%s with %s doesn't support classification\n",
			m_method->get_name(), lik->get_name())
	SG_UNREF(lik);

	if (data)
		m_method->set_features(data);

	// perform inference
	m_method->update_all();

	return true;
}

SGVector<float64_t> CGaussianProcessBinaryClassification::get_mean_vector(CFeatures* data)
{
	// check whether given combination of inference method and
	// likelihood function supports classification
	REQUIRE(m_method, "Inference method must be attached\n")
	CLikelihoodModel* lik=m_method->get_model();
	REQUIRE(m_method->supports_binary(), "%s with %s doesn't support classification\n",
			m_method->get_name(), lik->get_name())

	SG_REF(data);
	SGVector<float64_t> mu=get_posterior_means(data);
	SGVector<float64_t> s2=get_posterior_variances(data);
	SG_UNREF(data);

	// evaluate mean
	mu=lik->evaluate_means(mu, s2);
	SG_UNREF(lik);

	return mu;
}

SGVector<float64_t> CGaussianProcessBinaryClassification::get_variance_vector(CFeatures* data)
{
	// check whether given combination of inference method and
	// likelihood function supports classification
	REQUIRE(m_method, "Inference method must be attached\n")
	CLikelihoodModel* lik=m_method->get_model();
	REQUIRE(m_method->supports_binary(), "%s with %s doesn't support classification\n",
			m_method->get_name(), lik->get_name())

	SG_REF(data);
	SGVector<float64_t> mu=get_posterior_means(data);
	SGVector<float64_t> s2=get_posterior_variances(data);
	SG_UNREF(data);

	// evaluate variance
	s2=lik->evaluate_variances(mu, s2);
	SG_UNREF(lik);

	return s2;
}

SGVector<float64_t> CGaussianProcessBinaryClassification::get_probabilities(CFeatures* data)
{
	// check whether given combination of inference method and
	// likelihood function supports classification
	REQUIRE(m_method, "Inference method must be attached\n")
	CLikelihoodModel* lik=m_method->get_model();
	REQUIRE(m_method->supports_binary(), "%s with %s doesn't support classification\n",
			m_method->get_name(), lik->get_name())

	SG_REF(data);
	SGVector<float64_t> mu=get_posterior_means(data);
	SGVector<float64_t> s2=get_posterior_variances(data);
	SG_UNREF(data);

	// evaluate log probabilities
	SGVector<float64_t> p=lik->evaluate_log_probabilities(mu, s2);
	SG_UNREF(lik);

	// evaluate probabilities
	Map<VectorXd> eigen_p(p.vector, p.vlen);
	eigen_p=eigen_p.array().exp();

	return p;
}

#endif /* HAVE_EIGEN3 */
<commit_msg>replace eigen3 exp() call with shogun exp() call<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Roman Votyakov
 */

#include <shogun/lib/config.h>

#ifdef HAVE_EIGEN3

#include <shogun/classifier/GaussianProcessBinaryClassification.h>

using namespace shogun;

CGaussianProcessBinaryClassification::CGaussianProcessBinaryClassification()
	: CGaussianProcessMachine()
{
}

CGaussianProcessBinaryClassification::CGaussianProcessBinaryClassification(CInferenceMethod* method)
	: CGaussianProcessMachine(method)
{
	// set labels
	m_labels=method->get_labels();
}

CGaussianProcessBinaryClassification::~CGaussianProcessBinaryClassification()
{
}

CBinaryLabels* CGaussianProcessBinaryClassification::apply_binary(CFeatures* data)
{
	// check whether given combination of inference method and
	// likelihood function supports classification
	REQUIRE(m_method, "Inference method must be attached\n")
	CLikelihoodModel* lik=m_method->get_model();
	REQUIRE(m_method->supports_binary(), "%s with %s doesn't support classification\n",
			m_method->get_name(), lik->get_name())
	SG_UNREF(lik);

	// if regression data equals to NULL, then apply classification on
	// training features
	if (!data)
		data=m_method->get_features();
	else
		SG_REF(data);

	CBinaryLabels* result=new CBinaryLabels(get_mean_vector(data));
	SG_UNREF(data);

	return result;
}

bool CGaussianProcessBinaryClassification::train_machine(CFeatures* data)
{
	// check whether given combination of inference method and
	// likelihood function supports classification
	REQUIRE(m_method, "Inference method must be attached\n")
	CLikelihoodModel* lik=m_method->get_model();
	REQUIRE(m_method->supports_binary(), "%s with %s doesn't support classification\n",
			m_method->get_name(), lik->get_name())
	SG_UNREF(lik);

	if (data)
		m_method->set_features(data);

	// perform inference
	m_method->update_all();

	return true;
}

SGVector<float64_t> CGaussianProcessBinaryClassification::get_mean_vector(CFeatures* data)
{
	// check whether given combination of inference method and
	// likelihood function supports classification
	REQUIRE(m_method, "Inference method must be attached\n")
	CLikelihoodModel* lik=m_method->get_model();
	REQUIRE(m_method->supports_binary(), "%s with %s doesn't support classification\n",
			m_method->get_name(), lik->get_name())

	SG_REF(data);
	SGVector<float64_t> mu=get_posterior_means(data);
	SGVector<float64_t> s2=get_posterior_variances(data);
	SG_UNREF(data);

	// evaluate mean
	mu=lik->evaluate_means(mu, s2);
	SG_UNREF(lik);

	return mu;
}

SGVector<float64_t> CGaussianProcessBinaryClassification::get_variance_vector(CFeatures* data)
{
	// check whether given combination of inference method and
	// likelihood function supports classification
	REQUIRE(m_method, "Inference method must be attached\n")
	CLikelihoodModel* lik=m_method->get_model();
	REQUIRE(m_method->supports_binary(), "%s with %s doesn't support classification\n",
			m_method->get_name(), lik->get_name())

	SG_REF(data);
	SGVector<float64_t> mu=get_posterior_means(data);
	SGVector<float64_t> s2=get_posterior_variances(data);
	SG_UNREF(data);

	// evaluate variance
	s2=lik->evaluate_variances(mu, s2);
	SG_UNREF(lik);

	return s2;
}

SGVector<float64_t> CGaussianProcessBinaryClassification::get_probabilities(CFeatures* data)
{
	// check whether given combination of inference method and
	// likelihood function supports classification
	REQUIRE(m_method, "Inference method must be attached\n")
	CLikelihoodModel* lik=m_method->get_model();
	REQUIRE(m_method->supports_binary(), "%s with %s doesn't support classification\n",
			m_method->get_name(), lik->get_name())

	SG_REF(data);
	SGVector<float64_t> mu=get_posterior_means(data);
	SGVector<float64_t> s2=get_posterior_variances(data);
	SG_UNREF(data);

	// evaluate log probabilities
	SGVector<float64_t> p=lik->evaluate_log_probabilities(mu, s2);
	SG_UNREF(lik);

	// evaluate probabilities
	p.exp();

	return p;
}

#endif /* HAVE_EIGEN3 */
<|endoftext|>


<commit_before>/*
    Copyright (c) 2009 Kevin Ottens <ervin@kde.org>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "statisticsproxymodel.h"

#include "entitytreemodel.h"
#include "collectionutils_p.h"

#include <akonadi/collectionstatistics.h>
#include <akonadi/entitydisplayattribute.h>

#include <kdebug.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kio/global.h>

#include <QtGui/QApplication>
#include <QtGui/QPalette>

using namespace Akonadi;

/**
 * @internal
 */
class StatisticsProxyModel::Private
{
  public:
    Private( StatisticsProxyModel *parent )
      : mParent( parent )
    {
    }

    StatisticsProxyModel *mParent;
};

StatisticsProxyModel::StatisticsProxyModel( QObject *parent )
  : QSortFilterProxyModel( parent ),
    d( new Private( this ) )
{
  setSupportedDragActions( Qt::CopyAction | Qt::MoveAction );
}

StatisticsProxyModel::~StatisticsProxyModel()
{
  delete d;
}

QModelIndex Akonadi::StatisticsProxyModel::index( int row, int column, const QModelIndex & parent ) const
{
    int sourceColumn = column;

    if ( column>=columnCount( parent)-3 ) {
      sourceColumn = 0;
    }

    QModelIndex i = QSortFilterProxyModel::index( row, sourceColumn, parent );
    return createIndex( i.row(), column, i.internalPointer() );
}

QVariant StatisticsProxyModel::data( const QModelIndex & index, int role) const
{
  if ( role == Qt::DisplayRole && index.column()>=columnCount( index.parent() )-3 ) {
    const QModelIndex sourceIndex = mapToSource( index.sibling( index.row(), 0 ) );
    Collection collection = sourceModel()->data( sourceIndex, EntityTreeModel::CollectionRole ).value<Collection>();

    if ( collection.isValid() && collection.statistics().count()>=0 ) {
      if ( index.column() == columnCount( QModelIndex() )-1 ) {
        return KIO::convertSize( (KIO::filesize_t)( collection.statistics().size() ) );
      } else if ( index.column() == columnCount( QModelIndex() )-2 ) {
        return collection.statistics().count();
      } else if ( index.column() == columnCount( QModelIndex() )-3 ) {
        if ( collection.statistics().unreadCount() > 0 ) {
          return collection.statistics().unreadCount();
        } else {
          return QString();
        }
      } else {
        kWarning() << "We shouldn't get there for a column which is not total, unread or size.";
        return QVariant();
      }
    }
  } else if ( role == Qt::TextAlignmentRole && index.column()>=columnCount( index.parent() )-3 ) {
    return Qt::AlignRight;
  }

  return QAbstractProxyModel::data( index, role );
}

QVariant StatisticsProxyModel::headerData( int section, Qt::Orientation orientation, int role) const
{
  if ( orientation == Qt::Horizontal && role == Qt::DisplayRole ) {
    if ( section == columnCount( QModelIndex() )-1 ) {
      return i18n( "Size" );
    } else if ( section == columnCount( QModelIndex() )-2 ) {
      return i18n( "Total" );
    } else if ( section == columnCount( QModelIndex() )-3 ) {
      return i18n( "Unread" );
    }
  }

  return QSortFilterProxyModel::headerData( section, orientation, role );
}

Qt::ItemFlags StatisticsProxyModel::flags( const QModelIndex & index ) const
{
  if ( index.column()>=columnCount( index.parent() )-3 ) {
    return flags( index.sibling( index.row(), 0 ) )
         & ( Qt::ItemIsSelectable | Qt::ItemIsDragEnabled // Allowed flags
           | Qt::ItemIsDropEnabled | Qt::ItemIsEnabled );
  }

  return QSortFilterProxyModel::flags( index );
}

int StatisticsProxyModel::columnCount( const QModelIndex & parent ) const
{
  return sourceModel()->columnCount( mapToSource( parent ) ) + 3;
}

bool StatisticsProxyModel::dropMimeData( const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent )
{
  Q_ASSERT(sourceModel());
  const QModelIndex sourceParent = mapToSource(parent);
  return sourceModel()->dropMimeData(data, action, row, column, sourceParent);
}

QMimeData* StatisticsProxyModel::mimeData( const QModelIndexList & indexes ) const
{
  Q_ASSERT(sourceModel());
  QModelIndexList sourceIndexes;
  foreach(const QModelIndex& index, indexes)
    sourceIndexes << mapToSource(index);
  return sourceModel()->mimeData(sourceIndexes);
}

QStringList StatisticsProxyModel::mimeTypes() const
{
  Q_ASSERT(sourceModel());
  return sourceModel()->mimeTypes();
}

#include "statisticsproxymodel.moc"

<commit_msg>Fix infinite recursion.<commit_after>/*
    Copyright (c) 2009 Kevin Ottens <ervin@kde.org>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "statisticsproxymodel.h"

#include "entitytreemodel.h"
#include "collectionutils_p.h"

#include <akonadi/collectionstatistics.h>
#include <akonadi/entitydisplayattribute.h>

#include <kdebug.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kio/global.h>

#include <QtGui/QApplication>
#include <QtGui/QPalette>

using namespace Akonadi;

/**
 * @internal
 */
class StatisticsProxyModel::Private
{
  public:
    Private( StatisticsProxyModel *parent )
      : mParent( parent )
    {
    }

    StatisticsProxyModel *mParent;
};

StatisticsProxyModel::StatisticsProxyModel( QObject *parent )
  : QSortFilterProxyModel( parent ),
    d( new Private( this ) )
{
  setSupportedDragActions( Qt::CopyAction | Qt::MoveAction );
}

StatisticsProxyModel::~StatisticsProxyModel()
{
  delete d;
}

QModelIndex Akonadi::StatisticsProxyModel::index( int row, int column, const QModelIndex & parent ) const
{
    int sourceColumn = column;

    if ( column>=columnCount( parent)-3 ) {
      sourceColumn = 0;
    }

    QModelIndex i = QSortFilterProxyModel::index( row, sourceColumn, parent );
    return createIndex( i.row(), column, i.internalPointer() );
}

QVariant StatisticsProxyModel::data( const QModelIndex & index, int role) const
{
  if ( role == Qt::DisplayRole && index.column()>=columnCount( index.parent() )-3 ) {
    const QModelIndex sourceIndex = mapToSource( index.sibling( index.row(), 0 ) );
    Collection collection = sourceModel()->data( sourceIndex, EntityTreeModel::CollectionRole ).value<Collection>();

    if ( collection.isValid() && collection.statistics().count()>=0 ) {
      if ( index.column() == columnCount( QModelIndex() )-1 ) {
        return KIO::convertSize( (KIO::filesize_t)( collection.statistics().size() ) );
      } else if ( index.column() == columnCount( QModelIndex() )-2 ) {
        return collection.statistics().count();
      } else if ( index.column() == columnCount( QModelIndex() )-3 ) {
        if ( collection.statistics().unreadCount() > 0 ) {
          return collection.statistics().unreadCount();
        } else {
          return QString();
        }
      } else {
        kWarning() << "We shouldn't get there for a column which is not total, unread or size.";
        return QVariant();
      }
    }
  } else if ( role == Qt::TextAlignmentRole && index.column()>=columnCount( index.parent() )-3 ) {
    return Qt::AlignRight;
  }

  return QAbstractProxyModel::data( index, role );
}

QVariant StatisticsProxyModel::headerData( int section, Qt::Orientation orientation, int role) const
{
  if ( orientation == Qt::Horizontal && role == Qt::DisplayRole ) {
    if ( section == columnCount( QModelIndex() )-1 ) {
      return i18n( "Size" );
    } else if ( section == columnCount( QModelIndex() )-2 ) {
      return i18n( "Total" );
    } else if ( section == columnCount( QModelIndex() )-3 ) {
      return i18n( "Unread" );
    }
  }

  return QSortFilterProxyModel::headerData( section, orientation, role );
}

Qt::ItemFlags StatisticsProxyModel::flags( const QModelIndex & index ) const
{
  if ( index.column()>=columnCount( index.parent() )-3 ) {
    return QSortFilterProxyModel::flags( index.sibling( index.row(), 0 ) )
         & ( Qt::ItemIsSelectable | Qt::ItemIsDragEnabled // Allowed flags
           | Qt::ItemIsDropEnabled | Qt::ItemIsEnabled );
  }

  return QSortFilterProxyModel::flags( index );
}

int StatisticsProxyModel::columnCount( const QModelIndex & parent ) const
{
  return sourceModel()->columnCount( mapToSource( parent ) ) + 3;
}

bool StatisticsProxyModel::dropMimeData( const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent )
{
  Q_ASSERT(sourceModel());
  const QModelIndex sourceParent = mapToSource(parent);
  return sourceModel()->dropMimeData(data, action, row, column, sourceParent);
}

QMimeData* StatisticsProxyModel::mimeData( const QModelIndexList & indexes ) const
{
  Q_ASSERT(sourceModel());
  QModelIndexList sourceIndexes;
  foreach(const QModelIndex& index, indexes)
    sourceIndexes << mapToSource(index);
  return sourceModel()->mimeData(sourceIndexes);
}

QStringList StatisticsProxyModel::mimeTypes() const
{
  Q_ASSERT(sourceModel());
  return sourceModel()->mimeTypes();
}

#include "statisticsproxymodel.moc"

<|endoftext|>