text:
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/policy/core/browser/configuration_policy_handler.h"

#include <stddef.h>

#include <algorithm>
#include <string>
#include <utility>

#include "base/callback.h"
#include "base/check.h"
#include "base/containers/adapters.h"
#include "base/cxx17_backports.h"
#include "base/files/file_path.h"
#include "base/json/json_reader.h"
#include "base/metrics/histogram.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "components/policy/core/browser/policy_error_map.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/schema.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_value_map.h"
#include "components/strings/grit/components_strings.h"
#include "url/gurl.h"

namespace policy {

const size_t kMaxUrlFiltersPerPolicy = 1000;

// ConfigurationPolicyHandler implementation
// -----------------------------------

ConfigurationPolicyHandler::ConfigurationPolicyHandler() {}

ConfigurationPolicyHandler::~ConfigurationPolicyHandler() {}

void ConfigurationPolicyHandler::PrepareForDisplaying(
    PolicyMap* policies) const {}

void ConfigurationPolicyHandler::ApplyPolicySettingsWithParameters(
    const PolicyMap& policies,
    const PolicyHandlerParameters& parameters,
    PrefValueMap* prefs) {
  ApplyPolicySettings(policies, prefs);
}

// NamedPolicyHandler implementation -------------------------------------------
NamedPolicyHandler::NamedPolicyHandler(const char* policy_name)
    : policy_name_(policy_name) {}

NamedPolicyHandler::~NamedPolicyHandler() = default;

const char* NamedPolicyHandler::policy_name() const {
  return policy_name_;
}

// TypeCheckingPolicyHandler implementation ------------------------------------

TypeCheckingPolicyHandler::TypeCheckingPolicyHandler(
    const char* policy_name,
    base::Value::Type value_type)
    : NamedPolicyHandler(policy_name), value_type_(value_type) {}

TypeCheckingPolicyHandler::~TypeCheckingPolicyHandler() {}

bool TypeCheckingPolicyHandler::CheckPolicySettings(const PolicyMap& policies,
                                                    PolicyErrorMap* errors) {
  const base::Value* value = nullptr;
  return CheckAndGetValue(policy_name(), value_type_,
                          policies.Get(policy_name()), errors, &value);
}

bool TypeCheckingPolicyHandler::CheckPolicySettings(
    const char* policy,
    base::Value::Type value_type,
    const PolicyMap::Entry* entry,
    PolicyErrorMap* errors) {
  const base::Value* value = nullptr;
  return CheckAndGetValue(policy, value_type, entry, errors, &value);
}

bool TypeCheckingPolicyHandler::CheckAndGetValue(const PolicyMap& policies,
                                                 PolicyErrorMap* errors,
                                                 const base::Value** value) {
  return CheckAndGetValue(policy_name(), value_type_,
                          policies.Get(policy_name()), errors, value);
}

bool TypeCheckingPolicyHandler::CheckAndGetValue(const char* policy,
                                                 base::Value::Type value_type,
                                                 const PolicyMap::Entry* entry,
                                                 PolicyErrorMap* errors,
                                                 const base::Value** value) {
  // It is safe to use `value_unsafe()` as multiple policy types are handled.
  *value = entry ? entry->value_unsafe() : nullptr;
  if (*value && (*value)->type() != value_type) {
    errors->AddError(policy, IDS_POLICY_TYPE_ERROR,
                     base::Value::GetTypeName(value_type));
    return false;
  }
  return true;
}

// StringListPolicyHandler implementation --------------------------------------

ListPolicyHandler::ListPolicyHandler(const char* policy_name,
                                     base::Value::Type list_entry_type)
    : TypeCheckingPolicyHandler(policy_name, base::Value::Type::LIST),
      list_entry_type_(list_entry_type) {}

ListPolicyHandler::~ListPolicyHandler() {}

bool ListPolicyHandler::CheckPolicySettings(const policy::PolicyMap& policies,
                                            policy::PolicyErrorMap* errors) {
  return CheckAndGetList(policies, errors, nullptr);
}

void ListPolicyHandler::ApplyPolicySettings(const policy::PolicyMap& policies,
                                            PrefValueMap* prefs) {
  base::Value list(base::Value::Type::NONE);
  if (CheckAndGetList(policies, nullptr, &list) && list.is_list())
    ApplyList(std::move(list), prefs);
}

bool ListPolicyHandler::CheckAndGetList(const policy::PolicyMap& policies,
                                        policy::PolicyErrorMap* errors,
                                        base::Value* filtered_list) {
  const base::Value* value = nullptr;
  if (!CheckAndGetValue(policies, errors, &value))
    return false;

  if (!value)
    return true;

  // Filter the list, rejecting any invalid strings.
  const base::Value::List& list = value->GetList();
  if (filtered_list)
    *filtered_list = base::Value(base::Value::Type::LIST);
  for (size_t list_index = 0; list_index < list.size(); ++list_index) {
    const base::Value& entry = list[list_index];
    if (entry.type() != list_entry_type_) {
      if (errors) {
        errors->AddError(policy_name(), IDS_POLICY_TYPE_ERROR,
                         base::Value::GetTypeName(list_entry_type_),
                         PolicyErrorPath{list_index});
      }
      continue;
    }

    if (!CheckListEntry(entry)) {
      if (errors) {
        errors->AddError(policy_name(), IDS_POLICY_VALUE_FORMAT_ERROR,
                         PolicyErrorPath{list_index});
      }
      continue;
    }

    if (filtered_list)
      filtered_list->GetList().Append(entry.Clone());
  }

  return true;
}

bool ListPolicyHandler::CheckListEntry(const base::Value& value) {
  return true;
}

// IntRangePolicyHandlerBase implementation ------------------------------------

IntRangePolicyHandlerBase::IntRangePolicyHandlerBase(const char* policy_name,
                                                     int min,
                                                     int max,
                                                     bool clamp)
    : TypeCheckingPolicyHandler(policy_name, base::Value::Type::INTEGER),
      min_(min),
      max_(max),
      clamp_(clamp) {}

bool IntRangePolicyHandlerBase::CheckPolicySettings(const PolicyMap& policies,
                                                    PolicyErrorMap* errors) {
  const base::Value* value;
  return CheckAndGetValue(policies, errors, &value) &&
         EnsureInRange(value, nullptr, errors);
}

IntRangePolicyHandlerBase::~IntRangePolicyHandlerBase() {}

bool IntRangePolicyHandlerBase::EnsureInRange(const base::Value* input,
                                              int* output,
                                              PolicyErrorMap* errors) {
  if (!input)
    return true;

  DCHECK(input->is_int());
  int value = input->GetInt();

  if (value < min_ || value > max_) {
    if (errors) {
      errors->AddError(policy_name(), IDS_POLICY_OUT_OF_RANGE_ERROR,
                       base::NumberToString(value));
    }

    if (!clamp_)
      return false;

    value = base::clamp(value, min_, max_);
  }

  if (output)
    *output = value;
  return true;
}

// StringMappingListPolicyHandler implementation -----------------------------

StringMappingListPolicyHandler::MappingEntry::MappingEntry(
    const char* policy_value,
    std::unique_ptr<base::Value> map)
    : enum_value(policy_value), mapped_value(std::move(map)) {}

StringMappingListPolicyHandler::MappingEntry::~MappingEntry() {}

StringMappingListPolicyHandler::StringMappingListPolicyHandler(
    const char* policy_name,
    const char* pref_path,
    const GenerateMapCallback& callback)
    : TypeCheckingPolicyHandler(policy_name, base::Value::Type::LIST),
      pref_path_(pref_path),
      map_getter_(callback) {}

StringMappingListPolicyHandler::~StringMappingListPolicyHandler() {}

bool StringMappingListPolicyHandler::CheckPolicySettings(
    const PolicyMap& policies,
    PolicyErrorMap* errors) {
  const base::Value* value;
  return CheckAndGetValue(policies, errors, &value) &&
         Convert(value, nullptr, errors);
}

void StringMappingListPolicyHandler::ApplyPolicySettings(
    const PolicyMap& policies,
    PrefValueMap* prefs) {
  if (!pref_path_)
    return;
  const base::Value* value =
      policies.GetValue(policy_name(), base::Value::Type::LIST);
  base::ListValue list;
  if (value && Convert(value, &list, nullptr))
    prefs->SetValue(pref_path_, std::move(list));
}

bool StringMappingListPolicyHandler::Convert(const base::Value* input,
                                             base::ListValue* output,
                                             PolicyErrorMap* errors) {
  if (!input)
    return true;

  DCHECK(input->is_list());
  int index = -1;
  for (const auto& entry : input->GetListDeprecated()) {
    ++index;
    if (!entry.is_string()) {
      if (errors) {
        errors->AddError(policy_name(), IDS_POLICY_TYPE_ERROR,
                         base::Value::GetTypeName(base::Value::Type::STRING),
                         PolicyErrorPath{index});
      }
      continue;
    }

    std::unique_ptr<base::Value> mapped_value = Map(entry.GetString());
    if (mapped_value) {
      if (output) {
        output->GetList().Append(
            base::Value::FromUniquePtrValue(std::move(mapped_value)));
      }
    } else if (errors) {
      errors->AddError(policy_name(), IDS_POLICY_OUT_OF_RANGE_ERROR,
                       PolicyErrorPath{index});
    }
  }

  return true;
}

std::unique_ptr<base::Value> StringMappingListPolicyHandler::Map(
    const std::string& entry_value) {
  // Lazily generate the map of policy strings to mapped values.
  if (map_.empty())
    map_getter_.Run(&map_);

  for (const auto& mapping_entry : map_) {
    if (mapping_entry->enum_value == entry_value) {
      return base::Value::ToUniquePtrValue(
          mapping_entry->mapped_value->Clone());
    }
  }
  return nullptr;
}

// IntRangePolicyHandler implementation ----------------------------------------

IntRangePolicyHandler::IntRangePolicyHandler(const char* policy_name,
                                             const char* pref_path,
                                             int min,
                                             int max,
                                             bool clamp)
    : IntRangePolicyHandlerBase(policy_name, min, max, clamp),
      pref_path_(pref_path) {}

IntRangePolicyHandler::~IntRangePolicyHandler() {}

void IntRangePolicyHandler::ApplyPolicySettings(const PolicyMap& policies,
                                                PrefValueMap* prefs) {
  if (!pref_path_)
    return;
  const base::Value* value =
      policies.GetValue(policy_name(), base::Value::Type::INTEGER);
  int value_in_range;
  if (value && EnsureInRange(value, &value_in_range, nullptr))
    prefs->SetInteger(pref_path_, value_in_range);
}

// IntPercentageToDoublePolicyHandler implementation ---------------------------

IntPercentageToDoublePolicyHandler::IntPercentageToDoublePolicyHandler(
    const char* policy_name,
    const char* pref_path,
    int min,
    int max,
    bool clamp)
    : IntRangePolicyHandlerBase(policy_name, min, max, clamp),
      pref_path_(pref_path) {}

IntPercentageToDoublePolicyHandler::~IntPercentageToDoublePolicyHandler() {}

void IntPercentageToDoublePolicyHandler::ApplyPolicySettings(
    const PolicyMap& policies,
    PrefValueMap* prefs) {
  if (!pref_path_)
    return;
  const base::Value* value =
      policies.GetValue(policy_name(), base::Value::Type::INTEGER);
  int percentage;
  if (value && EnsureInRange(value, &percentage, nullptr))
    prefs->SetDouble(pref_path_, static_cast<double>(percentage) / 100.);
}

// SimplePolicyHandler implementation ------------------------------------------

SimplePolicyHandler::SimplePolicyHandler(const char* policy_name,
                                         const char* pref_path,
                                         base::Value::Type value_type)
    : TypeCheckingPolicyHandler(policy_name, value_type),
      pref_path_(pref_path) {}

SimplePolicyHandler::~SimplePolicyHandler() {}

void SimplePolicyHandler::ApplyPolicySettings(const PolicyMap& policies,
                                              PrefValueMap* prefs) {
  if (!pref_path_)
    return;
  // It is safe to use `GetValueUnsafe()` as multiple policy types are handled.
  const base::Value* value = policies.GetValueUnsafe(policy_name());
  if (value)
    prefs->SetValue(pref_path_, value->Clone());
}

// SchemaValidatingPolicyHandler implementation --------------------------------

SchemaValidatingPolicyHandler::SchemaValidatingPolicyHandler(
    const char* policy_name,
    Schema schema,
    SchemaOnErrorStrategy strategy)
    : NamedPolicyHandler(policy_name), schema_(schema), strategy_(strategy) {
  DCHECK(schema_.valid());
}

SchemaValidatingPolicyHandler::~SchemaValidatingPolicyHandler() {}

bool SchemaValidatingPolicyHandler::CheckPolicySettings(
    const PolicyMap& policies,
    PolicyErrorMap* errors) {
  // It is safe to use `GetValueUnsafe()` as multiple policy types are handled.
  const base::Value* value = policies.GetValueUnsafe(policy_name());
  if (!value)
    return true;

  PolicyErrorPath error_path;
  std::string error;
  std::vector<PolicyMap::PolicyMapType::value_type> errors_with_path;
  bool result = schema_.Validate(*value, strategy_, &error_path, &error);

  if (errors && !error.empty()) {
    // Set error_level based on whether strategy_ tolerates this error without
    // failure.
    errors->AddError(policy_name(), IDS_POLICY_SCHEMA_VALIDATION_ERROR, error,
                     error_path,
                     /*error_level=*/
                     result ? PolicyMap::MessageType::kWarning
                            : PolicyMap::MessageType::kError);
  }

  return result;
}

bool SchemaValidatingPolicyHandler::CheckAndGetValue(
    const PolicyMap& policies,
    PolicyErrorMap* errors,
    std::unique_ptr<base::Value>* output) {
  // It is safe to use `GetValueUnsafe()` as multiple policy types are handled.
  const base::Value* value = policies.GetValueUnsafe(policy_name());
  if (!value)
    return true;

  *output = base::Value::ToUniquePtrValue(value->Clone());
  PolicyErrorPath error_path;
  std::string error;
  bool result =
      schema_.Normalize(output->get(), strategy_, &error_path, &error, nullptr);

  if (errors && !error.empty()) {
    // Set error_level based on whether strategy_ tolerates this error without
    // failure.
    errors->AddError(policy_name(), IDS_POLICY_SCHEMA_VALIDATION_ERROR, error,
                     error_path,
                     /*error_level=*/
                     result ? PolicyMap::MessageType::kWarning
                            : PolicyMap::MessageType::kError);
  }

  return result;
}

// SimpleSchemaValidatingPolicyHandler implementation --------------------------

SimpleSchemaValidatingPolicyHandler::SimpleSchemaValidatingPolicyHandler(
    const char* policy_name,
    const char* pref_path,
    Schema schema,
    SchemaOnErrorStrategy strategy,
    RecommendedPermission recommended_permission,
    MandatoryPermission mandatory_permission)
    : SchemaValidatingPolicyHandler(policy_name,
                                    schema.GetKnownProperty(policy_name),
                                    strategy),
      pref_path_(pref_path),
      allow_recommended_(recommended_permission == RECOMMENDED_ALLOWED),
      allow_mandatory_(mandatory_permission == MANDATORY_ALLOWED) {}

SimpleSchemaValidatingPolicyHandler::~SimpleSchemaValidatingPolicyHandler() {}

bool SimpleSchemaValidatingPolicyHandler::CheckPolicySettings(
    const PolicyMap& policies,
    PolicyErrorMap* errors) {
  const PolicyMap::Entry* policy_entry = policies.Get(policy_name());
  if (!policy_entry)
    return true;
  if ((policy_entry->level == policy::POLICY_LEVEL_MANDATORY &&
       !allow_mandatory_) ||
      (policy_entry->level == policy::POLICY_LEVEL_RECOMMENDED &&
       !allow_recommended_)) {
    if (errors)
      errors->AddError(policy_name(), IDS_POLICY_LEVEL_ERROR);
    return false;
  }

  return SchemaValidatingPolicyHandler::CheckPolicySettings(policies, errors);
}

void SimpleSchemaValidatingPolicyHandler::ApplyPolicySettings(
    const PolicyMap& policies,
    PrefValueMap* prefs) {
  if (!pref_path_)
    return;
  // It is safe to use `GetValueUnsafe()` as multiple policy types are handled.
  const base::Value* value = policies.GetValueUnsafe(policy_name());
  if (value)
    prefs->SetValue(pref_path_, value->Clone());
}

// SimpleJsonStringSchemaValidatingPolicyHandler implementation ----------------

SimpleJsonStringSchemaValidatingPolicyHandler::
    SimpleJsonStringSchemaValidatingPolicyHandler(
        const char* policy_name,
        const char* pref_path,
        Schema schema,
        SimpleSchemaValidatingPolicyHandler::RecommendedPermission
            recommended_permission,
        SimpleSchemaValidatingPolicyHandler::MandatoryPermission
            mandatory_permission)
    : NamedPolicyHandler(policy_name),
      schema_(schema.GetKnownProperty(policy_name)),
      pref_path_(pref_path),
      allow_recommended_(
          recommended_permission ==
          SimpleSchemaValidatingPolicyHandler::RECOMMENDED_ALLOWED),
      allow_mandatory_(mandatory_permission ==
                       SimpleSchemaValidatingPolicyHandler::MANDATORY_ALLOWED) {
}

SimpleJsonStringSchemaValidatingPolicyHandler::
    ~SimpleJsonStringSchemaValidatingPolicyHandler() {}

bool SimpleJsonStringSchemaValidatingPolicyHandler::CheckPolicySettings(
    const PolicyMap& policies,
    PolicyErrorMap* errors) {
  // It is safe to use `GetValueUnsafe()` as multiple policy types are handled.
  const base::Value* root_value = policies.GetValueUnsafe(policy_name());
  if (!root_value)
    return true;

  const PolicyMap::Entry* policy_entry = policies.Get(policy_name());
  if ((policy_entry->level == policy::POLICY_LEVEL_MANDATORY &&
       !allow_mandatory_) ||
      (policy_entry->level == policy::POLICY_LEVEL_RECOMMENDED &&
       !allow_recommended_)) {
    if (errors)
      errors->AddError(policy_name(), IDS_POLICY_LEVEL_ERROR);
    return false;
  }

  if (IsListSchema())
    return CheckListOfJsonStrings(root_value, errors);

  return CheckSingleJsonString(root_value, errors);
}

bool SimpleJsonStringSchemaValidatingPolicyHandler::CheckSingleJsonString(
    const base::Value* root_value,
    PolicyErrorMap* errors) {
  // First validate the root value is a string.
  if (!root_value->is_string()) {
    if (errors) {
      errors->AddError(policy_name(), IDS_POLICY_TYPE_ERROR,
                       base::Value::GetTypeName(base::Value::Type::STRING));
    }
    return false;
  }

  // If that succeeds, validate the JSON inside the string.
  const std::string& json_string = root_value->GetString();
  if (!ValidateJsonString(json_string, errors, 0))
    RecordJsonError();

  // Very lenient - return true as long as the root value is a string.
  return true;
}

bool SimpleJsonStringSchemaValidatingPolicyHandler::CheckListOfJsonStrings(
    const base::Value* root_value,
    PolicyErrorMap* errors) {
  // First validate the root value is a list.
  if (!root_value->is_list()) {
    if (errors) {
      errors->AddError(policy_name(), IDS_POLICY_TYPE_ERROR,
                       base::Value::GetTypeName(base::Value::Type::LIST));
    }
    return false;
  }

  // If that succeeds, validate all the list items are strings and validate
  // the JSON inside the strings.
  const base::Value::List& list = root_value->GetList();
  bool json_error_seen = false;

  for (size_t index = 0; index < list.size(); ++index) {
    const base::Value& entry = list[index];
    if (!entry.is_string()) {
      if (errors) {
        errors->AddError(policy_name(), IDS_POLICY_TYPE_ERROR,
                         base::Value::GetTypeName(base::Value::Type::STRING),
                         PolicyErrorPath{index});
      }
      continue;
    }

    const std::string& json_string = entry.GetString();
    if (!ValidateJsonString(json_string, errors, index))
      json_error_seen = true;
  }

  if (json_error_seen)
    RecordJsonError();

  // Very lenient - return true as long as the root value is a list.
  return true;
}

bool SimpleJsonStringSchemaValidatingPolicyHandler::ValidateJsonString(
    const std::string& json_string,
    PolicyErrorMap* errors,
    int index) {
  auto value_with_error = base::JSONReader::ReadAndReturnValueWithError(
      json_string, base::JSONParserOptions::JSON_ALLOW_TRAILING_COMMAS);
  if (!value_with_error.has_value()) {
    if (errors) {
      PolicyErrorPath error_path = {index};
      errors->AddError(policy_name(), IDS_POLICY_INVALID_JSON_ERROR,
                       value_with_error.error().message, error_path);
    }
    return false;
  }

  std::string schema_error;
  PolicyErrorPath error_path;
  const Schema json_string_schema =
      IsListSchema() ? schema_.GetItems() : schema_;
  // Even though we are validating this schema here, we don't actually change
  // the policy if it fails to validate. This validation is just so we can show
  // the user errors.
  bool validated = json_string_schema.Validate(
      *value_with_error, SCHEMA_ALLOW_UNKNOWN, &error_path, &schema_error);
  if (errors && !schema_error.empty()) {
    error_path.emplace(error_path.begin(), index);
    errors->AddError(policy_name(), IDS_POLICY_SCHEMA_VALIDATION_ERROR,
                     schema_error, error_path);
  }
  if (!validated)
    return false;

  return true;
}

void SimpleJsonStringSchemaValidatingPolicyHandler::ApplyPolicySettings(
    const PolicyMap& policies,
    PrefValueMap* prefs) {
  if (!pref_path_)
    return;
  // It is safe to use `GetValueUnsafe()` as multiple policy types are handled.
  const base::Value* value = policies.GetValueUnsafe(policy_name());
  if (value)
    prefs->SetValue(pref_path_, value->Clone());
}

void SimpleJsonStringSchemaValidatingPolicyHandler::RecordJsonError() {
  const PolicyDetails* details = GetChromePolicyDetails(policy_name());
  if (details) {
    base::UmaHistogramSparse("EnterpriseCheck.InvalidJsonPolicies",
                             details->id);
  }
}

bool SimpleJsonStringSchemaValidatingPolicyHandler::IsListSchema() const {
  return schema_.type() == base::Value::Type::LIST;
}

// LegacyPoliciesDeprecatingPolicyHandler implementation -----------------------

LegacyPoliciesDeprecatingPolicyHandler::LegacyPoliciesDeprecatingPolicyHandler(
    std::vector<std::unique_ptr<ConfigurationPolicyHandler>>
        legacy_policy_handlers,
    std::unique_ptr<NamedPolicyHandler> new_policy_handler)
    : legacy_policy_handlers_(std::move(legacy_policy_handlers)),
      new_policy_handler_(std::move(new_policy_handler)) {}

LegacyPoliciesDeprecatingPolicyHandler::
    ~LegacyPoliciesDeprecatingPolicyHandler() {}

bool LegacyPoliciesDeprecatingPolicyHandler::CheckPolicySettings(
    const PolicyMap& policies,
    PolicyErrorMap* errors) {
  if (policies.Get(new_policy_handler_->policy_name()))
    return new_policy_handler_->CheckPolicySettings(policies, errors);

  // The new policy is not set, fall back to legacy ones.
  bool valid_policy_found = false;
  for (const auto& handler : legacy_policy_handlers_) {
    if (handler->CheckPolicySettings(policies, errors))
      valid_policy_found = true;
  }
  return valid_policy_found;
}

void LegacyPoliciesDeprecatingPolicyHandler::ApplyPolicySettingsWithParameters(
    const policy::PolicyMap& policies,
    const policy::PolicyHandlerParameters& parameters,
    PrefValueMap* prefs) {
  if (policies.Get(new_policy_handler_->policy_name())) {
    new_policy_handler_->ApplyPolicySettingsWithParameters(policies, parameters,
                                                           prefs);
    return;
  }

  // The new policy is not set, fall back to legacy ones.
  PolicyErrorMap scoped_errors;
  for (const auto& handler : legacy_policy_handlers_) {
    if (handler->CheckPolicySettings(policies, &scoped_errors))
      handler->ApplyPolicySettingsWithParameters(policies, parameters, prefs);
  }
}

void LegacyPoliciesDeprecatingPolicyHandler::ApplyPolicySettings(
    const policy::PolicyMap& /* policies */,
    PrefValueMap* /* prefs */) {
  NOTREACHED();
}

// SimpleDeprecatingPolicyHandler implementation -----------------------

SimpleDeprecatingPolicyHandler::SimpleDeprecatingPolicyHandler(
    std::unique_ptr<NamedPolicyHandler> legacy_policy_handler,
    std::unique_ptr<NamedPolicyHandler> new_policy_handler)
    : legacy_policy_handler_(std::move(legacy_policy_handler)),
      new_policy_handler_(std::move(new_policy_handler)) {}

SimpleDeprecatingPolicyHandler::~SimpleDeprecatingPolicyHandler() = default;

bool SimpleDeprecatingPolicyHandler::CheckPolicySettings(
    const PolicyMap& policies,
    PolicyErrorMap* errors) {
  if (policies.Get(new_policy_handler_->policy_name())) {
    if (policies.Get(legacy_policy_handler_->policy_name())) {
      errors->AddError(legacy_policy_handler_->policy_name(),
                       IDS_POLICY_OVERRIDDEN,
                       new_policy_handler_->policy_name());
    }
    return new_policy_handler_->CheckPolicySettings(policies, errors);
  }

  // The new policy is not set, fall back to legacy ones.
  return legacy_policy_handler_->CheckPolicySettings(policies, errors);
}

void SimpleDeprecatingPolicyHandler::ApplyPolicySettingsWithParameters(
    const policy::PolicyMap& policies,
    const policy::PolicyHandlerParameters& parameters,
    PrefValueMap* prefs) {
  if (policies.Get(new_policy_handler_->policy_name())) {
    new_policy_handler_->ApplyPolicySettingsWithParameters(policies, parameters,
                                                           prefs);
  } else {
    legacy_policy_handler_->ApplyPolicySettingsWithParameters(
        policies, parameters, prefs);
  }
}

void SimpleDeprecatingPolicyHandler::ApplyPolicySettings(
    const policy::PolicyMap& /* policies */,
    PrefValueMap* /* prefs */) {
  NOTREACHED();
}

}  // namespace policy


