<commit_before>// Copyright 2019 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/Translation/IREEVM.h"

#include "iree/compiler/Bindings/Native/Transforms/Passes.h"
#include "iree/compiler/Bindings/TFLite/Transforms/Passes.h"
#include "iree/compiler/Dialect/Flow/Transforms/Passes.h"
#include "iree/compiler/Dialect/HAL/Transforms/Passes.h"
#include "iree/compiler/Dialect/IREE/Transforms/Passes.h"
#include "iree/compiler/Dialect/VM/Target/Bytecode/TranslationFlags.h"
#include "iree/compiler/Dialect/VM/Transforms/Passes.h"
#include "iree/compiler/InputConversion/MHLO/Passes.h"
#include "iree/compiler/InputConversion/TOSA/Passes.h"
#include "iree/compiler/Utils/TracingUtils.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Translation.h"

#ifdef IREE_HAVE_EMITC_DIALECT
#include "iree/compiler/Dialect/VM/Target/C/CModuleTarget.h"
#include "iree/compiler/Dialect/VM/Target/C/TranslationFlags.h"
#endif  // IREE_HAVE_EMITC_DIALECT

namespace mlir {
namespace iree_compiler {

// TODO(#3817): move all of this code to the iree-compile driver/API.
// Breaking this up such that for development iree-opt runs all passes/pipelines
// and iree-translate strictly does the VM dialect to bytecode/emitc files will
// match upstream better, and then our own iree-compile C API/binary will do the
// whole end-to-end with options for bindings/targets/etc.
struct BindingOptions {
  // Whether to include runtime support functions for the IREE native ABI.
  bool native = true;
  // Whether to include runtime support functions required for the IREE TFLite
  // API compatibility bindings.
  bool tflite = false;
};

static BindingOptions getBindingOptionsFromFlags() {
  static llvm::cl::OptionCategory bindingOptionsCategory(
      "IREE translation binding support options");

  static llvm::cl::opt<bool> *bindingsNativeFlag = new llvm::cl::opt<bool>{
      "iree-native-bindings-support",
      llvm::cl::desc(
          "Include runtime support for native IREE ABI-compatible bindings"),
      llvm::cl::init(true), llvm::cl::cat(bindingOptionsCategory)};

  static llvm::cl::opt<bool> *bindingsTFLiteFlag = new llvm::cl::opt<bool>{
      "iree-tflite-bindings-support",
      llvm::cl::desc(
          "Include runtime support for the IREE TFLite compatibility bindings"),
      llvm::cl::init(false), llvm::cl::cat(bindingOptionsCategory)};

  BindingOptions bindingOptions;
  bindingOptions.native = *bindingsNativeFlag;
  bindingOptions.tflite = *bindingsTFLiteFlag;
  return bindingOptions;
}

// The transformation to apply to the input prior to main compiler execution.
// These input pipelines are purposefully primitive and mainly focused on
// test case/reproducers as opposed to anything that should be coming from
// a user. For user/framework level interfacing, a dedicated importer likely
// needs to be created in order to represent whole-module level framework
// quirks. These are just about the ops in the functions.
struct InputDialectOptions {
  enum class Type {
    // Applies no input transformation. Only supported core and extension ops
    // are supported.
    none,

    // Legalizes input defined over TOSA ops.
    tosa,

