<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <fstream>
#include <string>
#include <vector>
#include <exception>
#include <iomanip>
// StdAir
#include <stdair/stdair_demand_types.hpp>
#include <stdair/basic/ProgressStatusSet.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/SnapshotStruct.hpp>
#include <stdair/bom/CancellationStruct.hpp>
#include <stdair/bom/RMEventStruct.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>
// Distribution
#include <simcrs/SIMCRS_Service.hpp>
// TRADEMGEN
#include <trademgen/TRADEMGEN_Service.hpp>
// TRAVELCCM
#include <travelccm/TRAVELCCM_Service.hpp>
// Airsched
#include <airsched/AIRSCHED_Service.hpp>
// Dsim
#include <dsim/DSIM_Types.hpp>
#include <dsim/command/Simulator.hpp>

namespace DSIM {

  // ////////////////////////////////////////////////////////////////////
  void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                            TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service,
                            TRAVELCCM::TRAVELCCM_Service& ioTRAVELCCM_Service,
                            stdair::STDAIR_Service& ioSTDAIR_Service,
                            const stdair::DemandGenerationMethod& iDemandGenerationMethod,
                            const stdair::ForecastingMethod& iForecastingMethod,
                            const stdair::PartnershipTechnique& iPartnershipTechnique) {

    // DEBUG
    STDAIR_LOG_DEBUG ("The simulation is starting");

    // Retrieve the expected (mean value of the) number of events to be
    // generated
    const stdair::Count_T& lExpectedNbOfEventsToBeGenerated =
      ioTRADEMGEN_Service.getExpectedTotalNumberOfRequestsToBeGenerated();

    /**
       Initialisation step.

Generate the first event for each demand stream.
    */
    const stdair::Count_T& lActualNbOfEventsToBeGenerated =
      ioTRADEMGEN_Service.generateFirstRequests(iDemandGenerationMethod);

    // Initialise the (Boost) progress display object
    //boost::progress_display lProgressDisplay(lActualNbOfEventsToBeGenerated);

    // DEBUG
    STDAIR_LOG_DEBUG ("Expected number of events: "
                      << lExpectedNbOfEventsToBeGenerated << ", actual: "
                      << lActualNbOfEventsToBeGenerated);

    /**
       Main loop.

Pop a request and get its associated type/demand stream.

Generate the next request for the same type/demand stream.

    */
    while (ioTRADEMGEN_Service.isQueueDone() == false) {

      // Get the next event from the event queue
      stdair::EventStruct lEventStruct;
      stdair::ProgressStatusSet lPSS = ioTRADEMGEN_Service.popEvent (lEventStruct);

      // DEBUG
      STDAIR_LOG_DEBUG ("Poped event: '" << lEventStruct.describe() << "'.");

      // Check the event type
      const stdair::EventType::EN_EventType& lEventType =
        lEventStruct.getEventType();

      switch (lEventType) {
      case stdair::EventType::BKG_REQ: playBookingRequest (ioSIMCRS_Service,
                                                           ioTRADEMGEN_Service,
                                                           ioTRAVELCCM_Service,
                                                           lEventStruct,
                                                           lPSS,
                                                           iDemandGenerationMethod,
                                                           iPartnershipTechnique); break;
      case stdair::EventType::CX: playCancellation (ioSIMCRS_Service,
                                                    lEventStruct); break;
      case stdair::EventType::SNAPSHOT: playSnapshotEvent (ioSIMCRS_Service,
                                                           lEventStruct); break;
      case stdair::EventType::RM: playRMEvent (ioSIMCRS_Service,
                                               lEventStruct,
                                               iForecastingMethod,
                                               iPartnershipTechnique); break;
      default: assert (false); break;
      }

      // Update the progress display
      //++lProgressDisplay;
    }

    // DEBUG
    STDAIR_LOG_DEBUG ("The simulation has ended");
  }

  // ////////////////////////////////////////////////////////////////////
  void Simulator::
  playBookingRequest (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                      TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service,
                      TRAVELCCM::TRAVELCCM_Service& ioTRAVELCCM_Service,
                      const stdair::EventStruct& iEventStruct,
                      stdair::ProgressStatusSet& ioPSS,
                      const stdair::DemandGenerationMethod& iDemandGenerationMethod,
                      const stdair::PartnershipTechnique& iPartnershipTechnique) {
    // Extract the corresponding demand/booking request
    const stdair::BookingRequestStruct& lPoppedRequest =
      iEventStruct.getBookingRequest();

    // Check if the request if valid
    const stdair::Date_T& lDepDate = lPoppedRequest.getPreferedDepartureDate();
    const stdair::DateTime_T& lReqTime = lPoppedRequest.getRequestDateTime();
    const stdair::Date_T& lRegDate = lReqTime.date();
    if (lDepDate > lRegDate) {
      // DEBUG
      STDAIR_LOG_DEBUG ("Poped booking request: '" << lPoppedRequest.describe()
                        << "'.");

      // Retrieve the corresponding demand stream
      const stdair::DemandGeneratorKey_T& lDemandStreamKey =
        lPoppedRequest.getDemandGeneratorKey();

      // Assess whether more events should be generated for that demand stream
      const bool stillHavingRequestsToBeGenerated =
        ioTRADEMGEN_Service.stillHavingRequestsToBeGenerated (lDemandStreamKey,
                                                              ioPSS,
                                                              iDemandGenerationMethod);

      // DEBUG
      // STDAIR_LOG_DEBUG ("=> [" << lDemandStreamKey << "] is now processed. "
      //                   << "Still generate events for that demand stream? "
      //                   << stillHavingRequestsToBeGenerated);
      STDAIR_LOG_DEBUG ("Progress status" << ioPSS.describe());

      // If there are still events to be generated for that demand stream,
      // generate and add them to the event queue
      if (stillHavingRequestsToBeGenerated) {
      stdair::BookingRequestPtr_T lNextRequest_ptr =
        ioTRADEMGEN_Service.generateNextRequest (lDemandStreamKey,
                                                 iDemandGenerationMethod);
      assert (lNextRequest_ptr != NULL);

      // Sanity check
      const stdair::Duration_T lDuration =
        lNextRequest_ptr->getRequestDateTime()
        - lPoppedRequest.getRequestDateTime();
        if (lDuration.total_milliseconds() < 0) {
          STDAIR_LOG_NOTIFICATION ("[" << lDemandStreamKey
                                   << "] The date-time of the generated event ("
                                   << lNextRequest_ptr->getRequestDateTime()
                                   << ") is lower than the date-time "
                                   << "of the current event ("
                                   << lPoppedRequest.getRequestDateTime()
                                   << ")");
          assert (false);
        }

        // DEBUG
        // STDAIR_LOG_DEBUG ("[" << lDemandStreamKey << "] Added request: '"
        //                   << lNextRequest_ptr->describe()
        //                   << "'. Is queue done? "
        //                   << ioTRADEMGEN_Service.isQueueDone());
      }

      // Retrieve a list of travel solutions corresponding the given
      // booking request.
      stdair::TravelSolutionList_T lTravelSolutionList =
        ioSIMCRS_Service.calculateSegmentPathList (lPoppedRequest);

      if (lTravelSolutionList.empty() == false) {
        // Get the availability for each travel solution.
        ioSIMCRS_Service.calculateAvailability (lTravelSolutionList, iPartnershipTechnique);

        // Get the fare quote for each travel solution.
        ioSIMCRS_Service.fareQuote (lPoppedRequest, lTravelSolutionList);

        // Get a travel solution choice.
        const stdair::TravelSolutionStruct* lChosenTS_ptr =
          ioTRAVELCCM_Service.chooseTravelSolution (lTravelSolutionList,
                                                    lPoppedRequest);
        if (lChosenTS_ptr != NULL) {
          // DEBUG
          STDAIR_LOG_DEBUG ("Chosen TS: " << lChosenTS_ptr->describe());

          // Retrieve and convert the party size
          const stdair::NbOfSeats_T& lPartySizeDouble =
            lPoppedRequest.getPartySize();
          const stdair::PartySize_T lPartySize = std::floor (lPartySizeDouble);

          // Delegate the sell to the corresponding SimCRS service
          bool saleSucceedful =
            ioSIMCRS_Service.sell (*lChosenTS_ptr, lPartySize);

          // If the sale succeeded, generate the potential cancellation event.
          if (saleSucceedful == true) {
            ioTRADEMGEN_Service.generateCancellation (*lChosenTS_ptr,
                                                      lPartySize, lReqTime,
                                                      lDepDate);
          }

          // LOG
          const stdair::DateTime_T lDepartureDateTime =
            boost::posix_time::ptime (lDepDate, boost::posix_time::hours (0));
          const stdair::Duration_T lDTDRequest = lReqTime - lDepartureDateTime;
          const double lDTD = double(lDTDRequest.total_seconds()) / 86400.0;
          std::ostringstream oStr;
          const stdair::SegmentPath_T& lSegmentPath =
            lChosenTS_ptr->getSegmentPath();
          for (stdair::SegmentPath_T::const_iterator itSegPath =
                 lSegmentPath.begin();
               itSegPath != lSegmentPath.end(); ++itSegPath) {
            oStr << *itSegPath <<  ";";
          }
          STDAIR_LOG_NOTIFICATION (oStr.str() << std::setprecision(10) << lDTD);
        }
        else {
          // DEBUG
          STDAIR_LOG_DEBUG ("There is no chosen travel solution "
                            <<"for this request: "<< lPoppedRequest.describe());
        }
      } else {
        // DEBUG
        STDAIR_LOG_DEBUG ("No travel solution has been found for: "
                          << lPoppedRequest);
      }
    }
  }

  // ////////////////////////////////////////////////////////////////////
  void Simulator::
  playCancellation (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                    const stdair::EventStruct& iEventStruct) {
    // Retrieve the cancellation struct from the event.
    const stdair::CancellationStruct lCancellationStruct =
      iEventStruct.getCancellation();

    // DEBUG
    // STDAIR_LOG_DEBUG ("Play cancellation: "<<lCancellationStruct.describe());

    ioSIMCRS_Service.playCancellation (lCancellationStruct);
  }

  // ////////////////////////////////////////////////////////////////////
  void Simulator::
  playSnapshotEvent (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                     const stdair::EventStruct& iEventStruct) {
    // Retrieve the snapshot struct from the event.
    const stdair::SnapshotStruct lSnapshotStruct =
      iEventStruct.getSnapshotStruct();

    // DEBUG
    // STDAIR_LOG_DEBUG ("Taking snapshots: " << lSnapshotStruct.describe());

    ioSIMCRS_Service.takeSnapshots (lSnapshotStruct);
  }

  // ////////////////////////////////////////////////////////////////////
  void Simulator::
  playRMEvent (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
               const stdair::EventStruct& iEventStruct,
               const stdair::ForecastingMethod& iForecastingMethod,
               const stdair::PartnershipTechnique& iPartnershipTechnique) {
    // Retrieve the RM event struct from the event.
    const stdair::RMEventStruct lRMEvent = iEventStruct.getRMEvent();

    // DEBUG
    STDAIR_LOG_DEBUG ("Running RM system: " << lRMEvent.describe());

    //ioSIMCRS_Service.optimise (lRMEvent, iForecastingMethod, iPartnershipTechnique);
  }
}
<commit_msg>[Dev] Added break point case to avoid an assertion failure (do nothing for now).<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <fstream>
#include <string>
#include <vector>
#include <exception>
#include <iomanip>
// StdAir
#include <stdair/stdair_demand_types.hpp>
#include <stdair/basic/ProgressStatusSet.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/SnapshotStruct.hpp>
#include <stdair/bom/CancellationStruct.hpp>
#include <stdair/bom/RMEventStruct.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>
// Distribution
#include <simcrs/SIMCRS_Service.hpp>
// TRADEMGEN
#include <trademgen/TRADEMGEN_Service.hpp>
// TRAVELCCM
#include <travelccm/TRAVELCCM_Service.hpp>
// Airsched
#include <airsched/AIRSCHED_Service.hpp>
// Dsim
#include <dsim/DSIM_Types.hpp>
#include <dsim/command/Simulator.hpp>