text:
package core

import com.datastax.driver.core.{ProtocolOptions, Session, Cluster}
import org.specs2.specification.{SpecificationStructure, Fragments, Step}
import scala.io.Source
import java.io.File
import akka.actor.ActorSystem

trait TestCassandraCluster extends CassandraCluster {
  def system: ActorSystem

  private def config = system.settings.config

  import scala.collection.JavaConversions._
  private val cassandraConfig = config.getConfig("akka-cassandra.test.db.cassandra")
  private val port = cassandraConfig.getInt("port")
  private val hosts = cassandraConfig.getStringList("hosts").toList

  lazy val cluster: Cluster =
    Cluster.builder().
      addContactPoints(hosts: _*).
      withCompression(ProtocolOptions.Compression.SNAPPY).
      withPort(port).
      build()

}

trait CleanCassandra extends SpecificationStructure {
  this: CassandraCluster =>

  private def runCql(session: Session, file: File): Unit = {
    val query = Source.fromFile(file).mkString
    query.split(";").foreach(session.execute)
  }

  private def runAllCqls(): Unit = {
    val session = cluster.connect(Keyspaces.akkaCassandra)
    val uri = getClass.getResource("/").toURI
    new File(uri).listFiles().foreach { file =>
      if (file.getName.endsWith(".cql")) runCql(session, file)
    }
    session.close()
  }

