text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// 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 "arrow/scalar.h"

#include <memory>
#include <ostream>
#include <sstream>
#include <string>
#include <utility>

#include "arrow/array.h"
#include "arrow/array/util.h"
#include "arrow/buffer.h"
#include "arrow/compare.h"
#include "arrow/pretty_print.h"
#include "arrow/type.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/decimal.h"
#include "arrow/util/formatting.h"
#include "arrow/util/hashing.h"
#include "arrow/util/logging.h"
#include "arrow/util/time.h"
#include "arrow/util/unreachable.h"
#include "arrow/util/utf8.h"
#include "arrow/util/value_parsing.h"
#include "arrow/visit_scalar_inline.h"

namespace arrow {

using internal::checked_cast;
using internal::checked_pointer_cast;

bool Scalar::Equals(const Scalar& other, const EqualOptions& options) const {
  return ScalarEquals(*this, other, options);
}

bool Scalar::ApproxEquals(const Scalar& other, const EqualOptions& options) const {
  return ScalarApproxEquals(*this, other, options);
}

Status Scalar::Accept(ScalarVisitor* visitor) const {
  return VisitScalarInline(*this, visitor);
}

namespace {

// Implementation of Scalar::hash()
struct ScalarHashImpl {
  Status Visit(const NullScalar& s) { return Status::OK(); }

  template <typename T>
  Status Visit(const internal::PrimitiveScalar<T>& s) {
    return ValueHash(s);
  }

  Status Visit(const BaseBinaryScalar& s) { return BufferHash(*s.value); }

  template <typename T>
  Status Visit(const TemporalScalar<T>& s) {
    return ValueHash(s);
  }

  Status Visit(const DayTimeIntervalScalar& s) {
    return StdHash(s.value.days) & StdHash(s.value.milliseconds);
  }

  Status Visit(const MonthDayNanoIntervalScalar& s) {
    return StdHash(s.value.days) & StdHash(s.value.months) & StdHash(s.value.nanoseconds);
  }

  Status Visit(const Decimal128Scalar& s) {
    return StdHash(s.value.low_bits()) & StdHash(s.value.high_bits());
  }

  Status Visit(const Decimal256Scalar& s) {
    Status status = Status::OK();
    // endianness doesn't affect result
    for (uint64_t elem : s.value.native_endian_array()) {
      status &= StdHash(elem);
    }
    return status;
  }

  Status Visit(const BaseListScalar& s) { return ArrayHash(*s.value); }

  Status Visit(const StructScalar& s) {
    for (const auto& child : s.value) {
      AccumulateHashFrom(*child);
    }
    return Status::OK();
  }

  Status Visit(const DictionaryScalar& s) {
    AccumulateHashFrom(*s.value.index);
    return Status::OK();
  }

  Status Visit(const DenseUnionScalar& s) {
    // type_code is ignored when comparing for equality, so do not hash it either
    AccumulateHashFrom(*s.value);
    return Status::OK();
  }

  Status Visit(const SparseUnionScalar& s) {
    // type_code is ignored when comparing for equality, so do not hash it either
    AccumulateHashFrom(*s.value[s.child_id]);
    return Status::OK();
  }

  Status Visit(const ExtensionScalar& s) {
    AccumulateHashFrom(*s.value);
    return Status::OK();
  }

  template <typename T>
  Status StdHash(const T& t) {
    static std::hash<T> hash;
    hash_ ^= hash(t);
    return Status::OK();
  }

  template <typename S>
  Status ValueHash(const S& s) {
    return StdHash(s.value);
  }

  Status BufferHash(const Buffer& b) {
    hash_ ^= internal::ComputeStringHash<1>(b.data(), b.size());
    return Status::OK();
  }

  Status ArrayHash(const Array& a) { return ArrayHash(*a.data()); }

  Status ArrayHash(const ArrayData& a) {
    RETURN_NOT_OK(StdHash(a.length) & StdHash(a.GetNullCount()));
    if (a.buffers[0] != nullptr) {
      // We can't visit values without unboxing the whole array, so only hash
      // the null bitmap for now.
      RETURN_NOT_OK(BufferHash(*a.buffers[0]));
    }
    for (const auto& child : a.child_data) {
      RETURN_NOT_OK(ArrayHash(*child));
    }
    return Status::OK();
  }

  explicit ScalarHashImpl(const Scalar& scalar) : hash_(scalar.type->Hash()) {
    AccumulateHashFrom(scalar);
  }

  void AccumulateHashFrom(const Scalar& scalar) {
    // Note we already injected the type in ScalarHashImpl::ScalarHashImpl
    if (scalar.is_valid) {
      DCHECK_OK(VisitScalarInline(scalar, this));
    }
  }

  size_t hash_;
};

struct ScalarBoundsCheckImpl {
  int64_t min_value;
  int64_t max_value;
  int64_t actual_value = -1;
  bool ok = true;

  ScalarBoundsCheckImpl(int64_t min_value, int64_t max_value)
      : min_value(min_value), max_value(max_value) {}

  Status Visit(const Scalar&) {
    Unreachable();
    return Status::NotImplemented("");
  }

  template <typename ScalarType, typename Type = typename ScalarType::TypeClass>
  enable_if_integer<Type, Status> Visit(const ScalarType& scalar) {
    actual_value = static_cast<int64_t>(scalar.value);
    ok = (actual_value >= min_value && actual_value <= max_value);
    return Status::OK();
  }
};

// Implementation of Scalar::Validate() and Scalar::ValidateFull()
struct ScalarValidateImpl {
  const bool full_validation_;

  explicit ScalarValidateImpl(bool full_validation) : full_validation_(full_validation) {
    ::arrow::util::InitializeUTF8();
  }

  Status Validate(const Scalar& scalar) {
    if (!scalar.type) {
      return Status::Invalid("scalar lacks a type");
    }
    return VisitScalarInline(scalar, this);
  }

  Status Visit(const NullScalar& s) {
    if (s.is_valid) {
      return Status::Invalid("null scalar should have is_valid = false");
    }
    return Status::OK();
  }

  template <typename T>
  Status Visit(const internal::PrimitiveScalar<T>& s) {
    return Status::OK();
  }

  Status Visit(const BaseBinaryScalar& s) { return ValidateBinaryScalar(s); }

  Status Visit(const StringScalar& s) { return ValidateStringScalar(s); }

  Status Visit(const LargeStringScalar& s) { return ValidateStringScalar(s); }

  template <typename ScalarType>
  Status CheckValueNotNull(const ScalarType& s) {
    if (!s.value) {
      return Status::Invalid(s.type->ToString(), " value is null");
    }
    return Status::OK();
  }

  Status Visit(const FixedSizeBinaryScalar& s) {
    const auto& byte_width =
        checked_cast<const FixedSizeBinaryType&>(*s.type).byte_width();
    RETURN_NOT_OK(CheckValueNotNull(s));
    if (s.value->size() != byte_width) {
      return Status::Invalid(s.type->ToString(), " scalar should have a value of size ",
                             byte_width, ", got ", s.value->size());
    }
    return Status::OK();
  }

  Status Visit(const Decimal128Scalar& s) {
    const auto& ty = checked_cast<const DecimalType&>(*s.type);
    if (!s.value.FitsInPrecision(ty.precision())) {
      return Status::Invalid("Decimal value ", s.value.ToIntegerString(),
                             " does not fit in precision of ", ty);
    }
    return Status::OK();
  }

  Status Visit(const Decimal256Scalar& s) {
    const auto& ty = checked_cast<const DecimalType&>(*s.type);
    if (!s.value.FitsInPrecision(ty.precision())) {
      return Status::Invalid("Decimal value ", s.value.ToIntegerString(),
                             " does not fit in precision of ", ty);
    }
    return Status::OK();
  }

  Status Visit(const BaseListScalar& s) {
    RETURN_NOT_OK(CheckValueNotNull(s));
    const auto st = full_validation_ ? s.value->ValidateFull() : s.value->Validate();
    if (!st.ok()) {
      return st.WithMessage(s.type->ToString(),
                            " scalar fails validation for value: ", st.message());
    }

    const auto& list_type = checked_cast<const BaseListType&>(*s.type);
    const auto& value_type = *list_type.value_type();
    if (!s.value->type()->Equals(value_type)) {
      return Status::Invalid(list_type.ToString(), " scalar should have a value of type ",
                             value_type.ToString(), ", got ",
                             s.value->type()->ToString());
    }
    return Status::OK();
  }

  Status Visit(const FixedSizeListScalar& s) {
    RETURN_NOT_OK(Visit(static_cast<const BaseListScalar&>(s)));
    const auto& list_type = checked_cast<const FixedSizeListType&>(*s.type);
    if (s.value->length() != list_type.list_size()) {
      return Status::Invalid(s.type->ToString(),
                             " scalar should have a child value of length ",
                             list_type.list_size(), ", got ", s.value->length());
    }
    return Status::OK();
  }

  Status Visit(const StructScalar& s) {
    const int num_fields = s.type->num_fields();
    const auto& fields = s.type->fields();
    if (fields.size() != s.value.size()) {
      return Status::Invalid("non-null ", s.type->ToString(), " scalar should have ",
                             num_fields, " child values, got ", s.value.size());
    }
    for (int i = 0; i < num_fields; ++i) {
      const auto st = Validate(*s.value[i]);
      if (!st.ok()) {
        return st.WithMessage(s.type->ToString(),
                              " scalar fails validation for child at index ", i, ": ",
                              st.message());
      }
      if (!s.value[i]->type->Equals(*fields[i]->type())) {
        return Status::Invalid(
            s.type->ToString(), " scalar should have a child value of type ",
            fields[i]->type()->ToString(), "at index ", i, ", got ", s.value[i]->type);
      }
    }
    return Status::OK();
  }

  Status Visit(const DictionaryScalar& s) {
    const auto& dict_type = checked_cast<const DictionaryType&>(*s.type);

    // Validate index
    if (!s.value.index) {
      return Status::Invalid(s.type->ToString(), " scalar doesn't have an index value");
    }
    {
      const auto st = Validate(*s.value.index);
      if (!st.ok()) {
        return st.WithMessage(s.type->ToString(),
                              " scalar fails validation for index value: ", st.message());
      }
    }
    if (!s.value.index->type->Equals(*dict_type.index_type())) {
      return Status::Invalid(
          s.type->ToString(), " scalar should have an index value of type ",
          dict_type.index_type()->ToString(), ", got ", s.value.index->type->ToString());
    }
    if (s.is_valid && !s.value.index->is_valid) {
      return Status::Invalid("non-null ", s.type->ToString(),
                             " scalar has null index value");
    }
    if (!s.is_valid && s.value.index->is_valid) {
      return Status::Invalid("null ", s.type->ToString(),
                             " scalar has non-null index value");
    }

    // Validate dictionary
    if (!s.value.dictionary) {
      return Status::Invalid(s.type->ToString(),
                             " scalar doesn't have a dictionary value");
    }
    {
      const auto st = full_validation_ ? s.value.dictionary->ValidateFull()
                                       : s.value.dictionary->Validate();
      if (!st.ok()) {
        return st.WithMessage(
            s.type->ToString(),
            " scalar fails validation for dictionary value: ", st.message());
      }
    }
    if (!s.value.dictionary->type()->Equals(*dict_type.value_type())) {
      return Status::Invalid(s.type->ToString(),
                             " scalar should have a dictionary value of type ",
                             dict_type.value_type()->ToString(), ", got ",
                             s.value.dictionary->type()->ToString());
    }

    // Check index is in bounds
    if (full_validation_ && s.value.index->is_valid) {
      ScalarBoundsCheckImpl bounds_checker{0, s.value.dictionary->length() - 1};
      RETURN_NOT_OK(VisitScalarInline(*s.value.index, &bounds_checker));
      if (!bounds_checker.ok) {
        return Status::Invalid(s.type->ToString(), " scalar index value out of bounds: ",
                               bounds_checker.actual_value);
      }
    }
    return Status::OK();
  }