    // Legalizes input defined over MHLO ops.
    mhlo,
  };
  Type type;
};

static InputDialectOptions getInputDialectOptionsFromFlags() {
  static llvm::cl::OptionCategory inputDialectOptions(
      "IREE options for controlling the input transformations to apply");

  static llvm::cl::opt<InputDialectOptions::Type> *typeFlag =
      new llvm::cl::opt<InputDialectOptions::Type>{
          "iree-input-type", llvm::cl::desc("IREE input type"),
          llvm::cl::values(clEnumValN(InputDialectOptions::Type::none, "none",
                                      "No input dialect transformation"),
                           clEnumValN(InputDialectOptions::Type::tosa, "tosa",
                                      "Legalize from TOSA ops"),
                           clEnumValN(InputDialectOptions::Type::mhlo, "mhlo",
                                      "Legalize from MHLO ops")),
          llvm::cl::init(InputDialectOptions::Type::none),
          llvm::cl::cat(inputDialectOptions)};

  InputDialectOptions options;
  options.type = *typeFlag;
  return options;
}

// Performs initial dialect conversion to get the canonical input lowered into
// the IREE execution/dataflow dialect.
//
// This will fail if we cannot support the input yet. The hope is that any
// error that happens after this point is either backend-specific (like
// unsupported SPIR-V lowering) or a bug.
static LogicalResult convertToFlowModule(ModuleOp moduleOp) {
  PassManager passManager(moduleOp.getContext());
  mlir::applyPassManagerCLOptions(passManager);
  mlir::applyDefaultTimingPassManagerCLOptions(passManager);
  passManager.addInstrumentation(std::make_unique<PassTracing>());
  IREE::Flow::buildFlowTransformPassPipeline(passManager);
  if (failed(passManager.run(moduleOp))) {
    return moduleOp.emitError()
           << "failed to run flow transformation pass pipeline";
  }
  return success();
}

// Runs the flow->HAL transform pipeline to lower a flow module and compile
// executables for the specified target backends.
static LogicalResult convertToHALModule(
    ModuleOp moduleOp, IREE::HAL::TargetOptions executableOptions) {
  PassManager passManager(moduleOp.getContext());
  mlir::applyPassManagerCLOptions(passManager);
  mlir::applyDefaultTimingPassManagerCLOptions(passManager);
  passManager.addInstrumentation(std::make_unique<PassTracing>());
  IREE::HAL::buildHALTransformPassPipeline(passManager, executableOptions);
  if (failed(passManager.run(moduleOp))) {
    return moduleOp.emitError()
           << "failed to run HAL transformation pass pipeline";
  }
  return success();
}

// Converts the lowered module to a canonical vm.module containing only vm ops.
// This uses patterns to convert from standard ops and other dialects to their
// vm ABI form.
static LogicalResult convertToVMModule(ModuleOp moduleOp,
                                       IREE::VM::TargetOptions targetOptions) {
  PassManager passManager(moduleOp.getContext());
  mlir::applyPassManagerCLOptions(passManager);
  mlir::applyDefaultTimingPassManagerCLOptions(passManager);
  passManager.addInstrumentation(std::make_unique<PassTracing>());
  IREE::VM::buildVMTransformPassPipeline(passManager, targetOptions);
  if (failed(passManager.run(moduleOp))) {
    return moduleOp.emitError()
           << "failed to run VM transformation pass pipeline";
  }
  return success();
}

static void buildIREEVMTransformPassPipeline(
    BindingOptions bindingOptions, InputDialectOptions inputOptions,
    IREE::HAL::TargetOptions executableOptions,
    IREE::VM::TargetOptions targetOptions, OpPassManager &passManager) {
  if (bindingOptions.native) {
    IREE::ABI::buildTransformPassPipeline(passManager);
  }
  if (bindingOptions.tflite) {
    IREE::TFLite::buildTransformPassPipeline(passManager);
  }

  switch (inputOptions.type) {
    case InputDialectOptions::Type::none:
      break;
    case InputDialectOptions::Type::tosa:
      buildTOSAInputConversionPassPipeline(passManager);
      break;
    case InputDialectOptions::Type::mhlo:
      buildMHLOInputConversionPassPipeline(passManager);
      break;
  }

  IREE::Flow::buildFlowTransformPassPipeline(passManager);
  IREE::HAL::buildHALTransformPassPipeline(passManager, executableOptions);
  IREE::VM::buildVMTransformPassPipeline(passManager, targetOptions);
  passManager.addPass(mlir::iree_compiler::IREE::createDropCompilerHintsPass());
}

void buildDefaultIREEVMTransformPassPipeline(OpPassManager &passManager) {
  buildIREEVMTransformPassPipeline(
      getBindingOptionsFromFlags(), getInputDialectOptionsFromFlags(),
      IREE::HAL::getTargetOptionsFromFlags(),
      IREE::VM::getTargetOptionsFromFlags(), passManager);
}

void registerIREEVMTransformPassPipeline() {
  PassPipelineRegistration<> transformPassPipeline(
      "iree-transformation-pipeline",
      "Runs the full IREE input to VM transformation pipeline",
      [](OpPassManager &passManager) {
        buildDefaultIREEVMTransformPassPipeline(passManager);
      });
}

// Converts from our source to a vm.module in canonical form.
// After this completes we have a non-bytecode-specific vm.module that we
// could lower to other forms (LLVM IR, C, etc).
static LogicalResult translateFromMLIRToVM(
    ModuleOp moduleOp, BindingOptions bindingOptions,
    InputDialectOptions inputOptions,
    IREE::HAL::TargetOptions executableOptions,
    IREE::VM::TargetOptions targetOptions) {
  PassManager passManager(moduleOp.getContext());
  mlir::applyPassManagerCLOptions(passManager);
  mlir::applyDefaultTimingPassManagerCLOptions(passManager);
  passManager.addInstrumentation(std::make_unique<PassTracing>());
  buildIREEVMTransformPassPipeline(bindingOptions, inputOptions,
                                   executableOptions, targetOptions,
                                   passManager);
  if (failed(passManager.run(moduleOp))) {
    return moduleOp.emitError() << "conversion from source -> vm failed";
  }
  return success();
}

// Translates an MLIR module containing a set of supported IREE input dialects
// to an IREE VM bytecode module for loading at runtime.
//
// See iree/schemas/bytecode_module_def.fbs for the description of the
// serialized module format.
//
// Exposed via the --iree-mlir-to-vm-bytecode-module translation.
static LogicalResult translateFromMLIRToVMBytecodeModuleWithFlags(
    ModuleOp moduleOp, llvm::raw_ostream &output) {
  mlir::registerPassManagerCLOptions();
  auto bindingOptions = getBindingOptionsFromFlags();
  auto inputOptions = getInputDialectOptionsFromFlags();
  auto halTargetOptions = IREE::HAL::getTargetOptionsFromFlags();
  auto vmTargetOptions = IREE::VM::getTargetOptionsFromFlags();
  auto bytecodeTargetOptions = IREE::VM::getBytecodeTargetOptionsFromFlags();
  auto result = translateFromMLIRToVM(moduleOp, bindingOptions, inputOptions,
                                      halTargetOptions, vmTargetOptions);
  if (failed(result)) {
    return result;
  }
  return translateModuleToBytecode(moduleOp, bytecodeTargetOptions, output);
}

#ifdef IREE_HAVE_EMITC_DIALECT
// Translates an MLIR module containing a set of supported IREE input dialects
// to an IREE VM C module.
//
// Exposed via the --iree-mlir-to-vm-c-module translation.
static LogicalResult translateFromMLIRToVMCModule(
    ModuleOp moduleOp, BindingOptions bindingOptions,
    InputDialectOptions inputOptions,
    IREE::HAL::TargetOptions executableOptions,
    IREE::VM::TargetOptions targetOptions,
    IREE::VM::CTargetOptions cTargetOptions, llvm::raw_ostream &output) {
  auto result = translateFromMLIRToVM(moduleOp, bindingOptions, inputOptions,
                                      executableOptions, targetOptions);
  if (failed(result)) {
    return result;
  }

  // Serialize to c code.
  return mlir::iree_compiler::IREE::VM::translateModuleToC(
      moduleOp, cTargetOptions, output);
}

static LogicalResult translateFromMLIRToVMCModuleWithFlags(
    ModuleOp moduleOp, llvm::raw_ostream &output) {
  mlir::registerPassManagerCLOptions();
  auto bindingOptions = getBindingOptionsFromFlags();
  auto inputOptions = getInputDialectOptionsFromFlags();
  auto halTargetOptions = IREE::HAL::getTargetOptionsFromFlags();
  auto vmTargetOptions = IREE::VM::getTargetOptionsFromFlags();
  auto cTargetOptions = IREE::VM::getCTargetOptionsFromFlags();
  return translateFromMLIRToVMCModule(moduleOp, bindingOptions, inputOptions,
                                      halTargetOptions, vmTargetOptions,
                                      cTargetOptions, output);
}
#endif  // IREE_HAVE_EMITC_DIALECT

void registerIREEVMTranslationFlags() {
  getBindingOptionsFromFlags();
  getInputDialectOptionsFromFlags();
}

void registerIREEVMTranslation() {
  registerIREEVMTranslationFlags();
  TranslateFromMLIRRegistration toVMBytecodeModuleWithFlags(
      "iree-mlir-to-vm-bytecode-module",
      translateFromMLIRToVMBytecodeModuleWithFlags);

#ifdef IREE_HAVE_EMITC_DIALECT
  TranslateFromMLIRRegistration toVMCModuleWithFlags(
      "iree-mlir-to-vm-c-module", translateFromMLIRToVMCModuleWithFlags);
#endif  // IREE_HAVE_EMITC_DIALECT
}

}  // namespace iree_compiler
}  // namespace mlir
<commit_msg>Drop `translateFromMLIRToVMCModule()` (#6308)<commit_after>// Copyright 2019 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/Translation/IREEVM.h"

#include "iree/compiler/Bindings/Native/Transforms/Passes.h"
#include "iree/compiler/Bindings/TFLite/Transforms/Passes.h"
#include "iree/compiler/Dialect/Flow/Transforms/Passes.h"
#include "iree/compiler/Dialect/HAL/Transforms/Passes.h"
#include "iree/compiler/Dialect/IREE/Transforms/Passes.h"
#include "iree/compiler/Dialect/VM/Target/Bytecode/TranslationFlags.h"
#include "iree/compiler/Dialect/VM/Transforms/Passes.h"
#include "iree/compiler/InputConversion/MHLO/Passes.h"
#include "iree/compiler/InputConversion/TOSA/Passes.h"
#include "iree/compiler/Utils/TracingUtils.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Translation.h"

#ifdef IREE_HAVE_EMITC_DIALECT
#include "iree/compiler/Dialect/VM/Target/C/CModuleTarget.h"
#include "iree/compiler/Dialect/VM/Target/C/TranslationFlags.h"
#endif  // IREE_HAVE_EMITC_DIALECT

namespace mlir {
namespace iree_compiler {

// TODO(#3817): move all of this code to the iree-compile driver/API.
// Breaking this up such that for development iree-opt runs all passes/pipelines
// and iree-translate strictly does the VM dialect to bytecode/emitc files will
// match upstream better, and then our own iree-compile C API/binary will do the
// whole end-to-end with options for bindings/targets/etc.
struct BindingOptions {
  // Whether to include runtime support functions for the IREE native ABI.
  bool native = true;
  // Whether to include runtime support functions required for the IREE TFLite
  // API compatibility bindings.
  bool tflite = false;
};

static BindingOptions getBindingOptionsFromFlags() {
  static llvm::cl::OptionCategory bindingOptionsCategory(
      "IREE translation binding support options");

  static llvm::cl::opt<bool> *bindingsNativeFlag = new llvm::cl::opt<bool>{
      "iree-native-bindings-support",
      llvm::cl::desc(
          "Include runtime support for native IREE ABI-compatible bindings"),
      llvm::cl::init(true), llvm::cl::cat(bindingOptionsCategory)};

  static llvm::cl::opt<bool> *bindingsTFLiteFlag = new llvm::cl::opt<bool>{
      "iree-tflite-bindings-support",
      llvm::cl::desc(
          "Include runtime support for the IREE TFLite compatibility bindings"),
      llvm::cl::init(false), llvm::cl::cat(bindingOptionsCategory)};

  BindingOptions bindingOptions;
  bindingOptions.native = *bindingsNativeFlag;
  bindingOptions.tflite = *bindingsTFLiteFlag;
  return bindingOptions;
}

// The transformation to apply to the input prior to main compiler execution.
// These input pipelines are purposefully primitive and mainly focused on
// test case/reproducers as opposed to anything that should be coming from
// a user. For user/framework level interfacing, a dedicated importer likely
// needs to be created in order to represent whole-module level framework
// quirks. These are just about the ops in the functions.
struct InputDialectOptions {
  enum class Type {
    // Applies no input transformation. Only supported core and extension ops
    // are supported.
    none,

    // Legalizes input defined over TOSA ops.
    tosa,

    // Legalizes input defined over MHLO ops.
    mhlo,
  };
  Type type;
};

static InputDialectOptions getInputDialectOptionsFromFlags() {
  static llvm::cl::OptionCategory inputDialectOptions(
      "IREE options for controlling the input transformations to apply");

  static llvm::cl::opt<InputDialectOptions::Type> *typeFlag =
      new llvm::cl::opt<InputDialectOptions::Type>{
          "iree-input-type", llvm::cl::desc("IREE input type"),
          llvm::cl::values(clEnumValN(InputDialectOptions::Type::none, "none",
                                      "No input dialect transformation"),
                           clEnumValN(InputDialectOptions::Type::tosa, "tosa",
                                      "Legalize from TOSA ops"),
                           clEnumValN(InputDialectOptions::Type::mhlo, "mhlo",
                                      "Legalize from MHLO ops")),
          llvm::cl::init(InputDialectOptions::Type::none),
          llvm::cl::cat(inputDialectOptions)};

  InputDialectOptions options;
  options.type = *typeFlag;
  return options;
}

// Performs initial dialect conversion to get the canonical input lowered into
// the IREE execution/dataflow dialect.
//
// This will fail if we cannot support the input yet. The hope is that any
// error that happens after this point is either backend-specific (like
// unsupported SPIR-V lowering) or a bug.
static LogicalResult convertToFlowModule(ModuleOp moduleOp) {
  PassManager passManager(moduleOp.getContext());
  mlir::applyPassManagerCLOptions(passManager);
  mlir::applyDefaultTimingPassManagerCLOptions(passManager);
  passManager.addInstrumentation(std::make_unique<PassTracing>());
  IREE::Flow::buildFlowTransformPassPipeline(passManager);
  if (failed(passManager.run(moduleOp))) {
    return moduleOp.emitError()
           << "failed to run flow transformation pass pipeline";
  }
  return success();
}

// Runs the flow->HAL transform pipeline to lower a flow module and compile
// executables for the specified target backends.
static LogicalResult convertToHALModule(
    ModuleOp moduleOp, IREE::HAL::TargetOptions executableOptions) {
  PassManager passManager(moduleOp.getContext());
  mlir::applyPassManagerCLOptions(passManager);
  mlir::applyDefaultTimingPassManagerCLOptions(passManager);
  passManager.addInstrumentation(std::make_unique<PassTracing>());
  IREE::HAL::buildHALTransformPassPipeline(passManager, executableOptions);
  if (failed(passManager.run(moduleOp))) {
    return moduleOp.emitError()
           << "failed to run HAL transformation pass pipeline";
  }
  return success();
}

// Converts the lowered module to a canonical vm.module containing only vm ops.
// This uses patterns to convert from standard ops and other dialects to their
// vm ABI form.
static LogicalResult convertToVMModule(ModuleOp moduleOp,
                                       IREE::VM::TargetOptions targetOptions) {
  PassManager passManager(moduleOp.getContext());
  mlir::applyPassManagerCLOptions(passManager);
  mlir::applyDefaultTimingPassManagerCLOptions(passManager);
  passManager.addInstrumentation(std::make_unique<PassTracing>());
  IREE::VM::buildVMTransformPassPipeline(passManager, targetOptions);
  if (failed(passManager.run(moduleOp))) {
    return moduleOp.emitError()
           << "failed to run VM transformation pass pipeline";
  }
  return success();
}

static void buildIREEVMTransformPassPipeline(
    BindingOptions bindingOptions, InputDialectOptions inputOptions,
    IREE::HAL::TargetOptions executableOptions,
    IREE::VM::TargetOptions targetOptions, OpPassManager &passManager) {
  if (bindingOptions.native) {
    IREE::ABI::buildTransformPassPipeline(passManager);
  }
  if (bindingOptions.tflite) {
    IREE::TFLite::buildTransformPassPipeline(passManager);
  }

  switch (inputOptions.type) {
    case InputDialectOptions::Type::none:
      break;
    case InputDialectOptions::Type::tosa:
      buildTOSAInputConversionPassPipeline(passManager);
      break;
    case InputDialectOptions::Type::mhlo:
      buildMHLOInputConversionPassPipeline(passManager);
      break;
  }

  IREE::Flow::buildFlowTransformPassPipeline(passManager);
  IREE::HAL::buildHALTransformPassPipeline(passManager, executableOptions);
  IREE::VM::buildVMTransformPassPipeline(passManager, targetOptions);
  passManager.addPass(mlir::iree_compiler::IREE::createDropCompilerHintsPass());
}

void buildDefaultIREEVMTransformPassPipeline(OpPassManager &passManager) {
  buildIREEVMTransformPassPipeline(
      getBindingOptionsFromFlags(), getInputDialectOptionsFromFlags(),
      IREE::HAL::getTargetOptionsFromFlags(),
      IREE::VM::getTargetOptionsFromFlags(), passManager);
}

void registerIREEVMTransformPassPipeline() {
  PassPipelineRegistration<> transformPassPipeline(
      "iree-transformation-pipeline",
      "Runs the full IREE input to VM transformation pipeline",
      [](OpPassManager &passManager) {
        buildDefaultIREEVMTransformPassPipeline(passManager);
      });
}

// Converts from our source to a vm.module in canonical form.
// After this completes we have a non-bytecode-specific vm.module that we
// could lower to other forms (LLVM IR, C, etc).
static LogicalResult translateFromMLIRToVM(
    ModuleOp moduleOp, BindingOptions bindingOptions,
    InputDialectOptions inputOptions,
    IREE::HAL::TargetOptions executableOptions,
    IREE::VM::TargetOptions targetOptions) {
  PassManager passManager(moduleOp.getContext());
  mlir::applyPassManagerCLOptions(passManager);
  mlir::applyDefaultTimingPassManagerCLOptions(passManager);
  passManager.addInstrumentation(std::make_unique<PassTracing>());
  buildIREEVMTransformPassPipeline(bindingOptions, inputOptions,
                                   executableOptions, targetOptions,
                                   passManager);
  if (failed(passManager.run(moduleOp))) {
    return moduleOp.emitError() << "conversion from source -> vm failed";
  }
  return success();
}

// Translates an MLIR module containing a set of supported IREE input dialects
// to an IREE VM bytecode module for loading at runtime.
//
// See iree/schemas/bytecode_module_def.fbs for the description of the
// serialized module format.
//
// Exposed via the --iree-mlir-to-vm-bytecode-module translation.
static LogicalResult translateFromMLIRToVMBytecodeModuleWithFlags(
    ModuleOp moduleOp, llvm::raw_ostream &output) {
  mlir::registerPassManagerCLOptions();
  auto bindingOptions = getBindingOptionsFromFlags();
  auto inputOptions = getInputDialectOptionsFromFlags();
  auto halTargetOptions = IREE::HAL::getTargetOptionsFromFlags();
  auto vmTargetOptions = IREE::VM::getTargetOptionsFromFlags();
  auto bytecodeTargetOptions = IREE::VM::getBytecodeTargetOptionsFromFlags();
  auto result = translateFromMLIRToVM(moduleOp, bindingOptions, inputOptions,
                                      halTargetOptions, vmTargetOptions);
  if (failed(result)) {
    return result;
  }
  return translateModuleToBytecode(moduleOp, bytecodeTargetOptions, output);
}

#ifdef IREE_HAVE_EMITC_DIALECT
// Translates an MLIR module containing a set of supported IREE input dialects
// to an IREE VM C module.
//
// Exposed via the --iree-mlir-to-vm-c-module translation.
static LogicalResult translateFromMLIRToVMCModuleWithFlags(
    ModuleOp moduleOp, llvm::raw_ostream &output) {
  mlir::registerPassManagerCLOptions();
  auto bindingOptions = getBindingOptionsFromFlags();
  auto inputOptions = getInputDialectOptionsFromFlags();
  auto halTargetOptions = IREE::HAL::getTargetOptionsFromFlags();
  auto vmTargetOptions = IREE::VM::getTargetOptionsFromFlags();
  auto cTargetOptions = IREE::VM::getCTargetOptionsFromFlags();
  auto result = translateFromMLIRToVM(moduleOp, bindingOptions, inputOptions,
                                      halTargetOptions, vmTargetOptions);
  if (failed(result)) {
    return result;
  }
  // Serialize to c code.
  return mlir::iree_compiler::IREE::VM::translateModuleToC(
      moduleOp, cTargetOptions, output);
}
#endif  // IREE_HAVE_EMITC_DIALECT

void registerIREEVMTranslationFlags() {
  getBindingOptionsFromFlags();
  getInputDialectOptionsFromFlags();
}

void registerIREEVMTranslation() {
  registerIREEVMTranslationFlags();
  TranslateFromMLIRRegistration toVMBytecodeModuleWithFlags(
      "iree-mlir-to-vm-bytecode-module",
      translateFromMLIRToVMBytecodeModuleWithFlags);

#ifdef IREE_HAVE_EMITC_DIALECT
  TranslateFromMLIRRegistration toVMCModuleWithFlags(
      "iree-mlir-to-vm-c-module", translateFromMLIRToVMCModuleWithFlags);
#endif  // IREE_HAVE_EMITC_DIALECT
}

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


<commit_before>#include "perspective_camera.h"

PerspectiveCamera::PerspectiveCamera( void )
{}

PerspectiveCamera::PerspectiveCamera( const float min_x,
                                        const float max_x,
                                        const float min_y,
                                        const float max_y,
                                        const float distance, //distance to viewport
                                        const glm::ivec2 &resolution,
                                        const glm::vec3 &position,
                                        const glm::vec3 &up_vector,
                                        const glm::vec3 &look_at ) :
        Camera::Camera{ resolution,
                        position,
                        up_vector,
                        look_at },
        min_x_{ min_x },
        max_x_{ max_x },
        min_y_{ min_y },
        max_y_{ max_y },
        distance_{ distance }
{}

Ray PerspectiveCamera::getWorldSpaceRay( const glm::vec2 &pixel_coord ) const
{
    float width = max_x_ - min_x_;
    float height = max_y_ - min_y_;

    glm::vec3 direction{ ( pixel_coord[0]+0.5f )/ static_cast< float >( resolution_[0] ) * width + min_x_,
                         ( pixel_coord[1]+0.5f )/ static_cast< float >( resolution_[1] ) * -height - min_y_,
                         -distance_ };

    return Ray{ onb_.getBasisMatrix() * position_,
                glm::normalize( onb_.getBasisMatrix() * direction ) };
}<commit_msg>Perspective camera bug fixes<commit_after>#include "perspective_camera.h"

PerspectiveCamera::PerspectiveCamera( void )
{}

PerspectiveCamera::PerspectiveCamera( const float min_x,
                                        const float max_x,
                                        const float min_y,
                                        const float max_y,
                                        const float distance, //distance to viewport
                                        const glm::ivec2 &resolution,
                                        const glm::vec3 &position,
                                        const glm::vec3 &up_vector,
                                        const glm::vec3 &look_at ) :
        Camera::Camera{ resolution,
                        position,
                        up_vector,
                        look_at },
        min_x_{ min_x },
        max_x_{ max_x },
        min_y_{ min_y },
        max_y_{ max_y },
        distance_{ distance }
{}

Ray PerspectiveCamera::getWorldSpaceRay( const glm::vec2 &pixel_coord ) const
{
    float width = max_x_ - min_x_;
    float height = max_y_ - min_y_;

    glm::vec3 screen_point{ ( pixel_coord[0]+0.5f )/ static_cast< float >( resolution_[0] ) * width + min_x_,
                            ( pixel_coord[1]+0.5f )/ static_cast< float >( resolution_[1] ) * -height + max_y_,
                            -distance_ };

    return Ray{ position_, glm::normalize( onb_.getBasisMatrix() * screen_point ) };
}

<|endoftext|>


<commit_before>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/proxy/proxy_script_fetcher.h"

#include "base/file_path.h"
#include "base/compiler_specific.h"
#include "base/path_service.h"
#include "net/base/net_util.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/base/test_completion_callback.h"
#include "net/disk_cache/disk_cache.h"
#include "net/http/http_cache.h"
#include "net/url_request/url_request_unittest.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"

// TODO(eroman):
//   - Test canceling an outstanding request.
//   - Test deleting ProxyScriptFetcher while a request is in progress.

const wchar_t kDocRoot[] = L"net/data/proxy_script_fetcher_unittest";

struct FetchResult {
  int code;
  std::string bytes;
};

// A non-mock URL request which can access http:// and file:// urls.
class RequestContext : public URLRequestContext {
 public:
  RequestContext() {
    net::ProxyConfig no_proxy;
    host_resolver_ = net::CreateSystemHostResolver();
    proxy_service_ = net::ProxyService::CreateFixed(no_proxy);
    ssl_config_service_ = new net::SSLConfigServiceDefaults;

    http_transaction_factory_ =
        new net::HttpCache(net::HttpNetworkLayer::CreateFactory(
            host_resolver_, proxy_service_, ssl_config_service_),
            disk_cache::CreateInMemoryCacheBackend(0));
  }
  ~RequestContext() {
    delete http_transaction_factory_;
  }
};

// Required to be in net namespace by FRIEND_TEST.
namespace net {

// Get a file:// url relative to net/data/proxy/proxy_script_fetcher_unittest.
GURL GetTestFileUrl(const std::string& relpath) {
  FilePath path;
  PathService::Get(base::DIR_SOURCE_ROOT, &path);
  path = path.AppendASCII("net");
  path = path.AppendASCII("data");
  path = path.AppendASCII("proxy_script_fetcher_unittest");
  GURL base_url = FilePathToFileURL(path);
  return GURL(base_url.spec() + "/" + relpath);
}

typedef PlatformTest ProxyScriptFetcherTest;

TEST_F(ProxyScriptFetcherTest, FileUrl) {
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  { // Fetch a non-existent file.
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(GetTestFileUrl("does-not-exist"),
                                    &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(ERR_FILE_NOT_FOUND, callback.WaitForResult());
    EXPECT_TRUE(bytes.empty());
  }
  { // Fetch a file that exists.
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(GetTestFileUrl("pac.txt"),
                                    &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("-pac.txt-\n", bytes);
  }
}

// Note that all mime types are allowed for PAC file, to be consistent
// with other browsers.
TEST_F(ProxyScriptFetcherTest, HttpMimeType) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  { // Fetch a PAC with mime type "text/plain"
    GURL url = server->TestServerPage("files/pac.txt");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("-pac.txt-\n", bytes);
  }
  { // Fetch a PAC with mime type "text/html"
    GURL url = server->TestServerPage("files/pac.html");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("-pac.html-\n", bytes);
  }
  { // Fetch a PAC with mime type "application/x-ns-proxy-autoconfig"
    GURL url = server->TestServerPage("files/pac.nsproxy");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("-pac.nsproxy-\n", bytes);
  }
}

TEST_F(ProxyScriptFetcherTest, HttpStatusCode) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  { // Fetch a PAC which gives a 500 -- FAIL
    GURL url = server->TestServerPage("files/500.pac");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(ERR_PAC_STATUS_NOT_OK, callback.WaitForResult());
    EXPECT_TRUE(bytes.empty());
  }
  { // Fetch a PAC which gives a 404 -- FAIL
    GURL url = server->TestServerPage("files/404.pac");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(ERR_PAC_STATUS_NOT_OK, callback.WaitForResult());
    EXPECT_TRUE(bytes.empty());
  }
}

TEST_F(ProxyScriptFetcherTest, ContentDisposition) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  // Fetch PAC scripts via HTTP with a Content-Disposition header -- should
  // have no effect.
  GURL url = server->TestServerPage("files/downloadable.pac");
  std::string bytes;
  TestCompletionCallback callback;
  int result = pac_fetcher->Fetch(url, &bytes, &callback);
  EXPECT_EQ(ERR_IO_PENDING, result);
  EXPECT_EQ(OK, callback.WaitForResult());
  EXPECT_EQ("-downloadable.pac-\n", bytes);
}

TEST_F(ProxyScriptFetcherTest, NoCache) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  // Fetch a PAC script whose HTTP headers make it cacheable for 1 hour.
  GURL url = server->TestServerPage("files/cacheable_1hr.pac");
  {
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("-cacheable_1hr.pac-\n", bytes);
  }

  // Now kill the HTTP server.
  server->SendQuit();
  EXPECT_TRUE(server->WaitToFinish(20000));
  server = NULL;

  // Try to fetch the file again -- if should fail, since the server is not
  // running anymore. (If it were instead being loaded from cache, we would
  // get a success.
  {
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(ERR_CONNECTION_REFUSED, callback.WaitForResult());
  }
}

TEST_F(ProxyScriptFetcherTest, TooLarge) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  // Set the maximum response size to 50 bytes.
  int prev_size = ProxyScriptFetcher::SetSizeConstraintForUnittest(50);

  // These two URLs are the same file, but are http:// vs file://
  GURL urls[] = {
    server->TestServerPage("files/large-pac.nsproxy"),
    GetTestFileUrl("large-pac.nsproxy")
  };

  // Try fetching URLs that are 101 bytes large. We should abort the request
  // after 50 bytes have been read, and fail with a too large error.
  for (size_t i = 0; i < arraysize(urls); ++i) {
    const GURL& url = urls[i];
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(ERR_FILE_TOO_BIG, callback.WaitForResult());
    EXPECT_TRUE(bytes.empty());
  }

  // Restore the original size bound.
  ProxyScriptFetcher::SetSizeConstraintForUnittest(prev_size);

  { // Make sure we can still fetch regular URLs.
    GURL url = server->TestServerPage("files/pac.nsproxy");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("-pac.nsproxy-\n", bytes);
  }
}

TEST_F(ProxyScriptFetcherTest, Hang) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  // Set the timeout period to 0.5 seconds.
  int prev_timeout =
      ProxyScriptFetcher::SetTimeoutConstraintForUnittest(500);

  // Try fetching a URL which takes 1.2 seconds. We should abort the request
  // after 500 ms, and fail with a timeout error.
  { GURL url = server->TestServerPage("slow/proxy.pac?1.2");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(ERR_TIMED_OUT, callback.WaitForResult());
    EXPECT_TRUE(bytes.empty());
  }

  // Restore the original timeout period.
  ProxyScriptFetcher::SetTimeoutConstraintForUnittest(prev_timeout);

  { // Make sure we can still fetch regular URLs.
    GURL url = server->TestServerPage("files/pac.nsproxy");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("-pac.nsproxy-\n", bytes);
  }
}