  override def map(fs: => Fragments) = super.map(fs) insert Step(runAllCqls())
}

redpajama_set_name: RedPajamaGithub


text: Add here new games


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="renderer" content="webkit">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="format-detection" content="telephone=no">
<meta name="format-detection" content="address=no">
<meta name="fragment" content="!">
<link rel="stylesheet" href="../../../site/css/index.css">
<link rel="stylesheet" href="../../../dist/css/fly.css"/>
<link rel="stylesheet" type="text/css" href="../style/jm-alert.css">

        <fieldset>
            <legend>普通实例</legend>

                Well done! You successfully read this important alert message.

                Heads up! This alert needs your attention, but it's not super important.

                Warning! Better check yourself, you're not looking too good.

                Oh snap! Change a few things up and try submitting again.

        </fieldset>
        <fieldset>
            <legend>可关闭的实例</legend>

                <button type="button" class="close" data-dismiss="alert">
                    
                </button>
                Warning! Better check yourself, you're not looking too good.

                <button type="button" class="close" data-dismiss="alert">
                    Close
                </button>
                Warning! Better check yourself, you're not looking too good.

        </fieldset>
        <fieldset>
            <legend>带图标的实例</legend>

                
                Well done! You successfully read this important alert message.
                <button type="button" class="close" data-dismiss="alert">
                    
                </button>

                
                Heads up! This alert needs your attention, but it's not super important.
                <button type="button" class="close" data-dismiss="alert">
                    
                </button>

                
                Warning! Better check yourself, you're not looking too good.
                <button type="button" class="close" data-dismiss="alert">
                    
                </button>

                
                Oh snap! Change a few things up and try submitting again.
                <button type="button" class="close" data-dismiss="alert">
                    
                </button>

        </fieldset>
        <fieldset>
            <legend>带文字介绍和辅助性文字介绍</legend>

                

Well done!
 You successfully read this important alert message.

                <button type="button" class="close" data-dismiss="alert">
                    
                </button>

                

Heads up!
 This alert needs your attention, but it's not super important.

                <button type="button" class="close" data-dismiss="alert">
                    
                </button>

                

Warning!
 Better check yourself, you're not looking too good.

                <button type="button" class="close" data-dismiss="alert">
                    
                </button>

                

Oh snap!
 Change a few things up and try submitting again.

                <button type="button" class="close" data-dismiss="alert">
                    
                </button>

        </fieldset>


text:
(function($) {
	$.fn.rasterize = function(options) {
		var history = new Object();
		var chained = function(options) {
			return rasterize(this, options, history);
		};
		return $.extend(rasterize(this, options, history), {rasterize: chained});
	}

	var rasterize = function(collection, options, history) {
		var icon = options.to === 'favicon';
		options = $.extend({}, {
			attr: icon ? 'href' : 'src',
			dom: icon ? 'reinsert' : null,
			hd: false,
			height: null,
			preload: false,
			to: null,
			type: null,
			width: null
		}, options);
		if (icon) {
			options.to = getIcons();
			if (options.to.length === 0) {
				options.to = $('<link rel="icon" />').appendTo('head');
			}
		}
		var key = cacheKey(options);
		history[key] || (history[key] = {inProgress: []});
		var data = history[key];
		data.inProgress.push(options);
		if (data.dataUrl) {
			setUrls(data);
		} else if (data.inProgress.length === 1) {
			startRendering(collection, options, data);
		}
		return collection;
	};

	var cacheKey = function(options) {
		return [options.width, options.height, options.type, options.quality].join();
	};

	var startRendering = function(collection, options, data) {
		var attr = { width: 1, height: 1 };
		var html = new Array();
		collection.each(function() {
			var element = this === document ? $(':root') : $(this);
			html.push(element.html());
			var rect = this.getBoundingClientRect ? this.getBoundingClientRect() : { width: 0, height: 0 };
			var width = rect.width;
			var height = rect.height;
			width === 0 && (width = element.width());
			height === 0 && (height = element.height());
			attr = { width: Math.max(attr.width, width), height: Math.max(attr.height, height) };
		});

		var drawNextLayer = function() {
			if (html.length) {
				var layer = html.shift();
				if (typeof rasterizeHTML !== 'undefined') {
					rasterizeHTML.drawHTML(layer, canvas, {}, drawNextLayer);
				}
			} else {
				data.dataUrl = canvas.toDataURL(options.type, options.quality);
				setUrls(data);
				delete canvas;
			}
		};
		var canvas = $('<canvas/>').attr(attr).get(0);
		drawNextLayer();
		return collection;
	};

	var icons = 'head link[rel~=icon]';
	var getIcons = function() {
		return $(icons);
	};

	var setUrls = function(data) {
		while(data.inProgress.length) {
			loadImageAndSetUrl(data.dataUrl, data.inProgress.shift());
		}
	}

	var loadImageAndSetUrl = function(dataUrl, options) {
		if (!options.preload) {
			return setUrl(dataUrl, options);
		}
		var preload = new Image();
		preload.onload = function() {
			setUrl(preload.src, options);
		};
		preload.src = dataUrl;
	};

	var setUrl = function(dataUrl, options) {
		$(options.to).attr(options.attr, dataUrl).each(function() {
			if (options.dom === 'reinsert') {
				this.parentNode.insertBefore(this, this.nextSibling);
			}
		});
		options.done && options.done(dataUrl);
	};
})(jQuery);