  Status ValidateValue(const Scalar& s, const Scalar& value) {
    const auto st = Validate(value);
    if (!st.ok()) {
      return st.WithMessage(
          s.type->ToString(),
          " scalar fails validation for underlying value: ", st.message());
    }
    return Status::OK();
  }

  Status ValidateDenseUnion(const DenseUnionScalar& s, int child_id) {
    const auto& union_type = checked_cast<const DenseUnionType&>(*s.type);
    const auto& field_type = *union_type.field(child_id)->type();
    if (!field_type.Equals(*s.value->type)) {
      return Status::Invalid(s.type->ToString(), " scalar with type code ", s.type_code,
                             " should have an underlying value of type ",
                             field_type.ToString(), ", got ", s.value->type->ToString());
    }
    return ValidateValue(s, *s.value);
  }

  Status ValidateSparseUnion(const SparseUnionScalar& s) {
    const auto& union_type = checked_cast<const SparseUnionType&>(*s.type);
    if (union_type.num_fields() != static_cast<int>(s.value.size())) {
      return Status::Invalid("Sparse union scalar value had ", union_type.num_fields(),
                             " fields but type has ", s.value.size(), " fields.");
    }
    for (int j = 0; j < union_type.num_fields(); ++j) {
      const auto& field_type = *union_type.field(j)->type();
      const Scalar& field_value = *s.value[j];
      if (!field_type.Equals(*field_value.type)) {
        return Status::Invalid(s.type->ToString(), " value for field ",
                               union_type.field(j)->ToString(), " had incorrect type of ",
                               field_value.type->ToString());
      }
      RETURN_NOT_OK(ValidateValue(s, field_value));
    }
    return Status::OK();
  }

  Status Visit(const UnionScalar& s) {
    const int type_code = s.type_code;  // avoid 8-bit int types for printing
    const auto& union_type = checked_cast<const UnionType&>(*s.type);
    const auto& child_ids = union_type.child_ids();
    if (type_code < 0 || type_code >= static_cast<int64_t>(child_ids.size()) ||
        child_ids[type_code] == UnionType::kInvalidChildId) {
      return Status::Invalid(s.type->ToString(), " scalar has invalid type code ",
                             type_code);
    }
    if (union_type.id() == Type::DENSE_UNION) {
      return ValidateDenseUnion(checked_cast<const DenseUnionScalar&>(s),
                                child_ids[type_code]);
    } else {
      return ValidateSparseUnion(checked_cast<const SparseUnionScalar&>(s));
    }
  }

  Status Visit(const ExtensionScalar& s) {
    if (!s.value) {
      return Status::Invalid(s.type->ToString(), " scalar doesn't have storage value");
    }
    if (!s.is_valid && s.value->is_valid) {
      return Status::Invalid("null ", s.type->ToString(),
                             " scalar has non-null storage value");
      return Status::OK();
    }
    if (s.is_valid && !s.value->is_valid) {
      return Status::Invalid("non-null ", s.type->ToString(),
                             " scalar has null storage value");
    }
    const auto st = Validate(*s.value);
    if (!st.ok()) {
      return st.WithMessage(s.type->ToString(),
                            " scalar fails validation for storage value: ", st.message());
    }
    return Status::OK();
  }

  Status ValidateStringScalar(const BaseBinaryScalar& s) {
    RETURN_NOT_OK(ValidateBinaryScalar(s));
    if (s.is_valid && full_validation_) {
      if (!::arrow::util::ValidateUTF8(s.value->data(), s.value->size())) {
        return Status::Invalid(s.type->ToString(), " scalar contains invalid UTF8 data");
      }
    }
    return Status::OK();
  }

  Status ValidateBinaryScalar(const BaseBinaryScalar& s) {
    if (s.is_valid && !s.value) {
      return Status::Invalid(s.type->ToString(),
                             " scalar is marked valid but doesn't have a value");
    }
    if (!s.is_valid && s.value) {
      return Status::Invalid(s.type->ToString(),
                             " scalar is marked null but has a value");
    }
    return Status::OK();
  }
};

}  // namespace

size_t Scalar::hash() const { return ScalarHashImpl(*this).hash_; }

Status Scalar::Validate() const {
  return ScalarValidateImpl(/*full_validation=*/false).Validate(*this);
}

Status Scalar::ValidateFull() const {
  return ScalarValidateImpl(/*full_validation=*/true).Validate(*this);
}

BinaryScalar::BinaryScalar(std::string s)
    : BinaryScalar(Buffer::FromString(std::move(s))) {}

StringScalar::StringScalar(std::string s)
    : StringScalar(Buffer::FromString(std::move(s))) {}

LargeBinaryScalar::LargeBinaryScalar(std::string s)
    : LargeBinaryScalar(Buffer::FromString(std::move(s))) {}

LargeStringScalar::LargeStringScalar(std::string s)
    : LargeStringScalar(Buffer::FromString(std::move(s))) {}

FixedSizeBinaryScalar::FixedSizeBinaryScalar(std::shared_ptr<Buffer> value,
                                             std::shared_ptr<DataType> type,
                                             bool is_valid)
    : BinaryScalar(std::move(value), std::move(type)) {
  ARROW_CHECK_EQ(checked_cast<const FixedSizeBinaryType&>(*this->type).byte_width(),
                 this->value->size());
  this->is_valid = is_valid;
}

FixedSizeBinaryScalar::FixedSizeBinaryScalar(const std::shared_ptr<Buffer>& value,
                                             bool is_valid)
    : BinaryScalar(value, fixed_size_binary(static_cast<int>(value->size()))) {
  this->is_valid = is_valid;
}

FixedSizeBinaryScalar::FixedSizeBinaryScalar(std::string s, bool is_valid)
    : FixedSizeBinaryScalar(Buffer::FromString(std::move(s)), is_valid) {}

BaseListScalar::BaseListScalar(std::shared_ptr<Array> value,
                               std::shared_ptr<DataType> type, bool is_valid)
    : Scalar{std::move(type), is_valid}, value(std::move(value)) {
  ARROW_CHECK(this->type->field(0)->type()->Equals(this->value->type()));
}

ListScalar::ListScalar(std::shared_ptr<Array> value, bool is_valid)
    : BaseListScalar(value, list(value->type()), is_valid) {}

LargeListScalar::LargeListScalar(std::shared_ptr<Array> value, bool is_valid)
    : BaseListScalar(value, large_list(value->type()), is_valid) {}

inline std::shared_ptr<DataType> MakeMapType(const std::shared_ptr<DataType>& pair_type) {
  ARROW_CHECK_EQ(pair_type->id(), Type::STRUCT);
  ARROW_CHECK_EQ(pair_type->num_fields(), 2);
  return map(pair_type->field(0)->type(), pair_type->field(1)->type());
}

MapScalar::MapScalar(std::shared_ptr<Array> value, bool is_valid)
    : BaseListScalar(value, MakeMapType(value->type()), is_valid) {}

FixedSizeListScalar::FixedSizeListScalar(std::shared_ptr<Array> value,
                                         std::shared_ptr<DataType> type, bool is_valid)
    : BaseListScalar(value, std::move(type), is_valid) {
  ARROW_CHECK_EQ(this->value->length(),
                 checked_cast<const FixedSizeListType&>(*this->type).list_size());
}

FixedSizeListScalar::FixedSizeListScalar(std::shared_ptr<Array> value, bool is_valid)
    : BaseListScalar(
          value, fixed_size_list(value->type(), static_cast<int32_t>(value->length())),
          is_valid) {}

Result<std::shared_ptr<StructScalar>> StructScalar::Make(
    ScalarVector values, std::vector<std::string> field_names) {
  if (values.size() != field_names.size()) {
    return Status::Invalid("Mismatching number of field names and child scalars");
  }

  FieldVector fields(field_names.size());
  for (size_t i = 0; i < fields.size(); ++i) {
    fields[i] = arrow::field(std::move(field_names[i]), values[i]->type);
  }

  return std::make_shared<StructScalar>(std::move(values), struct_(std::move(fields)));
}

Result<std::shared_ptr<Scalar>> StructScalar::field(FieldRef ref) const {
  ARROW_ASSIGN_OR_RAISE(auto path, ref.FindOne(*type));
  if (path.indices().size() != 1) {
    return Status::NotImplemented("retrieval of nested fields from StructScalar");
  }
  auto index = path.indices()[0];
  if (is_valid) {
    return value[index];
  } else {
    const auto& struct_type = checked_cast<const StructType&>(*this->type);
    const auto& field_type = struct_type.field(index)->type();
    return MakeNullScalar(field_type);
  }
}

DictionaryScalar::DictionaryScalar(std::shared_ptr<DataType> type)
    : internal::PrimitiveScalarBase(std::move(type)),
      value{MakeNullScalar(checked_cast<const DictionaryType&>(*this->type).index_type()),
            MakeArrayOfNull(checked_cast<const DictionaryType&>(*this->type).value_type(),
                            0)
                .ValueOrDie()} {}

Result<std::shared_ptr<Scalar>> DictionaryScalar::GetEncodedValue() const {
  const auto& dict_type = checked_cast<DictionaryType&>(*type);

  if (!is_valid) {
    return MakeNullScalar(dict_type.value_type());
  }

  int64_t index_value = 0;
  switch (dict_type.index_type()->id()) {
    case Type::UINT8:
      index_value =
          static_cast<int64_t>(checked_cast<const UInt8Scalar&>(*value.index).value);
      break;
    case Type::INT8:
      index_value =
          static_cast<int64_t>(checked_cast<const Int8Scalar&>(*value.index).value);
      break;
    case Type::UINT16:
      index_value =
          static_cast<int64_t>(checked_cast<const UInt16Scalar&>(*value.index).value);
      break;
    case Type::INT16:
      index_value =
          static_cast<int64_t>(checked_cast<const Int16Scalar&>(*value.index).value);
      break;
    case Type::UINT32:
      index_value =
          static_cast<int64_t>(checked_cast<const UInt32Scalar&>(*value.index).value);
      break;
    case Type::INT32:
      index_value =
          static_cast<int64_t>(checked_cast<const Int32Scalar&>(*value.index).value);
      break;
    case Type::UINT64:
      index_value =
          static_cast<int64_t>(checked_cast<const UInt64Scalar&>(*value.index).value);
      break;
    case Type::INT64:
      index_value =
          static_cast<int64_t>(checked_cast<const Int64Scalar&>(*value.index).value);
      break;
    default:
      return Status::TypeError("Not implemented dictionary index type");
      break;
  }
  return value.dictionary->GetScalar(index_value);
}

std::shared_ptr<DictionaryScalar> DictionaryScalar::Make(std::shared_ptr<Scalar> index,
                                                         std::shared_ptr<Array> dict) {
  auto type = dictionary(index->type, dict->type());
  auto is_valid = index->is_valid;
  return std::make_shared<DictionaryScalar>(ValueType{std::move(index), std::move(dict)},
                                            std::move(type), is_valid);
}

SparseUnionScalar::SparseUnionScalar(ValueType value, int8_t type_code,
                                     std::shared_ptr<DataType> type)
    : UnionScalar(std::move(type), type_code, /*is_valid=*/true),
      value(std::move(value)) {
  this->child_id =
      checked_cast<const SparseUnionType&>(*this->type).child_ids()[type_code];

  // Fix nullness based on whether the selected child is null
  this->is_valid = this->value[this->child_id]->is_valid;
}

std::shared_ptr<Scalar> SparseUnionScalar::FromValue(std::shared_ptr<Scalar> value,
                                                     int field_index,
                                                     std::shared_ptr<DataType> type) {
  const auto& union_type = checked_cast<const SparseUnionType&>(*type);
  int8_t type_code = union_type.type_codes()[field_index];
  ScalarVector field_values;
  for (int i = 0; i < type->num_fields(); ++i) {
    if (i == field_index) {
      field_values.emplace_back(std::move(value));
    } else {
      field_values.emplace_back(MakeNullScalar(type->field(i)->type()));
    }
  }
  return std::make_shared<SparseUnionScalar>(field_values, type_code, std::move(type));
}

namespace {

template <typename T>
using scalar_constructor_has_arrow_type =
    std::is_constructible<typename TypeTraits<T>::ScalarType, std::shared_ptr<DataType>>;

template <typename T, typename R = void>
using enable_if_scalar_constructor_has_arrow_type =
    typename std::enable_if<scalar_constructor_has_arrow_type<T>::value, R>::type;

template <typename T, typename R = void>
using enable_if_scalar_constructor_has_no_arrow_type =
    typename std::enable_if<!scalar_constructor_has_arrow_type<T>::value, R>::type;

struct MakeNullImpl {
  template <typename T, typename ScalarType = typename TypeTraits<T>::ScalarType>
  enable_if_scalar_constructor_has_arrow_type<T, Status> Visit(const T&) {
    out_ = std::make_shared<ScalarType>(type_);
    return Status::OK();
  }