// The ProxyScriptFetcher should decode any content-codings
// (like gzip, bzip, etc.), and apply any charset conversions to yield
// UTF8.
TEST_F(ProxyScriptFetcherTest, Encodings) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  // Test a response that is gzip-encoded -- should get inflated.
  {
    GURL url = server->TestServerPage("files/gzipped_pac");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("This data was gzipped.\n", bytes);
  }

  // Test a response that was served as UTF-16 (BE). It should
  // be converted to UTF8.
  {
    GURL url = server->TestServerPage("files/utf16be_pac");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("This was encoded as UTF-16BE.\n", bytes);
  }
}

}  // namespace net
<commit_msg>Refactor: Don't send the quit command before killing test server for ProxyScriptFetcherTest.NoCache. Instead we just murder the process directly.<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/proxy/proxy_script_fetcher.h"

#include "base/file_path.h"
#include "base/compiler_specific.h"
#include "base/path_service.h"
#include "net/base/net_util.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/base/test_completion_callback.h"
#include "net/disk_cache/disk_cache.h"
#include "net/http/http_cache.h"
#include "net/url_request/url_request_unittest.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"

// TODO(eroman):
//   - Test canceling an outstanding request.
//   - Test deleting ProxyScriptFetcher while a request is in progress.

const wchar_t kDocRoot[] = L"net/data/proxy_script_fetcher_unittest";