text:
layout: page
title: Arnold Solutions Dinner
date: 2016-05-24
author: Maria Cruz
tags: weekly links, java
status: published
summary: Maecenas quis felis dui. Aenean iaculis dictum urna, sit.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 03/12/2016
  endDate: 03/17/2016
  ctyhocn: CAECLHX
  groupCode: ASD
published: true
---
Fusce eu libero porta, convallis dolor ut, rhoncus quam. Nulla ac ultricies nisl. Aliquam rhoncus est augue, at venenatis magna rutrum a. Praesent vel nibh non ex condimentum viverra sit amet at nulla. Proin aliquam laoreet nibh non malesuada. Praesent eget tellus nec dui eleifend finibus. Morbi hendrerit vehicula est, eu hendrerit ex euismod et. Nunc pulvinar euismod semper. Quisque vitae erat odio. Morbi nulla tellus, placerat vitae convallis et, malesuada eu ligula. Nam erat odio, iaculis at neque eget, ornare ultrices metus. Ut eget bibendum lorem. Nunc venenatis enim arcu, commodo luctus ipsum rutrum in.

* Nulla at sem elementum, laoreet tortor eu, placerat mi
* Morbi ut arcu non metus accumsan mattis sed vel risus
* Duis ut dui vel felis commodo auctor at eu metus
* Nam eu ligula id diam efficitur blandit vel at sem.

Vivamus hendrerit condimentum vulputate. Etiam mattis egestas tristique. Cras vel dolor et sem tempus tristique. Etiam eu ultrices libero. Nam finibus erat imperdiet orci egestas semper. In hac habitasse platea dictumst. Nulla diam lacus, volutpat at accumsan quis, aliquam non nisl.


text:
package org.fcrepo.kernel.modeshape.identifiers;

import static com.google.common.base.Joiner.on;
import static com.google.common.base.Splitter.fixedLength;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Lists.transform;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.UUID.randomUUID;
import static org.slf4j.LoggerFactory.getLogger;

import java.util.List;

import org.fcrepo.kernel.api.identifiers.InternalIdentifierConverter;
import org.slf4j.Logger;

/**
 * Injects and extracts segments of hierarchy before the last segment of a
 * multi-part identifier to ensure efficient performance of the JCR.
 *
 * @author ajs6f
 * @since Mar 26, 2014
 */
public class HierarchyConverter extends InternalIdentifierConverter {

    public static final String DEFAULT_SEPARATOR = "/";

    private String separator = DEFAULT_SEPARATOR;

    private String prefix = "";

    private static final int DEFAULT_LENGTH = 2;

    private static final int DEFAULT_COUNT = 4;

    private int length = DEFAULT_LENGTH;

    private int levels = DEFAULT_COUNT;

    private static final Logger log = getLogger(HierarchyConverter.class);

    /*
     * (non-Javadoc)
     * @see com.google.common.base.Converter#doBackward(java.lang.Object)
     */
    @Override
    protected String doBackward(final String flat) {
        log.debug("Converting incoming identifier: {}", flat);
        final List<String> hierarchySegments = createHierarchySegments();
        final List<String> flatSegments = asList(flat.split(separator));
        List<String> firstSegments = emptyList();
        List<String> lastSegment = emptyList();
        if (flatSegments.size() == 0) {
            // either empty identifier or separator identifier
            return on(separator).join(hierarchySegments);
        }
        if (flatSegments.size() > 1) {
            lastSegment = singletonList(getLast(flatSegments));
            firstSegments = flatSegments.subList(0, flatSegments.size() - 1);
        } else {
            // just one segment
            lastSegment = singletonList(flatSegments.get(0));
        }
        final Iterable<String> allSegments = concat(firstSegments, hierarchySegments, lastSegment);

        return on(separator).join(allSegments);
    }

    /*
     * (non-Javadoc)
     * @see com.google.common.base.Converter#doForward(java.lang.Object)
     */
    @Override
    protected String doForward(final String hierarchical) {
        log.debug("Converting outgoing identifier: {}", hierarchical);
        final List<String> segments = asList(hierarchical.split(separator));
        if (segments.size() <= levels) {
            // must be a root identifier
            return "";
        }
        List<String> firstSegments = emptyList();
        List<String> lastSegment = emptyList();
        if (segments.size() > levels + 1) {
            // we subtract one for the final segment, then levels for the
            // inserted hierarchy segments we want to remove
            firstSegments = segments.subList(0, segments.size() - 1 - levels);
            lastSegment = singletonList(getLast(segments));
        } else {
            // just the trailing non-hierarchical segment
            lastSegment = singletonList(getLast(segments));
        }
        return on(separator).join(concat(firstSegments, lastSegment));
    }

    private List<String> createHierarchySegments() {
        // offers a list of segments sliced out of a UUID, each prefixed
        if (levels == 0) {
            return emptyList();
        }
        return transform(fixedLength(length).splitToList(createHierarchyCharacterBlock()), x -> prefix + x);
    }

    private CharSequence createHierarchyCharacterBlock() {
        return randomUUID().toString().replace("-", "").substring(0, length * levels);
    }

    /**
     * @param sep the separator to use
     */
    public void setSeparator(final String sep) {
        this.separator = sep;
    }

    /**
     * @param l the length to set
     */
    public void setLength(final int l) {
        if (l < 1) {
            throw new IllegalArgumentException("Segment length must be at least one!");
        }
        this.length = l;
    }

    /**
     * @param l the levels to set
     */
    public void setLevels(final int l) {
        this.levels = l;
    }

    /**
     * @param p the prefix to set
     */
    public void setPrefix(final String p) {
        this.prefix = p;
    }

}


text:
package alec_wam.CrystalMod.blocks;

import net.minecraft.block.BlockRotatedPillar;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;

public class BlockBlazeRod extends BlockRotatedPillar
{
    public BlockBlazeRod()
    {
        super(Material.IRON, MapColor.SAND);
        this.setCreativeTab(CreativeTabs.BUILDING_BLOCKS);
        this.setHardness(5.0F);
        this.setResistance(10.0F);
        this.setSoundType(SoundType.METAL);
    }
}


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

describe Email do
  before(:each) do
    @email = Email.new
  end

  it "should be valid" do
    @email.should be_valid
  end
end


text:
namespace CLHEP {

class EngineFactory {
public:
  static HepRandomEngine* newEngine(std::istream & is);
  static HepRandomEngine* newEngine(std::vector<unsigned long> const & v);
};

}  // namespace CLHEP

#ifdef ENABLE_BACKWARDS_COMPATIBILITY
//  backwards compatibility will be enabled ONLY in CLHEP 1.9
using namespace CLHEP;
#endif

#endif


text:
import React, { forwardRef } from 'react';

import { StyledTableRow } from '../Table/StyledTable';

const TableRow = forwardRef((props, ref) => (
  <StyledTableRow ref={ref} {...props} />
));

TableRow.displayName = 'TableRow';

export { TableRow };


text:
<!doctype html>
<html>
<head>
    <title>Jasmine Spec Runner</title>

    <link rel="stylesheet" type="text/css" href="lib/jasmine.css">

    <script type="text/javascript" src="lib/jasmine.js"></script>
    <script type="text/javascript" src="lib/jasmine-html.js"></script>

    <script type="text/javascript" src="../shield.js"></script>

    <script type="text/javascript" src="shieldSpec.js"></script>

    <script type="text/javascript">
        (function() {
            var jasmineEnv = jasmine.getEnv();
            jasmineEnv.updateInterval = 1000;

            var htmlReporter = new jasmine.HtmlReporter();

            jasmineEnv.addReporter(htmlReporter);

            jasmineEnv.specFilter = function(spec) {
                return htmlReporter.specFilter(spec);
            };

            var currentWindowOnload = window.onload;

            window.onload = function() {
                if(currentWindowOnload) {
                    currentWindowOnload();
                }
                execJasmine();
            };

            function execJasmine() {
                jasmineEnv.execute();
            }
        })();
    </script>
</head>
<body>
</body>
</html>


text:
MyBatis Dynamic SQL works with Java objects that represent relational tables or views.

## Table or View Representation

The class `org.mybatis.dynamic.sql.SqlTable` is used to represent a table or view in a database. An `SqlTable` holds a
name, and a collection of `SqlColumn` objects that represent the columns in a table or view.

A table or view name in SQL has three parts:

1. The catalog - which is optional and is rarely used outside of Microsoft SQL Server. If unspecified the default
   catalog will be used - and many databases only have one catalog
1. The schema - which is optional but is very often specified. If unspecified, the default schema will be used
1. The table name - which is required

Typical examples of names are as follows:

- `"dbo..bar"` - a name with a catalog (dbo) and a table name (bar). This is typical for SQL Server
- `"foo.bar"` - a name with a schema (foo) and a table name (bar). This is typical in many databases when you want to
  access tables that are not in the default schema
- `"bar"` - a name with just a table name (bar). This will access a table or view in the default catalog and schema for
  a connection

In MyBatis Dynamic SQL, the table or view name can be specified in different ways:

1. The name can be a constant String
1. The name can be calculated at runtime based on a catalog and/or schema supplier functions and a constant table name
1. The name can be calculated at runtime with a name supplier function

### Constant Names

Constant names are used when you use the `SqlTable` constructor with a single String argument. For example:

```java
public class MyTable extends SqlTable {
    public MyTable() {
        super("MyTable");
    }
}
```