namespace DSIM {

  // ////////////////////////////////////////////////////////////////////
  void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                            TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service,
                            TRAVELCCM::TRAVELCCM_Service& ioTRAVELCCM_Service,
                            stdair::STDAIR_Service& ioSTDAIR_Service,
                            const stdair::DemandGenerationMethod& iDemandGenerationMethod,
                            const stdair::ForecastingMethod& iForecastingMethod,
                            const stdair::PartnershipTechnique& iPartnershipTechnique) {

    // DEBUG
    STDAIR_LOG_DEBUG ("The simulation is starting");

    // Retrieve the expected (mean value of the) number of events to be
    // generated
    const stdair::Count_T& lExpectedNbOfEventsToBeGenerated =
      ioTRADEMGEN_Service.getExpectedTotalNumberOfRequestsToBeGenerated();

    /**
       Initialisation step.

Generate the first event for each demand stream.
    */
    const stdair::Count_T& lActualNbOfEventsToBeGenerated =
      ioTRADEMGEN_Service.generateFirstRequests(iDemandGenerationMethod);

    // Initialise the (Boost) progress display object
    //boost::progress_display lProgressDisplay(lActualNbOfEventsToBeGenerated);

    // DEBUG
    STDAIR_LOG_DEBUG ("Expected number of events: "
                      << lExpectedNbOfEventsToBeGenerated << ", actual: "
                      << lActualNbOfEventsToBeGenerated);

    /**
       Main loop.

Pop a request and get its associated type/demand stream.

Generate the next request for the same type/demand stream.

    */
    while (ioTRADEMGEN_Service.isQueueDone() == false) {

      // Get the next event from the event queue
      stdair::EventStruct lEventStruct;
      stdair::ProgressStatusSet lPSS = ioTRADEMGEN_Service.popEvent (lEventStruct);

      // DEBUG
      STDAIR_LOG_DEBUG ("Poped event: '" << lEventStruct.describe() << "'.");

      // Check the event type
      const stdair::EventType::EN_EventType& lEventType =
        lEventStruct.getEventType();

      switch (lEventType) {
      case stdair::EventType::BKG_REQ: playBookingRequest (ioSIMCRS_Service,
                                                           ioTRADEMGEN_Service,
                                                           ioTRAVELCCM_Service,
                                                           lEventStruct,
                                                           lPSS,
                                                           iDemandGenerationMethod,
                                                           iPartnershipTechnique); break;
      case stdair::EventType::CX: playCancellation (ioSIMCRS_Service,
                                                    lEventStruct); break;
      case stdair::EventType::SNAPSHOT: playSnapshotEvent (ioSIMCRS_Service,
                                                           lEventStruct); break;
      case stdair::EventType::RM: playRMEvent (ioSIMCRS_Service,
                                               lEventStruct,
                                               iForecastingMethod,
                                               iPartnershipTechnique); break;
      case stdair::EventType::BRK_PT: break;
      default: assert (false); break;
      }

      // Update the progress display
      //++lProgressDisplay;
    }

    // DEBUG
    STDAIR_LOG_DEBUG ("The simulation has ended");
  }

  // ////////////////////////////////////////////////////////////////////
  void Simulator::
  playBookingRequest (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                      TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service,
                      TRAVELCCM::TRAVELCCM_Service& ioTRAVELCCM_Service,
                      const stdair::EventStruct& iEventStruct,
                      stdair::ProgressStatusSet& ioPSS,
                      const stdair::DemandGenerationMethod& iDemandGenerationMethod,
                      const stdair::PartnershipTechnique& iPartnershipTechnique) {
    // Extract the corresponding demand/booking request
    const stdair::BookingRequestStruct& lPoppedRequest =
      iEventStruct.getBookingRequest();

    // Check if the request if valid
    const stdair::Date_T& lDepDate = lPoppedRequest.getPreferedDepartureDate();
    const stdair::DateTime_T& lReqTime = lPoppedRequest.getRequestDateTime();
    const stdair::Date_T& lRegDate = lReqTime.date();
    if (lDepDate > lRegDate) {
      // DEBUG
      STDAIR_LOG_DEBUG ("Poped booking request: '" << lPoppedRequest.describe()
                        << "'.");

      // Retrieve the corresponding demand stream
      const stdair::DemandGeneratorKey_T& lDemandStreamKey =
        lPoppedRequest.getDemandGeneratorKey();

      // Assess whether more events should be generated for that demand stream
      const bool stillHavingRequestsToBeGenerated =
        ioTRADEMGEN_Service.stillHavingRequestsToBeGenerated (lDemandStreamKey,
                                                              ioPSS,
                                                              iDemandGenerationMethod);

      // DEBUG
      // STDAIR_LOG_DEBUG ("=> [" << lDemandStreamKey << "] is now processed. "
      //                   << "Still generate events for that demand stream? "
      //                   << stillHavingRequestsToBeGenerated);
      STDAIR_LOG_DEBUG ("Progress status" << ioPSS.describe());

      // If there are still events to be generated for that demand stream,
      // generate and add them to the event queue
      if (stillHavingRequestsToBeGenerated) {
      stdair::BookingRequestPtr_T lNextRequest_ptr =
        ioTRADEMGEN_Service.generateNextRequest (lDemandStreamKey,
                                                 iDemandGenerationMethod);
      assert (lNextRequest_ptr != NULL);

      // Sanity check
      const stdair::Duration_T lDuration =
        lNextRequest_ptr->getRequestDateTime()
        - lPoppedRequest.getRequestDateTime();
        if (lDuration.total_milliseconds() < 0) {
          STDAIR_LOG_NOTIFICATION ("[" << lDemandStreamKey
                                   << "] The date-time of the generated event ("
                                   << lNextRequest_ptr->getRequestDateTime()
                                   << ") is lower than the date-time "
                                   << "of the current event ("
                                   << lPoppedRequest.getRequestDateTime()
                                   << ")");
          assert (false);
        }

        // DEBUG
        // STDAIR_LOG_DEBUG ("[" << lDemandStreamKey << "] Added request: '"
        //                   << lNextRequest_ptr->describe()
        //                   << "'. Is queue done? "
        //                   << ioTRADEMGEN_Service.isQueueDone());
      }

      // Retrieve a list of travel solutions corresponding the given
      // booking request.
      stdair::TravelSolutionList_T lTravelSolutionList =
        ioSIMCRS_Service.calculateSegmentPathList (lPoppedRequest);

      if (lTravelSolutionList.empty() == false) {
        // Get the availability for each travel solution.
        ioSIMCRS_Service.calculateAvailability (lTravelSolutionList, iPartnershipTechnique);

        // Get the fare quote for each travel solution.
        ioSIMCRS_Service.fareQuote (lPoppedRequest, lTravelSolutionList);

        // Get a travel solution choice.
        const stdair::TravelSolutionStruct* lChosenTS_ptr =
          ioTRAVELCCM_Service.chooseTravelSolution (lTravelSolutionList,
                                                    lPoppedRequest);
        if (lChosenTS_ptr != NULL) {
          // DEBUG
          STDAIR_LOG_DEBUG ("Chosen TS: " << lChosenTS_ptr->describe());

          // Retrieve and convert the party size
          const stdair::NbOfSeats_T& lPartySizeDouble =
            lPoppedRequest.getPartySize();
          const stdair::PartySize_T lPartySize = std::floor (lPartySizeDouble);

          // Delegate the sell to the corresponding SimCRS service
          bool saleSucceedful =
            ioSIMCRS_Service.sell (*lChosenTS_ptr, lPartySize);

          // If the sale succeeded, generate the potential cancellation event.
          if (saleSucceedful == true) {
            ioTRADEMGEN_Service.generateCancellation (*lChosenTS_ptr,
                                                      lPartySize, lReqTime,
                                                      lDepDate);
          }

          // LOG
          const stdair::DateTime_T lDepartureDateTime =
            boost::posix_time::ptime (lDepDate, boost::posix_time::hours (0));
          const stdair::Duration_T lDTDRequest = lReqTime - lDepartureDateTime;
          const double lDTD = double(lDTDRequest.total_seconds()) / 86400.0;
          std::ostringstream oStr;
          const stdair::SegmentPath_T& lSegmentPath =
            lChosenTS_ptr->getSegmentPath();
          for (stdair::SegmentPath_T::const_iterator itSegPath =
                 lSegmentPath.begin();
               itSegPath != lSegmentPath.end(); ++itSegPath) {
            oStr << *itSegPath <<  ";";
          }
          STDAIR_LOG_NOTIFICATION (oStr.str() << std::setprecision(10) << lDTD);
        }
        else {
          // DEBUG
          STDAIR_LOG_DEBUG ("There is no chosen travel solution "
                            <<"for this request: "<< lPoppedRequest.describe());
        }
      } else {
        // DEBUG
        STDAIR_LOG_DEBUG ("No travel solution has been found for: "
                          << lPoppedRequest);
      }
    }
  }

  // ////////////////////////////////////////////////////////////////////
  void Simulator::
  playCancellation (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                    const stdair::EventStruct& iEventStruct) {
    // Retrieve the cancellation struct from the event.
    const stdair::CancellationStruct lCancellationStruct =
      iEventStruct.getCancellation();

    // DEBUG
    // STDAIR_LOG_DEBUG ("Play cancellation: "<<lCancellationStruct.describe());

    ioSIMCRS_Service.playCancellation (lCancellationStruct);
  }

  // ////////////////////////////////////////////////////////////////////
  void Simulator::
  playSnapshotEvent (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
                     const stdair::EventStruct& iEventStruct) {
    // Retrieve the snapshot struct from the event.
    const stdair::SnapshotStruct lSnapshotStruct =
      iEventStruct.getSnapshotStruct();

    // DEBUG
    // STDAIR_LOG_DEBUG ("Taking snapshots: " << lSnapshotStruct.describe());

    ioSIMCRS_Service.takeSnapshots (lSnapshotStruct);
  }

  // ////////////////////////////////////////////////////////////////////
  void Simulator::
  playRMEvent (SIMCRS::SIMCRS_Service& ioSIMCRS_Service,
               const stdair::EventStruct& iEventStruct,
               const stdair::ForecastingMethod& iForecastingMethod,
               const stdair::PartnershipTechnique& iPartnershipTechnique) {
    // Retrieve the RM event struct from the event.
    const stdair::RMEventStruct lRMEvent = iEventStruct.getRMEvent();

    // DEBUG
    STDAIR_LOG_DEBUG ("Running RM system: " << lRMEvent.describe());

    //ioSIMCRS_Service.optimise (lRMEvent, iForecastingMethod, iPartnershipTechnique);
  }
}
<|endoftext|>