  template <typename T, typename ScalarType = typename TypeTraits<T>::ScalarType>
  enable_if_scalar_constructor_has_no_arrow_type<T, Status> Visit(const T&) {
    out_ = std::make_shared<ScalarType>();
    return Status::OK();
  }

  template <typename T, typename ScalarType = typename TypeTraits<T>::ScalarType>
  Status VisitListLike(const T& type, int64_t value_size = 0) {
    ARROW_ASSIGN_OR_RAISE(std::shared_ptr<Array> value,
                          MakeArrayOfNull(type.value_type(), value_size));
    out_ = std::make_shared<ScalarType>(std::move(value), type_, /*is_valid=*/false);
    return Status::OK();
  }

  Status Visit(const FixedSizeBinaryType& type) {
    ARROW_ASSIGN_OR_RAISE(std::shared_ptr<Buffer> value,
                          AllocateBuffer(type.byte_width()));
    // Avoid exposing past memory contents
    memset(value->mutable_data(), 0, value->size());
    out_ = std::make_shared<FixedSizeBinaryScalar>(std::move(value), type_,
                                                   /*is_valid=*/false);
    return Status::OK();
  }

  Status Visit(const ListType& type) { return VisitListLike<ListType>(type); }

  Status Visit(const MapType& type) { return VisitListLike<MapType>(type); }

  Status Visit(const LargeListType& type) { return VisitListLike<LargeListType>(type); }

  Status Visit(const FixedSizeListType& type) {
    return VisitListLike<FixedSizeListType>(type, type.list_size());
  }

  Status Visit(const StructType& type) {
    ScalarVector field_values;
    for (int i = 0; i < type.num_fields(); ++i) {
      field_values.push_back(MakeNullScalar(type.field(i)->type()));
    }
    out_ = std::make_shared<StructScalar>(std::move(field_values), type_,
                                          /*is_valid=*/false);
    return Status::OK();
  }

  Status Visit(const SparseUnionType& type) {
    if (type.num_fields() == 0) {
      return Status::Invalid("Cannot make scalar of empty union type");
    }
    ScalarVector field_values;
    for (int i = 0; i < type.num_fields(); ++i) {
      field_values.emplace_back(MakeNullScalar(type.field(i)->type()));
    }
    out_ = std::make_shared<SparseUnionScalar>(std::move(field_values),
                                               type.type_codes()[0], type_);
    return Status::OK();
  }

  Status Visit(const DenseUnionType& type) {
    if (type.num_fields() == 0) {
      return Status::Invalid("Cannot make scalar of empty union type");
    }
    out_ = std::make_shared<DenseUnionScalar>(MakeNullScalar(type.field(0)->type()),
                                              type.type_codes()[0], type_);
    return Status::OK();
  }

  Status Visit(const ExtensionType& type) {
    out_ = std::make_shared<ExtensionScalar>(MakeNullScalar(type.storage_type()), type_,
                                             /*is_valid=*/false);
    return Status::OK();
  }

  std::shared_ptr<Scalar> Finish() && {
    // Should not fail.
    DCHECK_OK(VisitTypeInline(*type_, this));
    return std::move(out_);
  }

  std::shared_ptr<DataType> type_;
  std::shared_ptr<Scalar> out_;
};

}  // namespace

std::shared_ptr<Scalar> MakeNullScalar(std::shared_ptr<DataType> type) {
  return MakeNullImpl{std::move(type), nullptr}.Finish();
}

std::string Scalar::ToString() const {
  if (!this->is_valid) {
    return "null";
  }
  if (type->id() == Type::DICTIONARY) {
    auto dict_scalar = checked_cast<const DictionaryScalar*>(this);
    return dict_scalar->value.dictionary->ToString() + "[" +
           dict_scalar->value.index->ToString() + "]";
  }
  auto maybe_repr = CastTo(utf8());
  if (maybe_repr.ok()) {
    return checked_cast<const StringScalar&>(*maybe_repr.ValueOrDie()).value->ToString();
  }

  std::string result;
  std::shared_ptr<Array> as_array = *MakeArrayFromScalar(*this, 1);
  DCHECK_OK(PrettyPrint(*as_array, PrettyPrintOptions::Defaults(), &result));
  return result;
}

struct ScalarParseImpl {
  template <typename T, typename = internal::enable_if_parseable<T>>
  Status Visit(const T& t) {
    typename internal::StringConverter<T>::value_type value;
    if (!internal::ParseValue(t, s_.data(), s_.size(), &value)) {
      return Status::Invalid("error parsing '", s_, "' as scalar of type ", t);
    }
    return Finish(value);
  }

  Status Visit(const BinaryType&) { return FinishWithBuffer(); }

  Status Visit(const LargeBinaryType&) { return FinishWithBuffer(); }

  Status Visit(const FixedSizeBinaryType&) { return FinishWithBuffer(); }

  Status Visit(const DictionaryType& t) {
    ARROW_ASSIGN_OR_RAISE(auto value, Scalar::Parse(t.value_type(), s_));
    return Finish(std::move(value));
  }

  Status Visit(const DataType& t) {
    return Status::NotImplemented("parsing scalars of type ", t);
  }

  template <typename Arg>
  Status Finish(Arg&& arg) {
    return MakeScalar(std::move(type_), std::forward<Arg>(arg)).Value(&out_);
  }

  Status FinishWithBuffer() { return Finish(Buffer::FromString(std::string(s_))); }

  Result<std::shared_ptr<Scalar>> Finish() && {
    RETURN_NOT_OK(VisitTypeInline(*type_, this));
    return std::move(out_);
  }

  ScalarParseImpl(std::shared_ptr<DataType> type, util::string_view s)
      : type_(std::move(type)), s_(s) {}

  std::shared_ptr<DataType> type_;
  util::string_view s_;
  std::shared_ptr<Scalar> out_;
};

Result<std::shared_ptr<Scalar>> Scalar::Parse(const std::shared_ptr<DataType>& type,
                                              util::string_view s) {
  return ScalarParseImpl{type, s}.Finish();
}

namespace internal {
Status CheckBufferLength(const FixedSizeBinaryType* t, const std::shared_ptr<Buffer>* b) {
  return t->byte_width() == (*b)->size()
             ? Status::OK()
             : Status::Invalid("buffer length ", (*b)->size(), " is not compatible with ",
                               *t);
}
}  // namespace internal

namespace {
// CastImpl(...) assumes `to` points to a non null scalar of the correct type with
// uninitialized value

// helper for StringFormatter
template <typename Formatter, typename ScalarType>
std::shared_ptr<Buffer> FormatToBuffer(Formatter&& formatter, const ScalarType& from) {
  if (!from.is_valid) {
    return Buffer::FromString("null");
  }
  return formatter(from.value, [&](util::string_view v) {
    return Buffer::FromString(std::string(v));
  });
}

// error fallback
Status CastImpl(const Scalar& from, Scalar* to) {
  return Status::NotImplemented("casting scalars of type ", *from.type, " to type ",
                                *to->type);
}

// numeric to numeric
template <typename From, typename To>
Status CastImpl(const NumericScalar<From>& from, NumericScalar<To>* to) {
  to->value = static_cast<typename To::c_type>(from.value);
  return Status::OK();
}

// numeric to boolean
template <typename T>
Status CastImpl(const NumericScalar<T>& from, BooleanScalar* to) {
  constexpr auto zero = static_cast<typename T::c_type>(0);
  to->value = from.value != zero;
  return Status::OK();
}

// boolean to numeric
template <typename T>
Status CastImpl(const BooleanScalar& from, NumericScalar<T>* to) {
  to->value = static_cast<typename T::c_type>(from.value);
  return Status::OK();
}

// numeric to temporal
template <typename From, typename To>
typename std::enable_if<std::is_base_of<TemporalType, To>::value &&
                            !std::is_same<DayTimeIntervalType, To>::value &&
                            !std::is_same<MonthDayNanoIntervalType, To>::value,
                        Status>::type
CastImpl(const NumericScalar<From>& from, TemporalScalar<To>* to) {
  to->value = static_cast<typename To::c_type>(from.value);
  return Status::OK();
}

// temporal to numeric
template <typename From, typename To>
typename std::enable_if<std::is_base_of<TemporalType, From>::value &&
                            !std::is_same<DayTimeIntervalType, From>::value &&
                            !std::is_same<MonthDayNanoIntervalType, From>::value,
                        Status>::type
CastImpl(const TemporalScalar<From>& from, NumericScalar<To>* to) {
  to->value = static_cast<typename To::c_type>(from.value);
  return Status::OK();
}

// timestamp to timestamp
Status CastImpl(const TimestampScalar& from, TimestampScalar* to) {
  return util::ConvertTimestampValue(from.type, to->type, from.value).Value(&to->value);
}

template <typename TypeWithTimeUnit>
std::shared_ptr<DataType> AsTimestampType(const std::shared_ptr<DataType>& type) {
  return timestamp(checked_cast<const TypeWithTimeUnit&>(*type).unit());
}

// duration to duration
Status CastImpl(const DurationScalar& from, DurationScalar* to) {
  return util::ConvertTimestampValue(AsTimestampType<DurationType>(from.type),
                                     AsTimestampType<DurationType>(to->type), from.value)
      .Value(&to->value);
}

// time to time
template <typename F, typename ToScalar, typename T = typename ToScalar::TypeClass>
enable_if_time<T, Status> CastImpl(const TimeScalar<F>& from, ToScalar* to) {
  return util::ConvertTimestampValue(AsTimestampType<F>(from.type),
                                     AsTimestampType<T>(to->type), from.value)
      .Value(&to->value);
}

constexpr int64_t kMillisecondsInDay = 86400000;

// date to date
Status CastImpl(const Date32Scalar& from, Date64Scalar* to) {
  to->value = from.value * kMillisecondsInDay;
  return Status::OK();
}
Status CastImpl(const Date64Scalar& from, Date32Scalar* to) {
  to->value = static_cast<int32_t>(from.value / kMillisecondsInDay);
  return Status::OK();
}

// timestamp to date
Status CastImpl(const TimestampScalar& from, Date64Scalar* to) {
  ARROW_ASSIGN_OR_RAISE(
      auto millis,
      util::ConvertTimestampValue(from.type, timestamp(TimeUnit::MILLI), from.value));
  to->value = millis - millis % kMillisecondsInDay;
  return Status::OK();
}
Status CastImpl(const TimestampScalar& from, Date32Scalar* to) {
  ARROW_ASSIGN_OR_RAISE(
      auto millis,
      util::ConvertTimestampValue(from.type, timestamp(TimeUnit::MILLI), from.value));
  to->value = static_cast<int32_t>(millis / kMillisecondsInDay);
  return Status::OK();
}

// date to timestamp
template <typename D>
Status CastImpl(const DateScalar<D>& from, TimestampScalar* to) {
  int64_t millis = from.value;
  if (std::is_same<D, Date32Type>::value) {
    millis *= kMillisecondsInDay;
  }
  return util::ConvertTimestampValue(timestamp(TimeUnit::MILLI), to->type, millis)
      .Value(&to->value);
}

// string to any
template <typename ScalarType>
Status CastImpl(const StringScalar& from, ScalarType* to) {
  ARROW_ASSIGN_OR_RAISE(auto out,
                        Scalar::Parse(to->type, util::string_view(*from.value)));
  to->value = std::move(checked_cast<ScalarType&>(*out).value);
  return Status::OK();
}

// binary to string
Status CastImpl(const BinaryScalar& from, StringScalar* to) {
  to->value = from.value;
  return Status::OK();
}

// formattable to string
template <typename ScalarType, typename T = typename ScalarType::TypeClass,
          typename Formatter = internal::StringFormatter<T>,
          // note: Value unused but necessary to trigger SFINAE if Formatter is
          // undefined
          typename Value = typename Formatter::value_type>
Status CastImpl(const ScalarType& from, StringScalar* to) {
  to->value = FormatToBuffer(Formatter{from.type.get()}, from);
  return Status::OK();
}

Status CastImpl(const Decimal128Scalar& from, StringScalar* to) {
  auto from_type = checked_cast<const Decimal128Type*>(from.type.get());
  to->value = Buffer::FromString(from.value.ToString(from_type->scale()));
  return Status::OK();
}

Status CastImpl(const Decimal256Scalar& from, StringScalar* to) {
  auto from_type = checked_cast<const Decimal256Type*>(from.type.get());
  to->value = Buffer::FromString(from.value.ToString(from_type->scale()));
  return Status::OK();
}

Status CastImpl(const StructScalar& from, StringScalar* to) {
  std::stringstream ss;
  ss << '{';
  for (int i = 0; static_cast<size_t>(i) < from.value.size(); i++) {
    if (i > 0) ss << ", ";
    ss << from.type->field(i)->name() << ':' << from.type->field(i)->type()->ToString()
       << " = " << from.value[i]->ToString();
  }
  ss << '}';
  to->value = Buffer::FromString(ss.str());
  return Status::OK();
}

Status CastImpl(const UnionScalar& from, StringScalar* to) {
  const auto& union_ty = checked_cast<const UnionType&>(*from.type);
  std::stringstream ss;
  const Scalar* selected_value;
  if (from.type->id() == Type::DENSE_UNION) {
    selected_value = checked_cast<const DenseUnionScalar&>(from).value.get();
  } else {
    const auto& sparse_scalar = checked_cast<const SparseUnionScalar&>(from);
    selected_value = sparse_scalar.value[sparse_scalar.child_id].get();
  }
  ss << "union{" << union_ty.field(union_ty.child_ids()[from.type_code])->ToString()
     << " = " << selected_value->ToString() << '}';
  to->value = Buffer::FromString(ss.str());
  return Status::OK();
}

struct CastImplVisitor {
  Status NotImplemented() {
    return Status::NotImplemented("cast to ", *to_type_, " from ", *from_.type);
  }