Or

```java
public class MyTable extends SqlTable {
    public MyTable() {
        super("MySchema.MyTable");
    }
}
```

### Dynamic Catalog and/or Schema Names
MyBatis Dynamic SQL allows you to dynamically specify a catalog and/or schema. This is useful for applications where
the schema may change for different users or environments, or if you are using different schemas to shard the database.
Dynamic names are used when you use a `SqlTable` constructor that accepts one or more `java.util.function.Supplier`
arguments.

For example, suppose you wanted to change the schema based on the value of a system property. You could write a class
like this:

```java
public class SchemaSupplier {
    public static final String schema_property = "schemaToUse";

    public static Optional<String> schemaPropertyReader() {
        return Optional.ofNullable(System.getProperty(schema_property));
    }
}
```

This class has a static method `schemaPropertyReader` that will return an `Optional<String>` containing the value of a
system property. You could then reference this method in the constructor of the `SqlTable` like this:

```java
public static final class User extends SqlTable {
    public User() {
        super(SchemaSupplier::schemaPropertyReader, "User");
    }
}
```

Whenever the table is referenced for rendering SQL, the name will be calculated based on the current value of the
system property.

There are two constructors that can be used for dynamic names:

1. A constructor that accepts `Supplier<Optional<String>>` for the schema, and `String` for the name. This constructor
   assumes that the catalog is always empty or not used
1. A constructor that accepts `Supplier<Optional<String>>` for the catalog, `Supplier<Optional<String>>` for the schema,
   and `String` for the name

If you are using Microsoft SQL Server and want to use a dynamic catalog name and ignore the schema, then you should use
the second constructor like this:

```java
public static final class User extends SqlTable {
    public User() {
        super(CatalogSupplier::catalogPropertyReader, Optional::empty, "User");
    }
}
```

The following table shows how the name is calculated in all combinations of suppliers:

Catalog Supplier Value | Schema Supplier Value | Name | Fully Qualified Name
---|---|---|---
"MyCatalog" | "MySchema" | "MyTable" | "MyCatalog.MySchema.MyTable"
<empty> | "MySchema" | "MyTable" | "MySchema.MyTable"
"MyCatalog" | <empty> | "MyTable" | "MyCatalog..MyTable"
<empty> | <empty> | "MyTable" | "MyTable"

### Fully Dynamic Names
MyBatis Dynamic SQL allows you to dynamically specify a full table name. This is useful for applications where the
database is sharded with different tables representing different shards of the whole. Dynamic names are used when you
use a `SqlTable` constructor that accepts a single `java.util.function.Supplier` argument.

For example, suppose you wanted to change the name based on the value of a system property. You could write a class
like this:

```java
public class NameSupplier {
    public static final String name_property = "nameToUse";

    public static String namePropertyReader() {
        return System.getProperty(name_property);
    }
}
```

This class has a static method `namePropertyReader` that will return an `String` containing the value of a system
property. You could then reference this method in the constructor of the `SqlTable` like this:

```java
public static final class User extends SqlTable {
    public User() {
        super(NameSupplier::namePropertyReader);
    }
}
```

Whenever the table is referenced for rendering SQL, the name will be calculated based on the current value of the system property.

## Aliased Tables

In join queries, it is usually a good practice to specify table aliases. The `select` statement includes
support for specifying table aliases in each query in a way that looks like natural SQL. For example:

```java
    SelectStatementProvider selectStatement = select(orderMaster.orderId, orderDate, orderLine.lineNumber, itemMaster.description, orderLine.quantity)
            .from(orderMaster, "om")
            .join(orderLine, "ol").on(orderMaster.orderId, equalTo(orderLine.orderId))
            .join(itemMaster, "im").on(orderLine.itemId, equalTo(itemMaster.itemId))
            .where(orderMaster.orderId, isEqualTo(2))
            .build()
            .render(RenderingStrategies.MYBATIS3);
```

In a query like this, the library will automatically append the table alias to the column name when the query is rendered.
Internally, the alias for a column is determined by looking up the associated table in a HashMap maintained within the
query model. If you do not specify a table alias, the library will automatically append the table name in join queries.

Unfortunately, this strategy fails for self-joins. It can also get confusing when there are sub-queries. Imagine a
query like this:

```java
    SelectStatementProvider selectStatement = select(user.userId, user.userName, user.parentId)
            .from(user, "u1")
            .join(user, "u2").on(user.userId, equalTo(user.parentId))
            .where(user.userId, isEqualTo(4))
            .build()
            .render(RenderingStrategies.MYBATIS3);
```

In this query it is not clear which instance of the `user` table is used for each column, and there will only be entry in the
HashMap for the `user` table - so only one of the aliases specified in the select statement will be in effect.
There are two ways to deal with this problem.

The first is to simply create another instance of the User SqlTable object. With this method it is very clear which column
belongs to which instance of the table and the library can easily calculate aliases:

```java
    User user1 = new User();
    User user2 = new User();
    SelectStatementProvider selectStatement = select(user1.userId, user1.userName, user1.parentId)
            .from(user1, "u1")
            .join(user2, "u2").on(user1.userId, equalTo(user2.parentId))
            .where(user2.userId, isEqualTo(4))
            .build()
            .render(RenderingStrategies.MYBATIS3);
```

Starting with version 1.3.1, there is new method where the alias can be specified in the table object itself. This allows
you to move the aliases out of the `select` statement.

```java
    User user1 = user.withAlias("u1");
    User user2 = user.withAlias("u2");

    SelectStatementProvider selectStatement = select(user1.userId, user1.userName, user1.parentId)
            .from(user1)
            .join(user2).on(user1.userId, equalTo(user2.parentId))
            .where(user2.userId, isEqualTo(4))
            .build()
            .render(RenderingStrategies.MYBATIS3);
```

To enable this support, your table objects should extend `org.mybatis.dynamic.sql.AliasableSqlTable` rather than
`org.mybatis.dynamic.sql.SqlTable` as follows:

```java
    public static final class User extends AliasableSqlTable<User> {
        public final SqlColumn<Integer> userId = column("user_id", JDBCType.INTEGER);
        public final SqlColumn<String> userName = column("user_name", JDBCType.VARCHAR);
        public final SqlColumn<Integer> parentId = column("parent_id", JDBCType.INTEGER);

        public User() {
            super("User", User::new);
        }
    }
```

If you use an aliased table object, and also specify an alias in the `select` statement, the alias from the `select`
statement will override the alias in the table object.

## Column Representation

The class `org.mybatis.dynamic.sql.SqlColumn` is used to represent a column in a table or view. An `SqlColumn` is always
associated with a `SqlTable`. In its most basic form, the `SqlColumn` class holds a name and a reference to the
`SqlTable` it is associated with. The table reference is required so that table aliases can be applied to columns in the
rendering phase.

The `SqlColumn` will be rendered in SQL based on the `RenderingStrategy` applied to the SQL statement. Typically the
rendering strategy generates a string that represents a parameter marker in whatever SQL engine you are using. For
example, MyBatis3 parameter markers are formatted as "#{some_attribute}". By default, all columns are rendered with the
same strategy. The library supplies rendering strategies that are appropriate for several SQL execution engines
including MyBatis3 and Spring JDBC template.

In some cases it is necessary to override the rendering strategy for a particular column - so the `SqlColumn` class
supports specifying a rendering strategy for a column that will override the rendering strategy applied to a statement.
A good example of this use case is with PostgreSQL. In that database it is required to add the string "::jsonb" to a
prepared statement parameter marker when inserting or updating JSON fields, but not for other fields. A column based
rendering strategy enables this.

The `SqlColumn` class has additional optional attributes that are useful for SQL rendering - especially in MyBatis3.
These include:

* The `java.sql.JDBCType` of the column. This will be rendered into the MyBatis3 compatible parameter marker - which
  helps with picking type handlers and also inserting or updating null capable fields
* A String containing a type handler - either a type handler alias or the fully qualified type of a type handler. This
  will be rendered into the MyBatis3 compatible parameter marker

If you are not using MyBatis3, then you do not need to specify the JDBC Type or type handler as those attributes are
ignored by other rendering strategies.

Finally, the `SqlColumn` class has methods to designate a column alias or sort order for use in different SQL
statements.

We recommend a usage pattern for creating table and column objects that provides quite a bit of flexibility for usage.
See the [Quick Start](quickStart.html) page for a complete example.


text:
class Audit < ActiveRecord::Base
  include Authority::Abilities
end


text:
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Nest
{
	[JsonConverter(typeof(StringEnumConverter))]
	public enum SimilarityOption
	{
		[EnumMember(Value = "default")]
		Default,
		[EnumMember(Value = "BM25")]
		BM25
	}
}


text:
namespace dotnet_ildasm.Sample.Classes
{
    public sealed class PublicSealedClass
    {
    }
}


text:
<!DOCTYPE html>

      <meta charset = "utf-8">
      <title>CodeIgniter Session Example</title>

      Welcome <?php echo $this->session->userdata('name'); ?>

         Click Here to unset session data.


text:
using System;
using System.ComponentModel;