struct FetchResult {
  int code;
  std::string bytes;
};

// A non-mock URL request which can access http:// and file:// urls.
class RequestContext : public URLRequestContext {
 public:
  RequestContext() {
    net::ProxyConfig no_proxy;
    host_resolver_ = net::CreateSystemHostResolver();
    proxy_service_ = net::ProxyService::CreateFixed(no_proxy);
    ssl_config_service_ = new net::SSLConfigServiceDefaults;

    http_transaction_factory_ =
        new net::HttpCache(net::HttpNetworkLayer::CreateFactory(
            host_resolver_, proxy_service_, ssl_config_service_),
            disk_cache::CreateInMemoryCacheBackend(0));
  }
  ~RequestContext() {
    delete http_transaction_factory_;
  }
};

// Required to be in net namespace by FRIEND_TEST.
namespace net {

// Get a file:// url relative to net/data/proxy/proxy_script_fetcher_unittest.
GURL GetTestFileUrl(const std::string& relpath) {
  FilePath path;
  PathService::Get(base::DIR_SOURCE_ROOT, &path);
  path = path.AppendASCII("net");
  path = path.AppendASCII("data");
  path = path.AppendASCII("proxy_script_fetcher_unittest");
  GURL base_url = FilePathToFileURL(path);
  return GURL(base_url.spec() + "/" + relpath);
}

typedef PlatformTest ProxyScriptFetcherTest;

TEST_F(ProxyScriptFetcherTest, FileUrl) {
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  { // Fetch a non-existent file.
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(GetTestFileUrl("does-not-exist"),
                                    &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(ERR_FILE_NOT_FOUND, callback.WaitForResult());
    EXPECT_TRUE(bytes.empty());
  }
  { // Fetch a file that exists.
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(GetTestFileUrl("pac.txt"),
                                    &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("-pac.txt-\n", bytes);
  }
}

// Note that all mime types are allowed for PAC file, to be consistent
// with other browsers.
TEST_F(ProxyScriptFetcherTest, HttpMimeType) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  { // Fetch a PAC with mime type "text/plain"
    GURL url = server->TestServerPage("files/pac.txt");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("-pac.txt-\n", bytes);
  }
  { // Fetch a PAC with mime type "text/html"
    GURL url = server->TestServerPage("files/pac.html");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("-pac.html-\n", bytes);
  }
  { // Fetch a PAC with mime type "application/x-ns-proxy-autoconfig"
    GURL url = server->TestServerPage("files/pac.nsproxy");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("-pac.nsproxy-\n", bytes);
  }
}

TEST_F(ProxyScriptFetcherTest, HttpStatusCode) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  { // Fetch a PAC which gives a 500 -- FAIL
    GURL url = server->TestServerPage("files/500.pac");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(ERR_PAC_STATUS_NOT_OK, callback.WaitForResult());
    EXPECT_TRUE(bytes.empty());
  }
  { // Fetch a PAC which gives a 404 -- FAIL
    GURL url = server->TestServerPage("files/404.pac");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(ERR_PAC_STATUS_NOT_OK, callback.WaitForResult());
    EXPECT_TRUE(bytes.empty());
  }
}

TEST_F(ProxyScriptFetcherTest, ContentDisposition) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  // Fetch PAC scripts via HTTP with a Content-Disposition header -- should
  // have no effect.
  GURL url = server->TestServerPage("files/downloadable.pac");
  std::string bytes;
  TestCompletionCallback callback;
  int result = pac_fetcher->Fetch(url, &bytes, &callback);
  EXPECT_EQ(ERR_IO_PENDING, result);
  EXPECT_EQ(OK, callback.WaitForResult());
  EXPECT_EQ("-downloadable.pac-\n", bytes);
}

TEST_F(ProxyScriptFetcherTest, NoCache) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  // Fetch a PAC script whose HTTP headers make it cacheable for 1 hour.
  GURL url = server->TestServerPage("files/cacheable_1hr.pac");
  {
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("-cacheable_1hr.pac-\n", bytes);
  }

  // Now kill the HTTP server.
  EXPECT_TRUE(server->Stop());  // Verify it shutdown synchronously.
  server = NULL;

  // Try to fetch the file again -- if should fail, since the server is not
  // running anymore. (If it were instead being loaded from cache, we would
  // get a success.
  {
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(ERR_CONNECTION_REFUSED, callback.WaitForResult());
  }
}

