text:
@extends(Theme::path('admin/layouts/modal'))

@section('title')
	{{{ $title }}}
@stop

@section('styles')

@stop

@section('scripts')

@stop

@section('content')

	@if ($message = Session::get('success'))

	@else

@if (isset($user))
	{{ Form::open_horizontal(array('url' => array('admin/users/' . $user->id . '/email'), 'files'=>true,'class' => 'form-ajax', 'onsubmit' => "$('#wysiwyg-body').html($('#editor').html());")) }}
@else
	{{ Form::open_horizontal(array('url' => array('admin/user/mass/email'), 'files'=>true,'class' => 'form-ajax', 'onsubmit' => "$('#wysiwyg-body').html($('#editor').html());")) }}
@endif

	@if(isset($multi) && count($multi) > 0)
		{{ Form::select_group('to[]', '', $multi, $selected, $errors,array('multiple'=>'multiple','required'=>'required', 'style'=>'width: 100%; height: 40px;'), '',false) }}
	@endif

	{{ Form::input_group('text', 'subject', '', '', $errors, array('maxlength'=>'256','required'=>'required', 'placeholder'=>Lang::get('core.subject')), '', false) }}

			@include(Theme::path('wysiwyg'))

				{{ Form::reset(Lang::get('button.cancel'), array('class' => 'btn btn-responsive btn-danger', 'onclick'=>"$('#site-modal').modal('hide')")) }}
				{{ Form::reset(Lang::get('button.reset'), array('class' => 'btn btn-responsive btn-default')) }}

					     <input type="file" name="email_attachment" multiple>

						<button type="button" class="btn-responsive btn btn-default dropdown-toggle" data-toggle="dropdown">
							Template

						</button>

Default

							@foreach($templates as $id=>$var)
								@if($var->getFilename() != 'default.blade.php')

										getRelativePathname())) }}}">{{{ str_replace(DIRECTORY_SEPARATOR, '.',rtrim($var->getRelativePathname(),'.blade.php')) }}}

								@endif
							@endforeach

				{{ Form::submit(Lang::get('button.send'), array('class' => 'btn-responsive btn btn-success')) }}

			<input type="hidden" id="email-template" name="template" value="emails.default"/>
			<textarea class="hide" id="wysiwyg-body" name="body"></textarea>

	{{ Form::close() }}
	@endif
@stop

redpajama_set_name: RedPajamaGithub


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

#include "chrome/browser/ash/preferences.h"

#include <limits>
#include <memory>
#include <vector>

#include "ash/components/peripheral_notification/peripheral_notification_manager.h"
#include "ash/components/settings/cros_settings_names.h"
#include "ash/components/timezone/timezone_resolver.h"
#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/constants/ash_switches.h"
#include "ash/public/ash_interfaces.h"
#include "ash/public/cpp/ash_prefs.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/i18n/time_formatting.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ash/accessibility/magnification_manager.h"
#include "chrome/browser/ash/base/locale_util.h"
#include "chrome/browser/ash/child_accounts/parent_access_code/parent_access_service.h"
#include "chrome/browser/ash/crosapi/browser_util.h"
#include "chrome/browser/ash/drive/file_system_util.h"
#include "chrome/browser/ash/input_method/input_method_persistence.h"
#include "chrome/browser/ash/input_method/input_method_syncer.h"
#include "chrome/browser/ash/login/consolidated_consent_field_trial.h"
#include "chrome/browser/ash/login/login_pref_names.h"
#include "chrome/browser/ash/login/session/user_session_manager.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/ash/settings/cros_settings.h"
#include "chrome/browser/ash/system/input_device_settings.h"
#include "chrome/browser/ash/system/timezone_resolver_manager.h"
#include "chrome/browser/ash/system/timezone_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/prefs/pref_service_syncable_util.h"
#include "chrome/browser/ui/ash/system_tray_client_impl.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/pref_names.h"
#include "chromeos/ash/components/dbus/pciguard/pciguard_client.h"
#include "chromeos/ash/components/dbus/update_engine/update_engine.pb.h"
#include "chromeos/ash/components/dbus/update_engine/update_engine_client.h"
#include "chromeos/components/disks/disks_prefs.h"
#include "chromeos/system/devicemode.h"
#include "chromeos/system/statistics_provider.h"
#include "components/drive/drive_pref_names.h"
#include "components/feedback/content/content_tracing_manager.h"
#include "components/language/core/browser/pref_names.h"
#include "components/policy/proto/chrome_device_policy.pb.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_member.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/sync_preferences/pref_service_syncable.h"
#include "components/user_manager/known_user.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_manager.h"
#include "content/public/browser/browser_thread.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/mojom/speech/speech_synthesis.mojom.h"
#include "third_party/cros_system_api/dbus/update_engine/dbus-constants.h"
#include "third_party/icu/source/i18n/unicode/timezone.h"
#include "ui/base/ime/ash/extension_ime_util.h"
#include "ui/base/ime/ash/ime_keyboard.h"
#include "ui/base/ime/ash/input_method_manager.h"
#include "ui/chromeos/events/modifier_key.h"
#include "ui/chromeos/events/pref_names.h"
#include "ui/events/event_constants.h"
#include "ui/events/event_utils.h"
#include "url/gurl.h"

namespace ash {

namespace {

// These preferences will be saved in global user preferences dictionary so that
// they can be used on the signin screen.
const char* const kCopyToKnownUserPrefs[] = {
    // The keyboard preferences that determine how we remap modifier keys.
    ::prefs::kLanguageRemapSearchKeyTo,
    ::prefs::kLanguageRemapControlKeyTo,
    ::prefs::kLanguageRemapAltKeyTo,
    ::prefs::kLanguageRemapCapsLockKeyTo,
    ::prefs::kLanguageRemapEscapeKeyTo,
    ::prefs::kLanguageRemapBackspaceKeyTo,
    ::prefs::kLanguageRemapExternalCommandKeyTo,
    ::prefs::kLanguageRemapExternalMetaKeyTo,

    prefs::kLoginDisplayPasswordButtonEnabled,
    ::prefs::kUse24HourClock,
    prefs::kDarkModeEnabled};

bool AreScrollSettingsAllowed() {
  return base::FeatureList::IsEnabled(features::kAllowScrollSettings);
}

}  // namespace

Preferences::Preferences()
    : Preferences(input_method::InputMethodManager::Get()) {}

Preferences::Preferences(input_method::InputMethodManager* input_method_manager)
    : prefs_(nullptr),
      input_method_manager_(input_method_manager),
      user_(nullptr),
      user_is_primary_(false) {
  BindCrosDisplayConfigController(
      cros_display_config_.BindNewPipeAndPassReceiver());
}

Preferences::~Preferences() {
  prefs_->RemoveObserver(this);
  user_manager::UserManager::Get()->RemoveSessionStateObserver(this);
  UpdateEngineClient::Get()->RemoveObserver(this);
}

// static
void Preferences::RegisterPrefs(PrefRegistrySimple* registry) {
  registry->RegisterBooleanPref(::prefs::kOwnerPrimaryMouseButtonRight, false);
  registry->RegisterBooleanPref(::prefs::kOwnerPrimaryPointingStickButtonRight,
                                false);
  registry->RegisterBooleanPref(::prefs::kOwnerTapToClickEnabled, true);
  // TODO(jamescook): Move ownership and registration into ash.
  registry->RegisterStringPref(::prefs::kLogoutStartedLast, std::string());
  registry->RegisterStringPref(::prefs::kSigninScreenTimezone, std::string());
  registry->RegisterIntegerPref(
      ::prefs::kResolveDeviceTimezoneByGeolocationMethod,
      static_cast<int>(
          system::TimeZoneResolverManager::TimeZoneResolveMethod::IP_ONLY));
  registry->RegisterIntegerPref(
      ::prefs::kSystemTimezoneAutomaticDetectionPolicy,
      enterprise_management::SystemTimezoneProto::USERS_DECIDE);
  registry->RegisterStringPref(::prefs::kMinimumAllowedChromeVersion, "");
  registry->RegisterIntegerPref(
      ::prefs::kLacrosLaunchSwitch,
      static_cast<int>(crosapi::browser_util::LacrosAvailability::kUserChoice));
  registry->RegisterStringPref(::prefs::kLacrosDataBackwardMigrationMode, "");
  registry->RegisterBooleanPref(prefs::kDeviceSystemWideTracingEnabled, true);
  registry->RegisterBooleanPref(
      prefs::kLocalStateDevicePeripheralDataAccessEnabled, false);
  registry->RegisterBooleanPref(prefs::kDeviceI18nShortcutsEnabled, true);
  registry->RegisterBooleanPref(prefs::kChromadToCloudMigrationEnabled, false);
  registry->RegisterBooleanPref(prefs::kLoginScreenWebUILazyLoading, false);
  registry->RegisterBooleanPref(::prefs::kConsumerAutoUpdateToggle, true);

  RegisterLocalStatePrefs(registry);
  ash::consolidated_consent_field_trial::RegisterLocalStatePrefs(registry);
}

// static
void Preferences::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  // Some classes register their own prefs.
  input_method::InputMethodSyncer::RegisterProfilePrefs(registry);
  crosapi::browser_util::RegisterProfilePrefs(registry);

  std::string hardware_keyboard_id;
  // TODO(yusukes): Remove the runtime hack.
  if (chromeos::IsRunningAsSystemCompositor()) {
    DCHECK(g_browser_process);
    PrefService* local_state = g_browser_process->local_state();
    DCHECK(local_state);
    hardware_keyboard_id =
        local_state->GetString(::prefs::kHardwareKeyboardLayout);
  } else {
    hardware_keyboard_id = "xkb:us::eng";  // only for testing.
  }

  registry->RegisterBooleanPref(::prefs::kPerformanceTracingEnabled, false);