  const Scalar& from_;
  const std::shared_ptr<DataType>& to_type_;
  Scalar* out_;
};

template <typename ToType>
struct FromTypeVisitor : CastImplVisitor {
  using ToScalar = typename TypeTraits<ToType>::ScalarType;

  FromTypeVisitor(const Scalar& from, const std::shared_ptr<DataType>& to_type,
                  Scalar* out)
      : CastImplVisitor{from, to_type, out} {}

  template <typename FromType>
  Status Visit(const FromType&) {
    return CastImpl(checked_cast<const typename TypeTraits<FromType>::ScalarType&>(from_),
                    checked_cast<ToScalar*>(out_));
  }

  // identity cast only for parameter free types
  template <typename T1 = ToType>
  typename std::enable_if<TypeTraits<T1>::is_parameter_free, Status>::type Visit(
      const ToType&) {
    checked_cast<ToScalar*>(out_)->value = checked_cast<const ToScalar&>(from_).value;
    return Status::OK();
  }

  Status Visit(const NullType&) { return NotImplemented(); }
  Status Visit(const DictionaryType&) { return NotImplemented(); }
  Status Visit(const ExtensionType&) { return NotImplemented(); }
};

struct ToTypeVisitor : CastImplVisitor {
  ToTypeVisitor(const Scalar& from, const std::shared_ptr<DataType>& to_type, Scalar* out)
      : CastImplVisitor{from, to_type, out} {}

  template <typename ToType>
  Status Visit(const ToType&) {
    FromTypeVisitor<ToType> unpack_from_type{from_, to_type_, out_};
    return VisitTypeInline(*from_.type, &unpack_from_type);
  }

  Status Visit(const NullType&) {
    if (from_.is_valid) {
      return Status::Invalid("attempting to cast non-null scalar to NullScalar");
    }
    return Status::OK();
  }

  Status Visit(const DictionaryType& dict_type) {
    auto& out = checked_cast<DictionaryScalar*>(out_)->value;
    ARROW_ASSIGN_OR_RAISE(auto cast_value, from_.CastTo(dict_type.value_type()));
    ARROW_ASSIGN_OR_RAISE(out.dictionary, MakeArrayFromScalar(*cast_value, 1));
    return Int32Scalar(0).CastTo(dict_type.index_type()).Value(&out.index);
  }

  Status Visit(const ExtensionType&) { return NotImplemented(); }
};

}  // namespace

Result<std::shared_ptr<Scalar>> Scalar::CastTo(std::shared_ptr<DataType> to) const {
  std::shared_ptr<Scalar> out = MakeNullScalar(to);
  if (is_valid) {
    out->is_valid = true;
    ToTypeVisitor unpack_to_type{*this, to, out.get()};
    RETURN_NOT_OK(VisitTypeInline(*to, &unpack_to_type));
  }
  return out;
}

void PrintTo(const Scalar& scalar, std::ostream* os) { *os << scalar.ToString(); }

}  // namespace arrow


text:
#ifndef COMPONENTCALLBACKGENERATOR_HPP
#define COMPONENTCALLBACKGENERATOR_HPP

#include <fstream>
#include <sstream>

#if defined(USING_GTEST)
#include "gtest/gtest_prod.h"
#else
#define FRIEND_TEST(x, y)
#endif
#include "ComponentInfo.hpp"
#include "Util.hpp"

using codegen::datamodel::ComponentInfo;

namespace codegen {

class ComponentCallbackGenerator
{
public:
  ComponentCallbackGenerator(const std::vector<std::string>& includeHeaders
                             , const std::vector<ComponentInfo>& componentInfos)
    : mHeaderIncludes(includeHeaders)
    , mComponentInfos(componentInfos)
    , mStrStream()
  {
    Substitute();
  }

  std::string GetString() const
  {
    return mStrStream.str();
  }

private:
  FRIEND_TEST(CodeGenTest, TestSubstitution);
  FRIEND_TEST(CodeGenTest, TestSubstitutionDynamic);
  FRIEND_TEST(CodeGenTest, TestMultipleComponents);

  void Substitute()
  {
    SubstituteHeader();
    SubstituteBody();
  }

  void SubstituteHeader()
  {
    mStrStream << std::endl
               << R"(#include <vector>)" << std::endl
               << R"(#include <cppmicroservices/ServiceInterface.h>)" << std::endl
               << R"(#include "cppmicroservices/servicecomponent/detail/ComponentInstanceImpl.hpp")" << std::endl;

    for (const auto& header : mHeaderIncludes)
    {
      mStrStream << util::Substitute(R"(#include "{0}")", header) << std::endl;
    }
    mStrStream << std::endl
               << "namespace sc = cppmicroservices::service::component;" << std::endl
               << "namespace scd = cppmicroservices::service::component::detail;" << std::endl;
  }

  void SubstituteBody()
  {
    for (const auto& componentInfo : mComponentInfos)
    {
      // Generate the factory function for creating each component
      mStrStream << std::endl
                 << util::Substitute(R"(extern "C" US_ABI_EXPORT scd::ComponentInstance* NewInstance_{0}())"
                                     , datamodel::GetComponentNameStr(componentInfo)) << std::endl
                 << "{" << std::endl;

      auto isReferencesEmpty = componentInfo.references.empty();
      if(false == isReferencesEmpty)
      {
        mStrStream << util::Substitute("  std::vector<std::shared_ptr<scd::Binder<{0}>>> binders;"
                                       , componentInfo.implClassName)
                   << std::endl;
      }

      for(const auto& ref : componentInfo.references)
      {
        if ((false == componentInfo.injectReferences)
            || (ref.policy == "dynamic"))
        {
          mStrStream << "  binders.push_back("
                     << util::Substitute(datamodel::GetReferenceBinderStr(ref, componentInfo.injectReferences)
                                         , componentInfo.implClassName)
                     << ");"
                     << std::endl;
        }
      }

      mStrStream << "  scd::ComponentInstance* componentInstance = new (std::nothrow) scd::ComponentInstanceImpl<"
                 << componentInfo.implClassName
                 << ", std::tuple<"
                 << datamodel::GetServiceInterfacesStr(componentInfo.service)
                 << ">";

      if (true == isReferencesEmpty)
      {
        mStrStream << ">();";
      }
      else {
        mStrStream << datamodel::GetCtorInjectedRefTypes(componentInfo)
                   << ">("
                   << datamodel::GetCtorInjectedRefNames(componentInfo)
                   << ", binders"
                   << ");";
      }

      mStrStream << std::endl
                 << std::endl
                 << "  return componentInstance;" << std::endl
                 << "}" << std::endl;

      // Create deleter function for each component.
      mStrStream << std::endl
                 << util::Substitute(R"(extern "C" US_ABI_EXPORT void DeleteInstance_{0}(scd::ComponentInstance* componentInstance))"
                                     , datamodel::GetComponentNameStr(componentInfo)) << std::endl
                 << "{" << std::endl
                 << "  delete componentInstance;" << std::endl
                 << "}" << std::endl
                 << std::endl;
    }
  }

  const std::vector<std::string> mHeaderIncludes;
  const std::vector<ComponentInfo> mComponentInfos;
  std::stringstream mStrStream;
};

} // namespace codegen
#endif

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

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

#### Published in
Mycotaxon 83: 47 (2002)

#### Original name
Agaricus oniscus Fr., 1818

### Remarks
null


text:
<?php
// autogenerated file 30.09.2013 15:20
// $Id: $
// $Log: $
//
require_once 'EbatNs_FacetType.php';

/**
 * The offer type of the Best Offer.
 *
 * @link http://developer.ebay.com/DevZone/XML/docs/Reference/eBay/types/BestOfferTypeCodeType.html
 *
 * @property string BuyerBestOffer
 * @property string BuyerCounterOffer
 * @property string SellerCounterOffer
 * @property string CustomCode
 */
class BestOfferTypeCodeType extends EbatNs_FacetType
{
	const CodeType_BuyerBestOffer = 'BuyerBestOffer';
	const CodeType_BuyerCounterOffer = 'BuyerCounterOffer';
	const CodeType_SellerCounterOffer = 'SellerCounterOffer';
	const CodeType_CustomCode = 'CustomCode';

	/**
	 * @return
	 */
	function __construct()
	{
		parent::__construct('BestOfferTypeCodeType', 'urn:ebay:apis:eBLBaseComponents');

	}
}

$Facet_BestOfferTypeCodeType = new BestOfferTypeCodeType();

?>