TEST_F(ProxyScriptFetcherTest, TooLarge) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  // Set the maximum response size to 50 bytes.
  int prev_size = ProxyScriptFetcher::SetSizeConstraintForUnittest(50);

  // These two URLs are the same file, but are http:// vs file://
  GURL urls[] = {
    server->TestServerPage("files/large-pac.nsproxy"),
    GetTestFileUrl("large-pac.nsproxy")
  };

  // Try fetching URLs that are 101 bytes large. We should abort the request
  // after 50 bytes have been read, and fail with a too large error.
  for (size_t i = 0; i < arraysize(urls); ++i) {
    const GURL& url = urls[i];
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(ERR_FILE_TOO_BIG, callback.WaitForResult());
    EXPECT_TRUE(bytes.empty());
  }

  // Restore the original size bound.
  ProxyScriptFetcher::SetSizeConstraintForUnittest(prev_size);

  { // Make sure we can still fetch regular URLs.
    GURL url = server->TestServerPage("files/pac.nsproxy");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("-pac.nsproxy-\n", bytes);
  }
}

TEST_F(ProxyScriptFetcherTest, Hang) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  // Set the timeout period to 0.5 seconds.
  int prev_timeout =
      ProxyScriptFetcher::SetTimeoutConstraintForUnittest(500);

  // Try fetching a URL which takes 1.2 seconds. We should abort the request
  // after 500 ms, and fail with a timeout error.
  { GURL url = server->TestServerPage("slow/proxy.pac?1.2");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(ERR_TIMED_OUT, callback.WaitForResult());
    EXPECT_TRUE(bytes.empty());
  }

  // Restore the original timeout period.
  ProxyScriptFetcher::SetTimeoutConstraintForUnittest(prev_timeout);

  { // Make sure we can still fetch regular URLs.
    GURL url = server->TestServerPage("files/pac.nsproxy");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("-pac.nsproxy-\n", bytes);
  }
}

// The ProxyScriptFetcher should decode any content-codings
// (like gzip, bzip, etc.), and apply any charset conversions to yield
// UTF8.
TEST_F(ProxyScriptFetcherTest, Encodings) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<URLRequestContext> context = new RequestContext;
  scoped_ptr<ProxyScriptFetcher> pac_fetcher(
      ProxyScriptFetcher::Create(context));

  // Test a response that is gzip-encoded -- should get inflated.
  {
    GURL url = server->TestServerPage("files/gzipped_pac");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("This data was gzipped.\n", bytes);
  }

  // Test a response that was served as UTF-16 (BE). It should
  // be converted to UTF8.
  {
    GURL url = server->TestServerPage("files/utf16be_pac");
    std::string bytes;
    TestCompletionCallback callback;
    int result = pac_fetcher->Fetch(url, &bytes, &callback);
    EXPECT_EQ(ERR_IO_PENDING, result);
    EXPECT_EQ(OK, callback.WaitForResult());
    EXPECT_EQ("This was encoded as UTF-16BE.\n", bytes);
  }
}

}  // namespace net
<|endoftext|>


<commit_before>#pragma once

#include <tuple>
#include <type_traits>

namespace THI {

template <std::size_t N = 0, typename Func, typename... Tp,
          typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr>
void forEach(const Func&, const std::tuple<Tp...>&)
{
}

template <std::size_t N = 0, typename Func, typename... Tp,
          typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr>
void forEach(const Func& func, const std::tuple<Tp...>& tuple)
{
    func(std::get<N>(tuple));
    forEach<N + 1, Func, Tp...>(func, tuple);
}

template <std::size_t N = 0, typename Func, typename... Tp,
          typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr>
void forEachWithIndex(const Func&, const std::tuple<Tp...>&)
{
}

template <std::size_t N = 0, typename Func, typename... Tp,
          typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr>
void forEachWithIndex(const Func& func, const std::tuple<Tp...>& tuple)
{
    func(N, std::get<N>(tuple));
    forEachWithIndex<N + 1, Func, Tp...>(func, tuple);
}

template <std::size_t N = 0, typename Func, typename Identity, typename... Tp,
          typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr>
auto foldL(const Func&, const Identity& identity, const std::tuple<Tp...>&)
{
    return identity;
}

template <std::size_t N = 0, typename Func, typename Identity, typename... Tp,
          typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr>
auto foldL(const Func& func, const Identity& identity,
           const std::tuple<Tp...>& tuple)
{
    return foldL<N + 1, Func, Identity, Tp...>(
        func, func(identity, std::get<N>(tuple)), tuple);
}

template <std::size_t N = 0, typename Func, typename Identity, typename... Tp,
          typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr>
auto foldR(const Func&, const Identity& identity, const std::tuple<Tp...>&)
{
    return identity;
}

template <std::size_t N = 0, typename Func, typename Identity, typename... Tp,
          typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr>
auto foldR(const Func& func, const Identity& identity,
           const std::tuple<Tp...>& tuple)
{
    return func(std::get<N>(tuple),
                foldR<N + 1, Func, Identity, Tp...>(func, identity, tuple));
}

template <std::size_t N = 0, typename... Tp,
          typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr>
auto reverse(const std::tuple<Tp...>&)

{
    return std::make_tuple();
}

template <std::size_t N = 0, typename... Tp,
          typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr>
auto reverse(const std::tuple<Tp...>& tuple)
{
    return std::tuple_cat(reverse<N + 1>(tuple),
                          std::make_tuple(std::get<N>(tuple)));
}

} // namespace THI
<commit_msg>remove unnecessary template argument<commit_after>#pragma once

#include <tuple>
#include <type_traits>

namespace THI {

template <std::size_t N = 0, typename Func, typename... Tp,
          typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr>
void forEach(const Func&, const std::tuple<Tp...>&)
{
}

template <std::size_t N = 0, typename Func, typename... Tp,
          typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr>
void forEach(const Func& func, const std::tuple<Tp...>& tuple)
{
    func(std::get<N>(tuple));
    forEach<N + 1>(func, tuple);
}

template <std::size_t N = 0, typename Func, typename... Tp,
          typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr>
void forEachWithIndex(const Func&, const std::tuple<Tp...>&)
{
}

template <std::size_t N = 0, typename Func, typename... Tp,
          typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr>
void forEachWithIndex(const Func& func, const std::tuple<Tp...>& tuple)
{
    func(N, std::get<N>(tuple));
    forEachWithIndex<N + 1>(func, tuple);
}

template <std::size_t N = 0, typename Func, typename Identity, typename... Tp,
          typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr>
auto foldL(const Func&, const Identity& identity, const std::tuple<Tp...>&)
{
    return identity;
}

template <std::size_t N = 0, typename Func, typename Identity, typename... Tp,
          typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr>
auto foldL(const Func& func, const Identity& identity,
           const std::tuple<Tp...>& tuple)
{
    return foldL<N + 1>(func, func(identity, std::get<N>(tuple)), tuple);
}

template <std::size_t N = 0, typename Func, typename Identity, typename... Tp,
          typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr>
auto foldR(const Func&, const Identity& identity, const std::tuple<Tp...>&)
{
    return identity;
}

template <std::size_t N = 0, typename Func, typename Identity, typename... Tp,
          typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr>
auto foldR(const Func& func, const Identity& identity,
           const std::tuple<Tp...>& tuple)
{
    return func(std::get<N>(tuple), foldR<N + 1>(func, identity, tuple));
}

template <std::size_t N = 0, typename... Tp,
          typename std::enable_if_t<N == sizeof...(Tp)>* = nullptr>
auto reverse(const std::tuple<Tp...>&)
{
    return std::make_tuple();
}

template <std::size_t N = 0, typename... Tp,
          typename std::enable_if_t<(N < sizeof...(Tp))>* = nullptr>
auto reverse(const std::tuple<Tp...>& tuple)
{
    return std::tuple_cat(reverse<N + 1>(tuple),
                          std::make_tuple(std::get<N>(tuple)));
}

} // namespace THI
<|endoftext|>


<commit_before>#include <stan/variational/advi.hpp>
#include <gtest/gtest.h>
#include <vector>
#include <string>

#include <boost/random/additive_combine.hpp> // L'Ecuyer RNG

#include <test/test-models/good/variational/multivariate_no_constraint.hpp>

typedef boost::ecuyer1988 rng_t;
typedef multivariate_no_constraint_model_namespace::multivariate_no_constraint_model Model;

TEST(advi_test, multivar_no_constraint_fullrank_ELBO) {

  // Create mock data_var_context
  static const std::string DATA = "";
  std::stringstream data_stream(DATA);
  stan::io::dump dummy_context(data_stream);

  // Instantiate model
  Model my_model(dummy_context);

  // RNG
  rng_t base_rng(0);

  // Dummy input
  Eigen::VectorXd cont_params = Eigen::VectorXd::Zero(2);
  cont_params(0) = 0.75;
  cont_params(1) = 0.75;

  // ADVI
  stan::variational::advi<Model, rng_t> test_advi(my_model,
                                                  cont_params,
                                                  0,
                                                  10,
                                                  1e4, // absurdly high!
                                                  0.1,
                                                  base_rng,
                                                  100,
                                                  &std::cout,
                                                  &std::cout,
                                                  &std::cout);

  // Create some arbitrary variational q() family to calculate the ELBO over
  Eigen::VectorXd mu     = Eigen::VectorXd::Constant(my_model.num_params_r(),
                                                      2.5);
  Eigen::MatrixXd L_chol = Eigen::MatrixXd::Identity(my_model.num_params_r(),
                                                     my_model.num_params_r());
  stan::variational::advi_params_fullrank muL =
    stan::variational::advi_params_fullrank(mu, L_chol);

  double elbo = 0.0;
  elbo = test_advi.calc_ELBO(muL, 0.0);//constant_factor);
  std::cout << elbo << std::endl;

  double zeta = -0.5 * ( 3*2*log(2.0*stan::math::pi()) + 18.5 + 25 + 13 );
  Eigen::VectorXd mu_J = Eigen::VectorXd::Zero(2);
  mu_J(0) = 10.5;
  mu_J(1) =  7.5;

  double elbo_true = 0.0;
  elbo_true += zeta;
  elbo_true += mu_J.dot(mu);
  elbo_true += -0.5 * ( mu.dot(mu) + 3*2 );
  elbo_true += 1 + log(2.0*stan::math::pi());
  std::cout << elbo_true << std::endl;

  // Can calculate ELBO using formula for E_normal[(something - x)^2]
  // (see Sam Roweis' notes on Gaussian identities)
  //
  // mu0 = np.array([3.7, 2.7])
  // x1  = np.array([4.0, 3.0])
  // x2  = np.array([3.5, 2.5])
  // z   = np.array([5, 5])
  //
  // ELBO = - 0.5 * ( 6 + np.linalg.norm(x1-z)**2
  //                    + np.linalg.norm(x2-z)**2
  //                    + np.linalg.norm(z-mu0)**2 ) + 2
  //

  // FIXME: perhaps make EPSILON depend on stan::vb::bbvb.n_monte_carlo_ ?
  double const EPSILON = 1.0;
  EXPECT_NEAR(elbo_true, elbo, EPSILON);

}

