text:
<?php

namespace PFinal\Wechat\Message;

use PFinal\Wechat\Contract\SendMessage;
use PFinal\Wechat\Contract\ReplyMessage;

class Music implements ReplyMessage, SendMessage
{
    protected $type = 'music';
    protected $attributes;

    public function __construct($thumbMediaId, $title = '', $description = '', $musicUrl = '', $hqMusicUrl = '')
    {
        if (is_array($thumbMediaId)) {
            extract($thumbMediaId, EXTR_OVERWRITE);
        }

        $this->attributes = array(
            'Music' => array(
                'Title' => $title,
                'Description' => $description,
                'MusicUrl' => $musicUrl,
                'HQMusicUrl' => $hqMusicUrl,
                'ThumbMediaId' => $thumbMediaId,
            )
        );
    }

    /**
     * @return array
     */
    public function xmlData()
    {
        return $this->attributes;
    }

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

    /**
     * @return array
     */
    public function jsonData()
    {
        $music = array();

        //将key转为小写,微信json格式为全小写
        foreach ($this->attributes['Music'] as $k => $v) {
            $music[$k] = array_change_key_case($v, CASE_LOWER);
        }

        return array('music' => $music);
    }
}


text:
/**
 * UseCase incremental count is for Unique ID.
 */
let _UseCaseCount: number = 0;
/**
 * create new id
 */
export const generateNewId = (): string => {
    _UseCaseCount++;
    return `UseCase__${_UseCaseCount}`;
};

redpajama_set_name: RedPajamaGithub


text:
layout: byte
title: How to detect WebGL support
type: bytes
tag: [JavaScript, WebGL]
description: Detect if browser supports WebGL.
date: 2015-05-25T00:00:00-00:00
draft: false
---
Detect if browser supports WebGL.

```javascript
function webglDetect() {
  var canvas = document.createElement('canvas');
  var contextNames = ['webgl','experimental-webgl','moz-webgl','webkit-3d'];
  var context;

  if (navigator.userAgent.indexOf('MSIE') > -1) {
    try {
      context = WebGLHelper.CreateGLContext(canvas, 'canvas');
    } catch(e) {}
  } else {
    for (var i = 0; i < contextNames.length; i++) {
      try {
        context = canvas.getContext(contextNames[i]);
        if (context) {
          break;
        }
      } catch(e) {}
    }
  }

  return !!context;
}
```

Usage:

```javascript
if (webglDetect()) {
    // WebGL is supported
}
```

