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

#include "spirv-tools/optimizer.hpp"

#include <cassert>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "source/opt/build_module.h"
#include "source/opt/graphics_robust_access_pass.h"
#include "source/opt/log.h"
#include "source/opt/pass_manager.h"
#include "source/opt/passes.h"
#include "source/spirv_optimizer_options.h"
#include "source/util/make_unique.h"
#include "source/util/string_utils.h"

namespace spvtools {

struct Optimizer::PassToken::Impl {
  Impl(std::unique_ptr<opt::Pass> p) : pass(std::move(p)) {}

  std::unique_ptr<opt::Pass> pass;  // Internal implementation pass.
};

Optimizer::PassToken::PassToken(
    std::unique_ptr<Optimizer::PassToken::Impl> impl)
    : impl_(std::move(impl)) {}

Optimizer::PassToken::PassToken(std::unique_ptr<opt::Pass>&& pass)
    : impl_(MakeUnique<Optimizer::PassToken::Impl>(std::move(pass))) {}

Optimizer::PassToken::PassToken(PassToken&& that)
    : impl_(std::move(that.impl_)) {}

Optimizer::PassToken& Optimizer::PassToken::operator=(PassToken&& that) {
  impl_ = std::move(that.impl_);
  return *this;
}

Optimizer::PassToken::~PassToken() {}

struct Optimizer::Impl {
  explicit Impl(spv_target_env env) : target_env(env), pass_manager() {}