<commit_msg>moved the test include before the advi.hpp<commit_after>#include <test/test-models/good/variational/multivariate_no_constraint.hpp>
#include <stan/variational/advi.hpp>
#include <gtest/gtest.h>
#include <vector>
#include <string>

#include <boost/random/additive_combine.hpp> // L'Ecuyer RNG

typedef boost::ecuyer1988 rng_t;
typedef multivariate_no_constraint_model_namespace::multivariate_no_constraint_model Model;

TEST(advi_test, multivar_no_constraint_fullrank_ELBO) {

  // Create mock data_var_context
  static const std::string DATA = "";
  std::stringstream data_stream(DATA);
  stan::io::dump dummy_context(data_stream);

  // Instantiate model
  Model my_model(dummy_context);

  // RNG
  rng_t base_rng(0);

  // Dummy input
  Eigen::VectorXd cont_params = Eigen::VectorXd::Zero(2);
  cont_params(0) = 0.75;
  cont_params(1) = 0.75;

  // ADVI
  stan::variational::advi<Model, rng_t> test_advi(my_model,
                                                  cont_params,
                                                  0,
                                                  10,
                                                  1e4, // absurdly high!
                                                  0.1,
                                                  base_rng,
                                                  100,
                                                  &std::cout,
                                                  &std::cout,
                                                  &std::cout);

  // Create some arbitrary variational q() family to calculate the ELBO over
  Eigen::VectorXd mu     = Eigen::VectorXd::Constant(my_model.num_params_r(),
                                                      2.5);
  Eigen::MatrixXd L_chol = Eigen::MatrixXd::Identity(my_model.num_params_r(),
                                                     my_model.num_params_r());
  stan::variational::advi_params_fullrank muL =
    stan::variational::advi_params_fullrank(mu, L_chol);

  double elbo = 0.0;
  elbo = test_advi.calc_ELBO(muL, 0.0);//constant_factor);
  std::cout << elbo << std::endl;

  double zeta = -0.5 * ( 3*2*log(2.0*stan::math::pi()) + 18.5 + 25 + 13 );
  Eigen::VectorXd mu_J = Eigen::VectorXd::Zero(2);
  mu_J(0) = 10.5;
  mu_J(1) =  7.5;

  double elbo_true = 0.0;
  elbo_true += zeta;
  elbo_true += mu_J.dot(mu);
  elbo_true += -0.5 * ( mu.dot(mu) + 3*2 );
  elbo_true += 1 + log(2.0*stan::math::pi());
  std::cout << elbo_true << std::endl;

  // Can calculate ELBO using formula for E_normal[(something - x)^2]
  // (see Sam Roweis' notes on Gaussian identities)
  //
  // mu0 = np.array([3.7, 2.7])
  // x1  = np.array([4.0, 3.0])
  // x2  = np.array([3.5, 2.5])
  // z   = np.array([5, 5])
  //
  // ELBO = - 0.5 * ( 6 + np.linalg.norm(x1-z)**2
  //                    + np.linalg.norm(x2-z)**2
  //                    + np.linalg.norm(z-mu0)**2 ) + 2
  //

  // FIXME: perhaps make EPSILON depend on stan::vb::bbvb.n_monte_carlo_ ?
  double const EPSILON = 1.0;
  EXPECT_NEAR(elbo_true, elbo, EPSILON);

}

<|endoftext|>


<commit_before>#include <catch2/catch.hpp>

#include "virtual_hid_device_utility.hpp"

TEST_CASE("pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::modifiers") {
  {
    namespace hid_report = pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report;

    hid_report::modifiers modifiers;
    modifiers.insert(hid_report::modifier::left_shift);
    modifiers.insert(hid_report::modifier::right_command);

    nlohmann::json expected = nlohmann::json::array();
    expected.push_back("left_shift");
    expected.push_back("right_command");

    REQUIRE(nlohmann::json(modifiers).dump() == expected.dump());
  }
}

TEST_CASE("karabiner_virtual_hid_device::hid_report::keys") {
  namespace hid_report = pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report;

  // keyboard_or_keypad
  {
    hid_report::keys keys;
    keys.insert(type_safe::get(*(krbn::make_hid_usage(krbn::key_code::keyboard_a))));
    keys.insert(type_safe::get(*(krbn::make_hid_usage(krbn::key_code::keyboard_b))));
    keys.insert(type_safe::get(*(krbn::make_hid_usage(krbn::key_code::keyboard_c))));
    keys.erase(type_safe::get(*(krbn::make_hid_usage(krbn::key_code::keyboard_a))));

    nlohmann::json expected = nlohmann::json::array();
    expected.push_back("b");
    expected.push_back("c");

    REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::keyboard_or_keypad).dump() == expected.dump());
  }
  // consumer
  {
    hid_report::keys keys;
    keys.insert(type_safe::get(*(krbn::make_hid_usage(krbn::consumer_key_code::rewind))));
    keys.insert(type_safe::get(*(krbn::make_hid_usage(krbn::consumer_key_code::eject))));
    keys.insert(type_safe::get(*(krbn::make_hid_usage(krbn::consumer_key_code::mute))));

    nlohmann::json expected = nlohmann::json::array();
    expected.push_back("rewind");
    expected.push_back("eject");
    expected.push_back("mute");

    REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::consumer).dump() == expected.dump());
  }
  // apple_vendor_top_case
  {
    hid_report::keys keys;
    keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_top_case::keyboard_fn));
    keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_top_case::brightness_up));
    keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_top_case::illumination_up));

    nlohmann::json expected = nlohmann::json::array();
    expected.push_back("fn");
    expected.push_back("apple_top_case_display_brightness_increment");
    expected.push_back("illumination_increment");

    REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::apple_vendor_top_case).dump() == expected.dump());
  }
  // apple_vendor_keyboard
  {
    hid_report::keys keys;
    keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_keyboard::expose_all));
    keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_keyboard::launchpad));

    nlohmann::json expected = nlohmann::json::array();
    expected.push_back("mission_control");
    expected.push_back("launchpad");

    REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::apple_vendor_keyboard).dump() == expected.dump());
  }
}

TEST_CASE("karabiner_virtual_hid_device::hid_report::buttons") {
  {
    pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::buttons buttons;
    buttons.insert(1);
    buttons.insert(32);

    nlohmann::json expected = nlohmann::json::array();
    expected.push_back("button1");
    expected.push_back("button32");

    REQUIRE(nlohmann::json(buttons).dump() == expected.dump());
  }
}
<commit_msg>Update tests<commit_after>#include <catch2/catch.hpp>

#include "virtual_hid_device_utility.hpp"

TEST_CASE("pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::modifiers") {
  {
    namespace hid_report = pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report;

    hid_report::modifiers modifiers;
    modifiers.insert(hid_report::modifier::left_shift);
    modifiers.insert(hid_report::modifier::right_command);

    nlohmann::json expected = nlohmann::json::array();
    expected.push_back("left_shift");
    expected.push_back("right_command");

    REQUIRE(nlohmann::json(modifiers).dump() == expected.dump());
  }
}

TEST_CASE("karabiner_virtual_hid_device::hid_report::keys") {
  namespace hid_report = pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report;

  // keyboard_or_keypad
  {
    hid_report::keys keys;
    keys.insert(type_safe::get(pqrs::hid::usage::keyboard_or_keypad::keyboard_a));
    keys.insert(type_safe::get(pqrs::hid::usage::keyboard_or_keypad::keyboard_b));
    keys.insert(type_safe::get(pqrs::hid::usage::keyboard_or_keypad::keyboard_c));
    keys.erase(type_safe::get(pqrs::hid::usage::keyboard_or_keypad::keyboard_a));

    nlohmann::json expected = nlohmann::json::array();
    expected.push_back("b");
    expected.push_back("c");

    REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::keyboard_or_keypad).dump() == expected.dump());
  }
  // consumer
  {
    hid_report::keys keys;
    keys.insert(type_safe::get(pqrs::hid::usage::consumer::rewind));
    keys.insert(type_safe::get(pqrs::hid::usage::consumer::eject));
    keys.insert(type_safe::get(pqrs::hid::usage::consumer::mute));

    nlohmann::json expected = nlohmann::json::array();
    expected.push_back("rewind");
    expected.push_back("eject");
    expected.push_back("mute");

    REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::consumer).dump() == expected.dump());
  }
  // apple_vendor_top_case
  {
    hid_report::keys keys;
    keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_top_case::keyboard_fn));
    keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_top_case::brightness_up));
    keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_top_case::illumination_up));

    nlohmann::json expected = nlohmann::json::array();
    expected.push_back("fn");
    expected.push_back("apple_top_case_display_brightness_increment");
    expected.push_back("illumination_increment");

    REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::apple_vendor_top_case).dump() == expected.dump());
  }
  // apple_vendor_keyboard
  {
    hid_report::keys keys;
    keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_keyboard::expose_all));
    keys.insert(type_safe::get(pqrs::hid::usage::apple_vendor_keyboard::launchpad));

    nlohmann::json expected = nlohmann::json::array();
    expected.push_back("mission_control");
    expected.push_back("launchpad");

    REQUIRE(krbn::virtual_hid_device_utility::to_json(keys, pqrs::hid::usage_page::apple_vendor_keyboard).dump() == expected.dump());
  }
}