On github at [miguelmota/webgl-detect](https://github.com/miguelmota/webgl-detect).


text:
require File.expand_path('../../../spec_helper', __FILE__)

describe "String.allocate" do
  it "returns an instance of String" do
    str = String.allocate
    str.should be_an_instance_of(String)
  end

  it "returns a fully-formed String" do
    str = String.allocate
    str.size.should == 0
    str << "more"
    str.should == "more"
  end

  ruby_version_is "1.9" do
    it "returns a binary String" do
      String.new.encoding.should == Encoding::BINARY
    end
  end
end


text:
module ManageIQ::Providers::Azure::EventCatcherMixin
  def parse_event_type(event)
    event_name   = event["eventName"]["value"]
    event_action = event.fetch_path("authorization", "action")
    event_type   = parse_event_action(event_action) if event_action

    "#{event_type}#{event_name}"
  end

  def parse_event_action(event_action)
    # E.g. Microsoft.Compute/virtualMachines/deallocate/action

    _provider, object_class, event_type, _action = event_action.split("/")
    "#{object_class}_#{event_type}_"
  end

  def parse_vm_ref(event)
    # E.g. /subscriptions/123456789-a1234-12b4-1234-5cd67890312/resourceGroups/
    # rg_name/providers/Microsoft.Compute/virtualMachines/vm_name

    return nil if event["resourceId"].length < 9

    _empty_space,
    _subscriptions,
    subscription_id,
    _resource_groups,
    resource_group,
    _providers,
    provider,
    object_class,
    object_name = event["resourceId"].downcase.split("/")

    [subscription_id, resource_group, "#{provider}\/#{object_class}", object_name].join("\\")
  end
end


text:
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <sstream>
#include <string>
#include <vector>

#include "catalog/CatalogTypedefs.hpp"
#include "expressions/aggregation/AggregateFunction.hpp"
#include "expressions/aggregation/AggregateFunctionFactory.hpp"
#include "expressions/aggregation/AggregationHandle.hpp"
#include "expressions/aggregation/AggregationHandleMin.hpp"
#include "expressions/aggregation/AggregationID.hpp"
#include "storage/AggregationOperationState.hpp"
#include "storage/PackedPayloadHashTable.hpp"
#include "storage/StorageManager.hpp"
#include "storage/ValueAccessorMultiplexer.hpp"
#include "types/CharType.hpp"
#include "types/DatetimeIntervalType.hpp"
#include "types/DatetimeLit.hpp"
#include "types/DatetimeType.hpp"
#include "types/DoubleType.hpp"
#include "types/FloatType.hpp"
#include "types/IntType.hpp"
#include "types/IntervalLit.hpp"
#include "types/LongType.hpp"
#include "types/Type.hpp"
#include "types/TypeFactory.hpp"
#include "types/TypeID.hpp"
#include "types/TypedValue.hpp"
#include "types/VarCharType.hpp"
#include "types/YearMonthIntervalType.hpp"
#include "types/containers/ColumnVector.hpp"
#include "types/containers/ColumnVectorsValueAccessor.hpp"

#include "types/operations/comparisons/Comparison.hpp"
#include "types/operations/comparisons/ComparisonFactory.hpp"
#include "types/operations/comparisons/ComparisonID.hpp"

#include "gtest/gtest.h"

namespace quickstep {

class AggregationHandleMinTest : public ::testing::Test {
 protected:
  static const int kNumSamples = 200;
  static const int kIterations = 5;

  // Helper method that calls AggregationHandleMin::iterateUnaryInl() to
  // aggregate 'value' into '*state'.
  void iterateHandle(AggregationState *state, const TypedValue &value) {
    static_cast<const AggregationHandleMin &>(*aggregation_handle_min_)
        .iterateUnaryInl(static_cast<AggregationStateMin *>(state), value);
  }

  void initializeHandle(const Type &type) {
    aggregation_handle_min_.reset(
        AggregateFunctionFactory::Get(AggregationID::kMin)
            .createHandle(std::vector<const Type *>(1, &type)));
    aggregation_handle_min_state_.reset(
        aggregation_handle_min_->createInitialState());
  }

  static bool ApplyToTypesTest(TypeID typeID) {
    const Type &type =
        (typeID == kChar || typeID == kVarChar)
            ? TypeFactory::GetType(typeID, static_cast<std::size_t>(10))
            : TypeFactory::GetType(typeID);

    return AggregateFunctionFactory::Get(AggregationID::kMin)
        .canApplyToTypes(std::vector<const Type *>(1, &type));
  }

  static bool ResultTypeForArgumentTypeTest(TypeID input_type_id,
                                            TypeID output_type_id) {
    const Type *result_type =
        AggregateFunctionFactory::Get(AggregationID::kMin)
            .resultTypeForArgumentTypes(std::vector<const Type *>(
                1, &TypeFactory::GetType(input_type_id)));
    return (result_type->getTypeID() == output_type_id);
  }

  template <typename CppType>
  static void CheckMinValue(CppType expected,
                            const AggregationHandle &handle,
                            const AggregationState &state) {
    EXPECT_EQ(expected, handle.finalize(state).getLiteral<CppType>());
  }

  template <typename CppType>
  static void CheckMinValue(CppType expected, const TypedValue &value) {
    EXPECT_EQ(expected, value.getLiteral<CppType>());
  }

  static void CheckMinString(const std::string &expected,
                             const AggregationHandle &handle,
                             const AggregationState &state) {
    TypedValue value = handle.finalize(state);

    ASSERT_EQ(expected.length(), value.getAsciiStringLength());
    EXPECT_EQ(0,
              std::strncmp(expected.c_str(),
                           static_cast<const char *>(value.getDataPtr()),
                           value.getAsciiStringLength()));
  }

  // Static templated method to initialize data types.
  template <typename CppType>
  void SetDataType(int value, CppType *data) {
    *data = value;
  }

  template <typename GenericType>
  void checkAggregationMinGeneric() {
    const GenericType &type = GenericType::Instance(true);
    initializeHandle(type);
    EXPECT_TRUE(
        aggregation_handle_min_->finalize(*aggregation_handle_min_state_)
            .isNull());

    typename GenericType::cpptype val;
    typename GenericType::cpptype min;
    SetDataType(1000, &min);

    iterateHandle(aggregation_handle_min_state_.get(), type.makeNullValue());
    for (int i = 0; i < kIterations; ++i) {
      for (int j = kNumSamples - 1; j >= 0; --j) {
        if (type.getTypeID() == kInt || type.getTypeID() == kLong) {
          SetDataType(i * kNumSamples + j - 10, &val);
        } else {
          SetDataType(static_cast<float>(i * kNumSamples + j - 10) / 10, &val);
        }
        iterateHandle(aggregation_handle_min_state_.get(),
                      type.makeValue(&val));
        if (min > val) {
          min = val;
        }
      }
    }
    iterateHandle(aggregation_handle_min_state_.get(), type.makeNullValue());
    CheckMinValue<typename GenericType::cpptype>(
        min, *aggregation_handle_min_, *aggregation_handle_min_state_);

    // Test mergeStates().
    std::unique_ptr<AggregationState> merge_state(
        aggregation_handle_min_->createInitialState());
    aggregation_handle_min_->mergeStates(*merge_state,
                                         aggregation_handle_min_state_.get());

    iterateHandle(merge_state.get(), type.makeNullValue());
    for (int i = 0; i < kIterations; ++i) {
      for (int j = kNumSamples - 1; j >= 0; --j) {
        if (type.getTypeID() == kInt || type.getTypeID() == kLong) {
          SetDataType(i * kNumSamples + j - 20, &val);
        } else {
          SetDataType(static_cast<float>(i * kNumSamples + j - 20) / 10, &val);
        }
        iterateHandle(merge_state.get(), type.makeValue(&val));
        if (min > val) {
          min = val;
        }
      }
    }
    aggregation_handle_min_->mergeStates(*merge_state,
                                         aggregation_handle_min_state_.get());
    CheckMinValue<typename GenericType::cpptype>(
        min, *aggregation_handle_min_, *aggregation_handle_min_state_);
  }

  template <typename GenericType>
  ColumnVector* createColumnVectorGeneric(const Type &type,
                                          typename GenericType::cpptype *min) {
    NativeColumnVector *column =
        new NativeColumnVector(type, kIterations * kNumSamples + 3);

    typename GenericType::cpptype val;
    SetDataType(1000, min);

    column->appendTypedValue(type.makeNullValue());
    for (int i = 0; i < kIterations; ++i) {
      for (int j = kNumSamples - 1; j >= 0; --j) {
        if (type.getTypeID() == kInt || type.getTypeID() == kLong) {
          SetDataType(i * kNumSamples + j - 10, &val);
        } else {
          SetDataType(static_cast<float>(i * kNumSamples + j - 10) / 10, &val);
        }
        column->appendTypedValue(type.makeValue(&val));
        if (*min > val) {
          *min = val;
        }
      }
      // One NULL in the middle.
      if (i == kIterations / 2) {
        column->appendTypedValue(type.makeNullValue());
      }
    }
    column->appendTypedValue(type.makeNullValue());

    return column;
  }

  template <typename GenericType>
  void checkAggregationMinGenericValueAccessor() {
    const GenericType &type = GenericType::Instance(true);
    initializeHandle(type);
    EXPECT_TRUE(
        aggregation_handle_min_->finalize(*aggregation_handle_min_state_)
            .isNull());

    std::unique_ptr<ColumnVectorsValueAccessor> accessor(
        new ColumnVectorsValueAccessor());

    typename GenericType::cpptype min;
    accessor->addColumn(createColumnVectorGeneric<GenericType>(type, &min));

    std::unique_ptr<AggregationState> va_state(
        aggregation_handle_min_->accumulateValueAccessor(
            {MultiSourceAttributeId(ValueAccessorSource::kBase, 0)},
            ValueAccessorMultiplexer(accessor.get())));

    // Test the state generated directly by accumulateValueAccessor(), and also
    // test after merging back.
    CheckMinValue<typename GenericType::cpptype>(
        min, *aggregation_handle_min_, *va_state);

    aggregation_handle_min_->mergeStates(*va_state,
                                         aggregation_handle_min_state_.get());
    CheckMinValue<typename GenericType::cpptype>(
        min, *aggregation_handle_min_, *aggregation_handle_min_state_);
  }

  template <typename StringType>
  void checkAggregationMinString() {
    const StringType &type = StringType::Instance(10, true);
    initializeHandle(type);
    EXPECT_TRUE(
        aggregation_handle_min_->finalize(*aggregation_handle_min_state_)
            .isNull());

    std::unique_ptr<UncheckedComparator> fast_comparator_;
    fast_comparator_.reset(ComparisonFactory::GetComparison(ComparisonID::kLess)
                               .makeUncheckedComparatorForTypes(type, type));
    std::string string_literal;
    std::string min = "z";
    int val;
    iterateHandle(aggregation_handle_min_state_.get(), type.makeNullValue());
    for (int i = 0; i < kIterations; ++i) {
      for (int j = kNumSamples - 1; j >= 0; --j) {
        val = i * kNumSamples + j;
        std::ostringstream oss;
        oss << "test" << val;
        string_literal = oss.str();

        iterateHandle(
            aggregation_handle_min_state_.get(),
            type.makeValue(string_literal.c_str(), string_literal.length() + 1)
                .ensureNotReference());
        if (fast_comparator_->compareDataPtrs(string_literal.c_str(),
                                              min.c_str())) {
          min = string_literal;
        }
      }
    }
    iterateHandle(aggregation_handle_min_state_.get(), type.makeNullValue());
    CheckMinString(
        min, *aggregation_handle_min_, *aggregation_handle_min_state_);

    // Test mergeStates().
    std::unique_ptr<AggregationState> merge_state(
        aggregation_handle_min_->createInitialState());
    aggregation_handle_min_->mergeStates(*merge_state,
                                         aggregation_handle_min_state_.get());

    iterateHandle(merge_state.get(), type.makeNullValue());
    for (int i = 0; i < kIterations; ++i) {
      for (int j = kNumSamples - 1; j >= 0; --j) {
        val = i * kNumSamples + j;
        std::ostringstream oss;
        oss << "min" << val;
        string_literal = oss.str();

        iterateHandle(
            merge_state.get(),
            type.makeValue(string_literal.c_str(), string_literal.length() + 1)
                .ensureNotReference());
        if (fast_comparator_->compareDataPtrs(string_literal.c_str(),
                                              min.c_str())) {
          min = string_literal;
        }
      }
    }
    aggregation_handle_min_->mergeStates(*merge_state,
                                         aggregation_handle_min_state_.get());
    CheckMinString(
        min, *aggregation_handle_min_, *aggregation_handle_min_state_);
  }

  template <typename ColumnVectorType>
  ColumnVector* createColumnVectorString(const Type &type, std::string *min) {
    ColumnVectorType *column =
        new ColumnVectorType(type, kIterations * kNumSamples + 3);
    std::unique_ptr<UncheckedComparator> fast_comparator_;
    fast_comparator_.reset(ComparisonFactory::GetComparison(ComparisonID::kLess)
                               .makeUncheckedComparatorForTypes(type, type));
    std::string string_literal;
    *min = "z";
    int val;
    column->appendTypedValue(type.makeNullValue());
    for (int i = 0; i < kIterations; ++i) {
      for (int j = kNumSamples - 1; j >= 0; --j) {
        val = i * kNumSamples + j;
        std::ostringstream oss;
        oss << "test" << val;
        string_literal = oss.str();

        column->appendTypedValue(
            type.makeValue(string_literal.c_str(), string_literal.length() + 1)
                .ensureNotReference());
        if (fast_comparator_->compareDataPtrs(string_literal.c_str(),
                                              min->c_str())) {
          *min = string_literal;
        }
      }
      // One NULL in the middle.
      if (i == kIterations / 2) {
        column->appendTypedValue(type.makeNullValue());
      }
    }
    column->appendTypedValue(type.makeNullValue());

    return column;
  }

  template <typename StringType, typename ColumnVectorType>
  void checkAggregationMinStringValueAccessor() {
    const StringType &type = StringType::Instance(10, true);
    initializeHandle(type);
    EXPECT_TRUE(
        aggregation_handle_min_->finalize(*aggregation_handle_min_state_)
            .isNull());

    std::string min;
    std::unique_ptr<ColumnVectorsValueAccessor> accessor(
        new ColumnVectorsValueAccessor());
    accessor->addColumn(createColumnVectorString<ColumnVectorType>(type, &min));

    std::unique_ptr<AggregationState> va_state(
        aggregation_handle_min_->accumulateValueAccessor(
            {MultiSourceAttributeId(ValueAccessorSource::kBase, 0)},
            ValueAccessorMultiplexer(accessor.get())));

    // Test the state generated directly by accumulateValueAccessor(), and also
    // test after merging back.
    CheckMinString(min, *aggregation_handle_min_, *va_state);

    aggregation_handle_min_->mergeStates(*va_state,
                                         aggregation_handle_min_state_.get());
    CheckMinString(
        min, *aggregation_handle_min_, *aggregation_handle_min_state_);
  }

  std::unique_ptr<AggregationHandle> aggregation_handle_min_;
  std::unique_ptr<AggregationState> aggregation_handle_min_state_;
  std::unique_ptr<StorageManager> storage_manager_;
};

template <>
void AggregationHandleMinTest::CheckMinValue<float>(
    float val, const AggregationHandle &handle, const AggregationState &state) {
  EXPECT_FLOAT_EQ(val, handle.finalize(state).getLiteral<float>());
}

template <>
void AggregationHandleMinTest::CheckMinValue<double>(
    double val,
    const AggregationHandle &handle,
    const AggregationState &state) {
  EXPECT_DOUBLE_EQ(val, handle.finalize(state).getLiteral<double>());
}

template <>
void AggregationHandleMinTest::SetDataType<DatetimeLit>(int value,
                                                        DatetimeLit *data) {
  data->ticks = value;
}

template <>
void AggregationHandleMinTest::SetDataType<DatetimeIntervalLit>(
    int value, DatetimeIntervalLit *data) {
  data->interval_ticks = value;
}

template <>
void AggregationHandleMinTest::SetDataType<YearMonthIntervalLit>(
    int value, YearMonthIntervalLit *data) {
  data->months = value;
}

typedef AggregationHandleMinTest AggregationHandleMinDeathTest;

TEST_F(AggregationHandleMinTest, IntTypeTest) {
  checkAggregationMinGeneric<IntType>();
}

TEST_F(AggregationHandleMinTest, LongTypeTest) {
  checkAggregationMinGeneric<LongType>();
}

TEST_F(AggregationHandleMinTest, FloatTypeTest) {
  checkAggregationMinGeneric<FloatType>();
}

TEST_F(AggregationHandleMinTest, DoubleTypeTest) {
  checkAggregationMinGeneric<DoubleType>();
}

TEST_F(AggregationHandleMinTest, DatetimeType) {
  checkAggregationMinGeneric<DatetimeType>();
}

TEST_F(AggregationHandleMinTest, DatetimeIntervalType) {
  checkAggregationMinGeneric<DatetimeIntervalType>();
}

TEST_F(AggregationHandleMinTest, YearMonthIntervalType) {
  checkAggregationMinGeneric<YearMonthIntervalType>();
}

TEST_F(AggregationHandleMinTest, CharTypeTest) {
  checkAggregationMinString<CharType>();
}

TEST_F(AggregationHandleMinTest, VarCharTypeTest) {
  checkAggregationMinString<VarCharType>();
}

TEST_F(AggregationHandleMinTest, IntTypeValueAccessorTest) {
  checkAggregationMinGenericValueAccessor<IntType>();
}

TEST_F(AggregationHandleMinTest, LongTypeValueAccessorTest) {
  checkAggregationMinGenericValueAccessor<LongType>();
}

TEST_F(AggregationHandleMinTest, FloatTypeValueAccessorTest) {
  checkAggregationMinGenericValueAccessor<FloatType>();
}

TEST_F(AggregationHandleMinTest, DoubleTypeValueAccessorTest) {
  checkAggregationMinGenericValueAccessor<DoubleType>();
}

TEST_F(AggregationHandleMinTest, DatetimeTypeValueAccessorTest) {
  checkAggregationMinGenericValueAccessor<DatetimeType>();
}

TEST_F(AggregationHandleMinTest, DatetimeIntervalTypeValueAccessorTest) {
  checkAggregationMinGenericValueAccessor<DatetimeIntervalType>();
}

TEST_F(AggregationHandleMinTest, YearMonthIntervalTypeValueAccessorTest) {
  checkAggregationMinGenericValueAccessor<YearMonthIntervalType>();
}

TEST_F(AggregationHandleMinTest, CharTypeValueAccessorTest) {
  checkAggregationMinStringValueAccessor<CharType, NativeColumnVector>();
}

TEST_F(AggregationHandleMinTest, VarCharTypeValueAccessorTest) {
  checkAggregationMinStringValueAccessor<VarCharType, IndirectColumnVector>();
}

#ifdef QUICKSTEP_DEBUG
TEST_F(AggregationHandleMinDeathTest, WrongTypeTest) {
  const Type &int_non_null_type = IntType::Instance(false);
  const Type &long_type = LongType::Instance(true);
  const Type &double_type = DoubleType::Instance(true);
  const Type &float_type = FloatType::Instance(true);
  const Type &char_type = CharType::Instance(true, 10);
  const Type &varchar_type = VarCharType::Instance(true, 10);

  initializeHandle(IntType::Instance(true));
  int int_val = 0;
  std::int64_t long_val = 0;
  double double_val = 0;
  float float_val = 0;

  iterateHandle(aggregation_handle_min_state_.get(),
                int_non_null_type.makeValue(&int_val));

  EXPECT_DEATH(iterateHandle(aggregation_handle_min_state_.get(),
                             long_type.makeValue(&long_val)),
               "");
  EXPECT_DEATH(iterateHandle(aggregation_handle_min_state_.get(),
                             double_type.makeValue(&double_val)),
               "");
  EXPECT_DEATH(iterateHandle(aggregation_handle_min_state_.get(),
                             float_type.makeValue(&float_val)),
               "");
  EXPECT_DEATH(iterateHandle(aggregation_handle_min_state_.get(),
                             char_type.makeValue("asdf", 5)),
               "");
  EXPECT_DEATH(iterateHandle(aggregation_handle_min_state_.get(),
                             varchar_type.makeValue("asdf", 5)),
               "");

  // Test mergeStates() with incorrectly typed handles.
  std::unique_ptr<AggregationHandle> aggregation_handle_min_long(
      AggregateFunctionFactory::Get(AggregationID::kMin)
          .createHandle(std::vector<const Type *>(1, &long_type)));
  std::unique_ptr<AggregationState> aggregation_state_min_merge_long(
      aggregation_handle_min_long->createInitialState());
  static_cast<const AggregationHandleMin &>(*aggregation_handle_min_long)
      .iterateUnaryInl(static_cast<AggregationStateMin *>(
                           aggregation_state_min_merge_long.get()),
                       long_type.makeValue(&long_val));
  EXPECT_DEATH(
      aggregation_handle_min_->mergeStates(*aggregation_state_min_merge_long,
                                           aggregation_handle_min_state_.get()),
      "");

  std::unique_ptr<AggregationHandle> aggregation_handle_min_double(
      AggregateFunctionFactory::Get(AggregationID::kMin)
          .createHandle(std::vector<const Type *>(1, &double_type)));
  std::unique_ptr<AggregationState> aggregation_state_min_merge_double(
      aggregation_handle_min_double->createInitialState());
  static_cast<const AggregationHandleMin &>(*aggregation_handle_min_double)
      .iterateUnaryInl(static_cast<AggregationStateMin *>(
                           aggregation_state_min_merge_double.get()),
                       double_type.makeValue(&double_val));
  EXPECT_DEATH(
      aggregation_handle_min_->mergeStates(*aggregation_state_min_merge_double,
                                           aggregation_handle_min_state_.get()),
      "");

  std::unique_ptr<AggregationHandle> aggregation_handle_min_float(
      AggregateFunctionFactory::Get(AggregationID::kMin)
          .createHandle(std::vector<const Type *>(1, &float_type)));
  std::unique_ptr<AggregationState> aggregation_state_min_merge_float(
      aggregation_handle_min_float->createInitialState());
  static_cast<const AggregationHandleMin &>(*aggregation_handle_min_float)
      .iterateUnaryInl(static_cast<AggregationStateMin *>(
                           aggregation_state_min_merge_float.get()),
                       float_type.makeValue(&float_val));
  EXPECT_DEATH(
      aggregation_handle_min_->mergeStates(*aggregation_state_min_merge_float,
                                           aggregation_handle_min_state_.get()),
      "");
}
#endif

TEST_F(AggregationHandleMinTest, canApplyToTypeTest) {
  EXPECT_TRUE(ApplyToTypesTest(kInt));
  EXPECT_TRUE(ApplyToTypesTest(kLong));
  EXPECT_TRUE(ApplyToTypesTest(kFloat));
  EXPECT_TRUE(ApplyToTypesTest(kDouble));
  EXPECT_TRUE(ApplyToTypesTest(kChar));
  EXPECT_TRUE(ApplyToTypesTest(kVarChar));
}

TEST_F(AggregationHandleMinTest, ResultTypeForArgumentTypeTest) {
  EXPECT_TRUE(ResultTypeForArgumentTypeTest(kInt, kInt));
  EXPECT_TRUE(ResultTypeForArgumentTypeTest(kLong, kLong));
  EXPECT_TRUE(ResultTypeForArgumentTypeTest(kFloat, kFloat));
  EXPECT_TRUE(ResultTypeForArgumentTypeTest(kDouble, kDouble));
}

TEST_F(AggregationHandleMinTest, GroupByTableMergeTest) {
  const Type &int_non_null_type = IntType::Instance(false);
  initializeHandle(int_non_null_type);
  storage_manager_.reset(new StorageManager("./test_min_data"));
  std::unique_ptr<AggregationStateHashTableBase> source_hash_table(
      AggregationStateHashTableFactory::CreateResizable(
          HashTableImplType::kSeparateChaining,
          std::vector<const Type *>(1, &int_non_null_type),
          10,
          {aggregation_handle_min_.get()},
          storage_manager_.get()));
  std::unique_ptr<AggregationStateHashTableBase> destination_hash_table(
      AggregationStateHashTableFactory::CreateResizable(
          HashTableImplType::kSeparateChaining,
          std::vector<const Type *>(1, &int_non_null_type),
          10,
          {aggregation_handle_min_.get()},
          storage_manager_.get()));

  PackedPayloadHashTable *destination_hash_table_derived =
      static_cast<PackedPayloadHashTable *>(destination_hash_table.get());

  PackedPayloadHashTable *source_hash_table_derived =
      static_cast<PackedPayloadHashTable *>(source_hash_table.get());

  AggregationHandleMin *aggregation_handle_min_derived =
      static_cast<AggregationHandleMin *>(aggregation_handle_min_.get());
  // We create three keys: first is present in both the hash tables, second key
  // is present only in the source hash table while the third key is present
  // the destination hash table only.
  std::vector<TypedValue> common_key;
  common_key.emplace_back(0);
  std::vector<TypedValue> exclusive_source_key, exclusive_destination_key;
  exclusive_source_key.emplace_back(1);
  exclusive_destination_key.emplace_back(2);

  const int common_key_source_min = 3000;
  TypedValue common_key_source_min_val(common_key_source_min);

  const int common_key_destination_min = 4000;
  TypedValue common_key_destination_min_val(common_key_destination_min);

  const int exclusive_key_source_min = 100;
  TypedValue exclusive_key_source_min_val(exclusive_key_source_min);

  const int exclusive_key_destination_min = 200;
  TypedValue exclusive_key_destination_min_val(exclusive_key_destination_min);

  std::unique_ptr<AggregationStateMin> common_key_source_state(
      static_cast<AggregationStateMin *>(
          aggregation_handle_min_->createInitialState()));
  std::unique_ptr<AggregationStateMin> common_key_destination_state(
      static_cast<AggregationStateMin *>(
          aggregation_handle_min_->createInitialState()));
  std::unique_ptr<AggregationStateMin> exclusive_key_source_state(
      static_cast<AggregationStateMin *>(
          aggregation_handle_min_->createInitialState()));
  std::unique_ptr<AggregationStateMin> exclusive_key_destination_state(
      static_cast<AggregationStateMin *>(
          aggregation_handle_min_->createInitialState()));

  // Create min value states for keys.
  aggregation_handle_min_derived->iterateUnaryInl(common_key_source_state.get(),
                                                  common_key_source_min_val);
  int actual_val = aggregation_handle_min_->finalize(*common_key_source_state)
                       .getLiteral<int>();
  EXPECT_EQ(common_key_source_min_val.getLiteral<int>(), actual_val);

  aggregation_handle_min_derived->iterateUnaryInl(
      common_key_destination_state.get(), common_key_destination_min_val);
  actual_val = aggregation_handle_min_->finalize(*common_key_destination_state)
                   .getLiteral<int>();
  EXPECT_EQ(common_key_destination_min_val.getLiteral<int>(), actual_val);

  aggregation_handle_min_derived->iterateUnaryInl(
      exclusive_key_destination_state.get(), exclusive_key_destination_min_val);
  actual_val =
      aggregation_handle_min_->finalize(*exclusive_key_destination_state)
          .getLiteral<int>();
  EXPECT_EQ(exclusive_key_destination_min_val.getLiteral<int>(), actual_val);

  aggregation_handle_min_derived->iterateUnaryInl(
      exclusive_key_source_state.get(), exclusive_key_source_min_val);
  actual_val = aggregation_handle_min_->finalize(*exclusive_key_source_state)
                   .getLiteral<int>();
  EXPECT_EQ(exclusive_key_source_min_val.getLiteral<int>(), actual_val);

  // Add the key-state pairs to the hash tables.
  unsigned char buffer[100];
  buffer[0] = '\0';
  memcpy(buffer + 1,
         common_key_source_state.get()->getPayloadAddress(),
         aggregation_handle_min_.get()->getPayloadSize());
  source_hash_table_derived->upsertCompositeKey(common_key, buffer);

  memcpy(buffer + 1,
         common_key_destination_state.get()->getPayloadAddress(),
         aggregation_handle_min_.get()->getPayloadSize());
  destination_hash_table_derived->upsertCompositeKey(common_key, buffer);

  memcpy(buffer + 1,
         exclusive_key_source_state.get()->getPayloadAddress(),
         aggregation_handle_min_.get()->getPayloadSize());
  source_hash_table_derived->upsertCompositeKey(exclusive_source_key, buffer);

  memcpy(buffer + 1,
         exclusive_key_destination_state.get()->getPayloadAddress(),
         aggregation_handle_min_.get()->getPayloadSize());
  destination_hash_table_derived->upsertCompositeKey(exclusive_destination_key,
                                                     buffer);

  EXPECT_EQ(2u, destination_hash_table_derived->numEntries());
  EXPECT_EQ(2u, source_hash_table_derived->numEntries());

  HashTableMerger merger(destination_hash_table_derived);
  source_hash_table_derived->forEachCompositeKey(&merger);

  EXPECT_EQ(3u, destination_hash_table_derived->numEntries());

  CheckMinValue<int>(
      common_key_source_min_val.getLiteral<int>(),
      aggregation_handle_min_derived->finalizeHashTableEntry(
          destination_hash_table_derived->getSingleCompositeKey(common_key) +
          1));
  CheckMinValue<int>(
      exclusive_key_destination_min_val.getLiteral<int>(),
      aggregation_handle_min_derived->finalizeHashTableEntry(
          destination_hash_table_derived->getSingleCompositeKey(
              exclusive_destination_key) + 1));
  CheckMinValue<int>(
      exclusive_key_source_min_val.getLiteral<int>(),
      aggregation_handle_min_derived->finalizeHashTableEntry(
          source_hash_table_derived->getSingleCompositeKey(
              exclusive_source_key) + 1));
}

}  // namespace quickstep


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace LawnMowerLib
{
    public class Solver
    {
        public string Solve(string input)
        {
            var parsed = ParseRawInputs(input);

            if (parsed == null)
            {
                return "Error Parsing Input: " + input;
            }

            var grid = parsed.Item1;
            var problemSets = parsed.Item2;

            var res = new List<string>();

            // Model collision on grid??

            foreach(var problem in problemSets)
            {
                var mower = problem.Mower;
                var instructions = problem.Instructions;
                mower.Go(grid, instructions);
                res.Add(string.Format("{0} {1} {2}", mower.X, mower.Y, mower.Bearing));
            }

            return string.Join("\n", res);
        }

        public static Tuple<Grid, IEnumerable<ProblemSet>> ParseRawInputs(string inputs)
        {
            var lines = inputs.Split(new[]{ '\n' });

            return ParseRawInputs(lines);
        }

        public static Tuple<Grid, IEnumerable<ProblemSet>> ParseRawInputs(IEnumerable<string> inputs)
        {
            var problemSets = new List<ProblemSet>();
            var e = inputs.AsEnumerable().GetEnumerator();

            // Grid
            e.MoveNext();
            var rawGrid = e.Current;
            Grid grid;
            if (!Grid.TryParse(rawGrid, out grid)){ return null; }

            // Problem Sets
            while(e.MoveNext())
            {
                var rawState = e.Current;
                LawnMower mower;
                if(!LawnMower.TryParseLawnMower(rawState, out mower))
                {
                    return null;
                }

                e.MoveNext();

                var rawInstructions = e.Current;
                Instructions instructions;
                if (!Instructions.TryParseInstructions(rawInstructions, out instructions))
                {
                    return null;
                }

                var problemSet = new ProblemSet(mower, instructions);
                problemSets.Add(problemSet);
            }

            return Tuple.Create<Grid,IEnumerable<ProblemSet>>(grid, problemSets);
        }
    }
}


text:
sudo yum install richfaces.noarch-3.3.1 -y
sudo yum install richfaces-demo.noarch-3.3.1 -y
sudo yum install richfaces-framework.noarch-3.3.1 -y
sudo yum install richfaces-root.noarch-3.3.1 -y
sudo yum install richfaces-ui.noarch-3.3.1 -y


text:
namespace Practica2.GUI
{
    partial class Estados
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.button1 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.SuspendLayout();
            //
            // dataGridView1
            //
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Location = new System.Drawing.Point(34, 72);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.Size = new System.Drawing.Size(468, 150);
            this.dataGridView1.TabIndex = 0;
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(34, 34);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // Estados
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(542, 261);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.dataGridView1);
            this.Name = "Estados";
            this.Text = "Estados";
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.DataGridView dataGridView1;
        private System.Windows.Forms.Button button1;
    }
}