<commit_before>// Copyright 2020 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#include "iree/compiler/Dialect/Flow/IR/FlowOps.h"
#include "iree/compiler/Dialect/Flow/Transforms/PassDetail.h"
#include "iree/compiler/Dialect/Flow/Transforms/Passes.h"
#include "iree/compiler/Dialect/IREE/IR/IREEDialect.h"
#include "iree/compiler/Dialect/IREE/IR/IREEOps.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/Pass/Pass.h"

namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Flow {

// Clones each exported functions (including those just created) with
// placeholder constant inputs instead of arguments and removes the exported
// attribute from the old functions.
// The input are provided using flow.variables.
class ExportBenchmarkFuncsPass
    : public ExportBenchmarkFuncsBase<ExportBenchmarkFuncsPass> {
 public:
  void getDependentDialects(DialectRegistry& registry) const override {
    registry.insert<IREEDialect>();
  }

  void runOnOperation() override {
    ModuleOp moduleOp = getOperation();

    // Gather the functions we want to wrap for benchmarking and wrap them.
    // Since we are inserting new functions as part of this pass we must perform
    // the wrapping for only the inputs.
    SmallVector<FuncOp, 4> entryFuncOps;
    for (auto entryFuncOp : moduleOp.getOps<FuncOp>()) {
      if (entryFuncOp.isPublic()) {
        entryFuncOps.push_back(entryFuncOp);
      }
    }
    for (auto entryFuncOp : entryFuncOps) {
      createEntryPointBenchmarkFunc(moduleOp, entryFuncOp);
    }
  }

 private:
  IREE::Flow::VariableOp createDummyInputVariableOp(Location loc,
                                                    Type inputType,
                                                    OpBuilder& moduleBuilder) {
    std::string baseName = "_benchmark_input_";
    std::string name = baseName + std::to_string(uniqueId++);
    auto initialValue = moduleBuilder.getZeroAttr(inputType);
    assert(initialValue && "failed to get zero attr for type");
    auto variableOp = moduleBuilder.create<VariableOp>(loc, name,
                                                       /*isMutable=*/false,
                                                       inputType, initialValue);
    variableOp.setPrivate();
    variableOp->setAttr("noinline", UnitAttr::get(moduleBuilder.getContext()));
    return variableOp;
  }

  void createEntryPointBenchmarkFunc(ModuleOp moduleOp, FuncOp entryFuncOp) {
    OpBuilder moduleBuilder(&getContext());
    moduleBuilder.setInsertionPointAfter(entryFuncOp);

    // Create one dummy input variable per input.
    Location loc = entryFuncOp.getLoc();
    SmallVector<IREE::Flow::VariableOp, 4> dummyInputVariableOps;
    for (auto inputType : entryFuncOp.getType().getInputs()) {
      dummyInputVariableOps.push_back(
          createDummyInputVariableOp(loc, inputType, moduleBuilder));
    }

    // Create a `() -> ()` entry point op the benchmark tool can run.
    std::string funcName = std::string(entryFuncOp.getName()) + "_benchmark";
    auto funcOp = moduleBuilder.create<FuncOp>(
        loc, funcName, moduleBuilder.getFunctionType({}, {}));
    funcOp.setPublic();
    funcOp->setAttr("iree.abi.stub", moduleBuilder.getUnitAttr());
    SmallVector<NamedAttribute> reflectionAttrs = {
        moduleBuilder.getNamedAttr("benchmark",
                                   moduleBuilder.getStringAttr("entry")),
    };
    funcOp->setAttr("iree.reflection",
                    moduleBuilder.getDictionaryAttr(reflectionAttrs));
    Block* block = funcOp.addEntryBlock();

    // Call the existing function with dummy arguments.
    auto blockBuilder = OpBuilder::atBlockBegin(block);
    SmallVector<Value, 4> args;
    for (int i = 0, e = entryFuncOp.getNumArguments(); i < e; ++i) {
      args.push_back(blockBuilder.createOrFold<IREE::Flow::VariableLoadOp>(
          loc, dummyInputVariableOps[i]));
    }
    auto callOp = blockBuilder.create<mlir::CallOp>(loc, entryFuncOp, args);

    // Sink all results with do_not_optimize to ensure that DCE does not
    // remove the call.
    for (auto result : callOp.getResults()) {
      blockBuilder.create<IREE::DoNotOptimizeOp>(loc, result);
    }
    blockBuilder.create<mlir::ReturnOp>(loc);

    // Ensure the original function is not exported and not inlined.
    entryFuncOp->setAttr("noinline", moduleBuilder.getUnitAttr());
    entryFuncOp->removeAttr("iree.reflection");
    entryFuncOp.setPrivate();
  }

  int uniqueId = 0;
};

std::unique_ptr<OperationPass<ModuleOp>> createExportBenchmarkFuncsPass() {
  return std::make_unique<ExportBenchmarkFuncsPass>();
}

}  // namespace Flow
}  // namespace IREE
}  // namespace iree_compiler
}  // namespace mlir
<commit_msg>Error out on unsupported benchmark function input types. (#6655)<commit_after>// Copyright 2020 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#include "iree/compiler/Dialect/Flow/IR/FlowOps.h"
#include "iree/compiler/Dialect/Flow/Transforms/PassDetail.h"
#include "iree/compiler/Dialect/Flow/Transforms/Passes.h"
#include "iree/compiler/Dialect/IREE/IR/IREEDialect.h"
#include "iree/compiler/Dialect/IREE/IR/IREEOps.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/Pass/Pass.h"

namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Flow {

// Clones each exported functions (including those just created) with
// placeholder constant inputs instead of arguments and removes the exported
// attribute from the old functions.
// The input are provided using flow.variables.
class ExportBenchmarkFuncsPass
    : public ExportBenchmarkFuncsBase<ExportBenchmarkFuncsPass> {
 public:
  void getDependentDialects(DialectRegistry& registry) const override {
    registry.insert<IREEDialect>();
  }

  void runOnOperation() override {
    ModuleOp moduleOp = getOperation();

    // Gather the functions we want to wrap for benchmarking and wrap them.
    // Since we are inserting new functions as part of this pass we must perform
    // the wrapping for only the inputs.
    SmallVector<FuncOp, 4> entryFuncOps;
    for (auto entryFuncOp : moduleOp.getOps<FuncOp>()) {
      if (entryFuncOp.isPublic()) {
        entryFuncOps.push_back(entryFuncOp);
      }
    }
    for (auto entryFuncOp : entryFuncOps) {
      if (failed(createEntryPointBenchmarkFunc(moduleOp, entryFuncOp))) {
        signalPassFailure();
        return;
      }
    }
  }

 private:
  IREE::Flow::VariableOp createDummyInputVariableOp(Location loc,
                                                    Type inputType,
                                                    OpBuilder& moduleBuilder) {
    std::string baseName = "_benchmark_input_";
    std::string name = baseName + std::to_string(uniqueId++);
    auto initialValue = moduleBuilder.getZeroAttr(inputType);
    if (!initialValue) {
      mlir::emitError(loc) << "unsupported function argument type: "
                           << inputType;
      return {};
    }
    auto variableOp = moduleBuilder.create<VariableOp>(loc, name,
                                                       /*isMutable=*/false,
                                                       inputType, initialValue);
    variableOp.setPrivate();
    variableOp->setAttr("noinline", UnitAttr::get(moduleBuilder.getContext()));
    return variableOp;
  }

  LogicalResult createEntryPointBenchmarkFunc(ModuleOp moduleOp,
                                              FuncOp entryFuncOp) {
    OpBuilder moduleBuilder(&getContext());
    moduleBuilder.setInsertionPointAfter(entryFuncOp);

    // Create one dummy input variable per input.
    Location loc = entryFuncOp.getLoc();
    SmallVector<IREE::Flow::VariableOp, 4> dummyInputVariableOps;
    for (auto inputType : entryFuncOp.getType().getInputs()) {
      auto dummyVar = createDummyInputVariableOp(loc, inputType, moduleBuilder);
      if (!dummyVar) return failure();
      dummyInputVariableOps.push_back(dummyVar);
    }

    // Create a `() -> ()` entry point op the benchmark tool can run.
    std::string funcName = std::string(entryFuncOp.getName()) + "_benchmark";
    auto funcOp = moduleBuilder.create<FuncOp>(
        loc, funcName, moduleBuilder.getFunctionType({}, {}));
    funcOp.setPublic();
    funcOp->setAttr("iree.abi.stub", moduleBuilder.getUnitAttr());
    SmallVector<NamedAttribute> reflectionAttrs = {
        moduleBuilder.getNamedAttr("benchmark",
                                   moduleBuilder.getStringAttr("entry")),
    };
    funcOp->setAttr("iree.reflection",
                    moduleBuilder.getDictionaryAttr(reflectionAttrs));
    Block* block = funcOp.addEntryBlock();

    // Call the existing function with dummy arguments.
    auto blockBuilder = OpBuilder::atBlockBegin(block);
    SmallVector<Value, 4> args;
    for (int i = 0, e = entryFuncOp.getNumArguments(); i < e; ++i) {
      args.push_back(blockBuilder.createOrFold<IREE::Flow::VariableLoadOp>(
          loc, dummyInputVariableOps[i]));
    }
    auto callOp = blockBuilder.create<mlir::CallOp>(loc, entryFuncOp, args);

    // Sink all results with do_not_optimize to ensure that DCE does not
    // remove the call.
    for (auto result : callOp.getResults()) {
      blockBuilder.create<IREE::DoNotOptimizeOp>(loc, result);
    }
    blockBuilder.create<mlir::ReturnOp>(loc);

    // Ensure the original function is not exported and not inlined.
    entryFuncOp->setAttr("noinline", moduleBuilder.getUnitAttr());
    entryFuncOp->removeAttr("iree.reflection");
    entryFuncOp.setPrivate();

    return success();
  }

  int uniqueId = 0;
};

std::unique_ptr<OperationPass<ModuleOp>> createExportBenchmarkFuncsPass() {
  return std::make_unique<ExportBenchmarkFuncsPass>();
}

}  // namespace Flow
}  // namespace IREE
}  // namespace iree_compiler
}  // namespace mlir
<|endoftext|>