  spv_target_env target_env;      // Target environment.
  opt::PassManager pass_manager;  // Internal implementation pass manager.
};

Optimizer::Optimizer(spv_target_env env) : impl_(new Impl(env)) {}

Optimizer::~Optimizer() {}

void Optimizer::SetMessageConsumer(MessageConsumer c) {
  // All passes' message consumer needs to be updated.
  for (uint32_t i = 0; i < impl_->pass_manager.NumPasses(); ++i) {
    impl_->pass_manager.GetPass(i)->SetMessageConsumer(c);
  }
  impl_->pass_manager.SetMessageConsumer(std::move(c));
}

const MessageConsumer& Optimizer::consumer() const {
  return impl_->pass_manager.consumer();
}

Optimizer& Optimizer::RegisterPass(PassToken&& p) {
  // Change to use the pass manager's consumer.
  p.impl_->pass->SetMessageConsumer(consumer());
  impl_->pass_manager.AddPass(std::move(p.impl_->pass));
  return *this;
}

// The legalization passes take a spir-v shader generated by an HLSL front-end
// and turn it into a valid vulkan spir-v shader.  There are two ways in which
// the code will be invalid at the start:
//
// 1) There will be opaque objects, like images, which will be passed around
//    in intermediate objects.  Valid spir-v will have to replace the use of
//    the opaque object with an intermediate object that is the result of the
//    load of the global opaque object.
//
// 2) There will be variables that contain pointers to structured or uniform
//    buffers.  It be legal, the variables must be eliminated, and the
//    references to the structured buffers must use the result of OpVariable
//    in the Uniform storage class.
//
// Optimization in this list must accept shaders with these relaxation of the
// rules.  There is not guarantee that this list of optimizations is able to
// legalize all inputs, but it is on a best effort basis.
//
// The legalization problem is essentially a very general copy propagation
// problem.  The optimization we use are all used to either do copy propagation
// or enable more copy propagation.
Optimizer& Optimizer::RegisterLegalizationPasses() {
  return
      // Wrap OpKill instructions so all other code can be inlined.
      RegisterPass(CreateWrapOpKillPass())
          // Remove unreachable block so that merge return works.
          .RegisterPass(CreateDeadBranchElimPass())
          // Merge the returns so we can inline.
          .RegisterPass(CreateMergeReturnPass())
          // Make sure uses and definitions are in the same function.
          .RegisterPass(CreateInlineExhaustivePass())
          // Make private variable function scope
          .RegisterPass(CreateEliminateDeadFunctionsPass())
          .RegisterPass(CreatePrivateToLocalPass())
          // Fix up the storage classes that DXC may have purposely generated
          // incorrectly.  All functions are inlined, and a lot of dead code has
          // been removed.
          .RegisterPass(CreateFixStorageClassPass())
          // Propagate the value stored to the loads in very simple cases.
          .RegisterPass(CreateLocalSingleBlockLoadStoreElimPass())
          .RegisterPass(CreateLocalSingleStoreElimPass())
          .RegisterPass(CreateAggressiveDCEPass())
          // Split up aggregates so they are easier to deal with.
          .RegisterPass(CreateScalarReplacementPass(0))
          // Remove loads and stores so everything is in intermediate values.
          // Takes care of copy propagation of non-members.
          .RegisterPass(CreateLocalSingleBlockLoadStoreElimPass())
          .RegisterPass(CreateLocalSingleStoreElimPass())
          .RegisterPass(CreateAggressiveDCEPass())
          .RegisterPass(CreateLocalMultiStoreElimPass())
          .RegisterPass(CreateAggressiveDCEPass())
          // Propagate constants to get as many constant conditions on branches
          // as possible.
          .RegisterPass(CreateCCPPass())
          .RegisterPass(CreateLoopUnrollPass(true))
          .RegisterPass(CreateDeadBranchElimPass())
          // Copy propagate members.  Cleans up code sequences generated by
          // scalar replacement.  Also important for removing OpPhi nodes.
          .RegisterPass(CreateSimplificationPass())
          .RegisterPass(CreateAggressiveDCEPass())
          .RegisterPass(CreateCopyPropagateArraysPass())
          // May need loop unrolling here see
          // https://github.com/Microsoft/DirectXShaderCompiler/pull/930
          // Get rid of unused code that contain traces of illegal code
          // or unused references to unbound external objects
          .RegisterPass(CreateVectorDCEPass())
          .RegisterPass(CreateDeadInsertElimPass())
          .RegisterPass(CreateReduceLoadSizePass())
          .RegisterPass(CreateAggressiveDCEPass());
}

Optimizer& Optimizer::RegisterPerformancePasses() {
  return RegisterPass(CreateWrapOpKillPass())
      .RegisterPass(CreateDeadBranchElimPass())
      .RegisterPass(CreateMergeReturnPass())
      .RegisterPass(CreateInlineExhaustivePass())
      .RegisterPass(CreateAggressiveDCEPass())
      .RegisterPass(CreatePrivateToLocalPass())
      .RegisterPass(CreateLocalSingleBlockLoadStoreElimPass())
      .RegisterPass(CreateLocalSingleStoreElimPass())
      .RegisterPass(CreateAggressiveDCEPass())
      .RegisterPass(CreateScalarReplacementPass())
      .RegisterPass(CreateLocalAccessChainConvertPass())
      .RegisterPass(CreateLocalSingleBlockLoadStoreElimPass())
      .RegisterPass(CreateLocalSingleStoreElimPass())
      .RegisterPass(CreateAggressiveDCEPass())
      .RegisterPass(CreateLocalMultiStoreElimPass())
      .RegisterPass(CreateAggressiveDCEPass())
      .RegisterPass(CreateCCPPass())
      .RegisterPass(CreateAggressiveDCEPass())
      .RegisterPass(CreateRedundancyEliminationPass())
      .RegisterPass(CreateCombineAccessChainsPass())
      .RegisterPass(CreateSimplificationPass())
      .RegisterPass(CreateVectorDCEPass())
      .RegisterPass(CreateDeadInsertElimPass())
      .RegisterPass(CreateDeadBranchElimPass())
      .RegisterPass(CreateSimplificationPass())
      .RegisterPass(CreateIfConversionPass())
      .RegisterPass(CreateCopyPropagateArraysPass())
      .RegisterPass(CreateReduceLoadSizePass())
      .RegisterPass(CreateAggressiveDCEPass())
      .RegisterPass(CreateBlockMergePass())
      .RegisterPass(CreateRedundancyEliminationPass())
      .RegisterPass(CreateDeadBranchElimPass())
      .RegisterPass(CreateBlockMergePass())
      .RegisterPass(CreateSimplificationPass());
}

Optimizer& Optimizer::RegisterSizePasses() {
  return RegisterPass(CreateWrapOpKillPass())
      .RegisterPass(CreateDeadBranchElimPass())
      .RegisterPass(CreateMergeReturnPass())
      .RegisterPass(CreateInlineExhaustivePass())
      .RegisterPass(CreateAggressiveDCEPass())
      .RegisterPass(CreatePrivateToLocalPass())
      .RegisterPass(CreateScalarReplacementPass())
      .RegisterPass(CreateLocalAccessChainConvertPass())
      .RegisterPass(CreateLocalSingleBlockLoadStoreElimPass())
      .RegisterPass(CreateLocalSingleStoreElimPass())
      .RegisterPass(CreateAggressiveDCEPass())
      .RegisterPass(CreateSimplificationPass())
      .RegisterPass(CreateDeadInsertElimPass())
      .RegisterPass(CreateLocalMultiStoreElimPass())
      .RegisterPass(CreateAggressiveDCEPass())
      .RegisterPass(CreateCCPPass())
      .RegisterPass(CreateAggressiveDCEPass())
      .RegisterPass(CreateDeadBranchElimPass())
      .RegisterPass(CreateIfConversionPass())
      .RegisterPass(CreateAggressiveDCEPass())
      .RegisterPass(CreateBlockMergePass())
      .RegisterPass(CreateSimplificationPass())
      .RegisterPass(CreateDeadInsertElimPass())
      .RegisterPass(CreateRedundancyEliminationPass())
      .RegisterPass(CreateCFGCleanupPass())
      .RegisterPass(CreateAggressiveDCEPass());
}

Optimizer& Optimizer::RegisterVulkanToWebGPUPasses() {
  return RegisterPass(CreateStripDebugInfoPass())
      .RegisterPass(CreateStripAtomicCounterMemoryPass())
      .RegisterPass(CreateGenerateWebGPUInitializersPass())
      .RegisterPass(CreateLegalizeVectorShufflePass())
      .RegisterPass(CreateSplitInvalidUnreachablePass())
      .RegisterPass(CreateEliminateDeadConstantPass())
      .RegisterPass(CreateFlattenDecorationPass())
      .RegisterPass(CreateAggressiveDCEPass())
      .RegisterPass(CreateDeadBranchElimPass())
      .RegisterPass(CreateCompactIdsPass());
}

Optimizer& Optimizer::RegisterWebGPUToVulkanPasses() {
  return RegisterPass(CreateDecomposeInitializedVariablesPass())
      .RegisterPass(CreateCompactIdsPass());
}

bool Optimizer::RegisterPassesFromFlags(const std::vector<std::string>& flags) {
  for (const auto& flag : flags) {
    if (!RegisterPassFromFlag(flag)) {
      return false;
    }
  }

  return true;
}

bool Optimizer::FlagHasValidForm(const std::string& flag) const {
  if (flag == "-O" || flag == "-Os") {
    return true;
  } else if (flag.size() > 2 && flag.substr(0, 2) == "--") {
    return true;
  }

  Errorf(consumer(), nullptr, {},
         "%s is not a valid flag.  Flag passes should have the form "
         "'--pass_name[=pass_args]'. Special flag names also accepted: -O "
         "and -Os.",
         flag.c_str());
  return false;
}

bool Optimizer::RegisterPassFromFlag(const std::string& flag) {
  if (!FlagHasValidForm(flag)) {
    return false;
  }

  // Split flags of the form --pass_name=pass_args.
  auto p = utils::SplitFlagArgs(flag);
  std::string pass_name = p.first;
  std::string pass_args = p.second;

  // FIXME(dnovillo): This should be re-factored so that pass names can be
  // automatically checked against Pass::name() and PassToken instances created
  // via a template function.  Additionally, class Pass should have a desc()
  // method that describes the pass (so it can be used in --help).
  //
  // Both Pass::name() and Pass::desc() should be static class members so they
  // can be invoked without creating a pass instance.
  if (pass_name == "strip-atomic-counter-memory") {
    RegisterPass(CreateStripAtomicCounterMemoryPass());
  } else if (pass_name == "strip-debug") {
    RegisterPass(CreateStripDebugInfoPass());
  } else if (pass_name == "strip-reflect") {
    RegisterPass(CreateStripReflectInfoPass());
  } else if (pass_name == "set-spec-const-default-value") {
    if (pass_args.size() > 0) {
      auto spec_ids_vals =
          opt::SetSpecConstantDefaultValuePass::ParseDefaultValuesString(
              pass_args.c_str());
      if (!spec_ids_vals) {
        Errorf(consumer(), nullptr, {},
               "Invalid argument for --set-spec-const-default-value: %s",
               pass_args.c_str());
        return false;
      }
      RegisterPass(
          CreateSetSpecConstantDefaultValuePass(std::move(*spec_ids_vals)));
    } else {
      Errorf(consumer(), nullptr, {},
             "Invalid spec constant value string '%s'. Expected a string of "
             "<spec id>:<default value> pairs.",
             pass_args.c_str());
      return false;
    }
  } else if (pass_name == "if-conversion") {
    RegisterPass(CreateIfConversionPass());
  } else if (pass_name == "freeze-spec-const") {
    RegisterPass(CreateFreezeSpecConstantValuePass());
  } else if (pass_name == "inline-entry-points-exhaustive") {
    RegisterPass(CreateInlineExhaustivePass());
  } else if (pass_name == "inline-entry-points-opaque") {
    RegisterPass(CreateInlineOpaquePass());
  } else if (pass_name == "combine-access-chains") {
    RegisterPass(CreateCombineAccessChainsPass());
  } else if (pass_name == "convert-local-access-chains") {
    RegisterPass(CreateLocalAccessChainConvertPass());
  } else if (pass_name == "descriptor-scalar-replacement") {
    RegisterPass(CreateDescriptorScalarReplacementPass());
  } else if (pass_name == "eliminate-dead-code-aggressive") {
    RegisterPass(CreateAggressiveDCEPass());
  } else if (pass_name == "propagate-line-info") {
    RegisterPass(CreatePropagateLineInfoPass());
  } else if (pass_name == "eliminate-redundant-line-info") {
    RegisterPass(CreateRedundantLineInfoElimPass());
  } else if (pass_name == "eliminate-insert-extract") {
    RegisterPass(CreateInsertExtractElimPass());
  } else if (pass_name == "eliminate-local-single-block") {
    RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
  } else if (pass_name == "eliminate-local-single-store") {
    RegisterPass(CreateLocalSingleStoreElimPass());
  } else if (pass_name == "merge-blocks") {
    RegisterPass(CreateBlockMergePass());
  } else if (pass_name == "merge-return") {
    RegisterPass(CreateMergeReturnPass());
  } else if (pass_name == "eliminate-dead-branches") {
    RegisterPass(CreateDeadBranchElimPass());
  } else if (pass_name == "eliminate-dead-functions") {
    RegisterPass(CreateEliminateDeadFunctionsPass());
  } else if (pass_name == "eliminate-local-multi-store") {
    RegisterPass(CreateLocalMultiStoreElimPass());
  } else if (pass_name == "eliminate-dead-const") {
    RegisterPass(CreateEliminateDeadConstantPass());
  } else if (pass_name == "eliminate-dead-inserts") {
    RegisterPass(CreateDeadInsertElimPass());
  } else if (pass_name == "eliminate-dead-variables") {
    RegisterPass(CreateDeadVariableEliminationPass());
  } else if (pass_name == "eliminate-dead-members") {
    RegisterPass(CreateEliminateDeadMembersPass());
  } else if (pass_name == "fold-spec-const-op-composite") {
    RegisterPass(CreateFoldSpecConstantOpAndCompositePass());
  } else if (pass_name == "loop-unswitch") {
    RegisterPass(CreateLoopUnswitchPass());
  } else if (pass_name == "scalar-replacement") {
    if (pass_args.size() == 0) {
      RegisterPass(CreateScalarReplacementPass());
    } else {
      int limit = -1;
      if (pass_args.find_first_not_of("0123456789") == std::string::npos) {
        limit = atoi(pass_args.c_str());
      }

      if (limit >= 0) {
        RegisterPass(CreateScalarReplacementPass(limit));
      } else {
        Error(consumer(), nullptr, {},
              "--scalar-replacement must have no arguments or a non-negative "
              "integer argument");
        return false;
      }
    }
  } else if (pass_name == "strength-reduction") {
    RegisterPass(CreateStrengthReductionPass());
  } else if (pass_name == "unify-const") {
    RegisterPass(CreateUnifyConstantPass());
  } else if (pass_name == "flatten-decorations") {
    RegisterPass(CreateFlattenDecorationPass());
  } else if (pass_name == "compact-ids") {
    RegisterPass(CreateCompactIdsPass());
  } else if (pass_name == "cfg-cleanup") {
    RegisterPass(CreateCFGCleanupPass());
  } else if (pass_name == "local-redundancy-elimination") {
    RegisterPass(CreateLocalRedundancyEliminationPass());
  } else if (pass_name == "loop-invariant-code-motion") {
    RegisterPass(CreateLoopInvariantCodeMotionPass());
  } else if (pass_name == "reduce-load-size") {
    RegisterPass(CreateReduceLoadSizePass());
  } else if (pass_name == "redundancy-elimination") {
    RegisterPass(CreateRedundancyEliminationPass());
  } else if (pass_name == "private-to-local") {
    RegisterPass(CreatePrivateToLocalPass());
  } else if (pass_name == "remove-duplicates") {
    RegisterPass(CreateRemoveDuplicatesPass());
  } else if (pass_name == "workaround-1209") {
    RegisterPass(CreateWorkaround1209Pass());
  } else if (pass_name == "replace-invalid-opcode") {
    RegisterPass(CreateReplaceInvalidOpcodePass());
  } else if (pass_name == "inst-bindless-check") {
    RegisterPass(CreateInstBindlessCheckPass(7, 23, false, false, 2));
    RegisterPass(CreateSimplificationPass());
    RegisterPass(CreateDeadBranchElimPass());
    RegisterPass(CreateBlockMergePass());
    RegisterPass(CreateAggressiveDCEPass());
  } else if (pass_name == "inst-desc-idx-check") {
    RegisterPass(CreateInstBindlessCheckPass(7, 23, true, true, 2));
    RegisterPass(CreateSimplificationPass());
    RegisterPass(CreateDeadBranchElimPass());
    RegisterPass(CreateBlockMergePass());
    RegisterPass(CreateAggressiveDCEPass());
  } else if (pass_name == "inst-buff-addr-check") {
    RegisterPass(CreateInstBuffAddrCheckPass(7, 23, 2));
    RegisterPass(CreateAggressiveDCEPass());
  } else if (pass_name == "convert-relaxed-to-half") {
    RegisterPass(CreateConvertRelaxedToHalfPass());
  } else if (pass_name == "relax-float-ops") {
    RegisterPass(CreateRelaxFloatOpsPass());
  } else if (pass_name == "simplify-instructions") {
    RegisterPass(CreateSimplificationPass());
  } else if (pass_name == "ssa-rewrite") {
    RegisterPass(CreateSSARewritePass());
  } else if (pass_name == "copy-propagate-arrays") {
    RegisterPass(CreateCopyPropagateArraysPass());
  } else if (pass_name == "loop-fission") {
    int register_threshold_to_split =
        (pass_args.size() > 0) ? atoi(pass_args.c_str()) : -1;
    if (register_threshold_to_split > 0) {
      RegisterPass(CreateLoopFissionPass(
          static_cast<size_t>(register_threshold_to_split)));
    } else {
      Error(consumer(), nullptr, {},
            "--loop-fission must have a positive integer argument");
      return false;
    }
  } else if (pass_name == "loop-fusion") {
    int max_registers_per_loop =
        (pass_args.size() > 0) ? atoi(pass_args.c_str()) : -1;
    if (max_registers_per_loop > 0) {
      RegisterPass(
          CreateLoopFusionPass(static_cast<size_t>(max_registers_per_loop)));
    } else {
      Error(consumer(), nullptr, {},
            "--loop-fusion must have a positive integer argument");
      return false;
    }
  } else if (pass_name == "loop-unroll") {
    RegisterPass(CreateLoopUnrollPass(true));
  } else if (pass_name == "upgrade-memory-model") {
    RegisterPass(CreateUpgradeMemoryModelPass());
  } else if (pass_name == "vector-dce") {
    RegisterPass(CreateVectorDCEPass());
  } else if (pass_name == "loop-unroll-partial") {
    int factor = (pass_args.size() > 0) ? atoi(pass_args.c_str()) : 0;
    if (factor > 0) {
      RegisterPass(CreateLoopUnrollPass(false, factor));
    } else {
      Error(consumer(), nullptr, {},
            "--loop-unroll-partial must have a positive integer argument");
      return false;
    }
  } else if (pass_name == "loop-peeling") {
    RegisterPass(CreateLoopPeelingPass());
  } else if (pass_name == "loop-peeling-threshold") {
    int factor = (pass_args.size() > 0) ? atoi(pass_args.c_str()) : 0;
    if (factor > 0) {
      opt::LoopPeelingPass::SetLoopPeelingThreshold(factor);
    } else {
      Error(consumer(), nullptr, {},
            "--loop-peeling-threshold must have a positive integer argument");
      return false;
    }
  } else if (pass_name == "ccp") {
    RegisterPass(CreateCCPPass());
  } else if (pass_name == "code-sink") {
    RegisterPass(CreateCodeSinkingPass());
  } else if (pass_name == "fix-storage-class") {
    RegisterPass(CreateFixStorageClassPass());
  } else if (pass_name == "O") {
    RegisterPerformancePasses();
  } else if (pass_name == "Os") {
    RegisterSizePasses();
  } else if (pass_name == "legalize-hlsl") {
    RegisterLegalizationPasses();
  } else if (pass_name == "generate-webgpu-initializers") {
    RegisterPass(CreateGenerateWebGPUInitializersPass());
  } else if (pass_name == "legalize-vector-shuffle") {
    RegisterPass(CreateLegalizeVectorShufflePass());
  } else if (pass_name == "split-invalid-unreachable") {
    RegisterPass(CreateLegalizeVectorShufflePass());
  } else if (pass_name == "decompose-initialized-variables") {
    RegisterPass(CreateDecomposeInitializedVariablesPass());
  } else if (pass_name == "graphics-robust-access") {
    RegisterPass(CreateGraphicsRobustAccessPass());
  } else if (pass_name == "wrap-opkill") {
    RegisterPass(CreateWrapOpKillPass());
  } else if (pass_name == "amd-ext-to-khr") {
    RegisterPass(CreateAmdExtToKhrPass());
  } else {
    Errorf(consumer(), nullptr, {},
           "Unknown flag '--%s'. Use --help for a list of valid flags",
           pass_name.c_str());
    return false;
  }

  return true;
}

void Optimizer::SetTargetEnv(const spv_target_env env) {
  impl_->target_env = env;
}

bool Optimizer::Run(const uint32_t* original_binary,
                    const size_t original_binary_size,
                    std::vector<uint32_t>* optimized_binary) const {
  return Run(original_binary, original_binary_size, optimized_binary,
             OptimizerOptions());
}

bool Optimizer::Run(const uint32_t* original_binary,
                    const size_t original_binary_size,
                    std::vector<uint32_t>* optimized_binary,
                    const ValidatorOptions& validator_options,
                    bool skip_validation) const {
  OptimizerOptions opt_options;
  opt_options.set_run_validator(!skip_validation);
  opt_options.set_validator_options(validator_options);
  return Run(original_binary, original_binary_size, optimized_binary,
             opt_options);
}

bool Optimizer::Run(const uint32_t* original_binary,
                    const size_t original_binary_size,
                    std::vector<uint32_t>* optimized_binary,
                    const spv_optimizer_options opt_options) const {
  spvtools::SpirvTools tools(impl_->target_env);
  tools.SetMessageConsumer(impl_->pass_manager.consumer());
  if (opt_options->run_validator_ &&
      !tools.Validate(original_binary, original_binary_size,
                      &opt_options->val_options_)) {
    return false;
  }

  std::unique_ptr<opt::IRContext> context = BuildModule(
      impl_->target_env, consumer(), original_binary, original_binary_size);
  if (context == nullptr) return false;

  context->set_max_id_bound(opt_options->max_id_bound_);
  context->set_preserve_bindings(opt_options->preserve_bindings_);
  context->set_preserve_spec_constants(opt_options->preserve_spec_constants_);

  impl_->pass_manager.SetValidatorOptions(&opt_options->val_options_);
  impl_->pass_manager.SetTargetEnv(impl_->target_env);
  auto status = impl_->pass_manager.Run(context.get());

  if (status == opt::Pass::Status::Failure) {
    return false;
  }

  optimized_binary->clear();
  context->module()->ToBinary(optimized_binary, /* skip_nop = */ true);

#ifndef NDEBUG
  if (status == opt::Pass::Status::SuccessWithoutChange) {
    auto changed = optimized_binary->size() != original_binary_size ||
                   memcmp(optimized_binary->data(), original_binary,
                          original_binary_size) != 0;
    assert(!changed &&
           "Binary unexpectedly changed despite optimizer saying there was no "
           "change");
  }
#endif  // !NDEBUG

  return true;
}

Optimizer& Optimizer::SetPrintAll(std::ostream* out) {
  impl_->pass_manager.SetPrintAll(out);
  return *this;
}

Optimizer& Optimizer::SetTimeReport(std::ostream* out) {
  impl_->pass_manager.SetTimeReport(out);
  return *this;
}

Optimizer& Optimizer::SetValidateAfterAll(bool validate) {
  impl_->pass_manager.SetValidateAfterAll(validate);
  return *this;
}

Optimizer::PassToken CreateNullPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(MakeUnique<opt::NullPass>());
}