text:
module Octopress
  class Draft < Post

    def set_default_options
      @options['type']      ||= 'draft'
      @options['layout']      = @config['post_layout']
      @options['dir']       ||= ''
      @options['extension'] ||= @config['post_ext']
      @options['template']  ||= @config['post_template']

      if @options['date']
        @options['date'] = convert_date @options['date']
      end
    end

    def path
      name = "#{title_slug}.#{extension}"
      File.join(site.source, '_drafts', name)
    end

    # -----
    # Methods for publishing drafts
    # -----

    # Create a new post from draft file
    #
    # Sets post options based on draft file contents
    # and options passed to the publish command
    #
    def publish
      @options['date'] ||= read_draft_date || Time.now.iso8601

      post_options = {
        'title'   => read_draft_title,
        'date'    => @options['date'],
        'slug'    => publish_slug,
        'content' => read_draft_content,
        'dir'     => @options['dir'],
        'type'    => 'post from draft'
      }

      # Create a new post file
      #
      Post.new(site, post_options).write

      # Remove the old draft file
      #
      FileUtils.rm @options['path']

    end

    # Get the slug from options or filename
    #
    def publish_slug
      @options['slug'] || File.basename(@options['path'], '.*')
    end

    # Reads the file from _drafts/[path]
    #
    def read
      if @draft_content
        @draft_content
      else
        file = @options['path']
        abort "File #{file} not found." if !File.exist? file
        @draft_content = File.open(file).read
      end
    end

    # Get title from draft post file
    #
    def read_draft_title
      match = read.match(/title:\s+(.+)?$/)
      match[1] if match
    end

    # read_draft_date
    #
    def read_draft_date
      match = read.match(/date:\s+(\d.+)$/)
      match[1] if match
    end

    # Get content from draft post file
    # also update the draft's date configuration
    #
    def read_draft_content
      if @options['date']
        # remove date if it exists
        content = read.sub(/date:.*$\n/, "")

        # Insert date after title
        content.sub(/(title:.+$)/i, '\1'+"\ndate: #{@options['date']}")
      else
        read
      end
    end

    def default_template
      'draft'
    end

    # Draft template defaults
    #
    def default_content

      if @options['date']
        front_matter %w{layout title date}
      else
        front_matter %w{layout title}
      end
    end
  end
end


text:
namespace Hospital.Server.Controllers
{
    using Data.Repository;
    using System.Web.Mvc;
    using System.Linq;
    using AutoMapper.QueryableExtensions;
    using Models;
    using DatabaseModels;
    using Data.Constants;

    [Authorize]
    public class ClinicalResultsController : BaseController
    {

        public ClinicalResultsController(IUnitOfWork data): base(data)
        {
        }

        public ActionResult GetClinicalResult()
        {
            var result = Data.ClinicalResults
                .All()
                .Where(x => x.Patient.Id == this.UserProfile.Id)
                .OrderByDescending(x => x.AddedOn)
                .Project()
                .To<PatientResultViewModel>()
                .ToList();

            return View(result);
        }

        public ActionResult DownloadResult(int id)
        {
            var clinicalResult = this.Data.ClinicalResults.GetById(id);
            if (clinicalResult.File != null)
            {
                PDF file = clinicalResult.File;

                return File(file.Content, "text/plain", file.FileName);
            }
            else
            {
                PDF file = new PDF()
                {
                    Path = PathConstants.PathPDF,
                    FileName = "AsiaBecheva.pdf"
                };

                return File(file.Path + file.FileName, "text/plain");
            }
        }
    }
}


text:
var self = require('sdk/self');
var pageMod = require('sdk/page-mod');

pageMod.PageMod({
    include: "*.youtube.com",
    contentScriptFile: self.data.url("content.js")
});


text:
//#define MV_DEBUG

#import "RBLMainViewController.h"
#import "RBLControlViewController.h"
#import "RBLDetailViewController.h"
#import <KiiSDK/KiiBucket.h>
#import <KiiSDK/Kii.h>
#import "KiiFileUploadViewController.h"
#import "KiiViewUtilities.h"
#import "KiiAppConstants.h"
#import "KiiCommonUtilities.h"

NSString * const  UUIDPrefKey = @"UUIDPrefKey";

@implementation RBLMainViewController
@synthesize ble;
RBLControlViewController *cv;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.

    ble = [[BLE alloc] init];
    [ble controlSetup];
    ble.delegate = self;

    self.mDevices = [[NSMutableArray alloc] init];
    self.mDevicesName = [[NSMutableArray alloc] init];

    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"])
    {
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:UUIDPrefKey];
    }

    //Retrieve saved UUID from system
    self.lastUUID = [[NSUserDefaults standardUserDefaults] objectForKey:UUIDPrefKey];
    if ([self.lastUUID isEqualToString:@""])
    {
        [btnConnectLast setEnabled:NO];
    }
    else
    {
        [btnConnectLast setEnabled:YES];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    //[self.navigationController setNavigationBarHidden:YES animated:animated];

    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    //[self.navigationController setNavigationBarHidden:NO animated:animated];
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showDevice"])
    {
        RBLDetailViewController *vc = [segue destinationViewController];
        vc.BLEDevices = self.mDevices;
        vc.BLEDevicesName = self.mDevicesName;
        vc.ble = ble;
    }
    else if ([[segue identifier] isEqualToString:@"gotoControlVC"])
    {
        cv = [segue destinationViewController];
        cv.ble = ble;
    }
}

-(void) connectionTimer:(NSTimer *)timer
{
    showAlert = YES;
    [btnConnect setEnabled:YES];

    self.lastUUID = [[NSUserDefaults standardUserDefaults] objectForKey:UUIDPrefKey];

    if ([self.lastUUID isEqualToString:@""])
    {
        [btnConnectLast setEnabled:NO];
    }
    else
    {
        [btnConnectLast setEnabled:YES];
    }

    if (ble.peripherals.count > 0)
    {
        if(isFindingLast)
        {
            int i;
            for (i = 0; i < ble.peripherals.count; i++)
            {
                CBPeripheral *p = [ble.peripherals objectAtIndex:i];

                if (p.UUID != NULL)

                {
                    //Comparing UUIDs and call connectPeripheral is matched
                    if([self.lastUUID isEqualToString:[self getUUIDString:p.UUID]])
                    {
                        showAlert = NO;
                        [ble connectPeripheral:p];
                        [self performSegueWithIdentifier:@"showDevice" sender:self];
                    }
                }
            }
        }
        else
        {
            [self.mDevices removeAllObjects];
            [self.mDevicesName removeAllObjects];

            int i;
            for (i = 0; i < ble.peripherals.count; i++)
            {
                CBPeripheral *p = [ble.peripherals objectAtIndex:i];

                if (p.UUID != NULL)
                {
                    [self.mDevices insertObject:[self getUUIDString:p.UUID] atIndex:i];
                    if (p.name != nil) {
                        [self.mDevicesName insertObject:p.name atIndex:i];
                    } else {
                        [self.mDevicesName insertObject:@"RedBear Device" atIndex:i];
                    }
                }
                else
                {
                    [self.mDevices insertObject:@"NULL" atIndex:i];
                    [self.mDevicesName insertObject:@"RedBear Device" atIndex:i];
                }
            }
            showAlert = NO;
            [self performSegueWithIdentifier:@"showDevice" sender:self];
        }
    }

    if (showAlert == YES) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                        message:@"No BLE Device(s) found."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    }

    [activityScanning stopAnimating];
}

- (IBAction)mCreateKiiObjectButton:(id)sender {
    KiiBucket *bucket = [Kii bucketWithName:KII_APP_BUCKET_NAME];
    KiiObject *object = [bucket createObject];
    [object setObject:[KiiUser currentUser].username forKey:@"username"];
    [object saveWithBlock:^(KiiObject *retObject, NSError *retError) {
        [KiiViewUtilities hideProgressHUD:self.view];
        if (retError) {
            [KiiViewUtilities showFailureHUD:@"KiiObject creation is failed." withView:self.view];
        } else {
            self.kiiObject = retObject;
            [self performSegueWithIdentifier:@"CreateObjectCompleted" sender:self];
        }
    }];
    [KiiViewUtilities showProgressHUD:@"Create KiiObject..." withView:self.view];
}

- (IBAction)btnConnectClicked:(id)sender
{
    if (ble.activePeripheral)
        if(ble.activePeripheral.state == CBPeripheralStateConnected)
        {
            [[ble CM] cancelPeripheralConnection:[ble activePeripheral]];
            return;
        }

    if (ble.peripherals)
        ble.peripherals = nil;

    [btnConnect setEnabled:false];
    [btnConnectLast setEnabled:NO];
    [ble findBLEPeripherals:3];

    [NSTimer scheduledTimerWithTimeInterval:(float)3.0 target:self selector:@selector(connectionTimer:) userInfo:nil repeats:NO];

    isFindingLast = false;
    [activityScanning startAnimating];
}

- (IBAction)lastClick:(id)sender {
    if (ble.peripherals) {
        ble.peripherals = nil;
    }

    [btnConnect setEnabled:false];
    [btnConnectLast setEnabled:NO];
    [ble findBLEPeripherals:3];

    [NSTimer scheduledTimerWithTimeInterval:(float)3.0 target:self selector:@selector(connectionTimer:) userInfo:nil repeats:NO];

    isFindingLast = true;
    [activityScanning startAnimating];
}

-(void) bleDidConnect
{
    NSLog(@"->DidConnect");

    self.lastUUID = [self getUUIDString:ble.activePeripheral.UUID];
    [[NSUserDefaults standardUserDefaults] setObject:self.lastUUID forKey:UUIDPrefKey];
    [[NSUserDefaults standardUserDefaults] synchronize];

    self.lastUUID = [[NSUserDefaults standardUserDefaults] objectForKey:UUIDPrefKey];
    if ([self.lastUUID isEqualToString:@""]) {
        [btnConnectLast setEnabled:NO];
    } else {
        [btnConnectLast setEnabled:YES];
    }

    [activityScanning stopAnimating];
    [self performSegueWithIdentifier:@"gotoControlVC" sender:self];
}

- (void)bleDidDisconnect
{
    NSLog(@"->DidDisconnect");

    [activityScanning stopAnimating];
    [self.navigationController popToRootViewControllerAnimated:true];
}

-(void) bleDidReceiveData:(unsigned char *)data length:(int)length
{
#if defined(MV_DEBUG)
    NSLog(@"->DidReceiveData");
#endif

    if (cv != nil)
    {
        [cv processData:data length:length];
    }
}

-(void) bleDidUpdateRSSI:(NSNumber *) rssi
{
}

-(NSString *)getUUIDString:(CFUUIDRef)ref {
    NSString *str = [NSString stringWithFormat:@"%@", ref];
    return [[NSString stringWithFormat:@"%@", str] substringWithRange:NSMakeRange(str.length - 36, 36)];
}

@end


text:
namespace Orchard.AuditTrail.Services.Models {
    public enum DiffType {
        Change,
        Addition
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shyamu.translocwidget" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application xmlns:tools="http://schemas.android.com/tools"
        tools:replace="android:icon"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.MyTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".AboutActivity" />

        <receiver android:name=".widget.Provider" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_info" />
        </receiver>

    </application>

</manifest>


text:
package docomo

import "net/url"

const (
	// KnowledgeQAURL docomoAPIの知識Q&Aのmethod
	KnowledgeQAURL = "/knowledgeQA/v1/ask"
)

// ResponseCode 知識Q&Aのレスポンスコード
type ResponseCode string

const (
	// OkResponseCode 質問結果あり
	OkResponseCode ResponseCode = "S020000"
	// NoResponseCode 質問結果なし
	NoResponseCode ResponseCode = "S020011"
)

// KnowledgeQAService API docs: https://dev.smt.docomo.ne.jp/?p=docs.api.page&api_docs_id=6
type KnowledgeQAService struct {
	client *Client
}

// KnowledgeQARequest 知識Q&Aのリクエスト
type KnowledgeQARequest struct {
	QAText string `json:"q"`
}

// KnowledgeQAResponse 知識Q&Aのレスポンス
type KnowledgeQAResponse struct {
	Code    ResponseCode `json:"code"`
	Answers []struct {
		AnswerText string `json:"answerText"`
		LinkText   string `json:"linkText"`
		LinkURL    string `json:"linkUrl"`
		Rank       string `json:"rank"`
	} `json:"answers"`
	Message struct {
		TextForDisplay string `json:"textForDisplay"`
		TextForSpeech  string `json:"textForSpeech"`
	} `json:"message"`
}

// Success 質問成功
func (q KnowledgeQAResponse) Success() bool {
	return q.Code == OkResponseCode
}

// Get docomoAPIを呼び出して結果を返す
func (q *KnowledgeQAService) Get(req KnowledgeQARequest) (*KnowledgeQAResponse, error) {

	val := url.Values{}
	val.Set("q", req.QAText)

	var knowRes KnowledgeQAResponse
	res, err := q.client.get(KnowledgeQAURL, val, &knowRes)
	if err != nil {
		return nil, err
	}

	defer res.Body.Close()

	return &knowRes, nil
}


text:
package com.strv.rxjavademo.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import com.strv.rxjavademo.R;
import com.strv.rxjavademo.adapter.CardsGithubAdapter;
import com.strv.rxjavademo.cache.RequestCache;
import com.strv.rxjavademo.model.GithubUserModel;
import com.strv.rxjavademo.service.GithubService;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit.CallAdapter;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by adamcerny on 24/08/15.
 */
public class RetrofitCustomCacheFragment extends BaseFragment
{
	@Bind(R.id.fragment_retrofit_example_recycler)
	RecyclerView mRecyclerView;