<commit_before>#include "Graphics.h"
#include "sfwindow.h"
#include <SFML/Graphics.hpp>
#include "utility/misc.h"

#define GRAPHICS WalrusRPG::Graphics

sf::RenderWindow window;
sf::View view;
sf::RenderTexture buffer;

void GRAPHICS::init()
{
    window.create(sf::VideoMode(640, 480), "WalrusRPG",
                  sf::Style::Titlebar | sf::Style::Resize);
    view = sf::View(window.getDefaultView());
    buffer.create(320, 240);
}

void GRAPHICS::deinit()
{
    window.close();
}

void GRAPHICS::frame_begin()
{
    window.clear(sf::Color::Black);
}

void GRAPHICS::frame_end()
{
    sf::Sprite sprite(buffer.getTexture());
    sf::Vector2u winsize = window.getSize();
    sf::Event event;
    float scale = min(winsize.x / 320.f, winsize.y / 240.f);

    while (window.pollEvent(event))
    {
    }

    window.setView(view = sf::View(sf::FloatRect(0, 0, winsize.x, winsize.y)));

    buffer.display();
    window.clear();
    sprite.setScale(scale, scale);
    sprite.setPosition((winsize.x - 320.f * scale) / 2, (winsize.y - 240.f * scale) / 2);
    window.draw(sprite);
    window.display();
}

void GRAPHICS::put_sprite(const Texture &sheet, int x, int y,
                          const WalrusRPG::Utils::Rect &window)
{
    sf::Sprite sprite;
    sprite.setTexture(sheet.data);
    sprite.setTextureRect(sf::IntRect(window.x, window.y, window.width, window.height));
    sprite.setPosition(x, y);
    buffer.draw(sprite);
}

void GRAPHICS::fill(const WalrusRPG::Graphics::Pixel &color)
{
    UNUSED(color);
}
<commit_msg>SFML: enable full screen and vsync<commit_after>#include "Graphics.h"
#include "sfwindow.h"
#include <SFML/Graphics.hpp>
#include "utility/misc.h"

#define GRAPHICS WalrusRPG::Graphics

sf::RenderWindow window;
sf::View view;
sf::RenderTexture buffer;

void GRAPHICS::init()
{
    window.create(sf::VideoMode::getDesktopMode(), "WalrusRPG", sf::Style::Fullscreen);
    window.setVerticalSyncEnabled(true);
    view = sf::View(window.getDefaultView());
    buffer.create(320, 240);
}

void GRAPHICS::deinit()
{
    window.close();
}

void GRAPHICS::frame_begin()
{
    window.clear(sf::Color::Black);
}

void GRAPHICS::frame_end()
{
    sf::Sprite sprite(buffer.getTexture());
    sf::Vector2u winsize = window.getSize();
    sf::Event event;
    float scale = min(winsize.x / 320.f, winsize.y / 240.f);

    while (window.pollEvent(event))
    {
    }

    window.setView(view = sf::View(sf::FloatRect(0, 0, winsize.x, winsize.y)));

    buffer.display();
    window.clear();
    sprite.setScale(scale, scale);
    sprite.setPosition((winsize.x - 320.f * scale) / 2, (winsize.y - 240.f * scale) / 2);
    window.draw(sprite);
    window.display();
}

void GRAPHICS::put_sprite(const Texture &sheet, int x, int y,
                          const WalrusRPG::Utils::Rect &window)
{
    sf::Sprite sprite;
    sprite.setTexture(sheet.data);
    sprite.setTextureRect(sf::IntRect(window.x, window.y, window.width, window.height));
    sprite.setPosition(x, y);
    buffer.draw(sprite);
}

void GRAPHICS::fill(const WalrusRPG::Graphics::Pixel &color)
{
    UNUSED(color);
}
<|endoftext|>


<commit_before>// Copyright (c) 2019 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <uint256.h>
#include <arith_uint256.h>
#include <ethereum/ethereum.h>
#include <ethereum/sha3.h>
#include <logging.h>
#include <util/strencodings.h>
#include <key_io.h>

int nibblesToTraverse(const std::string &encodedPartialPath, const std::string &path, int pathPtr) {
  std::string partialPath;
  char pathPtrInt[2] = {encodedPartialPath[0], '\0'};
  int partialPathInt = strtol(pathPtrInt, NULL, 10);
  if(partialPathInt == 0 || partialPathInt == 2){
    partialPath = encodedPartialPath.substr(2);
  }else{
    partialPath = encodedPartialPath.substr(1);
  }
  if(partialPath == path.substr(pathPtr, partialPath.size())){
    return partialPath.size();
  }else{
    return -1;
  }
}
std::string hexToASCII(std::string hex)
{
    // initialize the ASCII code string as empty.
    string ascii = "";
    for (size_t i = 0; i < hex.length(); i += 2)
    {
        // extract two characters from hex string
        string part = hex.substr(i, 2);

        // change it into base 16 and
        // typecast as the character
        char ch = stoul(part, nullptr, 16);

        // add this char to final ASCII string
        ascii += ch;
    }
    return ascii;
}
bool VerifyProof(dev::bytesConstRef path, const dev::RLP& value, const dev::RLP& parentNodes, const dev::RLP& root) {
    try{
        dev::RLP currentNode;
        const int len = parentNodes.itemCount();
        dev::RLP nodeKey = root;
        int pathPtr = 0;

    	const std::string pathString = dev::toHex(path);

        int nibbles;
        char pathPtrInt[2];
        for (int i = 0 ; i < len ; i++) {
          currentNode = parentNodes[i];
          if(!nodeKey.payload().contentsEqual(sha3(currentNode.data()).ref().toVector())){
            return false;
          }

          if(pathPtr > (int)pathString.size()){
            return false;
          }

          switch(currentNode.itemCount()){
            case 17://branch node
              if(pathPtr == (int)pathString.size()){
                if(currentNode[16].payload().contentsEqual(value.data().toVector())){

                  return true;
                }else{
                  return false;
                }
              }

              pathPtrInt[0] = pathString[pathPtr];
              pathPtrInt[1] = '\0';

              nodeKey = currentNode[strtol(pathPtrInt, NULL, 16)]; //must == sha3(rlp.encode(currentNode[path[pathptr]]))
              pathPtr += 1;
              break;
            case 2:
              nibbles = nibblesToTraverse(toHex(currentNode[0].payload()), pathString, pathPtr);

              if(nibbles <= -1)
                return false;
              pathPtr += nibbles;

              if(pathPtr == (int)pathString.size()) { //leaf node
                if(currentNode[1].payload().contentsEqual(value.data().toVector())){

                  return true;
                } else {
                  return false;
                }
              } else {//extension node
                nodeKey = currentNode[1];
              }
              break;
            default:
              return false;
          }
        }
    }
    catch(...){
        return false;
    }
  return false;
}

/**
 * Parse eth input string expected to contain smart contract method call data. If the method call is not what we
 * expected, or the length of the expected string is not what we expect then return false.
 *
 * @param vchInputExpectedMethodHash The expected method hash
 * @param nERC20Precision The erc20 precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits
 * @param nLocalPrecision The local precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits
 * @param vchInputData The input to parse
 * @param outputAmount The amount burned
 * @param nAsset The asset burned
 * @param witnessAddress The destination witness address for the minting
 * @return true if everything is valid
 */
bool parseEthMethodInputData(const std::vector<unsigned char>& vchInputExpectedMethodHash, const uint8_t &nERC20Precision, const uint8_t& nLocalPrecision, const std::vector<unsigned char>& vchInputData, uint64_t& outputAmount, uint32_t& nAsset, CTxDestination& witnessAddress) {
    // total 5 or 6 fields are expected @ 32 bytes each field, 6 fields if witness > 32 bytes + 4 byte method hash
    if(vchInputData.size() < 164 || vchInputData.size() > 196) {
      return false;
    }
    // method hash is 4 bytes
    std::vector<unsigned char>::const_iterator firstMethod = vchInputData.begin();
    std::vector<unsigned char>::const_iterator lastMethod = firstMethod + 4;
    const std::vector<unsigned char> vchMethodHash(firstMethod,lastMethod);
    // if the method hash doesn't match the expected method hash then return false
    if(vchMethodHash != vchInputExpectedMethodHash) {
      return false;
    }

    std::vector<unsigned char> vchAmount(lastMethod,lastMethod + 32);
    // reverse endian
    std::reverse(vchAmount.begin(), vchAmount.end());
    arith_uint256 outputAmountArith = UintToArith256(uint256(vchAmount));
    // local precision can range between 0 and 8 decimal places, so it should fit within a CAmount
    // we pad zero's if erc20's precision is less than ours so we can accurately get the whole value of the amount transferred
    if(nLocalPrecision > nERC20Precision){
      outputAmountArith *= pow(10, nLocalPrecision-nERC20Precision);
    // ensure we truncate decimals to fit within int64 if erc20's precision is more than our asset precision
    } else if(nLocalPrecision < nERC20Precision){
      outputAmountArith /= pow(10, nERC20Precision-nLocalPrecision);
    }
    outputAmount = outputAmountArith.GetLow64();

    // convert the vch into a uint32_t (nAsset)
    // should be in position 68 walking backwards
    nAsset = static_cast<uint32_t>(vchInputData[67]);
    nAsset |= static_cast<uint32_t>(vchInputData[66]) << 8;
    nAsset |= static_cast<uint32_t>(vchInputData[65]) << 16;
    nAsset |= static_cast<uint32_t>(vchInputData[64]) << 24;

    // skip data field marker (32 bytes) + 31 bytes offset to the varint _byte
    const unsigned char &dataLength = vchInputData[131];
    // bech32 addresses to 46 bytes (sys1 vs bc1), min length is 9 for min witness address https://en.bitcoin.it/wiki/BIP_0173
    if(dataLength > 46 || dataLength < 9) {
      return false;
    }

    // witness address information starting at position 132 till the end
    witnessAddress = DecodeDestination(hexToASCII(HexStr(vchInputData.begin()+132, vchInputData.begin()+132 + dataLength))));
    return true;
}<commit_msg>compile<commit_after>// Copyright (c) 2019 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <uint256.h>
#include <arith_uint256.h>
#include <ethereum/ethereum.h>
#include <ethereum/sha3.h>
#include <logging.h>
#include <util/strencodings.h>
#include <key_io.h>