Optimizer::PassToken CreateStripAtomicCounterMemoryPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::StripAtomicCounterMemoryPass>());
}

Optimizer::PassToken CreateStripDebugInfoPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::StripDebugInfoPass>());
}

Optimizer::PassToken CreateStripReflectInfoPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::StripReflectInfoPass>());
}

Optimizer::PassToken CreateEliminateDeadFunctionsPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::EliminateDeadFunctionsPass>());
}

Optimizer::PassToken CreateEliminateDeadMembersPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::EliminateDeadMembersPass>());
}

Optimizer::PassToken CreateSetSpecConstantDefaultValuePass(
    const std::unordered_map<uint32_t, std::string>& id_value_map) {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::SetSpecConstantDefaultValuePass>(id_value_map));
}

Optimizer::PassToken CreateSetSpecConstantDefaultValuePass(
    const std::unordered_map<uint32_t, std::vector<uint32_t>>& id_value_map) {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::SetSpecConstantDefaultValuePass>(id_value_map));
}

Optimizer::PassToken CreateFlattenDecorationPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::FlattenDecorationPass>());
}

Optimizer::PassToken CreateFreezeSpecConstantValuePass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::FreezeSpecConstantValuePass>());
}

Optimizer::PassToken CreateFoldSpecConstantOpAndCompositePass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::FoldSpecConstantOpAndCompositePass>());
}

Optimizer::PassToken CreateUnifyConstantPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::UnifyConstantPass>());
}

Optimizer::PassToken CreateEliminateDeadConstantPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::EliminateDeadConstantPass>());
}

Optimizer::PassToken CreateDeadVariableEliminationPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::DeadVariableElimination>());
}

Optimizer::PassToken CreateStrengthReductionPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::StrengthReductionPass>());
}

Optimizer::PassToken CreateBlockMergePass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::BlockMergePass>());
}

Optimizer::PassToken CreateInlineExhaustivePass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::InlineExhaustivePass>());
}

Optimizer::PassToken CreateInlineOpaquePass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::InlineOpaquePass>());
}

Optimizer::PassToken CreateLocalAccessChainConvertPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::LocalAccessChainConvertPass>());
}

Optimizer::PassToken CreateLocalSingleBlockLoadStoreElimPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::LocalSingleBlockLoadStoreElimPass>());
}

Optimizer::PassToken CreateLocalSingleStoreElimPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::LocalSingleStoreElimPass>());
}

Optimizer::PassToken CreateInsertExtractElimPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::SimplificationPass>());
}

Optimizer::PassToken CreateDeadInsertElimPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::DeadInsertElimPass>());
}

Optimizer::PassToken CreateDeadBranchElimPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::DeadBranchElimPass>());
}

Optimizer::PassToken CreateLocalMultiStoreElimPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::SSARewritePass>());
}

Optimizer::PassToken CreateAggressiveDCEPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::AggressiveDCEPass>());
}

Optimizer::PassToken CreatePropagateLineInfoPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::ProcessLinesPass>(opt::kLinesPropagateLines));
}

Optimizer::PassToken CreateRedundantLineInfoElimPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::ProcessLinesPass>(opt::kLinesEliminateDeadLines));
}

Optimizer::PassToken CreateCompactIdsPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::CompactIdsPass>());
}

Optimizer::PassToken CreateMergeReturnPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::MergeReturnPass>());
}

std::vector<const char*> Optimizer::GetPassNames() const {
  std::vector<const char*> v;
  for (uint32_t i = 0; i < impl_->pass_manager.NumPasses(); i++) {
    v.push_back(impl_->pass_manager.GetPass(i)->name());
  }
  return v;
}

Optimizer::PassToken CreateCFGCleanupPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::CFGCleanupPass>());
}

Optimizer::PassToken CreateLocalRedundancyEliminationPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::LocalRedundancyEliminationPass>());
}

Optimizer::PassToken CreateLoopFissionPass(size_t threshold) {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::LoopFissionPass>(threshold));
}

Optimizer::PassToken CreateLoopFusionPass(size_t max_registers_per_loop) {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::LoopFusionPass>(max_registers_per_loop));
}

Optimizer::PassToken CreateLoopInvariantCodeMotionPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(MakeUnique<opt::LICMPass>());
}

Optimizer::PassToken CreateLoopPeelingPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::LoopPeelingPass>());
}

Optimizer::PassToken CreateLoopUnswitchPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::LoopUnswitchPass>());
}

Optimizer::PassToken CreateRedundancyEliminationPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::RedundancyEliminationPass>());
}

Optimizer::PassToken CreateRemoveDuplicatesPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::RemoveDuplicatesPass>());
}

Optimizer::PassToken CreateScalarReplacementPass(uint32_t size_limit) {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::ScalarReplacementPass>(size_limit));
}

Optimizer::PassToken CreatePrivateToLocalPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::PrivateToLocalPass>());
}

Optimizer::PassToken CreateCCPPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(MakeUnique<opt::CCPPass>());
}

Optimizer::PassToken CreateWorkaround1209Pass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::Workaround1209>());
}

Optimizer::PassToken CreateIfConversionPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::IfConversion>());
}

Optimizer::PassToken CreateReplaceInvalidOpcodePass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::ReplaceInvalidOpcodePass>());
}

Optimizer::PassToken CreateSimplificationPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::SimplificationPass>());
}

Optimizer::PassToken CreateLoopUnrollPass(bool fully_unroll, int factor) {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::LoopUnroller>(fully_unroll, factor));
}

Optimizer::PassToken CreateSSARewritePass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::SSARewritePass>());
}

Optimizer::PassToken CreateCopyPropagateArraysPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::CopyPropagateArrays>());
}

Optimizer::PassToken CreateVectorDCEPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(MakeUnique<opt::VectorDCE>());
}

Optimizer::PassToken CreateReduceLoadSizePass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::ReduceLoadSize>());
}

Optimizer::PassToken CreateCombineAccessChainsPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::CombineAccessChains>());
}

Optimizer::PassToken CreateUpgradeMemoryModelPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::UpgradeMemoryModel>());
}

Optimizer::PassToken CreateInstBindlessCheckPass(uint32_t desc_set,
                                                 uint32_t shader_id,
                                                 bool input_length_enable,
                                                 bool input_init_enable,
                                                 uint32_t version) {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::InstBindlessCheckPass>(desc_set, shader_id,
                                             input_length_enable,
                                             input_init_enable, version));
}

Optimizer::PassToken CreateInstBuffAddrCheckPass(uint32_t desc_set,
                                                 uint32_t shader_id,
                                                 uint32_t version) {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::InstBuffAddrCheckPass>(desc_set, shader_id, version));
}

Optimizer::PassToken CreateConvertRelaxedToHalfPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::ConvertToHalfPass>());
}

Optimizer::PassToken CreateRelaxFloatOpsPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::RelaxFloatOpsPass>());
}

Optimizer::PassToken CreateCodeSinkingPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::CodeSinkingPass>());
}

Optimizer::PassToken CreateGenerateWebGPUInitializersPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::GenerateWebGPUInitializersPass>());
}

Optimizer::PassToken CreateFixStorageClassPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::FixStorageClass>());
}

Optimizer::PassToken CreateLegalizeVectorShufflePass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::LegalizeVectorShufflePass>());
}

Optimizer::PassToken CreateDecomposeInitializedVariablesPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::DecomposeInitializedVariablesPass>());
}

Optimizer::PassToken CreateSplitInvalidUnreachablePass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::SplitInvalidUnreachablePass>());
}

Optimizer::PassToken CreateGraphicsRobustAccessPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::GraphicsRobustAccessPass>());
}

Optimizer::PassToken CreateDescriptorScalarReplacementPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::DescriptorScalarReplacement>());
}

Optimizer::PassToken CreateWrapOpKillPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(MakeUnique<opt::WrapOpKill>());
}

Optimizer::PassToken CreateAmdExtToKhrPass() {
  return MakeUnique<Optimizer::PassToken::Impl>(
      MakeUnique<opt::AmdExtensionToKhrPass>());
}

}  // namespace spvtools


text:
package org.geneticmachine.common.graph

import scala.reflect._

object Graph {

  val algorithmLabel = "ALGORITHM"
  val environmentLabel = "ENVIRONMENT"

  val inputLabel = "INPUT"
  val outputLabel = "OUTPUT"
  val nodeLabel = "NODE"

  val parentRelation = "INHERIT"
  val experimentRelation = "EXAMINES"

  val typeProp = "$type"
  val labelProp = "$label"