namespace Azure.AI.Language.Conversations
{
    /// <summary> The SummaryAspect. </summary>
    public readonly partial struct SummaryAspect : IEquatable<SummaryAspect>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="SummaryAspect"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public SummaryAspect(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string IssueValue = "issue";
        private const string ResolutionValue = "resolution";
        private const string ChapterTitleValue = "chapterTitle";
        private const string NarrativeValue = "narrative";

        /// <summary> A summary of issues in transcripts of web chats and service call transcripts between customer-service agents, and your customers. </summary>
        public static SummaryAspect Issue { get; } = new SummaryAspect(IssueValue);
        /// <summary> A summary of resolutions in transcripts of web chats and service call transcripts between customer-service agents, and your customers. </summary>
        public static SummaryAspect Resolution { get; } = new SummaryAspect(ResolutionValue);
        /// <summary> A chapter title of any conversation. It is usually one phrase or several phrases naturally combined together. Long conversation tends to have more chapters. The chapter boundary can be found from the summary context. </summary>
        public static SummaryAspect ChapterTitle { get; } = new SummaryAspect(ChapterTitleValue);
        /// <summary> A generic narrative summary of any conversation. It generally converts the conversational language into formal written language, compresses the text length and keeps the salient information. </summary>
        public static SummaryAspect Narrative { get; } = new SummaryAspect(NarrativeValue);
        /// <summary> Determines if two <see cref="SummaryAspect"/> values are the same. </summary>
        public static bool operator ==(SummaryAspect left, SummaryAspect right) => left.Equals(right);
        /// <summary> Determines if two <see cref="SummaryAspect"/> values are not the same. </summary>
        public static bool operator !=(SummaryAspect left, SummaryAspect right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="SummaryAspect"/>. </summary>
        public static implicit operator SummaryAspect(string value) => new SummaryAspect(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is SummaryAspect other && Equals(other);
        /// <inheritdoc />
        public bool Equals(SummaryAspect other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
package org.codehaus.waffle.action.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 *
This annotation identifies a method as being an Action Method.
 * See {@link org.codehaus.waffle.action.intercept.SecurityMethodInterceptor} to protect your application
 * from potential security risk (e.g. hackers).

 *
 * @author Mauro Talevi
 * @author Michael Ward
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ActionMethod {

    /**
     * Used to define the parameter names that should be used to resolve an action methods
     * arguments (order is important).
     *
     * @return the parameter names to resolve with
     */
    String[] parameters() default {};

    /**
     * When set signal that the annotated method should be invoked when no other ActionMethod was requested.
     *
     * @return true if the annotated method should be default.
     */
    boolean asDefault() default false;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
	<testsuite name="PrivateTestsGrader" tests="2" time="0.000" failures="0" errors="0" skipped="0">
		<testcase classname="PrivateTestsGrader" name="test_private_01" time="0.000">
			<meta expression="get_tag_type(to_rna(tagged_dna1))" expected="'rna'" hint="" output="'rna'"/>
		</testcase>
		<testcase classname="PrivateTestsGrader" name="test_private_02" time="0.000">
			<meta expression="get_tag_type(to_dna(tagged_rna1))" expected="'dna'" hint="" output="'dna'"/>
		</testcase>
		<system-out><![CDATA[]]></system-out>
		<system-err><![CDATA[]]></system-err>
	</testsuite>n
</testsuites>


text:
<?php

namespace Acme\StoreBundle\Entity;

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

/**
 * Owner
 */
class Owner {

    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $firstName;

    /**
     * @var string
     */
    private $lastName;

    /**
     * @var \Date
     */
    private $born;

    /**
     * @var string
     */
    private $gender;

    /**
     * @var array
     */
    protected $cars;

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

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

    /**
     * Set firstName
     *
     * @param string $firstName
     * @return Owner
     */
    public function setFirstName($firstName) {
        $this->firstName = $firstName;

        return $this;
    }

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

    /**
     * Set lastName
     *
     * @param string $lastName
     * @return Owner
     */
    public function setLastName($lastName) {
        $this->lastName = $lastName;

        return $this;
    }

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

    /**
     * Set born
     *
     * @param \DateTime $born
     * @return Owner
     */
    public function setBorn($born) {
        $this->born = $born;

        return $this;
    }

    /**
     * Get born
     *
     * @return \DateTime
     */
    public function getBorn() {
        return $this->born;
    }

    /**
     * Set gender
     *
     * @param string $gender
     * @return Owner
     */
    public function setGender($gender) {
        $this->gender = $gender;

        return $this;
    }

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

    public function __toString() {
        $owner = $this->getFirstName(). ' ' . $this->getLastName();
        return (string) $owner;
    }

}


text:
package br.com.fuelclub.bo;

import java.util.List;

import br.com.fuelclub.dao.CartaoDao;
import br.com.fuelclub.entity.Cartao;

public class CartaoBo implements InterfaceBo<Cartao>{

	CartaoDao cartaoBo = new CartaoDao();

	@Override
	public void salvar(Cartao cartao) throws Exception {
		try {
			cartaoBo.salvar(cartao);
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	@Override
	public List<Cartao> listar() {
		return cartaoBo.listas();

	}

	@Override
	public void editar(Cartao cartao) {
		cartaoBo.editar(cartao);
	}

	@Override
	public Cartao getObjectTById(Long id) {
		return cartaoBo.getObjectTById(id);
	}

	@Override
	public void excluir(Cartao cartao) {
		cartaoBo.excluir(cartao);
	}

	public boolean existe(Cartao cartao){
		List<Cartao> lista = new CartaoDao().listar(cartao);
		if(lista.size() > 0){
			return true;
		}else{
			return false;
		}
	}

}


text:
if [ -z "$KEYSIZE" ]; then
  KEYSIZE=4096
fi

if [ ! -e imageFiles/tls/key.pem ]; then
  echo "Generating key.  This can take a few seconds."
  openssl req \
    -newkey rsa:$KEYSIZE -sha256 -nodes \
    -subj "/CN=bidms-samba/OU=BIDMS Samba Docker Dev/" \
    -keyout imageFiles/tls/key.pem \
    -x509 \
    -days 10000 \
    -out imageFiles/tls/cert.pem \
  && chmod 600 imageFiles/tls/key.pem \
  && cp imageFiles/tls/cert.pem imageFiles/tls/ca.pem
else
  echo "imageFiles/tls/key.pem already exists"
  exit 1
fi


text:
import { Component, Type } from '../../src'

test('Component', () => {
  const component = new Component('uid', Type.Uint16)

  expect(component.name).toBe('uid')
  expect(component.def.byteLength).toBe(2)
})


text:
/* global Windows, WinJS */

const FTErr = require('./FileTransferError');
const ProgressEvent = require('cordova-plugin-file.ProgressEvent');
const FileUploadResult = require('cordova-plugin-file.FileUploadResult');
const FileProxy = require('cordova-plugin-file.FileProxy');

const appData = Windows.Storage.ApplicationData.current;

const LINE_START = '--';
const LINE_END = '\r\n';
const BOUNDARY = '+++++';

const fileTransferOps = [];

// Some private helper functions, hidden by the module
function cordovaPathToNative (path) {
    let cleanPath = String(path);
    // turn / into \\
    cleanPath = cleanPath.replace(/\//g, '\\');
    // turn  \\ into \
    cleanPath = cleanPath.replace(/\\\\/g, '\\');
    // strip end \\ characters
    cleanPath = cleanPath.replace(/\\+$/g, '');
    return cleanPath;
}

function nativePathToCordova (path) {
    return String(path).replace(/\\/g, '/');
}

function alreadyCancelled (opId) {
    const op = fileTransferOps[opId];
    return op && op.state === FileTransferOperation.CANCELLED;
}

function doUpload (upload, uploadId, filePath, server, successCallback, errorCallback) {
    if (alreadyCancelled(uploadId)) {
        errorCallback(new FTErr(FTErr.ABORT_ERR, nativePathToCordova(filePath), server));
        return;
    }

    // update internal TransferOperation object with newly created promise
    const uploadOperation = upload.startAsync();
    fileTransferOps[uploadId].promise = uploadOperation;

    uploadOperation.then(
        function (result) {
            // Update TransferOperation object with new state, delete promise property
            // since it is not actual anymore
            const currentUploadOp = fileTransferOps[uploadId];
            if (currentUploadOp) {
                currentUploadOp.state = FileTransferOperation.DONE;
                currentUploadOp.promise = null;
            }

            const response = result.getResponseInformation();
            const ftResult = new FileUploadResult(result.progress.bytesSent, response.statusCode, '');

            // if server's response doesn't contain any data, then resolve operation now
            if (result.progress.bytesReceived === 0) {
                successCallback(ftResult);
                return;
            }

            // otherwise create a data reader, attached to response stream to get server's response
            const reader = new Windows.Storage.Streams.DataReader(result.getResultStreamAt(0));
            reader.loadAsync(result.progress.bytesReceived).then(function (size) {
                ftResult.response = reader.readString(size);
                successCallback(ftResult);
                reader.close();
            });
        },
        function (error) {
            const source = nativePathToCordova(filePath);

            // Handle download error here.
            // Wrap this routines into promise due to some async methods
            const getTransferError = new WinJS.Promise(function (resolve) {
                if (error.message === 'Canceled') {
                    // If download was cancelled, message property will be specified
                    resolve(new FTErr(FTErr.ABORT_ERR, source, server, null, null, error));
                } else {
                    // in the other way, try to get response property
                    const response = upload.getResponseInformation();
                    if (!response) {
                        resolve(new FTErr(FTErr.CONNECTION_ERR, source, server));
                    } else {
                        const reader = new Windows.Storage.Streams.DataReader(upload.getResultStreamAt(0));
                        reader.loadAsync(upload.progress.bytesReceived).then(function (size) {
                            const responseText = reader.readString(size);
                            resolve(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, server, response.statusCode, responseText, error));
                            reader.close();
                        });
                    }
                }
            });

            // Update TransferOperation object with new state, delete promise property
            // since it is not actual anymore
            const currentUploadOp = fileTransferOps[uploadId];
            if (currentUploadOp) {
                currentUploadOp.state = FileTransferOperation.CANCELLED;
                currentUploadOp.promise = null;
            }

            // Report the upload error back
            getTransferError.then(function (transferError) {
                errorCallback(transferError);
            });
        },
        function (evt) {
            const progressEvent = new ProgressEvent('progress', {
                loaded: evt.progress.bytesSent,
                total: evt.progress.totalBytesToSend,
                target: evt.resultFile
            });
            progressEvent.lengthComputable = true;
            successCallback(progressEvent, { keepCallback: true });
        }
    );
}

function FileTransferOperation (state, promise) {
    this.state = state;
    this.promise = promise;
}

FileTransferOperation.PENDING = 0;
FileTransferOperation.DONE = 1;
FileTransferOperation.CANCELLED = 2;

const HTTP_E_STATUS_NOT_MODIFIED = -2145844944;

module.exports = {
    /*
exec(win, fail, 'FileTransfer', 'upload',
[filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
*/
    upload: function (successCallback, errorCallback, options) {
        let filePath = options[0];
        const server = options[1];
        const fileKey = options[2] || 'source';
        let fileName = options[3];
        let mimeType = options[4];
        const params = options[5];
        // var trustAllHosts = options[6]; // todo
        // var chunkedMode = options[7]; // todo
        const headers = options[8] || {};
        const uploadId = options[9];
        const httpMethod = options[10];

        const isMultipart = typeof headers['Content-Type'] === 'undefined';

        function stringToByteArray (str) {
            const byteCharacters = atob(str);
            const byteNumbers = new Array(byteCharacters.length);
            for (let i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            return new Uint8Array(byteNumbers);
        }

        if (!filePath || typeof filePath !== 'string') {
            errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, null, server));
            return;
        }

        if (filePath.indexOf('data:') === 0 && filePath.indexOf('base64') !== -1) {
            // First a DataWriter object is created, backed by an in-memory stream where
            // the data will be stored.
            const writer = Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream());
            writer.unicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.utf8;
            writer.byteOrder = Windows.Storage.Streams.ByteOrder.littleEndian;

            const commaIndex = filePath.indexOf(',');
            if (commaIndex === -1) {
                errorCallback(new FTErr(FTErr.INVALID_URL_ERR, fileName, server, null, null, 'No comma in data: URI'));
                return;
            }

            // Create internal download operation object
            fileTransferOps[uploadId] = new FileTransferOperation(FileTransferOperation.PENDING, null);

            const fileDataString = filePath.substr(commaIndex + 1);

            // setting request headers for uploader
            const uploader = new Windows.Networking.BackgroundTransfer.BackgroundUploader();
            uploader.method = httpMethod;
            for (const header in headers) {
                if (Object.prototype.hasOwnProperty.call(headers, header)) {
                    uploader.setRequestHeader(header, headers[header]);
                }
            }

            if (isMultipart) {
                // adding params supplied to request payload
                let multipartParams = '';
                for (const key in params) {
                    if (Object.prototype.hasOwnProperty.call(params, key)) {
                        multipartParams += LINE_START + BOUNDARY + LINE_END;
                        multipartParams += 'Content-Disposition: form-data; name="' + key + '"';
                        multipartParams += LINE_END + LINE_END;
                        multipartParams += params[key];
                        multipartParams += LINE_END;
                    }
                }

                let multipartFile = LINE_START + BOUNDARY + LINE_END;
                multipartFile += 'Content-Disposition: form-data; name="file";';
                multipartFile += ' filename="' + fileName + '"' + LINE_END;
                multipartFile += 'Content-Type: ' + mimeType + LINE_END + LINE_END;

                const bound = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;

                uploader.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + BOUNDARY);
                writer.writeString(multipartParams);
                writer.writeString(multipartFile);
                writer.writeBytes(stringToByteArray(fileDataString));
                writer.writeString(bound);
            } else {
                writer.writeBytes(stringToByteArray(fileDataString));
            }

            let stream;

            // The call to store async sends the actual contents of the writer
            // to the backing stream.
            writer
                .storeAsync()
                .then(function () {
                    // For the in-memory stream implementation we are using, the flushAsync call
                    // is superfluous, but other types of streams may require it.
                    return writer.flushAsync();
                })
                .then(function () {
                    // We detach the stream to prolong its useful lifetime. Were we to fail
                    // to detach the stream, the call to writer.close() would close the underlying
                    // stream, preventing its subsequent use by the DataReader below. Most clients
                    // of DataWriter will have no reason to use the underlying stream after
                    // writer.close() is called, and will therefore have no reason to call
                    // writer.detachStream(). Note that once we detach the stream, we assume
                    // responsibility for closing the stream subsequently; after the stream
                    // has been detached, a call to writer.close() will have no effect on the stream.
                    stream = writer.detachStream();
                    // Make sure the stream is read from the beginning in the reader
                    // we are creating below.
                    stream.seek(0);
                    // Most DataWriter clients will not call writer.detachStream(),
                    // and furthermore will be working with a file-backed or network-backed stream,
                    // rather than an in-memory-stream. In such cases, it would be particularly
                    // important to call writer.close(). Doing so is always a best practice.
                    writer.close();

                    if (alreadyCancelled(uploadId)) {
                        errorCallback(new FTErr(FTErr.ABORT_ERR, nativePathToCordova(filePath), server));
                        return;
                    }

                    // create download object. This will throw an exception if URL is malformed
                    const uri = new Windows.Foundation.Uri(server);

                    let createUploadOperation;
                    try {
                        createUploadOperation = uploader.createUploadFromStreamAsync(uri, stream);
                    } catch (e) {
                        errorCallback(new FTErr(FTErr.INVALID_URL_ERR));
                        return;
                    }

                    createUploadOperation.then(
                        function (upload) {
                            doUpload(upload, uploadId, filePath, server, successCallback, errorCallback);
                        },
                        function (err) {
                            const errorObj = new FTErr(FTErr.INVALID_URL_ERR);
                            errorObj.exception = err;
                            errorCallback(errorObj);
                        }
                    );
                });

            return;
        }

        if (filePath.substr(0, 8) === 'file:///') {
            filePath = appData.localFolder.path + filePath.substr(8).split('/').join('\\');
        } else if (filePath.indexOf('ms-appdata:///') === 0) {
            // Handle 'ms-appdata' scheme
            filePath = filePath
                .replace('ms-appdata:///local', appData.localFolder.path)
                .replace('ms-appdata:///temp', appData.temporaryFolder.path);
        } else if (filePath.indexOf('cdvfile://') === 0) {
            filePath = filePath
                .replace('cdvfile://localhost/persistent', appData.localFolder.path)
                .replace('cdvfile://localhost/temporary', appData.temporaryFolder.path);
        }

        // normalize path separators
        filePath = cordovaPathToNative(filePath);

        // Create internal download operation object
        fileTransferOps[uploadId] = new FileTransferOperation(FileTransferOperation.PENDING, null);

        Windows.Storage.StorageFile.getFileFromPathAsync(filePath).then(
            function (storageFile) {
                if (!fileName) {
                    fileName = storageFile.name;
                }
                if (!mimeType) {
                    // use the actual content type of the file, probably this should be the default way.
                    // other platforms probably can't look this up.
                    mimeType = storageFile.contentType;
                }

                if (alreadyCancelled(uploadId)) {
                    errorCallback(new FTErr(FTErr.ABORT_ERR, nativePathToCordova(filePath), server));
                    return;
                }

                // setting request headers for uploader
                const uploader = new Windows.Networking.BackgroundTransfer.BackgroundUploader();
                uploader.method = httpMethod;
                for (const header in headers) {
                    if (Object.prototype.hasOwnProperty.call(headers, header)) {
                        uploader.setRequestHeader(header, headers[header]);
                    }
                }

                // create download object. This will throw an exception if URL is malformed
                const uri = new Windows.Foundation.Uri(server);

                let createUploadOperation;
                try {
                    if (isMultipart) {
                        // adding params supplied to request payload
                        const transferParts = [];
                        for (const key in params) {
                            // Create content part for params only if value is specified because CreateUploadAsync fails otherwise
                            if (
                                Object.prototype.hasOwnProperty.call(params, key) &&
                                params[key] !== null &&
                                params[key] !== undefined &&
                                params[key].toString() !== ''
                            ) {
                                const contentPart = new Windows.Networking.BackgroundTransfer.BackgroundTransferContentPart();
                                contentPart.setHeader('Content-Disposition', 'form-data; name="' + key + '"');
                                contentPart.setText(params[key]);
                                transferParts.push(contentPart);
                            }
                        }

                        // Adding file to upload to request payload
                        const fileToUploadPart = new Windows.Networking.BackgroundTransfer.BackgroundTransferContentPart(fileKey, fileName);
                        fileToUploadPart.setHeader('Content-Type', mimeType);
                        fileToUploadPart.setFile(storageFile);
                        transferParts.push(fileToUploadPart);

                        createUploadOperation = uploader.createUploadAsync(uri, transferParts);
                    } else {
                        createUploadOperation = WinJS.Promise.wrap(uploader.createUpload(uri, storageFile));
                    }
                } catch (e) {
                    errorCallback(new FTErr(FTErr.INVALID_URL_ERR));
                    return;
                }

                createUploadOperation.then(
                    function (upload) {
                        doUpload(upload, uploadId, filePath, server, successCallback, errorCallback);
                    },
                    function (err) {
                        const errorObj = new FTErr(FTErr.INVALID_URL_ERR);
                        errorObj.exception = err;
                        errorCallback(errorObj);
                    }
                );
            },
            function (err) {
                errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, fileName, server, null, null, err));
            }
        );
    },

    // [source, target, trustAllHosts, id, headers]
    download: function (successCallback, errorCallback, options) {
        const source = options[0];
        let target = options[1];
        const downloadId = options[3];
        const headers = options[4] || {};

        if (!target) {
            errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR));
            return;
        }
        if (target.substr(0, 8) === 'file:///') {
            target = appData.localFolder.path + target.substr(8).split('/').join('\\');
        } else if (target.indexOf('ms-appdata:///') === 0) {
            // Handle 'ms-appdata' scheme
            target = target
                .replace('ms-appdata:///local', appData.localFolder.path)
                .replace('ms-appdata:///temp', appData.temporaryFolder.path);
        } else if (target.indexOf('cdvfile://') === 0) {
            target = target
                .replace('cdvfile://localhost/persistent', appData.localFolder.path)
                .replace('cdvfile://localhost/temporary', appData.temporaryFolder.path);
        }
        target = cordovaPathToNative(target);

        const path = target.substr(0, target.lastIndexOf('\\'));
        const fileName = target.substr(target.lastIndexOf('\\') + 1);
        if (path === null || fileName === null) {
            errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR));
            return;
        }
        // Download to a temp file to avoid the file deletion on 304
        // CB-7006 Empty file is created on file transfer if server response is 304
        const tempFileName = '~' + fileName;