	@Bind(R.id.fragment_retrofit_example_progress)
	ProgressBar mProgressBar;

	private CardsGithubAdapter mCardAdapter;

	private RequestCache mCache;

	public static RetrofitCustomCacheFragment newInstance()
	{
		RetrofitCustomCacheFragment fragment = new RetrofitCustomCacheFragment();
		return fragment;
	}

	public RetrofitCustomCacheFragment()
	{
		super();
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);

		renderView();
		handleCache();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
	{
		View layout = inflater.inflate(R.layout.fragment_retrofit, container, false);
		ButterKnife.bind(this, layout);
		return layout;
	}

	@OnClick(R.id.fragment_retrofit_lambda_example_button)
	public void clickLoadLambdaData()
	{
		if(mProgressBar.getVisibility() == View.VISIBLE)
			return;

		mCardAdapter.clearAdapter();

		GithubService service = new Retrofit.Builder()
				.baseUrl(GithubService.BASE_ENDPOINT)
				.addConverterFactory(GsonConverterFactory.create())
				.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
				.build()
				.create(GithubService.class);

		mProgressBar.setVisibility(View.VISIBLE);

		for(String username : RetrofitCustomCacheFragment.getGithubusernames)
		{
			Observable<GithubUserModel> request = service.getUser(username).cache();
			mCache.saveRequest(request);

			mCompositeSubscription.add(
				request
					.subscribeOn(Schedulers.io())
					.observeOn(AndroidSchedulers.mainThread())
					.delay(2, TimeUnit.SECONDS)
					.observeOn(AndroidSchedulers.mainThread())
					.subscribe(item ->
					{
						mCardAdapter.addGithubItem(item);
						mCache.saveData(item);
						mCache.deleteRequest(request);

						if(mCardAdapter.getItemCount() == RetrofitCustomCacheFragment.getGithubusernames.size())
						{
							mProgressBar.setVisibility(View.GONE);
						}
					},
					error ->
					{
						mProgressBar.setVisibility(View.GONE);
						System.out.println("FUCK : error is : " + error.getLocalizedMessage());
					},
					() -> {
					}
				)
			);
		}
	}

	@OnClick(R.id.fragment_retrofit_rxandroid_example_button)
	public void clickLoadRxAndroidData()
	{
		if(mProgressBar.getVisibility() == View.VISIBLE)
			return;

		mCardAdapter.clearAdapter();

		GithubService service = new Retrofit.Builder()
				.baseUrl(GithubService.BASE_ENDPOINT)
				.addConverterFactory(GsonConverterFactory.create())
				.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
				.build()
				.create(GithubService.class);

		mProgressBar.setVisibility(View.VISIBLE);

		for(String username : RetrofitCustomCacheFragment.getGithubusernames)
		{
			Observable<GithubUserModel> request = service.getUser(username).cache();
			mCache.saveRequest(request);

			mCompositeSubscription.add(
				request
					.subscribeOn(Schedulers.io())
					.observeOn(AndroidSchedulers.mainThread())
					.delay(2, TimeUnit.SECONDS)
					.observeOn(AndroidSchedulers.mainThread())
					.subscribe(new Subscriber<GithubUserModel>()
					{
						@Override
						public void onNext(GithubUserModel item)
						{
							mCardAdapter.addGithubItem(item);
							mCache.saveData(item);
							mCache.deleteRequest(request);

							if(mCardAdapter.getItemCount() == RetrofitCustomCacheFragment.getGithubusernames.size())
							{
								mProgressBar.setVisibility(View.GONE);
							}
						}

						@Override
						public void onCompleted()
						{
						}

						@Override
						public void onError(Throwable e)
						{
							mProgressBar.setVisibility(View.GONE);
							System.out.println("FUCK : error is : " + e.getLocalizedMessage());
						}
					})
			);
		}
	}

	private void renderView()
	{
		mRecyclerView.setHasFixedSize(true);
		mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
		mCardAdapter = new CardsGithubAdapter();
		mRecyclerView.setAdapter(mCardAdapter);
	}

	private void handleCache()
	{
		mCache = RequestCache.getInstance();
		if(mCache.hasRequests())
		{
			reSubscribe();
		}

		if(mCache.hasData())
		{
			mCardAdapter.addGithubItems(mCache.getData());
		}
	}

	private void reSubscribe()
	{
		mProgressBar.setVisibility(View.VISIBLE);

		for(Observable<GithubUserModel> request : mCache.getRequests())
		{
			mCompositeSubscription.add(
				request
					.subscribeOn(Schedulers.io())
					.observeOn(AndroidSchedulers.mainThread())
					.subscribe(item ->
					{
						mCardAdapter.addGithubItem(item);
						mCache.deleteRequest(request);
						mCache.saveData(item);

						if(mCardAdapter.getItemCount() == RetrofitCustomCacheFragment.getGithubusernames.size())
						{
							mProgressBar.setVisibility(View.GONE);
						}
					},
					error ->
					{
						mProgressBar.setVisibility(View.GONE);
						System.out.println("FUCK : error is : " + error.getLocalizedMessage());
					},
					() -> {
					}
				)
			);
		}

	}

	public static List<String> getGithubusernames = new ArrayList<String>() {{
		add("strvcom");
		add("linkedin");
		add("tumblr");
		add("square");
		add("google");
		add("torvalds");
		add("marak");
		add("facebook");
		add("rails");
	}};
}


text:
namespace fst {

// Applies a FST model as a discriminative model to weighted input
// `ifst`. `A` is an arc type with tropical weight of all the
// input/output FSTs.
//
// In general, consider `ifst` an unnormalized probability
// distribution between its input X and output Y, P(X, Y); and `lfst`
// a group of unnormalized probability distributions of all its output
// Z for every input Y, Q(Z|Y). `normalize` controls whether Q is
// normalized for every Y before chaining with P(X, Y). I.e., for a
// path (X, Y, Z) in `ofst` (where Y is hidden),
//
// - When `normalize` is true, its weight is P(X, Y) Q(Z|Y) / sum_z Q(z|Y);
// - When `normalize` is false, its weight is P(X, Y) Q(Z|Y).
template <class A>
void LogLinearApply(const Fst<A> &ifst, const Fst<A> &lfst, MutableFst<A> *ofst,
                    bool normalize = true) {
  LogLinearApply<A, LogArc>(ifst, lfst, ofst, normalize);
}

// This version gives finer control over the arc type (`B`) to be used
// in normalization. `B` is an arc type with log weight (e.g. `LogArc`
// or `Log64Arc`).
template <class A, class B>
void LogLinearApply(const Fst<A> &ifst, const Fst<A> &lfst, MutableFst<A> *ofst,
                    bool normalize = true) {
  if (normalize) {
    VectorFst<A> unnormalized_ofst, rescored_ifsa;
    Compose(ifst, lfst, &unnormalized_ofst);
    {
      VectorFst<A> tropical_ifsa(unnormalized_ofst);
      Project(&tropical_ifsa, PROJECT_INPUT);
      {
        VectorFst<B> minimal_log_ifsa;
        {
          VectorFst<B> log_ifsa;
          ArcMap(tropical_ifsa, &log_ifsa, WeightConvertMapper<A, B>());
          RmEpsilon(&log_ifsa);
          Determinize(log_ifsa, &minimal_log_ifsa);
        }
        Minimize(&minimal_log_ifsa);
        ArcMap(&minimal_log_ifsa, InvertWeightMapper<B>());
        ArcMap(minimal_log_ifsa, &tropical_ifsa, WeightConvertMapper<B, A>());
      }
      ArcSort(&tropical_ifsa, OLabelCompare<A>());
      Compose(tropical_ifsa, ifst, &rescored_ifsa);
    }
    ArcSort(&rescored_ifsa, OLabelCompare<A>());
    Compose(rescored_ifsa, unnormalized_ofst, ofst);
  } else {
    Compose(ifst, lfst, ofst);
  }
}

}  // namespace fst

#endif  // FST_EXTENSIONS_LINEAR_LOGLINEAR_APPLY_H_


text:
package advent2021;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Task6 {

    public static void main(String[] args) throws IOException {
        long[] ageCounts = new long[9];
        for (String s : new BufferedReader(new InputStreamReader(System.in)).readLine().split(",")) {
            ageCounts[Integer.parseInt(s)]++;
        }
        for (int i = 0; i < 80; i++) {
            long newFish = ageCounts[0];
            System.arraycopy(ageCounts, 1, ageCounts, 0, 8);
            ageCounts[6] += newFish;
            ageCounts[8] = newFish;
        }
        System.out.println(Arrays.stream(ageCounts).sum());
    }
}


text:
from __future__ import print_function, absolute_import, division, unicode_literals

from .compat import text_type
from .anchor import Anchor

if False:  # MYPY
    from typing import Text, Any, Dict, List  # NOQA

__all__ = [
    "ScalarString",
    "LiteralScalarString",
    "FoldedScalarString",
    "SingleQuotedScalarString",
    "DoubleQuotedScalarString",
    "PlainScalarString",
    # PreservedScalarString is the old name, as it was the first to be preserved on rt,
    # use LiteralScalarString instead
    "PreservedScalarString",
]

class ScalarString(text_type):
    __slots__ = Anchor.attrib

    def __new__(cls, *args, **kw):
        # type: (Any, Any) -> Any
        anchor = kw.pop("anchor", None)  # type: ignore
        ret_val = text_type.__new__(cls, *args, **kw)  # type: ignore
        if anchor is not None:
            ret_val.yaml_set_anchor(anchor, always_dump=True)
        return ret_val

    def replace(self, old, new, maxreplace=-1):
        # type: (Any, Any, int) -> Any
        return type(self)((text_type.replace(self, old, new, maxreplace)))

    @property
    def anchor(self):
        # type: () -> Any
        if not hasattr(self, Anchor.attrib):
            setattr(self, Anchor.attrib, Anchor())
        return getattr(self, Anchor.attrib)

    def yaml_anchor(self, any=False):
        # type: (bool) -> Any
        if not hasattr(self, Anchor.attrib):
            return None
        if any or self.anchor.always_dump:
            return self.anchor
        return None

    def yaml_set_anchor(self, value, always_dump=False):
        # type: (Any, bool) -> None
        self.anchor.value = value
        self.anchor.always_dump = always_dump

class LiteralScalarString(ScalarString):
    __slots__ = "comment"  # the comment after the | on the first line

    style = "|"

    def __new__(cls, value, anchor=None):
        # type: (Text, Any) -> Any
        return ScalarString.__new__(cls, value, anchor=anchor)

PreservedScalarString = LiteralScalarString

class FoldedScalarString(ScalarString):
    __slots__ = ("fold_pos", "comment")  # the comment after the > on the first line

    style = ">"

    def __new__(cls, value, anchor=None):
        # type: (Text, Any) -> Any
        return ScalarString.__new__(cls, value, anchor=anchor)

class SingleQuotedScalarString(ScalarString):
    __slots__ = ()

    style = "'"

    def __new__(cls, value, anchor=None):
        # type: (Text, Any) -> Any
        return ScalarString.__new__(cls, value, anchor=anchor)

class DoubleQuotedScalarString(ScalarString):
    __slots__ = ()

    style = '"'