int nibblesToTraverse(const std::string &encodedPartialPath, const std::string &path, int pathPtr) {
  std::string partialPath;
  char pathPtrInt[2] = {encodedPartialPath[0], '\0'};
  int partialPathInt = strtol(pathPtrInt, NULL, 10);
  if(partialPathInt == 0 || partialPathInt == 2){
    partialPath = encodedPartialPath.substr(2);
  }else{
    partialPath = encodedPartialPath.substr(1);
  }
  if(partialPath == path.substr(pathPtr, partialPath.size())){
    return partialPath.size();
  }else{
    return -1;
  }
}
std::string hexToASCII(std::string hex)
{
    // initialize the ASCII code string as empty.
    std::string ascii = "";
    for (size_t i = 0; i < hex.length(); i += 2)
    {
        // extract two characters from hex string
        std::string part = hex.substr(i, 2);

        // change it into base 16 and
        // typecast as the character
        char ch = std::stoul(part, nullptr, 16);

        // add this char to final ASCII string
        ascii += ch;
    }
    return ascii;
}
bool VerifyProof(dev::bytesConstRef path, const dev::RLP& value, const dev::RLP& parentNodes, const dev::RLP& root) {
    try{
        dev::RLP currentNode;
        const int len = parentNodes.itemCount();
        dev::RLP nodeKey = root;
        int pathPtr = 0;

    	const std::string pathString = dev::toHex(path);

        int nibbles;
        char pathPtrInt[2];
        for (int i = 0 ; i < len ; i++) {
          currentNode = parentNodes[i];
          if(!nodeKey.payload().contentsEqual(sha3(currentNode.data()).ref().toVector())){
            return false;
          }

          if(pathPtr > (int)pathString.size()){
            return false;
          }

          switch(currentNode.itemCount()){
            case 17://branch node
              if(pathPtr == (int)pathString.size()){
                if(currentNode[16].payload().contentsEqual(value.data().toVector())){

                  return true;
                }else{
                  return false;
                }
              }

              pathPtrInt[0] = pathString[pathPtr];
              pathPtrInt[1] = '\0';

              nodeKey = currentNode[strtol(pathPtrInt, NULL, 16)]; //must == sha3(rlp.encode(currentNode[path[pathptr]]))
              pathPtr += 1;
              break;
            case 2:
              nibbles = nibblesToTraverse(toHex(currentNode[0].payload()), pathString, pathPtr);

              if(nibbles <= -1)
                return false;
              pathPtr += nibbles;

              if(pathPtr == (int)pathString.size()) { //leaf node
                if(currentNode[1].payload().contentsEqual(value.data().toVector())){

                  return true;
                } else {
                  return false;
                }
              } else {//extension node
                nodeKey = currentNode[1];
              }
              break;
            default:
              return false;
          }
        }
    }
    catch(...){
        return false;
    }
  return false;
}

/**
 * Parse eth input string expected to contain smart contract method call data. If the method call is not what we
 * expected, or the length of the expected string is not what we expect then return false.
 *
 * @param vchInputExpectedMethodHash The expected method hash
 * @param nERC20Precision The erc20 precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits
 * @param nLocalPrecision The local precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits
 * @param vchInputData The input to parse
 * @param outputAmount The amount burned
 * @param nAsset The asset burned
 * @param witnessAddress The destination witness address for the minting
 * @return true if everything is valid
 */
bool parseEthMethodInputData(const std::vector<unsigned char>& vchInputExpectedMethodHash, const uint8_t &nERC20Precision, const uint8_t& nLocalPrecision, const std::vector<unsigned char>& vchInputData, uint64_t& outputAmount, uint32_t& nAsset, CTxDestination& witnessAddress) {
    // total 5 or 6 fields are expected @ 32 bytes each field, 6 fields if witness > 32 bytes + 4 byte method hash
    if(vchInputData.size() < 164 || vchInputData.size() > 196) {
      return false;
    }
    // method hash is 4 bytes
    std::vector<unsigned char>::const_iterator firstMethod = vchInputData.begin();
    std::vector<unsigned char>::const_iterator lastMethod = firstMethod + 4;
    const std::vector<unsigned char> vchMethodHash(firstMethod,lastMethod);
    // if the method hash doesn't match the expected method hash then return false
    if(vchMethodHash != vchInputExpectedMethodHash) {
      return false;
    }

    std::vector<unsigned char> vchAmount(lastMethod,lastMethod + 32);
    // reverse endian
    std::reverse(vchAmount.begin(), vchAmount.end());
    arith_uint256 outputAmountArith = UintToArith256(uint256(vchAmount));
    // local precision can range between 0 and 8 decimal places, so it should fit within a CAmount
    // we pad zero's if erc20's precision is less than ours so we can accurately get the whole value of the amount transferred
    if(nLocalPrecision > nERC20Precision){
      outputAmountArith *= pow(10, nLocalPrecision-nERC20Precision);
    // ensure we truncate decimals to fit within int64 if erc20's precision is more than our asset precision
    } else if(nLocalPrecision < nERC20Precision){
      outputAmountArith /= pow(10, nERC20Precision-nLocalPrecision);
    }
    outputAmount = outputAmountArith.GetLow64();

    // convert the vch into a uint32_t (nAsset)
    // should be in position 68 walking backwards
    nAsset = static_cast<uint32_t>(vchInputData[67]);
    nAsset |= static_cast<uint32_t>(vchInputData[66]) << 8;
    nAsset |= static_cast<uint32_t>(vchInputData[65]) << 16;
    nAsset |= static_cast<uint32_t>(vchInputData[64]) << 24;

    // skip data field marker (32 bytes) + 31 bytes offset to the varint _byte
    const unsigned char &dataLength = vchInputData[131];
    // bech32 addresses to 46 bytes (sys1 vs bc1), min length is 9 for min witness address https://en.bitcoin.it/wiki/BIP_0173
    if(dataLength > 46 || dataLength < 9) {
      return false;
    }

    // witness address information starting at position 132 till the end
    witnessAddress = DecodeDestination(hexToASCII(HexStr(vchInputData.begin()+132, vchInputData.begin()+132 + dataLength))));
    return true;
}<|endoftext|>


<commit_before>// Copyright (c) 2014-2017 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#include <cstdlib>
#include <iostream>
#include <string>

#include <tao/pegtl.hpp>

using namespace tao::TAOCPP_PEGTL_NAMESPACE;

#include "double.hpp"

namespace sum
{
   struct padded_double
      : pad< double_::grammar, space >
   {
   };

   struct double_list
      : list< padded_double, one< ',' > >
   {
   };

   struct grammar
      : seq< double_list, eof >
   {
   };

   template< typename Rule >
   struct action
      : nothing< Rule >
   {
   };

   template<>
   struct action< double_::grammar >
   {
      template< typename Input >
      static void apply( const Input& in, double& sum )
      {
         // assume all values will fit into a C++ double
         auto ptr = const_cast< char* >( in.end() );
         sum += std::strtod( const_cast< char* >( in.begin() ), &ptr );
      }
   };

}  // namespace sum

int main()
{
   std::cout << "Give me a comma separated list of numbers.\n";
   std::cout << "The numbers are added using the PEGTL.\n";
   std::cout << "Type [q or Q] to quit\n\n";

   std::string str;

   while( std::getline( std::cin, str ) ) {
      if( str.empty() || str[ 0 ] == 'q' || str[ 0 ] == 'Q' ) {
         break;
      }
      double d = 0.0;
      memory_input<> in( str, "std::cin" );
      if( parse< sum::grammar, sum::action >( in, d ) ) {
         std::cout << "parsing OK; sum = " << d << std::endl;
      }
      else {
         std::cout << "parsing failed" << std::endl;
      }
   }
}
<commit_msg>Fix clang-tidy issue with old libstdc++<commit_after>// Copyright (c) 2014-2017 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#include <cstdlib>
#include <iostream>
#include <string>

#include <tao/pegtl.hpp>

using namespace tao::TAOCPP_PEGTL_NAMESPACE;

#include "double.hpp"

namespace sum
{
   struct padded_double
      : pad< double_::grammar, space >
   {
   };

   struct double_list
      : list< padded_double, one< ',' > >
   {
   };

   struct grammar
      : seq< double_list, eof >
   {
   };

   template< typename Rule >
   struct action
      : nothing< Rule >
   {
   };

   template<>
   struct action< double_::grammar >
   {
      template< typename Input >
      static void apply( const Input& in, double& sum )
      {
         // assume all values will fit into a C++ double
         auto ptr = const_cast< char* >( in.end() );
         sum += std::strtod( const_cast< char* >( in.begin() ), &ptr );
      }
   };

}  // namespace sum

int main()
{
   std::cout << "Give me a comma separated list of numbers.\n";
   std::cout << "The numbers are added using the PEGTL.\n";
   std::cout << "Type [q or Q] to quit\n\n";

   std::string str;

   while( !std::getline( std::cin, str ).fail() ) {
      if( str.empty() || str[ 0 ] == 'q' || str[ 0 ] == 'Q' ) {
         break;
      }
      double d = 0.0;
      memory_input<> in( str, "std::cin" );
      if( parse< sum::grammar, sum::action >( in, d ) ) {
         std::cout << "parsing OK; sum = " << d << std::endl;
      }
      else {
         std::cout << "parsing failed" << std::endl;
      }
   }
}
<|endoftext|>


<commit_before>// $Header$

TPolyMarker3D* make_vertex_marker(AliESDVertex* v, const Text_t* name)
{
  Double_t x[3], e[3];
  v->GetTruePos(x);
  v->GetSigmaXYZ(e);

  printf("%s: %f %f %f   -   %f %f %f\n", name,
	 x[0], x[1], x[2], e[0], e[1], e[2]);

  TPolyMarker3D* m = new TPolyMarker3D(8);
  m->SetName(name);

  // Problem with volume/length suppression of objects in TGLViewer
  /*
  m->SetPoint(0, x[0]+e[0], x[1]+e[1], x[2]+e[2]);
  m->SetPoint(1, x[0]+e[0], x[1]-e[1], x[2]+e[2]);
  m->SetPoint(2, x[0]-e[0], x[1]-e[1], x[2]+e[2]);
  m->SetPoint(3, x[0]-e[0], x[1]+e[1], x[2]+e[2]);

  m->SetPoint(4, x[0]+e[0], x[1]+e[1], x[2]-e[2]);
  m->SetPoint(5, x[0]+e[0], x[1]-e[1], x[2]-e[2]);
  m->SetPoint(6, x[0]-e[0], x[1]+e[1], x[2]-e[2]);
  m->SetPoint(7, x[0]-e[0], x[1]-e[1], x[2]-e[2]);
  */
  m->SetPoint(0, x[0], x[1], x[2]);

  return m;
}