TEST_CASE("karabiner_virtual_hid_device::hid_report::buttons") {
  {
    pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::buttons buttons;
    buttons.insert(1);
    buttons.insert(32);

    nlohmann::json expected = nlohmann::json::array();
    expected.push_back("button1");
    expected.push_back("button32");

    REQUIRE(nlohmann::json(buttons).dump() == expected.dump());
  }
}
<|endoftext|>


<commit_before>#include "MultipleKinectsPlatformServer.h"

namespace MultipleKinectsPlatformServer{

	Core::Core(/*Server Address*/string address,/*Server Port*/string httpPort,string udpPort){
	  try
	  {
		/*Upgraded the Priority Class*/
		DWORD dwPriClass;
		dwPriClass = GetPriorityClass(GetCurrentProcess());
		cout << "Current priority class is " << std::hex << dwPriClass << endl;
		if(!SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS)){
			cout << "Failed to upgrade priority class" << GetLastError() << endl;
		}else{
			dwPriClass = GetPriorityClass(GetCurrentProcess());
			cout << "Upgraded priority class is " << std::hex << dwPriClass << endl;
		}

		/* Communicate with a centralised time server */
		unsigned short randomTimeServerId = rand()%5;
		string timeServer = std::to_string(randomTimeServerId)+".asia.pool.ntp.org";
		this->ReportStatus("Sync with Time Server - "+ timeServer);
		NTPClient timeClient(timeServer);
		long timeFromServer = timeClient.RequestDatetime_UNIX();
		this->_time = new Timer(timeFromServer);
		this->_time = new Timer(0);
		this->_time->Start();

		this->ReportStatus("Create Key Objects");
		/* Initialise the Client Machine List */
		this->_clientList = new MultipleKinectsPlatformServer::ClientsList(this->_time);
		/* Create the jobs queue that process each incoming data from client machines */
		this->_jobQueue = new MultipleKinectsPlatformServer::JobsQueue();
		/* Create algorithm that merge the scenes */
		this->_minorityViewport = new MinorityViewport(this->_time,this->_clientList);

		this->ReportStatus("Server Starting");
		//Initialise the Server with the number of threads
		string docRoot = "C:\\Users\\ethanlim\\Documents\\Projects\\School\\MultipleKinectsPlatformServer\\Web";
		std::size_t num_threads = boost::lexical_cast<std::size_t>(5);
		this->_httpServer = new http::server::server(
												address,
												httpPort,
												docRoot,
												this->_jobQueue,
												num_threads,
												this->_clientList,
												this->_minorityViewport
												);

		this->ReportStatus("Server Started");

		this->_udpServer = new MultipleKinectsPlatformServer::UdpServer(address,atoi(udpPort.c_str()),this->_minorityViewport);
	  }
	  catch (std::exception& e)
	  {
		std::cerr << "exception: " << e.what() << "\n";
	  }
	}

	void Core::BeginListen(){
		try{
			this->_httpServer->run();
		}
		catch(std::exception& e){
			std::cerr << "exception: " << e.what() << "\n";
		}
	}

	void Core::BeginUdpListen(){
		try{
			this->_udpServer->Run();
		}
		catch(std::exception& e){
			std::cerr << "exception: " << e.what() << "\n";
		}
	}

	/** Depreciated
	void Core::ProcessJobs(){

		Json::Value root;
		Json::Reader reader;
		string rawJSON;
		string timeStamp;

		while(true){

			Job recvJob;
			JobThreadMutex.lock();
			recvJob =  this->_jobQueue->get();
			JobThreadMutex.unlock();

			rawJSON = recvJob.GetJobJSON();
			timeStamp = recvJob.GetTimeStamp();

			if (!rawJSON.empty()&&!timeStamp.empty()&&reader.parse(rawJSON,root))
			{
				for(unsigned short skeletons=0;skeletons<root.size();skeletons++){
					MultipleKinectsPlatformServer::Skeleton newSkeleton(root.get(skeletons,NULL),atol(timeStamp.c_str()));
					this->_minorityViewport->LoadSkeleton(newSkeleton);
				}
			}
		}
	}
	*/

	void Core::ReportStatus(string msg){
		cout << "Core : " << msg << endl;
	}
}

int main(int argc, char **argv)
{
	srand(time(NULL));

	MultipleKinectsPlatformServer::Core *platform;

	if(argc==1){
		throw exception("Program arguments are empty");
	}

	try{
		platform = new MultipleKinectsPlatformServer::Core(argv[1],argv[2],argv[3]);

		if(platform!=NULL){
			thread server_thread(&MultipleKinectsPlatformServer::Core::BeginListen,platform);
			thread udp_thread(&MultipleKinectsPlatformServer::Core::BeginUdpListen,platform);

			server_thread.join();
			udp_thread.join();
		}
	}catch(exception &error){
		throw error;
	}

	return 0;
}
<commit_msg>Remove the timeclient<commit_after>#include "MultipleKinectsPlatformServer.h"

namespace MultipleKinectsPlatformServer{

	Core::Core(/*Server Address*/string address,/*Server Port*/string httpPort,string udpPort){
	  try
	  {
		/*Upgraded the Priority Class*/
		DWORD dwPriClass;
		dwPriClass = GetPriorityClass(GetCurrentProcess());
		cout << "Current priority class is " << std::hex << dwPriClass << endl;
		if(!SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS)){
			cout << "Failed to upgrade priority class" << GetLastError() << endl;
		}else{
			dwPriClass = GetPriorityClass(GetCurrentProcess());
			cout << "Upgraded priority class is " << std::hex << dwPriClass << endl;
		}

		/* Communicate with a centralised time server */
		/*
		unsigned short randomTimeServerId = rand()%5;
		string timeServer = std::to_string(randomTimeServerId)+".asia.pool.ntp.org";
		this->ReportStatus("Sync with Time Server - "+ timeServer);
		NTPClient timeClient(timeServer);
		long timeFromServer = timeClient.RequestDatetime_UNIX();
		*/
		time_t ltime;
		this->_time = new Timer(time(&ltime));
		this->_time->Start();

		this->ReportStatus("Create Key Objects");
		/* Initialise the Client Machine List */
		this->_clientList = new MultipleKinectsPlatformServer::ClientsList(this->_time);
		/* Create the jobs queue that process each incoming data from client machines */
		this->_jobQueue = new MultipleKinectsPlatformServer::JobsQueue();
		/* Create algorithm that merge the scenes */
		this->_minorityViewport = new MinorityViewport(this->_time,this->_clientList);

		this->ReportStatus("Server Starting");
		//Initialise the Server with the number of threads
		string docRoot = "C:\\Users\\ethanlim\\Documents\\Projects\\School\\MultipleKinectsPlatformServer\\Web";
		std::size_t num_threads = boost::lexical_cast<std::size_t>(5);
		this->_httpServer = new http::server::server(
												address,
												httpPort,
												docRoot,
												this->_jobQueue,
												num_threads,
												this->_clientList,
												this->_minorityViewport
												);

		this->ReportStatus("Server Started");

		this->_udpServer = new MultipleKinectsPlatformServer::UdpServer(address,atoi(udpPort.c_str()),this->_minorityViewport);
	  }
	  catch (std::exception& e)
	  {
		std::cerr << "exception: " << e.what() << "\n";
	  }
	}

	void Core::BeginListen(){
		try{
			this->_httpServer->run();
		}
		catch(std::exception& e){
			std::cerr << "exception: " << e.what() << "\n";
		}
	}

	void Core::BeginUdpListen(){
		try{
			this->_udpServer->Run();
		}
		catch(std::exception& e){
			std::cerr << "exception: " << e.what() << "\n";
		}
	}

	/** Depreciated
	void Core::ProcessJobs(){

		Json::Value root;
		Json::Reader reader;
		string rawJSON;
		string timeStamp;

		while(true){

			Job recvJob;
			JobThreadMutex.lock();
			recvJob =  this->_jobQueue->get();
			JobThreadMutex.unlock();

			rawJSON = recvJob.GetJobJSON();
			timeStamp = recvJob.GetTimeStamp();

			if (!rawJSON.empty()&&!timeStamp.empty()&&reader.parse(rawJSON,root))
			{
				for(unsigned short skeletons=0;skeletons<root.size();skeletons++){
					MultipleKinectsPlatformServer::Skeleton newSkeleton(root.get(skeletons,NULL),atol(timeStamp.c_str()));
					this->_minorityViewport->LoadSkeleton(newSkeleton);
				}
			}
		}
	}
	*/

	void Core::ReportStatus(string msg){
		cout << "Core : " << msg << endl;
	}
}

int main(int argc, char **argv)
{
	srand(time(NULL));

	MultipleKinectsPlatformServer::Core *platform;

	if(argc==1){
		throw exception("Program arguments are empty");
	}

	try{
		platform = new MultipleKinectsPlatformServer::Core(argv[1],argv[2],argv[3]);

		if(platform!=NULL){
			thread server_thread(&MultipleKinectsPlatformServer::Core::BeginListen,platform);
			thread udp_thread(&MultipleKinectsPlatformServer::Core::BeginUdpListen,platform);

			server_thread.join();
			udp_thread.join();
		}
	}catch(exception &error){
		throw error;
	}

	return 0;
}
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName         :    NFMemoryCounter.hpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2016-11-08
//    @Module           :    NFMemoryCounter
//
// -------------------------------------------------------------------------

#ifndef NF_COUNTER_MEMORY_HPP
#define NF_COUNTER_MEMORY_HPP

#include <iostream>
#include <string>
#include <map>
#include "NFComm/NFPluginModule/NFPlatform.h"

class NFMemoryCounter
{
public:
	virtual ~NFMemoryCounter() {}

    void AddInstance(const std::string& strClassName)
    {
        std::map<std::string, int>::iterator it = mxCounter.find(strClassName);
        if(it != mxCounter.end())
        {
            it->second++;
        }
        else
        {
            mxCounter.insert(std::map<std::string, int>::value_type(strClassName, 1));
        }
    }

	void RemInstance(const std::string& strClassName)
	{
		std::map<std::string, int>::iterator it = mxCounter.find(strClassName);
		if (it != mxCounter.end())
		{
			mxCounter.erase(it);
		}
	}

	const std::map<std::string, int>& GetCounter()
	{
		return mxCounter;
	}

private:
    static std::map<std::string, int> mxCounter;
};