  val inputsProp = "$inputs"
  val outputsProp = "$outputs"

  val idProp = "$id"
  val errorCauseProp = "$cause"
  val nullParent: Long = -1l

  final case class Port(nodeId: Int, portN: Int)

  final case class Node(inputs: Int, outputs: Int, props: Map[String, Any], edges: Array[Set[Port]]) {
    override def toString: String = {
      val edgesRepr = (for {
        (ports, portN) <- edges.zipWithIndex
        portsRepr = (for { port <- ports } yield s"${port.nodeId}[${port.portN}]").mkString(", ")
      } yield s"        [$portN]: {$portsRepr}").mkString("\n")

      val propsRepr = (for {
        (k, v) <- props
      } yield s"$k = $v").mkString(", ")

      s"[$inputs -> $outputs] {$propsRepr}\n$edgesRepr"
    }
  }

  def empty(graphLabel: String, inputType: String, outputType: String): Graph = {
    val builder = GraphBuilder(graphLabel)

    val inputNode = builder.node(inputType).asInput()
    val outputNode = builder.node(outputType).asOutput()
    inputNode --> outputNode

    builder.toGraph
  }

  def single(graphLabel: String)(nodeType: String, props: Map[String, Any]): Graph = {
    val builder = new GraphBuilder(graphLabel)

    builder.node(nodeType)(props).asInput().asOutput()

    builder.toGraph
  }

  def errorGraph(graphLabel: String, e: Throwable): Graph = {
    val props = Map(errorCauseProp -> e.getStackTrace.mkString("\n"))

    single(graphLabel)("Error", props)
  }

  final class Props(val props: Map[String, Any]) {
    def getAs[T : ClassTag](key: String): Option[T] = {
      for {
        x <- props.get(key)
        if classTag[T].runtimeClass.isInstance(x)
      } yield x.asInstanceOf[T]
    }
  }

  import scala.language.implicitConversions
  implicit def mapToProps(props: Map[String, Any]): Props = new Props(props)
}

import Graph._