void register_vertex_marker(TPolyMarker3D* m)
{
  using namespace Reve;
  Color_t* colp = FindColorVar(m, "fMarkerColor");
  RenderElementObjPtr* rnrEl = new RenderElementObjPtr(m, *colp);
  gReve->AddRenderElement(rnrEl);
  gReve->Redraw3D();
}

void primary_vertex(Bool_t showSPD=kTRUE)
{
  AliESD* esd = Alieve::Event::AssertESD();

  AliESDVertex*  pv  = esd->GetPrimaryVertex();
  TPolyMarker3D* pvm = make_vertex_marker(pv, "Primary Vertex");
  pvm->SetMarkerStyle(5);
  pvm->SetMarkerColor(3);
  register_vertex_marker(pvm);

  if(showSPD) {
    AliESDVertex*  spdv  = esd->GetVertex();
    TPolyMarker3D* spdvm = make_vertex_marker(spdv, "SPD Vertex");
    spdvm->SetMarkerStyle(2);
    spdvm->SetMarkerColor(7);
    register_vertex_marker(spdvm);
  }
}
<commit_msg>Removed code that gave vertex markers some volume (to avoid being discarded by a too smart GLViewer).<commit_after>// $Header$

TPolyMarker3D* make_vertex_marker(AliESDVertex* v, const Text_t* name)
{
  Double_t x[3], e[3];
  v->GetTruePos(x);
  v->GetSigmaXYZ(e);

  printf("%s: %f %f %f   -   %f %f %f\n", name,
	 x[0], x[1], x[2], e[0], e[1], e[2]);

  TPolyMarker3D* m = new TPolyMarker3D(8);
  m->SetName(name);
  m->SetPoint(0, x[0], x[1], x[2]);

  return m;
}

void register_vertex_marker(TPolyMarker3D* m)
{
  using namespace Reve;
  Color_t* colp = FindColorVar(m, "fMarkerColor");
  RenderElementObjPtr* rnrEl = new RenderElementObjPtr(m, *colp);
  gReve->AddRenderElement(rnrEl);
  gReve->Redraw3D();
}

void primary_vertex(Bool_t showSPD=kTRUE)
{
  AliESD* esd = Alieve::Event::AssertESD();

  AliESDVertex*  pv  = esd->GetPrimaryVertex();
  TPolyMarker3D* pvm = make_vertex_marker(pv, "Primary Vertex");
  pvm->SetMarkerStyle(5);
  pvm->SetMarkerColor(3);
  register_vertex_marker(pvm);

  if(showSPD) {
    AliESDVertex*  spdv  = esd->GetVertex();
    TPolyMarker3D* spdvm = make_vertex_marker(spdv, "SPD Vertex");
    spdvm->SetMarkerStyle(2);
    spdvm->SetMarkerColor(7);
    register_vertex_marker(spdvm);
  }
}
<|endoftext|>


<commit_before>/*
 *  caosVar.cpp
 *  openc2e
 *
 *  Created by Bryan Donlan on Thu Mar 10 2005.
 *  Copyright (c) 2005-2006 Alyssa Milburn and Bryan Donlan. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 */

#define IN_CAOSVAR_CPP

#include "caosVar.h"
#include "Engine.h" // version

#include <iostream>
#include <sstream>
#include <boost/format.hpp>

#ifdef DONT_INLINE_CAOSVAR_ACCESSORS
#error meh, copy the stuff out of caosVar.h and drop it here
#endif

using boost::str;

static inline std::string stringify(double x) {
	std::ostringstream o;
	if (!(o << x)) throw "stringify() failed";
	return o.str();
}

std::string caosVar::dump() const {
	switch(getType()) {
		case CAOSSTR:
			return str(boost::format("String \"%s\" ") % getString());
			break;
		case CAOSINT:
			return str(boost::format("Int %d ") % getInt());
			break;
		case CAOSFLOAT:
			return str(boost::format("Float %f ") % getFloat());
			break;
		case CAOSAGENT:
			return str(boost::format("Agent %p ") % (Agent *)getAgent().get());
			break;
		case CAOSVEC:
			return str(boost::format("Vector (%f, %f)") % getVector().x % getVector().y);
			break;
		default:
			return "[bad caosVar!] ";
			break;
	};
}

bool caosVar::operator == (const caosVar &v) const {
	// todo: should be able to compare int and float, apparently
	if (this->hasInt() && v.hasInt()) {
		return this->getInt() == v.getInt();
	} else if (this->hasDecimal() && v.hasDecimal()) {
		return this->getFloat() == v.getFloat();
	} else if (this->hasString() && v.hasString()) {
		return this->getString() == v.getString();
	} else if (this->hasAgent() && v.hasAgent()) {
		return this->getAgent() == v.getAgent();
	} else if (this->hasVector() && v.hasVector()) {
		return this->getVector() == v.getVector();
	} else if (engine.version < 3) {
		// C1/C2 allow you to compare an agent to zero, since agents are integers..
		// TODO: do this for >/< too?

		if (this->hasInt() && this->getInt() == 0 && v.hasAgent()) {
			return v.getAgent();
		} else if (v.hasInt() && v.getInt() == 0 && this->hasAgent()) {
			return this->getAgent();
		}
	}

	throw caosException(std::string("caosVar operator == couldn't compare ") + this->dump() + "and " + v.dump());
}

bool caosVar::operator > (const caosVar &v) const {
	if (this->hasDecimal() && v.hasDecimal()) {
		return this->getFloat() > v.getFloat();
	} else if (this->hasString() && v.hasString()) {
		return this->getString() > v.getString();
	} else if (this->hasVector() && v.hasVector()) {
		// XXX this is totally arbitrary
		const Vector<float> &v1 = this->getVector();
		const Vector<float> &v2 = v.getVector();
		if (v1.x > v2.x)
			return true;
		else if (v1.x < v2.x)
			return false;
		else if (v1.y > v2.y)
			return true;
		else return false;
	}

	throw caosException(std::string("caosVar operator > couldn't compare ") + this->dump() + "and " + v.dump());
}

bool caosVar::operator < (const caosVar &v) const {
	if (this->hasDecimal() && v.hasDecimal()) {
		return this->getFloat() < v.getFloat();
	} else if (this->hasString() && v.hasString()) {
		return this->getString() < v.getString();
	} else if (this->hasVector() && v.hasVector()) {
		return (*this != v) && !(*this > v);
	}

	throw caosException(std::string("caosVar operator < couldn't compare ") + this->dump() + "and " + v.dump());
}

/* vim: set noet: */
<commit_msg>fix comparing an agent to zero so it gives the right result<commit_after>/*
 *  caosVar.cpp
 *  openc2e
 *
 *  Created by Bryan Donlan on Thu Mar 10 2005.
 *  Copyright (c) 2005-2006 Alyssa Milburn and Bryan Donlan. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 */

#define IN_CAOSVAR_CPP

#include "caosVar.h"
#include "Engine.h" // version

#include <iostream>
#include <sstream>
#include <boost/format.hpp>

#ifdef DONT_INLINE_CAOSVAR_ACCESSORS
#error meh, copy the stuff out of caosVar.h and drop it here
#endif

using boost::str;

static inline std::string stringify(double x) {
	std::ostringstream o;
	if (!(o << x)) throw "stringify() failed";
	return o.str();
}

std::string caosVar::dump() const {
	switch(getType()) {
		case CAOSSTR:
			return str(boost::format("String \"%s\" ") % getString());
			break;
		case CAOSINT:
			return str(boost::format("Int %d ") % getInt());
			break;
		case CAOSFLOAT:
			return str(boost::format("Float %f ") % getFloat());
			break;
		case CAOSAGENT:
			return str(boost::format("Agent %p ") % (Agent *)getAgent().get());
			break;
		case CAOSVEC:
			return str(boost::format("Vector (%f, %f)") % getVector().x % getVector().y);
			break;
		default:
			return "[bad caosVar!] ";
			break;
	};
}

bool caosVar::operator == (const caosVar &v) const {
	// todo: should be able to compare int and float, apparently
	if (this->hasInt() && v.hasInt()) {
		return this->getInt() == v.getInt();
	} else if (this->hasDecimal() && v.hasDecimal()) {
		return this->getFloat() == v.getFloat();
	} else if (this->hasString() && v.hasString()) {
		return this->getString() == v.getString();
	} else if (this->hasAgent() && v.hasAgent()) {
		return this->getAgent() == v.getAgent();
	} else if (this->hasVector() && v.hasVector()) {
		return this->getVector() == v.getVector();
	} else if (engine.version < 3) {
		// C1/C2 allow you to compare an agent to zero, since agents are integers..
		// TODO: do this for >/< too?

		if (this->hasInt() && this->getInt() == 0 && v.hasAgent()) {
			return !(v.getAgent());
		} else if (v.hasInt() && v.getInt() == 0 && this->hasAgent()) {
			return !(this->getAgent());
		}
	}

	throw caosException(std::string("caosVar operator == couldn't compare ") + this->dump() + "and " + v.dump());
}

bool caosVar::operator > (const caosVar &v) const {
	if (this->hasDecimal() && v.hasDecimal()) {
		return this->getFloat() > v.getFloat();
	} else if (this->hasString() && v.hasString()) {
		return this->getString() > v.getString();
	} else if (this->hasVector() && v.hasVector()) {
		// XXX this is totally arbitrary
		const Vector<float> &v1 = this->getVector();
		const Vector<float> &v2 = v.getVector();
		if (v1.x > v2.x)
			return true;
		else if (v1.x < v2.x)
			return false;
		else if (v1.y > v2.y)
			return true;
		else return false;
	}

	throw caosException(std::string("caosVar operator > couldn't compare ") + this->dump() + "and " + v.dump());
}

bool caosVar::operator < (const caosVar &v) const {
	if (this->hasDecimal() && v.hasDecimal()) {
		return this->getFloat() < v.getFloat();
	} else if (this->hasString() && v.hasString()) {
		return this->getString() < v.getString();
	} else if (this->hasVector() && v.hasVector()) {
		return (*this != v) && !(*this > v);
	}

	throw caosException(std::string("caosVar operator < couldn't compare ") + this->dump() + "and " + v.dump());
}

/* vim: set noet: */
<|endoftext|>


<commit_before>/*
 *  \remark This file is part of VITA.
 *
 *  \copyright Copyright (C) 2019-2020 EOS di Manlio Morini.
 *
 *  \license
 *  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/
 *
 *  \see https://github.com/morinim/vita/wiki/scheduling_tutorial
 */

#include "kernel/vita.h"

double neg_rastrigin(const std::vector<double> &x)
{
  constexpr double  A = 10.0;
  constexpr double PI =  3.141592653589793;

  const double rastrigin =
    A * x.size() + std::accumulate(x.begin(), x.end(), 0.0,
                                   [](double sum, double xi)
                                   {
                                     return sum + xi*xi - A*std::cos(2*PI*xi);
                                   });

  return -rastrigin;
}