  registry->RegisterBooleanPref(
      ::prefs::kTapToClickEnabled, true,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterBooleanPref(::prefs::kEnableTouchpadThreeFingerClick,
                                false);
  // This preference can only be set to true by policy or command_line flag
  // and it should not carry over to sessions were neither of these is set.
  registry->RegisterBooleanPref(::prefs::kUnifiedDesktopEnabledByDefault, false,
                                PrefRegistry::NO_REGISTRATION_FLAGS);
  // TODO(anasalazar): Finish moving this to ash.
  registry->RegisterBooleanPref(
      prefs::kNaturalScroll,
      base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kNaturalScrollDefault),
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterBooleanPref(
      prefs::kMouseReverseScroll, false,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);

  registry->RegisterBooleanPref(
      ::prefs::kPrimaryMouseButtonRight, false,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterBooleanPref(
      ::prefs::kPrimaryPointingStickButtonRight, false,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterBooleanPref(
      ::prefs::kMouseAcceleration, true,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterBooleanPref(
      ::prefs::kMouseScrollAcceleration, true,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterBooleanPref(
      ::prefs::kPointingStickAcceleration, true,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterBooleanPref(
      ::prefs::kTouchpadAcceleration, true,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterBooleanPref(
      ::prefs::kTouchpadScrollAcceleration, true,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterBooleanPref(
      ::prefs::kTouchpadHapticFeedback, true,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterBooleanPref(::prefs::kLabsMediaplayerEnabled, false);
  registry->RegisterBooleanPref(::prefs::kLabsAdvancedFilesystemEnabled, false);
  registry->RegisterBooleanPref(::prefs::kAppReinstallRecommendationEnabled,
                                false);

  registry->RegisterIntegerPref(
      ::prefs::kMouseSensitivity, 3,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterIntegerPref(
      ::prefs::kMouseScrollSensitivity, 3,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterIntegerPref(
      ::prefs::kPointingStickSensitivity, 3,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterIntegerPref(
      ::prefs::kTouchpadSensitivity, 3,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterIntegerPref(
      ::prefs::kTouchpadScrollSensitivity, 3,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterIntegerPref(
      ::prefs::kTouchpadHapticClickSensitivity, 3,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterBooleanPref(
      ::prefs::kUse24HourClock, base::GetHourClockType() == base::k24HourClock,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);
  registry->RegisterBooleanPref(
      drive::prefs::kDisableDrive, false,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);
  registry->RegisterBooleanPref(
      drive::prefs::kDisableDriveOverCellular, true,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);
  registry->RegisterBooleanPref(drive::prefs::kDriveFsWasLaunchedAtLeastOnce,
                                false);
  registry->RegisterStringPref(drive::prefs::kDriveFsProfileSalt, "");
  registry->RegisterBooleanPref(drive::prefs::kDriveFsPinnedMigrated, false);
  registry->RegisterBooleanPref(drive::prefs::kDriveFsEnableVerboseLogging,
                                false);
  // Do not sync drive::prefs::kDriveFsEnableMirrorSync and
  // drive::prefs::kDriveFsMirrorSyncMachineId because we're syncing local files
  // and users may wish to turn this off on a per device basis.
  registry->RegisterBooleanPref(drive::prefs::kDriveFsEnableMirrorSync, false);
  registry->RegisterStringPref(drive::prefs::kDriveFsMirrorSyncMachineRootId,
                               "");
  // We don't sync ::prefs::kLanguageCurrentInputMethod and PreviousInputMethod
  // because they're just used to track the logout state of the device.
  registry->RegisterStringPref(::prefs::kLanguageCurrentInputMethod, "");
  registry->RegisterStringPref(::prefs::kLanguagePreviousInputMethod, "");
  registry->RegisterListPref(::prefs::kLanguageAllowedInputMethods);
  registry->RegisterListPref(::prefs::kAllowedLanguages);
  registry->RegisterStringPref(::prefs::kLanguagePreloadEngines,
                               hardware_keyboard_id);
  registry->RegisterStringPref(::prefs::kLanguageEnabledImes, "");
  registry->RegisterDictionaryPref(prefs::kAssistiveInputFeatureSettings);
  registry->RegisterBooleanPref(prefs::kAssistPersonalInfoEnabled, true);
  registry->RegisterBooleanPref(prefs::kAssistPredictiveWritingEnabled, true);
  registry->RegisterBooleanPref(prefs::kEmojiSuggestionEnabled, true);
  registry->RegisterBooleanPref(prefs::kEmojiSuggestionEnterpriseAllowed, true);
  registry->RegisterDictionaryPref(
      ::prefs::kLanguageInputMethodSpecificSettings);
  registry->RegisterBooleanPref(prefs::kLastUsedImeShortcutReminderDismissed,
                                false);
  registry->RegisterBooleanPref(prefs::kNextImeShortcutReminderDismissed,
                                false);

  registry->RegisterIntegerPref(
      ::prefs::kLanguageRemapSearchKeyTo,
      static_cast<int>(ui::chromeos::ModifierKey::kSearchKey),
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterIntegerPref(
      ::prefs::kLanguageRemapControlKeyTo,
      static_cast<int>(ui::chromeos::ModifierKey::kControlKey),
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterIntegerPref(
      ::prefs::kLanguageRemapAltKeyTo,
      static_cast<int>(ui::chromeos::ModifierKey::kAltKey),
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterIntegerPref(
      ::prefs::kLanguageRemapAssistantKeyTo,
      static_cast<int>(ui::chromeos::ModifierKey::kAssistantKey),
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);

  // Even though most of the Chrome OS devices don't have the CapsLock key - the
  // user always could plug in an external keyboard with the CapsLock. So we're
  // syncing the pref to support this case.
  registry->RegisterIntegerPref(
      ::prefs::kLanguageRemapCapsLockKeyTo,
      static_cast<int>(ui::chromeos::ModifierKey::kCapsLockKey),
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);

  registry->RegisterIntegerPref(
      ::prefs::kLanguageRemapEscapeKeyTo,
      static_cast<int>(ui::chromeos::ModifierKey::kEscapeKey),
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  registry->RegisterIntegerPref(
      ::prefs::kLanguageRemapBackspaceKeyTo,
      static_cast<int>(ui::chromeos::ModifierKey::kBackspaceKey),
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  // The Command key on external Apple keyboards is remapped by default to Ctrl
  // until the user changes it from the keyboard settings.
  registry->RegisterIntegerPref(
      ::prefs::kLanguageRemapExternalCommandKeyTo,
      static_cast<int>(ui::chromeos::ModifierKey::kControlKey),
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  // The Meta key (Search or Windows keys) on external keyboards is remapped by
  // default to Search until the user changes it from the keyboard settings.
  registry->RegisterIntegerPref(
      ::prefs::kLanguageRemapExternalMetaKeyTo,
      static_cast<int>(ui::chromeos::ModifierKey::kSearchKey),
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PRIORITY_PREF);
  // The following pref isn't synced since the user may desire a different value
  // depending on whether an external keyboard is attached to a particular
  // device.
  registry->RegisterBooleanPref(prefs::kSendFunctionKeys, false);

  // Don't sync the note-taking app; it may not be installed on other devices.
  registry->RegisterStringPref(::prefs::kNoteTakingAppId, std::string());
  registry->RegisterBooleanPref(::prefs::kRestoreLastLockScreenNote, true);
  registry->RegisterDictionaryPref(
      ::prefs::kNoteTakingAppsLockScreenToastShown);

  registry->RegisterBooleanPref(::prefs::kShowMobileDataNotification, true);

  // Initially all existing users would see "What's new" for current version
  // after update.
  registry->RegisterStringPref(
      ::prefs::kChromeOSReleaseNotesVersion, "0.0.0.0",
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);

  disks::prefs::RegisterProfilePrefs(registry);

  registry->RegisterStringPref(::prefs::kTermsOfServiceURL, "");

  registry->RegisterBooleanPref(::prefs::kTouchVirtualKeyboardEnabled, false);

  std::string current_timezone_id;
  if (CrosSettings::IsInitialized()) {
    // In unit tests CrosSettings is not always initialized.
    CrosSettings::Get()->GetString(kSystemTimezone, &current_timezone_id);
  }
  // |current_timezone_id| will be empty if CrosSettings doesn't know the
  // timezone yet.
  registry->RegisterStringPref(::prefs::kUserTimezone, current_timezone_id);

  registry->RegisterBooleanPref(
      ::prefs::kResolveTimezoneByGeolocationMigratedToMethod, false,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);

  bool allow_time_zone_resolve_by_default = true;
  // CfM devices default to static timezone unless time zone resolving is
  // explicitly enabled for the signin screen (usually by policy).
  // We need local_state fully initialized, which does not happen in tests.
  if (!g_browser_process->local_state() ||
      g_browser_process->local_state()
              ->GetAllPrefStoresInitializationStatus() ==
          PrefService::INITIALIZATION_STATUS_WAITING ||
      system::InputDeviceSettings::Get()->ForceKeyboardDrivenUINavigation() ||
      !system::TimeZoneResolverManager::
          IfServiceShouldBeRunningForSigninScreen()) {
    allow_time_zone_resolve_by_default = false;
  }

  registry->RegisterIntegerPref(
      ::prefs::kResolveTimezoneByGeolocationMethod,
      static_cast<int>(
          allow_time_zone_resolve_by_default
              ? system::TimeZoneResolverManager::TimeZoneResolveMethod::IP_ONLY
              : system::TimeZoneResolverManager::TimeZoneResolveMethod::
                    DISABLED),
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);

  registry->RegisterBooleanPref(
      ::prefs::kCaptivePortalAuthenticationIgnoresProxy, true);

  registry->RegisterBooleanPref(::prefs::kLanguageImeMenuActivated, false);

  // TODO(b/227674947): Eventually delete this after Sign in with Smart Lock has
  // been removed and enough time has elapsed for users to be notified.
  registry->RegisterBooleanPref(
      ::prefs::kHasSeenSmartLockSignInRemovedNotification, false);

  registry->RegisterInt64Pref(::prefs::kHatsLastInteractionTimestamp, 0);

  registry->RegisterInt64Pref(::prefs::kHatsSurveyCycleEndTimestamp, 0);

  registry->RegisterBooleanPref(::prefs::kHatsDeviceIsSelected, false);

  registry->RegisterInt64Pref(::prefs::kHatsOnboardingSurveyCycleEndTs, 0);

  registry->RegisterBooleanPref(::prefs::kHatsOnboardingDeviceIsSelected,
                                false);

  registry->RegisterInt64Pref(::prefs::kHatsSmartLockSurveyCycleEndTs, 0);

  registry->RegisterBooleanPref(::prefs::kHatsSmartLockDeviceIsSelected, false);

  registry->RegisterInt64Pref(::prefs::kHatsUnlockSurveyCycleEndTs, 0);

  registry->RegisterBooleanPref(::prefs::kHatsUnlockDeviceIsSelected, false);

  registry->RegisterInt64Pref(::prefs::kHatsArcGamesSurveyCycleEndTs, 0);

  registry->RegisterBooleanPref(::prefs::kHatsArcGamesDeviceIsSelected, false);

  registry->RegisterInt64Pref(::prefs::kHatsAudioSurveyCycleEndTs, 0);

  registry->RegisterBooleanPref(::prefs::kHatsAudioDeviceIsSelected, false);

  registry->RegisterInt64Pref(::prefs::kHatsEntSurveyCycleEndTs, 0);

  registry->RegisterBooleanPref(::prefs::kHatsEntDeviceIsSelected, false);

  registry->RegisterInt64Pref(::prefs::kHatsStabilitySurveyCycleEndTs, 0);

  registry->RegisterBooleanPref(::prefs::kHatsStabilityDeviceIsSelected, false);

  registry->RegisterInt64Pref(::prefs::kHatsPerformanceSurveyCycleEndTs, 0);

  registry->RegisterBooleanPref(::prefs::kHatsPerformanceDeviceIsSelected,
                                false);

  registry->RegisterInt64Pref(::prefs::kHatsCameraAppSurveyCycleEndTs, 0);

  registry->RegisterBooleanPref(::prefs::kHatsCameraAppDeviceIsSelected, false);

  // Personalization HaTS survey prefs for avatar, screensaver, and wallpaper
  // features.
  registry->RegisterInt64Pref(
      ::prefs::kHatsPersonalizationAvatarSurveyCycleEndTs, 0);
  registry->RegisterBooleanPref(
      ::prefs::kHatsPersonalizationAvatarSurveyIsSelected, false);
  registry->RegisterInt64Pref(
      ::prefs::kHatsPersonalizationScreensaverSurveyCycleEndTs, 0);
  registry->RegisterBooleanPref(
      ::prefs::kHatsPersonalizationScreensaverSurveyIsSelected, false);
  registry->RegisterInt64Pref(
      ::prefs::kHatsPersonalizationWallpaperSurveyCycleEndTs, 0);
  registry->RegisterBooleanPref(
      ::prefs::kHatsPersonalizationWallpaperSurveyIsSelected, false);

  // MediaApp HaTS prefs for Pdf and Photos experiences.
  registry->RegisterInt64Pref(::prefs::kHatsMediaAppPdfCycleEndTs, 0);
  registry->RegisterBooleanPref(::prefs::kHatsMediaAppPdfIsSelected, false);
  registry->RegisterInt64Pref(::prefs::kHatsPhotosExperienceCycleEndTs, 0);
  registry->RegisterBooleanPref(::prefs::kHatsPhotosExperienceIsSelected,
                                false);

  registry->RegisterBooleanPref(::prefs::kPinUnlockFeatureNotificationShown,
                                false);
  registry->RegisterBooleanPref(
      ::prefs::kFingerprintUnlockFeatureNotificationShown, false);

  // We don't sync EOL related prefs because they are device specific.
  registry->RegisterBooleanPref(::prefs::kEolNotificationDismissed, false);
  registry->RegisterTimePref(::prefs::kEndOfLifeDate, base::Time());
  registry->RegisterBooleanPref(::prefs::kFirstEolWarningDismissed, false);
  registry->RegisterBooleanPref(::prefs::kSecondEolWarningDismissed, false);

  registry->RegisterBooleanPref(::prefs::kCastReceiverEnabled, false);
  registry->RegisterBooleanPref(::prefs::kShowArcSettingsOnSessionStart, false);
  registry->RegisterBooleanPref(::prefs::kShowSyncSettingsOnSessionStart,
                                false);

  // Text-to-speech prefs.
  registry->RegisterDictionaryPref(
      ::prefs::kTextToSpeechLangToVoiceName,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);
  registry->RegisterDoublePref(
      ::prefs::kTextToSpeechRate, blink::mojom::kSpeechSynthesisDefaultRate,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);
  registry->RegisterDoublePref(
      ::prefs::kTextToSpeechPitch, blink::mojom::kSpeechSynthesisDefaultPitch,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);
  registry->RegisterDoublePref(
      ::prefs::kTextToSpeechVolume, blink::mojom::kSpeechSynthesisDefaultVolume,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);

  registry->RegisterBooleanPref(prefs::kSyncOobeCompleted, false);

  registry->RegisterBooleanPref(::prefs::kTPMFirmwareUpdateCleanupDismissed,
                                false);

  registry->RegisterBooleanPref(::prefs::kStartupBrowserWindowLaunchSuppressed,
                                false);

  // This pref is a per-session pref and must not be synced.
  registry->RegisterBooleanPref(
      ::prefs::kLoginExtensionApiCanLockManagedGuestSession, false,
      PrefRegistry::NO_REGISTRATION_FLAGS);

  registry->RegisterBooleanPref(prefs::kLoginDisplayPasswordButtonEnabled,
                                true);

  registry->RegisterBooleanPref(
      prefs::kSuggestedContentEnabled, true,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);
  registry->RegisterBooleanPref(
      prefs::kLauncherResultEverLaunched, false,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);

  registry->RegisterDictionaryPref(prefs::kLauncherSearchNormalizerParameters);

  registry->RegisterListPref(
      prefs::kFilesAppFolderShortcuts,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);

  registry->RegisterBooleanPref(
      prefs::kFilesAppUIPrefsMigrated, false,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);

  registry->RegisterBooleanPref(
      prefs::kFilesAppTrashEnabled, true,
      user_prefs::PrefRegistrySyncable::SYNCABLE_OS_PREF);
}

void Preferences::InitUserPrefs(sync_preferences::PrefServiceSyncable* prefs) {
  prefs_ = prefs;

  BooleanPrefMember::NamedChangeCallback callback = base::BindRepeating(
      &Preferences::OnPreferenceChanged, base::Unretained(this));

  performance_tracing_enabled_.Init(::prefs::kPerformanceTracingEnabled, prefs,
                                    callback);
  tap_to_click_enabled_.Init(::prefs::kTapToClickEnabled, prefs, callback);
  three_finger_click_enabled_.Init(::prefs::kEnableTouchpadThreeFingerClick,
                                   prefs, callback);
  unified_desktop_enabled_by_default_.Init(
      ::prefs::kUnifiedDesktopEnabledByDefault, prefs, callback);
  // TODO(anasalazar): Finish moving this to ash.
  natural_scroll_.Init(prefs::kNaturalScroll, prefs, callback);
  mouse_reverse_scroll_.Init(prefs::kMouseReverseScroll, prefs, callback);

  mouse_sensitivity_.Init(::prefs::kMouseSensitivity, prefs, callback);
  mouse_scroll_sensitivity_.Init(::prefs::kMouseScrollSensitivity, prefs,
                                 callback);
  touchpad_sensitivity_.Init(::prefs::kTouchpadSensitivity, prefs, callback);
  touchpad_scroll_sensitivity_.Init(::prefs::kTouchpadScrollSensitivity, prefs,
                                    callback);
  pointing_stick_sensitivity_.Init(::prefs::kPointingStickSensitivity, prefs,
                                   callback);
  primary_mouse_button_right_.Init(::prefs::kPrimaryMouseButtonRight, prefs,
                                   callback);
  primary_pointing_stick_button_right_.Init(
      ::prefs::kPrimaryPointingStickButtonRight, prefs, callback);
  mouse_acceleration_.Init(::prefs::kMouseAcceleration, prefs, callback);
  mouse_scroll_acceleration_.Init(::prefs::kMouseScrollAcceleration, prefs,
                                  callback);
  pointing_stick_acceleration_.Init(::prefs::kPointingStickAcceleration, prefs,
                                    callback);
  touchpad_acceleration_.Init(::prefs::kTouchpadAcceleration, prefs, callback);
  touchpad_scroll_acceleration_.Init(::prefs::kTouchpadScrollAcceleration,
                                     prefs, callback);
  touchpad_haptic_feedback_.Init(::prefs::kTouchpadHapticFeedback, prefs,
                                 callback);
  touchpad_haptic_click_sensitivity_.Init(
      ::prefs::kTouchpadHapticClickSensitivity, prefs, callback);
  download_default_directory_.Init(::prefs::kDownloadDefaultDirectory, prefs,
                                   callback);
  preload_engines_.Init(::prefs::kLanguagePreloadEngines, prefs, callback);
  enabled_imes_.Init(::prefs::kLanguageEnabledImes, prefs, callback);
  current_input_method_.Init(::prefs::kLanguageCurrentInputMethod, prefs,
                             callback);
  previous_input_method_.Init(::prefs::kLanguagePreviousInputMethod, prefs,
                              callback);
  allowed_input_methods_.Init(::prefs::kLanguageAllowedInputMethods, prefs,
                              callback);
  allowed_languages_.Init(::prefs::kAllowedLanguages, prefs, callback);
  preferred_languages_.Init(language::prefs::kPreferredLanguages, prefs,
                            callback);
  ime_menu_activated_.Init(::prefs::kLanguageImeMenuActivated, prefs, callback);
  // Notifies the system tray to remove the IME items.
  if (ime_menu_activated_.GetValue())
    input_method::InputMethodManager::Get()->ImeMenuActivationChanged(true);

  xkb_auto_repeat_enabled_.Init(prefs::kXkbAutoRepeatEnabled, prefs, callback);
  xkb_auto_repeat_delay_pref_.Init(prefs::kXkbAutoRepeatDelay, prefs, callback);
  xkb_auto_repeat_interval_pref_.Init(prefs::kXkbAutoRepeatInterval, prefs,
                                      callback);
  pci_data_access_enabled_pref_.Init(
      prefs::kLocalStateDevicePeripheralDataAccessEnabled,
      g_browser_process->local_state(), callback);

  consumer_auto_update_toggle_pref_.Init(::prefs::kConsumerAutoUpdateToggle,
                                         g_browser_process->local_state(),
                                         callback);

  pref_change_registrar_.Init(prefs);
  pref_change_registrar_.Add(::prefs::kUserTimezone, callback);
  pref_change_registrar_.Add(::prefs::kResolveTimezoneByGeolocationMethod,
                             callback);
  pref_change_registrar_.Add(::prefs::kParentAccessCodeConfig, callback);
  for (auto* copy_pref : kCopyToKnownUserPrefs)
    pref_change_registrar_.Add(copy_pref, callback);

  // Re-enable OTA update when feature flag is disabled by owner.
  auto* update_engine_client = UpdateEngineClient::Get();
  if (user_manager::UserManager::Get()->IsCurrentUserOwner() &&
      !features::IsConsumerAutoUpdateToggleAllowed()) {
    // Write into the platform will signal back so pref gets synced.
    update_engine_client->ToggleFeature(
        update_engine::kFeatureConsumerAutoUpdate, true);
  } else {
    // Otherwise, trigger a read + sync with signal.
    update_engine_client->IsFeatureEnabled(
        update_engine::kFeatureConsumerAutoUpdate,
        base::BindOnce(&Preferences::OnIsConsumerAutoUpdateEnabled,
                       weak_ptr_factory_.GetWeakPtr()));
  }
}

void Preferences::Init(Profile* profile, const user_manager::User* user) {
  DCHECK(profile);
  DCHECK(user);
  sync_preferences::PrefServiceSyncable* prefs =
      PrefServiceSyncableFromProfile(profile);
  // This causes OnIsSyncingChanged to be called when the value of
  // PrefService::IsSyncing() changes.
  prefs->AddObserver(this);
  UpdateEngineClient::Get()->AddObserver(this);

  user_ = user;
  user_is_primary_ =
      user_manager::UserManager::Get()->GetPrimaryUser() == user_;
  InitUserPrefs(prefs);

  user_manager::UserManager::Get()->AddSessionStateObserver(this);

  UserSessionManager* session_manager = UserSessionManager::GetInstance();
  DCHECK(session_manager);
  ime_state_ = session_manager->GetDefaultIMEState(profile);

  if (user_is_primary_) {
    g_browser_process->platform_part()
        ->GetTimezoneResolverManager()
        ->SetPrimaryUserPrefs(prefs_);
  }

  // Initialize preferences to currently saved state.
  ApplyPreferences(REASON_INITIALIZATION, "");

  const std::string& login_input_method_id_used =
      session_manager->user_context().GetLoginInputMethodIdUsed();

  if (user_is_primary_ && !login_input_method_id_used.empty()) {
    // Persist input method when transitioning from Login screen into the
    // session.
    input_method::InputMethodPersistence::SetUserLastLoginInputMethodId(
        login_input_method_id_used, input_method::InputMethodManager::Get(),
        profile);
  }

  // Note that |ime_state_| was modified by ApplyPreferences(), and
  // SetState() is modifying |current_input_method_| (via
  // PersistUserInputMethod() ). This way SetState() here may be called only
  // after ApplyPreferences().
  // As InputMethodManager only holds the active state for the active user,
  // SetState() is only called if the preferences belongs to the active user.
  // See https://crbug.com/841112.
  if (user->is_active())
    input_method_manager_->SetState(ime_state_);

  input_method_syncer_ =
      std::make_unique<input_method::InputMethodSyncer>(prefs, ime_state_);
  input_method_syncer_->Initialize();

  // If a guest is logged in, initialize the prefs as if this is the first
  // login. For a regular user this is done in
  // UserSessionManager::InitProfilePreferences().
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kGuestSession))
    session_manager->SetFirstLoginPrefs(profile, std::string(), std::string());
}

void Preferences::InitUserPrefsForTesting(
    sync_preferences::PrefServiceSyncable* prefs,
    const user_manager::User* user,
    scoped_refptr<input_method::InputMethodManager::State> ime_state) {
  user_ = user;
  ime_state_ = ime_state;

  if (ime_state.get())
    input_method_manager_->SetState(ime_state);

  InitUserPrefs(prefs);

  UpdateEngineClient::Get()->AddObserver(this);

  input_method_syncer_ =
      std::make_unique<input_method::InputMethodSyncer>(prefs, ime_state_);
  input_method_syncer_->Initialize();
}

void Preferences::SetInputMethodListForTesting() {
  SetInputMethodList();
}

void Preferences::OnPreferenceChanged(const std::string& pref_name) {
  ApplyPreferences(REASON_PREF_CHANGED, pref_name);
}

void Preferences::ReportBooleanPrefApplication(
    ApplyReason reason,
    const std::string& changed_histogram_name,
    const std::string& started_histogram_name,
    bool sample) {
  if (reason == REASON_PREF_CHANGED)
    base::UmaHistogramBoolean(changed_histogram_name, sample);
  else if (reason == REASON_INITIALIZATION)
    base::UmaHistogramBoolean(started_histogram_name, sample);
}

void Preferences::ReportSensitivityPrefApplication(
    ApplyReason reason,
    const std::string& changed_histogram_name,
    const std::string& started_histogram_name,
    int sensitivity_int) {
  system::PointerSensitivity sensitivity =
      static_cast<system::PointerSensitivity>(sensitivity_int);
  if (reason == REASON_PREF_CHANGED)
    base::UmaHistogramEnumeration(changed_histogram_name, sensitivity);
  else if (reason == REASON_INITIALIZATION)
    base::UmaHistogramEnumeration(started_histogram_name, sensitivity);
}

void Preferences::ApplyPreferences(ApplyReason reason,
                                   const std::string& pref_name) {
  DCHECK(reason != REASON_PREF_CHANGED || !pref_name.empty());
  const bool user_is_owner =
      user_manager::UserManager::Get()->GetOwnerAccountId() ==
      user_->GetAccountId();
  const bool user_is_active = user_->is_active();

  system::TouchpadSettings touchpad_settings;
  system::MouseSettings mouse_settings;
  system::PointingStickSettings pointing_stick_settings;
  user_manager::KnownUser known_user(g_browser_process->local_state());

  if (user_is_primary_ && (reason == REASON_INITIALIZATION ||
                           pref_name == ::prefs::kPerformanceTracingEnabled)) {
    const bool enabled = performance_tracing_enabled_.GetValue();
    if (enabled)
      tracing_manager_ = ContentTracingManager::Create();
    else
      tracing_manager_.reset();
    SystemTrayClientImpl::Get()->SetPerformanceTracingIconVisible(enabled);
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kTapToClickEnabled) {
    const bool enabled = tap_to_click_enabled_.GetValue();
    if (user_is_active)
      touchpad_settings.SetTapToClick(enabled);
    ReportBooleanPrefApplication(reason, "Touchpad.TapToClick.Changed",
                                 "Touchpad.TapToClick.Started", enabled);

    // Save owner preference in local state to use on login screen.
    if (user_is_owner) {
      PrefService* prefs = g_browser_process->local_state();
      if (prefs->GetBoolean(::prefs::kOwnerTapToClickEnabled) != enabled)
        prefs->SetBoolean(::prefs::kOwnerTapToClickEnabled, enabled);
    }
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kEnableTouchpadThreeFingerClick) {
    const bool enabled = three_finger_click_enabled_.GetValue();
    if (user_is_active)
      touchpad_settings.SetThreeFingerClick(enabled);
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kUnifiedDesktopEnabledByDefault) {
    // "Unified Desktop" is a per-user policy setting which will not be applied
    // until a user logs in.
    if (cros_display_config_) {  // May be null in tests.
      cros_display_config_->SetUnifiedDesktopEnabled(
          unified_desktop_enabled_by_default_.GetValue());
    }
  }
  // TODO(anasalazar): Finish moving this to ash.
  if (reason != REASON_PREF_CHANGED || pref_name == prefs::kNaturalScroll) {
    // Force natural scroll default if we've sync'd and if the cmd line arg is
    // set.
    ForceNaturalScrollDefault();

    const bool enabled = natural_scroll_.GetValue();
    DVLOG(1) << "Natural scroll set to " << enabled;
    if (user_is_active)
      touchpad_settings.SetNaturalScroll(enabled);
    ReportBooleanPrefApplication(reason, "Touchpad.NaturalScroll.Changed",
                                 "Touchpad.NaturalScroll.Started", enabled);
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == prefs::kMouseReverseScroll) {
    const bool enabled = mouse_reverse_scroll_.GetValue();
    if (user_is_active)
      mouse_settings.SetReverseScroll(enabled);
    ReportBooleanPrefApplication(reason, "Mouse.ReverseScroll.Changed",
                                 "Mouse.ReverseScroll.Started", enabled);
  }

  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kMouseSensitivity) {
    const int sensitivity_int = mouse_sensitivity_.GetValue();
    if (user_is_active) {
      mouse_settings.SetSensitivity(sensitivity_int);

      // With the flag off, also set scroll sensitivity (legacy fallback).
      // TODO(https://crbug.com/836258): Remove check when flag is removed.
      if (!AreScrollSettingsAllowed())
        mouse_settings.SetScrollSensitivity(sensitivity_int);
    }
    ReportSensitivityPrefApplication(reason, "Mouse.PointerSensitivity.Changed",
                                     "Mouse.PointerSensitivity.Started",
                                     sensitivity_int);
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kMouseScrollSensitivity) {
    // With the flag off, use to normal sensitivity (legacy fallback).
    // TODO(https://crbug.com/836258): Remove check when flag is removed.
    const int sensitivity_int = AreScrollSettingsAllowed()
                                    ? mouse_scroll_sensitivity_.GetValue()
                                    : mouse_sensitivity_.GetValue();
    if (user_is_active)
      mouse_settings.SetScrollSensitivity(sensitivity_int);
    ReportSensitivityPrefApplication(reason, "Mouse.ScrollSensitivity.Changed",
                                     "Mouse.ScrollSensitivity.Started",
                                     sensitivity_int);
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kPointingStickSensitivity) {
    const int sensitivity_int = pointing_stick_sensitivity_.GetValue();
    if (user_is_active) {
      pointing_stick_settings.SetSensitivity(sensitivity_int);
    }
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kTouchpadSensitivity) {
    const int sensitivity_int = touchpad_sensitivity_.GetValue();
    if (user_is_active) {
      touchpad_settings.SetSensitivity(sensitivity_int);

      // With the flag off, also set scroll sensitivity (legacy fallback).
      // TODO(https://crbug.com/836258): Remove check when flag is removed.
      if (!AreScrollSettingsAllowed())
        touchpad_settings.SetScrollSensitivity(sensitivity_int);
    }
    ReportSensitivityPrefApplication(
        reason, "Touchpad.PointerSensitivity.Changed",
        "Touchpad.PointerSensitivity.Started", sensitivity_int);
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kTouchpadScrollSensitivity) {
    // With the flag off, use normal sensitivity (legacy fallback).
    // TODO(https://crbug.com/836258): Remove check when flag is removed.
    const int sensitivity_int = AreScrollSettingsAllowed()
                                    ? touchpad_scroll_sensitivity_.GetValue()
                                    : touchpad_sensitivity_.GetValue();
    if (user_is_active)
      touchpad_settings.SetScrollSensitivity(sensitivity_int);
    ReportSensitivityPrefApplication(
        reason, "Touchpad.ScrollSensitivity.Changed",
        "Touchpad.ScrollSensitivity.Started", sensitivity_int);
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kPrimaryMouseButtonRight) {
    const bool right = primary_mouse_button_right_.GetValue();
    if (user_is_active)
      mouse_settings.SetPrimaryButtonRight(right);
    ReportBooleanPrefApplication(reason, "Mouse.PrimaryButtonRight.Changed",
                                 "Mouse.PrimaryButtonRight.Started", right);
    // Save owner preference in local state to use on login screen.
    if (user_is_owner) {
      PrefService* prefs = g_browser_process->local_state();
      if (prefs->GetBoolean(::prefs::kOwnerPrimaryMouseButtonRight) != right)
        prefs->SetBoolean(::prefs::kOwnerPrimaryMouseButtonRight, right);
    }
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kPrimaryPointingStickButtonRight) {
    const bool right = primary_pointing_stick_button_right_.GetValue();
    if (user_is_active)
      pointing_stick_settings.SetPrimaryButtonRight(right);
    // Save owner preference in local state to use on login screen.
    if (user_is_owner) {
      PrefService* prefs = g_browser_process->local_state();
      if (prefs->GetBoolean(::prefs::kOwnerPrimaryPointingStickButtonRight) !=
          right) {
        prefs->SetBoolean(::prefs::kOwnerPrimaryPointingStickButtonRight,
                          right);
      }
    }
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kMouseAcceleration) {
    const bool enabled = mouse_acceleration_.GetValue();
    if (user_is_active)
      mouse_settings.SetAcceleration(enabled);
    ReportBooleanPrefApplication(reason, "Mouse.Acceleration.Changed",
                                 "Mouse.Acceleration.Started", enabled);
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kMouseScrollAcceleration) {
    const bool enabled = mouse_scroll_acceleration_.GetValue();
    if (user_is_active)
      mouse_settings.SetScrollAcceleration(enabled);
    ReportBooleanPrefApplication(reason, "Mouse.ScrollAcceleration.Changed",
                                 "Mouse.ScrollAcceleration.Started", enabled);
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kPointingStickAcceleration) {
    const bool enabled = pointing_stick_acceleration_.GetValue();
    if (user_is_active)
      pointing_stick_settings.SetAcceleration(enabled);
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kTouchpadAcceleration) {
    const bool enabled = touchpad_acceleration_.GetValue();
    if (user_is_active)
      touchpad_settings.SetAcceleration(enabled);
    ReportBooleanPrefApplication(reason, "Touchpad.Acceleration.Changed",
                                 "Touchpad.Acceleration.Started", enabled);
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kTouchpadScrollAcceleration) {
    const bool enabled = touchpad_scroll_acceleration_.GetValue();
    if (user_is_active)
      touchpad_settings.SetScrollAcceleration(enabled);
    ReportBooleanPrefApplication(reason, "Touchpad.ScrollAcceleration.Changed",
                                 "Touchpad.ScrollAcceleration.Started",
                                 enabled);
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kTouchpadHapticFeedback) {
    const bool enabled = touchpad_haptic_feedback_.GetValue();
    if (user_is_active)
      touchpad_settings.SetHapticFeedback(enabled);
    ReportBooleanPrefApplication(reason, "Touchpad.HapticFeedback.Changed",
                                 "Touchpad.HapticFeedback.Started", enabled);
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kTouchpadHapticClickSensitivity) {
    const int sensitivity_int = touchpad_haptic_click_sensitivity_.GetValue();
    if (user_is_active)
      touchpad_settings.SetHapticClickSensitivity(sensitivity_int);
    ReportSensitivityPrefApplication(
        reason, "Touchpad.HapticClickSensitivity.Changed",
        "Touchpad.HapticClickSensitivity.Started", sensitivity_int);
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kDownloadDefaultDirectory) {
    const bool default_download_to_drive = drive::util::IsUnderDriveMountPoint(
        download_default_directory_.GetValue());
    ReportBooleanPrefApplication(
        reason, "FileBrowser.DownloadDestination.IsGoogleDrive.Changed",
        "FileBrowser.DownloadDestination.IsGoogleDrive.Started",
        default_download_to_drive);
  }

  if (reason != REASON_PREF_CHANGED ||
      pref_name == prefs::kXkbAutoRepeatEnabled) {
    if (user_is_active) {
      const bool enabled = xkb_auto_repeat_enabled_.GetValue();
      input_method::InputMethodManager::Get()
          ->GetImeKeyboard()
          ->SetAutoRepeatEnabled(enabled);

      known_user.SetBooleanPref(user_->GetAccountId(),
                                prefs::kXkbAutoRepeatEnabled, enabled);
    }
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == prefs::kXkbAutoRepeatDelay ||
      pref_name == prefs::kXkbAutoRepeatInterval) {
    if (user_is_active)
      UpdateAutoRepeatRate();
  }
  if (reason != REASON_PREF_CHANGED ||
      pref_name == ::prefs::kLanguageAllowedInputMethods) {
    const std::vector<std::string> allowed_input_methods =
        allowed_input_methods_.GetValue();

    bool managed_by_policy =
        ime_state_->SetAllowedInputMethods(allowed_input_methods);
    bool success = ime_state_->ReplaceEnabledInputMethods(
        ime_state_->GetEnabledInputMethodIds());
    if (!success) {
      const std::vector<std::string> fallback = {
          ime_state_->GetAllowedFallBackKeyboardLayout()};
      ime_state_->ReplaceEnabledInputMethods(fallback);
    }

    if (managed_by_policy) {
      preload_engines_.SetValue(
          base::JoinString(ime_state_->GetEnabledInputMethodIds(), ","));
    }
  }
  if (reason != REASON_PREF_CHANGED || pref_name == ::prefs::kAllowedLanguages)
    locale_util::RemoveDisallowedLanguagesFromPreferred(prefs_);

  if (reason != REASON_PREF_CHANGED ||
      pref_name == language::prefs::kPreferredLanguages) {
    // In case setting has been changed with sync it can contain disallowed
    // values.
    locale_util::RemoveDisallowedLanguagesFromPreferred(prefs_);
  }

  if (reason == REASON_INITIALIZATION)
    SetInputMethodList();

  if (pref_name == ::prefs::kLanguagePreloadEngines &&
      reason == REASON_PREF_CHANGED) {
    SetLanguageConfigStringListAsCSV(language_prefs::kGeneralSectionName,
                                     language_prefs::kPreloadEnginesConfigName,
                                     preload_engines_.GetValue());
  }

  if ((reason == REASON_INITIALIZATION) ||
      (pref_name == ::prefs::kLanguageEnabledImes &&
       reason == REASON_PREF_CHANGED)) {
    std::string value(enabled_imes_.GetValue());

    std::vector<std::string> split_values;
    if (!value.empty()) {
      split_values = base::SplitString(value, ",", base::TRIM_WHITESPACE,
                                       base::SPLIT_WANT_ALL);
    }
    ime_state_->SetEnabledExtensionImes(&split_values);
  }

  if (pref_name == ::prefs::kLanguageImeMenuActivated &&
      (reason == REASON_PREF_CHANGED || reason == REASON_ACTIVE_USER_CHANGED)) {
    const bool activated = ime_menu_activated_.GetValue();
    input_method::InputMethodManager::Get()->ImeMenuActivationChanged(
        activated);
  }

  if (user_is_active) {
    system::InputDeviceSettings::Get()->UpdateTouchpadSettings(
        touchpad_settings);
    system::InputDeviceSettings::Get()->UpdateMouseSettings(mouse_settings);
    system::InputDeviceSettings::Get()->UpdatePointingStickSettings(
        pointing_stick_settings);
  }

  if (pref_name == ::prefs::kUserTimezone &&
      reason != REASON_ACTIVE_USER_CHANGED) {
    system::UpdateSystemTimezone(ProfileHelper::Get()->GetProfileByUser(user_));
  }

  if (pref_name == ::prefs::kResolveTimezoneByGeolocationMethod &&
      reason != REASON_ACTIVE_USER_CHANGED) {
    if (pref_name == ::prefs::kResolveTimezoneByGeolocationMethod &&
        !prefs_->FindPreference(::prefs::kResolveTimezoneByGeolocationMethod)
             ->IsDefaultValue()) {
      prefs_->SetBoolean(::prefs::kResolveTimezoneByGeolocationMigratedToMethod,
                         true);
    }
    if (user_is_owner) {
      // Policy check is false here, because there is no owner for enterprise.
      g_browser_process->local_state()->SetInteger(
          ::prefs::kResolveDeviceTimezoneByGeolocationMethod,
          static_cast<int>(system::TimeZoneResolverManager::
                               GetEffectiveUserTimeZoneResolveMethod(
                                   prefs_, false /* check_policy */)));
    }
    if (user_is_primary_) {
      g_browser_process->platform_part()
          ->GetTimezoneResolverManager()
          ->UpdateTimezoneResolver();
      if (system::TimeZoneResolverManager::
                  GetEffectiveUserTimeZoneResolveMethod(
                      prefs_, true /* check_policy */) ==
              system::TimeZoneResolverManager::TimeZoneResolveMethod::
                  DISABLED &&
          reason == REASON_PREF_CHANGED) {
        // Allow immediate timezone update on Stop + Start.
        g_browser_process->local_state()->ClearPref(
            TimeZoneResolver::kLastTimeZoneRefreshTime);
      }
    }
  }

  if (pref_name == ::prefs::kParentAccessCodeConfig ||
      reason != REASON_PREF_CHANGED) {
    if (prefs_->IsManagedPreference(::prefs::kParentAccessCodeConfig) &&
        user_->IsChild()) {
      const base::Value::Dict& value =
          prefs_->GetDict(::prefs::kParentAccessCodeConfig);
      known_user.SetPath(user_->GetAccountId(),
                         ::prefs::kKnownUserParentAccessCodeConfig,
                         base::Value(value.Clone()));
      parent_access::ParentAccessService::Get().LoadConfigForUser(user_);
    } else {
      known_user.RemovePref(user_->GetAccountId(),
                            ::prefs::kKnownUserParentAccessCodeConfig);
    }
  }

  for (auto* copy_pref : kCopyToKnownUserPrefs) {
    if (pref_name == copy_pref || reason != REASON_ACTIVE_USER_CHANGED) {
      known_user.SetPath(user_->GetAccountId(), copy_pref,
                         prefs_->GetValue(copy_pref).Clone());
    }
  }

  if (pref_name == prefs::kLocalStateDevicePeripheralDataAccessEnabled &&
      reason == REASON_PREF_CHANGED) {
    const bool value = g_browser_process->local_state()->GetBoolean(
        prefs::kLocalStateDevicePeripheralDataAccessEnabled);
    if (PeripheralNotificationManager::IsInitialized()) {
      PeripheralNotificationManager::Get()->SetPcieTunnelingAllowedState(value);
    }
    PciguardClient::Get()->SendExternalPciDevicesPermissionState(value);
  }
}

void Preferences::OnIsSyncingChanged() {
  DVLOG(1) << "OnIsSyncingChanged";
  ForceNaturalScrollDefault();
}

// TODO(anasalazar): Finish moving this to TouchDevicesController.
void Preferences::ForceNaturalScrollDefault() {
  DVLOG(1) << "ForceNaturalScrollDefault";
  // Natural scroll is a priority pref.
  bool is_syncing = features::IsSyncSettingsCategorizationEnabled()
                        ? prefs_->AreOsPriorityPrefsSyncing()
                        : prefs_->IsPrioritySyncing();
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kNaturalScrollDefault) &&
      is_syncing && !prefs_->GetUserPrefValue(prefs::kNaturalScroll)) {
    DVLOG(1) << "Natural scroll forced to true";
    natural_scroll_.SetValue(true);
  }
}

void Preferences::SetLanguageConfigStringListAsCSV(const char* section,
                                                   const char* name,
                                                   const std::string& value) {
  VLOG(1) << "Setting " << name << " to '" << value << "'";

  std::vector<std::string> split_values;
  if (!value.empty()) {
    split_values = base::SplitString(value, ",", base::TRIM_WHITESPACE,
                                     base::SPLIT_WANT_ALL);
  }

  // Transfers the xkb id to extension-xkb id.
  if (input_method_manager_->MigrateInputMethods(&split_values))
    preload_engines_.SetValue(base::JoinString(split_values, ","));

  if (section == std::string(language_prefs::kGeneralSectionName) &&
      name == std::string(language_prefs::kPreloadEnginesConfigName)) {
    ime_state_->ReplaceEnabledInputMethods(split_values);
    return;
  }
}

void Preferences::SetInputMethodList() {
  // When |preload_engines_| are set, InputMethodManager::ChangeInputMethod()
  // might be called to change the current input method to the first one in the
  // |preload_engines_| list. This also updates previous/current input method
  // prefs. That's why GetValue() calls are placed before the
  // SetLanguageConfigStringListAsCSV() call below.
  const std::string previous_input_method_id =
      previous_input_method_.GetValue();
  const std::string current_input_method_id = current_input_method_.GetValue();
  SetLanguageConfigStringListAsCSV(language_prefs::kGeneralSectionName,
                                   language_prefs::kPreloadEnginesConfigName,
                                   preload_engines_.GetValue());

  // ChangeInputMethod() has to be called AFTER the value of |preload_engines_|
  // is sent to the InputMethodManager. Otherwise, the ChangeInputMethod request
  // might be ignored as an invalid input method ID. The ChangeInputMethod()
  // calls are also necessary to restore the previous/current input method prefs
  // which could have been modified by the SetLanguageConfigStringListAsCSV call
  // above to the original state.
  if (!previous_input_method_id.empty())
    ime_state_->ChangeInputMethod(previous_input_method_id,
                                  false /* show_message */);
  if (!current_input_method_id.empty())
    ime_state_->ChangeInputMethod(current_input_method_id,
                                  false /* show_message */);
}

void Preferences::UpdateAutoRepeatRate() {
  input_method::AutoRepeatRate rate;
  rate.initial_delay_in_ms = xkb_auto_repeat_delay_pref_.GetValue();
  rate.repeat_interval_in_ms = xkb_auto_repeat_interval_pref_.GetValue();
  DCHECK(rate.initial_delay_in_ms > 0);
  DCHECK(rate.repeat_interval_in_ms > 0);
  input_method::InputMethodManager::Get()->GetImeKeyboard()->SetAutoRepeatRate(
      rate);

  user_manager::KnownUser known_user(g_browser_process->local_state());
  known_user.SetIntegerPref(user_->GetAccountId(), prefs::kXkbAutoRepeatDelay,
                            rate.initial_delay_in_ms);
  known_user.SetIntegerPref(user_->GetAccountId(),
                            prefs::kXkbAutoRepeatInterval,
                            rate.repeat_interval_in_ms);
}

void Preferences::ActiveUserChanged(user_manager::User* active_user) {
  if (active_user != user_)
    return;
  ApplyPreferences(REASON_ACTIVE_USER_CHANGED, "");
}

void Preferences::UpdateStatusChanged(
    const update_engine::StatusResult& status) {
  DVLOG(1) << "UpdateStatusChanged";
  for (int i = 0; i < status.features_size(); ++i) {
    const update_engine::Feature& feature = status.features(i);
    bool enabled = feature.enabled();
    DVLOG(1) << "Feature name=" << feature.name() << " enabled=" << enabled;
    if (feature.name() == update_engine::kFeatureConsumerAutoUpdate) {
      // Writes into this preference are only flushed by listening to
      // platform side signals. This means Chrome side writes into this
      // preference will not be visible outside of Chrome. This preference
      // should be updated by making DBus calls into the platform side, which
      // will signal out the true value of this preference as the true value is
      // managed by the update_engine daemon.
      consumer_auto_update_toggle_pref_.SetValue(enabled);
    }
  }
}

void Preferences::OnIsConsumerAutoUpdateEnabled(absl::optional<bool> enabled) {
  DVLOG(1) << "OnIsConsumerAutoUpdateEnabled";
  if (!enabled.has_value()) {
    VLOG(1) << "Failed to retrieve consumer auto update feature value.";
    return;
  }
  consumer_auto_update_toggle_pref_.SetValue(enabled.value());
}

}  // namespace ash


text:
<?php

/**
 * @namespace
 */
namespace Zend\Filter;
use Zend\Locale\Format;

/**
 * Normalizes given localized input
 *
 * @uses       Zend\Filter\AbstractFilter
 * @uses       Zend\Locale\Format
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class LocalizedToNormalized extends AbstractFilter
{
    /**
     * Set options
     * @var array
     */
    protected $_options = array(
        'locale'      => null,
        'date_format' => null,
        'precision'   => null
    );

    /**
     * Class constructor
     *
     * @param string|\Zend\Locale\Locale $locale (Optional) Locale to set
     */
    public function __construct($options = null)
    {
        if ($options instanceof \Zend\Config\Config) {
            $options = $options->toArray();
        }

        if (null !== $options) {
            $this->setOptions($options);
        }
    }

    /**
     * Returns the set options
     *
     * @return array
     */
    public function getOptions()
    {
        return $this->_options;
    }

    /**
     * Sets options to use
     *
     * @param  array $options (Optional) Options to use
     * @return \Zend\Filter\LocalizedToNormalized
     */
    public function setOptions(array $options = null)
    {
        $this->_options = $options + $this->_options;
        return $this;
    }

    /**
     * Defined by Zend_Filter_Interface
     *
     * Normalizes the given input
     *
     * @param  string $value Value to normalized
     * @return string|array The normalized value
     */
    public function filter($value)
    {
        if (Format::isNumber($value, $this->_options)) {
            return Format::getNumber($value, $this->_options);
        } else if (($this->_options['date_format'] === null) && (strpos($value, ':') !== false)) {
            // Special case, no date format specified, detect time input
            return Format::getTime($value, $this->_options);
        } else if (Format::checkDateFormat($value, $this->_options)) {
            // Detect date or time input
            return Format::getDate($value, $this->_options);
        }

        return $value;
    }
}


text:
<?php

namespace keltanas\Bundle\TrackingBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * HistoryRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class HistoryRepository extends EntityRepository
{
    public function getQueryNoBot()
    {
        return $this->createQueryBuilder('h')
            ->where('h.bot = :bot AND h.utmSource != :source')
            ->setParameter(':bot', 0)
            ->setParameter(':source', 'trafficgen')
            ->orderBy('h.trackingAt', 'desc')
            ->getQuery();
    }

    public function getQueryGroupingByRange(\DateTime $dateFrom = null, \DateTime $dateTo = null)
    {
        $qb = $this->createQueryBuilder('h')
            ->select('h.utmSource, COUNT(h.id) as sourceCount')
            ->where('h.bot = :bot')
            ->setParameter(':bot', 0)
            ->addGroupBy('h.utmSource')
            ;

        if ($dateFrom) {
            $qb->andWhere('h.updatedAt > :dateFrom')->setParameter(':dateFrom', $dateFrom->format('Y-m-d H:i:s'));
        }
        if ($dateTo) {
            $qb->andWhere('h.updatedAt < :dateTo')->setParameter(':dateTo', $dateTo->format('Y-m-d H:i:s'));
        }

        return $qb->getQuery();
    }
}


text:
title: USGIN ISO profile
slug: usgin-iso-profile
website: http://repository.stategeothermaldata.org/repository/resource/98ddf901b9782a25982e01af3b0bda50/
subjects:
- physical-sciences-and-mathematics
disciplines:
- geoscience
standards:
- iso-19115
layout: extension
type: extension
---


text:
import traceback
import json

from sys import version_info
import yaml
import jsonschema

PYTHON_MAJOR_VERSION = version_info[0]

try:  # First try to load pyresttest from global namespace
    from pyresttest import validators
    from pyresttest import binding
    from pyresttest import parsing
    from pyresttest import contenthandling
except ImportError:  # Then try a relative import if possible
    from .. import validators
    from .. import binding
    from .. import parsing
    from .. import contenthandling

class JsonSchemaValidator(validators.AbstractValidator):
    """ Json schema validator using the jsonschema library """
    schema = None

    def validate(self, body=None, headers=None, context=None):
        schema_text = self.schema.get_content(context=context)
        schema = yaml.safe_load(schema_text)
        # TODO add caching of parsed schema

        try:
            # TODO try draft3/draft4 iter_errors -
            # https://python-jsonschema.readthedocs.org/en/latest/validate/#jsonschema.IValidator.iter_errors
            parsed_body = body
            if PYTHON_MAJOR_VERSION > 2 and isinstance(body, bytes):
                parsed_body = str(body, 'utf-8')
            jsonschema.validate(json.loads(parsed_body), schema)
            return True
        except jsonschema.exceptions.ValidationError as ve:
            trace = traceback.format_exc()
            return validators.Failure(message="JSON Schema Validation Failed", details=trace, validator=self, failure_type=validators.FAILURE_VALIDATOR_EXCEPTION)

    def get_readable_config(self, context=None):
        return "JSON schema validation"

    @classmethod
    def parse(cls, config):
        validator = JsonSchemaValidator()
        config = parsing.lowercase_keys(config)
        if 'schema' not in config:
            raise ValueError(
                "Cannot create schema validator without a 'schema' configuration element!")
        validator.schema = contenthandling.ContentHandler.parse_content(config[
                                                                        'schema'])
        return validator

VALIDATORS = {'json_schema': JsonSchemaValidator.parse}


text:
using System.Windows;
using System.Windows.Controls;

namespace DNTProfiler.Common.Behaviors
{
    public static class ScrollCurrentItemIntoViewBehavior
    {
        public static readonly DependencyProperty AutoScrollToCurrentItemProperty =
            DependencyProperty.RegisterAttached("AutoScrollToCurrentItem",
                typeof(bool), typeof(ScrollCurrentItemIntoViewBehavior),
                new UIPropertyMetadata(default(bool), OnAutoScrollToCurrentItemChanged));

        public static bool GetAutoScrollToCurrentItem(DependencyObject obj)
        {
            return (bool)obj.GetValue(AutoScrollToCurrentItemProperty);
        }

        public static void OnAutoScrollToCurrentItemChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            var listBox = obj as ListBox;
            if (listBox == null) return;

            var newValue = (bool)e.NewValue;
            if (newValue)
                listBox.SelectionChanged += listBoxSelectionChanged;
            else
                listBox.SelectionChanged -= listBoxSelectionChanged;
        }

        static void listBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var listBox = sender as ListBox;
            if (listBox == null || listBox.SelectedItem == null || listBox.Items == null) return;

            listBox.Items.MoveCurrentTo(listBox.SelectedItem);
            listBox.ScrollIntoView(listBox.SelectedItem);
        }

        public static void SetAutoScrollToCurrentItem(DependencyObject obj, bool value)
        {
            obj.SetValue(AutoScrollToCurrentItemProperty, value);
        }
    }
}


text:
#region Apache Notice

#endregion

#region Imports

using System.Collections;
using System.Text;
using IBatisNet.DataMapper.Configuration.ParameterMapping;
using IBatisNet.DataMapper.Configuration.Sql.Dynamic.Elements;

#endregion

namespace IBatisNet.DataMapper.Configuration.Sql.Dynamic.Handlers
{
	/// <summary>
	/// Summary description for SqlTagContext.
	/// </summary>
	public sealed class SqlTagContext
	{
		#region Fields
		private Hashtable _attributes = new Hashtable();
		private bool _overridePrepend = false;
		private SqlTag _firstNonDynamicTagWithPrepend = null;
		private ArrayList _parameterMappings = new ArrayList();
		private StringBuilder buffer = new StringBuilder();
		#endregion

		/// <summary>
		///
		/// </summary>
		public SqlTagContext()
		{
			_overridePrepend = false;
		}

		/// <summary>
		///
		/// </summary>
		/// <returns></returns>
		public StringBuilder GetWriter()
		{
			return buffer;
		}

		/// <summary>
		///
		/// </summary>
		public string BodyText
		{
			get
			{
				return buffer.ToString().Trim();
			}
		}

		/// <summary>
		///
		/// </summary>
		public bool IsOverridePrepend
		{
			set
			{
				_overridePrepend = value;
			}
			get
			{
				return _overridePrepend;
			}
		}

		/// <summary>
		///
		/// </summary>
		public SqlTag FirstNonDynamicTagWithPrepend
		{
			get
			{
				return _firstNonDynamicTagWithPrepend;
			}
			set
			{
				_firstNonDynamicTagWithPrepend = value;
			}
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="key"></param>
		/// <param name="value"></param>
		public void AddAttribute(object key, object value)
		{
			_attributes.Add(key, value);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public object GetAttribute(object key)
		{
			return _attributes[key];
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="mapping"></param>
		public void AddParameterMapping(ParameterProperty mapping)
		{
			_parameterMappings.Add(mapping);
		}

		/// <summary>
		///
		/// </summary>
		/// <returns></returns>
		public IList GetParameterMappings()
		{
			return _parameterMappings;
		}
	}
}


text:
package org.omg.PortableInterceptor;

/**
 * A single constant interface, defining the adapter state (NON_EXISTENT) = 4.
 * NON_EXISTENT does not map directly to a particular POAManager state, but
 * indicates that a POA has been destroyed. Used with IOR interceptors.
 *
 * @since 1.5
 *
 * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org)
 */

public interface NON_EXISTENT
{
  /**
    * Specifies the NON_EXISTENT value, 4.
    */
  short value = 4;
}


text:
package com.orpc.example.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.orpc.client.RpcClient;
import com.orpc.example.client.command.UserCommand;
import com.orpc.example.domain.User;

@RestController
@RequestMapping("/user")
public class ClentController {
	Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private RpcClient rpcClient;

	@RequestMapping("/get/{id}")
	public String get(@PathVariable("id") String id) {
		User user = new User();
		// 成功
		for (int i = 0; i < 30; i++) {
			UserCommand userCommand = new UserCommand(rpcClient, Long.parseLong(id));
			user = userCommand.execute();
			logger.info("{}", user);
		}
		// 失败
		for (int i = 0; i < 30; i++) {
			UserCommand userCommand = new UserCommand(rpcClient, null);
			user = userCommand.execute();
			logger.info("{}", user);
		}
		//
		for (int i = 0; i < 10; i++) {
			UserCommand userCommand = new UserCommand(rpcClient, Long.parseLong(id));
			user = userCommand.execute();
			logger.info("{}", user);
		}
		return "ko...";
	}
}


text:
'use strict';

(function(module) {
  const aboutController = {};

  aboutController.init = function() {
    $('#about').show();
    $('nav').show();
    $('#home').hide();
    $('#cart').hide();
    $('#store').hide();
    $('#services').hide();
    $('header').show();

  };

  module.aboutController = aboutController;
})(window);


text:
const angular = require('angular');
require('angular-route');
const grokApp = angular.module('grokApp', ['ngRoute', 'google.places']);

require(__dirname + '/home')(grokApp);
require(__dirname + '/business_detail')(grokApp);
require(__dirname + '/d3_cloud')(grokApp);
require(__dirname + '/google_places')(grokApp);
require(__dirname + '/menu')(grokApp)

grokApp.config(['$routeProvider', function($routeProvider) {
	$routeProvider
		.when('/', {
			templateUrl: '/views/home_view.html',
			controller: 'HomeController'
		})
		.when('/business/:businessid', {
			templateUrl: '/views/business_detail_view.html',
			controller: 'BusinessDetailController'
		})
		.when('/user', {
			templateUrl: '/views/user_profile_view.html'
		})
		.when('/addreview', {
			templateUrl: '/views/add_review_view.html'
		})
		.otherwise({
			redirectTo: '/'
		});
}]);


text:
package com.googlecode.objectify.impl;

import com.google.cloud.datastore.ProjectionEntity;
import com.google.cloud.datastore.QueryResults;
import com.googlecode.objectify.impl.translate.LoadContext;
import com.googlecode.objectify.util.TranslatingQueryResults;

/**
 * Projections bypass the session entirely, neither loading nor saving.
 */
class ProjectionQueryResults<T> extends TranslatingQueryResults<ProjectionEntity, T> {
	private final LoadEngine loadEngine;
	private final LoadContext ctx;

	/** */
	ProjectionQueryResults(final QueryResults<ProjectionEntity> base, final LoadEngine loadEngine) {
		super(base);
		this.loadEngine = loadEngine;
		this.ctx = new LoadContext(loadEngine);
	}

	@Override
	protected T translate(final ProjectionEntity from) {
		return loadEngine.load(from, ctx);
	}
}


text:
<?php

namespace Google\Service\Contentwarehouse;

class SocialGraphApiProtoSearchProfileEducation extends \Google\Collection
{
  protected $collection_key = 'fieldOfStudy';
  protected $endTimeType = GoogleTypeDate::class;
  protected $endTimeDataType = '';
  protected $fieldOfStudyType = SocialGraphApiProtoSearchProfileEntity::class;
  protected $fieldOfStudyDataType = 'array';
  protected $institutionType = SocialGraphApiProtoSearchProfileEntity::class;
  protected $institutionDataType = '';
  protected $startTimeType = GoogleTypeDate::class;
  protected $startTimeDataType = '';

  /**
   * @param GoogleTypeDate
   */
  public function setEndTime(GoogleTypeDate $endTime)
  {
    $this->endTime = $endTime;
  }
  /**
   * @return GoogleTypeDate
   */
  public function getEndTime()
  {
    return $this->endTime;
  }
  /**
   * @param SocialGraphApiProtoSearchProfileEntity[]
   */
  public function setFieldOfStudy($fieldOfStudy)
  {
    $this->fieldOfStudy = $fieldOfStudy;
  }
  /**
   * @return SocialGraphApiProtoSearchProfileEntity[]
   */
  public function getFieldOfStudy()
  {
    return $this->fieldOfStudy;
  }
  /**
   * @param SocialGraphApiProtoSearchProfileEntity
   */
  public function setInstitution(SocialGraphApiProtoSearchProfileEntity $institution)
  {
    $this->institution = $institution;
  }
  /**
   * @return SocialGraphApiProtoSearchProfileEntity
   */
  public function getInstitution()
  {
    return $this->institution;
  }
  /**
   * @param GoogleTypeDate
   */
  public function setStartTime(GoogleTypeDate $startTime)
  {
    $this->startTime = $startTime;
  }
  /**
   * @return GoogleTypeDate
   */
  public function getStartTime()
  {
    return $this->startTime;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(SocialGraphApiProtoSearchProfileEducation::class, 'Google_Service_Contentwarehouse_SocialGraphApiProtoSearchProfileEducation');


text:
/*      $OpenBSD: mips_opcode.h,v 1.1 2004/08/06 20:56:02 pefo Exp $	*/

/*-
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Ralph Campbell.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	from: @(#)mips_opcode.h	8.1 (Berkeley) 6/10/93
 */

#ifndef _MIPS_MIPS_OPCODE_H_
#define _MIPS_MIPS_OPCODE_H_

/*
 * Define the instruction formats and opcode values for the
 * MIPS instruction set.
 */

/*
 * Define the instruction formats.
 */
typedef union {
	unsigned word;

#if BYTE_ORDER == BIG_ENDIAN
	struct {
		unsigned op: 6;
		unsigned rs: 5;
		unsigned rt: 5;
		unsigned imm: 16;
	} IType;

	struct {
		unsigned op: 6;
		unsigned target: 26;
	} JType;

	struct {
		unsigned op: 6;
		unsigned rs: 5;
		unsigned rt: 5;
		unsigned rd: 5;
		unsigned shamt: 5;
		unsigned func: 6;
	} RType;

	struct {
		unsigned op: 6;		/* always '0x11' */
		unsigned : 1;		/* always '1' */
		unsigned fmt: 4;
		unsigned ft: 5;
		unsigned fs: 5;
		unsigned fd: 5;
		unsigned func: 6;
	} FRType;
#endif
#if BYTE_ORDER == LITTLE_ENDIAN
	struct {
		unsigned imm: 16;
		unsigned rt: 5;
		unsigned rs: 5;
		unsigned op: 6;
	} IType;

	struct {
		unsigned target: 26;
		unsigned op: 6;
	} JType;

	struct {
		unsigned func: 6;
		unsigned shamt: 5;
		unsigned rd: 5;
		unsigned rt: 5;
		unsigned rs: 5;
		unsigned op: 6;
	} RType;

	struct {
		unsigned func: 6;
		unsigned fd: 5;
		unsigned fs: 5;
		unsigned ft: 5;
		unsigned fmt: 4;
		unsigned : 1;		/* always '1' */
		unsigned op: 6;		/* always '0x11' */
	} FRType;
#endif
} InstFmt;

/*
 * Values for the 'op' field.
 */
#define OP_SPECIAL	000
#define OP_BCOND	001
#define OP_J		002
#define	OP_JAL		003
#define OP_BEQ		004
#define OP_BNE		005
#define OP_BLEZ		006
#define OP_BGTZ		007

#define OP_ADDI		010
#define OP_ADDIU	011
#define OP_SLTI		012
#define OP_SLTIU	013
#define OP_ANDI		014
#define OP_ORI		015
#define OP_XORI		016
#define OP_LUI		017

#define OP_COP0		020
#define OP_COP1		021
#define OP_COP2		022
#define OP_COP3		023
#define	OP_BEQL		024
#define	OP_BNEL		025
#define	OP_BLEZL	026
#define	OP_BGTZL	027

#define	OP_DADDI	030
#define	OP_DADDIU	031
#define	OP_LDL		032
#define	OP_LDR		033

#define	OP_LB		040
#define	OP_LH		041
#define OP_LWL		042
#define OP_LW		043
#define OP_LBU		044
#define OP_LHU		045
#define OP_LWR		046
#define	OP_LHU		045
#define	OP_LWR		046
#define	OP_LWU		047

#define OP_SB		050
#define OP_SH		051
#define OP_SWL		052
#define OP_SW		053
#define	OP_SDL		054
#define	OP_SDR		055
#define OP_SWR		056
#define	OP_CACHE	057

#define OP_LL		060
#define OP_LWC1		061
#define OP_LWC2		062
#define OP_LWC3		063
#define	OP_LLD		064
#define	OP_LD		067

#define OP_SC		070
#define OP_SWC1		071
#define OP_SWC2		072
#define OP_SWC3		073
#define	OP_SCD		074
#define	OP_SD		077

/*
 * Values for the 'func' field when 'op' == OP_SPECIAL.
 */
#define OP_SLL		000
#define OP_SRL		002
#define OP_SRA		003
#define OP_SLLV		004
#define OP_SRLV		006
#define OP_SRAV		007

#define OP_JR		010
#define OP_JALR		011
#define OP_SYSCALL	014
#define OP_BREAK	015
#define	OP_SYNC		017

#define OP_MFHI		020
#define OP_MTHI		021
#define OP_MFLO		022
#define OP_MTLO		023
#define	OP_DSLLV	024
#define	OP_DSRLV	026
#define	OP_DSRAV	027

#define OP_MULT		030
#define OP_MULTU	031
#define OP_DIV		032
#define OP_DIVU		033
#define	OP_DMULT	034
#define	OP_DMULTU	035
#define	OP_DDIV		036
#define	OP_DDIVU	037

#define OP_ADD		040
#define OP_ADDU		041
#define OP_SUB		042
#define OP_SUBU		043
#define OP_AND		044
#define OP_OR		045
#define OP_XOR		046
#define OP_NOR		047

#define OP_SLT		052
#define OP_SLTU		053
#define	OP_DADD		054
#define	OP_DADDU	055
#define	OP_DSUB		056
#define	OP_DSUBU	057

#define	OP_TGE		060
#define	OP_TGEU		061
#define	OP_TLT		062
#define	OP_TLTU		063
#define	OP_TEQ		064
#define	OP_TNE		066

#define	OP_DSLL		070
#define	OP_DSRL		072
#define	OP_DSRA		073
#define	OP_DSLL32	074
#define	OP_DSRL32	076
#define	OP_DSRA32	077

/*
 * Values for the 'func' field when 'op' == OP_BCOND.
 */
#define OP_BLTZ		000
#define OP_BGEZ		001
#define	OP_BLTZL	002
#define	OP_BGEZL	003

#define	OP_TGEI		010
#define	OP_TGEIU	011
#define	OP_TLTI		012
#define	OP_TLTIU	013
#define	OP_TEQI		014
#define	OP_TNEI		016

#define OP_BLTZAL	020
#define	OP_BLTZAL	020
#define OP_BGEZAL	021
#define OP_BLTZALL	022
#define	OP_BGEZALL	023

/*
 * Values for the 'rs' field when 'op' == OP_COPz.
 */
#define OP_MF		000
#define	OP_DMF		001
#define OP_MT		004
#define	OP_DMT		005
#define OP_BCx		010
#define OP_BCy		014
#define OP_CF		002
#define OP_CT		006

/*
 * Values for the 'rt' field when 'op' == OP_COPz.
 */
#define COPz_BC_TF_MASK	0x01
#define COPz_BC_TRUE	0x01
#define COPz_BC_FALSE	0x00
#define COPz_BCL_TF_MASK	0x02
#define COPz_BCL_TRUE	0x02
#define COPz_BCL_FALSE	0x00

#endif /* !_MIPS_MIPS_OPCODE_H_ */


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

#import <Foundation/Foundation.h>

/**
 *  This class adds some useful methods to encrypt/decrypt data.
 *  All methods are static
 */
@interface YSCryptor : NSObject

/**
 *  Create a MD5 string
 *
 *  @param string The string to be converted
 *
 *  @return Returns the MD5 NSString
 */
+ (NSString * _Nullable)MD5:(NSString * _Nonnull)string;

/**
 *  Create a SHA1 string
 *
 *  @param string The string to be converted
 *
 *  @return Returns the SHA1 NSString
 */
+ (NSString * _Nullable)SHA1:(NSString * _Nonnull)string;

/**
 *  Create a SHA256 string
 *
 *  @param string The string to be converted
 *
 *  @return Returns the SHA256 NSString
 */
+ (NSString * _Nullable)SHA256:(NSString * _Nonnull)string;

/**
 *  Create a SHA512 string
 *
 *  @param string The string to be converted
 *
 *  @return Returns the SHA512 NSString
 */
+ (NSString * _Nullable)SHA512:(NSString * _Nonnull)string;

/**
 *  Encrypt NSData in AES128
 *
 *  @param data NSData to be encrypted
 *  @param key  Key to encrypt data
 *
 *  @return Returns the encrypted NSData
 */
+ (NSData * _Nullable)AES128EncryptData:(NSData * _Nonnull)data
                                withKey:(NSString * _Nonnull)key;

/**
 *  Decrypt NSData in AES128
 *
 *  @param data NSData to be decrypted
 *  @param key  Key to decrypt data
 *
 *  @return Returns the decrypted NSData
 */
+ (NSData * _Nullable)AES128DecryptData:(NSData * _Nonnull)data
                                withKey:(NSString * _Nonnull)key;

/**
 *  Encrypt NSData in AES256
 *
 *  @param data NSData to be encrypted
 *  @param key  Key to encrypt data
 *
 *  @return Returns the encrypted NSData
 */
+ (NSData * _Nullable)AES256EncryptData:(NSData * _Nonnull)data
                                withKey:(NSString * _Nonnull)key;

/**
 *  Decrypt NSData in AES256
 *
 *  @param data NSData to be decrypted
 *  @param key  Key to decrypt data
 *
 *  @return Returns the decrypted NSData
 */
+ (NSData * _Nullable)AES256DecryptData:(NSData * _Nonnull)data
                                withKey:(NSString * _Nonnull)key;

/**
 *  Encrypt NSString in AES128
 *
 *  @param data NSString to be encrypted
 *  @param key  Key to encrypt data
 *
 *  @return Returns the encrypted NSData
 */
+ (NSData * _Nullable)AES128EncryptString:(NSString * _Nonnull)string
                                  withKey:(NSString * _Nonnull)key;

/**
 *  Decrypt NSString in AES128
 *
 *  @param data NSString to be decrypted
 *  @param key  Key to decrypt data
 *
 *  @return Returns the decrypted NSData
 */
+ (NSData * _Nullable)AES128DecryptString:(NSString * _Nonnull)string
                                  withKey:(NSString * _Nonnull)key;

/**
 *  Encrypt NSString in AES256
 *
 *  @param data NSString to be encrypted
 *  @param key  Key to encrypt data
 *
 *  @return Returns the encrypted NSData
 */
+ (NSData * _Nullable)AES256EncryptString:(NSString * _Nonnull)string
                                  withKey:(NSString * _Nonnull)key;

/**
 *  Decrypt NSString in AES256
 *
 *  @param data NSString to be decrypted
 *  @param key  Key to decrypt data
 *
 *  @return Returns the decrypted NSData
 */
+ (NSData * _Nullable)AES256DecryptString:(NSString * _Nonnull)string
                                  withKey:(NSString * _Nonnull)key;

@end