    def __new__(cls, value, anchor=None):
        # type: (Text, Any) -> Any
        return ScalarString.__new__(cls, value, anchor=anchor)

class PlainScalarString(ScalarString):
    __slots__ = ()

    style = ""

    def __new__(cls, value, anchor=None):
        # type: (Text, Any) -> Any
        return ScalarString.__new__(cls, value, anchor=anchor)

def preserve_literal(s):
    # type: (Text) -> Text
    return LiteralScalarString(s.replace("\r\n", "\n").replace("\r", "\n"))

def walk_tree(base, map=None):
    # type: (Any, Any) -> None
    """
    the routine here walks over a simple yaml tree (recursing in
    dict values and list items) and converts strings that
    have multiple lines to literal scalars

    You can also provide an explicit (ordered) mapping for multiple transforms
    (first of which is executed):
        map = .compat.ordereddict
        map['\n'] = preserve_literal
        map[':'] = SingleQuotedScalarString
        walk_tree(data, map=map)
    """
    from .compat import string_types
    from .compat import MutableMapping, MutableSequence  # type: ignore

    if map is None:
        map = {"\n": preserve_literal}

    if isinstance(base, MutableMapping):
        for k in base:
            v = base[k]  # type: Text
            if isinstance(v, string_types):
                for ch in map:
                    if ch in v:
                        base[k] = map[ch](v)
                        break
            else:
                walk_tree(v)
    elif isinstance(base, MutableSequence):
        for idx, elem in enumerate(base):
            if isinstance(elem, string_types):
                for ch in map:
                    if ch in elem:  # type: ignore
                        base[idx] = map[ch](elem)
                        break
            else:
                walk_tree(elem)


text:
import os
import subprocess
import yaml

from cliff import command as cmd
from fuelclient.objects import environment as environment_obj

from octane.helpers import network
from octane import magic_consts
from octane.util import env as env_util
from octane.util import maintenance
from octane.util import ssh

def start_corosync_services(env):
    node = next(env_util.get_controllers(env))
    status_out, _ = ssh.call(['crm', 'resource', 'list'],
                             stdout=ssh.PIPE,
                             node=node)
    for service in maintenance.parse_crm_status(status_out):
        while True:
            try:
                ssh.call(['crm', 'resource', 'start', service],
                         node=node)
            except subprocess.CalledProcessError:
                pass
            else:
                break

def start_upstart_services(env):
    controllers = list(env_util.get_controllers(env))
    for node in controllers:
        sftp = ssh.sftp(node)
        try:
            svc_file = sftp.open('/root/services_list')
        except IOError:
            raise
        else:
            with svc_file:
                to_start = svc_file.read().splitlines()
        for service in to_start:
            ssh.call(['start', service], node=node)

def disconnect_networks(env):
    controllers = list(env_util.get_controllers(env))
    for node in controllers:
        deployment_info = env_util.get_astute_yaml(env, node)
        network.delete_patch_ports(node, deployment_info)

def connect_to_networks(env):
    deployment_info = []
    controllers = list(env_util.get_controllers(env))
    backup_path = os.path.join(magic_consts.FUEL_CACHE,
                               'deployment_{0}.orig'
                               .format(env.id))
    for filename in os.listdir(backup_path):
        filepath = os.path.join(backup_path, filename)
        with open(filepath) as info_file:
            info = yaml.safe_load(info_file)
            deployment_info.append(info)
    for node in controllers:
        for info in deployment_info:
            if (info['role'] in ('primary-controller', 'controller')
                    and info['uid'] == str(node.id)):
                network.delete_overlay_networks(node, info)
                network.create_patch_ports(node, info)

def update_neutron_config(env):
    controllers = list(env_util.get_controllers(env))
    tenant_file = '%s/env-%s-service-tenant-id' % (magic_consts.FUEL_CACHE,
                                                   str(env.id))
    with open(tenant_file) as f:
        tenant_id = f.read()

    sed_script = 's/^(nova_admin_tenant_id )=.*/\\1 = %s/' % (tenant_id,)
    for node in controllers:
        ssh.call(['sed', '-re', sed_script, '-i', '/etc/neutron/neutron.conf'],
                 node=node)

def upgrade_control_plane(orig_id, seed_id):
    orig_env = environment_obj.Environment(orig_id)
    seed_env = environment_obj.Environment(seed_id)
    update_neutron_config(seed_env)
    start_corosync_services(seed_env)
    start_upstart_services(seed_env)
    disconnect_networks(orig_env)
    connect_to_networks(seed_env)

class UpgradeControlPlaneCommand(cmd.Command):
    """Switch control plane to the seed environment"""

    def get_parser(self, prog_name):
        parser = super(UpgradeControlPlaneCommand, self).get_parser(prog_name)
        parser.add_argument(
            'orig_id', type=int, metavar='ORIG_ID',
            help="ID of original environment")
        parser.add_argument(
            'seed_id', type=int, metavar='SEED_ID',
            help="ID of seed environment")
        return parser