text:
package org.drip.analytics.eventday;

/*
 * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 */

/*!
 * Copyright (C) 2017 Lakshmi Krishnamurthy
 * Copyright (C) 2016 Lakshmi Krishnamurthy
 * Copyright (C) 2015 Lakshmi Krishnamurthy
 * Copyright (C) 2014 Lakshmi Krishnamurthy
 * Copyright (C) 2013 Lakshmi Krishnamurthy
 * Copyright (C) 2012 Lakshmi Krishnamurthy
 * Copyright (C) 2011 Lakshmi Krishnamurthy
 *
 *  This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
 *  	libraries targeting analysts and developers
 *  	https://lakshmidrip.github.io/DRIP/
 *
 *  DRIP is composed of four main libraries:
 *
 *  - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
 *  - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
 *  - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
 *  - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
 *
 *  - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
 *  	Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
 *  	Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
 *  	Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
 *  	Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
 *
 *  - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
 *  	Incorporator, Holdings Constraint, and Transaction Costs.
 *
 *  - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
 *
 *  - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
 *
 *  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.
 */

/**
 * Weekend holds the left and the right weekend days. It provides functionality to retrieve them, check if
 *  the given day is a weekend, and serialize/de-serialize weekend days.
 *
 * @author Lakshmi Krishnamurthy
 */