#endif<commit_msg>fixed counter's bug<commit_after>// -------------------------------------------------------------------------
//    @FileName         :    NFMemoryCounter.hpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2016-11-08
//    @Module           :    NFMemoryCounter
//
// -------------------------------------------------------------------------

#ifndef NF_COUNTER_MEMORY_HPP
#define NF_COUNTER_MEMORY_HPP

#include <iostream>
#include <string>
#include <map>
#include "NFComm/NFPluginModule/NFPlatform.h"

class NFMemoryCounter
{
public:
	virtual ~NFMemoryCounter() {}

    void AddInstance(const std::string& strClassName)
    {
        std::map<std::string, int>::iterator it = mxCounter.find(strClassName);
        if(it != mxCounter.end())
        {
            it->second++;
        }
        else
        {
            mxCounter.insert(std::map<std::string, int>::value_type(strClassName, 1));
        }
    }

	void RemInstance(const std::string& strClassName)
	{
		std::map<std::string, int>::iterator it = mxCounter.find(strClassName);
		if (it != mxCounter.end())
		{
			it->second--;
		}
	}

	const std::map<std::string, int>& GetCounter()
	{
		return mxCounter;
	}

protected:
    static std::map<std::string, int> mxCounter;
};

#endif<|endoftext|>


<commit_before>#include	"Bot.hh"

Bot::Bot()
  : _action(NULL), _battle(NULL), _battleState(false), _state(0)
{
}

Bot::~Bot()
{
}

void		Bot::_saveKeyState()
{
  _keyState = 0;
  for (uint8_t i = KEY_LEFT; i <= KEY_BUTTON_AUTO_B; i++)
    if (sdlGetButton((EKey) i))
      _keyState |= (1 << i);
}

void		Bot::_loadKeyState()
{
  for (uint8_t i = KEY_LEFT; i <= KEY_BUTTON_AUTO_B; i++)
    sdlSetButton((EKey) i, (_keyState >> i) & 1);
  _keyState = 0;
}

void		Bot::update()
{
  if (Action::data->inBattle() != _battleState)
    (this->*(!_battleState ? &Bot::_saveKeyState : &Bot::_loadKeyState))();
  _battleState = Action::data->inBattle();
  if (_battleState)
    {
      if (_battle)
	_battle->update();
      return;
    }
  if (!_action)
    {
      if (_queue.size())
	{
	  _action = _queue.front();
	  _queue.pop_front();
	}
      else
	_state = Action::NOT_STARTED;
    }
  if (_action)
    {
      _action->update();
      _state = _action->getState();
      if (_state > Action::RUNNING)
	{
	  delete _action;
	  _action = NULL;
	}
    }
  _battleState = Action::data->inBattle();
}

void		Bot::queue(AAction *action)
{
  _queue.push_back(action);
}
<commit_msg>add: reset Battle Action<commit_after>#include	"Bot.hh"

Bot::Bot()
  : _action(NULL), _battle(NULL), _battleState(false), _state(0)
{
}

Bot::~Bot()
{
}

void		Bot::_saveKeyState()
{
  _keyState = 0;
  for (uint8_t i = KEY_LEFT; i <= KEY_BUTTON_AUTO_B; i++)
    if (sdlGetButton((EKey) i))
      _keyState |= (1 << i);
}

void		Bot::_loadKeyState()
{
  for (uint8_t i = KEY_LEFT; i <= KEY_BUTTON_AUTO_B; i++)
    sdlSetButton((EKey) i, (_keyState >> i) & 1);
  _keyState = 0;
}

void		Bot::update()
{
  if (Action::data->inBattle() != _battleState)
    {
      (this->*(!_battleState ? &Bot::_saveKeyState : &Bot::_loadKeyState))();
      if (!_battleState && _battle)
	_battle->reset();
    }
  _battleState = Action::data->inBattle();
  if (_battleState)
    {
      if (_battle)
	_battle->update();
      return;
    }
  if (!_action)
    {
      if (_queue.size())
	{
	  _action = _queue.front();
	  _queue.pop_front();
	}
      else
	_state = Action::NOT_STARTED;
    }
  if (_action)
    {
      _action->update();
      _state = _action->getState();
      if (_state > Action::RUNNING)
	{
	  delete _action;
	  _action = NULL;
	}
    }
}

void		Bot::queue(AAction *action)
{
  _queue.push_back(action);
}
<|endoftext|>


<commit_before>#include <cmath>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/LU>
#include <angles/angles.h>
#include <robot_kf/robot_kf.h>

using namespace Eigen;

namespace robot_kf {

KalmanFilter::KalmanFilter(void)
    : x_(Vector3d::Zero())
    , cov_x_(9999 * Matrix3d::Identity())
    , A_(Matrix3d::Identity())
    , Hgps_((Matrix<double, 2, 3>() << 1, 0, 0, 0, 1, 0).finished())
    , Hcomp_((Matrix<double, 1, 3>() << 0, 0, 1).finished())
{}

KalmanFilter::~KalmanFilter(void)
{}

Vector3d KalmanFilter::getState(void) const
{
    return x_;
}

Matrix3d KalmanFilter::getCovariance(void) const
{
    return cov_x_;
}

void KalmanFilter::update_encoders(Vector2d enc, Matrix2d cov_enc, double separation)
{
    Matrix<double, 3, 2> const B = (Matrix<double, 3, 2>() <<
        0.5 * cos(x_[2]),  0.5 * cos(x_[2]),
        0.5 * sin(x_[2]),  0.5 * sin(x_[2]),
        -1.0 / separation, 1.0 / separation
    ).finished();
    // TODO: Verify that this is correct.
    Matrix3d const cov_process = B * cov_enc * B.transpose();

    predict(enc, cov_process, A_, B);
    normalize_yaw();
}

void KalmanFilter::update_gps(Vector2d gps, Matrix2d cov_gps)
{
    measure(gps, cov_gps, Hgps_);
}

void KalmanFilter::update_compass(double compass, double cov_compass)
{
    Matrix<double, 1, 1> mat_compass, mat_cov_compass;
    mat_compass << compass;
    mat_cov_compass << cov_compass;

    measure(mat_compass, mat_cov_compass, Hcomp_);
    normalize_yaw();
}

template <int m>
void KalmanFilter::predict(Matrix<double, m, 1> u, Matrix<double, 3, 3> cov_process,
                           Matrix<double, 3, 3> A, Matrix<double, 3, m> B)
{
    x_ = A * x_ + B * u;
    cov_x_ = A * cov_x_ * A.transpose() + cov_process;
}

template <int m>
void KalmanFilter::measure(Matrix<double, m, 1> z, Matrix<double, m, m> cov_z,
                           Matrix<double, m, 3> H)
{
    Matrix<double, 3, m> const K = cov_x_ * H.transpose() * (H * cov_x_
                                  * H.transpose() + cov_z).inverse();
    x_ = x_ + K * (z - H * x_);
    cov_x_ = (Matrix3d::Identity() - K * H) * cov_x_;
}

void KalmanFilter::normalize_yaw(void) {
    x_[2] = angles::normalize_angle(x_[2]);
}

};
<commit_msg>fixed glitch when the compass crosses +/-pi<commit_after>#include <cmath>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/LU>
#include <angles/angles.h>
#include <robot_kf/robot_kf.h>

using namespace Eigen;

namespace robot_kf {

KalmanFilter::KalmanFilter(void)
    : x_(Vector3d::Zero())
    , cov_x_(9999 * Matrix3d::Identity())
    , A_(Matrix3d::Identity())
    , Hgps_((Matrix<double, 2, 3>() << 1, 0, 0, 0, 1, 0).finished())
    , Hcomp_((Matrix<double, 1, 3>() << 0, 0, 1).finished())
{}

KalmanFilter::~KalmanFilter(void)
{}

Vector3d KalmanFilter::getState(void) const
{
    return x_;
}

Matrix3d KalmanFilter::getCovariance(void) const
{
    return cov_x_;
}

void KalmanFilter::update_encoders(Vector2d enc, Matrix2d cov_enc, double separation)
{
    Matrix<double, 3, 2> const B = (Matrix<double, 3, 2>() <<
        0.5 * cos(x_[2]),  0.5 * cos(x_[2]),
        0.5 * sin(x_[2]),  0.5 * sin(x_[2]),
        -1.0 / separation, 1.0 / separation
    ).finished();
    // TODO: Verify that this is correct.
    Matrix3d const cov_process = B * cov_enc * B.transpose();

    predict(enc, cov_process, A_, B);
    normalize_yaw();
}

void KalmanFilter::update_gps(Vector2d gps, Matrix2d cov_gps)
{
    measure(gps, cov_gps, Hgps_);
}

void KalmanFilter::update_compass(double compass, double cov_compass)
{
    // Renormalize the compass heading so the filter behaves correctly when
    // crossing +/-pi. This prevents the heading from slowly drifting the "long
    // way" around the circle (i.e. through 0 instead of +/-pi).
    if (x_[2] - compass > M_PI) {
        compass = compass + 2 * M_PI;
    } else if (x_[2] - compass < -M_PI) {
        compass = compass - 2 * M_PI;
    }

    Matrix<double, 1, 1> mat_compass, mat_cov_compass;
    mat_compass << compass;
    mat_cov_compass << cov_compass;

    measure(mat_compass, mat_cov_compass, Hcomp_);
    normalize_yaw();
}

template <int m>
void KalmanFilter::predict(Matrix<double, m, 1> u, Matrix<double, 3, 3> cov_process,
                           Matrix<double, 3, 3> A, Matrix<double, 3, m> B)
{
    x_ = A * x_ + B * u;
    cov_x_ = A * cov_x_ * A.transpose() + cov_process;
}

template <int m>
void KalmanFilter::measure(Matrix<double, m, 1> z, Matrix<double, m, m> cov_z,
                           Matrix<double, m, 3> H)
{
    Matrix<double, 3, m> const K = cov_x_ * H.transpose() * (H * cov_x_
                                  * H.transpose() + cov_z).inverse();
    x_ = x_ + K * (z - H * x_);
    cov_x_ = (Matrix3d::Identity() - K * H) * cov_x_;
}

void KalmanFilter::normalize_yaw(void) {
    x_[2] = angles::normalize_angle(x_[2]);
}

};
<|endoftext|>