        let download = null;

        // Create internal download operation object
        fileTransferOps[downloadId] = new FileTransferOperation(FileTransferOperation.PENDING, null);

        const downloadCallback = function (storageFolder) {
            storageFolder.createFileAsync(tempFileName, Windows.Storage.CreationCollisionOption.replaceExisting).then(
                function (storageFile) {
                    if (alreadyCancelled(downloadId)) {
                        errorCallback(new FTErr(FTErr.ABORT_ERR, source, target));
                        return;
                    }

                    // if download isn't cancelled, contunue with creating and preparing download operation
                    const downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();
                    for (const header in headers) {
                        if (Object.prototype.hasOwnProperty.call(headers, header)) {
                            downloader.setRequestHeader(header, headers[header]);
                        }
                    }

                    // create download object. This will throw an exception if URL is malformed
                    try {
                        const uri = Windows.Foundation.Uri(source);
                        download = downloader.createDownload(uri, storageFile);
                    } catch (e) {
                        // so we handle this and call errorCallback
                        errorCallback(new FTErr(FTErr.INVALID_URL_ERR));
                        return;
                    }

                    const downloadOperation = download.startAsync();
                    // update internal TransferOperation object with newly created promise
                    fileTransferOps[downloadId].promise = downloadOperation;

                    downloadOperation.then(
                        function () {
                            // Update TransferOperation object with new state, delete promise property
                            // since it is not actual anymore
                            const currentDownloadOp = fileTransferOps[downloadId];
                            if (currentDownloadOp) {
                                currentDownloadOp.state = FileTransferOperation.DONE;
                                currentDownloadOp.promise = null;
                            }

                            storageFile.renameAsync(fileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(
                                function () {
                                    const nativeURI = storageFile.path
                                        .replace(appData.localFolder.path, 'ms-appdata:///local')
                                        .replace(appData.temporaryFolder.path, 'ms-appdata:///temp')
                                        .replace(/\\/g, '/');

                                    // Passing null as error callback here because downloaded file should exist in any case
                                    // otherwise the error callback will be hit during file creation in another place
                                    FileProxy.resolveLocalFileSystemURI(successCallback, null, [nativeURI]);
                                },
                                function (error) {
                                    errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, null, null, error));
                                }
                            );
                        },
                        function (error) {
                            const getTransferError = new WinJS.Promise(function (resolve) {
                                // Handle download error here. If download was cancelled,
                                // message property will be specified
                                if (error.message === 'Canceled') {
                                    resolve(new FTErr(FTErr.ABORT_ERR, source, target, null, null, error));
                                } else if (error && error.number === HTTP_E_STATUS_NOT_MODIFIED) {
                                    resolve(new FTErr(FTErr.NOT_MODIFIED_ERR, source, target, 304, null, error));
                                } else {
                                    // in the other way, try to get response property
                                    const response = download.getResponseInformation();
                                    if (!response) {
                                        resolve(new FTErr(FTErr.CONNECTION_ERR, source, target));
                                    } else {
                                        if (download.progress.bytesReceived === 0) {
                                            resolve(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, response.statusCode, null, error));
                                            return;
                                        }
                                        const reader = new Windows.Storage.Streams.DataReader(download.getResultStreamAt(0));
                                        reader.loadAsync(download.progress.bytesReceived).then(function (bytesLoaded) {
                                            const payload = reader.readString(bytesLoaded);
                                            resolve(
                                                new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, response.statusCode, payload, error)
                                            );
                                        });
                                    }
                                }
                            });
                            getTransferError.then(function (fileTransferError) {
                                // Update TransferOperation object with new state, delete promise property
                                // since it is not actual anymore
                                const currentDownloadOp = fileTransferOps[downloadId];
                                if (currentDownloadOp) {
                                    currentDownloadOp.state = FileTransferOperation.CANCELLED;
                                    currentDownloadOp.promise = null;
                                }

                                // Cleanup, remove incompleted file
                                storageFile.deleteAsync().then(function () {
                                    errorCallback(fileTransferError);
                                });
                            });
                        },
                        function (evt) {
                            const progressEvent = new ProgressEvent('progress', {
                                loaded: evt.progress.bytesReceived,
                                total: evt.progress.totalBytesToReceive,
                                target: evt.resultFile
                            });
                            // when bytesReceived == 0, BackgroundDownloader has not yet differentiated whether it could get file length or not,
                            // when totalBytesToReceive == 0, BackgroundDownloader is unable to get file length
                            progressEvent.lengthComputable = evt.progress.bytesReceived > 0 && evt.progress.totalBytesToReceive > 0;

                            successCallback(progressEvent, { keepCallback: true });
                        }
                    );
                },
                function (error) {
                    errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, null, null, error));
                }
            );
        };

        const fileNotFoundErrorCallback = function (error) {
            errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, null, null, error));
        };

        Windows.Storage.StorageFolder.getFolderFromPathAsync(path).then(downloadCallback, function (error) {
            // Handle non-existent directory
            if (error.number === -2147024894) {
                const parent = path.substr(0, path.lastIndexOf('\\'));
                const folderNameToCreate = path.substr(path.lastIndexOf('\\') + 1);

                Windows.Storage.StorageFolder.getFolderFromPathAsync(parent).then(function (parentFolder) {
                    parentFolder.createFolderAsync(folderNameToCreate).then(downloadCallback, fileNotFoundErrorCallback);
                }, fileNotFoundErrorCallback);
            } else {
                fileNotFoundErrorCallback();
            }
        });
    },

    abort: function (successCallback, error, options) {
        const fileTransferOpId = options[0];

        // Try to find transferOperation with id specified, and cancel its' promise
        const currentOp = fileTransferOps[fileTransferOpId];
        if (currentOp) {
            currentOp.state = FileTransferOperation.CANCELLED;
            currentOp.promise && currentOp.promise.cancel();
        } else if (typeof fileTransferOpId !== 'undefined') {
            // Create the operation in cancelled state to be aborted right away
            fileTransferOps[fileTransferOpId] = new FileTransferOperation(FileTransferOperation.CANCELLED, null);
        }
    }
};