public class Weekend {
	private int[] _aiDay = null;

	/**
	 * Create a Weekend Instance with SATURDAY and SUNDAY
	 *
	 * @return Weekend object
	 */

	public static final Weekend StandardWeekend()
	{
		try {
			return new Weekend (new int[] {org.drip.analytics.date.DateUtil.SUNDAY,
				org.drip.analytics.date.DateUtil.SATURDAY});
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * Create the weekend instance object from the array of the weekend days
	 *
	 * @param aiDay Array of the weekend days
	 *
	 * @throws java.lang.Exception Thrown if cannot properly de-serialize Weekend
	 */

	public Weekend (
		final int[] aiDay)
		throws java.lang.Exception
	{
		if (null == aiDay) throw new java.lang.Exception ("Weekend ctr: Invalid Inputs");

		int iNumWeekendDays = aiDay.length;;

		if (0 == iNumWeekendDays) throw new java.lang.Exception ("Weekend ctr: Invalid Inputs");

		_aiDay = new int[iNumWeekendDays];

		for (int i = 0; i < iNumWeekendDays; ++i)
			_aiDay[i] = aiDay[i];
	}

	/**
	 * Retrieve the weekend days
	 *
	 * @return Array of the weekend days
	 */

	public int[] days()
	{
		return _aiDay;
	}

	/**
	 * Is the given date a left weekend day
	 *
	 * @param iDate Date
	 *
	 * @return True (Left weekend day)
	 */

	public boolean isLeftWeekend (
		final int iDate)
	{
		if (null == _aiDay || 0 == _aiDay.length) return false;

		if (_aiDay[0] == (iDate % 7)) return true;

		return false;
	}

	/**
	 * Is the given date a right weekend day
	 *
	 * @param dblDate Date
	 *
	 * @return True (Right weekend day)
	 */

	public boolean isRightWeekend (
		final double dblDate)
	{
		if (null == _aiDay || 1 >= _aiDay.length) return false;

		if (_aiDay[1] == (dblDate % 7)) return true;

		return false;
	}

	/**
	 * Is the given date a weekend day
	 *
	 * @param iDate Date
	 *
	 * @return True (Weekend day)
	 */

	public boolean isWeekend (
		final int iDate)
	{
		return isLeftWeekend (iDate) || isRightWeekend (iDate);
	}
}


text:
namespace Microsoft.PackageManagement.PackageSourceListProvider
{
    using System;
    using System.Globalization;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Microsoft.PackageManagement.Internal.Implementation;
    using System.Text.RegularExpressions;
    using System.Xml.Linq;
    using System.Xml;
    using System.Collections.Concurrent;
    using System.Net.Http;
    using Internal.Utility.Plugin;
    using System.Management.Automation;
    using ErrorCategory = PackageManagement.Internal.ErrorCategory;
    using Microsoft.PackageManagement.Implementation;
    using Microsoft.PackageManagement.Internal.Api;
    using Microsoft.PackageManagement.Provider.Utility;
    using SemanticVersion = Microsoft.PackageManagement.Provider.Utility.SemanticVersion;

    public abstract class PackageSourceListRequest : Request {

        private IEnumerable<PackageQuery> _packageQuery;
        private static IDictionary<string, PackageSource> _registeredPackageSources;
        private string _configurationFileLocation;
        private XDocument _config;
        private string _defaultConfig;
        private string PowerShellSourceURL = @"https://go.microsoft.com/fwlink/?LinkID=821777&clcid=0x409";
        private string PowerShellNanoSourceURL = @"https://go.microsoft.com/fwlink/?LinkID=821783&clcid=0x409";
        private string PowerShellSourceCatalogURL = @"https://go.microsoft.com/fwlink/?LinkID=823093&clcid=0x409";
        private string PowerShellNanoSourceCatalogURL = @"https://go.microsoft.com/fwlink/?LinkID=823094&clcid=0x409";
        private IEnumerable<string> _packageSources;
        private const string _PackageSourceListRequest = "PackageSourceListRequest";
        private HttpClient _httpClient;
        //private HttpClient _httpClientWithoutAcceptHeader;

        private static IDictionary<string, PackageSource> _checkedUnregisteredPackageSources = new ConcurrentDictionary<string, PackageSource>();
        private static Dictionary<string, PackageProvider> _packageProviders = new Dictionary<string, PackageProvider>();

        private static readonly Regex RegexFastPath = new Regex(@"\$(?<id>[\w,\+,\/,=]*)\\(?<version>[\w,\+,\/,=]*)");
        internal static readonly Regex RegexFastPathComplex = new Regex(@"\$(?<location>[\w,\+,\/,=]*)#(?<id>[\w,\+,\/,=]*)#(?<displayname>[\w,\+,\/,=]*)#(?<version>[\w,\+,\/,=]*)#(?<fastpath>[\w,\+,\/,=]*)");

        internal Lazy<bool> SkipValidate;
        internal readonly Lazy<bool> AllVersions;
        internal readonly Lazy<string[]> Headers;
        internal Lazy<bool> SkipHashValidation;

        internal const WildcardOptions WildcardOptions = System.Management.Automation.WildcardOptions.CultureInvariant | System.Management.Automation.WildcardOptions.IgnoreCase;

        internal const string DefaultConfigDefinition = @"<?xml version=""1.0""?>
<configuration>
  <packageSources>
    <add key=""PSL"" value=""##"" />
  </packageSources>
</configuration>";

        internal const string EmptyConfig = @"<?xml version=""1.0""?>
<configuration>
  <packageSources>
  </packageSources>
</configuration>";

        /// <summary>
        /// Ctor required by the PackageManagement Platform
        /// </summary>
        protected PackageSourceListRequest()
        {
            AllVersions = new Lazy<bool>(() => GetOptionValue("AllVersions").IsTrue());
            SkipValidate = new Lazy<bool>(() => GetOptionValue("SkipValidate").IsTrue());
            Headers = new Lazy<string[]>(() => (GetOptionValues("Headers") ?? new string[0]).ToArray());
            SkipHashValidation = new Lazy<bool>(() => GetOptionValue("SkipHashValidation").IsTrue());
        }

        internal string DefaultJSONFileLocation
        {
            get
            {
                return Path.Combine(Environment.GetEnvironmentVariable("appdata"), Constants.ProviderName, Constants.JSONFileName);
            }
        }

        internal string DefaultCatalogFileLocation
        {
            get
            {
                return Path.Combine(Environment.GetEnvironmentVariable("appdata"), Constants.ProviderName, Constants.CatFileName);
            }
        }

        internal string DefaultJSONSourceLocation
        {
            get
            {
#if CORECLR
                    return PowerShellNanoSourceURL;
#else
                return PowerShellSourceURL;
#endif
            }
        }

        internal string DefaultJSONCatalogFileLocation
        {
            get
            {
#if CORECLR
                    return PowerShellNanoSourceCatalogURL;
#else
                return PowerShellSourceCatalogURL;
#endif
            }
        }

        internal string DefaultConfig
        {
            get
            {
                if (_defaultConfig == null)
                {
                    _defaultConfig = DefaultConfigDefinition.Replace("##", DefaultJSONFileLocation);
                }
                return _defaultConfig;
            }
        }

        internal IEnumerable<string> PackageSources
        {
            get
            {
                return _packageSources ?? (_packageSources = (Sources ?? new string[0]).ToArray());
            }
        }
        private IEnumerable<PackageQuery> Packages
        {
            get
            {
                if (_packageQuery == null)
                {
                    try
                    {
                        _packageQuery = SelectedSources.AsParallel().WithMergeOptions(ParallelMergeOptions.NotBuffered).SelectMany(source =>
                        (new PackageQuery(source, this)).SingleItemAsEnumerable()).Where(each=>each.IsValid);
                    }
                    catch (Exception ex)
                    {
                        ex.Dump(this);
                    }
                }
                return _packageQuery;
            }
        }

        internal virtual bool IsValid
        {
            get
            {
                return _packageQuery != null;
            }
        }

        internal IEqualityComparer<PackageJson> PackageEqualityComparer { get; private set; }

        /// <summary>
        /// Supported package source schemes by this provider
        /// </summary>
        internal static IEnumerable<string> SupportedSchemes
        {
            get
            {
                return PackageSourceListProvider.Features[Constants.Features.SupportedSchemes];
            }
        }
        private string GetValue(string name) {
            // get the value from the request
            return (GetOptionValues(name) ?? Enumerable.Empty<string>()).LastOrDefault();
        }

        internal PackageJson GetPackage(string name) {
            return Packages.SelectMany(each => each.Query(name)).OrderByDescending(p => p.Version).FirstOrDefault();
        }

        internal PackageJson GetPackage(string name, string requiredVersion)
        {
            if (string.IsNullOrWhiteSpace(requiredVersion))
            {
                return Packages.SelectMany(each => each.Query(name)).FirstOrDefault();
            }

            return Packages.SelectMany(each => each.Query(name, requiredVersion)).FirstOrDefault();
        }

        internal IEnumerable<PackageJson> GetPackagesWithinVersionRange(string name, string minimumversion, string maximumversion)
        {
            return Packages.SelectMany(each => each.Query(name, minimumversion, maximumversion))
                .OrderByDescending(p => p.Version);
        }

        internal IEnumerable<PackageJson> GetPackages(string name)
        {
            var wildcardPattern = new WildcardPattern(name, WildcardOptions);

            return Packages.SelectMany(each => each.Query()).Distinct(PackageEqualityComparer)
                 .Where(p => !string.IsNullOrWhiteSpace(p.Name) && (string.IsNullOrWhiteSpace(name) || (wildcardPattern.IsMatch(p.Name) || wildcardPattern.IsMatch(p.DisplayName))));
        }

        internal IEnumerable<PackageJson> GetPackages(string name, string requiredVersion, string minimumversion, string maximumversion)
        {
            if (!string.IsNullOrWhiteSpace(requiredVersion))
            {
                return Packages.SelectMany(each => each.Query(name, requiredVersion));
            }

            return Packages.SelectMany(each => each.Query(name, minimumversion, maximumversion))
                .OrderByDescending(p => p.Version);
        }

        internal static PackageProvider FindProvider(PackageSourceListRequest request, string providerType, IHostApi hostApi, bool logError = false) {

            string providerName = null;
            switch (providerType.ToLowerInvariant()) {
                case Constants.MediaType.MsiPackage:
                    providerName = Constants.ProviderNames.Msi;
                    break;
                case Constants.MediaType.MsuPackage:
                    providerName = Constants.ProviderNames.Msu;
                    break;
                case Constants.MediaType.AppxPackage:
                    //TODO for future whenever needed to support appx packages
                    break;
                case Constants.MediaType.NuGetPackage:
                    providerName = Constants.ProviderNames.NuGet;
                    break;
                case Constants.MediaType.ZipPackage:
                case Constants.MediaType.ExePackage:
                    providerName = Constants.ProviderNames.PSL;
                    break;
                case Constants.MediaType.PsArtifacts:
                    providerName = Constants.ProviderNames.PowerShellGet;
                    break;

                default:
                    request.Warning(Resources.Messages.UnsupportedProviderType, providerType);
                    break;
            }

            if (string.IsNullOrWhiteSpace(providerName)) {
                return null;
            }

            PackageProvider provider;
            if (_packageProviders.ContainsKey(providerName)) {
                provider = _packageProviders[providerName];
            } else {
                provider = request.PackageManagementService.SelectProviders(providerName, request).FirstOrDefault();
                if (provider != null) {
                    _packageProviders.AddOrSet(providerName, provider);
                }
            }

            if (provider != null) {
                return provider;
            }

            request.Verbose(Resources.Messages.ProviderNotFound, providerName);

            if (logError) {
                request.Error(ErrorCategory.InvalidOperation, providerName, Resources.Messages.ProviderNotFound, providerName);
            }
            return null;
        }

        internal static string CreateCanonicalId(PackageJson package, string providerName)
        {
            // example: "nuget:jquery/2.1.0#http://nuget.org/api/v2"
            if (package == null || string.IsNullOrEmpty(package.Name) || string.IsNullOrEmpty(providerName))
            {
                return null;
            }
            if (string.IsNullOrWhiteSpace(package.Version) && string.IsNullOrWhiteSpace(package.Source))
            {
                return "{0}:{1}".format(CultureInfo.CurrentCulture.TextInfo.ToLower(providerName), package.Name);
            }
            if (string.IsNullOrWhiteSpace(package.Source))
            {
                return "{0}:{1}/{2}".format(CultureInfo.CurrentCulture.TextInfo.ToLower(providerName), package.Name, package.Version);
            }

            Uri pkgId;
            var source = package.Source;
            if (Uri.TryCreate(package.Source, UriKind.Absolute, out pkgId))
            {
                source = pkgId.AbsoluteUri;
            }

            if (string.IsNullOrWhiteSpace(package.Version))
            {
                "{0}:{1}#{2}".format(CultureInfo.CurrentCulture.TextInfo.ToLower(providerName), package.Name, source);
            }

            return "{0}:{1}/{2}#{3}".format(CultureInfo.CurrentCulture.TextInfo.ToLower(providerName), package.Name, package.Version, source);
        }

        internal string MakeFastPath(PackageJson package)
        {
            return string.Format(CultureInfo.InvariantCulture, @"${0}\{1}", package.Name.ToBase64(), package.Version.ToBase64());
        }
        private bool TryParseFastPath(string fastPath, Regex regex, out string id, out string version)
        {
            var match = regex.Match(fastPath);
            id = match.Success ? match.Groups["id"].Value.FromBase64() : null;
            version = match.Success ? match.Groups["version"].Value.FromBase64() : null;
            return match.Success;
        }

        /// <summary>
        /// Get the PackageItem object from the fast path
        /// </summary>
        /// <param name="fastPath"></param>
        /// <returns></returns>
        internal PackageJson GetPackageByFastPath(string fastPath)
        {
            string id;
            string version;

            if (TryParseFastPath(fastPath, RegexFastPath, out id, out version))
            {
                return GetPackage(id, version);
            }

            return null;
        }

        internal static string MakeFastPathComplex(string source, string name, string displayName, string version, string fastPackageReference)
        {
            return string.Format(CultureInfo.InvariantCulture, @"${0}#{1}#{2}#{3}#{4}", (source ?? "").ToBase64(), (name ?? "").ToBase64(), (displayName ?? "").ToBase64(), (version ?? "").ToBase64(), (fastPackageReference ?? "").ToBase64());
        }

        internal bool TryParseFastPathComplex(string fastPath, Regex regex, out string location, out string id, out string displayname, out string version, out string fastpath)
        {
            var match = regex.Match(fastPath);
            location = match.Success ? match.Groups["location"].Value.FromBase64() : null;
            id = match.Success ? match.Groups["id"].Value.FromBase64() : null;
            displayname = match.Success ? match.Groups["displayname"].Value.FromBase64() : null;
            version = match.Success ? match.Groups["version"].Value.FromBase64() : null;
            fastpath = match.Success ? match.Groups["fastpath"].Value.FromBase64() : null;

            return match.Success;
        }

        internal PackageJson GetFastReferenceComplex(string fastPath)
        {
            string sourceLocation;
            string id;
            string displayname;
            string version;
            string fastreference;

            if (TryParseFastPathComplex(fastPath: fastPath, regex: RegexFastPathComplex, location: out sourceLocation, id: out id, displayname: out displayname, version: out version, fastpath: out fastreference))
            {
                var ver = (new SemanticVersion(version)).ToString();
                return GetPackage(id, ver) ?? GetPackage(displayname, ver);
            }

            return null;
        }

        internal IEnumerable<PackageJson> FilterOnVersion(IEnumerable<PackageJson> pkgs, string requiredVersion, string minimumVersion, string maximumVersion, bool minInclusive = true, bool maxInclusive = true, bool latest=true)
        {
            if (!string.IsNullOrWhiteSpace(requiredVersion))
            {
                pkgs = pkgs.Where(each => each.SemVer == new SemanticVersion(requiredVersion));
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(minimumVersion))
                {
                    // if minInclusive, then use >= else use >
                    if (minInclusive)
                    {
                        pkgs = pkgs.Where(each => each.SemVer >= new SemanticVersion(minimumVersion));
                    }
                    else
                    {
                        pkgs = pkgs.Where(each => each.SemVer > new SemanticVersion(minimumVersion));
                    }
                }

                if (!String.IsNullOrWhiteSpace(maximumVersion))
                {
                    // if maxInclusive, then use < else use <=
                    if (maxInclusive)
                    {
                        pkgs = pkgs.Where(each => each.SemVer <= new SemanticVersion(maximumVersion));
                    }
                    else
                    {
                        pkgs = pkgs.Where(each => each.SemVer < new SemanticVersion(maximumVersion));
                    }
                }
            }

            return latest ? pkgs.OrderByDescending(each => each.Version).FirstOrDefault().SingleItemAsEnumerable() : pkgs;
        }

        internal bool YieldFromSwidtag(PackageJson package, string searchKey)
        {
            if (package == null)
            {
                return !IsCanceled;
            }

            var targetFilename = package.FilePath;
            var summary = package.Summary;

            var fastPath = MakeFastPath(package);

            // As 'nodejs' become 'node.js' after the install, GetInstalledPackage() will return node.js. To skip installing node.js
            // if already installed, we need to return the node.js i.e., use display name for msi provider.
            if (package.Type.EqualsIgnoreCase(Constants.MediaType.MsiPackage))
            {
                if (!string.IsNullOrWhiteSpace(package.DisplayName))
                {
                    package.Name = package.DisplayName;
                }
            }

            if (YieldSoftwareIdentity(fastPath, package.Name, package.SemVer.ToString(), package.VersionScheme, summary, package.Source, searchKey, null, targetFilename) != null)
            {
                //this is a trusted source
                if (AddMetadata(fastPath, "FromTrustedSource", "true") == null)
                {
                    return !IsCanceled;
                }

                if (AddMetadata(fastPath, "Source", package.Source) == null)
                {
                    return !IsCanceled;
                }
                if (AddMetadata(fastPath, "Type", package.Type) == null)
                {
                    return !IsCanceled;
                }

                if (package.Dependencies != null)
                {
                    //iterate thru the dependencies and add them to the software identity.
                    foreach (var dependency in package.Dependencies)
                    {
                        // foreach (var pkg in dependency)
                        {
                            AddDependency("PSL", dependency.Name, dependency.Version, null, null);
                        }
                    }
                }
            }
            return !IsCanceled;
        }

        /// <summary>
        /// Unregister the package source
        /// </summary>
        /// <param name="id">package source id or name</param>
        internal void RemovePackageSource(string id)
        {
            Debug(Resources.Messages.DebugInfoCallMethod3, Constants.ProviderName, "RemovePackageSource", id);
            var config = Config;
            if (config == null)
            {
                return;
            }

            try
            {

                XElement configuration = config.ElementsNoNamespace("configuration").FirstOrDefault();
                if (configuration == null)
                {
                    return;
                }

                XElement packageSources = configuration.ElementsNoNamespace("packageSources").FirstOrDefault();
                if (packageSources == null)
                {
                    return;
                }

                var nodes = packageSources.Elements("add");
                if (nodes == null)
                {
                    return;
                }

                foreach (XElement node in nodes)
                {

                    if (node.Attribute("key") != null && String.Equals(node.Attribute("key").Value, id, StringComparison.OrdinalIgnoreCase))
                    {
                        // remove itself
                        node.Remove();
                        Config = config;
                        Verbose(Resources.Messages.RemovedPackageSource, id);
                        break;
                    }

                }

                if (_registeredPackageSources.ContainsKey(id))
                {
                    _registeredPackageSources.Remove(id);
                }

                if (_checkedUnregisteredPackageSources.ContainsKey(id))
                {
                    _checkedUnregisteredPackageSources.Remove(id);
                }

                //var source = config.SelectNodes("/configuration/packageSources/add").Cast<XmlNode>().FirstOrDefault(node => String.Equals(node.Attributes["key"].Value, id, StringComparison.CurrentCultureIgnoreCase));

                //if (source != null)
                //{
                //    source.ParentNode.RemoveChild(source);
                //    Config = config;
                //    Verbose(Resources.Messages.RemovedPackageSource, id);
                //}
            }
            catch (Exception ex)
            {
                ex.Dump(this);
            }
        }

        /// <summary>
        /// Register the package source
        /// </summary>
        /// <param name="name">package source name</param>
        /// <param name="location">package source location</param>
        /// <param name="isTrusted">is the source trusted</param>
        /// <param name="isValidated">need validate before storing the information to config file</param>
        internal void AddPackageSource(string name, string location, bool isTrusted, bool isValidated)
        {

            Debug(Resources.Messages.DebugInfoCallMethod, Constants.ProviderName, string.Format(CultureInfo.InvariantCulture, "AddPackageSource - name= {0}, location={1}", name, location));
            try
            {
                // here the source is already validated by the caller
                var config = Config;
                if (config == null)
                {
                    return;
                }

                XElement source = null;
                XElement packageSources = null;
                // Check whether there is an existing node with the same name
                var configuration = config.ElementsNoNamespace("configuration").FirstOrDefault();
                if (configuration != null)
                {
                    packageSources = configuration.ElementsNoNamespace("packageSources").FirstOrDefault();
                    if (packageSources != null)
                    {
                        source = packageSources.Elements("add").FirstOrDefault(node =>
                            node.Attribute("key") != null && String.Equals(node.Attribute("key").Value, name, StringComparison.OrdinalIgnoreCase));
                    }
                }
                else
                {
                    // create configuration node if it does not exist
                    configuration = new XElement("configuration");
                    // add that to the config
                    config.Add(configuration);
                }

                // There is no existing node with the same name. So we have to create one.
                if (source == null)
                {
                    // if packagesources is null we have to create that too
                    if (packageSources == null)
                    {
                        // create packagesources node
                        packageSources = new XElement("packageSources");
                        // add that to the config
                        configuration.Add(packageSources);
                    }

                    // Create new source
                    source = new XElement("add");
                    // Add that to packagesource
                    packageSources.Add(source);
                }

                // Now set the source node properties
                source.SetAttributeValue("key", name);
                source.SetAttributeValue("value", location);
                if (isValidated)
                {
                    source.SetAttributeValue("validated", true.ToString());
                }
                if (isTrusted)
                {
                    source.SetAttributeValue("trusted", true.ToString());
                }

                // Write back to the config file
                Config = config;

                // Add or set the source node from the dictionary depends on whether it was there
                if (_registeredPackageSources.ContainsKey(name))
                {
                    var packageSource = _registeredPackageSources[name];
                    packageSource.Name = name;
                    packageSource.Location = location;
                    packageSource.Trusted = isTrusted;
                    packageSource.IsRegistered = true;
                    packageSource.IsValidated = isValidated;
                }
                else
                {
                    _registeredPackageSources.Add(name, new PackageSource
                    {
                        Request = this,
                        Name = name,
                        Location = location,
                        Trusted = isTrusted,
                        IsRegistered = true,
                        IsValidated = isValidated,
                    });
                }

            }
            catch (Exception ex)
            {
                ex.Dump(this);
            }
        }

        /// <summary>
        /// Return the package source object
        /// </summary>
        /// <param name="name">The package source name to search for</param>
        /// <returns>package source object</returns>
        internal PackageSource FindRegisteredSource(string name)
        {

            Debug(Resources.Messages.DebugInfoCallMethod3, Constants.ProviderName, "FindRegisteredSource", name);
            var srcs = RegisteredPackageSources;

            if (srcs == null)
            {
                return null;
            }
            if (srcs.ContainsKey(name))
            {
                return srcs[name];
            }

            var src = srcs.Values.FirstOrDefault(each => LocationCloseEnoughMatch(name, each.Location));
            return src;
        }

        private bool LocationCloseEnoughMatch(string givenLocation, string knownLocation)
        {
            if (givenLocation.Equals(knownLocation, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            // make trailing slashes consistent
            if (givenLocation.TrimEnd('/').Equals(knownLocation.TrimEnd('/'), StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            // and trailing backslashes
            if (givenLocation.TrimEnd('\\').Equals(knownLocation.TrimEnd('\\'), StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }
            return false;
        }

        private IDictionary<string, PackageSource> RegisteredPackageSources
        {
            get
            {
                if (_registeredPackageSources == null || !_registeredPackageSources.Any())
                {
                    _registeredPackageSources = new ConcurrentDictionary<string, PackageSource>(StringComparer.OrdinalIgnoreCase);

                    try
                    {
                        Debug(Resources.Messages.DebugInfoCallMethod3, Constants.ProviderName, "RegisteredPackageSources", ConfigurationFileLocation);

                        var config = Config;
                        if (config != null)
                        {
                            // get the configuration node
                            var configuration = config.ElementsNoNamespace("configuration").FirstOrDefault();
                            if (configuration != null)
                            {
                                // get the packageSources node
                                var packageSources = configuration.ElementsNoNamespace("packageSources").FirstOrDefault();

                                if (packageSources != null)
                                {
                                    _registeredPackageSources = packageSources.Elements("add")
                                        .Where(each => each.Attribute("key") != null && each.Attribute("value") != null)
                                        .ToDictionaryNicely(each => each.Attribute("key").Value, each =>
                                            new PackageSource
                                            {
                                                Request = this,
                                                Name = each.Attribute("key").Value,
                                                Location = each.Attribute("value").Value,
                                                Trusted = each.Attribute("trusted") != null && each.Attribute("trusted").Value.IsTrue(),
                                                IsRegistered = true,
                                                IsValidated = each.Attribute("validated") != null && each.Attribute("validated").Value.IsTrue(),
                                            }, StringComparer.OrdinalIgnoreCase);

                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        _registeredPackageSources = new ConcurrentDictionary<string, PackageSource>();
                    }
                }

                return _registeredPackageSources;
            }
        }

        /// <summary>
        /// Return all registered package sources
        /// </summary>
        internal IEnumerable<PackageSource> SelectedSources
        {
            get
            {
                if (IsCanceled)
                {
                    yield break;
                }

                //get sources from user's input
                var sourcesFromUser = (PackageSources ?? Enumerable.Empty<string>()).ToArray();
                //get sources from config file that registered earlier
                var pkgSources = RegisteredPackageSources;

                Debug(Resources.Messages.RegisteredSources, pkgSources.Count, Constants.ProviderName);

                //If a user does not provide -source, we use the registered ones
                if (sourcesFromUser.Length == 0)
                {
                    // return them all.
                    foreach (var src in pkgSources.Values)
                    {
                        Debug(src.Name);
                        yield return src;
                    }
                    yield break;
                }
                var userSpecifiesArrayOfSources =  sourcesFromUser.Length > 1;

                // otherwise, return package sources that match the items given.
                foreach (var src in sourcesFromUser)
                {
                    // Check whether we've already processed this item before
                    if (_checkedUnregisteredPackageSources.ContainsKey(src))
                    {
                        _checkedUnregisteredPackageSources[src].Request = this;
                        yield return _checkedUnregisteredPackageSources[src];
                        continue;
                    }

                    // check to see if we have a source with either that name
                    // or that URI first.
                    if (pkgSources.ContainsKey(src))
                    {
                        Debug(Resources.Messages.FoundRegisteredSource, src, Constants.ProviderName);
                        _checkedUnregisteredPackageSources.Add(src, pkgSources[src]);
                        yield return pkgSources[src];
                        continue;
                    }

                    var srcLoc = src;
                    var found = false;
                    foreach (var byLoc in pkgSources.Values)
                    {
                        // srcLoc does not match byLoc.Location, try to check for srcLoc with "/" appended at the end
                        if (!string.Equals(byLoc.Location, srcLoc, StringComparison.OrdinalIgnoreCase)
                            && !string.Equals(byLoc.Location, string.Concat(srcLoc, "/"), StringComparison.OrdinalIgnoreCase)
                            && !string.Equals(string.Concat(byLoc.Location, "/"), srcLoc, StringComparison.OrdinalIgnoreCase))
                        {
                            continue;
                        }

                        _checkedUnregisteredPackageSources.Add(srcLoc, byLoc);
                        yield return byLoc;
                        found = true;
                    }
                    if (found)
                    {
                        continue;
                    }

                    Debug(Resources.Messages.NotFoundRegisteredSource, src, Constants.ProviderName);

                    // is it a file path?
                    if (System.IO.Directory.Exists(src))
                    {
                        Debug(Resources.Messages.SourceIsADirectory, src);
                        PackageSource newSource = new PackageSource
                        {
                            Request = this,
                            Location = src,
                            Name = src,
                            Trusted = true,
                            IsRegistered = false,
                            IsValidated = true,
                        };
                        yield return newSource;
                    }
                    else if (File.Exists(src) && (Path.GetExtension(src).EqualsIgnoreCase(".json")) )
                    {
                        PackageSource newSource = new PackageSource
                        {
                            Request = this,
                            Location = src,
                            Name = src,
                            Trusted = true,
                            IsRegistered = false,
                            IsValidated = true,
                        };
                        yield return newSource;
                    }
                    else
                    {
                        // Not a valid location?
                        if (userSpecifiesArrayOfSources)
                        {
                            Verbose(Constants.Messages.UnableToResolveSource, Constants.ProviderName, src);
                        }
                        else
                        {
                            Warning(Constants.Messages.UnableToResolveSource, Constants.ProviderName, src);
                        }
                    }
                }
            }
        }

        private XDocument Config
        {
            get
            {
                if (_config == null)
                {
                    Debug(Resources.Messages.LoadingConfigurationFile, ConfigurationFileLocation);

                    XDocument doc = null;

                    try
                    {
                        using (FileStream fs = new FileStream(ConfigurationFileLocation, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            // load the xdocument from the file stream
                            doc = XmlUtility.LoadSafe(fs, ignoreWhiteSpace: true);
                        }

                        Debug(Resources.Messages.LoadedConfigurationFile, ConfigurationFileLocation);

                        if (doc.Root != null && doc.Root.Name != null && String.Equals(doc.Root.Name.LocalName, "configuration", StringComparison.OrdinalIgnoreCase))
                        {
                            _config = doc;
                            return _config;
                        }
                        Warning(Resources.Messages.MissingConfigurationElement, ConfigurationFileLocation);
                    }
                    catch (Exception e)
                    {
                        // a bad xml doc or a folder gets deleted somehow
                        Warning(e.Message);
                    }
                }

                return _config;
            }
            set
            {

                if (value == null)
                {
                    Debug(Resources.Messages.SettingConfigurationToNull);
                    return;
                }

                _config = value;

                Verbose(Resources.Messages.SavingConfigurationWithFile, ConfigurationFileLocation);
                var stringBuilder = new System.Text.StringBuilder();

                var settings = new XmlWriterSettings
                {
                    OmitXmlDeclaration = false,
                    Indent = true,
                    NewLineOnAttributes = true,
                    NamespaceHandling = NamespaceHandling.OmitDuplicates
                };

                using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
                {
                    _config.Save(xmlWriter);
                    System.IO.File.WriteAllText(ConfigurationFileLocation, _config.ToString());
                }
            }
        }

        private string ConfigurationFileLocation
        {
            get
            {
            if (string.IsNullOrWhiteSpace(_configurationFileLocation))
            {
                    var appdataFolder = Environment.GetEnvironmentVariable("appdata");
                    _configurationFileLocation = Path.Combine(appdataFolder, Constants.ProviderName, Constants.SettingsFileName);

                    //create directory if does not exist
                    string dir = Path.GetDirectoryName(_configurationFileLocation);
                    if (dir != null && !System.IO.Directory.Exists(dir))
                    {
                        Debug(Resources.Messages.CreateDirectory, dir);
                        System.IO.Directory.CreateDirectory(dir);
                    }
                    //create place holder config file
                    if (!System.IO.File.Exists(_configurationFileLocation))
                    {
                        Debug(Resources.Messages.CreateFile, _configurationFileLocation);
                        bool addDefaultConfig = false;
                        if (System.IO.File.Exists(DefaultJSONFileLocation))
                        {
                            addDefaultConfig = true;
                        }
                        else
                        {
                            bool force = this.GetOptionValue("Force") != null;
                            if (force || this.ShouldContinue(Resources.Messages.QueryDownloadPackageSourceList.format(DefaultJSONSourceLocation), Resources.Messages.PackageSourceListNotFound.format(DefaultJSONFileLocation)))
                            {
                                WebDownloader.DownloadFile(DefaultJSONSourceLocation, DefaultJSONFileLocation, this, null);
                                WebDownloader.DownloadFile(DefaultJSONCatalogFileLocation, DefaultCatalogFileLocation, this, null);
                                if (System.IO.File.Exists(DefaultJSONFileLocation) && System.IO.File.Exists(DefaultCatalogFileLocation) &&
                                    PackageSourceListProvider.TestCatalogFile(DefaultJSONFileLocation, DefaultCatalogFileLocation, this))
                                {
                                   addDefaultConfig = true;
                                }
                            }
                        }

                        if(addDefaultConfig)
                            System.IO.File.WriteAllText(_configurationFileLocation, DefaultConfig);
                        else
                            System.IO.File.WriteAllText(_configurationFileLocation, EmptyConfig);
                    }
                }
                return _configurationFileLocation;
            }
        }

        internal bool WriteError(Internal.ErrorCategory category, string targetObjectValue, string messageText, params object[] args)
        {
            return Error(messageText, category.ToString(), targetObjectValue, base.FormatMessageString(messageText, args));
        }

        /// <summary>
        /// Check if the package source location is valid
        /// </summary>
        /// <param name="location"></param>
        /// <returns></returns>
        internal bool ValidateSourceLocation(string location)
        {
            Debug(Resources.Messages.DebugInfoCallMethod3, _PackageSourceListRequest, "ValidateSourceLocation", location);
            if (File.Exists(location) && (Path.GetExtension(location).EqualsIgnoreCase(".json")))
            {
                return true;
            }
            return false;
        }

        internal static IRequest ExtendRequest(Dictionary<string, string[]> options, string[] sources, bool isTrusted, PackageSourceListRequest request) {
            var srcs = sources ?? new List<string>().ToArray();
            var opts = options ?? new Dictionary<string, string[]>();

            return (new object[]
            {
                new {
                    GetOptionKeys = new Func<IEnumerable<string>>(() => opts.Keys.Any() ? request.OptionKeys.Concat(opts.Keys) : request.OptionKeys),
                    GetOptionValues = new Func<string, IEnumerable<string>>((key) =>
                    {
                        if (opts.ContainsKey(key))
                        {
                            return opts[key];
                        }
                        return request.GetOptionValues(key);
                    }),

                    GetSources = new Func<IEnumerable<string>>(() => srcs),
                    //ShouldContinueWithUntrustedPackageSource = new Func<string, string, bool>((pkgName, pkgSource) => isTrusted),
                },
                request
            }).As<IRequest>();
        }

        /// <summary>
        /// HttpClient with Accept-CharSet and Accept-Encoding Header
        /// We want to reuse HttpClient
        /// </summary>
        internal HttpClient Client
        {
            get
            {
                if (_httpClient == null)
                {
                    _httpClient = PathUtility.GetHttpClientHelper(CredentialUsername, CredentialPassword, WebProxy);

                    _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "UTF-8");
                    // Request for gzip and deflate encoding to make the response lighter.
                    _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip,deflate");

                    // needed for downloading package like node.js.msi
                    _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text / html, application / xhtml + xml, image / jxr, */*");

                    foreach (var header in Headers.Value)
                    {
                        // header is in the format "A=B" because OneGet doesn't support Dictionary parameters
                        if (!string.IsNullOrEmpty(header))
                        {
                            var headerSplit = header.Split(new string[] { "=" }, 2, StringSplitOptions.RemoveEmptyEntries);

                            // ignore wrong entries
                            if (headerSplit.Count() == 2)
                            {
                                _httpClient.DefaultRequestHeaders.TryAddWithoutValidation(headerSplit[0], headerSplit[1]);
                            }
                            else
                            {
                                Warning(Resources.Messages.HeaderIgnored, header);
                            }
                        }
                    }
                }

                return _httpClient;
            }
        }
    }
}

#endif


text:
require 'test_helper'

class CallbackControllerTest < ActionController::TestCase
  test "should get store" do
    get :store
    assert_response :success
  end

  test "should get failure" do
    get :failure
    assert_response :success
  end

end


text:
package com.java110.core.factory;

import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @ClassName Java110ThreadPoolFactory
 * @Description java110提供线程池工厂类
 * @Author wuxw
 * @Date 2021/1/14 21:04
 * @Version 1.0
 * add by wuxw 2021/1/14
 **/
public class Java110ThreadPoolFactory<T> {

    public static final int JAVA110_DEFAULT_THREAD_NUM = 5;
    private Vector<Future<T>> futureList = null;
    ExecutorService executor = null;

    public static Java110ThreadPoolFactory getInstance() {
        return new Java110ThreadPoolFactory();
    }

    /**
     * 创建 线程池
     *
     * @param defaultThreadNum 线程数量
     * @return
     */
    public Java110ThreadPoolFactory<T> createThreadPool(int defaultThreadNum) {
        futureList = new Vector<>();
        executor = Executors.newFixedThreadPool(defaultThreadNum);
        return this;
    }

    public Java110ThreadPoolFactory submit(Callable<T> task) {
        Future<T> result = executor.submit(task);
        futureList.add(result);
        return this;
    }

    public List<T> get() {
        List<T> result = new LinkedList<>();
        for (Future<T> future :
                futureList) {
            try {
                result.add(future.get());
            } catch (Exception e) {
                result.add(null);
            }

        }
        return result;
    }

    public void stop() {
        executor.shutdown();
    }
}


text:
package com.canoo.dp.impl.remoting.info;

import com.canoo.dp.impl.platform.core.Assert;
import com.canoo.platform.remoting.spi.converter.Converter;
import com.canoo.platform.remoting.spi.converter.ValueConverterException;
import org.apiguardian.api.API;

import static org.apiguardian.api.API.Status.INTERNAL;

@API(since = "0.x", status = INTERNAL)
public abstract class PropertyInfo {

    private final String attributeName;
    private final Converter converter;

    public PropertyInfo(final String attributeName, final Converter converter) {
        this.attributeName = attributeName;
        this.converter = Assert.requireNonNull(converter, "converter");
    }

    public String getAttributeName() {
        return attributeName;
    }

    public abstract Object getPrivileged(final Object bean);

    public abstract void setPriviliged(final Object bean, final Object value);

    public Object convertFromDolphin(final Object value) throws ValueConverterException {
        return converter.convertFromDolphin(value);
    }

    public Object convertToDolphin(final Object value) throws ValueConverterException {
        return converter.convertToDolphin(value);
    }
}


text:
package legacyclient

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/watch"
	clientgotesting "k8s.io/client-go/testing"
	kapi "k8s.io/kubernetes/pkg/api"

	otestclient "github.com/openshift/origin/pkg/client/testclient"
	securityapi "github.com/openshift/origin/pkg/security/apis/security"
)

// NewSimpleFake returns a client that will respond with the provided objects
func NewSimpleFake(objects ...runtime.Object) *FakeSecurityContextContstraint {
	o := clientgotesting.NewObjectTracker(kapi.Registry, kapi.Scheme, kapi.Codecs.UniversalDecoder())
	for _, obj := range objects {
		if err := o.Add(obj); err != nil {
			panic(err)
		}
	}

	fakeClient := &otestclient.Fake{}
	fakeClient.AddReactor("*", "*", clientgotesting.ObjectReaction(o, kapi.Registry.RESTMapper()))

	fakeClient.AddWatchReactor("*", clientgotesting.DefaultWatchReactor(watch.NewFake(), nil))

	return &FakeSecurityContextContstraint{Fake: fakeClient}
}

type FakeSecurityContextContstraint struct {
	Fake *otestclient.Fake
}

var sccResource = schema.GroupVersionResource{Group: "", Version: "", Resource: "securitycontextconstraints"}

func (c *FakeSecurityContextContstraint) Get(name string, options metav1.GetOptions) (*securityapi.SecurityContextConstraints, error) {
	obj, err := c.Fake.Invokes(clientgotesting.NewRootGetAction(sccResource, name), &securityapi.SecurityContextConstraints{})
	if obj == nil {
		return nil, err
	}

	return obj.(*securityapi.SecurityContextConstraints), err
}

func (c *FakeSecurityContextContstraint) List(opts metav1.ListOptions) (*securityapi.SecurityContextConstraintsList, error) {
	obj, err := c.Fake.Invokes(clientgotesting.NewRootListAction(sccResource, opts), &securityapi.SecurityContextConstraintsList{})
	if obj == nil {
		return nil, err
	}

	return obj.(*securityapi.SecurityContextConstraintsList), err
}

func (c *FakeSecurityContextContstraint) Create(inObj *securityapi.SecurityContextConstraints) (*securityapi.SecurityContextConstraints, error) {
	obj, err := c.Fake.Invokes(clientgotesting.NewRootCreateAction(sccResource, inObj), inObj)
	if obj == nil {
		return nil, err
	}

	return obj.(*securityapi.SecurityContextConstraints), err
}

func (c *FakeSecurityContextContstraint) Update(inObj *securityapi.SecurityContextConstraints) (*securityapi.SecurityContextConstraints, error) {
	obj, err := c.Fake.Invokes(clientgotesting.NewRootUpdateAction(sccResource, inObj), inObj)
	if obj == nil {
		return nil, err
	}

	return obj.(*securityapi.SecurityContextConstraints), err
}

func (c *FakeSecurityContextContstraint) Delete(name string) error {
	_, err := c.Fake.Invokes(clientgotesting.NewRootDeleteAction(sccResource, name), &securityapi.SecurityContextConstraints{})
	return err
}

func (c *FakeSecurityContextContstraint) Watch(opts metav1.ListOptions) (watch.Interface, error) {
	return c.Fake.InvokesWatch(clientgotesting.NewRootWatchAction(sccResource, opts))
}