    def take_action(self, parsed_args):
        upgrade_control_plane(parsed_args.orig_id, parsed_args.seed_id)


text:
[![build status](https://travis-ci.org/refined-bitbucket/refined-bitbucket.svg?branch=test-it)](https://travis-ci.org/refined-bitbucket/refined-bitbucket)
-
[![downloads](https://img.shields.io/chrome-web-store/d/afppminkfnfngihdocacbgeajbbdklkf.svg)](https://chrome.google.com/webstore/detail/refined-bitbucket/afppminkfnfngihdocacbgeajbbdklkf?utm_source=chrome-ntp-icon)
-
[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)

![Refined BitBucket](./logo-full.svg)

We all know BitBucket lacks some features that we have in other platforms like GitHub, GitLab and others. Originally inspired on Sindre Sorhus' [Refined Github](https://github.com/sindresorhus/refined-github) extension, _refined-bitbucket_ is born as a collaborative project by a few developers to improve upon those holes, and even add some additional functionality that will enhance the overall user experience.

[Subscribe to this issue if you would like to receive e-mail notifications on updates](https://github.com/refined-bitbucket/refined-bitbucket/issues/182).

## Current features

-   Adds syntax highlighting for pull requests and commits. See the full list of enabled languages [here][prismjs-languages], and then [here][language-ext]. [Test them here](http://prismjs.com/test.html). Missing any language? [Let me know](https://github.com/refined-bitbucket/refined-bitbucket/issues) or submit a pull request!
-   Double click on a word to highlight all occurrences.
-   ~~Block pull request merging without a minimum number of approvals (defaults to 2 minimum approvals).~~ Removed. [Implemented natively by Bitbucket with "merge checks"](https://confluence.atlassian.com/bitbucketserver/checks-for-merging-pull-requests-776640039.html)
-   Key binding feature, which allows for quicker navigation through pull requests.
-   Button to collapse pull request descriptions.
-   Button to collapse diffs in Pull Request and Commits view.
-   Autocollapse:
    -   Add filename patterns in the Options page that you would like the extension to collapse automatically when the pull request or commit loads.
    -   Deleted files are automatically collapsed.
-   Diff Ignore. Add filename patterns in the Options page that you would like the extension to completely remove when the pull request or commit loads.
-   Counters for open or active branches and pull requests in the sidebar navigation menu.
-   Button to load all failed diffs in pull request and commit view.
-   Adds 'Create Pull Request' link to the 'Compare branches and tags' page.
-   Choose a default merge strategy for your pull requests. [Also implemented natively by Bitbucket per project](https://bitbucket.org/site/master/issues/13895/default-merge-strategy#comment-45364593)
-   Check the "Close anchor branch" checkbox by default when creating or editing pull requests.
-   Add source branch, linkify branch names, add creation date and last person to interact with the pull request (commit, comment or approval) to each pull request row in pull request list.
-   Don't carry pluses and minuses to clipboard when copying diff's contents.
-   Badge with the number of commits of the current pull request next to the "Commits" tab.
-   Set custom tab indentation size of code (Bitbucket defaults to 8 spaces) when viewing commits/pull requests.
-   Insert "Comments" checkbox in diff header to toggle comments.
-   Insert "Copy filename to clipboard" button in diff header.
-   Define your own custom CSS styles to be applied to Bitbucket.
-   URLs and emails in diffs automatically become real clickable links.
-   Include a `PULL_REQUEST_TEMPLATE.md` file in the default branch of the repository in one of the locations below, and the contents of that file template will replace the default pull request body inserted by Bitbucket when creating a new one.

    ```
    /PULL_REQUEST_TEMPLATE.md
    /docs/PULL_REQUEST_TEMPLATE.md
    /.github/PULL_REQUEST_TEMPLATE.md
    /.bitbucket/PULL_REQUEST_TEMPLATE.md
    ```

    Please note that the filename IS case sensitive (must be all caps),
    and MUST have the .md file extension. No other file extensions will be
    recognized. The file to be used will be the first to be found in one
    of these locations (from top to bottom).

    It's also possible to specify a URL for a raw Gist with the contents
    of the template in the options page, in case you don't want to include
    the file in your repository, e.g., https://gist.githubusercontent.com/anonymous/8054a3ee32f7cf1a5975e3fd52b3c5f3/raw/f6897720e8b6b93becd246187dac36038291c3a4/PULL_REQUEST_TEMPLATE.md.

    _Note: Currently, externally hosted pull request templates outside of BitBucket's domain is not supported with the Firefox addon._

-   Similar to how the pull request template feature works,
    it is now possible to configure the extension to replace the default merge commit message for
    pull requests with a template that has access to dynamically injected variables like the pull
    request title, description, source and destination branch, and more. [Click here for a more in-depth explanation](https://github.com/refined-bitbucket/refined-bitbucket/pull/243)

## Some images

			Syntax highlighting

			Pull request list

			(notice the source branch name and creation date)

			The Options page.

			Diff ignore and Load all diffs

			Diff ignore

			Load all diffs

			Collapse diff

			Occurrences highlighter

			Sidebar counters

			Expanded

			Collapsed

## Installing

_refined-bitbucket_ is available on the [Google Chrome Web Store][chrome-install] and [Add-ons for Firefox][firefox-install]. When installed, go check the extension's Options to customize it to your needs.

Sometimes the extension is not immediately picked up by the browser after installation. If this happens to you, log out of Bitbucket and then log back in, or clear your cache.

## Default Key Mapping

The following are the default key mappings

#### Tab Selection

![bitbucket pull request tabs][tab-image]

| Key          | Action                       |
| ------------ | ---------------------------- |
| 1 | Selects the **Overview** tab |
| 2 | Selects the **Commits** tab  |
| 3 | Selects the **Activity** tab |

#### Page Navigation and Scrolling

_Upper case letters mean that you need to press shift and the letter_

| Key                       | Action                                           |
| ------------------------- | ------------------------------------------------ |
| N (Shift+n)    | Scrolls to the **N**ext comment on the page.     |
| P (Shift+p)    | Scrolls to the **P**revious comment on the page. |
| g g | Scrolls to the top of the page                   |
| G (Shift+g)    | Scrolls to the bottom of the page                |

## Can I use this on Bitbucket Server?

Sadly, no :(. Although Bitbucket Server and Bitbucket Cloud share a similar name, both are actually two completely different products. [Read this comment for a more detailed explanation](https://github.com/refined-bitbucket/refined-bitbucket/issues/39#issuecomment-338455398).

## Compiling & Contributing

Contributions are very appreciated! Even if you can't contribute with a pull request, if you stumble upon any weird behavior or bugs, let us know with an issue!

If you want to run a development version of the extension, clone the repo and run the following commands:

```bash
npm install
npm run watch
```

This will watch any changes in the `src` folder and compile them to the `extension` folder.

#### Chrome Development

To test in Chrome, activate the Developer mode in `chrome://extensions`, click "Load unpacked extension..." and browse to that folder.
If you're new to Chrome extension development, take some time to read Google's [documentation on extensions](https://developer.chrome.com/extensions).

#### Firefox Development

To test in Firefox, open `about:debugging` in a new tab and click "Load Temporary Add-on". Navigate to the extension folder and load `manifest.json`. For further Firefox add-on development & debugging help, please refer to Mozilla's [documentation](https://developer.mozilla.org/en-US/Add-ons).

#### Integration

There is a test suite included. Before sending a pull request please make
sure all tests are passing by running:

```bash
npm test
```

## License

MIT © [refined-bitbucket](https://github.com/refined-bitbucket)

[chrome-install]: https://chrome.google.com/webstore/detail/refined-bitbucket/afppminkfnfngihdocacbgeajbbdklkf?utm_source=chrome-ntp-icon
[firefox-install]: https://addons.mozilla.org/en-US/firefox/addon/refined-bitbucket-/
[tab-image]: https://cloud.githubusercontent.com/assets/755669/18594922/1c74c184-7bf7-11e6-887d-859fb6206c65.png
[prismjs-languages]: http://prismjs.com/download.html?themes=prism&languages=markup+css+clike+javascript+abap+actionscript+ada+apacheconf+apl+applescript+c+asciidoc+asm6502+aspnet+autohotkey+autoit+bash+basic+batch+bison+brainfuck+bro+cpp+csharp+arduino+coffeescript+ruby+csp+css-extras+d+dart+diff+django+docker+eiffel+elixir+elm+erlang+fsharp+flow+fortran+gherkin+git+glsl+go+graphql+groovy+haml+handlebars+haskell+haxe+http+hpkp+hsts+ichigojam+icon+inform7+ini+io+j+java+jolie+json+julia+keyman+kotlin+latex+less+livescript+lolcode+lua+makefile+markdown+matlab+mel+mizar+monkey+n4js+nasm+nginx+nim+nix+nsis+objectivec+ocaml+opencl+oz+parigp+parser+pascal+perl+php+php-extras+powershell+processing+prolog+properties+protobuf+pug+puppet+pure+python+q+qore+r+jsx+typescript+renpy+reason+rest+rip+roboconf+crystal+rust+sas+sass+scss+scala+scheme+smalltalk+smarty+sql+stylus+swift+tcl+textile+twig+tsx+vbnet+verilog+vhdl+vim+wiki+xeora+xojo+yaml#category-languages
[language-ext]: https://github.com/refined-bitbucket/refined-bitbucket/blob/dev/src/syntax-highlight/language-ext.js


text:
package net.nemerosa.ontrack.model.exceptions;

import net.nemerosa.ontrack.model.structure.ID;

public class ProjectNotFoundException extends NotFoundException {

    public ProjectNotFoundException(ID id) {
        super("Project ID not found: %s", id);
    }

    public ProjectNotFoundException(String name) {
        super("Project name not found: %s", name);
    }

}


text:
package com.greghaskins.spectrum.dsl.specification;

import static com.greghaskins.spectrum.Configure.focus;
import static com.greghaskins.spectrum.Configure.ignore;
import static com.greghaskins.spectrum.Configure.with;
import static com.greghaskins.spectrum.internal.hooks.AfterHook.after;
import static com.greghaskins.spectrum.internal.hooks.BeforeHook.before;

import com.greghaskins.spectrum.Block;
import com.greghaskins.spectrum.ThrowingConsumer;
import com.greghaskins.spectrum.ThrowingSupplier;
import com.greghaskins.spectrum.internal.DeclarationState;
import com.greghaskins.spectrum.internal.Suite;
import com.greghaskins.spectrum.internal.blocks.IdempotentBlock;
import com.greghaskins.spectrum.internal.hooks.EagerLetHook;
import com.greghaskins.spectrum.internal.hooks.Hook;
import com.greghaskins.spectrum.internal.hooks.HookContext.AppliesTo;
import com.greghaskins.spectrum.internal.hooks.HookContext.Precedence;
import com.greghaskins.spectrum.internal.hooks.LetHook;

import org.junit.AssumptionViolatedException;

import java.util.function.Supplier;

public interface Specification {

  /**
   * Declare a test suite that describes the expected behavior of the system in a given context.
   *
   * @param context Description of the context for this suite
   * @param block   {@link Block} with one or more calls to {@link #it(String, Block) it} that
   *                define each expected behavior
   */
  static void describe(final String context, final Block block) {
    final Suite suite = DeclarationState.instance()
        .getCurrentSuiteBeingDeclared()
        .addSuite(context);
    suite.applyConfigurationFromBlock(block);
    DeclarationState.instance().beginDeclaration(suite, block);
  }

  /**
   * Focus on this specific suite, while ignoring others.
   *
   * @param context Description of the context for this suite
   * @param block   {@link Block} with one or more calls to {@link #it(String, Block) it} that
   *                define each expected behavior
   * @see #describe(String, Block)
   */
  static void fdescribe(final String context, final Block block) {
    describe(context, with(focus(), block));
  }

  /**
   * Ignore the specific suite.
   *
   * @param context Description of the context for this suite
   * @param block   {@link Block} with one or more calls to {@link #it(String, Block) it} that
   *                define each expected behavior
   * @see #describe(String, Block)
   */
  static void xdescribe(final String context, final Block block) {
    describe(context, with(ignore(), block));
  }

  /**
   * Declare a spec, or test, for an expected behavior of the system in this suite context.
   *
   * @param behavior Description of the expected behavior
   * @param block    {@link Block} that verifies the system behaves as expected and throws a {@link
   *                 java.lang.Throwable Throwable} if that expectation is not met.
   */
  static void it(final String behavior, final Block block) {
    DeclarationState.instance().getCurrentSuiteBeingDeclared().addSpec(behavior, block);
  }

  /**
   * Declare a pending spec (without a block) that will be ignored.
   *
   * @param behavior Description of the expected behavior
   * @see #xit(String, Block)
   */
  static void it(final String behavior) {
    DeclarationState.instance().getCurrentSuiteBeingDeclared().addSpec(behavior, null).ignore();
  }

  /**
   * Focus on this specific spec, while ignoring others.
   *
   * @param behavior Description of the expected behavior
   * @param block    {@link Block} that verifies the system behaves as expected and throws a {@link
   *                 java.lang.Throwable Throwable} if that expectation is not met.
   * @see #it(String, Block)
   */
  static void fit(final String behavior, final Block block) {
    it(behavior, with(focus(), block));
  }

  /**
   * Mark a spec as ignored so that it will be skipped.
   *
   * @param behavior Description of the expected behavior
   * @param block    {@link Block} that will not run, since this spec is ignored.
   * @see #it(String, Block)
   */
  static void xit(final String behavior, final Block block) {
    it(behavior);
  }

  /**
   * Declare a {@link Block} to be run before each spec in the suite.
   *
   *

   * Use this to perform setup actions that are common across tests in the context. If multiple
   * {@code beforeEach} blocks are declared, they will run in declaration order.
   *

   *
   * @param block {@link Block} to run once before each spec
   */
  static void beforeEach(final Block block) {
    DeclarationState.instance().addHook(before(block), AppliesTo.ATOMIC_ONLY, Precedence.LOCAL);
  }

  /**
   * Declare a {@link Block Block} to be run after each spec in the current suite.
   *
   *

   * Use this to perform teardown or cleanup actions that are common across specs in this suite. If
   * multiple {@code afterEach} blocks are declared, they will run in declaration order.
   *

   *
   * @param block {@link Block Block} to run once after each spec
   */
  static void afterEach(final Block block) {
    DeclarationState.instance().addHook(after(block), AppliesTo.ATOMIC_ONLY,
        Precedence.GUARANTEED_CLEAN_UP_LOCAL);
  }

  /**
   * Declare a {@link Block Block} to be run once before all the specs in the current suite begin.
   *
   *

   * Use {@code beforeAll} and {@link #afterAll(Block) afterAll} blocks with caution: since they
   * only run once, shared state will leak across specs.
   *

   *
   * @param block {@link Block} to run once before all specs in this suite
   */
  static void beforeAll(final Block block) {
    DeclarationState.instance().addHook(before(new IdempotentBlock(block)), AppliesTo.ATOMIC_ONLY,
        Precedence.SET_UP);
  }

  /**
   * Declare a {@link Block} to be run once after all the specs in the current suite have run.
   *
   *

   * Use {@link #beforeAll(Block) beforeAll} and {@code afterAll} blocks with caution: since they
   * only run once, shared state will leak across tests.
   *

   *
   * @param block {@link Block} to run once after all specs in this suite
   */
  static void afterAll(final Block block) {
    DeclarationState.instance().addHook(after(block), AppliesTo.ONCE,
        Precedence.GUARANTEED_CLEAN_UP_GLOBAL);
  }

  /**
   * A value that will be fresh within each spec and cannot bleed across specs.
   *
   *

   * Note that {@code let} is lazy-evaluated: the {@code supplier} is not called until the first
   * time it is used.
   *

   *
   * @param <T>      The type of value
   * @param supplier {@link ThrowingSupplier} function that either generates the value, or throws a
   *                 {@link Throwable}
   * @return supplier which is refreshed for each spec's context
   */
  static <T> Supplier<T> let(final ThrowingSupplier<T> supplier) {
    LetHook<T> letHook = new LetHook<>(supplier);
    DeclarationState.instance().addHook(letHook, AppliesTo.ATOMIC_ONLY, Precedence.LOCAL);

    return letHook;
  }

  /**
   * A value that will be calculated fresh at the start of each spec and cannot bleed across specs.
   *
   *

   * Note that {@code eagerLet} is eagerly evaluated: the {@code supplier} is called at the start
   * of the spec, before {@code beforeEach} blocks.
   *

   *
   * @param <T>      The type of value
   * @param supplier {@link ThrowingSupplier} function that either generates the value, or throws a
   *                 {@link Throwable}
   * @return supplier which is refreshed for each spec's context
   */
  static <T> Supplier<T> eagerLet(final ThrowingSupplier<T> supplier) {
    EagerLetHook<T> eagerLetHook = new EagerLetHook<>(supplier);
    DeclarationState.instance().addHook(eagerLetHook, AppliesTo.ATOMIC_ONLY, Precedence.LOCAL);

    return eagerLetHook;
  }

  /**
   * Define a test context. Alias for {@link #describe}.
   *
   * @param context the description of the context
   * @param block   the block to execute
   */
  static void context(final String context, final Block block) {
    describe(context, block);
  }

  /**
   * Define a focused test context. Alias for {@link #fdescribe}.
   *
   * @param context the description of the context
   * @param block   the block to execute
   */
  static void fcontext(final String context, final Block block) {
    fdescribe(context, block);
  }

  /**
   * Define an ignored test context. Alias for {@link #xdescribe}.
   *
   * @param context the description of the context
   * @param block   the block to execute
   */
  static void xcontext(final String context, final Block block) {
    xdescribe(context, block);
  }

  /**
   * Call this from within a Spec block to mark the spec as ignored/pending.
   */
  static void pending() {
    throw new AssumptionViolatedException("pending");
  }

  /**
   * Call this from within a Specification to mark the spec as ignored/pending.
   *
   * @param message the annotation of the pending
   */
  static void pending(final String message) {
    throw new AssumptionViolatedException(message);
  }

  /**
   * Declare a block of code that runs around each spec, partly before and partly after. You must
   * call {@link com.greghaskins.spectrum.Block#run} inside this Consumer. This code is applied to
   * every spec in the current suite.
   *
   * @param consumer to run each spec block
   */
  static void aroundEach(ThrowingConsumer<Block> consumer) {
    DeclarationState.instance().addHook(Hook.from(consumer), AppliesTo.ATOMIC_ONLY,
        Precedence.GUARANTEED_CLEAN_UP_LOCAL);
  }

  /**
   * Declare a block of code that runs once around all specs, partly before and partly after specs
   * are run. You must call {@link Block#run} inside this Consumer. This code is applied once per
   * suite, so be careful about shared state across specs.
   *
   * @param consumer to run each spec block
   */
  static void aroundAll(ThrowingConsumer<Block> consumer) {
    DeclarationState.instance().addHook(Hook.from(consumer), AppliesTo.ONCE, Precedence.OUTER);
  }

}