final case class Graph(props: Map[String, Any], relations: Map[String, Set[Long]],
                       nodes: Vector[Node], inputNodeId: Int, outputNodeId: Int) {

  def apply(prop: String): Any = props(prop)
  def apply(nodeId: Int): Node = nodes(nodeId)
  def node(nodeId: Int): Node = nodes(nodeId)

  def id: Option[Long] = props.getAs[Long](idProp)

  override def toString: String = {
    def nodeRepr(node: Node, nodeId: Int): String = {
      nodeId match {
        case _ if nodeId == outputNodeId && nodeId == inputNodeId =>
          s"  ->($nodeId)->  $node"

        case `inputNodeId` =>
          s"  ->($nodeId)    $node"

        case `outputNodeId` =>
          s"    ($nodeId)->  $node"

        case _ =>
          s"    ($nodeId)    $node"
      }
    }

    val nodesRepr = (for {
      (node, nodeId) <- nodes.zipWithIndex
    } yield nodeRepr(node, nodeId)).mkString("\n")

    val propsRepr = (for {
      (k, v) <- props
    } yield s"$k = $v").mkString(", ")

    val relationsRepr = (for {
      (r, id) <- relations
    } yield s"  -[$r]-> Graph($id)").mkString("\n")

    s"Graph {$propsRepr}:\n{$relationsRepr}:\n$nodesRepr"
  }

  def injection(propName: String, value: Any): Graph = {
    this.copy(props = props + (propName -> value))
  }

  def idInjection(id: Long): Graph = {
    this.copy(props = props + (idProp -> id))
  }

  def relationInjection(relationType: String, id: Long): Graph = {
    val relations = this.relations.getOrElse(relationType, Set.empty)
    val injected = this.relations.updated(relationType, relations + id)
    this.copy(relations = injected)
  }

  def uniqueRelationInjection(relationType: String, id: Long): Graph = {
    val injected = this.relations.updated(relationType, Set(id))
    this.copy(relations = injected)
  }

  def parentInjection(id: Long): Graph = {
    uniqueRelationInjection(parentRelation, id)
  }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Get files from <img> tags
 * some image binary is copied thus
 * @param html {string}
 * @param options {Object}
 * @param options.asBinary {boolean}
 * @param options.success {function}
 * @param options.error {function}
 * @return {boolean} is data found
 */
function getImagesFromHtml(html, options) {

    // global pattern must be announced as local variable
    var pattern = /<img[^>]+?src=(["'])([^>]+?)\1/ig,
        urlMatch,
        found = false;

    while (urlMatch = pattern.exec(html)) {
        found = getFilesFromText(urlMatch[2], options) || found;
    }

    return found;
}


text:
package utils

import (
	"encoding/base64"
	"fmt"
	"strings"
)

// BasicAuth basic auth information
type BasicAuth struct {
	Username string
	Password string
}

func (ba *BasicAuth) String() string {
	encoded := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", ba.Username, ba.Password)))
	return fmt.Sprintf("Basic %s", encoded)
}

// ParseAuthHeader creates a new BasicAuth from header values
func ParseAuthHeader(header string) (*BasicAuth, error) {
	values := strings.Fields(header)
	if len(values) != 2 {
		return nil, fmt.Errorf(fmt.Sprintf("Failed to parse header '%s'", header))
	}

	authType := strings.ToLower(values[0])
	if authType != "basic" {
		return nil, fmt.Errorf("Expected basic auth type, got '%s'", authType)
	}

	encodedString := values[1]
	decodedString, err := base64.StdEncoding.DecodeString(encodedString)
	if err != nil {
		return nil, fmt.Errorf("Failed to parse header '%s', base64 failed: %s", header, err)
	}

	values = strings.SplitN(string(decodedString), ":", 2)
	if len(values) != 2 {
		return nil, fmt.Errorf("Failed to parse header '%s', expected separator ':'", header)
	}
	return &BasicAuth{Username: values[0], Password: values[1]}, nil
}


text:
"""Definition of the Player class used in the Mastermind project."""

from functions import remove_empty_elements

class Player(object):

    """Mastermind Player class."""

    def __init__(self):
        self.name = ''
        self.score = 0

    def __validate_input(self, message, allow_save=False):
        """Validate pattern input; return pattern on success, else None."""
        pattern = None
        while not pattern:
            if allow_save:  # Allow Ctrl-D saving
                pattern = raw_input(message)[:self.pattern_length].lower()
            else:
                try:
                    pattern = raw_input(message)[:self.pattern_length].lower()
                except EOFError:
                    print

        if len(pattern) < self.pattern_length:      # Too short
            return

        for colour in pattern:
            if colour not in self.pattern_colours:  # Invalid colour
                return

        return list(pattern)

    def remember_rules(self, pattern_length, pattern_colours):
        """Remember current game set rules."""
        self.pattern_length = pattern_length
        self.pattern_colours = pattern_colours

    def ready_for_game(self):
        pass

    def ask_for_name(self, message=''):
        """Set player name."""
        self.name = None
        while not self.name:
            try:
                self.name = raw_input(message).lower().capitalize()
            except EOFError:
                print

    def choose_secret_pattern(self, message=''):
        """Set secret pattern."""
        self.secret_pattern = None
        while not self.secret_pattern:
            self.secret_pattern = self.__validate_input(message)

    def make_guess(self, message='', allow_save=False):
        """Set guess."""
        self.guess = None
        while not self.guess:
            self.guess = self.__validate_input(message, allow_save)

    def is_correct(self, guess):
        """Return True if guess is correct, else False."""
        return guess == self.secret_pattern

    def prepare_feedback(self, guess, feedback_keys):
        """Prepare feedback for guess."""
        self.feedback = []

        guess = list(guess)                         # Cast from str
        secret_pattern = list(self.secret_pattern)  # Make a copy

        # Find correct pegs (feedback 'black')
        for i, colour in enumerate(guess):
            if colour == secret_pattern[i]:
                self.feedback.append(feedback_keys['correct'])
                guess[i] = secret_pattern[i] = None  # Done

        # Remove done pegs
        remove_empty_elements(guess)
        remove_empty_elements(secret_pattern)

        # Find partially correct pegs (feedback 'white')
        for i, colour in enumerate(guess):
            if colour in secret_pattern:
                self.feedback.append(feedback_keys['partially_correct'])
                secret_pattern[secret_pattern.index(colour)] = None  # Done

    def show_feedback(self, feedback_names):
        """Show feedback for current guess."""
        if self.feedback:
            feedback = []
            for key in self.feedback:
                feedback.append(feedback_names[key])  # Use feedback names
            print ' '.join(feedback)
        else:
            print 'none'

    def analyse_feedback(self, feedback):
        pass

    def show_secret_pattern(self, colour_names):
        """Show secret pattern."""
        secret_pattern = []
        for colour in self.secret_pattern:
            secret_pattern.append(colour_names[colour])  # Use colour names
        print ' '.join(secret_pattern)

    def gain_point(self):
        """Gain a point."""
        self.score += 1


text:
/*
   Copyright (C) 2006, 2007 Sony Computer Entertainment Inc.
   All rights reserved.

   Redistribution and use in source and binary forms,
   with or without modification, are permitted provided that the
   following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Sony Computer Entertainment Inc nor the names
      of its contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE.
*/

#ifndef _VECTORMATH_VECIDX_AOS_H
#define _VECTORMATH_VECIDX_AOS_H

#include "floatInVec.h"

namespace Vectormath
{
namespace Aos
{
//-----------------------------------------------------------------------------
// VecIdx
// Used in setting elements of Vector3, Vector4, Point3, or Quat with the
// subscripting operator.
//

VM_ATTRIBUTE_ALIGNED_CLASS16(class)
VecIdx
{
private:
    __m128& ref;
    int i;

public:
    inline VecIdx(__m128 & vec, int idx)
        : ref(vec)
    {
        i = idx;
    }

// implicitly casts to float unless _VECTORMATH_NO_SCALAR_CAST defined
// in which case, implicitly casts to floatInVec, and one must call
// getAsFloat to convert to float.
//
#ifdef _VECTORMATH_NO_SCALAR_CAST
    inline operator floatInVec() const;
    inline float getAsFloat() const;
#else
    inline operator float() const;
#endif

    inline float operator=(float scalar);
    inline floatInVec operator=(const floatInVec& scalar);
    inline floatInVec operator=(const VecIdx& scalar);
    inline floatInVec operator*=(float scalar);
    inline floatInVec operator*=(const floatInVec& scalar);
    inline floatInVec operator/=(float scalar);
    inline floatInVec operator/=(const floatInVec& scalar);
    inline floatInVec operator+=(float scalar);
    inline floatInVec operator+=(const floatInVec& scalar);
    inline floatInVec operator-=(float scalar);
    inline floatInVec operator-=(const floatInVec& scalar);
};

} // namespace Aos
} // namespace Vectormath

#endif


text:
package org.jitsi.impl.neomedia.transform;

import org.jitsi.impl.neomedia.*;
import org.jitsi.util.function.*;

/**
 *
 * @author Lyubomir Marinov
 */
public class SinglePacketTransformerAdapter
    extends SinglePacketTransformer
{
    /**
     * Ctor.
     */
    public SinglePacketTransformerAdapter()
    {
        super();
    }

    /**
     * Ctor.
     *
     * @param packetPredicate the <tt>PacketPredicate</tt> to use to match
     * packets to (reverse) transform.
     */
    public SinglePacketTransformerAdapter(Predicate<RawPacket> packetPredicate)
    {
        super(packetPredicate);
    }

    @Override
    public RawPacket reverseTransform(RawPacket pkt)
    {
        return pkt;
    }

    @Override
    public RawPacket transform(RawPacket pkt)
    {
        return pkt;
    }
}


text:
/**
 * @fileOverview shape creator
 * @author Daisuke Homma
 */

new function() {  // block

an.ShapeCreator = function() {

  an.g.ShapeCreator = this;

  this.on;
  this.x;
  this.y;
  this.width;
  this.height;

  this.initialize();

}

var self = an.ShapeCreator;

// inherit from an.EventState
self.prototype = new an.EventState();

self.prototype.initialize = function() {

  this.on = false;
  this.x = 0;
  this.y = 0;
  this.width = 0;
  this.height = 0;

  an.g.editor.deselectAll();

}

self.prototype.select = function() {

  an.g.editor.setEditorMode(an.g.editor.EditorModes.shape);
  this.selectSelf();

}

self.prototype.deselect = function() {

  this.initialize();
  this.deselectSelf();

}

self.prototype.onMouseDown = function(e) {

  var position = an.u.getMousePositionInCanvas(e);
  this.x = position.x;
  this.y = position.y;
  this.width = 0;
  this.height = 0;

  this.on = true;

}

self.prototype.onMouseMove = function(e) {

  if( !this.on ) { return; }

  var position = an.u.getMousePositionInCanvas(e);
  this.width = position.x - this.x;
  this.height = position.y - this.y;

  an.g.editor.drawShape(this.x, this.y, this.width, this.height);

}

self.prototype.onMouseUp = function(e) {

  if( !this.on ) { return; }

  var position = an.u.getMousePositionInCanvas(e);
  this.width = position.x - this.x;
  this.height = position.y - this.y;

  an.g.editor.createShape(this.x, this.y, this.width, this.height);

  this.initialize();
  an.g.editor.draw();

}

} // block


text:
//
//  JSONRequest.h
//  JSONClient
//
//  Created by John Clayton on 9/6/2009.
//  Copyright 2009 Fivesquare Software, LLC. All rights reserved.
//

#import <Foundation/Foundation.h>

@class JSONRequest;

@protocol JSONRequestDelegate <NSObject>
@optional
- (void) requestDidFinish:(JSONRequest *)request;
@end

@class JSONResponse;

@interface JSONRequest : NSOperation {
	id<JSONRequestDelegate> delegate;

	NSURLRequest *urlRequest;
	NSURLCredential *credentials;

	JSONResponse *response;
}

@property (nonatomic, retain) id<JSONRequestDelegate> delegate;
@property (nonatomic, retain) NSURLRequest *urlRequest;
@property (nonatomic, retain) NSURLCredential *credentials;
@property (nonatomic, readonly) JSONResponse *response;

- (id) initWithURLRequest:(NSURLRequest *)aURLRequest;

@end


text:
int test(int x) {
  // We expect to get warnings for all of the quoted includes but none of the
  // system includes here because the first module is a non-system module and
  // the quote macros come from non-system-headers.
  x = FOO1_QUOTE(x); // expected-warning {{ambiguous expansion of macro}}
  // expected-note@Inputs/macro-ambiguity/c/quote/c_quote.h:4 {{expanding this definition}}
  // expected-note@Inputs/macro-ambiguity/a/quote/a_quote.h:4 {{other definition}}

  x = FOO1_SYSTEM(x);

  x = BAR1_QUOTE(x); // expected-warning {{ambiguous expansion of macro}}
  // expected-note@Inputs/macro-ambiguity/d/quote/d_quote.h:4 {{expanding this definition}}
  // expected-note@Inputs/macro-ambiguity/a/quote/a_quote.h:5 {{other definition}}

  x = BAR1_SYSTEM(x);

  x = BAZ1_QUOTE(x); // expected-warning {{ambiguous expansion of macro}}
  // expected-note@Inputs/macro-ambiguity/a/quote/a_quote.h:6 {{expanding this definition}}
  // expected-note@Inputs/macro-ambiguity/e/quote/e_quote.h:4 {{other definition}}

  x = BAZ1_SYSTEM(x);

  // Here, we don't even warn on bar because in that cas both b and d are
  // system modules and so the use of non-system headers is irrelevant.
  x = FOO2_QUOTE(x); // expected-warning {{ambiguous expansion of macro}}
  // expected-note@Inputs/macro-ambiguity/c/quote/c_quote.h:5 {{expanding this definition}}
  // expected-note@Inputs/macro-ambiguity/b/quote/b_quote.h:4 {{other definition}}

  x = FOO2_SYSTEM(x);

  x = BAR2_QUOTE(x);

  x = BAR2_SYSTEM(x);

  x = BAZ2_QUOTE(x); // expected-warning {{ambiguous expansion of macro}}
  // expected-note@Inputs/macro-ambiguity/b/quote/b_quote.h:6 {{expanding this definition}}
  // expected-note@Inputs/macro-ambiguity/e/quote/e_quote.h:5 {{other definition}}

  x = BAZ2_SYSTEM(x);
  return x;
}


text:
// Copyright (c) 2014 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;

namespace ICSharpCode.Roslyn.PatternMatching
{
	/// <summary>
	/// Data holder for the overall pattern matching operation.
	/// </summary>
	/// <remarks>
	/// This type is a struct in order to prevent unnecessary memory allocations during pattern matching.
	/// The default value <c>default(Match)</c> represents an unsuccessful match.
	/// </remarks>
	public struct Match
	{
		static readonly List<KeyValuePair<CaptureGroup, SyntaxNode>> emptyResults = new List<KeyValuePair<CaptureGroup, SyntaxNode>>();

		readonly SemanticModel semanticModel;
		List<KeyValuePair<CaptureGroup, SyntaxNode>> results;

		/// <summary>
		/// Creates a new Match instance.
		/// </summary>
		public Match(SemanticModel semanticModel = null)
		{
			this.semanticModel = semanticModel;
			this.results = null;
		}

		/// <summary>
		/// Gets whether the match was successful.
		/// </summary>
		public bool Success {
			get {
				return results != null;
			}
			internal set {
				if (value) {
					if (results == null)
						results = emptyResults;
				} else {
					results = null;
				}
			}
		}

		/// <summary>
		/// Gets whether the match was successful.
		/// </summary>
		public static bool operator true(Match m)
		{
			return m.Success;
		}

		/// <summary>
		/// Gets whether the match failed.
		/// </summary>
		public static bool operator false(Match m)
		{
			return !m.Success;
		}

		/// <summary>
		/// Retrieves the semantic model used for pattern matching.
		/// </summary>
		public SemanticModel SemanticModel {
			get {
				return semanticModel;
			}
		}

		internal void Add(CaptureGroup g, SyntaxNode n)
		{
			if (results == null)
				results = new List<KeyValuePair<CaptureGroup, SyntaxNode>>();
			results.Add(new KeyValuePair<CaptureGroup, SyntaxNode>(g, n));
		}

		internal int CheckPoint()
		{
			return results != null ? results.Count : 0;
		}

		internal void RestoreCheckPoint(int checkPoint)
		{
			if (results != null)
				results.RemoveRange(checkPoint, results.Count - checkPoint);
		}

		public IEnumerable<SyntaxNode> Get(CaptureGroup captureGroup)
		{
			if (results != null) {
				foreach (var pair in results) {
					if (pair.Key == captureGroup)
						yield return pair.Value;
				}
			}
		}

		public IEnumerable<T> Get<T>(CaptureGroup<T> captureGroup) where T : SyntaxNode
		{
			if (results != null) {
				foreach (var pair in results) {
					if (pair.Key == captureGroup)
						yield return (T)pair.Value;
				}
			}
		}
	}
}


text:
package ipv6_test

import (
	"errors"

	"golang.org/x/sys/unix"
)

// isENOBUFS reports whether err is unix.ENOBUFS.
// (Always false on non-Unix platforms.)
func isENOBUFS(err error) bool {
	return errors.Is(err, unix.ENOBUFS)
}


text:
<resources>
    <string name="app_name">Lockable Bottom Sheet</string>
</resources>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Flora, Jena 62: 358 (1879)

#### Original name
Opegrapha devulgata Nyl.

### Remarks
null


text:
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
    if (!req.user) {
        res.render('index', { title: 'DriveSpoke' });
    } else {
        res.render('driver-dashboard', { title: 'DriveSpoke - Driver Dashboard' });
    }
});

router.get('/logout', function(req, res, next) {
	req.logout();
	res.redirect('/');
});

module.exports = router;


text:
// Copyright 2015 The Prometheus Authors
// 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.

// +build !nofilesystem

package collector

import (
	"errors"
	"unsafe"

	"github.com/prometheus/common/log"
)

/*
#include <sys/param.h>
#include <sys/ucred.h>
#include <sys/mount.h>
#include <stdio.h>
*/
import "C"

const (
	defIgnoredMountPoints = "^/(dev)($|/)"
)

var (
	filesystemLabelNames = []string{"filesystem"}
)

// Expose filesystem fullness.
func (c *filesystemCollector) GetStats() (stats []filesystemStats, err error) {
	var mntbuf *C.struct_statfs
	count := C.getmntinfo(&mntbuf, C.MNT_NOWAIT)
	if count == 0 {
		return nil, errors.New("getmntinfo() failed")
	}

	mnt := (*[1 << 30]C.struct_statfs)(unsafe.Pointer(mntbuf))
	stats = []filesystemStats{}
	for i := 0; i < int(count); i++ {
		name := C.GoString(&mnt[i].f_mntonname[0])
		if c.ignoredMountPointsPattern.MatchString(name) {
			log.Debugf("Ignoring mount point: %s", name)
			continue
		}
		labelValues := []string{name}
		stats = append(stats, filesystemStats{
			labelValues: labelValues,
			size:        float64(mnt[i].f_blocks) * float64(mnt[i].f_bsize),
			free:        float64(mnt[i].f_bfree) * float64(mnt[i].f_bsize),
			avail:       float64(mnt[i].f_bavail) * float64(mnt[i].f_bsize),
			files:       float64(mnt[i].f_files),
			filesFree:   float64(mnt[i].f_ffree),
		})
	}
	return stats, nil
}


text:
Sample Functions Framework Ruby
-------------------------------

Run Locally:
1. [Install Ruby](https://www.ruby-lang.org/en/documentation/installation/)
1. Install [Bundler](https://bundler.io/)
    ```
    gem install bundler
    ```
1. Install application dependencies
    ```
    bundle install
    ```
1. Run the server locally:
    ```
    bundle exec functions-framework-ruby --source=app.rb --target=hello
    ```

Run Locally with Buildpacks & Docker:
```
pack build --builder=gcr.io/buildpacks/builder sample-functions-framework-ruby
docker run -it -ePORT=8080 -p8080:8080 sample-functions-framework-ruby
```

Run on Cloud Run:

[![Run on Google Cloud](https://deploy.cloud.run/button.svg)](https://deploy.cloud.run)


text:
// This file is automatically generated.

package adila.db;

/*
 * Allview P5 Life
 *
 * DEVICE: P5Life
 * MODEL: P5Life
 */
final class p5life_p5life {
    public static final String DATA = "Allview|P5 Life|";
}


text:
package org.apache.druid.sql.calcite.schema;

import org.apache.druid.server.coordination.DruidServerMetadata;
import org.apache.druid.sql.calcite.table.RowSignature;
import org.apache.druid.timeline.DataSegment;

import javax.annotation.Nullable;
import java.util.Set;

/**
 * Immutable representation of RowSignature and other segment attributes needed by {@link SystemSchema.SegmentsTable}
 * This class contains the metadata of segments announced by historicals or ingestion tasks.
 */
public class AvailableSegmentMetadata
{
  public static Builder builder(
      DataSegment segment,
      long isRealtime,
      Set<DruidServerMetadata> segmentServers,
      RowSignature rowSignature,
      long numRows
  )
  {
    return new Builder(segment, isRealtime, segmentServers, rowSignature, numRows);
  }

  public static Builder from(AvailableSegmentMetadata h)
  {
    return new Builder(
        h.getSegment(),
        h.isRealtime(),
        h.getReplicas(),
        h.getRowSignature(),
        h.getNumRows()
    );
  }

  private final DataSegment segment;
  // Booleans represented as long type, where 1 = true and 0 = false
  // to make it easy to count number of segments which are realtime
  private final long isRealtime;
  // set of servers that contain the segment
  private final Set<DruidServerMetadata> segmentServers;
  private final long numRows;
  @Nullable
  private final RowSignature rowSignature;

  private AvailableSegmentMetadata(Builder builder)
  {
    this.rowSignature = builder.rowSignature;
    this.isRealtime = builder.isRealtime;
    this.segmentServers = builder.segmentServers;
    this.numRows = builder.numRows;
    this.segment = builder.segment;
  }

  public long isRealtime()
  {
    return isRealtime;
  }

  public DataSegment getSegment()
  {
    return segment;
  }

  public Set<DruidServerMetadata> getReplicas()
  {
    return segmentServers;
  }

  public long getNumReplicas()
  {
    return segmentServers.size();
  }

  public long getNumRows()
  {
    return numRows;
  }

  @Nullable
  public RowSignature getRowSignature()
  {
    return rowSignature;
  }

  public static class Builder
  {
    private final DataSegment segment;

    private long isRealtime;
    private Set<DruidServerMetadata> segmentServers;
    @Nullable
    private RowSignature rowSignature;
    private long numRows;

    private Builder(
        DataSegment segment,
        long isRealtime,
        Set<DruidServerMetadata> servers,
        @Nullable RowSignature rowSignature,
        long numRows
    )
    {
      this.segment = segment;
      this.isRealtime = isRealtime;
      this.segmentServers = servers;
      this.rowSignature = rowSignature;
      this.numRows = numRows;
    }

    public Builder withRowSignature(RowSignature rowSignature)
    {
      this.rowSignature = rowSignature;
      return this;
    }

    public Builder withNumRows(long numRows)
    {
      this.numRows = numRows;
      return this;
    }

    public Builder withReplicas(Set<DruidServerMetadata> servers)
    {
      this.segmentServers = servers;
      return this;
    }

    public Builder withRealtime(long isRealtime)
    {
      this.isRealtime = isRealtime;
      return this;
    }

    public AvailableSegmentMetadata build()
    {
      return new AvailableSegmentMetadata(this);
    }
  }

}


text:
% Example evaluation script of keypoint matching benchmark to compute
% false-positive rate (error) at 95% recall

% Path to .log files (change me)
descLogFile = '3dmatch.log'; % List of descriptor distances per comparison
gtLogFile = 'validation-set-gt.log'; % Ground truth binary correspondence labels

% Load descriptor distances
descDistPred = dlmread(descLogFile);
numComparisons = descDistPred(1);
descDistPred = descDistPred(2:end)';

% Load ground truth binary labels (1 - is match, 0 - is nonmatch)
descIsMatchGT = dlmread(gtLogFile);
numComparisons = descIsMatchGT(1);
descIsMatchGT = descIsMatchGT(2:end)';

% Loop through 1001 descriptor distance thresholds
thresh = (0:(max(descDistPred)*1.05/1000):(max(descDistPred)*1.05))';

allThresh = repmat(thresh,1,size(descDistPred,2));
allDescDistPred = repmat(descDistPred,length(thresh),1);
allDescIsMatchGT = repmat(descIsMatchGT,length(thresh),1);
allDescIsMatchPred = allDescDistPred < allThresh;

numTP = sum(allDescIsMatchPred&allDescIsMatchGT,2);
numFP = sum(allDescIsMatchPred&~allDescIsMatchGT,2);
numTN = sum(~allDescIsMatchPred&~allDescIsMatchGT,2);
numFN = sum(~allDescIsMatchPred&allDescIsMatchGT,2);

accuracy = (numTP+numTN)./(numTP+numTN+numFP+numFN);
precision = numTP./(numTP+numFP);
recall = numTP./(numTP+numFN);
TNrate = numTN./(numTN+numFP);
FPrate = numFP./(numFP+numTN);

errorAt95Recall = mean(FPrate(find(recall>0.949&recall<0.951)));
fprintf('False-positive rate (error) at 95%% recall: %f\n',errorAt95Recall);


text:
<?php
include 'config.php';

$results = array($statusMessage,
	$totalMem,
	$usedMem,
	$availMem,
	$memPercent,
	$totalDisk,
	$usedDisk,
	$availDisk,
	$diskPercent,
	$totalBW,
	$usedBW,
	$availBW,
	$bwPercent,
	$onlineMessage,
	$offlineMessage,
	$onlineReload,
	$offlineReload);

echo json_encode($results);
?>


text:
namespace app.guest.login {

    describe('Login', () => {

        let $q:ng.IQService,
            fixtures = {
                getLoginSuccessPromise(deferredCreds) {

                    let deferred = $q.defer();

                    deferredCreds.promise.then(null, null, (creds) => {
                        if (creds.password == 'fail') {
                            deferred.notify(new NgJwtAuth.NgJwtAuthCredentialsFailedException('error'));
                        }
                        else if (creds.password == 'differentemail') {
                            deferred.resolve({email:'foofoo'});
                        }
                        else {
                            deferred.resolve('success');
                            deferredCreds.resolve(creds);
                        }
                    });

                    return {
                        promise: deferred.promise,
                    };
                }
            };

        describe('Configuration', () => {

            let LoginController:LoginController,
                $scope:ng.IScope,
                $rootScope:ng.IRootScopeService,
                $timeout:ng.ITimeoutService,
                $mdDialog:ng.material.IDialogService,
                notificationService:common.services.notification.NotificationService,
                ngJwtAuthService:NgJwtAuth.NgJwtAuthService,
                deferredCredentials:ng.IDeferred<any>,
                loginSuccess:{promise:ng.IPromise<any>},
                authService = {
                    socialLogin:(type:string, redirectState:string = '', redirectStateParams:Object = {}) => {
                        return true;
                    }
                }
                ;

            beforeEach(() => {

                module('app');

                inject(($controller, _$rootScope_, _ngJwtAuthService_, _$mdDialog_, _notificationService_, _$q_, _$timeout_) => {
                    $rootScope = _$rootScope_;
                    $scope = $rootScope.$new();
                    $timeout = _$timeout_;
                    $mdDialog = _$mdDialog_;
                    notificationService = _notificationService_;
                    ngJwtAuthService = _ngJwtAuthService_;
                    $q = _$q_;
                    deferredCredentials = $q.defer();

                    loginSuccess = fixtures.getLoginSuccessPromise(deferredCredentials);

                    LoginController = $controller(app.guest.login.namespace + '.controller', {
                        $scope: $scope,
                        $mdDialog: $mdDialog,
                        deferredCredentials: deferredCredentials,
                        loginSuccess: loginSuccess,
                        authService: authService
                    });
                });

                sinon.spy($mdDialog, 'hide');
                sinon.spy($mdDialog, 'cancel');
                sinon.spy($mdDialog, 'show');
                sinon.spy(notificationService, 'toast');
                sinon.spy(authService, 'socialLogin');

            });

            afterEach(() => {

                (<any>$mdDialog).hide.restore();
                (<any>$mdDialog).cancel.restore();
                (<any>$mdDialog).show.restore();
                (<any>notificationService).toast.restore();
                (<any>authService).socialLogin.restore();

            });

            it('should be a valid controller', () => {

                expect(LoginController).to.be.ok;
            });

            it('should have initialised the auth service', () => {

                $scope.$apply();
                expect((<any>ngJwtAuthService).refreshTimerPromise).to.be.ok;

            });

            describe('dialog interactions - valid login', () => {

                it('should cancel dialog when requested', () => { //@todo resolve why the cancel function is not firing the $mdDialog.show().catch() method

                    LoginController.cancelLoginDialog();

                    $timeout.flush(); //flush timeout as the modal is delayed

                    expect($mdDialog.cancel).to.have.been.called;
                    expect(deferredCredentials.promise).eventually.to.be.rejected;

                    $scope.$apply();

                    expect(ngJwtAuthService.loggedIn).to.be.false;

                });

                it('should show the login dialog when prompted', () => {

                    ngJwtAuthService.promptLogin();

                    $timeout.flush(); //flush timeout as the modal is delayed

                    expect($mdDialog.show).to.have.been.called;

                });

                it('should resolve the deferred credentials when valid login credentials are passed, then hide the dialog on success', function () {

                    let creds = {
                        username: 'foo',
                        password: 'bar',
                    };

                    LoginController.login(creds.username, creds.password);

                    expect(deferredCredentials.promise).eventually.to.become(creds);

                    expect(loginSuccess.promise).eventually.to.become('success');

                    $scope.$apply();

                    return loginSuccess.promise.then(() => {

                        expect($mdDialog.hide).to.have.been.called;

                    });

                });

                it('should show a please confirm email dialog when logged in with an unconfirmed email', function () {

                    let creds = {
                        username: 'foo',
                        password: 'differentemail',
                    };

                    LoginController.login(creds.username, creds.password);

                    expect(deferredCredentials.promise).eventually.to.become(creds);

                    expect(loginSuccess.promise).eventually.to.become({email:'foofoo'});

                    $scope.$apply();

                    return loginSuccess.promise.then(() => {

                        expect($mdDialog.show).to.have.been.called;

                    });

                });

                it('should cancel dialog and open reset password', () => {

                    LoginController.resetPassword();

                    $timeout.flush(); //flush timeout as the modal is delayed

                    expect($mdDialog.cancel).to.have.been.called;
                    expect(deferredCredentials.promise).eventually.to.be.rejected;

                    //check to see if the reset password dialog has been opened
                    expect($mdDialog.show).to.have.been.calledWith(sinon.match.has('controller', 'app.guest.resetPassword.controller'));

                });

                it('should be able to log you in using a social network', () => {

                    LoginController.socialLogin(common.models.UserSocialLogin.facebookType);

                    expect(authService.socialLogin).to.have.been.calledWith(common.models.UserSocialLogin.facebookType);
                });
            });

            describe('dialog interactions - invalid login', () => {

                let credsFail = {
                    username: 'foo',
                    password: 'fail',
                };

                let credsPass = {
                    username: 'foo',
                    password: 'pass',
                };

                it('should show an error when invalid login credentials are passed', () => {

                    var progressSpy = sinon.spy();
                    deferredCredentials.promise.then(null, null, progressSpy);

                    LoginController.login(credsFail.username, credsFail.password);
                    $scope.$apply();

                    LoginController.login(credsPass.username, credsPass.password);
                    $scope.$apply();

                    return loginSuccess.promise.then(function () {
                        progressSpy.should.have.been.calledWith(credsFail);
                        progressSpy.should.have.been.calledWith(credsPass);
                        progressSpy.should.have.been.calledTwice;
                        expect(notificationService.toast).to.have.been.calledOnce;
                    });

                });

                it('should only repeat the error message once for each failed credential attempt', () => {

                    var progressSpy = sinon.spy();
                    deferredCredentials.promise.then(null, null, progressSpy);

                    LoginController.login(credsFail.username, credsFail.password);
                    LoginController.login(credsFail.username, credsFail.password);
                    LoginController.login(credsPass.username, credsPass.password);

                    $scope.$apply();

                    return loginSuccess.promise.then(function () {
                        progressSpy.should.have.been.calledWith(credsFail);
                        progressSpy.should.have.been.calledWith(credsPass);
                        expect(notificationService.toast).to.have.been.calledTwice;
                    });

                })

            });

        });

    });

}


text:
<?php

namespace Success\SalesGeneratorBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Question
 *
 * @ORM\Table(name="Questions")
 * @ORM\Entity(repositoryClass="Success\SalesGeneratorBundle\Entity\QuestionRepository")
 */
class Question
{
    const PREVIEW_QUESTION_MAX_LENGTH = 25;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="text", type="text")
     */
    private $text;

    /**
     * @ORM\ManyToOne(targetEntity="Success\SalesGeneratorBundle\Entity\Audience")
     * @ORM\JoinColumn(name="audience_id", referencedColumnName="id", nullable=true)
     */
    private $audience;

    /**
     * @var ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Success\SalesGeneratorBundle\Entity\Answer", mappedBy="currentQuestion", cascade={"all"}, orphanRemoval=true)
     */
    private $answers;

    public function __construct()
    {
        $this->answers = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set text
     *
     * @param string $text
     * @return Question
     */
    public function setText($text)
    {
        $this->text = $text;

        return $this;
    }

    /**
     * Get text
     *
     * @return string
     */
    public function getText()
    {
        return $this->text;
    }

    /**
     * Set audience
     *
     * @param \Success\SalesGeneratorBundle\Entity\Audience $audience
     * @return Success\SalesGeneratorBundle\Entity\Question
     */
    public function setAudience(\Success\SalesGeneratorBundle\Entity\Audience $audience)
    {
        $this->audience = $audience;

        return $this;
    }

    /**
     * Get audience
     *
     * @return \Success\SalesGeneratorBundle\Entity\Audience
     */
    public function getAudience()
    {
        return $this->audience;
    }

    /**
     *
     * @param \Success\SalesGeneratorBundle\Entity\Answer $answer
     * @return \Success\SalesGeneratorBundle\Entity\Question
     */
    public function addAnswer(\Success\SalesGeneratorBundle\Entity\Answer $answer)
    {
        if (!$this->answers->contains($answer)) {
            $answer->setCurrentQuestion($this);
            $this->answers[] = $answer;
        }

        return $this;
    }

    /**
     *
     * @param \Success\SalesGeneratorBundle\Entity\Answer $answer
     */
    public function removeAnswer(\Success\SalesGeneratorBundle\Entity\Answer $answer)
    {
        $this->answers->removeElement($answer);
    }

    /**
     *
     * @return ArrayCollection
     */
    public function getAnswers()
    {
        return $this->answers;
    }

    public function __toString()
    {
        $firstQuestion = explode('||', $this->text)[0];

        // Limit specific question to specific amount of words
        if (strlen($firstQuestion) > self::PREVIEW_QUESTION_MAX_LENGTH) {
            $position = strpos($this->text, ' ', self::PREVIEW_QUESTION_MAX_LENGTH);
            $questionText = substr($firstQuestion, 0, $position) . '...';
        } else {
            $questionText = $firstQuestion;
        }
        return (string)$this->id . ' ' . $questionText;
    }
}


text:
import React from 'react';
import { expect } from 'chai';
import _ from 'lodash';

let sharedSteps = module.exports = function(){
  this.World = require('../support/world');

  this.Given(/^the app has loaded$/, function(callback) {
    // Allow any asynchronous behavior to happen before effectively testing things
    setTimeout(() => {
      callback()
    }, 0)
  });

  this.Given(/^I am on the home page$/, function() {
    this.visit('/');
  });

  this.Given(/^I wait for ([^"]*)s$/, function(seconds, callback) {
    setTimeout(() => {
      callback()
    }, seconds * 1000);
  });

  this.Then(/^I should see "([^"]*)"$/, function(selector) {
    expect(this.wrapper.find(selector).length > 0).to.be.true;
  });

  this.Then(/^I should see a "([^"]*)" containing "([^"]*)"$/, function(selector, text) {
    const bool = this.wrapper.find(selector).someWhere((node) => {
      return _.lowerCase(node.text().trim()) === _.lowerCase(text.trim());
    });
    expect(bool).to.be.true;
  });
  this.Then(/^I should see a "([^"]*)" containing exactly "([^"]*)"$/, function(selector, text) {
    const bool = this.wrapper.find(selector).someWhere((node) => { return node.text() === text; });
    expect(bool).to.be.true;
  });
}


text:
import { connect } from 'react-redux';
import { setBook } from '../../store/ducks/book';
import {
  setActiveChapter,
  setAssetsLocation,
  incrementRenderIndex,
  setReaderContainerEl,
} from '../../store/ducks/application';
import { setChapters } from '../../store/ducks/chapters';
import { setLines } from '../../store/ducks/lines';
import { setBlocks } from '../../store/ducks/blocks';
import getBook from '../../services/book-service';
import isSmallScreen from '../../utils/isSmallScreen';
import Reader from './Reader';

function mapStateToProps(state) {
  const { audioPlayer, application, book } = state;
  return {
    book,
    audioOn: application.audioOn,
    darkmode: application.darkmode,
    player: audioPlayer.element,
    timestamp: audioPlayer.timestamp,
    renderIndex: application.renderIndex,
  };
}

// First increment the renderIndex by one, which allows us to render more blocks
function updateRenderIndexAndRender() {
  return (dispatch, getState) => {
    const { book, application } = getState();
    if (application.renderIndex >= book.chapters.length - 1) return;
    dispatch(incrementRenderIndex());
  };
}

// Uses book-service to retrieve the book data from the server,
// normalize it, and then dispatch the data-setting actions
function getBookAsync(bookId) {
  return (dispatch) => {
    getBook(bookId)
      .then((response) => {
        dispatch(setBook(response.book[bookId]));
        dispatch(setChapters(response.chapters));
        dispatch(setBlocks(response.blocks));
        dispatch(setLines(response.lines));
      });
  };
}

function dispatchSetActiveChapter(scrollPos) {
  return (dispatch, getState) => {
    const state = getState();
    const { book: { chapters: chapterOrder }, chapters } = state;
    const next = [...chapterOrder].reverse().find(chapterId => (
      scrollPos >= chapters[chapterId]?.el?.offsetTop - (isSmallScreen() ? 75 : 30)
    ));
    dispatch(setActiveChapter(next));
  };
}

function mapDispatchToProps(dispatch) {
  return {
    mountBookAndAssets(bookId) {
      dispatch(getBookAsync(bookId));
      dispatch(setAssetsLocation(`data/${bookId}/assets`));
    },
    setActiveChapter(scrollPos) {
      dispatch(dispatchSetActiveChapter(scrollPos));
    },
    renderMore() {
      dispatch(updateRenderIndexAndRender());
    },
    refReaderContainer(el) {
      dispatch(setReaderContainerEl(el));
    },
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(Reader);


text:
#ifndef ORM_CACHE_HPP
#define ORM_CACHE_HPP

#include <ORM/backends/Query.hpp>
#include <string>
#include <memory>

//#include <mutex>

#ifdef ORM_USE_CACHE
    #include <unordered_map>
#endif

namespace orm
{
    template<typename T> class SqlObject;
    template<typename T> class FKBase;

    /**
     * \brief Class to store object tha have already be query
     * \todo colector that clear unused obj of the Cache every ... minutes
     **/
    template<typename T>
    class Cache
    {
        public:
            typedef std::shared_ptr<T> type_ptr; ///< Type of the stored object
            /***
             * \brief Construct a Cache for T
             *
             * Note: T have to be a SqlObject
             **/
            explicit Cache();

            /**
             * \brief Destructor
             **/
            ~Cache();

            //Cache(const Cache<T>&)=delete;
            //Cache<T>& operator=(const Cache<T>&)=delete;

            /**
             * \brief make query to get object if not in cache
             *
             * \param pk PK of the object
             * \param max_depth Maximum depth of construction
             *
             * \return a shared_ptr to tho object stored in cache
             **/
            type_ptr getOrCreate(const unsigned int& pk,DB& bd,int max_depth);

            /**
             * \brief construct object from query if pk not in cache
             *
             * \param pk PK of the object
             * \param query Query to use for construction
             * \param index colum in the query to start
             * \param max_depth Maximum depth of construction
             *
             * \return a shared_ptr to tho object stored in cache
             **/
            type_ptr getOrCreate(const unsigned int& pk,const Query& query,int& prefix,int max_depth);

            /**
             * \brief construct object from query if not in cache after extracting pk from query
             *
             * \param query Query to use for construction
             * \param max_depth Maximum depth of construction
             *
             * \return a shared_ptr to tho object stored in cache
             **/
            type_ptr getOrCreate(const Query& query,int max_depth);

            /**
             * \brief Print the cache content
             **/
            void __print__();

            /**
             * \brief clear the entire cash
             * Delete all the objects from the cache
             * All future references for the same PK of
             * object will be errored
             * \param reset_pk if true, all the pk are set to default (-1)
             */
            void clear(bool reset_pk=true);

        private:
            friend class SqlObject<T>;
            friend class FKBase<T>;

            //std::recursive_mutex _mutex;
            /*
             * \brief stuct that hold an object
             * and the date that hit was added to the cache.
             */
            /*class time_obj {
                std::time_t added;
                type_ptr obj;
            };*/

            /**
             * \brief Add a object in the cache
             *
             * \param obj Object to add
             *
             * \return the shared_ptr of the stored object
             **/
            type_ptr& add(type_ptr& obj);

            /**
             * \brief Add a object in the cache
             *
             * \param obj Object to add
             *
             * \return the shared_ptr of the stored object
             **/
            //type_ptr& add(T& obj);

#ifdef ORM_USE_CACHE
            std::unordered_map<int,type_ptr> map; ///< store all the objects
#endif

            /**
             * \brief delete object of specified pk
             **/
            void del(const unsigned int& pk);

    };
}
#include <ORM/core/Cache.tpl>
#endif


text:
namespace Zone.UmbracoPersonalisationGroups.V8.Criteria.NumberOfVisits
{
    using System;
    using System.Web;
    using Umbraco.Core.Composing;
    using Umbraco.Web;
    using Zone.UmbracoPersonalisationGroups.Common.Criteria.NumberOfVisits;
    using Zone.UmbracoPersonalisationGroups.Common.Helpers;

    /// <summary>
    /// Registered required Umbraco application events for the number of visits criteria - to track via a cookie
    /// the number of times the visitor has accessed the site
    /// </summary>
    public class NumberOfVisitsComponent : IComponent
    {
        public void Initialize()
        {
            if (CriteriaConfigHelpers.IsCriteriaInUse(NumberOfVisitsPersonalisationGroupCriteria.CriteriaAlias))
            {
                UmbracoApplicationBase.ApplicationInit += ApplicationInit;
            }
        }

        private static void ApplicationInit(object sender, EventArgs e)
        {
            var app = (HttpApplication)sender;
            app.PostRequestHandlerExecute += UserActivityTracker.TrackSession;
        }

        public void Terminate()
        {
        }
    }
}


text:
<!DOCTYPE html>

        {% block head %}
        <title>{% block title %}{{ SITENAME }}{% endblock title %}</title>
        <meta charset="utf-8" />
        {% if FEED_ALL_ATOM %}
        <link href="{{ FEED_DOMAIN }}/{{ FEED_ALL_ATOM }}" type="application/atom+xml" rel="alternate" title="{{ SITENAME }} Full Atom Feed" />
        {% endif %}
        {% if FEED_ALL_RSS %}
        <link href="{{ FEED_DOMAIN }}/{{ FEED_ALL_RSS }}" type="application/rss+xml" rel="alternate" title="{{ SITENAME }} Full RSS Feed" />
        {% endif %}
        {% if FEED_ATOM %}
        <link href="{{ FEED_DOMAIN }}/{{ FEED_ATOM }}" type="application/atom+xml" rel="alternate" title="{{ SITENAME }} Atom Feed" />
        {% endif %}
        {% if FEED_RSS %}
        <link href="{{ FEED_DOMAIN }}/{{ FEED_RSS }}" type="application/rss+xml" rel="alternate" title="{{ SITENAME }} RSS Feed" />
        {% endif %}
        {% if CATEGORY_FEED_ATOM and category %}
        <link href="{{ FEED_DOMAIN }}/{{ CATEGORY_FEED_ATOM|format(category.slug) }}" type="application/atom+xml" rel="alternate" title="{{ SITENAME }} Categories Atom Feed" />
        {% endif %}
        {% if CATEGORY_FEED_RSS and category %}
        <link href="{{ FEED_DOMAIN }}/{{ CATEGORY_FEED_RSS|format(category.slug) }}" type="application/rss+xml" rel="alternate" title="{{ SITENAME }} Categories RSS Feed" />
        {% endif %}
        {% if TAG_FEED_ATOM and tag %}
        <link href="{{ FEED_DOMAIN }}/{{ TAG_FEED_ATOM|format(tag.slug) }}" type="application/atom+xml" rel="alternate" title="{{ SITENAME }} Tags Atom Feed" />
        {% endif %}
        {% if TAG_FEED_RSS and tag %}
        <link href="{{ FEED_DOMAIN }}/{{ TAG_FEED_RSS|format(tag.slug) }}" type="application/rss+xml" rel="alternate" title="{{ SITENAME }} Tags RSS Feed" />
        {% endif %}
        <link rel="stylesheet" type="text/css" href="{{ SITEURL}}/theme/css/style.css" />
        <link href='https://fonts.googleapis.com/css?family=Lato:300,700' rel='stylesheet' type='text/css'>
        <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,400italic' rel='stylesheet' type='text/css'>
        {% endblock head %}

{{ SITENAME }} {{ SITESUBTITLE }}

        {% for title, link in MENUITEMS %}

{{ title }}

        {% endfor %}
        {% if DISPLAY_PAGES_ON_MENU %}
          {% for p in PAGES %}

{{ p.title }}

          {% endfor %}
        {% else %}
          {% if DISPLAY_CATEGORIES_ON_MENU %}
            {% for cat, null in categories %}

{{ cat }}

            {% endfor %}
          {% endif %}
        {% endif %}

        {% block content %}
        {% endblock %}

                <address id="about" class="vcard body">
                Powered by Pelican.
                </address>


text:
<?php

namespace Strider2038\ImgCache\Tests\Acceptance;

use Strider2038\ImgCache\Enum\HttpStatusCodeEnum;
use Strider2038\ImgCache\Tests\Support\AcceptanceTestCase;

/**
 * @author Igor Lazarev <strider2038@rambler.ru>
 */
class FilesystemSourceApplicationTest extends AcceptanceTestCase
{
    private const URL_NOT_EXIST = '/i/not-exist.jpg';
    private const URL_INCORRECT_EXTENSION = '/index.php';
    private const URL_IMAGE_JPEG = '/sub/dir/image.jpg';
    private const URL_IMAGE_JPEG_THUMBNAIL = '/sub/dir/image_s150x150_q60.jpg';

    /** @test */
    public function GET_givenUrlWithIncorrectExtension_404NotFound(): void
    {
        $response = $this->sendGET(self::URL_INCORRECT_EXTENSION);

        $this->assertEquals(HttpStatusCodeEnum::NOT_FOUND, $response->getStatusCode());
    }

    /** @test */
    public function GET_imageDoesNotExist_404NotFound(): void
    {
        $response = $this->sendGET(self::URL_NOT_EXIST);

        $this->assertEquals(HttpStatusCodeEnum::NOT_FOUND, $response->getStatusCode());
    }

    /** @test */
    public function POST_invalidImageBody_400BadRequest(): void
    {
        $this->givenAccessToken(self::ACCESS_CONTROL_TOKEN);

        $response = $this->sendPOST(self::URL_IMAGE_JPEG);

        $this->assertEquals(HttpStatusCodeEnum::BAD_REQUEST, $response->getStatusCode());
    }

    /** @test */
    public function POST_imageNotExistInStorage_201Created(): void
    {
        $this->givenAccessToken(self::ACCESS_CONTROL_TOKEN);
        $imageBody = $this->givenImageJpegContents();

        $response = $this->sendPOST(self::URL_IMAGE_JPEG, $imageBody);

        $this->assertEquals(HttpStatusCodeEnum::CREATED, $response->getStatusCode());
    }

    /** @test */
    public function POST_imageExistInStorage_209Conflict(): void
    {
        $this->givenAccessToken(self::ACCESS_CONTROL_TOKEN);
        $imageBody = $this->givenImageJpegContents();
        $this->sendPOST(self::URL_IMAGE_JPEG, $imageBody);

        $response = $this->sendPOST(self::URL_IMAGE_JPEG, $imageBody);

        $this->assertEquals(HttpStatusCodeEnum::CONFLICT, $response->getStatusCode());
    }

    /** @test */
    public function GET_imageExistInStorageAndNotExistInCache_201Created(): void
    {
        $this->givenAccessToken(self::ACCESS_CONTROL_TOKEN);
        $imageBody = $this->givenImageJpegContents();
        $this->sendPOST(self::URL_IMAGE_JPEG, $imageBody);

        $response = $this->sendGET(self::URL_IMAGE_JPEG);

        $this->assertEquals(HttpStatusCodeEnum::CREATED, $response->getStatusCode());
    }

    /** @test */
    public function GET_imageExistInStorageAndExistInCache_200Created(): void
    {
        $this->givenAccessToken(self::ACCESS_CONTROL_TOKEN);
        $imageBody = $this->givenImageJpegContents();
        $this->sendPOST(self::URL_IMAGE_JPEG, $imageBody);
        $this->sendGET(self::URL_IMAGE_JPEG);

        $response = $this->sendGET(self::URL_IMAGE_JPEG);

        $this->assertEquals(HttpStatusCodeEnum::OK, $response->getStatusCode());
    }

    /** @test */
    public function PUT_imageNotExistInStorage_201Created(): void
    {
        $this->givenAccessToken(self::ACCESS_CONTROL_TOKEN);
        $imageBody = $this->givenImageJpegContents();

        $response = $this->sendPUT(self::URL_IMAGE_JPEG, $imageBody);

        $this->assertEquals(HttpStatusCodeEnum::CREATED, $response->getStatusCode());
    }

    /** @test */
    public function PUT_imageExistInStorage_201Created(): void
    {
        $this->givenAccessToken(self::ACCESS_CONTROL_TOKEN);
        $imageBody = $this->givenImageJpegContents();
        $this->sendPOST(self::URL_IMAGE_JPEG, $imageBody);

        $response = $this->sendPUT(self::URL_IMAGE_JPEG, $imageBody);

        $this->assertEquals(HttpStatusCodeEnum::CREATED, $response->getStatusCode());
    }

    /** @test */
    public function DELETE_imageNotExistInStorage_404NotFound(): void
    {
        $this->givenAccessToken(self::ACCESS_CONTROL_TOKEN);

        $response = $this->sendDELETE(self::URL_IMAGE_JPEG);

        $this->assertEquals(HttpStatusCodeEnum::NOT_FOUND, $response->getStatusCode());
    }

    /** @test */
    public function DELETE_imageExistInStorage_200Ok(): void
    {
        $this->givenAccessToken(self::ACCESS_CONTROL_TOKEN);
        $imageBody = $this->givenImageJpegContents();
        $this->sendPOST(self::URL_IMAGE_JPEG, $imageBody);

        $response = $this->sendDELETE(self::URL_IMAGE_JPEG);

        $this->assertEquals(HttpStatusCodeEnum::OK, $response->getStatusCode());
    }

    /** @test */
    public function GET_givenThumbnailNameAndImageExistInStorage_201Created(): void
    {
        $this->givenAccessToken(self::ACCESS_CONTROL_TOKEN);
        $imageBody = $this->givenImageJpegContents();
        $this->sendPOST(self::URL_IMAGE_JPEG, $imageBody);

        $response = $this->sendGET(self::URL_IMAGE_JPEG_THUMBNAIL);

        $this->assertEquals(HttpStatusCodeEnum::CREATED, $response->getStatusCode());
    }

    /** @test */
    public function DELETE_imageExistInStorageAndInCacheWithThumbnail_200OkAndThumbnailNotAccessible(): void
    {
        $this->givenAccessToken(self::ACCESS_CONTROL_TOKEN);
        $imageBody = $this->givenImageJpegContents();
        $this->sendPOST(self::URL_IMAGE_JPEG, $imageBody);
        $this->sendGET(self::URL_IMAGE_JPEG);
        $this->sendGET(self::URL_IMAGE_JPEG_THUMBNAIL);

        $response = $this->sendDELETE(self::URL_IMAGE_JPEG);

        $this->assertEquals(HttpStatusCodeEnum::OK, $response->getStatusCode());
        $this->assertGETUri404(self::URL_IMAGE_JPEG);
        $this->assertGETUri404(self::URL_IMAGE_JPEG_THUMBNAIL);
    }

    private function assertGETUri404(string $uri): void
    {
        $response = $this->sendGET($uri);
        $this->assertEquals(HttpStatusCodeEnum::NOT_FOUND, $response->getStatusCode());
    }
}


text:
package com.aquarians.aqlib.serialization;

import java.util.Map;
import java.util.TreeMap;

/**
 * Default implementation of ObjectFactory.
 */
public class DefaultObjectFactory implements ObjectFactory {

    private final Map<String, AqSerializable> prototypes = new TreeMap<String, AqSerializable>();

    @Override
    public void registerPrototype(String type, AqSerializable prototype) {
        prototypes.put(type, prototype);
    }

    @Override
    public AqSerializable createObject(String type) {
        AqSerializable prototype = prototypes.get(type);
        if (null == prototype) {
            return null;
        }

        return prototype.createInstance();
    }

}


text:
<?php

namespace App\Common\Models\Lexiangla\Mysql\Contact;

use App\Common\Models\Base\Mysql\Base;

class TagParty extends Base
{

    /**
     * 乐享-通讯录管理-部门标签管理
     * This model is mapped to the table ilexiangla_tag_party
     */
    public function getSource()
    {
        return 'ilexiangla_tag_party';
    }

    public function reorganize(array $data)
    {
        $data = parent::reorganize($data);
        $data['get_time'] = $this->changeToValidDate($data['get_time']);
        $data['is_exist'] = $this->changeToBoolean($data['is_exist']);
        return $data;
    }
}