text:
namespace translate {

namespace {

// Returns whether or not the given list includes at least one language with
// the same base as the input language.
// For example: "en-US" and "en-UK" share the same base "en".
bool ContainsSameBaseLanguage(const std::vector<std::string>& list,
                              base::StringPiece language_code) {
  base::StringPiece base_language =
      language::ExtractBaseLanguage(language_code);
  for (const auto& item : list) {
    if (base_language == language::ExtractBaseLanguage(item))
      return true;
  }
  return false;
}

// Removes from the language list any language that isn't supported as an
// Accept-Language (it's not in kAcceptLanguageList) if and only if there
// aren't any other languages from the same family in the list that are
// supported.
void PurgeUnsupportedLanguagesInLanguageFamily(base::StringPiece language,
                                               std::vector<std::string>* list) {
  base::StringPiece base_language = language::ExtractBaseLanguage(language);
  for (const auto& lang : *list) {
    // This method only operates on languages in the same family as |language|.
    if (base_language != language::ExtractBaseLanguage(lang))
      continue;
    // If at least one of these same-family languages in |list| is supported by
    // Accept-Languages, then that means that none of the languages in this
    // family should be purged.
    if (TranslateAcceptLanguages::CanBeAcceptLanguage(lang))
      return;
  }

  // Purge all languages in the same family as |language|.
  base::EraseIf(*list, [base_language](const std::string& lang) {
    return base_language == language::ExtractBaseLanguage(lang);
  });
}

// Merge old always-translate languages from the deprecated pref to the new
// version. Because of crbug/1291356, it's possible that on iOS the client
// started using the new pref without properly migrating and clearing the old
// pref. This function will avoid merging values from the old pref that seem to
// conflict with values already present in the new pref.
void MigrateObsoleteAlwaysTranslateLanguagesPref(PrefService* prefs) {
  const base::Value* deprecated_dictionary = prefs->GetUserPrefValue(
      TranslatePrefs::kPrefAlwaysTranslateListDeprecated);
  // Migration is performed only once per client, since the deprecated pref is
  // cleared after migration. This will make subsequent calls to migrate no-ops.
  if (!deprecated_dictionary)
    return;

  DictionaryPrefUpdate always_translate_dictionary_update(
      prefs, prefs::kPrefAlwaysTranslateList);
  base::Value* always_translate_dictionary =
      always_translate_dictionary_update.Get();

  for (const auto old_language_pair : deprecated_dictionary->DictItems()) {
    // If the old pref's language pair conflicts with any of the new pref's
    // language pairs, where either the new pref already specifies behavior
    // about always translating from or to the old source language, or always
    // translating from the old target language, then skip merging this pair
    // into the new pref.
    const auto& new_language_pairs = always_translate_dictionary->DictItems();
    if (std::any_of(new_language_pairs.begin(), new_language_pairs.end(),
                    [&old_language_pair](const auto& new_language_pair) {
                      return old_language_pair.first ==
                                 new_language_pair.first ||
                             old_language_pair.first ==
                                 new_language_pair.second.GetString() ||
                             old_language_pair.second.GetString() ==
                                 new_language_pair.first;
                    })) {
      continue;
    }

    // If the old pair's source language matches any of the never-translate
    // languages, it probably means that this source language was set to never
    // be translated after the old pref was deprecated, so avoid this conflict.
    const auto& never_translate_languages =
        prefs->GetList(prefs::kBlockedLanguages)->GetList();
    if (std::any_of(
            never_translate_languages.begin(), never_translate_languages.end(),
            [&old_language_pair](const base::Value& never_translate_language) {
              return old_language_pair.first ==
                     never_translate_language.GetString();
            })) {
      continue;
    }

    always_translate_dictionary->SetStringKey(
        old_language_pair.first, old_language_pair.second.GetString());
  }

  prefs->ClearPref(TranslatePrefs::kPrefAlwaysTranslateListDeprecated);
}

}  // namespace

const char TranslatePrefs::kPrefForceTriggerTranslateCount[] =
    "translate_force_trigger_on_english_count_for_backoff_1";
const char TranslatePrefs::kPrefNeverPromptSitesDeprecated[] =
    "translate_site_blacklist";
const char TranslatePrefs::kPrefNeverPromptSitesWithTime[] =
    "translate_site_blacklist_with_time";
const char TranslatePrefs::kPrefTranslateDeniedCount[] =
    "translate_denied_count_for_language";
const char TranslatePrefs::kPrefTranslateIgnoredCount[] =
    "translate_ignored_count_for_language";
const char TranslatePrefs::kPrefTranslateAcceptedCount[] =
    "translate_accepted_count";

// Deprecated 10/2021.
const char TranslatePrefs::kPrefAlwaysTranslateListDeprecated[] =
    "translate_whitelists";

#if defined(OS_ANDROID) || defined(OS_IOS)
const char TranslatePrefs::kPrefTranslateAutoAlwaysCount[] =
    "translate_auto_always_count";
const char TranslatePrefs::kPrefTranslateAutoNeverCount[] =
    "translate_auto_never_count";
#endif

#if defined(OS_ANDROID)
const char TranslatePrefs::kPrefExplicitLanguageAskShown[] =
    "translate_explicit_language_ask_shown";
#endif

// The below properties used to be used but now are deprecated. Don't use them
// since an old profile might have some values there.
//
// * translate_last_denied_time
// * translate_too_often_denied
// * translate_language_blacklist

const base::Feature kTranslateRecentTarget{"TranslateRecentTarget",
                                           base::FEATURE_ENABLED_BY_DEFAULT};

const base::Feature kTranslate{"Translate", base::FEATURE_ENABLED_BY_DEFAULT};

const base::Feature kMigrateAlwaysTranslateLanguagesFix{
    "MigrateAlwaysTranslateLanguagesFix", base::FEATURE_DISABLED_BY_DEFAULT};

TranslateLanguageInfo::TranslateLanguageInfo() = default;

TranslateLanguageInfo::TranslateLanguageInfo(const TranslateLanguageInfo&) =
    default;
TranslateLanguageInfo::TranslateLanguageInfo(TranslateLanguageInfo&&) noexcept =
    default;
TranslateLanguageInfo& TranslateLanguageInfo::operator=(
    const TranslateLanguageInfo&) = default;
TranslateLanguageInfo& TranslateLanguageInfo::operator=(
    TranslateLanguageInfo&&) noexcept = default;

TranslatePrefs::TranslatePrefs(PrefService* user_prefs)
    : prefs_(user_prefs),
      language_prefs_(std::make_unique<language::LanguagePrefs>(user_prefs)) {
  MigrateNeverPromptSites();
  ResetEmptyBlockedLanguagesToDefaults();

  if (base::FeatureList::IsEnabled(kMigrateAlwaysTranslateLanguagesFix))
    MigrateObsoleteAlwaysTranslateLanguagesPref(user_prefs);
}

TranslatePrefs::~TranslatePrefs() = default;

// static
std::string TranslatePrefs::MapPreferenceName(const std::string& pref_name) {
  if (pref_name == kPrefNeverPromptSitesDeprecated) {
    return "translate_site_blocklist";
  }
  return pref_name;
}

bool TranslatePrefs::IsOfferTranslateEnabled() const {
  return prefs_->GetBoolean(prefs::kOfferTranslateEnabled);
}

bool TranslatePrefs::IsTranslateAllowedByPolicy() const {
  const PrefService::Preference* const pref =
      prefs_->FindPreference(prefs::kOfferTranslateEnabled);
  DCHECK(pref);
  DCHECK(pref->GetValue()->is_bool());

  return pref->GetValue()->GetBool() || !pref->IsManaged();
}

void TranslatePrefs::SetCountry(const std::string& country) {
  country_ = country;
}

std::string TranslatePrefs::GetCountry() const {
  return country_;
}

void TranslatePrefs::ResetToDefaults() {
  ResetBlockedLanguagesToDefault();
  ClearNeverPromptSiteList();
  ClearAlwaysTranslateLanguagePairs();
  prefs_->ClearPref(kPrefTranslateDeniedCount);
  prefs_->ClearPref(kPrefTranslateIgnoredCount);
  prefs_->ClearPref(kPrefTranslateAcceptedCount);
  prefs_->ClearPref(prefs::kPrefTranslateRecentTarget);

#if defined(OS_ANDROID) || defined(OS_IOS)
  prefs_->ClearPref(kPrefTranslateAutoAlwaysCount);
  prefs_->ClearPref(kPrefTranslateAutoNeverCount);
#endif

  prefs_->ClearPref(prefs::kOfferTranslateEnabled);
}

// static
base::Value TranslatePrefs::GetDefaultBlockedLanguages() {
  typename base::Value::ListStorage languages;
#if BUILDFLAG(IS_CHROMEOS_ASH)
  // Preferred languages.
  std::string language = language::kFallbackInputMethodLocale;
  language::ToTranslateLanguageSynonym(&language);
  languages.push_back(base::Value(std::move(language)));
#else
  // Accept languages.
#pragma GCC diagnostic push
// See comment above the |break;| in the loop just below for why.
#pragma GCC diagnostic ignored "-Wunreachable-code"
  for (std::string& language :
       base::SplitString(l10n_util::GetStringUTF8(IDS_ACCEPT_LANGUAGES), ",",
                         base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
    language::ToTranslateLanguageSynonym(&language);
    languages.push_back(base::Value(std::move(language)));

    // crbug.com/958348: The default value for Accept-Language *should* be the
    // same as the one for Blocked Languages. However, Accept-Language contains
    // English (and more) in addition to the local language in most locales due
    // to historical reasons. Exiting early from this loop is a temporary fix
    // that allows Blocked Languages to be at least populated with the UI
    // language while still allowing Translate to trigger on other languages,
    // most importantly English.
    // Once the change to remove English from Accept-Language defaults lands,
    // this break should be removed to enable the Blocked Language List and the
    // Accept-Language list to be initialized to the same values.
    break;
#pragma GCC diagnostic pop
  }
#endif

  std::sort(languages.begin(), languages.end());
  languages.erase(std::unique(languages.begin(), languages.end()),
                  languages.end());

  return base::Value(std::move(languages));
}

bool TranslatePrefs::IsBlockedLanguage(base::StringPiece input_language) const {
  std::string canonical_lang(input_language);
  language::ToTranslateLanguageSynonym(&canonical_lang);
  const base::Value* blocked =
      prefs_->GetList(translate::prefs::kBlockedLanguages);
  return base::Contains(blocked->GetList(),
                        base::Value(std::move(canonical_lang)));
}

void TranslatePrefs::BlockLanguage(base::StringPiece input_language) {
  DCHECK(!input_language.empty());
  if (!IsBlockedLanguage(input_language)) {
    std::string canonical_lang(input_language);
    language::ToTranslateLanguageSynonym(&canonical_lang);
    ListPrefUpdate update(prefs_, translate::prefs::kBlockedLanguages);
    update->Append(std::move(canonical_lang));
  }
  // Remove the blocked language from the always translate list if present.
  SetLanguageAlwaysTranslateState(input_language, false);
}

void TranslatePrefs::UnblockLanguage(base::StringPiece input_language) {
  DCHECK(!input_language.empty());
  // Never remove last fluent language.
  if (GetNeverTranslateLanguages().size() <= 1) {
    return;
  }
  std::string canonical_lang(input_language);
  language::ToTranslateLanguageSynonym(&canonical_lang);
  ListPrefUpdate update(prefs_, translate::prefs::kBlockedLanguages);
  update->EraseListValue(base::Value(std::move(canonical_lang)));
}

void TranslatePrefs::ResetEmptyBlockedLanguagesToDefaults() {
  if (GetNeverTranslateLanguages().size() == 0) {
    ResetBlockedLanguagesToDefault();
  }
}

void TranslatePrefs::ResetBlockedLanguagesToDefault() {
  prefs_->ClearPref(translate::prefs::kBlockedLanguages);
}

std::vector<std::string> TranslatePrefs::GetNeverTranslateLanguages() const {
  const base::Value* fluent_languages_value =
      prefs_->GetList(translate::prefs::kBlockedLanguages);
  if (!fluent_languages_value) {
    NOTREACHED() << "Fluent languages pref is unregistered";
  }

  std::vector<std::string> languages;
  for (const auto& language : fluent_languages_value->GetList()) {
    std::string chrome_language(language.GetString());
    language::ToChromeLanguageSynonym(&chrome_language);
    languages.push_back(chrome_language);
  }
  return languages;
}

// Note: the language codes used in the language settings list have the Chrome
// internal format and not the Translate server format.
// To convert from one to the other use util functions
// ToTranslateLanguageSynonym() and ToChromeLanguageSynonym().
void TranslatePrefs::AddToLanguageList(base::StringPiece input_language,
                                       const bool force_blocked) {
  DCHECK(!input_language.empty());

  std::string chrome_language(input_language);
  language::ToChromeLanguageSynonym(&chrome_language);

  std::vector<std::string> languages;
  std::vector<std::string> user_selected_languages;
  GetLanguageList(&languages);
  GetUserSelectedLanguageList(&user_selected_languages);

  // We should block the language if the list does not already contain another
  // language with the same base language. Policy-forced languages aren't
  // counted as "blocking", so only user-selected languages are checked.
  const bool should_block =
      !ContainsSameBaseLanguage(user_selected_languages, chrome_language);

  if (force_blocked || should_block) {
    BlockLanguage(input_language);
  }

  // Add the language to the list.
  if (!base::Contains(languages, chrome_language)) {
    user_selected_languages.push_back(chrome_language);
    language_prefs_->SetUserSelectedLanguagesList(user_selected_languages);
  }
}

void TranslatePrefs::RemoveFromLanguageList(base::StringPiece input_language) {
  DCHECK(!input_language.empty());

  std::string chrome_language(input_language);
  language::ToChromeLanguageSynonym(&chrome_language);

  std::vector<std::string> languages;
  std::vector<std::string> user_selected_languages;
  GetUserSelectedLanguageList(&user_selected_languages);

  // Remove the language from the list.
  const auto& it = std::find(user_selected_languages.begin(),
                             user_selected_languages.end(), chrome_language);
  if (it != user_selected_languages.end()) {

    user_selected_languages.erase(it);
    PurgeUnsupportedLanguagesInLanguageFamily(chrome_language,
                                              &user_selected_languages);
    language_prefs_->SetUserSelectedLanguagesList(user_selected_languages);

    // We should unblock the language if this was the last one from the same
    // language family.
    GetLanguageList(&languages);
    if (!ContainsSameBaseLanguage(languages, chrome_language)) {
      UnblockLanguage(input_language);
      // If the recent translate target matches the last language of a family
      // being removed, reset the most recent target language so it will not be
      // used the next time Translate is triggered.
      std::string translate_language(input_language);
      language::ToTranslateLanguageSynonym(&translate_language);
      if (translate_language == GetRecentTargetLanguage()) {
        ResetRecentTargetLanguage();
      }
    }
  }
}

void TranslatePrefs::RearrangeLanguage(
    base::StringPiece language,
    const TranslatePrefs::RearrangeSpecifier where,
    int offset,
    const std::vector<std::string>& enabled_languages) {
  // Negative offset is not supported.
  DCHECK(!(offset < 1 && (where == kUp || where == kDown)));

  std::vector<std::string> languages;
  GetUserSelectedLanguageList(&languages);

  auto pos = std::find(languages.begin(), languages.end(), language);
  if (pos == languages.end())
    return;

  // Sort the vector of enabled languages for fast lookup.
  std::vector<base::StringPiece> enabled(enabled_languages.begin(),
                                         enabled_languages.end());
  std::sort(enabled.begin(), enabled.end());
  if (!std::binary_search(enabled.begin(), enabled.end(), language))
    return;

  switch (where) {
    case kTop:
      // To avoid code duplication, set |offset| to max int and re-use the logic
      // to move |language| up in the list as far as possible.
      offset = std::numeric_limits<int>::max();
      FALLTHROUGH;
    case kUp:
      if (pos == languages.begin())
        return;
      while (pos != languages.begin()) {
        auto next_pos = pos - 1;
        // Skip over non-enabled languages without decrementing |offset|.
        // Also skip over languages hidden due to duplication between forced
        // and user-selected languages.
        if (std::binary_search(enabled.begin(), enabled.end(), *next_pos) &&
            !language_prefs_->IsForcedLanguage(*next_pos)) {
          // By only checking |offset| when an enabled, non-forced language is
          // found, and decrementing |offset| after checking it (instead of
          // before), this means that |language| will be moved up the list until
          // it has either reached the next enabled language or the top of the
          // list.
          if (offset <= 0)
            break;
          --offset;
        }
        std::swap(*next_pos, *pos);
        pos = next_pos;
      }
      break;

    case kDown:
      if (pos + 1 == languages.end())
        return;
      for (auto next_pos = pos + 1; next_pos != languages.end() && offset > 0;
           pos = next_pos++) {
        // Skip over non-enabled or forced languages without decrementing
        // offset. Unlike moving languages up in the list, moving languages down
        // in the list stops as soon as |offset| reaches zero, instead of
        // continuing to skip non-enabled languages after |offset| has reached
        // zero.
        if (std::binary_search(enabled.begin(), enabled.end(), *next_pos) &&
            !language_prefs_->IsForcedLanguage(*next_pos))
          --offset;
        std::swap(*next_pos, *pos);
      }
      break;

    case kNone:
      return;

    default:
      NOTREACHED();
      return;
  }

  language_prefs_->SetUserSelectedLanguagesList(languages);
}

void TranslatePrefs::SetLanguageOrder(
    const std::vector<std::string>& new_order) {
  language_prefs_->SetUserSelectedLanguagesList(new_order);
}

// static
void TranslatePrefs::GetLanguageInfoList(
    const std::string& app_locale,
    bool translate_allowed,
    std::vector<TranslateLanguageInfo>* language_list) {
  DCHECK(language_list != nullptr);

  if (app_locale.empty()) {
    return;
  }

  language_list->clear();

  // Collect the language codes from the supported accept-languages.
  std::vector<std::string> language_codes;
  l10n_util::GetAcceptLanguagesForLocale(app_locale, &language_codes);

  // Collator used to sort display names in the given locale.
  UErrorCode error = U_ZERO_ERROR;
  std::unique_ptr<icu::Collator> collator(
      icu::Collator::createInstance(icu::Locale(app_locale.c_str()), error));
  if (U_FAILURE(error)) {
    collator.reset();
  }
  // Map of [display name -> language code].
  std::map<std::u16string, std::string,
           l10n_util::StringComparator<std::u16string>>
      language_map(l10n_util::StringComparator<std::u16string>(collator.get()));

  // Build the list of display names and the language map.
  for (std::string& code : language_codes) {
    language_map[l10n_util::GetDisplayNameForLocale(code, app_locale, false)] =
        std::move(code);
  }

  // Get the sorted list of translatable languages.
  std::vector<std::string> translate_languages;
  translate::TranslateDownloadManager::GetSupportedLanguages(
      translate_allowed, &translate_languages);
  // |translate_languages| should already be sorted alphabetically for fast
  // searching.
  DCHECK(
      std::is_sorted(translate_languages.begin(), translate_languages.end()));

  // Build the language list from the language map.
  for (auto& entry : language_map) {
    TranslateLanguageInfo language;
    language.code = std::move(entry.second);

    std::u16string adjusted_display_name = entry.first;
    base::i18n::AdjustStringForLocaleDirection(&adjusted_display_name);
    language.display_name = base::UTF16ToUTF8(adjusted_display_name);

    std::u16string adjusted_native_display_name =
        l10n_util::GetDisplayNameForLocale(language.code, language.code, false);
    base::i18n::AdjustStringForLocaleDirection(&adjusted_native_display_name);
    language.native_display_name =
        base::UTF16ToUTF8(adjusted_native_display_name);

    std::string supports_translate_code = language.code;

    // Extract the base language: if the base language can be translated, then
    // even the regional one should be marked as such.
    language::ToTranslateLanguageSynonym(&supports_translate_code);
    language.supports_translate =
        std::binary_search(translate_languages.begin(),
                           translate_languages.end(), supports_translate_code);

    language_list->push_back(std::move(language));
  }
}

void TranslatePrefs::GetTranslatableContentLanguages(
    const std::string& app_locale,
    std::vector<std::string>* codes) {
  DCHECK(codes != nullptr);

  if (app_locale.empty()) {
    return;
  }
  codes->clear();

  // Get the language codes of user content languages.
  // Returned in Chrome format.
  std::vector<std::string> language_codes;
  GetLanguageList(&language_codes);

  std::set<std::string> unique_languages;
  for (auto& entry : language_codes) {
    std::string supports_translate_code = entry;
    // Get the language in Translate format.
    language::ToTranslateLanguageSynonym(&supports_translate_code);
    // Extract the language code, for example for en-US it returns en.
    std::string lang_code =
        TranslateDownloadManager::GetLanguageCode(supports_translate_code);
    // If the language code for a translatable language hasn't yet been added,
    // add it to the result list.
    if (TranslateDownloadManager::IsSupportedLanguage(lang_code)) {
      if (unique_languages.count(lang_code) == 0) {
        unique_languages.insert(lang_code);
        codes->push_back(lang_code);
      }
    }
  }
}

bool TranslatePrefs::IsSiteOnNeverPromptList(base::StringPiece site) const {
  return prefs_->GetDictionary(kPrefNeverPromptSitesWithTime)->FindKey(site);
}

void TranslatePrefs::AddSiteToNeverPromptList(base::StringPiece site) {
  DCHECK(!site.empty());
  AddValueToNeverPromptList(kPrefNeverPromptSitesDeprecated, site);
  DictionaryPrefUpdate update(prefs_, kPrefNeverPromptSitesWithTime);
  update.Get()->SetKey(site, base::TimeToValue(base::Time::Now()));
}

void TranslatePrefs::RemoveSiteFromNeverPromptList(base::StringPiece site) {
  DCHECK(!site.empty());
  RemoveValueFromNeverPromptList(kPrefNeverPromptSitesDeprecated, site);
  DictionaryPrefUpdate update(prefs_, kPrefNeverPromptSitesWithTime);
  update.Get()->RemoveKey(site);
}

std::vector<std::string> TranslatePrefs::GetNeverPromptSitesBetween(
    base::Time begin,
    base::Time end) const {
  std::vector<std::string> result;
  auto* dict = prefs_->GetDictionary(kPrefNeverPromptSitesWithTime);
  for (auto entry : dict->DictItems()) {
    absl::optional<base::Time> time = base::ValueToTime(entry.second);
    if (!time) {
      NOTREACHED();
      continue;
    }
    if (begin <= *time && *time < end)
      result.push_back(entry.first);
  }
  return result;
}

void TranslatePrefs::DeleteNeverPromptSitesBetween(base::Time begin,
                                                   base::Time end) {
  for (auto& site : GetNeverPromptSitesBetween(begin, end))
    RemoveSiteFromNeverPromptList(site);
}

bool TranslatePrefs::IsLanguagePairOnAlwaysTranslateList(
    base::StringPiece source_language,
    base::StringPiece target_language) {
  const base::Value* dict =
      prefs_->GetDictionary(prefs::kPrefAlwaysTranslateList);
  if (dict) {
    const std::string* auto_target_lang = dict->FindStringKey(source_language);
    if (auto_target_lang && *auto_target_lang == target_language)
      return true;
  }
  return false;
}

void TranslatePrefs::AddLanguagePairToAlwaysTranslateList(
    base::StringPiece source_language,
    base::StringPiece target_language) {
  DictionaryPrefUpdate update(prefs_, prefs::kPrefAlwaysTranslateList);
  DCHECK(update.Get()) << "Always translated pref is unregistered";

  // Get translate version of language codes.
  std::string translate_source_language(source_language);
  language::ToTranslateLanguageSynonym(&translate_source_language);
  std::string translate_target_language(target_language);
  language::ToTranslateLanguageSynonym(&translate_target_language);

  update.Get()->SetStringKey(translate_source_language,
                             translate_target_language);
  // Remove source language from block list if present.
  UnblockLanguage(translate_source_language);
}

void TranslatePrefs::RemoveLanguagePairFromAlwaysTranslateList(
    base::StringPiece source_language,
    base::StringPiece target_language) {
  DictionaryPrefUpdate update(prefs_, prefs::kPrefAlwaysTranslateList);
  DCHECK(update.Get()) << "Always translate pref is unregistered";

  // Get translate version of language codes.
  std::string translate_source_language(source_language);
  language::ToTranslateLanguageSynonym(&translate_source_language);
  update.Get()->RemoveKey(translate_source_language);
}

void TranslatePrefs::SetLanguageAlwaysTranslateState(
    base::StringPiece source_language,
    bool always_translate) {
  if (always_translate) {
    AddLanguagePairToAlwaysTranslateList(source_language,
                                         GetRecentTargetLanguage());
  } else {
    RemoveLanguagePairFromAlwaysTranslateList(source_language,
                                              GetRecentTargetLanguage());
  }
}

std::vector<std::string> TranslatePrefs::GetAlwaysTranslateLanguages() const {
  const base::Value* dict =
      prefs_->GetDictionary(prefs::kPrefAlwaysTranslateList);
  DCHECK(dict) << "Always translate pref is unregistered";

  std::vector<std::string> languages;
  for (auto language_pair : dict->DictItems()) {
    std::string chrome_language(language_pair.first);
    language::ToChromeLanguageSynonym(&chrome_language);
    languages.push_back(chrome_language);
  }
  return languages;
}

void TranslatePrefs::ClearNeverPromptSiteList() {
  prefs_->ClearPref(kPrefNeverPromptSitesDeprecated);
  prefs_->ClearPref(kPrefNeverPromptSitesWithTime);
}

bool TranslatePrefs::HasLanguagePairsToAlwaysTranslate() const {
  return !IsDictionaryEmpty(prefs::kPrefAlwaysTranslateList);
}

void TranslatePrefs::ClearAlwaysTranslateLanguagePairs() {
  prefs_->ClearPref(prefs::kPrefAlwaysTranslateList);
}

int TranslatePrefs::GetTranslationDeniedCount(
    base::StringPiece language) const {
  const base::Value* dict = prefs_->GetDictionary(kPrefTranslateDeniedCount);
  return dict->FindIntKey(language).value_or(0);
}

void TranslatePrefs::IncrementTranslationDeniedCount(
    base::StringPiece language) {
  DictionaryPrefUpdate update(prefs_, kPrefTranslateDeniedCount);
  base::Value* dict = update.Get();

  int count = dict->FindIntKey(language).value_or(0);
  if (count < std::numeric_limits<int>::max())
    dict->SetIntKey(language, count + 1);
}

void TranslatePrefs::ResetTranslationDeniedCount(base::StringPiece language) {
  DictionaryPrefUpdate update(prefs_, kPrefTranslateDeniedCount);
  update.Get()->SetIntKey(language, 0);
}

int TranslatePrefs::GetTranslationIgnoredCount(
    base::StringPiece language) const {
  const base::Value* dict = prefs_->GetDictionary(kPrefTranslateIgnoredCount);
  return dict->FindIntKey(language).value_or(0);
}

void TranslatePrefs::IncrementTranslationIgnoredCount(
    base::StringPiece language) {
  DictionaryPrefUpdate update(prefs_, kPrefTranslateIgnoredCount);
  base::Value* dict = update.Get();

  int count = dict->FindIntKey(language).value_or(0);
  if (count < std::numeric_limits<int>::max())
    dict->SetIntKey(language, count + 1);
}

void TranslatePrefs::ResetTranslationIgnoredCount(base::StringPiece language) {
  DictionaryPrefUpdate update(prefs_, kPrefTranslateIgnoredCount);
  update.Get()->SetIntKey(language, 0);
}

int TranslatePrefs::GetTranslationAcceptedCount(
    base::StringPiece language) const {
  const base::Value* dict = prefs_->GetDictionary(kPrefTranslateAcceptedCount);
  return dict->FindIntKey(language).value_or(0);
}

void TranslatePrefs::IncrementTranslationAcceptedCount(
    base::StringPiece language) {
  DictionaryPrefUpdate update(prefs_, kPrefTranslateAcceptedCount);
  base::Value* dict = update.Get();

  int count = dict->FindIntKey(language).value_or(0);
  if (count < std::numeric_limits<int>::max())
    dict->SetIntKey(language, count + 1);
}

void TranslatePrefs::ResetTranslationAcceptedCount(base::StringPiece language) {
  DictionaryPrefUpdate update(prefs_, kPrefTranslateAcceptedCount);
  update.Get()->SetIntKey(language, 0);
}

#if defined(OS_ANDROID) || defined(OS_IOS)
int TranslatePrefs::GetTranslationAutoAlwaysCount(
    base::StringPiece language) const {
  const base::Value* dict =
      prefs_->GetDictionary(kPrefTranslateAutoAlwaysCount);
  return dict->FindIntKey(language).value_or(0);
}

void TranslatePrefs::IncrementTranslationAutoAlwaysCount(
    base::StringPiece language) {
  DictionaryPrefUpdate update(prefs_, kPrefTranslateAutoAlwaysCount);
  base::Value* dict = update.Get();

  int count = dict->FindIntKey(language).value_or(0);
  if (count < std::numeric_limits<int>::max())
    dict->SetIntKey(language, count + 1);
}

void TranslatePrefs::ResetTranslationAutoAlwaysCount(
    base::StringPiece language) {
  DictionaryPrefUpdate update(prefs_, kPrefTranslateAutoAlwaysCount);
  update.Get()->SetIntKey(language, 0);
}

int TranslatePrefs::GetTranslationAutoNeverCount(
    base::StringPiece language) const {
  const base::Value* dict = prefs_->GetDictionary(kPrefTranslateAutoNeverCount);
  return dict->FindIntKey(language).value_or(0);
}

void TranslatePrefs::IncrementTranslationAutoNeverCount(
    base::StringPiece language) {
  DictionaryPrefUpdate update(prefs_, kPrefTranslateAutoNeverCount);
  base::Value* dict = update.Get();

  int count = dict->FindIntKey(language).value_or(0);
  if (count < std::numeric_limits<int>::max())
    dict->SetIntKey(language, count + 1);
}

void TranslatePrefs::ResetTranslationAutoNeverCount(
    base::StringPiece language) {
  DictionaryPrefUpdate update(prefs_, kPrefTranslateAutoNeverCount);
  update.Get()->SetIntKey(language, 0);
}
#endif  // defined(OS_ANDROID) || defined(OS_IOS)

#if defined(OS_ANDROID)
bool TranslatePrefs::GetExplicitLanguageAskPromptShown() const {
  return prefs_->GetBoolean(kPrefExplicitLanguageAskShown);
}

void TranslatePrefs::SetExplicitLanguageAskPromptShown(bool shown) {
  prefs_->SetBoolean(kPrefExplicitLanguageAskShown, shown);
}

bool TranslatePrefs::GetAppLanguagePromptShown() const {
  return prefs_->GetBoolean(language::prefs::kAppLanguagePromptShown);
}

void TranslatePrefs::SetAppLanguagePromptShown() {
  prefs_->SetBoolean(language::prefs::kAppLanguagePromptShown, true);
}
#endif  // defined(OS_ANDROID)

void TranslatePrefs::GetLanguageList(
    std::vector<std::string>* const languages) const {
  language_prefs_->GetAcceptLanguagesList(languages);
}

void TranslatePrefs::GetUserSelectedLanguageList(
    std::vector<std::string>* const languages) const {
  language_prefs_->GetUserSelectedLanguagesList(languages);
}

bool TranslatePrefs::CanTranslateLanguage(
    TranslateAcceptLanguages* accept_languages,
    base::StringPiece language) {
  // Languages not on the blocklist can always be translated.
  if (!IsBlockedLanguage(language))
    return true;

  // Languages not on the Accept-Language list should not be blocked unless the
  // detailed language settings are showing or the language can not be on the
  // Accept-Language list (this is true for languages that do not have a ICU
  // localization for the current UI locale.
  bool can_be_accept_language =
      TranslateAcceptLanguages::CanBeAcceptLanguage(language);
  bool is_accept_language = accept_languages->IsAcceptLanguage(language);
  if (!is_accept_language && can_be_accept_language &&
      !IsDetailedLanguageSettingsEnabled())
    return true;

  // Under this experiment, translate English page even though English may be
  // blocked.
  if (language == "en" && language::ShouldForceTriggerTranslateOnEnglishPages(
                              GetForceTriggerOnEnglishPagesCount()))
    return true;
  return false;
}

// static
bool TranslatePrefs::IsDetailedLanguageSettingsEnabled() {
#if defined(OS_ANDROID)
  return base::FeatureList::IsEnabled(language::kDetailedLanguageSettings);
#elif defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX)
  return base::FeatureList::IsEnabled(
      language::kDesktopDetailedLanguageSettings);
#else
  return false;
#endif
}

bool TranslatePrefs::ShouldAutoTranslate(base::StringPiece source_language,
                                         std::string* target_language) {
  const base::Value* dict =
      prefs_->GetDictionary(prefs::kPrefAlwaysTranslateList);
  if (!dict)
    return false;

  const std::string* value = dict->FindStringKey(source_language);
  if (!value)
    return false;

  DCHECK(!value->empty());
  target_language->assign(*value);
  return true;
}

void TranslatePrefs::SetRecentTargetLanguage(
    const std::string& target_language) {
  // Get translate version of language code.
  std::string translate_target_language(target_language);
  language::ToTranslateLanguageSynonym(&translate_target_language);
  prefs_->SetString(prefs::kPrefTranslateRecentTarget,
                    translate_target_language);
}

void TranslatePrefs::ResetRecentTargetLanguage() {
  SetRecentTargetLanguage("");
}

std::string TranslatePrefs::GetRecentTargetLanguage() const {
  return prefs_->GetString(prefs::kPrefTranslateRecentTarget);
}

int TranslatePrefs::GetForceTriggerOnEnglishPagesCount() const {
  return prefs_->GetInteger(kPrefForceTriggerTranslateCount);
}

void TranslatePrefs::ReportForceTriggerOnEnglishPages() {
  int current_count = GetForceTriggerOnEnglishPagesCount();
  if (current_count != -1 && current_count < std::numeric_limits<int>::max())
    prefs_->SetInteger(kPrefForceTriggerTranslateCount, current_count + 1);
}

void TranslatePrefs::ReportAcceptedAfterForceTriggerOnEnglishPages() {
  int current_count = GetForceTriggerOnEnglishPagesCount();
  if (current_count != -1)
    prefs_->SetInteger(kPrefForceTriggerTranslateCount, -1);
}

// static
void TranslatePrefs::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterListPref(kPrefNeverPromptSitesDeprecated,
                             user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
  registry->RegisterDictionaryPref(
      kPrefNeverPromptSitesWithTime,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
  registry->RegisterDictionaryPref(
      prefs::kPrefAlwaysTranslateList,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
  registry->RegisterDictionaryPref(
      kPrefTranslateDeniedCount,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
  registry->RegisterDictionaryPref(
      kPrefTranslateIgnoredCount,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
  registry->RegisterDictionaryPref(
      kPrefTranslateAcceptedCount,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
  registry->RegisterStringPref(prefs::kPrefTranslateRecentTarget, "",
                               user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
  registry->RegisterIntegerPref(
      kPrefForceTriggerTranslateCount, 0,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
  registry->RegisterListPref(translate::prefs::kBlockedLanguages,
                             TranslatePrefs::GetDefaultBlockedLanguages(),
                             user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
#if defined(OS_ANDROID) || defined(OS_IOS)
  registry->RegisterDictionaryPref(
      kPrefTranslateAutoAlwaysCount,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
  registry->RegisterDictionaryPref(
      kPrefTranslateAutoNeverCount,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
#endif

#if defined(OS_ANDROID)
  registry->RegisterBooleanPref(
      kPrefExplicitLanguageAskShown, false,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
#endif

  RegisterProfilePrefsForMigration(registry);
}

// static
void TranslatePrefs::RegisterProfilePrefsForMigration(
    user_prefs::PrefRegistrySyncable* registry) {
  // Deprecated 10/2021.
  registry->RegisterDictionaryPref(kPrefAlwaysTranslateListDeprecated);
}

void TranslatePrefs::MigrateNeverPromptSites() {
  // Migration copies any sites on the deprecated never prompt pref to
  // the new version and clears all references to the old one. This will
  // make subsequent calls to migrate no-ops.
  DictionaryPrefUpdate never_prompt_list_update(prefs_,
                                                kPrefNeverPromptSitesWithTime);
  base::Value* never_prompt_list = never_prompt_list_update.Get();
  if (never_prompt_list) {
    ListPrefUpdate deprecated_prompt_list_update(
        prefs_, kPrefNeverPromptSitesDeprecated);
    base::Value* deprecated_list = deprecated_prompt_list_update.Get();
    for (auto& site : deprecated_list->GetList()) {
      if (!never_prompt_list->FindKey(site.GetString()) ||
          !base::ValueToTime(never_prompt_list->FindKey(site.GetString()))) {
        never_prompt_list->SetKey(site.GetString(),
                                  base::TimeToValue(base::Time::Now()));
      }
    }
    deprecated_list->ClearList();
  }
}

// static
void TranslatePrefs::MigrateObsoleteProfilePrefs(PrefService* profile_prefs) {
  // TODO(crbug/1291356): Remove this method.
  const base::Value* deprecated_always_translate_list =
      profile_prefs->GetUserPrefValue(kPrefAlwaysTranslateListDeprecated);
  if (deprecated_always_translate_list &&
      !profile_prefs->GetUserPrefValue(prefs::kPrefAlwaysTranslateList)) {
    profile_prefs->Set(prefs::kPrefAlwaysTranslateList,
                       *deprecated_always_translate_list);
  }
}

// static
void TranslatePrefs::ClearObsoleteProfilePrefs(PrefService* profile_prefs) {
  // TODO(crbug/1291356): Remove this method.
  profile_prefs->ClearPref(kPrefAlwaysTranslateListDeprecated);
}

bool TranslatePrefs::IsValueOnNeverPromptList(const char* pref_id,
                                              base::StringPiece value) const {
  const base::Value* never_prompt_list = prefs_->GetList(pref_id);
  if (!never_prompt_list)
    return false;
  for (const base::Value& value_in_list : never_prompt_list->GetList()) {
    if (value_in_list.is_string() && value_in_list.GetString() == value)
      return true;
  }
  return false;
}

void TranslatePrefs::AddValueToNeverPromptList(const char* pref_id,
                                               base::StringPiece value) {
  ListPrefUpdate update(prefs_, pref_id);
  base::Value* never_prompt_list = update.Get();
  if (!never_prompt_list) {
    NOTREACHED() << "Unregistered never-translate pref";
    return;
  }

  if (IsValueOnNeverPromptList(pref_id, value)) {
    return;
  }
  never_prompt_list->Append(value);
}

void TranslatePrefs::RemoveValueFromNeverPromptList(const char* pref_id,
                                                    base::StringPiece value) {
  ListPrefUpdate update(prefs_, pref_id);
  base::Value* never_prompt_list = update.Get();
  if (!never_prompt_list) {
    NOTREACHED() << "Unregistered never-translate pref";
    return;
  }

  auto list_view = never_prompt_list->GetList();
  never_prompt_list->EraseListIter(std::find_if(
      list_view.begin(), list_view.end(),
      [value](const base::Value& value_in_list) {
        return value_in_list.is_string() && value_in_list.GetString() == value;
      }));
}

size_t TranslatePrefs::GetListSize(const char* pref_id) const {
  const base::Value* never_prompt_list = prefs_->GetList(pref_id);
  return never_prompt_list == nullptr ? 0 : never_prompt_list->GetList().size();
}

bool TranslatePrefs::IsDictionaryEmpty(const char* pref_id) const {
  const base::Value* dict = prefs_->GetDictionary(pref_id);
  return (dict == nullptr || dict->DictEmpty());
}
}  // namespace translate


text:
/**CFile****************************************************************

  FileName    [aigTiming.c]

  SystemName  [ABC: Logic synthesis and verification system.]

  PackageName [AIG package.]

  Synopsis    [Incremental updating of direct/reverse AIG levels.]

  Author      [Alan Mishchenko]

  Affiliation [UC Berkeley]

  Date        [Ver. 1.0. Started - April 28, 2007.]

  Revision    [$Id: aigTiming.c,v 1.00 2007/04/28 00:00:00 alanmi Exp $]

***********************************************************************/

#include "aig.h"

////////////////////////////////////////////////////////////////////////
///                        DECLARATIONS                              ///
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
///                     FUNCTION DEFINITIONS                         ///
////////////////////////////////////////////////////////////////////////

/**Function*************************************************************

  Synopsis    [Returns the reverse level of the node.]

  Description [The reverse level is the level of the node in reverse
  topological order, starting from the COs.]

  SideEffects []

  SeeAlso     []

***********************************************************************/
static inline int Aig_ObjReverseLevel( Aig_Man_t * p, Aig_Obj_t * pObj )
{
    assert( p->vLevelR );
    Vec_IntFillExtra( p->vLevelR, pObj->Id + 1, 0 );
    return Vec_IntEntry(p->vLevelR, pObj->Id);
}

/**Function*************************************************************

  Synopsis    [Sets the reverse level of the node.]

  Description [The reverse level is the level of the node in reverse
  topological order, starting from the COs.]

  SideEffects []

  SeeAlso     []

***********************************************************************/
static inline void Aig_ObjSetReverseLevel( Aig_Man_t * p, Aig_Obj_t * pObj, int LevelR )
{
    assert( p->vLevelR );
    Vec_IntFillExtra( p->vLevelR, pObj->Id + 1, 0 );
    Vec_IntWriteEntry( p->vLevelR, pObj->Id, LevelR );
}

/**Function*************************************************************

  Synopsis    [Resets reverse level of the node.]

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
void Aig_ObjClearReverseLevel( Aig_Man_t * p, Aig_Obj_t * pObj )
{
    Aig_ObjSetReverseLevel( p, pObj, 0 );
}

/**Function*************************************************************

  Synopsis    [Returns required level of the node.]

  Description [Converts the reverse levels of the node into its required
  level as follows: ReqLevel(Node) = MaxLevels(Ntk) + 1 - LevelR(Node).]

  SideEffects []

  SeeAlso     []

***********************************************************************/
int Aig_ObjRequiredLevel( Aig_Man_t * p, Aig_Obj_t * pObj )
{
    assert( p->vLevelR );
    return p->nLevelMax + 1 - Aig_ObjReverseLevel(p, pObj);
}

/**Function*************************************************************

  Synopsis    [Computes the reverse level of the node using its fanout levels.]

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
int Aig_ObjReverseLevelNew( Aig_Man_t * p, Aig_Obj_t * pObj )
{
    Aig_Obj_t * pFanout;
    int i, iFanout, LevelCur, Level = 0;
    Aig_ObjForEachFanout( p, pObj, pFanout, iFanout, i )
    {
        LevelCur = Aig_ObjReverseLevel( p, pFanout );
        Level = AIG_MAX( Level, LevelCur );
    }
    return Level + 1;
}

/**Function*************************************************************

  Synopsis    [Prepares for the computation of required levels.]

  Description [This procedure should be called before the required times
  are used. It starts internal data structures, which records the level
  from the COs of the network nodes in reverse topologogical order.]

  SideEffects []

  SeeAlso     []

***********************************************************************/
void Aig_ManStartReverseLevels( Aig_Man_t * p, int nMaxLevelIncrease )
{
    Vec_Ptr_t * vNodes;
    Aig_Obj_t * pObj;
    int i;
    assert( p->pFanData != NULL );
    assert( p->vLevelR == NULL );
    // remember the maximum number of direct levels
    p->nLevelMax = Aig_ManLevels(p) + nMaxLevelIncrease;
    // start the reverse levels
    p->vLevelR = Vec_IntAlloc( 0 );
    Vec_IntFill( p->vLevelR, 1 + Aig_ManObjIdMax(p), 0 );
    // compute levels in reverse topological order
    vNodes = Aig_ManDfsReverse( p );
    Vec_PtrForEachEntry( vNodes, pObj, i )
    {
        assert( pObj->fMarkA == 0 );
        Aig_ObjSetReverseLevel( p, pObj, Aig_ObjReverseLevelNew(p, pObj) );
    }
    Vec_PtrFree( vNodes );
}

/**Function*************************************************************

  Synopsis    [Cleans the data structures used to compute required levels.]

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
void Aig_ManStopReverseLevels( Aig_Man_t * p )
{
    assert( p->vLevelR != NULL );
    Vec_IntFree( p->vLevelR );
    p->vLevelR = NULL;
    p->nLevelMax = 0;

}

/**Function*************************************************************

  Synopsis    [Incrementally updates level of the nodes.]

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
void Aig_ManUpdateLevel( Aig_Man_t * p, Aig_Obj_t * pObjNew )
{
    Aig_Obj_t * pFanout, * pTemp;
    int iFanout, LevelOld, Lev, k, m;
    assert( p->pFanData != NULL );
    assert( Aig_ObjIsNode(pObjNew) );
    // allocate level if needed
    if ( p->vLevels == NULL )
        p->vLevels = Vec_VecAlloc( Aig_ManLevels(p) + 8 );
    // check if level has changed
    LevelOld = Aig_ObjLevel(pObjNew);
    if ( LevelOld == Aig_ObjLevelNew(pObjNew) )
        return;
    // start the data structure for level update
    // we cannot fail to visit a node when using this structure because the
    // nodes are stored by their _old_ levels, which are assumed to be correct
    Vec_VecClear( p->vLevels );
    Vec_VecPush( p->vLevels, LevelOld, pObjNew );
    pObjNew->fMarkA = 1;
    // recursively update level
    Vec_VecForEachEntryStart( p->vLevels, pTemp, Lev, k, LevelOld )
    {
        pTemp->fMarkA = 0;
        assert( Aig_ObjLevel(pTemp) == Lev );
        pTemp->Level = Aig_ObjLevelNew(pTemp);
        // if the level did not change, no need to check the fanout levels
        if ( Aig_ObjLevel(pTemp) == Lev )
            continue;
        // schedule fanout for level update
        Aig_ObjForEachFanout( p, pTemp, pFanout, iFanout, m )
        {
            if ( Aig_ObjIsNode(pFanout) && !pFanout->fMarkA )
            {
                assert( Aig_ObjLevel(pFanout) >= Lev );
                Vec_VecPush( p->vLevels, Aig_ObjLevel(pFanout), pFanout );
                pFanout->fMarkA = 1;
            }
        }
    }
}

/**Function*************************************************************

  Synopsis    [Incrementally updates level of the nodes.]

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
void Aig_ManUpdateReverseLevel( Aig_Man_t * p, Aig_Obj_t * pObjNew )
{
    Aig_Obj_t * pFanin, * pTemp;
    int LevelOld, LevFanin, Lev, k;
    assert( p->vLevelR != NULL );
    assert( Aig_ObjIsNode(pObjNew) );
    // allocate level if needed
    if ( p->vLevels == NULL )
        p->vLevels = Vec_VecAlloc( Aig_ManLevels(p) + 8 );
    // check if level has changed
    LevelOld = Aig_ObjReverseLevel(p, pObjNew);
    if ( LevelOld == Aig_ObjReverseLevelNew(p, pObjNew) )
        return;
    // start the data structure for level update
    // we cannot fail to visit a node when using this structure because the
    // nodes are stored by their _old_ levels, which are assumed to be correct
    Vec_VecClear( p->vLevels );
    Vec_VecPush( p->vLevels, LevelOld, pObjNew );
    pObjNew->fMarkA = 1;
    // recursively update level
    Vec_VecForEachEntryStart( p->vLevels, pTemp, Lev, k, LevelOld )
    {
        pTemp->fMarkA = 0;
        LevelOld = Aig_ObjReverseLevel(p, pTemp);
        assert( LevelOld == Lev );
        Aig_ObjSetReverseLevel( p, pTemp, Aig_ObjReverseLevelNew(p, pTemp) );
        // if the level did not change, to need to check the fanout levels
        if ( Aig_ObjReverseLevel(p, pTemp) == Lev )
            continue;
        // schedule fanins for level update
        pFanin = Aig_ObjFanin0(pTemp);
        if ( Aig_ObjIsNode(pFanin) && !pFanin->fMarkA )
        {
            LevFanin = Aig_ObjReverseLevel( p, pFanin );
            assert( LevFanin >= Lev );
            Vec_VecPush( p->vLevels, LevFanin, pFanin );
            pFanin->fMarkA = 1;
        }
        pFanin = Aig_ObjFanin1(pTemp);
        if ( Aig_ObjIsNode(pFanin) && !pFanin->fMarkA )
        {
            LevFanin = Aig_ObjReverseLevel( p, pFanin );
            assert( LevFanin >= Lev );
            Vec_VecPush( p->vLevels, LevFanin, pFanin );
            pFanin->fMarkA = 1;
        }
    }
}

/**Function*************************************************************

  Synopsis    [Verifies direct level of the nodes.]

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
void Aig_ManVerifyLevel( Aig_Man_t * p )
{
    Aig_Obj_t * pObj;
    int i, Counter = 0;
    assert( p->pFanData );
    Aig_ManForEachNode( p, pObj, i )
        if ( Aig_ObjLevel(pObj) != Aig_ObjLevelNew(pObj) )
        {
            printf( "Level of node %6d should be %4d instead of %4d.\n",
                pObj->Id, Aig_ObjLevelNew(pObj), Aig_ObjLevel(pObj) );
            Counter++;
        }
    if ( Counter )
    printf( "Levels of %d nodes are incorrect.\n", Counter );
}

/**Function*************************************************************

  Synopsis    [Verifies reverse level of the nodes.]

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
void Aig_ManVerifyReverseLevel( Aig_Man_t * p )
{
    Aig_Obj_t * pObj;
    int i, Counter = 0;
    assert( p->vLevelR );
    Aig_ManForEachNode( p, pObj, i )
        if ( Aig_ObjLevel(pObj) != Aig_ObjLevelNew(pObj) )
        {
            printf( "Reverse level of node %6d should be %4d instead of %4d.\n",
                pObj->Id, Aig_ObjReverseLevelNew(p, pObj), Aig_ObjReverseLevel(p, pObj) );
            Counter++;
        }
    if ( Counter )
    printf( "Reverse levels of %d nodes are incorrect.\n", Counter );
}

////////////////////////////////////////////////////////////////////////
///                       END OF FILE                                ///
////////////////////////////////////////////////////////////////////////

redpajama_set_name: RedPajamaGithub


text:
"""
Run this after updating country_info.json and or
"""
from frappe.utils.install import import_country_and_currency

def execute():
	import_country_and_currency()


text:
<?php

namespace Vectorface\SnappyRouterTests\Di;

use Exception;
use PHPUnit\Framework\TestCase;
use Vectorface\SnappyRouter\Di\ServiceProvider;
use Vectorface\SnappyRouterTests\Controller\TestDummyController;

class ServiceProviderTest extends TestCase
{
    /**
     * An overview of how to use the ServiceProvider class.
     *
     * @throws Exception
     */
    public function testSynopsis()
    {
        // instantiate the class
        $config = [
            'TestController' => TestDummyController::class
        ];
        $serviceProvider = new ServiceProvider($config);

        // public setters (object chaining)
        $services = array_merge(
            $config,
            [
                'AnotherService'             => '/path/to/anotherService.php',
                'AnotherServiceForFileClass' => null
            ]
        );

        $serviceProvider->setService('AnotherService', '/path/to/anotherService.php');
        $serviceProvider->setService(
            'AnotherServiceForFileClass',
            [
                'file'  => 'tests/Vectorface/SnappyRouterTests/Controller/NonNamespacedController.php',
                'class' => 'NonNamespacedController',
            ]
        );

        // public getters
        $this->assertEquals(
            array_keys($services),
            $serviceProvider->getServices()
        );
        $this->assertEquals(
            '/path/to/anotherService.php',
            $serviceProvider->getService('AnotherService')
        );

        $this->assertInstanceOf(
            TestDummyController::class,
            $serviceProvider->getServiceInstance('TestController')
        );

        //Tests instanceCache
        $this->assertInstanceOf(
            TestDummyController::class,
            $serviceProvider->getServiceInstance('TestController')
        );

        $this->assertInstanceOf(
            'NonNamespacedController',
            $serviceProvider->getServiceInstance('AnotherServiceForFileClass')
        );
    }

    /**
     * Test that we can retrieve a non namespaced service.
     *
     * @throws Exception
     */
    public function testNonNamespacedService()
    {
        $config = [
            'NonNamespacedController' => 'tests/Vectorface/SnappyRouterTests/Controller/NonNamespacedController.php'
        ];
        $serviceProvider = new ServiceProvider($config);

        $this->assertInstanceOf(
            'NonNamespacedController',
            $serviceProvider->getServiceInstance('NonNamespacedController')
        );
    }

    /**
     * Test that we can retrieve a service while in namespace provisioning mode.
     *
     * @throws Exception
     */
    public function testNamespaceProvisioning()
    {
        $serviceProvider = new ServiceProvider([]);
        $namespaces = ['Vectorface\SnappyRouterTests\Controller'];
        $serviceProvider->setNamespaces($namespaces);

        $this->assertInstanceOf(
            TestDummyController::class,
            $serviceProvider->getServiceInstance('TestDummyController')
        );
    }

    /**
     * Test that we get an exception if we cannot find the service in any
     * of the given namespaces.
     *
     * @throws Exception
     */
    public function testNamespaceProvisioningMissingService()
    {
        $this->expectException(Exception::class);
        $this->expectExceptionMessage("Controller class TestDummyController was not found in any listed namespace.");

        $serviceProvider = new ServiceProvider([]);
        $serviceProvider->setNamespaces([]);

        $this->assertInstanceOf(
            TestDummyController::class,
            $serviceProvider->getServiceInstance('TestDummyController')
        );
    }

    /**
     * Test that we can retrieve a service while in folder provisioning mode.
     *
     * @throws Exception
     */
    public function testFolderProvisioning()
    {
        $serviceProvider = new ServiceProvider([]);
        $folders = [realpath(__DIR__.'/../')];
        $serviceProvider->setFolders($folders);

        $this->assertInstanceOf(
            'NonNamespacedController',
            $serviceProvider->getServiceInstance('NonNamespacedController')
        );
    }

    /**
     * Test that we get an exception if we cannot find the service in any
     * of the given folders (recursively checking).
     *
     * @throws Exception
     */
    public function testFolderProvisioningMissingService()
    {
        $this->expectException(Exception::class);
        $this->expectExceptionMessage("Controller class NonExistentController not found in any listed folder.");

        $serviceProvider = new ServiceProvider([]);
        $folders = [realpath(__DIR__.'/../')];
        $serviceProvider->setFolders($folders);

        $serviceProvider->getServiceInstance('NonExistentController');
    }
}


text:
package org.dashbuilder.client.navigation.widget.editor;

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.dashbuilder.client.navigation.event.NavItemEditCancelledEvent;
import org.dashbuilder.client.navigation.event.NavItemEditStartedEvent;
import org.dashbuilder.client.navigation.plugin.PerspectivePluginManager;
import org.dashbuilder.navigation.NavDivider;
import org.dashbuilder.navigation.NavFactory;
import org.dashbuilder.navigation.NavGroup;
import org.dashbuilder.navigation.NavItem;
import org.dashbuilder.navigation.workbench.NavWorkbenchCtx;
import org.jboss.errai.ioc.client.container.SyncBeanManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.uberfire.client.authz.PerspectiveTreeProvider;
import org.uberfire.client.mvp.PlaceManager;
import org.uberfire.mocks.EventSourceMock;
import org.uberfire.mvp.Command;

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

@RunWith(GwtMockitoTestRunner.class)
public class NavItemEditorTest {

    @Mock
    NavItemDefaultEditorView view;

    @Mock
    SyncBeanManager beanManager;

    @Mock
    PerspectiveTreeProvider perspectiveTreeProvider;

    @Mock
    EventSourceMock<NavItemEditStartedEvent> navItemEditStartedEvent;

    @Mock
    EventSourceMock<NavItemEditCancelledEvent> navItemEditCancelledEvent;

    @Mock
    PlaceManager placeManager;

    @Mock
    TargetPerspectiveEditor targetPerspectiveEditor;

    @Mock
    PerspectivePluginManager perspectivePluginManager;

    @Mock
    Command updateCommand;

    NavItemEditor presenter;
    static final String NEW_PERSPECTIVE_NAME = "- New Perspective -";

    @Before
    public void setUp() throws Exception {
        presenter = new NavItemDefaultEditor(view, beanManager,
                placeManager, perspectiveTreeProvider, targetPerspectiveEditor,
                perspectivePluginManager, navItemEditStartedEvent, navItemEditCancelledEvent);

        when(view.i18nNewItemName("Perspective")).thenReturn(NEW_PERSPECTIVE_NAME);
        presenter.getSettings().setLiteralPerspective("Perspective");

        doAnswer(invocationOnMock -> invocationOnMock.getArguments()[0])
                .when(targetPerspectiveEditor).getPerspectiveName(anyString());
    }

    @Test
    public void testChangeGroup() {
        NavGroup navGroup = NavFactory.get().createNavGroup();
        navGroup.setId("id");
        navGroup.setName("name");
        navGroup.setDescription("description");
        navGroup.setModifiable(true);
        presenter.setOnUpdateCommand(updateCommand);
        presenter.edit(navGroup);

        when(view.getItemName()).thenReturn("name");
        presenter.onChangesOk();
        verify(view).finishItemEdition();
        verify(updateCommand).execute();
        assertEquals(presenter.getNavItem().getName(), "name");

        reset(updateCommand);
        reset(view);
        when(view.getItemName()).thenReturn("  \t   ");
        presenter.onChangesOk();
        verify(view, never()).finishItemEdition();
        verify(updateCommand, never()).execute();
        assertEquals(presenter.getNavItem().getName(), "name");

        reset(updateCommand);
        reset(view);
        when(view.getItemName()).thenReturn("newName");
        presenter.onChangesOk();
        verify(view).finishItemEdition();
        verify(updateCommand).execute();
        assertEquals(presenter.getNavItem().getName(), "newName");
    }

    @Test
    public void testChangePerspective() {
        NavItem navItem = NavFactory.get().createNavItem();
        NavWorkbenchCtx navCtxA = NavWorkbenchCtx.perspective("A");
        NavWorkbenchCtx navCtxB = NavWorkbenchCtx.perspective("B");
        navItem.setContext(navCtxA.toString());

        navItem.setId("id");
        navItem.setName("name");
        navItem.setDescription("description");
        navItem.setModifiable(true);
        presenter.setOnUpdateCommand(updateCommand);
        presenter.edit(navItem);

        // Empty perspective
        when(view.getItemName()).thenReturn("name");
        presenter.onChangesOk();
        verify(view, never()).finishItemEdition();

        // Perspective changes
        reset(updateCommand);
        reset(view);
        when(view.getItemName()).thenReturn("name");
        when(targetPerspectiveEditor.getPerspectiveId()).thenReturn("B");
        presenter.onChangesOk();
        verify(view).finishItemEdition();
        verify(updateCommand).execute();
        assertEquals(presenter.getNavItem().getName(), "name");
        assertEquals(presenter.getNavItem().getContext(), navCtxB.toString());

        // Cancel changes
        navItem.setContext(navCtxA.toString());
        presenter.edit(navItem);
        reset(updateCommand);
        reset(targetPerspectiveEditor);
        reset(view);
        when(view.getItemName()).thenReturn("newName");
        when(targetPerspectiveEditor.getPerspectiveId()).thenReturn("B");
        presenter.cancelEdition();
        verify(view).finishItemEdition();
        verify(view).setItemName("name");
        verify(targetPerspectiveEditor).setPerspectiveId("A");
        assertEquals(presenter.getNavItem().getName(), "name");
        assertEquals(presenter.getNavItem().getContext(), navCtxA.toString());
    }

    @Test
    public void testEditGroup() {
        NavGroup navGroup = NavFactory.get().createNavGroup();
        navGroup.setId("id");
        navGroup.setName("name");
        navGroup.setDescription("description");
        navGroup.setModifiable(false);
        presenter.edit(navGroup);

        verify(view, atLeastOnce()).clearChildren();
        verify(view, atLeastOnce()).clearCommands();
        verify(view).setItemName("name");
        verify(view).setItemDescription("description");
        verify(view).setItemEditable(false);
        verify(view).setItemType(NavItemEditor.ItemType.GROUP);
        verify(view, atLeastOnce()).setCommandsEnabled(true);
        verify(view, atLeastOnce()).addCommand(any(), any());
        verify(view, never()).setContextWidget(any());
    }

    @Test
    public void testEditDivider() {
        NavDivider divider = NavFactory.get().createDivider();
        divider.setId("id");
        divider.setName("name");
        divider.setDescription("description");
        divider.setModifiable(true);
        presenter.edit(divider);

        verify(view, atLeastOnce()).clearChildren();
        verify(view, atLeastOnce()).clearCommands();
        verify(view).setItemName("name");
        verify(view).setItemDescription("description");
        verify(view).setItemEditable(false);
        verify(view).setItemType(NavItemEditor.ItemType.DIVIDER);
        verify(view, atLeastOnce()).setCommandsEnabled(true);
        verify(view, atLeastOnce()).addCommand(any(), any());
        verify(view, never()).setContextWidget(any());

        reset(view);
        presenter.startEdition();
        verify(view, never()).startItemEdition();
    }

    @Test
    public void testEditPerspective() {
        NavItem navItem = NavFactory.get().createNavItem();
        navItem.setModifiable(false);
        navItem.setContext(NavWorkbenchCtx.perspective("p1").toString());
        presenter.edit(navItem);

        verify(view, atLeastOnce()).clearChildren();
        verify(view, atLeastOnce()).clearCommands();
        verify(view).setItemEditable(false);
        verify(view).setItemType(NavItemEditor.ItemType.PERSPECTIVE);
        verify(view, atLeastOnce()).setCommandsEnabled(true);
        verify(view, atLeastOnce()).addCommand(any(), any());
        verify(view).setContextWidget(targetPerspectiveEditor);
    }

    @Test
    public void testCommandsAvailability() {
        // Disable move actions
        presenter.setMoveUpEnabled(false);
        presenter.setMoveDownEnabled(false);

        // Non-modifiable group (only creation actions available)
        NavGroup navGroup = NavFactory.get().createNavGroup();
        navGroup.setModifiable(false);
        presenter.edit(navGroup);
        verify(view, atLeastOnce()).setCommandsEnabled(true);

        // Modifiable group (creation actions)
        reset(view);
        navGroup.setModifiable(true);
        presenter.edit(navGroup);
        verify(view, atLeastOnce()).setCommandsEnabled(true);

        // Non-modifiable perspective (move actions disabled => no actions)
        reset(view);
        NavItem navItem = NavFactory.get().createNavItem();
        navItem.setContext(NavWorkbenchCtx.perspective("p1").toString());
        navItem.setModifiable(false);
        presenter.edit(navItem);
        verify(view, never()).setCommandsEnabled(true);

        // Modifiable perspective (only delete action)
        reset(view);
        navItem.setModifiable(true);
        presenter.edit(navItem);
        verify(view).setItemEditable(true);
        verify(view).setItemDeletable(true);
        verify(view, never()).setCommandsEnabled(true);

        // Modifiable divider (only delete action)
        reset(view);
        NavDivider navDivider = NavFactory.get().createDivider();
        navDivider.setModifiable(true);
        presenter.edit(navDivider);
        verify(view).setItemEditable(false);
        verify(view).setItemDeletable(true);
        verify(view, never()).setCommandsEnabled(true);

        // Non-modifiable divider (no actions)
        reset(view);
        navDivider.setModifiable(false);
        presenter.edit(navDivider);
        verify(view, never()).setCommandsEnabled(true);

        // Move actions available
        reset(view);
        presenter.setMoveUpEnabled(true);
        presenter.setMoveDownEnabled(true);
        presenter.edit(navItem);
        verify(view, atLeastOnce()).setCommandsEnabled(true);
        reset(view);
        presenter.edit(navDivider);
        verify(view, atLeastOnce()).setCommandsEnabled(true);
        reset(view);
        presenter.edit(navGroup);
        verify(view, atLeastOnce()).setCommandsEnabled(true);
    }

    @Test
    public void testItemNameFromPerspective() {
        NavItem navItem = NavFactory.get().createNavItem();
        navItem.setId("id");
        navItem.setName("name");
        navItem.setModifiable(true);
        navItem.setContext(NavWorkbenchCtx.perspective("A").toString());

        // Existing item => The name does not changes on perspective change
        presenter.edit(navItem);
        presenter.startEdition();
        verify(view).setItemName("name");
        when(targetPerspectiveEditor.getPerspectiveId()).thenReturn("B");
        presenter.onTargetPerspectiveUpdated();
        verify(view, never()).setItemName("B");

        // Newly created item => The name always matches the selected perspective
        reset(view);
        navItem.setName(NEW_PERSPECTIVE_NAME);
        presenter.edit(navItem);
        presenter.startEdition();
        verify(view).setItemName("A");
        when(targetPerspectiveEditor.getPerspectiveId()).thenReturn("B");
        presenter.onTargetPerspectiveUpdated();
        verify(view).setItemName("B");

        // If user changes the name then the auto-matching is disabled
        reset(view);
        presenter.onItemNameChanged();
        presenter.onTargetPerspectiveUpdated();
        verify(view, never()).setItemName("B");
    }
}


text:
Convertion.color = new function (){

	'use strict';

	this.FromRGB = function (){

		var rgb = color.RGB.getcolor();
		var cmy = this.rgb.tocmy(rgb);
		var hsv = this.rgb.tohsv(rgb);

		Validation.form.color.cmy.setForm(cmy);
		Validation.form.color.hsv.setForm(hsv);

		console.log(rgb);
		console.log(hsv);
		console.log(cmy);
	};

	this.FromCMY = function (){

		var cmy = color.CMY.getcolor();
		var rgb = this.cmy.torgb(cmy);
		var hsv = this.rgb.tohsv(rgb);

		color.RGB.setcolor(rgb);

		Validation.form.color.rgb.setForm(rgb);
		Validation.form.color.hsv.setForm(hsv);

		console.log(rgb);
		console.log(hsv);
		console.log(cmy);
	};

	this.FromHSV = function (){

		var hsv = color.HSV.getcolor();
		var rgb = this.hsv.torgb(hsv);
		var cmy = this.rgb.tocmy(rgb);

		color.RGB.setcolor(rgb);

		Validation.form.color.rgb.setForm(rgb);
		Validation.form.color.cmy.setForm(cmy);

		console.log(rgb);
		console.log(hsv);
		console.log(cmy);
	};

};


text:
Redditext
=========

Extract text from URLs for reading purposes. Right now, it only gets the text from [Reddit](https://reddit.com). Future plan is to extend it to be more friendlier to any URLs given.

### Plans
- [ ] Extend it such that it can take any URL
- [ ] If the article is good and want to send to kindle, have the interface for that.
- [ ] ...


text:
#pragma once

class ClientSession;
struct OverlappedIOContext;

class IocpManager
{
public:
	IocpManager();
	~IocpManager();

	bool Initialize();
	void Finalize();

	bool StartIoThreads();
	bool StartAcceptLoop();

	HANDLE GetCompletionPort()	{ return mCompletionPort; }
	int	GetIoThreadCount()		{ return mIoThreadCount;  }

private:

	static unsigned int WINAPI IoWorkerThread(LPVOID lpParam);

	static bool ReceiveCompletion(const ClientSession* client, OverlappedIOContext* context, DWORD dwTransferred);
	static bool SendCompletion(const ClientSession* client, OverlappedIOContext* context, DWORD dwTransferred);

private:

	HANDLE	mCompletionPort;
	int		mIoThreadCount;

	SOCKET	mListenSocket;

};

extern __declspec(thread) int LIoThreadId;
extern IocpManager* GIocpManager;


text:
See my [blog post for details](http://www.evanjones.ca/jvm-mmap-pause.html).

1. Start a new Ubuntu image.
2. Run the following commands:
  ```
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install linux-virtual gcc screen openjdk-8-jdk
sudo reboot
  ```
3. Copy these files to this machine.
4. `gcc --std=gnu99 -O3 -Wall -Wextra -o mmapwritepause mmapwritepause.c`
5. Start screen. In one terminal: `./mmapwritepause /tmp/mmapout`
6. In another terminal: `./diskload.sh`
7. Watch the output of `mmapwritepause`; it will print long pauses.

# JVM reproduction

1. `javac MakeGarbage.java`
2. `java -XX:+PrintGCDetails -XX:+PrintGC -XX:+PrintGCDateStamps -XX:+PrintGCApplicationStoppedTime -Xmx1G -Xms1G MakeGarbage`
3. In another terminal, run `./diskload.sh`

This will show large safepoint times, correlated with when mmapwritepause reports pauses. To verify that disabling the stats fixes the problem, add `-XX:+PerfDisableSharedMem` and rerun it.


text:
from django.core.management.base import BaseCommand

from app.users.serializers import UserSerializer
from oauth2_provider.admin import Application

class Command(BaseCommand):
    def handle(self, *args, **options):
        app = Application(
            name='Auth',
            client_id='RBPoX0l6x2D2kuhe3UCrU1pNrCLaKdgME2ce2I3T',
            client_secret='oabAcDqFoGCRUyH4YEbLCAugrjznSFd4OUHKLAsNkGxPOAAU9tJjwp6SF1KGW9T7QKzFwjZyxUrjidbht9gXwgvr7kDLBXVjiAHGFvYQ0B3iCHTPYcp4qZ9NZNEtdJZW',
            user_id=1,
            client_type='confidential',
            authorization_grant_type='password'
        )
        app.save()


text:
package org.zstack.storage.fusionstor;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.zstack.header.core.Completion;
import org.zstack.header.core.ReturnValueCompletion;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.rest.JsonAsyncRESTCallback;
import org.zstack.header.rest.RESTFacade;
import org.zstack.utils.ssh.Ssh;

/**
 * Created by frank on 7/27/2015.
 */
@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE, dependencyCheck = true)
public abstract class FusionstorMonBase {
    protected FusionstorMonAO self;

    @Autowired
    protected RESTFacade restf;

    public static class PingResult {
        public boolean operationFailure;
        public boolean success;
        public String error;
    }

    public abstract void connect(Completion completion);

    public abstract void ping(ReturnValueCompletion<PingResult> completion);

    protected abstract int getAgentPort();

    public FusionstorMonBase(FusionstorMonAO self) {
        this.self = self;
    }

    protected void checkTools() {
        Ssh ssh = new Ssh();
        ssh.setHostname(self.getHostname()).setUsername(self.getSshUsername()).setPassword(self.getSshPassword())
            .checkTool("/opt/fusionstack/lich/bin/lich", "/opt/fusionstack/lich/sbin/lichd").runErrorByExceptionAndClose();
    }

    protected String makeHttpPath(String ip, String path) {
        return String.format("http://%s:%s%s", ip, getAgentPort(), path);
    }

    public <T> void httpCall(final String path, final Object cmd, final Class<T> retClass, final ReturnValueCompletion<T> completion) {
        restf.asyncJsonPost(makeHttpPath(self.getHostname(), path), cmd, new JsonAsyncRESTCallback<T>(completion) {
            @Override
            public void fail(ErrorCode err) {
                completion.fail(err);
            }

            @Override
            public void success(T ret) {
                completion.success(ret);
            }

            @Override
            public Class<T> getReturnClass() {
                return retClass;
            }
        });
    }

    public FusionstorMonAO getSelf() {
        return self;
    }
}


text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>

#include "vtkPolyDataAlgorithmWrap.h"
#include "vtkTessellatedBoxSourceWrap.h"
#include "vtkObjectWrap.h"
#include "../../plus/plus.h"

using namespace v8;

extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkTessellatedBoxSourceWrap::ptpl;

VtkTessellatedBoxSourceWrap::VtkTessellatedBoxSourceWrap()
{ }

VtkTessellatedBoxSourceWrap::VtkTessellatedBoxSourceWrap(vtkSmartPointer<vtkTessellatedBoxSource> _native)
{ native = _native; }

VtkTessellatedBoxSourceWrap::~VtkTessellatedBoxSourceWrap()
{ }

void VtkTessellatedBoxSourceWrap::Init(v8::Local<v8::Object> exports)
{
	Nan::SetAccessor(exports, Nan::New("vtkTessellatedBoxSource").ToLocalChecked(), ConstructorGetter);
	Nan::SetAccessor(exports, Nan::New("TessellatedBoxSource").ToLocalChecked(), ConstructorGetter);
}

void VtkTessellatedBoxSourceWrap::ConstructorGetter(
	v8::Local<v8::String> property,
	const Nan::PropertyCallbackInfo<v8::Value>& info)
{
	InitPtpl();
	info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}

void VtkTessellatedBoxSourceWrap::InitPtpl()
{
	if (!ptpl.IsEmpty()) return;
	v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
	VtkPolyDataAlgorithmWrap::InitPtpl( );
	tpl->Inherit(Nan::New<FunctionTemplate>(VtkPolyDataAlgorithmWrap::ptpl));
	tpl->SetClassName(Nan::New("VtkTessellatedBoxSourceWrap").ToLocalChecked());
	tpl->InstanceTemplate()->SetInternalFieldCount(1);

	Nan::SetPrototypeMethod(tpl, "DuplicateSharedPointsOff", DuplicateSharedPointsOff);
	Nan::SetPrototypeMethod(tpl, "duplicateSharedPointsOff", DuplicateSharedPointsOff);

	Nan::SetPrototypeMethod(tpl, "DuplicateSharedPointsOn", DuplicateSharedPointsOn);
	Nan::SetPrototypeMethod(tpl, "duplicateSharedPointsOn", DuplicateSharedPointsOn);

	Nan::SetPrototypeMethod(tpl, "GetBounds", GetBounds);
	Nan::SetPrototypeMethod(tpl, "getBounds", GetBounds);

	Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName);
	Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName);

	Nan::SetPrototypeMethod(tpl, "GetDuplicateSharedPoints", GetDuplicateSharedPoints);
	Nan::SetPrototypeMethod(tpl, "getDuplicateSharedPoints", GetDuplicateSharedPoints);

	Nan::SetPrototypeMethod(tpl, "GetLevel", GetLevel);
	Nan::SetPrototypeMethod(tpl, "getLevel", GetLevel);

	Nan::SetPrototypeMethod(tpl, "GetOutputPointsPrecision", GetOutputPointsPrecision);
	Nan::SetPrototypeMethod(tpl, "getOutputPointsPrecision", GetOutputPointsPrecision);

	Nan::SetPrototypeMethod(tpl, "GetQuads", GetQuads);
	Nan::SetPrototypeMethod(tpl, "getQuads", GetQuads);

	Nan::SetPrototypeMethod(tpl, "IsA", IsA);
	Nan::SetPrototypeMethod(tpl, "isA", IsA);

	Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
	Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);

	Nan::SetPrototypeMethod(tpl, "QuadsOff", QuadsOff);
	Nan::SetPrototypeMethod(tpl, "quadsOff", QuadsOff);

	Nan::SetPrototypeMethod(tpl, "QuadsOn", QuadsOn);
	Nan::SetPrototypeMethod(tpl, "quadsOn", QuadsOn);

	Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
	Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);

	Nan::SetPrototypeMethod(tpl, "SetBounds", SetBounds);
	Nan::SetPrototypeMethod(tpl, "setBounds", SetBounds);

	Nan::SetPrototypeMethod(tpl, "SetDuplicateSharedPoints", SetDuplicateSharedPoints);
	Nan::SetPrototypeMethod(tpl, "setDuplicateSharedPoints", SetDuplicateSharedPoints);

	Nan::SetPrototypeMethod(tpl, "SetLevel", SetLevel);
	Nan::SetPrototypeMethod(tpl, "setLevel", SetLevel);

	Nan::SetPrototypeMethod(tpl, "SetOutputPointsPrecision", SetOutputPointsPrecision);
	Nan::SetPrototypeMethod(tpl, "setOutputPointsPrecision", SetOutputPointsPrecision);

	Nan::SetPrototypeMethod(tpl, "SetQuads", SetQuads);
	Nan::SetPrototypeMethod(tpl, "setQuads", SetQuads);

#ifdef VTK_NODE_PLUS_VTKTESSELLATEDBOXSOURCEWRAP_INITPTPL
	VTK_NODE_PLUS_VTKTESSELLATEDBOXSOURCEWRAP_INITPTPL
#endif
	ptpl.Reset( tpl );
}

void VtkTessellatedBoxSourceWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	if(!info.IsConstructCall())
	{
		Nan::ThrowError("Constructor not called in a construct call.");
		return;
	}

	if(info.Length() == 0)
	{
		vtkSmartPointer<vtkTessellatedBoxSource> native = vtkSmartPointer<vtkTessellatedBoxSource>::New();
		VtkTessellatedBoxSourceWrap* obj = new VtkTessellatedBoxSourceWrap(native);
		obj->Wrap(info.This());
	}
	else
	{
		if(info[0]->ToObject() != vtkNodeJsNoWrap )
		{
			Nan::ThrowError("Parameter Error");
			return;
		}
	}

	info.GetReturnValue().Set(info.This());
}

void VtkTessellatedBoxSourceWrap::DuplicateSharedPointsOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->DuplicateSharedPointsOff();
}

void VtkTessellatedBoxSourceWrap::DuplicateSharedPointsOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->DuplicateSharedPointsOn();
}

void VtkTessellatedBoxSourceWrap::GetBounds(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
	double const * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetBounds();
	Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 6 * sizeof(double));
	Local<v8::Float64Array> at = v8::Float64Array::New(ab, 0, 6);
	memcpy(ab->GetContents().Data(), r, 6 * sizeof(double));
	info.GetReturnValue().Set(at);
}

void VtkTessellatedBoxSourceWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
	char const * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetClassName();
	info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}

void VtkTessellatedBoxSourceWrap::GetDuplicateSharedPoints(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
	int r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetDuplicateSharedPoints();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkTessellatedBoxSourceWrap::GetLevel(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
	int r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetLevel();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkTessellatedBoxSourceWrap::GetOutputPointsPrecision(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
	int r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetOutputPointsPrecision();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkTessellatedBoxSourceWrap::GetQuads(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
	int r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetQuads();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkTessellatedBoxSourceWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsString())
	{
		Nan::Utf8String a0(info[0]);
		int r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->IsA(
			*a0
		);
		info.GetReturnValue().Set(Nan::New(r));
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkTessellatedBoxSourceWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
	vtkTessellatedBoxSource * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->NewInstance();
	VtkTessellatedBoxSourceWrap::InitPtpl();
	v8::Local<v8::Value> argv[1] =
		{ Nan::New(vtkNodeJsNoWrap) };
	v8::Local<v8::Function> cons =
		Nan::New<v8::FunctionTemplate>(VtkTessellatedBoxSourceWrap::ptpl)->GetFunction();
	v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
	VtkTessellatedBoxSourceWrap *w = new VtkTessellatedBoxSourceWrap();
	w->native = r;
	w->Wrap(wo);
	info.GetReturnValue().Set(wo);
}

void VtkTessellatedBoxSourceWrap::QuadsOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->QuadsOff();
}

void VtkTessellatedBoxSourceWrap::QuadsOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
		if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	native->QuadsOn();
}

void VtkTessellatedBoxSourceWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0]))
	{
		VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject());
		vtkTessellatedBoxSource * r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->SafeDownCast(
			(vtkObject *) a0->native.GetPointer()
		);
		VtkTessellatedBoxSourceWrap::InitPtpl();
		v8::Local<v8::Value> argv[1] =
			{ Nan::New(vtkNodeJsNoWrap) };
		v8::Local<v8::Function> cons =
			Nan::New<v8::FunctionTemplate>(VtkTessellatedBoxSourceWrap::ptpl)->GetFunction();
		v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
		VtkTessellatedBoxSourceWrap *w = new VtkTessellatedBoxSourceWrap();
		w->native = r;
		w->Wrap(wo);
		info.GetReturnValue().Set(wo);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkTessellatedBoxSourceWrap::SetBounds(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
	size_t i;
	if(info.Length() > 0 && info[0]->IsFloat64Array())
	{
		v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
		if( a0->Length() < 6 )
		{
			Nan::ThrowError("Array too short.");
			return;
		}

				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetBounds(
			(double *)(a0->Buffer()->GetContents().Data())
		);
		return;
	}
	else if(info.Length() > 0 && info[0]->IsArray())
	{
		v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
		double b0[6];
		if( a0->Length() < 6 )
		{
			Nan::ThrowError("Array too short.");
			return;
		}

		for( i = 0; i < 6; i++ )
		{
			if( !a0->Get(i)->IsNumber() )
			{
				Nan::ThrowError("Array contents invalid.");
				return;
			}
			b0[i] = a0->Get(i)->NumberValue();
		}
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetBounds(
			b0
		);
		return;
	}
	else if(info.Length() > 0 && info[0]->IsNumber())
	{
		if(info.Length() > 1 && info[1]->IsNumber())
		{
			if(info.Length() > 2 && info[2]->IsNumber())
			{
				if(info.Length() > 3 && info[3]->IsNumber())
				{
					if(info.Length() > 4 && info[4]->IsNumber())
					{
						if(info.Length() > 5 && info[5]->IsNumber())
						{
														if(info.Length() != 6)
							{
								Nan::ThrowError("Too many parameters.");
								return;
							}
							native->SetBounds(
								info[0]->NumberValue(),
								info[1]->NumberValue(),
								info[2]->NumberValue(),
								info[3]->NumberValue(),
								info[4]->NumberValue(),
								info[5]->NumberValue()
							);
							return;
						}
					}
				}
			}
		}
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkTessellatedBoxSourceWrap::SetDuplicateSharedPoints(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsInt32())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetDuplicateSharedPoints(
			info[0]->Int32Value()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkTessellatedBoxSourceWrap::SetLevel(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsInt32())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetLevel(
			info[0]->Int32Value()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkTessellatedBoxSourceWrap::SetOutputPointsPrecision(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsInt32())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetOutputPointsPrecision(
			info[0]->Int32Value()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkTessellatedBoxSourceWrap::SetQuads(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkTessellatedBoxSourceWrap *wrapper = ObjectWrap::Unwrap<VtkTessellatedBoxSourceWrap>(info.Holder());
	vtkTessellatedBoxSource *native = (vtkTessellatedBoxSource *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsInt32())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetQuads(
			info[0]->Int32Value()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}


text:
<?php

namespace KTU\CountersBundle\Controller;

use KTU\CountersBundle\Components\Locale;
use KTU\CountersBundle\Model\CategoriesModel;
use KTU\CountersBundle\Model\CountersModel;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class DefaultController. Homepage controller.
 * @package KTU\CountersBundle\Controller
 */
class DefaultController extends Controller
{
    /**
     * Renders main page, includes TOP counters and all categories
     * @param Request $request
     * @return Response
     */
    public function indexAction(Request $request)
    {
        $manager = $this->getDoctrine()->getManager();
        $locale = $request->getLocale();
        $locator = new Locale($request);
        $columnName = $locator->getCategoryColumn($locale);

        $topPages = $this->container->getParameter('ktu_counters.top_pages');
        $counters = CountersModel::getTopCounters($manager, $topPages, date('Y-m-d'));
        $categories = CategoriesModel::getCategoriesInfo($manager, $columnName);

        return $this->render('KTUCountersBundle:Default:index.html.twig', array(
            'counters' => $counters,
            'categories' => $categories
        ));
    }

    /**
     * Changes the user's locale according to the given parameter.
     * @param Request $request
     * @param $locale Locale to be changed.
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function changeLocaleAction(Request $request, $locale)
    {
        $locales = $this->container->getParameter('ktu_counters.languages');
        $locator = new Locale($request);
        if (in_array($locale, $locales)) {
            $locator->setCookieLocale($locale);
        }
        $url = $this->generateUrl('ktu_counters_homepage');
        return $this->redirect($url);
    }
}


text:
  Javaugues est
       un village
       localisé dans le département de Haute-Loire en Auvergne. On dénombrait 191 habitants en 2008.

Si vous pensez venir habiter à Javaugues, vous pourrez aisément trouver une maison à vendre.

Le parc de logements, à Javaugues, se décomposait en 2011 en cinq appartements et 97 maisons soit
 un marché plutôt équilibré.

La ville offre quelques  équipements sportifs, elle dispose, entre autres, de une boucle de randonnée.

À coté de Javaugues sont positionnées géographiquement les villes de
Chaniat à 3 km, 156 habitants,
Saint-Didier-sur-Doulon située à 4 km, 228 habitants,
Saint-Préjet-Armandon localisée à 6 km, 105 habitants,
La Chomette située à 6 km, 136 habitants,
Domeyrat à 4 km, 162 habitants,
Frugières-le-Pin à 2 km, 142 habitants,
 entre autres. De plus, Javaugues est située à seulement sept km de Brioude.


text:
module DeployNotifier
  class GithubCommits
    def self.commits_since_sha(sha)
      # magic
    end
  end
end


text:
package ua.dp.radiator;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;

import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClient.ResponseSpec;

import reactor.core.publisher.Mono;

public class Helper {

	public static WebClient mockWebClient(final Mono<?> mono) {
		WebClient originalClient = WebClient.create();
		WebClient client = spy(originalClient);

		WebClient.UriSpec uriSpec = mock(WebClient.UriSpec.class);
		doReturn(uriSpec).when(client).get();

		WebClient.RequestHeadersSpec<?> headerSpec = mock(WebClient.RequestHeadersSpec.class);
		doReturn(headerSpec).when(uriSpec).uri(anyString());
		doReturn(headerSpec).when(headerSpec).header(any(), any());
		doReturn(headerSpec).when(headerSpec).accept(any());
		doReturn(headerSpec).when(headerSpec).acceptCharset(any());

		ResponseSpec responseSpec = mock(ResponseSpec.class);
		doReturn(responseSpec).when(headerSpec).retrieve();
		doReturn(mono).when(responseSpec).bodyToMono(any());

		ClientResponse clientResponse = mock(ClientResponse.class);
		doReturn(mono).when(clientResponse).bodyToMono(any());
		doReturn(Mono.just(clientResponse)).when(headerSpec).exchange();

		return client;
	}
}


text:
from stack import Stack

def dec2bin(decNumber):

    remStack = Stack()
    binString = ''

    if not isinstance(decNumber,int):
        print("args should be integer: .", end = ' ')
        return -1
    elif decNumber < 0:
        print("args should not be negative:", end = ' ')
        return -1
    elif decNumber == 0:
        binString = '0'
    else:
        while decNumber > 0:
            remainder = decNumber % 2
            decNumber = decNumber // 2
            remStack.push(remainder)

    while not remStack.isEmpty():
        binString = binString + str(remStack.pop())

    return binString

print("dec = 0, bin = {}".format(dec2bin(0)))
print("dec = -1, bin = {}".format(dec2bin(-1)))
print("dec = 8, bin = {}".format(dec2bin(8)))
print("dec = 17, bin = {}".format(dec2bin(17)))
print("dec = 21, bin = {}".format(dec2bin(21)))
print("dec = 21939449955959595, bin = {}".format(dec2bin(21939449955959595)))
print("dec = 1.9, bin = {}".format(dec2bin(1.9)))
print("dec = '89', bin = {}".format(dec2bin('89')))


text:
using Content.Server.Cargo.Systems;
using Content.Shared.Cargo;
using Content.Shared.Cargo.Components;
using Content.Shared.MachineLinking;
using Robust.Shared.Audio;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;

namespace Content.Server.Cargo.Components
{
    /// <summary>
    /// Handles teleporting in requested cargo after the specified delay.
    /// </summary>
    [RegisterComponent, Access(typeof(CargoSystem))]
    public sealed class CargoTelepadComponent : SharedCargoTelepadComponent
    {
        [DataField("delay")]
        public float Delay = 45f;

        /// <summary>
        /// How much time we've accumulated until next teleport.
        /// </summary>
        [DataField("accumulator")]
        public float Accumulator = 0f;

        [ViewVariables]
        public CargoTelepadState CurrentState = CargoTelepadState.Unpowered;

        [DataField("teleportSound")] public SoundSpecifier TeleportSound = new SoundPathSpecifier("/Audio/Machines/phasein.ogg");

        /// <summary>
        ///     The paper-type prototype to spawn with the order information.
        /// </summary>
        [DataField("printerOutput", customTypeSerializer: typeof(PrototypeIdSerializer<EntityPrototype>))]
        public string PrinterOutput = "Paper";

        [DataField("receiverPort", customTypeSerializer: typeof(PrototypeIdSerializer<ReceiverPortPrototype>))]
        public string ReceiverPort = "OrderReceiver";
    }
}


text:
package org.openqa.selenium.grid.data;

import org.openqa.selenium.internal.Require;
import org.openqa.selenium.json.JsonInput;

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

import static java.util.Collections.unmodifiableMap;

public class NewSessionErrorResponse {

  private final String message;
  private final RequestId requestId;

  public NewSessionErrorResponse(RequestId requestId, String message) {
    this.requestId = Require.nonNull("Request Id", requestId);
    this.message = Require.nonNull("Message", message);
  }

  public String getMessage() {
    return message;
  }

  public RequestId getRequestId() {
    return requestId;
  }

  private Map<String, Object> toJson() {
    Map<String, Object> toReturn = new TreeMap<>();
    toReturn.put("message", message);
    toReturn.put("requestId", requestId);
    return unmodifiableMap(toReturn);
  }

  private static NewSessionErrorResponse fromJson(JsonInput input) {
    String message = null;
    RequestId requestId = null;

    input.beginObject();
    while (input.hasNext()) {
      switch (input.nextName()) {
        case "message":
          message = input.read(String.class);
          break;

        case "requestId":
          requestId = input.read(RequestId.class);
          break;

        default:
          input.skipValue();
          break;
      }
    }
    input.endObject();

    return new NewSessionErrorResponse(requestId, message);
  }

}


text:
/**
 * Autogenerated by Thrift Compiler (0.10.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.airavata.model.workflow;

import java.util.Map;
import java.util.HashMap;
import org.apache.thrift.TEnum;

public enum HandlerState implements org.apache.thrift.TEnum {
  CREATED(0),
  VALIDATED(1),
  SCHEDULED(2),
  LAUNCHED(3),
  EXECUTING(4),
  CANCELING(5),
  CANCELED(6),
  COMPLETED(7),
  FAILED(8);

  private final int value;

  private HandlerState(int value) {
    this.value = value;
  }

  /**
   * Get the integer value of this enum value, as defined in the Thrift IDL.
   */
  public int getValue() {
    return value;
  }

  /**
   * Find a the enum type by its integer value, as defined in the Thrift IDL.
   * @return null if the value is not found.
   */
  public static HandlerState findByValue(int value) {
    switch (value) {
      case 0:
        return CREATED;
      case 1:
        return VALIDATED;
      case 2:
        return SCHEDULED;
      case 3:
        return LAUNCHED;
      case 4:
        return EXECUTING;
      case 5:
        return CANCELING;
      case 6:
        return CANCELED;
      case 7:
        return COMPLETED;
      case 8:
        return FAILED;
      default:
        return null;
    }
  }
}