require('cordova/exec/proxy').add('FileTransfer', module.exports);


text:
ACCEPTED

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

#### Published in
N. Amer. Slime-Moulds (New York) 103 (1899)

#### Original name
Chondrioderma sauteri Rostaf., 1874

### Remarks
null


text:
package ODEsolver.interpreter;

//-----------------------------------------------------------------------------
// Written 2002 by Juergen Arndt.
//
//
// File Ex2.java
// Use  semantische funktion fuer vorzeichenminus
//-----------------------------------------------------------------------------

class Ex2 implements SemFuncPointer
{
   public int exec (double a)
   {
      return 1;
   }

   public int exec ()
   {
      //System.out.println ("\n   EX2: vorzeichenminus ende");

      Node K;

      K = (Node) stack.peek();

      if ( K.GetInfoString().equals ("vorzeichenminus") )
      {
         stack.pop();
         //System.out.println ("\n   Ex2: vorzeichenminus wurde entfernt\n");
      }
      else
      {
         //System.out.println ("\n   Ex2: das war gar kein vorzeichenminus!");
         //System.exit(-1);
      }

      return 1;
   }

   public int exec (String str)
   {
      return 1;
   }
}


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

namespace Liath.BigSpace.UI.Web.Areas.OuterSpace.Models.LocalArea
{
    public class SystemSummary
    {
        public int X { get; set; }
        public int Y { get; set; }
        public string Name { get; set; }
        public Int64 ID { get; set; }
    }
}


text:
'use strict';

angular.module('GoogleCalendarService', [], function ($provide) {

	$provide.factory('$googleCalendar', function ($http, $q, $location) {

		var $scope = angular.element(document).scope();

		//the url where our node.js application is located
		var baseUrl = $location.protocol() + '://' + location.host;

		return {
			getEventByUser: function (user, startDate, endDate) {
				var defer = $q.defer();

				var jsonData = {
					params: {
						startdate: startDate,
						enddate: endDate,
						user: user.fName + ' ' + user.lName
					}
				};

				$http.get(baseUrl + '/api/getEventByUser', jsonData)
					.then(function (response) {

						if (response.status === 200) {
							$scope.$broadcast('GoogleEventsReceived', response.data.items);
							defer.resolve(response.data.items);
							console.log(response.data.items);
						}

						else {
							$scope.$broadcast('GoogleError', response.data);
							defer.reject(response.data);
						}

					});

				return defer.promise;
			},
			getEvents: function () {
				var defer = $q.defer();

				$http.get(baseUrl + '/api/events').then(function (response) {

					if (response.status === 200) {
						$scope.$broadcast('GoogleEventsReceived', response.data.items);
						defer.resolve(response.data.items);
						console.log(response.data.items);
					}

					else {
						$scope.$broadcast('GoogleError', response.data);
						defer.reject(response.data);
					}

				});

				return defer.promise;
			},
			addEvent: function (scheduledDate, endDate, contactInfo, patientInfo) {
				var defer = $q.defer();

				/*
				$scope.patientInfo = {
                    patientName: $scope.event.patientName,
                    patientAge: $scope.event.patientAge,
                    patientGender: $scope.event.patientGender,
                    patientPlace: $scope.event.patientPlace,
                    contact: $scope.event.patientPhoneNumber,
                    emailId: $scope.event.patientEmail,
                    patientSelectedMedicalCondition: $scope.patientSelectedMedicalCondition,
                    patientChiefComplaint: $scope.event.patientChiefComplaint,
                };

                var contactInfo = {
                    doctorName: this.selectedDentist.fName + ' ' + this.selectedDentist.lName,
                    emailId: this.selectedDentist.emailId,
                    treatment: this.selectedTreatment.description
                };*/

				var postData = {
					startdate: scheduledDate,
					enddate: endDate,
					personal: contactInfo,
                    patient: patientInfo
				};

				$http.post(baseUrl + '/api/events', postData, { 'Content-Type': 'application/json' })
					.then(function (response) {

						if (response.status === 200) {
							$scope.$broadcast('eventAddedSuccess', response.data);
							defer.resolve(response.data);
						}
						else {
							console.log(response.data);
							$scope.$broadcast('GoogleError', response.data);
							defer.reject(response.data);
						}
					},
					function (response) {
						console.log(response.data);
						$scope.$broadcast('GoogleError', response.data);
						defer.reject(response.data);
					});

				return defer.promise;
			}
		};

	});

});


text:
using Chinchilla.Topologies.Model;
using Machine.Fakes;
using Machine.Specifications;

namespace Chinchilla.Specifications.Topologies.Model
{
    public class QueueSpecification
    {
        [Subject(typeof(Queue))]
        public class in_general : with_queue
        {
            It should_not_have_bindings = () =>
                Subject.HasBindings.ShouldBeFalse();

            It should_not_have_deadletter_exchange = () =>
                Subject.DeadLetterExchange.ShouldBeNull();
        }

        [Subject(typeof(Queue))]
        public class without_name
        {
            Establish context = () =>
                queue = new Queue();

            It should_be_transient = () =>
                queue.Durability.ShouldEqual(Durability.Transient);

            It should_be_auto_delete = () =>
                queue.IsAutoDelete.ShouldBeTrue();

            It should_not_have_name = () =>
                queue.HasName.ShouldBeFalse();

            static Queue queue;
        }

        [Subject(typeof(Queue))]
        public class with_name
        {
            Establish context = () =>
                queue = new Queue("queue-name");

            It should_be_durable = () =>
                queue.Durability.ShouldEqual(Durability.Durable);

            It should_not_be_auto_delete = () =>
                queue.IsAutoDelete.ShouldBeFalse();

            static Queue queue;
        }

        [Subject(typeof(Queue))]
        public class when_binding : with_queue
        {
            Because of = () =>
                Subject.BindTo(new Exchange("exchange", ExchangeType.Fanout));

            It should_have_bindings = () =>
                Subject.HasBindings.ShouldBeTrue();
        }

        [Subject(typeof(Queue))]
        public class when_visiting : with_bound_queue
        {
            Establish context = () =>
                visitor = An<ITopologyVisitor>();

            Because of = () =>
                Subject.Visit(visitor);

            It should_visit_queue = () =>
                visitor.WasToldTo(v => v.Visit(Subject));

            It should_visit_each_binding = () =>
                visitor.WasToldTo(v => v.Visit(Param.IsAny<IBinding>()));

            static ITopologyVisitor visitor;
        }

        public class with_queue : WithFakes
        {
            Establish context = () =>
                Subject = new Queue();

            protected static Queue Subject;
        }

        public class with_bound_queue : with_queue
        {
            Establish context = () =>
                Subject.BindTo(new Exchange("foo", ExchangeType.Fanout));
        }
    }
}