int main()
{
  const unsigned dimensions(5);  // 5D - Rastrigin function

  vita::de_problem prob(dimensions, {-5.12, 5.12});

  prob.env.individuals =   50;
  prob.env.generations = 1000;

  vita::de_search<decltype(neg_rastrigin)> search(prob, neg_rastrigin);

  const auto res(search.run());

  const auto solution(  res.best.solution);
  const auto value(res.best.score.fitness);

  std::cout << "Minimum found: " <<  value << '\n';

  std::cout << "Coordinates: [ ";
  for (auto xi : solution)
    std::cout << xi << ' ';
  std::cout << "]\n";
}
<commit_msg>[FIX] Visual Studio compile error<commit_after>/*
 *  \remark This file is part of VITA.
 *
 *  \copyright Copyright (C) 2019-2020 EOS di Manlio Morini.
 *
 *  \license
 *  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/
 *
 *  \see https://github.com/morinim/vita/wiki/scheduling_tutorial
 */

#include "kernel/vita.h"

double neg_rastrigin(const std::vector<double> &x)
{
  constexpr double  A = 10.0;
  constexpr double PI =  3.141592653589793;

  const double rastrigin =
    A * x.size() + std::accumulate(x.begin(), x.end(), 0.0,
                                   [=](double sum, double xi)
                                   {
                                     return sum + xi*xi - A*std::cos(2*PI*xi);
                                   });

  return -rastrigin;
}

int main()
{
  const unsigned dimensions(5);  // 5D - Rastrigin function

  vita::de_problem prob(dimensions, {-5.12, 5.12});

  prob.env.individuals =   50;
  prob.env.generations = 1000;

  vita::de_search<decltype(neg_rastrigin)> search(prob, neg_rastrigin);

  const auto res(search.run());

  const auto solution(  res.best.solution);
  const auto value(res.best.score.fitness);

  std::cout << "Minimum found: " <<  value << '\n';

  std::cout << "Coordinates: [ ";
  for (auto xi : solution)
    std::cout << xi << ' ';
  std::cout << "]\n";
}
<|endoftext|>


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

// A demo sandbox for the static_bin binary.
// Use: static_sandbox --logtostderr

#include <fcntl.h>
#include <sys/resource.h>
#include <syscall.h>
#include <unistd.h>

#include <csignal>
#include <cstdlib>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include <glog/logging.h>
#include "sandboxed_api/util/flag.h"
#include "absl/memory/memory.h"
#include "sandboxed_api/sandbox2/executor.h"
#include "sandboxed_api/sandbox2/ipc.h"
#include "sandboxed_api/sandbox2/limits.h"
#include "sandboxed_api/sandbox2/policy.h"
#include "sandboxed_api/sandbox2/policybuilder.h"
#include "sandboxed_api/sandbox2/result.h"
#include "sandboxed_api/sandbox2/sandbox2.h"
#include "sandboxed_api/sandbox2/util/bpf_helper.h"
#include "sandboxed_api/sandbox2/util/runfiles.h"

std::unique_ptr<sandbox2::Policy> GetPolicy() {
  return sandbox2::PolicyBuilder()
      // The most frequent syscall should go first in this sequence (to make it
      // fast).
      // Allow read() with all arguments.
      .AllowRead()
      // Allow a preset of syscalls that are known to be used during startup
      // of static binaries.
      .AllowStaticStartup()
      // Allow the getpid() syscall.
      .AllowSyscall(__NR_getpid)

      // On Debian, even static binaries check existence of /etc/ld.so.nohwcap.
      .BlockSyscallWithErrno(__NR_access, ENOENT)

      // Examples for AddPolicyOnSyscall:
      .AddPolicyOnSyscall(__NR_write,
                          {
                              // Load the first argument of write() (= fd)
                              ARG_32(0),
                              // Allow write(fd=STDOUT)
                              JEQ32(1, ALLOW),
                              // Allow write(fd=STDERR)
                              JEQ32(2, ALLOW),
                              // Fall-through for every other case.
                              // The default action will be KILL if it is not
                              // explicitly ALLOWed by a following rule.
                          })
      // write() calls with fd not in (1, 2) will continue evaluating the
      // policy. This means that other rules might still allow them.

      // Allow exit() only with an exit_code of 0.
      // Explicitly jumping to KILL, thus the following rules can not
      // override this rule.
      .AddPolicyOnSyscall(
          __NR_exit_group,
          {// Load first argument (exit_code).
           ARG_32(0),
           // Deny every argument except 0.
           JNE32(0, KILL),
           // Allow all exit() calls that were not previously forbidden
           // = exit_code == 0.
           ALLOW})

      // = This won't have any effect as we handled every case of this syscall
      // in the previous rule.
      .AllowSyscall(__NR_exit_group)

#ifdef __NR_open
      .BlockSyscallWithErrno(__NR_open, ENOENT)
#else
      .BlockSyscallWithErrno(__NR_openat, ENOENT)
#endif
      .BuildOrDie();
}

int main(int argc, char** argv) {
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(argv[0]);

  const std::string path = sandbox2::GetInternalDataDependencyFilePath(
      "sandbox2/examples/static/static_bin");
  std::vector<std::string> args = {path};
  auto executor = absl::make_unique<sandbox2::Executor>(path, args);

  executor
      // Sandboxing is enabled by the sandbox itself. The sandboxed binary is
      // not aware that it'll be sandboxed.
      // Note: 'true' is the default setting for this class.
      ->set_enable_sandbox_before_exec(true)
      .limits()
      // Remove restrictions on the size of address-space of sandboxed
      // processes.
      ->set_rlimit_as(RLIM64_INFINITY)
      // Kill sandboxed processes with a signal (SIGXFSZ) if it writes more than
      // these many bytes to the file-system.
      .set_rlimit_fsize(1024)
      // The CPU time limit.
      .set_rlimit_cpu(60)
      .set_walltime_limit(absl::Seconds(30));

  int proc_version_fd = open("/proc/version", O_RDONLY);
  PCHECK(proc_version_fd != -1);

  // Map this fils to sandboxee's stdin.
  executor->ipc()->MapFd(proc_version_fd, STDIN_FILENO);

  auto policy = GetPolicy();
  sandbox2::Sandbox2 s2(std::move(executor), std::move(policy));

  // Let the sandboxee run (synchronously).
  auto result = s2.Run();

  LOG(INFO) << "Final execution status: " << result.ToString();

  return EXIT_SUCCESS;
}
<commit_msg>Use proper return code for static_sandbox example<commit_after>// Copyright 2019 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// A demo sandbox for the static_bin binary.
// Use: static_sandbox --logtostderr

#include <fcntl.h>
#include <sys/resource.h>
#include <syscall.h>
#include <unistd.h>

#include <csignal>
#include <cstdlib>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include <glog/logging.h>
#include "sandboxed_api/util/flag.h"
#include "absl/memory/memory.h"
#include "sandboxed_api/sandbox2/executor.h"
#include "sandboxed_api/sandbox2/ipc.h"
#include "sandboxed_api/sandbox2/limits.h"
#include "sandboxed_api/sandbox2/policy.h"
#include "sandboxed_api/sandbox2/policybuilder.h"
#include "sandboxed_api/sandbox2/result.h"
#include "sandboxed_api/sandbox2/sandbox2.h"
#include "sandboxed_api/sandbox2/util/bpf_helper.h"
#include "sandboxed_api/sandbox2/util/runfiles.h"

std::unique_ptr<sandbox2::Policy> GetPolicy() {
  return sandbox2::PolicyBuilder()
      // The most frequent syscall should go first in this sequence (to make it
      // fast).
      // Allow read() with all arguments.
      .AllowRead()
      // Allow a preset of syscalls that are known to be used during startup
      // of static binaries.
      .AllowStaticStartup()
      // Allow the getpid() syscall.
      .AllowSyscall(__NR_getpid)

      // On Debian, even static binaries check existence of /etc/ld.so.nohwcap.
      .BlockSyscallWithErrno(__NR_access, ENOENT)

      // Examples for AddPolicyOnSyscall:
      .AddPolicyOnSyscall(__NR_write,
                          {
                              // Load the first argument of write() (= fd)
                              ARG_32(0),
                              // Allow write(fd=STDOUT)
                              JEQ32(1, ALLOW),
                              // Allow write(fd=STDERR)
                              JEQ32(2, ALLOW),
                              // Fall-through for every other case.
                              // The default action will be KILL if it is not
                              // explicitly ALLOWed by a following rule.
                          })
      // write() calls with fd not in (1, 2) will continue evaluating the
      // policy. This means that other rules might still allow them.

      // Allow exit() only with an exit_code of 0.
      // Explicitly jumping to KILL, thus the following rules can not
      // override this rule.
      .AddPolicyOnSyscall(
          __NR_exit_group,
          {// Load first argument (exit_code).
           ARG_32(0),
           // Deny every argument except 0.
           JNE32(0, KILL),
           // Allow all exit() calls that were not previously forbidden
           // = exit_code == 0.
           ALLOW})

      // = This won't have any effect as we handled every case of this syscall
      // in the previous rule.
      .AllowSyscall(__NR_exit_group)

#ifdef __NR_open
      .BlockSyscallWithErrno(__NR_open, ENOENT)
#else
      .BlockSyscallWithErrno(__NR_openat, ENOENT)
#endif
      .BuildOrDie();
}

int main(int argc, char** argv) {
  // This test is incompatible with sanitizers.
  // The `SKIP_SANITIZERS_AND_COVERAGE` macro won't work for us here since we
  // need to return something.
#if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
    defined(THREAD_SANITIZER)
  return EXIT_SUCCESS;
#endif
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(argv[0]);

  const std::string path = sandbox2::GetInternalDataDependencyFilePath(
      "sandbox2/examples/static/static_bin");
  std::vector<std::string> args = {path};
  auto executor = absl::make_unique<sandbox2::Executor>(path, args);

  executor
      // Sandboxing is enabled by the sandbox itself. The sandboxed binary is
      // not aware that it'll be sandboxed.
      // Note: 'true' is the default setting for this class.
      ->set_enable_sandbox_before_exec(true)
      .limits()
      // Remove restrictions on the size of address-space of sandboxed
      // processes.
      ->set_rlimit_as(RLIM64_INFINITY)
      // Kill sandboxed processes with a signal (SIGXFSZ) if it writes more than
      // these many bytes to the file-system.
      .set_rlimit_fsize(1024 * 1024)
      // The CPU time limit.
      .set_rlimit_cpu(60)
      .set_walltime_limit(absl::Seconds(30));

  int proc_version_fd = open("/proc/version", O_RDONLY);
  PCHECK(proc_version_fd != -1);

  // Map this fils to sandboxee's stdin.
  executor->ipc()->MapFd(proc_version_fd, STDIN_FILENO);

  auto policy = GetPolicy();
  sandbox2::Sandbox2 s2(std::move(executor), std::move(policy));

  // Let the sandboxee run (synchronously).
  auto result = s2.Run();

  LOG(INFO) << "Final execution status: " << result.ToString();

  return result.final_status() == sandbox2::Result::OK ? EXIT_SUCCESS
                                                       : EXIT_FAILURE;
}
<|endoftext|>


<commit_before>
<commit_msg>test for detectFileType<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* 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 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program 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 General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Sofa_test.h"

#include "SofaLoader/MeshVTKLoader.h"

namespace sofa {

struct MeshVTKLoader_test : public Sofa_test<>, public component::loader::MeshVTKLoader
{

    MeshVTKLoader_test()
    {
    }

};

TEST_F(MeshVTKLoader_test, detectFileType)
{
    ASSERT_EQ(component::loader::MeshVTKLoader::LEGACY, this->detectFileType(sofa::helper::system::DataRepository.getFile("mesh/liver.vtk").c_str()));
    ASSERT_EQ(component::loader::MeshVTKLoader::XML, this->detectFileType(sofa::helper::system::DataRepository.getFile("mesh/Armadillo_Tetra_4406.vtu").c_str()));
}

}// namespace sofa
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "modules/audio_coding/neteq/tools/fake_decode_from_file.h"

#include "modules/rtp_rtcp/source/byte_io.h"
#include "rtc_base/checks.h"
#include "rtc_base/numerics/safe_conversions.h"

namespace webrtc {
namespace test {

int FakeDecodeFromFile::DecodeInternal(const uint8_t* encoded,
                                       size_t encoded_len,
                                       int sample_rate_hz,
                                       int16_t* decoded,
                                       SpeechType* speech_type) {
  RTC_DCHECK_EQ(sample_rate_hz, SampleRateHz());

  const int samples_to_decode = PacketDuration(encoded, encoded_len);
  const int total_samples_to_decode = samples_to_decode * (stereo_ ? 2 : 1);

  if (encoded_len == 0) {
    // Decoder is asked to produce codec-internal comfort noise.
    RTC_DCHECK(!encoded);  // NetEq always sends nullptr in this case.
    RTC_DCHECK(cng_mode_);
    RTC_DCHECK_GT(last_decoded_length_, 0);
    std::fill_n(decoded, total_samples_to_decode, 0);
    *speech_type = kComfortNoise;
    return rtc::dchecked_cast<int>(total_samples_to_decode);
  }

  RTC_CHECK_GE(encoded_len, 12);
  uint32_t timestamp_to_decode =
      ByteReader<uint32_t>::ReadLittleEndian(encoded);

  if (next_timestamp_from_input_ &&
      timestamp_to_decode != *next_timestamp_from_input_) {
    // A gap in the timestamp sequence is detected. Skip the same number of
    // samples from the file.
    uint32_t jump = timestamp_to_decode - *next_timestamp_from_input_;
    RTC_CHECK(input_->Seek(jump));
  }

  next_timestamp_from_input_ = timestamp_to_decode + samples_to_decode;

  uint32_t original_payload_size_bytes =
      ByteReader<uint32_t>::ReadLittleEndian(&encoded[8]);
  if (original_payload_size_bytes == 1) {
    // This is a comfort noise payload.
    RTC_DCHECK_GT(last_decoded_length_, 0);
    std::fill_n(decoded, total_samples_to_decode, 0);
    *speech_type = kComfortNoise;
    cng_mode_ = true;
    return rtc::dchecked_cast<int>(total_samples_to_decode);
  }

  cng_mode_ = false;
  RTC_CHECK(input_->Read(static_cast<size_t>(samples_to_decode), decoded));

  if (stereo_) {
    InputAudioFile::DuplicateInterleaved(decoded, samples_to_decode, 2,
                                         decoded);
  }

  *speech_type = kSpeech;
  last_decoded_length_ = samples_to_decode;
  return rtc::dchecked_cast<int>(total_samples_to_decode);
}

int FakeDecodeFromFile::PacketDuration(const uint8_t* encoded,
                                       size_t encoded_len) const {
  const uint32_t original_payload_size_bytes =
      encoded_len < 8 + sizeof(uint32_t)
          ? 0
          : ByteReader<uint32_t>::ReadLittleEndian(&encoded[8]);
  const uint32_t samples_to_decode =
      encoded_len < 4 + sizeof(uint32_t)
          ? 0
          : ByteReader<uint32_t>::ReadLittleEndian(&encoded[4]);
  if (  // Decoder is asked to produce codec-internal comfort noise
      encoded_len == 0 ||
      // Comfort noise payload
      original_payload_size_bytes == 1 || samples_to_decode == 0 ||
      // Erroneous duration since it is not a multiple of 10ms
      samples_to_decode % rtc::CheckedDivExact(SampleRateHz(), 100) != 0) {
    if (last_decoded_length_ > 0) {
      // Use length of last decoded packet.
      return rtc::dchecked_cast<int>(last_decoded_length_);
    } else {
      // This is the first packet to decode, and we do not know the length of
      // it. Set it to 10 ms.
      return rtc::CheckedDivExact(SampleRateHz(), 100);
    }
  }
  return samples_to_decode;
}

void FakeDecodeFromFile::PrepareEncoded(uint32_t timestamp,
                                        size_t samples,
                                        size_t original_payload_size_bytes,
                                        rtc::ArrayView<uint8_t> encoded) {
  RTC_CHECK_GE(encoded.size(), 12);
  ByteWriter<uint32_t>::WriteLittleEndian(&encoded[0], timestamp);
  ByteWriter<uint32_t>::WriteLittleEndian(&encoded[4],
                                          rtc::checked_cast<uint32_t>(samples));
  ByteWriter<uint32_t>::WriteLittleEndian(
      &encoded[8], rtc::checked_cast<uint32_t>(original_payload_size_bytes));
}

}  // namespace test
}  // namespace webrtc
<commit_msg>Remove a legacy DCHEC in FakeDecodeFromFile.<commit_after>/*
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "modules/audio_coding/neteq/tools/fake_decode_from_file.h"

#include "modules/rtp_rtcp/source/byte_io.h"
#include "rtc_base/checks.h"
#include "rtc_base/numerics/safe_conversions.h"

namespace webrtc {
namespace test {

int FakeDecodeFromFile::DecodeInternal(const uint8_t* encoded,
                                       size_t encoded_len,
                                       int sample_rate_hz,
                                       int16_t* decoded,
                                       SpeechType* speech_type) {
  RTC_DCHECK_EQ(sample_rate_hz, SampleRateHz());

  const int samples_to_decode = PacketDuration(encoded, encoded_len);
  const int total_samples_to_decode = samples_to_decode * (stereo_ ? 2 : 1);

  if (encoded_len == 0) {
    // Decoder is asked to produce codec-internal comfort noise.
    RTC_DCHECK(!encoded);  // NetEq always sends nullptr in this case.
    RTC_DCHECK(cng_mode_);
    RTC_DCHECK_GT(total_samples_to_decode, 0);
    std::fill_n(decoded, total_samples_to_decode, 0);
    *speech_type = kComfortNoise;
    return rtc::dchecked_cast<int>(total_samples_to_decode);
  }

  RTC_CHECK_GE(encoded_len, 12);
  uint32_t timestamp_to_decode =
      ByteReader<uint32_t>::ReadLittleEndian(encoded);

  if (next_timestamp_from_input_ &&
      timestamp_to_decode != *next_timestamp_from_input_) {
    // A gap in the timestamp sequence is detected. Skip the same number of
    // samples from the file.
    uint32_t jump = timestamp_to_decode - *next_timestamp_from_input_;
    RTC_CHECK(input_->Seek(jump));
  }

  next_timestamp_from_input_ = timestamp_to_decode + samples_to_decode;

  uint32_t original_payload_size_bytes =
      ByteReader<uint32_t>::ReadLittleEndian(&encoded[8]);
  if (original_payload_size_bytes == 1) {
    // This is a comfort noise payload.
    RTC_DCHECK_GT(total_samples_to_decode, 0);
    std::fill_n(decoded, total_samples_to_decode, 0);
    *speech_type = kComfortNoise;
    cng_mode_ = true;
    return rtc::dchecked_cast<int>(total_samples_to_decode);
  }

  cng_mode_ = false;
  RTC_CHECK(input_->Read(static_cast<size_t>(samples_to_decode), decoded));

  if (stereo_) {
    InputAudioFile::DuplicateInterleaved(decoded, samples_to_decode, 2,
                                         decoded);
  }

  *speech_type = kSpeech;
  last_decoded_length_ = samples_to_decode;
  return rtc::dchecked_cast<int>(total_samples_to_decode);
}

int FakeDecodeFromFile::PacketDuration(const uint8_t* encoded,
                                       size_t encoded_len) const {
  const uint32_t original_payload_size_bytes =
      encoded_len < 8 + sizeof(uint32_t)
          ? 0
          : ByteReader<uint32_t>::ReadLittleEndian(&encoded[8]);
  const uint32_t samples_to_decode =
      encoded_len < 4 + sizeof(uint32_t)
          ? 0
          : ByteReader<uint32_t>::ReadLittleEndian(&encoded[4]);
  if (  // Decoder is asked to produce codec-internal comfort noise
      encoded_len == 0 ||
      // Comfort noise payload
      original_payload_size_bytes == 1 || samples_to_decode == 0 ||
      // Erroneous duration since it is not a multiple of 10ms
      samples_to_decode % rtc::CheckedDivExact(SampleRateHz(), 100) != 0) {
    if (last_decoded_length_ > 0) {
      // Use length of last decoded packet.
      return rtc::dchecked_cast<int>(last_decoded_length_);
    } else {
      // This is the first packet to decode, and we do not know the length of
      // it. Set it to 10 ms.
      return rtc::CheckedDivExact(SampleRateHz(), 100);
    }
  }
  return samples_to_decode;
}

void FakeDecodeFromFile::PrepareEncoded(uint32_t timestamp,
                                        size_t samples,
                                        size_t original_payload_size_bytes,
                                        rtc::ArrayView<uint8_t> encoded) {
  RTC_CHECK_GE(encoded.size(), 12);
  ByteWriter<uint32_t>::WriteLittleEndian(&encoded[0], timestamp);
  ByteWriter<uint32_t>::WriteLittleEndian(&encoded[4],
                                          rtc::checked_cast<uint32_t>(samples));
  ByteWriter<uint32_t>::WriteLittleEndian(
      &encoded[8], rtc::checked_cast<uint32_t>(original_payload_size_bytes));
}

}  // namespace test
}  // namespace webrtc
<|endoftext|>